print.html 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502
  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="development/synapse_architecture/streams.html">Streams</a></li><li class="chapter-item expanded "><a href="tcp_replication.html">TCP Replication</a></li><li class="chapter-item expanded "><a href="development/synapse_architecture/faster_joins.html">Faster remote joins</a></li></ol></li><li class="chapter-item expanded "><a href="development/internal_documentation/index.html">Internal Documentation</a></li><li><ol class="section"><li class="chapter-item expanded "><div>Single Sign-On</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="development/saml.html">SAML</a></li><li class="chapter-item expanded "><a href="development/cas.html">CAS</a></li></ol></li><li class="chapter-item expanded "><a href="development/room-dag-concepts.html">Room DAG concepts</a></li><li class="chapter-item expanded "><div>State Resolution</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="auth_chain_difference_algorithm.html">The Auth Chain Difference Algorithm</a></li></ol></li><li class="chapter-item expanded "><a href="media_repository.html">Media Repository</a></li><li class="chapter-item expanded "><a href="room_and_user_statistics.html">Room and User Statistics</a></li></ol></li><li class="chapter-item expanded "><div>Scripts</div></li><li class="chapter-item expanded affix "><li class="part-title">Other</li><li class="chapter-item expanded "><a href="deprecation_policy.html">Dependency Deprecation Policy</a></li><li class="chapter-item expanded "><a href="other/running_synapse_on_single_board_computers.html">Running Synapse on a Single-Board Computer</a></li></ol>
  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 official 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 available 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="alpine-linux"><a class="header" href="#alpine-linux">Alpine Linux</a></h4>
  337. <p>6543 maintains <a href="https://pkgs.alpinelinux.org/packages?name=synapse&amp;branch=edge">Synapse packages for Alpine Linux</a> in the community repository. Install with:</p>
  338. <pre><code class="language-sh">sudo apk add synapse
  339. </code></pre>
  340. <h4 id="void-linux"><a class="header" href="#void-linux">Void Linux</a></h4>
  341. <p>Synapse can be found in the void repositories as
  342. <a href="https://github.com/void-linux/void-packages/tree/master/srcpkgs/synapse">'synapse'</a>:</p>
  343. <pre><code class="language-sh">xbps-install -Su
  344. xbps-install -S synapse
  345. </code></pre>
  346. <h4 id="freebsd"><a class="header" href="#freebsd">FreeBSD</a></h4>
  347. <p>Synapse can be installed via FreeBSD Ports or Packages contributed by Brendan Molloy from:</p>
  348. <ul>
  349. <li>Ports: <code>cd /usr/ports/net-im/py-matrix-synapse &amp;&amp; make install clean</code></li>
  350. <li>Packages: <code>pkg install py38-matrix-synapse</code></li>
  351. </ul>
  352. <h4 id="openbsd"><a class="header" href="#openbsd">OpenBSD</a></h4>
  353. <p>As of OpenBSD 6.7 Synapse is available as a pre-compiled binary. The filesystem
  354. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  355. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  356. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  357. <p>Installing Synapse:</p>
  358. <pre><code class="language-sh">doas pkg_add synapse
  359. </code></pre>
  360. <h4 id="nixos"><a class="header" href="#nixos">NixOS</a></h4>
  361. <p>Robin Lambertz has packaged Synapse for NixOS at:
  362. <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>
  363. <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>
  364. <p>It's also possible to install Synapse as a Python module from PyPI.</p>
  365. <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>
  366. <p>System requirements:</p>
  367. <ul>
  368. <li>POSIX-compliant system (tested on Linux &amp; OS X)</li>
  369. <li>Python 3.8 or later, up to Python 3.11.</li>
  370. <li>At least 1GB of free RAM if you want to join large public rooms like #matrix:matrix.org</li>
  371. </ul>
  372. <p>If building on an uncommon architecture for which pre-built wheels are
  373. unavailable, you will need to have a recent Rust compiler installed. The easiest
  374. way of installing the latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
  375. <p>To install the Synapse homeserver run:</p>
  376. <pre><code class="language-sh">mkdir -p ~/synapse
  377. virtualenv -p python3 ~/synapse/env
  378. source ~/synapse/env/bin/activate
  379. pip install --upgrade pip
  380. pip install --upgrade setuptools
  381. pip install matrix-synapse
  382. </code></pre>
  383. <p>This will download Synapse from <a href="https://pypi.org/project/matrix-synapse">PyPI</a>
  384. and install it, along with the python libraries it uses, into a virtual environment
  385. under <code>~/synapse/env</code>. Feel free to pick a different directory if you
  386. prefer.</p>
  387. <p>This Synapse installation can then be later upgraded by using pip again with the
  388. update flag:</p>
  389. <pre><code class="language-sh">source ~/synapse/env/bin/activate
  390. pip install -U matrix-synapse
  391. </code></pre>
  392. <p>Before you can start Synapse, you will need to generate a configuration
  393. file. To do this, run (in your virtualenv, as before):</p>
  394. <pre><code class="language-sh">cd ~/synapse
  395. python -m synapse.app.homeserver \
  396. --server-name my.domain.name \
  397. --config-path homeserver.yaml \
  398. --generate-config \
  399. --report-stats=[yes|no]
  400. </code></pre>
  401. <p>... substituting an appropriate value for <code>--server-name</code> and choosing whether
  402. or not to report usage statistics (hostname, Synapse version, uptime, total
  403. users, etc.) to the developers via the <code>--report-stats</code> argument.</p>
  404. <p>This command will generate you a config file that you can then customise, but it will
  405. also generate a set of keys for you. These keys will allow your homeserver to
  406. identify itself to other homeserver, so don't lose or delete them. It would be
  407. wise to back them up somewhere safe. (If, for whatever reason, you do need to
  408. change your homeserver's keys, you may find that other homeserver have the
  409. old key cached. If you update the signing key, you should change the name of the
  410. key in the <code>&lt;server name&gt;.signing.key</code> file (the second word) to something
  411. 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>
  412. <p>To actually run your new homeserver, pick a working directory for Synapse to
  413. run (e.g. <code>~/synapse</code>), and:</p>
  414. <pre><code class="language-sh">cd ~/synapse
  415. source env/bin/activate
  416. synctl start
  417. </code></pre>
  418. <h4 id="platform-specific-prerequisites"><a class="header" href="#platform-specific-prerequisites">Platform-specific prerequisites</a></h4>
  419. <p>Synapse is written in Python but some of the libraries it uses are written in
  420. C. So before we can install Synapse itself we need a working C compiler and the
  421. header files for Python C extensions.</p>
  422. <h5 id="debianubunturaspbian"><a class="header" href="#debianubunturaspbian">Debian/Ubuntu/Raspbian</a></h5>
  423. <p>Installing prerequisites on Ubuntu or Debian:</p>
  424. <pre><code class="language-sh">sudo apt install build-essential python3-dev libffi-dev \
  425. python3-pip python3-setuptools sqlite3 \
  426. libssl-dev virtualenv libjpeg-dev libxslt1-dev libicu-dev
  427. </code></pre>
  428. <h5 id="archlinux-1"><a class="header" href="#archlinux-1">ArchLinux</a></h5>
  429. <p>Installing prerequisites on ArchLinux:</p>
  430. <pre><code class="language-sh">sudo pacman -S base-devel python python-pip \
  431. python-setuptools python-virtualenv sqlite3 icu
  432. </code></pre>
  433. <h5 id="centosfedora"><a class="header" href="#centosfedora">CentOS/Fedora</a></h5>
  434. <p>Installing prerequisites on CentOS or Fedora Linux:</p>
  435. <pre><code class="language-sh">sudo dnf install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
  436. libwebp-devel libxml2-devel libxslt-devel libpq-devel \
  437. python3-virtualenv libffi-devel openssl-devel python3-devel \
  438. libicu-devel
  439. sudo dnf groupinstall &quot;Development Tools&quot;
  440. </code></pre>
  441. <h5 id="macos"><a class="header" href="#macos">macOS</a></h5>
  442. <p>Installing prerequisites on macOS:</p>
  443. <p>You may need to install the latest Xcode developer tools:</p>
  444. <pre><code class="language-sh">xcode-select --install
  445. </code></pre>
  446. <p>Some extra dependencies may be needed. You can use Homebrew (https://brew.sh) for them.</p>
  447. <p>You may need to install icu, and make the icu binaries and libraries accessible.
  448. Please follow <a href="https://pypi.org/project/PyICU/">the official instructions of PyICU</a> to do so.</p>
  449. <p>On ARM-based Macs you may also need to install libjpeg and libpq:</p>
  450. <pre><code class="language-sh"> brew install jpeg libpq
  451. </code></pre>
  452. <p>On macOS Catalina (10.15) you may need to explicitly install OpenSSL
  453. via brew and inform <code>pip</code> about it so that <code>psycopg2</code> builds:</p>
  454. <pre><code class="language-sh">brew install openssl@1.1
  455. export LDFLAGS=&quot;-L/usr/local/opt/openssl/lib&quot;
  456. export CPPFLAGS=&quot;-I/usr/local/opt/openssl/include&quot;
  457. </code></pre>
  458. <h5 id="opensuse-1"><a class="header" href="#opensuse-1">OpenSUSE</a></h5>
  459. <p>Installing prerequisites on openSUSE:</p>
  460. <pre><code class="language-sh">sudo zypper in -t pattern devel_basis
  461. sudo zypper in python-pip python-setuptools sqlite3 python-virtualenv \
  462. python-devel libffi-devel libopenssl-devel libjpeg62-devel \
  463. libicu-devel
  464. </code></pre>
  465. <h5 id="openbsd-1"><a class="header" href="#openbsd-1">OpenBSD</a></h5>
  466. <p>A port of Synapse is available under <code>net/synapse</code>. The filesystem
  467. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  468. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  469. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  470. <p>To be able to build Synapse's dependency on python the <code>WRKOBJDIR</code>
  471. (cf. <code>bsd.port.mk(5)</code>) for building python, too, needs to be on a filesystem
  472. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>).</p>
  473. <p>Creating a <code>WRKOBJDIR</code> for building python under <code>/usr/local</code> (which on a
  474. default OpenBSD installation is mounted with <code>wxallowed</code>):</p>
  475. <pre><code class="language-sh">doas mkdir /usr/local/pobj_wxallowed
  476. </code></pre>
  477. <p>Assuming <code>PORTS_PRIVSEP=Yes</code> (cf. <code>bsd.port.mk(5)</code>) and <code>SUDO=doas</code> are
  478. configured in <code>/etc/mk.conf</code>:</p>
  479. <pre><code class="language-sh">doas chown _pbuild:_pbuild /usr/local/pobj_wxallowed
  480. </code></pre>
  481. <p>Setting the <code>WRKOBJDIR</code> for building python:</p>
  482. <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
  483. </code></pre>
  484. <p>Building Synapse:</p>
  485. <pre><code class="language-sh">cd /usr/ports/net/synapse
  486. make install
  487. </code></pre>
  488. <h5 id="windows"><a class="header" href="#windows">Windows</a></h5>
  489. <p>Running Synapse natively on Windows is not officially supported.</p>
  490. <p>If you wish to run or develop Synapse on Windows, the Windows Subsystem for
  491. Linux provides a Linux environment which is capable of using the Debian, Fedora,
  492. or source installation methods. More information about WSL can be found at
  493. <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
  494. <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
  495. Windows Server.</p>
  496. <h2 id="setting-up-synapse"><a class="header" href="#setting-up-synapse">Setting up Synapse</a></h2>
  497. <p>Once you have installed synapse as above, you will need to configure it.</p>
  498. <h3 id="using-postgresql"><a class="header" href="#using-postgresql">Using PostgreSQL</a></h3>
  499. <p>By default Synapse uses an <a href="https://sqlite.org/">SQLite</a> database and in doing so trades
  500. performance for convenience. Almost all installations should opt to use <a href="https://www.postgresql.org">PostgreSQL</a>
  501. instead. Advantages include:</p>
  502. <ul>
  503. <li>significant performance improvements due to the superior threading and
  504. caching model, smarter query optimiser</li>
  505. <li>allowing the DB to be run on separate hardware</li>
  506. </ul>
  507. <p>For information on how to install and use PostgreSQL in Synapse, please see
  508. <a href="setup/../postgres.html">Using Postgres</a></p>
  509. <p>SQLite is only acceptable for testing purposes. SQLite should not be used in
  510. a production server. Synapse will perform poorly when using
  511. SQLite, especially when participating in large rooms.</p>
  512. <h3 id="tls-certificates"><a class="header" href="#tls-certificates">TLS certificates</a></h3>
  513. <p>The default configuration exposes a single HTTP port on the local
  514. interface: <code>http://localhost:8008</code>. It is suitable for local testing,
  515. but for any practical use, you will need Synapse's APIs to be served
  516. over HTTPS.</p>
  517. <p>The recommended way to do so is to set up a reverse proxy on port
  518. <code>8448</code>. You can find documentation on doing so in
  519. <a href="setup/../reverse_proxy.html">the reverse proxy documentation</a>.</p>
  520. <p>Alternatively, you can configure Synapse to expose an HTTPS port. To do
  521. so, you will need to edit <code>homeserver.yaml</code>, as follows:</p>
  522. <ul>
  523. <li>First, under the <code>listeners</code> option, add the configuration for the
  524. TLS-enabled listener like so:</li>
  525. </ul>
  526. <pre><code class="language-yaml">listeners:
  527. - port: 8448
  528. type: http
  529. tls: true
  530. resources:
  531. - names: [client, federation]
  532. </code></pre>
  533. <ul>
  534. <li>
  535. <p>You will also need to add the options <code>tls_certificate_path</code> and
  536. <code>tls_private_key_path</code>. to your configuration file. You will need to manage provisioning of
  537. these certificates yourself.</p>
  538. </li>
  539. <li>
  540. <p>You can find more information about these options as well as how to configure synapse in the
  541. <a href="setup/../usage/configuration/config_documentation.html">configuration manual</a>.</p>
  542. <p>If you are using your own certificate, be sure to use a <code>.pem</code> file that
  543. includes the full certificate chain including any intermediate certificates
  544. (for instance, if using certbot, use <code>fullchain.pem</code> as your certificate, not
  545. <code>cert.pem</code>).</p>
  546. </li>
  547. </ul>
  548. <p>For a more detailed guide to configuring your server for federation, see
  549. <a href="setup/../federate.html">Federation</a>.</p>
  550. <h3 id="client-well-known-uri"><a class="header" href="#client-well-known-uri">Client Well-Known URI</a></h3>
  551. <p>Setting up the client Well-Known URI is optional but if you set it up, it will
  552. allow users to enter their full username (e.g. <code>@user:&lt;server_name&gt;</code>) into clients
  553. which support well-known lookup to automatically configure the homeserver and
  554. identity server URLs. This is useful so that users don't have to memorize or think
  555. about the actual homeserver URL you are using.</p>
  556. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/client</code> should return JSON in
  557. the following format.</p>
  558. <pre><code class="language-json">{
  559. &quot;m.homeserver&quot;: {
  560. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  561. }
  562. }
  563. </code></pre>
  564. <p>It can optionally contain identity server information as well.</p>
  565. <pre><code class="language-json">{
  566. &quot;m.homeserver&quot;: {
  567. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  568. },
  569. &quot;m.identity_server&quot;: {
  570. &quot;base_url&quot;: &quot;https://&lt;identity.example.com&gt;&quot;
  571. }
  572. }
  573. </code></pre>
  574. <p>To work in browser based clients, the file must be served with the appropriate
  575. Cross-Origin Resource Sharing (CORS) headers. A recommended value would be
  576. <code>Access-Control-Allow-Origin: *</code> which would allow all browser based clients to
  577. view it.</p>
  578. <p>In nginx this would be something like:</p>
  579. <pre><code class="language-nginx">location /.well-known/matrix/client {
  580. return 200 '{&quot;m.homeserver&quot;: {&quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;}}';
  581. default_type application/json;
  582. add_header Access-Control-Allow-Origin *;
  583. }
  584. </code></pre>
  585. <p>You should also ensure the <code>public_baseurl</code> option in <code>homeserver.yaml</code> is set
  586. correctly. <code>public_baseurl</code> should be set to the URL that clients will use to
  587. connect to your server. This is the same URL you put for the <code>m.homeserver</code>
  588. <code>base_url</code> above.</p>
  589. <pre><code class="language-yaml">public_baseurl: &quot;https://&lt;matrix.example.com&gt;&quot;
  590. </code></pre>
  591. <h3 id="email"><a class="header" href="#email">Email</a></h3>
  592. <p>It is desirable for Synapse to have the capability to send email. This allows
  593. Synapse to send password reset emails, send verifications when an email address
  594. is added to a user's account, and send email notifications to users when they
  595. receive new messages.</p>
  596. <p>To configure an SMTP server for Synapse, modify the configuration section
  597. headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>, <code>smtp_port</code>
  598. and <code>notif_from</code> fields filled out. You may also need to set <code>smtp_user</code>,
  599. <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  600. <p>If email is not configured, password reset, registration and notifications via
  601. email will be disabled.</p>
  602. <h3 id="registering-a-user"><a class="header" href="#registering-a-user">Registering a user</a></h3>
  603. <p>One way to create a new user is to do so from a client like
  604. <a href="https://element.io/">Element</a>. This requires registration to be enabled via
  605. the
  606. <a href="setup/../usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a>
  607. setting.</p>
  608. <p>Alternatively, you can create new users from the command line. This can be done as follows:</p>
  609. <ol>
  610. <li>If synapse was installed via pip, activate the virtualenv as follows (if Synapse was
  611. installed via a prebuilt package, <code>register_new_matrix_user</code> should already be
  612. on the search path):
  613. <pre><code class="language-sh">cd ~/synapse
  614. source env/bin/activate
  615. synctl start # if not already running
  616. </code></pre>
  617. </li>
  618. <li>Run the following command:
  619. <pre><code class="language-sh">register_new_matrix_user -c homeserver.yaml
  620. </code></pre>
  621. </li>
  622. </ol>
  623. <p>This will prompt you to add details for the new user, and will then connect to
  624. the running Synapse to create the new user. For example:</p>
  625. <pre><code>New user localpart: erikj
  626. Password:
  627. Confirm password:
  628. Make admin [no]:
  629. Success!
  630. </code></pre>
  631. <p>This process uses a setting
  632. <a href="setup/../usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>,
  633. which is shared between Synapse itself and the <code>register_new_matrix_user</code>
  634. script. It doesn't matter what it is (a random value is generated by
  635. <code>--generate-config</code>), but it should be kept secret, as anyone with knowledge of
  636. it can register users, including admin accounts, on your server even if
  637. <code>enable_registration</code> is <code>false</code>.</p>
  638. <h3 id="setting-up-a-turn-server"><a class="header" href="#setting-up-a-turn-server">Setting up a TURN server</a></h3>
  639. <p>For reliable VoIP calls to be routed via this homeserver, you MUST configure
  640. a TURN server. See <a href="setup/../turn-howto.html">TURN setup</a> for details.</p>
  641. <h3 id="url-previews"><a class="header" href="#url-previews">URL previews</a></h3>
  642. <p>Synapse includes support for previewing URLs, which is disabled by default. To
  643. turn it on you must enable the <code>url_preview_enabled: True</code> config parameter
  644. and explicitly specify the IP ranges that Synapse is not allowed to spider for
  645. previewing in the <code>url_preview_ip_range_blacklist</code> configuration parameter.
  646. This is critical from a security perspective to stop arbitrary Matrix users
  647. spidering 'internal' URLs on your network. At the very least we recommend that
  648. your loopback and RFC1918 IP addresses are blacklisted.</p>
  649. <p>This also requires the optional <code>lxml</code> python dependency to be installed. This
  650. in turn requires the <code>libxml2</code> library to be available - on Debian/Ubuntu this
  651. means <code>apt-get install libxml2-dev</code>, or equivalent for your OS.</p>
  652. <h3 id="troubleshooting-installation"><a class="header" href="#troubleshooting-installation">Troubleshooting Installation</a></h3>
  653. <p><code>pip</code> seems to leak <em>lots</em> of memory during installation. For instance, a Linux
  654. host with 512MB of RAM may run out of memory whilst installing Twisted. If this
  655. happens, you will have to individually install the dependencies which are
  656. failing, e.g.:</p>
  657. <pre><code class="language-sh">pip install twisted
  658. </code></pre>
  659. <p>If you have any other problems, feel free to ask in
  660. <a href="https://matrix.to/#/#synapse:matrix.org">#synapse:matrix.org</a>.</p>
  661. <div style="break-before: page; page-break-before: always;"></div><h1 id="using-postgres"><a class="header" href="#using-postgres">Using Postgres</a></h1>
  662. <p>The minimum supported version of PostgreSQL is determined by the <a href="deprecation_policy.html">Dependency
  663. Deprecation Policy</a>.</p>
  664. <h2 id="install-postgres-client-libraries"><a class="header" href="#install-postgres-client-libraries">Install postgres client libraries</a></h2>
  665. <p>Synapse will require the python postgres client library in order to
  666. connect to a postgres database.</p>
  667. <ul>
  668. <li>
  669. <p>If you are using the <a href="setup/installation.html#matrixorg-packages">matrix.org debian/ubuntu
  670. packages</a>, the necessary python
  671. library will already be installed, but you will need to ensure the
  672. low-level postgres library is installed, which you can do with
  673. <code>apt install libpq5</code>.</p>
  674. </li>
  675. <li>
  676. <p>For other pre-built packages, please consult the documentation from
  677. the relevant package.</p>
  678. </li>
  679. <li>
  680. <p>If you installed synapse <a href="setup/installation.html#installing-as-a-python-module-from-pypi">in a
  681. virtualenv</a>, you can install
  682. the library with:</p>
  683. <pre><code>~/synapse/env/bin/pip install &quot;matrix-synapse[postgres]&quot;
  684. </code></pre>
  685. <p>(substituting the path to your virtualenv for <code>~/synapse/env</code>, if
  686. you used a different path). You will require the postgres
  687. development files. These are in the <code>libpq-dev</code> package on
  688. Debian-derived distributions.</p>
  689. </li>
  690. </ul>
  691. <h2 id="set-up-database"><a class="header" href="#set-up-database">Set up database</a></h2>
  692. <p>Assuming your PostgreSQL database user is called <code>postgres</code>, first authenticate as the database user with:</p>
  693. <pre><code class="language-sh">su - postgres
  694. # Or, if your system uses sudo to get administrative rights
  695. sudo -u postgres bash
  696. </code></pre>
  697. <p>Then, create a postgres user and a database with:</p>
  698. <pre><code class="language-sh"># this will prompt for a password for the new user
  699. createuser --pwprompt synapse_user
  700. createdb --encoding=UTF8 --locale=C --template=template0 --owner=synapse_user synapse
  701. </code></pre>
  702. <p>The above will create a user called <code>synapse_user</code>, and a database called
  703. <code>synapse</code>.</p>
  704. <p>Note that the PostgreSQL database <em>must</em> have the correct encoding set
  705. (as shown above), otherwise it will not be able to store UTF8 strings.</p>
  706. <p>You may need to enable password authentication so <code>synapse_user</code> can
  707. connect to the database. See
  708. <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>
  709. <h2 id="synapse-config"><a class="header" href="#synapse-config">Synapse config</a></h2>
  710. <p>When you are ready to start using PostgreSQL, edit the <code>database</code>
  711. section in your config file to match the following lines:</p>
  712. <pre><code class="language-yaml">database:
  713. name: psycopg2
  714. args:
  715. user: &lt;user&gt;
  716. password: &lt;pass&gt;
  717. database: &lt;db&gt;
  718. host: &lt;host&gt;
  719. cp_min: 5
  720. cp_max: 10
  721. </code></pre>
  722. <p>All key, values in <code>args</code> are passed to the <code>psycopg2.connect(..)</code>
  723. function, except keys beginning with <code>cp_</code>, which are consumed by the
  724. twisted adbapi connection pool. See the <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">libpq
  725. documentation</a>
  726. for a list of options which can be passed.</p>
  727. <p>You should consider tuning the <code>args.keepalives_*</code> options if there is any danger of
  728. the connection between your homeserver and database dropping, otherwise Synapse
  729. may block for an extended period while it waits for a response from the
  730. database server. Example values might be:</p>
  731. <pre><code class="language-yaml">database:
  732. args:
  733. # ... as above
  734. # seconds of inactivity after which TCP should send a keepalive message to the server
  735. keepalives_idle: 10
  736. # the number of seconds after which a TCP keepalive message that is not
  737. # acknowledged by the server should be retransmitted
  738. keepalives_interval: 10
  739. # the number of TCP keepalives that can be lost before the client's connection
  740. # to the server is considered dead
  741. keepalives_count: 3
  742. </code></pre>
  743. <h2 id="tuning-postgres"><a class="header" href="#tuning-postgres">Tuning Postgres</a></h2>
  744. <p>The default settings should be fine for most deployments. For larger
  745. scale deployments tuning some of the settings is recommended, details of
  746. which can be found at
  747. <a href="https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server">https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server</a>.</p>
  748. <p>In particular, we've found tuning the following values helpful for
  749. performance:</p>
  750. <ul>
  751. <li><code>shared_buffers</code></li>
  752. <li><code>effective_cache_size</code></li>
  753. <li><code>work_mem</code></li>
  754. <li><code>maintenance_work_mem</code></li>
  755. <li><code>autovacuum_work_mem</code></li>
  756. </ul>
  757. <p>Note that the appropriate values for those fields depend on the amount
  758. of free memory the database host has available.</p>
  759. <p>Additionally, admins of large deployments might want to consider using huge pages
  760. to help manage memory, especially when using large values of <code>shared_buffers</code>. You
  761. can read more about that <a href="https://www.postgresql.org/docs/10/kernel-resources.html#LINUX-HUGE-PAGES">here</a>.</p>
  762. <h2 id="porting-from-sqlite"><a class="header" href="#porting-from-sqlite">Porting from SQLite</a></h2>
  763. <h3 id="overview"><a class="header" href="#overview">Overview</a></h3>
  764. <p>The script <code>synapse_port_db</code> allows porting an existing synapse server
  765. backed by SQLite to using PostgreSQL. This is done in as a two phase
  766. process:</p>
  767. <ol>
  768. <li>Copy the existing SQLite database to a separate location and run
  769. the port script against that offline database.</li>
  770. <li>Shut down the server. Rerun the port script to port any data that
  771. has come in since taking the first snapshot. Restart server against
  772. the PostgreSQL database.</li>
  773. </ol>
  774. <p>The port script is designed to be run repeatedly against newer snapshots
  775. of the SQLite database file. This makes it safe to repeat step 1 if
  776. there was a delay between taking the previous snapshot and being ready
  777. to do step 2.</p>
  778. <p>It is safe to at any time kill the port script and restart it.</p>
  779. <p>However, under no circumstances should the SQLite database be <code>VACUUM</code>ed between
  780. multiple runs of the script. Doing so can lead to an inconsistent copy of your database
  781. into Postgres.
  782. To avoid accidental error, the script will check that SQLite's <code>auto_vacuum</code> mechanism
  783. is disabled, but the script is not able to protect against a manual <code>VACUUM</code> operation
  784. performed either by the administrator or by any automated task that the administrator
  785. may have configured.</p>
  786. <p>Note that the database may take up significantly more (25% - 100% more)
  787. space on disk after porting to Postgres.</p>
  788. <h3 id="using-the-port-script"><a class="header" href="#using-the-port-script">Using the port script</a></h3>
  789. <p>Firstly, shut down the currently running synapse server and copy its
  790. database file (typically <code>homeserver.db</code>) to another location. Once the
  791. copy is complete, restart synapse. For instance:</p>
  792. <pre><code class="language-sh">synctl stop
  793. cp homeserver.db homeserver.db.snapshot
  794. synctl start
  795. </code></pre>
  796. <p>Copy the old config file into a new config file:</p>
  797. <pre><code class="language-sh">cp homeserver.yaml homeserver-postgres.yaml
  798. </code></pre>
  799. <p>Edit the database section as described in the section <em>Synapse config</em>
  800. above and with the SQLite snapshot located at <code>homeserver.db.snapshot</code>
  801. simply run:</p>
  802. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db.snapshot \
  803. --postgres-config homeserver-postgres.yaml
  804. </code></pre>
  805. <p>The flag <code>--curses</code> displays a coloured curses progress UI.</p>
  806. <p>If the script took a long time to complete, or time has otherwise passed
  807. since the original snapshot was taken, repeat the previous steps with a
  808. newer snapshot.</p>
  809. <p>To complete the conversion shut down the synapse server and run the port
  810. script one last time, e.g. if the SQLite database is at <code>homeserver.db</code>
  811. run:</p>
  812. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db \
  813. --postgres-config homeserver-postgres.yaml
  814. </code></pre>
  815. <p>Once that has completed, change the synapse config to point at the
  816. PostgreSQL database configuration file <code>homeserver-postgres.yaml</code>:</p>
  817. <pre><code class="language-sh">synctl stop
  818. mv homeserver.yaml homeserver-old-sqlite.yaml
  819. mv homeserver-postgres.yaml homeserver.yaml
  820. synctl start
  821. </code></pre>
  822. <p>Synapse should now be running against PostgreSQL.</p>
  823. <h2 id="troubleshooting"><a class="header" href="#troubleshooting">Troubleshooting</a></h2>
  824. <h3 id="alternative-auth-methods"><a class="header" href="#alternative-auth-methods">Alternative auth methods</a></h3>
  825. <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
  826. <code>ident</code>:</p>
  827. <ul>
  828. <li>
  829. <p>If the <code>synapse_user</code> user has a password, add the password to the <code>database:</code>
  830. section of <code>homeserver.yaml</code>. Then add the following to <code>pg_hba.conf</code>:</p>
  831. <pre><code>host synapse synapse_user ::1/128 md5 # or `scram-sha-256` instead of `md5` if you use that
  832. </code></pre>
  833. </li>
  834. <li>
  835. <p>If the <code>synapse_user</code> user does not have a password, then a password doesn't
  836. have to be added to <code>homeserver.yaml</code>. But the following does need to be added
  837. to <code>pg_hba.conf</code>:</p>
  838. <pre><code>host synapse synapse_user ::1/128 trust
  839. </code></pre>
  840. </li>
  841. </ul>
  842. <p>Note that line order matters in <code>pg_hba.conf</code>, so make sure that if you do add a
  843. new line, it is inserted before:</p>
  844. <pre><code>host all all ::1/128 ident
  845. </code></pre>
  846. <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>
  847. <p>Synapse will refuse to set up a new database if it has the wrong values of
  848. <code>COLLATE</code> and <code>CTYPE</code> set. Synapse will also refuse to start an existing database with incorrect values
  849. of <code>COLLATE</code> and <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the
  850. <code>database</code> section of the config, is set to true. Using different locales can cause issues if the locale library is updated from
  851. underneath the database, or if a different version of the locale is used on any
  852. replicas.</p>
  853. <p>If you have a database with an unsafe locale, the safest way to fix the issue is to dump the database and recreate it with
  854. the correct locale parameter (as shown above). It is also possible to change the
  855. parameters on a live database and run a <code>REINDEX</code> on the entire database,
  856. however extreme care must be taken to avoid database corruption.</p>
  857. <p>Note that the above may fail with an error about duplicate rows if corruption
  858. has already occurred, and such duplicate rows will need to be manually removed.</p>
  859. <h3 id="fixing-inconsistent-sequences-error"><a class="header" href="#fixing-inconsistent-sequences-error">Fixing inconsistent sequences error</a></h3>
  860. <p>Synapse uses Postgres sequences to generate IDs for various tables. A sequence
  861. and associated table can get out of sync if, for example, Synapse has been
  862. downgraded and then upgraded again.</p>
  863. <p>To fix the issue shut down Synapse (including any and all workers) and run the
  864. SQL command included in the error message. Once done Synapse should start
  865. successfully.</p>
  866. <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>
  867. <p>It is recommended to put a reverse proxy such as
  868. <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">nginx</a>,
  869. <a href="https://httpd.apache.org/docs/current/mod/mod_proxy_http.html">Apache</a>,
  870. <a href="https://caddyserver.com/docs/quick-starts/reverse-proxy">Caddy</a>,
  871. <a href="https://www.haproxy.org/">HAProxy</a> or
  872. <a href="https://man.openbsd.org/relayd.8">relayd</a> in front of Synapse. One advantage
  873. of doing so is that it means that you can expose the default https port
  874. (443) to Matrix clients without needing to run Synapse with root
  875. privileges.</p>
  876. <p>You should configure your reverse proxy to forward requests to <code>/_matrix</code> or
  877. <code>/_synapse/client</code> to Synapse, and have it set the <code>X-Forwarded-For</code> and
  878. <code>X-Forwarded-Proto</code> request headers.</p>
  879. <p>You should remember that Matrix clients and other Matrix servers do not
  880. necessarily need to connect to your server via the same server name or
  881. port. Indeed, clients will use port 443 by default, whereas servers default to
  882. port 8448. Where these are different, we refer to the 'client port' and the
  883. 'federation port'. See <a href="https://matrix.org/docs/spec/server_server/latest#resolving-server-names">the Matrix
  884. specification</a>
  885. for more details of the algorithm used for federation connections, and
  886. <a href="delegate.html">Delegation</a> for instructions on setting up delegation.</p>
  887. <p><strong>NOTE</strong>: Your reverse proxy must not <code>canonicalise</code> or <code>normalise</code>
  888. the requested URI in any way (for example, by decoding <code>%xx</code> escapes).
  889. Beware that Apache <em>will</em> canonicalise URIs unless you specify
  890. <code>nocanon</code>.</p>
  891. <p>Let's assume that we expect clients to connect to our server at
  892. <code>https://matrix.example.com</code>, and other servers to connect at
  893. <code>https://example.com:8448</code>. The following sections detail the configuration of
  894. the reverse proxy and the homeserver.</p>
  895. <h2 id="homeserver-configuration"><a class="header" href="#homeserver-configuration">Homeserver Configuration</a></h2>
  896. <p>The HTTP configuration will need to be updated for Synapse to correctly record
  897. client IP addresses and generate redirect URLs while behind a reverse proxy. </p>
  898. <p>In <code>homeserver.yaml</code> set <code>x_forwarded: true</code> in the port 8008 section and
  899. consider setting <code>bind_addresses: ['127.0.0.1']</code> so that the server only
  900. listens to traffic on localhost. (Do not change <code>bind_addresses</code> to <code>127.0.0.1</code>
  901. when using a containerized Synapse, as that will prevent it from responding
  902. to proxied traffic.)</p>
  903. <p>Optionally, you can also set
  904. <a href="./usage/configuration/config_documentation.html#listeners"><code>request_id_header</code></a>
  905. so that the server extracts and re-uses the same request ID format that the
  906. reverse proxy is using.</p>
  907. <h2 id="reverse-proxy-configuration-examples"><a class="header" href="#reverse-proxy-configuration-examples">Reverse-proxy configuration examples</a></h2>
  908. <p><strong>NOTE</strong>: You only need one of these.</p>
  909. <h3 id="nginx"><a class="header" href="#nginx">nginx</a></h3>
  910. <pre><code class="language-nginx">server {
  911. listen 443 ssl http2;
  912. listen [::]:443 ssl http2;
  913. # For the federation port
  914. listen 8448 ssl http2 default_server;
  915. listen [::]:8448 ssl http2 default_server;
  916. server_name matrix.example.com;
  917. location ~ ^(/_matrix|/_synapse/client) {
  918. # note: do not add a path (even a single /) after the port in `proxy_pass`,
  919. # otherwise nginx will canonicalise the URI and cause signature verification
  920. # errors.
  921. proxy_pass http://localhost:8008;
  922. proxy_set_header X-Forwarded-For $remote_addr;
  923. proxy_set_header X-Forwarded-Proto $scheme;
  924. proxy_set_header Host $host;
  925. # Nginx by default only allows file uploads up to 1M in size
  926. # Increase client_max_body_size to match max_upload_size defined in homeserver.yaml
  927. client_max_body_size 50M;
  928. # Synapse responses may be chunked, which is an HTTP/1.1 feature.
  929. proxy_http_version 1.1;
  930. }
  931. }
  932. </code></pre>
  933. <h3 id="caddy-v2"><a class="header" href="#caddy-v2">Caddy v2</a></h3>
  934. <pre><code>matrix.example.com {
  935. reverse_proxy /_matrix/* localhost:8008
  936. reverse_proxy /_synapse/client/* localhost:8008
  937. }
  938. example.com:8448 {
  939. reverse_proxy /_matrix/* localhost:8008
  940. }
  941. </code></pre>
  942. <p><a href="delegate.html">Delegation</a> example:</p>
  943. <pre><code>example.com {
  944. header /.well-known/matrix/* Content-Type application/json
  945. header /.well-known/matrix/* Access-Control-Allow-Origin *
  946. respond /.well-known/matrix/server `{&quot;m.server&quot;: &quot;matrix.example.com:443&quot;}`
  947. 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;}}`
  948. }
  949. matrix.example.com {
  950. reverse_proxy /_matrix/* localhost:8008
  951. reverse_proxy /_synapse/client/* localhost:8008
  952. }
  953. </code></pre>
  954. <h3 id="apache"><a class="header" href="#apache">Apache</a></h3>
  955. <pre><code class="language-apache">&lt;VirtualHost *:443&gt;
  956. SSLEngine on
  957. ServerName matrix.example.com
  958. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  959. AllowEncodedSlashes NoDecode
  960. ProxyPreserveHost on
  961. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  962. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  963. ProxyPass /_synapse/client http://127.0.0.1:8008/_synapse/client nocanon
  964. ProxyPassReverse /_synapse/client http://127.0.0.1:8008/_synapse/client
  965. &lt;/VirtualHost&gt;
  966. &lt;VirtualHost *:8448&gt;
  967. SSLEngine on
  968. ServerName example.com
  969. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  970. AllowEncodedSlashes NoDecode
  971. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  972. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  973. &lt;/VirtualHost&gt;
  974. </code></pre>
  975. <p><strong>NOTE</strong>: ensure the <code>nocanon</code> options are included.</p>
  976. <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>
  977. <pre><code class="language-apache">&lt;IfModule security2_module&gt;
  978. SecRuleEngine off
  979. &lt;/IfModule&gt;
  980. </code></pre>
  981. <p><strong>NOTE 3</strong>: Missing <code>ProxyPreserveHost on</code> can lead to a redirect loop.</p>
  982. <h3 id="haproxy"><a class="header" href="#haproxy">HAProxy</a></h3>
  983. <pre><code>frontend https
  984. bind *:443,[::]:443 ssl crt /etc/ssl/haproxy/ strict-sni alpn h2,http/1.1
  985. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  986. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  987. http-request set-header X-Forwarded-For %[src]
  988. # Matrix client traffic
  989. acl matrix-host hdr(host) -i matrix.example.com matrix.example.com:443
  990. acl matrix-path path_beg /_matrix
  991. acl matrix-path path_beg /_synapse/client
  992. use_backend matrix if matrix-host matrix-path
  993. frontend matrix-federation
  994. bind *:8448,[::]:8448 ssl crt /etc/ssl/haproxy/synapse.pem alpn h2,http/1.1
  995. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  996. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  997. http-request set-header X-Forwarded-For %[src]
  998. default_backend matrix
  999. backend matrix
  1000. server matrix 127.0.0.1:8008
  1001. </code></pre>
  1002. <p><a href="delegate.html">Delegation</a> example:</p>
  1003. <pre><code>frontend https
  1004. acl matrix-well-known-client-path path /.well-known/matrix/client
  1005. acl matrix-well-known-server-path path /.well-known/matrix/server
  1006. use_backend matrix-well-known-client if matrix-well-known-client-path
  1007. use_backend matrix-well-known-server if matrix-well-known-server-path
  1008. backend matrix-well-known-client
  1009. http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  1010. http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  1011. http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  1012. 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;}}'
  1013. backend matrix-well-known-server
  1014. http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  1015. http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  1016. http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  1017. http-request return status 200 content-type application/json string '{&quot;m.server&quot;:&quot;matrix.example.com:443&quot;}'
  1018. </code></pre>
  1019. <h3 id="relayd"><a class="header" href="#relayd">Relayd</a></h3>
  1020. <pre><code>table &lt;webserver&gt; { 127.0.0.1 }
  1021. table &lt;matrixserver&gt; { 127.0.0.1 }
  1022. http protocol &quot;https&quot; {
  1023. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  1024. tls keypair &quot;example.com&quot;
  1025. match header set &quot;X-Forwarded-For&quot; value &quot;$REMOTE_ADDR&quot;
  1026. match header set &quot;X-Forwarded-Proto&quot; value &quot;https&quot;
  1027. # set CORS header for .well-known/matrix/server, .well-known/matrix/client
  1028. # httpd does not support setting headers, so do it here
  1029. match request path &quot;/.well-known/matrix/*&quot; tag &quot;matrix-cors&quot;
  1030. match response tagged &quot;matrix-cors&quot; header set &quot;Access-Control-Allow-Origin&quot; value &quot;*&quot;
  1031. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1032. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1033. # pass on non-matrix traffic to webserver
  1034. pass forward to &lt;webserver&gt;
  1035. }
  1036. relay &quot;https_traffic&quot; {
  1037. listen on egress port 443 tls
  1038. protocol &quot;https&quot;
  1039. forward to &lt;matrixserver&gt; port 8008 check tcp
  1040. forward to &lt;webserver&gt; port 8080 check tcp
  1041. }
  1042. http protocol &quot;matrix&quot; {
  1043. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  1044. tls keypair &quot;example.com&quot;
  1045. block
  1046. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1047. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1048. }
  1049. relay &quot;matrix_federation&quot; {
  1050. listen on egress port 8448 tls
  1051. protocol &quot;matrix&quot;
  1052. forward to &lt;matrixserver&gt; port 8008 check tcp
  1053. }
  1054. </code></pre>
  1055. <h2 id="health-check-endpoint"><a class="header" href="#health-check-endpoint">Health check endpoint</a></h2>
  1056. <p>Synapse exposes a health check endpoint for use by reverse proxies.
  1057. Each configured HTTP listener has a <code>/health</code> endpoint which always returns
  1058. 200 OK (and doesn't get logged).</p>
  1059. <h2 id="synapse-administration-endpoints"><a class="header" href="#synapse-administration-endpoints">Synapse administration endpoints</a></h2>
  1060. <p>Endpoints for administering your Synapse instance are placed under
  1061. <code>/_synapse/admin</code>. These require authentication through an access token of an
  1062. admin user. However as access to these endpoints grants the caller a lot of power,
  1063. we do not recommend exposing them to the public internet without good reason.</p>
  1064. <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>
  1065. <p>You can use Synapse with a forward or outbound proxy. An example of when
  1066. this is necessary is in corporate environments behind a DMZ (demilitarized zone).
  1067. Synapse supports routing outbound HTTP(S) requests via a proxy. Only HTTP(S)
  1068. proxy is supported, not SOCKS proxy or anything else.</p>
  1069. <h2 id="configure"><a class="header" href="#configure">Configure</a></h2>
  1070. <p>The <code>http_proxy</code>, <code>https_proxy</code>, <code>no_proxy</code> environment variables are used to
  1071. specify proxy settings. The environment variable is not case sensitive.</p>
  1072. <ul>
  1073. <li><code>http_proxy</code>: Proxy server to use for HTTP requests.</li>
  1074. <li><code>https_proxy</code>: Proxy server to use for HTTPS requests.</li>
  1075. <li><code>no_proxy</code>: Comma-separated list of hosts, IP addresses, or IP ranges in CIDR
  1076. format which should not use the proxy. Synapse will directly connect to these hosts.</li>
  1077. </ul>
  1078. <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>
  1079. <ul>
  1080. <li>
  1081. <p>Supported schemes are <code>http://</code> and <code>https://</code>. The default scheme is <code>http://</code>
  1082. for compatibility reasons; it is recommended to set a scheme. If scheme is set
  1083. to <code>https://</code> the connection uses TLS between Synapse and the proxy.</p>
  1084. <p><strong>NOTE</strong>: Synapse validates the certificates. If the certificate is not
  1085. valid, then the connection is dropped.</p>
  1086. </li>
  1087. <li>
  1088. <p>Default port if not given is <code>1080</code>.</p>
  1089. </li>
  1090. <li>
  1091. <p>Username and password are optional and will be used to authenticate against
  1092. the proxy.</p>
  1093. </li>
  1094. </ul>
  1095. <p><strong>Examples</strong></p>
  1096. <ul>
  1097. <li>HTTP_PROXY=http://USERNAME:PASSWORD@10.0.1.1:8080/</li>
  1098. <li>HTTPS_PROXY=http://USERNAME:PASSWORD@proxy.example.com:8080/</li>
  1099. <li>NO_PROXY=master.hostname.example.com,10.1.0.0/16,172.30.0.0/16</li>
  1100. </ul>
  1101. <p><strong>NOTE</strong>:
  1102. Synapse does not apply the IP blacklist to connections through the proxy (since
  1103. the DNS resolution is done by the proxy). It is expected that the proxy or firewall
  1104. will apply blacklisting of IP addresses.</p>
  1105. <h2 id="connection-types"><a class="header" href="#connection-types">Connection types</a></h2>
  1106. <p>The proxy will be <strong>used</strong> for:</p>
  1107. <ul>
  1108. <li>push</li>
  1109. <li>url previews</li>
  1110. <li>phone-home stats</li>
  1111. <li>recaptcha validation</li>
  1112. <li>CAS auth validation</li>
  1113. <li>OpenID Connect</li>
  1114. <li>Outbound federation</li>
  1115. <li>Federation (checking public key revocation)</li>
  1116. <li>Fetching public keys of other servers</li>
  1117. <li>Downloading remote media</li>
  1118. </ul>
  1119. <p>It will <strong>not be used</strong> for:</p>
  1120. <ul>
  1121. <li>Application Services</li>
  1122. <li>Identity servers</li>
  1123. <li>In worker configurations
  1124. <ul>
  1125. <li>connections between workers</li>
  1126. <li>connections from workers to Redis</li>
  1127. </ul>
  1128. </li>
  1129. </ul>
  1130. <h2 id="troubleshooting-1"><a class="header" href="#troubleshooting-1">Troubleshooting</a></h2>
  1131. <p>If a proxy server is used with TLS (HTTPS) and no connections are established,
  1132. it is most likely due to the proxy's certificates. To test this, the validation
  1133. in Synapse can be deactivated.</p>
  1134. <p><strong>NOTE</strong>: This has an impact on security and is for testing purposes only!</p>
  1135. <p>To deactivate the certificate validation, the following setting must be added to
  1136. your <a href="setup/../usage/configuration/homeserver_sample_config.html">homserver.yaml</a>.</p>
  1137. <pre><code class="language-yaml">use_insecure_ssl_client_just_for_testing_do_not_use: true
  1138. </code></pre>
  1139. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-1"><a class="header" href="#overview-1">Overview</a></h1>
  1140. <p>This document explains how to enable VoIP relaying on your homeserver with
  1141. TURN.</p>
  1142. <p>The synapse Matrix homeserver supports integration with TURN server via the
  1143. <a href="https://tools.ietf.org/html/draft-uberti-behave-turn-rest-00">TURN server REST API</a>. This
  1144. allows the homeserver to generate credentials that are valid for use on the
  1145. TURN server through the use of a secret shared between the homeserver and the
  1146. TURN server.</p>
  1147. <p>This documentation provides two TURN server configuration examples:</p>
  1148. <ul>
  1149. <li><a href="setup/turn/coturn.html">coturn</a></li>
  1150. <li><a href="setup/turn/eturnal.html">eturnal</a></li>
  1151. </ul>
  1152. <h2 id="requirements"><a class="header" href="#requirements">Requirements</a></h2>
  1153. <p>For TURN relaying to work, the TURN service must be hosted on a server/endpoint with a public IP.</p>
  1154. <p>Hosting TURN behind NAT requires port forwarding and for the NAT gateway to have a public IP.
  1155. However, even with appropriate configuration, NAT is known to cause issues and to often not work.</p>
  1156. <p>Afterwards, the homeserver needs some further configuration.</p>
  1157. <h2 id="synapse-setup"><a class="header" href="#synapse-setup">Synapse setup</a></h2>
  1158. <p>Your homeserver configuration file needs the following extra keys:</p>
  1159. <ol>
  1160. <li><a href="usage/configuration/config_documentation.html#turn_uris"><code>turn_uris</code></a></li>
  1161. <li><a href="usage/configuration/config_documentation.html#turn_shared_secret"><code>turn_shared_secret</code></a></li>
  1162. <li><a href="usage/configuration/config_documentation.html#turn_user_lifetime"><code>turn_user_lifetime</code></a></li>
  1163. <li><a href="usage/configuration/config_documentation.html#turn_allow_guests"><code>turn_allow_guests</code></a></li>
  1164. </ol>
  1165. <p>As an example, here is the relevant section of the config file for <code>matrix.org</code>. The
  1166. <code>turn_uris</code> are appropriate for TURN servers listening on the default ports, with no TLS.</p>
  1167. <pre><code>turn_uris: [ &quot;turn:turn.matrix.org?transport=udp&quot;, &quot;turn:turn.matrix.org?transport=tcp&quot; ]
  1168. turn_shared_secret: &quot;n0t4ctuAllymatr1Xd0TorgSshar3d5ecret4obvIousreAsons&quot;
  1169. turn_user_lifetime: 86400000
  1170. turn_allow_guests: true
  1171. </code></pre>
  1172. <p>After updating the homeserver configuration, you must restart synapse:</p>
  1173. <ul>
  1174. <li>If you use synctl:
  1175. <pre><code class="language-sh"># Depending on how Synapse is installed, synctl may already be on
  1176. # your PATH. If not, you may need to activate a virtual environment.
  1177. synctl restart
  1178. </code></pre>
  1179. </li>
  1180. <li>If you use systemd:
  1181. <pre><code class="language-sh">systemctl restart matrix-synapse.service
  1182. </code></pre>
  1183. </li>
  1184. </ul>
  1185. <p>... and then reload any clients (or wait an hour for them to refresh their
  1186. settings).</p>
  1187. <h2 id="troubleshooting-2"><a class="header" href="#troubleshooting-2">Troubleshooting</a></h2>
  1188. <p>The normal symptoms of a misconfigured TURN server are that calls between
  1189. devices on different networks ring, but get stuck at &quot;call
  1190. connecting&quot;. Unfortunately, troubleshooting this can be tricky.</p>
  1191. <p>Here are a few things to try:</p>
  1192. <ul>
  1193. <li>
  1194. <p>Check that you have opened your firewall to allow TCP and UDP traffic to the
  1195. TURN ports (normally 3478 and 5349).</p>
  1196. </li>
  1197. <li>
  1198. <p>Check that you have opened your firewall to allow UDP traffic to the UDP
  1199. relay ports (49152-65535 by default).</p>
  1200. </li>
  1201. <li>
  1202. <p>Try disabling TLS/DTLS listeners and enable only its (unencrypted)
  1203. TCP/UDP listeners. (This will only leave signaling traffic unencrypted;
  1204. voice &amp; video WebRTC traffic is always encrypted.)</p>
  1205. </li>
  1206. <li>
  1207. <p>Some WebRTC implementations (notably, that of Google Chrome) appear to get
  1208. confused by TURN servers which are reachable over IPv6 (this appears to be
  1209. an unexpected side-effect of its handling of multiple IP addresses as
  1210. defined by
  1211. <a href="https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12"><code>draft-ietf-rtcweb-ip-handling</code></a>).</p>
  1212. <p>Try removing any AAAA records for your TURN server, so that it is only
  1213. reachable over IPv4.</p>
  1214. </li>
  1215. <li>
  1216. <p>If your TURN server is behind NAT:</p>
  1217. <ul>
  1218. <li>
  1219. <p>double-check that your NAT gateway is correctly forwarding all TURN
  1220. ports (normally 3478 &amp; 5349 for TCP &amp; UDP TURN traffic, and 49152-65535 for the UDP
  1221. relay) to the NAT-internal address of your TURN server. If advertising
  1222. both IPv4 and IPv6 external addresses via the <code>external-ip</code> option, ensure
  1223. that the NAT is forwarding both IPv4 and IPv6 traffic to the IPv4 and IPv6
  1224. internal addresses of your TURN server. When in doubt, remove AAAA records
  1225. for your TURN server and specify only an IPv4 address as your <code>external-ip</code>.</p>
  1226. </li>
  1227. <li>
  1228. <p>ensure that your TURN server uses the NAT gateway as its default route.</p>
  1229. </li>
  1230. </ul>
  1231. </li>
  1232. <li>
  1233. <p>Enable more verbose logging, in <code>coturn</code> via the <code>verbose</code> setting:</p>
  1234. <pre><code>verbose
  1235. </code></pre>
  1236. <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>
  1237. <pre><code class="language-yaml"> ## Logging configuration:
  1238. log_level: debug
  1239. </code></pre>
  1240. <p>... and then see if there are any clues in its logs.</p>
  1241. </li>
  1242. <li>
  1243. <p>If you are using a browser-based client under Chrome, check
  1244. <code>chrome://webrtc-internals/</code> for insights into the internals of the
  1245. negotiation. On Firefox, check the &quot;Connection Log&quot; on <code>about:webrtc</code>.</p>
  1246. <p>(Understanding the output is beyond the scope of this document!)</p>
  1247. </li>
  1248. <li>
  1249. <p>You can test your Matrix homeserver TURN setup with <a href="https://test.voip.librepush.net/">https://test.voip.librepush.net/</a>.
  1250. Note that this test is not fully reliable yet, so don't be discouraged if
  1251. the test fails.
  1252. <a href="https://github.com/matrix-org/voip-tester">Here</a> is the github repo of the
  1253. source of the tester, where you can file bug reports.</p>
  1254. </li>
  1255. <li>
  1256. <p>There is a WebRTC test tool at
  1257. <a href="https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/">https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/</a>. To
  1258. use it, you will need a username/password for your TURN server. You can
  1259. either:</p>
  1260. <ul>
  1261. <li>
  1262. <p>look for the <code>GET /_matrix/client/r0/voip/turnServer</code> request made by a
  1263. matrix client to your homeserver in your browser's network inspector. In
  1264. the response you should see <code>username</code> and <code>password</code>. Or:</p>
  1265. </li>
  1266. <li>
  1267. <p>Use the following shell commands for <code>coturn</code>:</p>
  1268. <pre><code class="language-sh">secret=staticAuthSecretHere
  1269. u=$((`date +%s` + 3600)):test
  1270. p=$(echo -n $u | openssl dgst -hmac $secret -sha1 -binary | base64)
  1271. echo -e &quot;username: $u\npassword: $p&quot;
  1272. </code></pre>
  1273. <p>or for <code>eturnal</code></p>
  1274. <pre><code class="language-sh">eturnalctl credentials
  1275. </code></pre>
  1276. </li>
  1277. <li>
  1278. <p>Or (<strong>coturn only</strong>): Temporarily configure <code>coturn</code> to accept a static
  1279. username/password. To do this, comment out <code>use-auth-secret</code> and
  1280. <code>static-auth-secret</code> and add the following:</p>
  1281. <pre><code>lt-cred-mech
  1282. user=username:password
  1283. </code></pre>
  1284. <p><strong>Note</strong>: these settings will not take effect unless <code>use-auth-secret</code>
  1285. and <code>static-auth-secret</code> are disabled.</p>
  1286. <p>Restart coturn after changing the configuration file.</p>
  1287. <p>Remember to restore the original settings to go back to testing with
  1288. Matrix clients!</p>
  1289. </li>
  1290. </ul>
  1291. <p>If the TURN server is working correctly, you should see at least one <code>relay</code>
  1292. entry in the results.</p>
  1293. </li>
  1294. </ul>
  1295. <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>
  1296. <p>The following sections describe how to install <a href="https://github.com/coturn/coturn">coturn</a> (which implements the TURN REST API).</p>
  1297. <h2 id="coturn-setup"><a class="header" href="#coturn-setup"><code>coturn</code> setup</a></h2>
  1298. <h3 id="initial-installation"><a class="header" href="#initial-installation">Initial installation</a></h3>
  1299. <p>The TURN daemon <code>coturn</code> is available from a variety of sources such as native package managers, or installation from source.</p>
  1300. <h4 id="debian-and-ubuntu-based-distributions"><a class="header" href="#debian-and-ubuntu-based-distributions">Debian and Ubuntu based distributions</a></h4>
  1301. <p>Just install the debian package:</p>
  1302. <pre><code class="language-sh">sudo apt install coturn
  1303. </code></pre>
  1304. <p>This will install and start a systemd service called <code>coturn</code>.</p>
  1305. <h4 id="source-installation"><a class="header" href="#source-installation">Source installation</a></h4>
  1306. <ol>
  1307. <li>
  1308. <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>
  1309. </li>
  1310. <li>
  1311. <p>Configure it:</p>
  1312. <pre><code class="language-sh">./configure
  1313. </code></pre>
  1314. <p>You may need to install <code>libevent2</code>: if so, you should do so in
  1315. the way recommended by your operating system. You can ignore
  1316. warnings about lack of database support: a database is unnecessary
  1317. for this purpose.</p>
  1318. </li>
  1319. <li>
  1320. <p>Build and install it:</p>
  1321. <pre><code class="language-sh">make
  1322. sudo make install
  1323. </code></pre>
  1324. </li>
  1325. </ol>
  1326. <h3 id="configuration"><a class="header" href="#configuration">Configuration</a></h3>
  1327. <ol>
  1328. <li>
  1329. <p>Create or edit the config file in <code>/etc/turnserver.conf</code>. The relevant
  1330. lines, with example values, are:</p>
  1331. <pre><code>use-auth-secret
  1332. static-auth-secret=[your secret key here]
  1333. realm=turn.myserver.org
  1334. </code></pre>
  1335. <p>See <code>turnserver.conf</code> for explanations of the options. One way to generate
  1336. the <code>static-auth-secret</code> is with <code>pwgen</code>:</p>
  1337. <pre><code class="language-sh">pwgen -s 64 1
  1338. </code></pre>
  1339. <p>A <code>realm</code> must be specified, but its value is somewhat arbitrary. (It is
  1340. sent to clients as part of the authentication flow.) It is conventional to
  1341. set it to be your server name.</p>
  1342. </li>
  1343. <li>
  1344. <p>You will most likely want to configure <code>coturn</code> to write logs somewhere. The
  1345. easiest way is normally to send them to the syslog:</p>
  1346. <pre><code class="language-sh">syslog
  1347. </code></pre>
  1348. <p>(in which case, the logs will be available via <code>journalctl -u coturn</code> on a
  1349. systemd system). Alternatively, <code>coturn</code> can be configured to write to a
  1350. logfile - check the example config file supplied with <code>coturn</code>.</p>
  1351. </li>
  1352. <li>
  1353. <p>Consider your security settings. TURN lets users request a relay which will
  1354. connect to arbitrary IP addresses and ports. The following configuration is
  1355. suggested as a minimum starting point:</p>
  1356. <pre><code># VoIP traffic is all UDP. There is no reason to let users connect to arbitrary TCP endpoints via the relay.
  1357. no-tcp-relay
  1358. # don't let the relay ever try to connect to private IP address ranges within your network (if any)
  1359. # given the turn server is likely behind your firewall, remember to include any privileged public IPs too.
  1360. denied-peer-ip=10.0.0.0-10.255.255.255
  1361. denied-peer-ip=192.168.0.0-192.168.255.255
  1362. denied-peer-ip=172.16.0.0-172.31.255.255
  1363. # recommended additional local peers to block, to mitigate external access to internal services.
  1364. # https://www.rtcsec.com/article/slack-webrtc-turn-compromise-and-bug-bounty/#how-to-fix-an-open-turn-relay-to-address-this-vulnerability
  1365. no-multicast-peers
  1366. denied-peer-ip=0.0.0.0-0.255.255.255
  1367. denied-peer-ip=100.64.0.0-100.127.255.255
  1368. denied-peer-ip=127.0.0.0-127.255.255.255
  1369. denied-peer-ip=169.254.0.0-169.254.255.255
  1370. denied-peer-ip=192.0.0.0-192.0.0.255
  1371. denied-peer-ip=192.0.2.0-192.0.2.255
  1372. denied-peer-ip=192.88.99.0-192.88.99.255
  1373. denied-peer-ip=198.18.0.0-198.19.255.255
  1374. denied-peer-ip=198.51.100.0-198.51.100.255
  1375. denied-peer-ip=203.0.113.0-203.0.113.255
  1376. denied-peer-ip=240.0.0.0-255.255.255.255
  1377. # special case the turn server itself so that client-&gt;TURN-&gt;TURN-&gt;client flows work
  1378. # this should be one of the turn server's listening IPs
  1379. allowed-peer-ip=10.0.0.1
  1380. # consider whether you want to limit the quota of relayed streams per user (or total) to avoid risk of DoS.
  1381. user-quota=12 # 4 streams per video call, so 12 streams = 3 simultaneous relayed calls per user.
  1382. total-quota=1200
  1383. </code></pre>
  1384. </li>
  1385. <li>
  1386. <p>Also consider supporting TLS/DTLS. To do this, add the following settings
  1387. to <code>turnserver.conf</code>:</p>
  1388. <pre><code># TLS certificates, including intermediate certs.
  1389. # For Let's Encrypt certificates, use `fullchain.pem` here.
  1390. cert=/path/to/fullchain.pem
  1391. # TLS private key file
  1392. pkey=/path/to/privkey.pem
  1393. # Ensure the configuration lines that disable TLS/DTLS are commented-out or removed
  1394. #no-tls
  1395. #no-dtls
  1396. </code></pre>
  1397. <p>In this case, replace the <code>turn:</code> schemes in the <code>turn_uris</code> settings below
  1398. with <code>turns:</code>.</p>
  1399. <p>We recommend that you only try to set up TLS/DTLS once you have set up a
  1400. basic installation and got it working.</p>
  1401. <p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
  1402. not work with any Matrix client that uses Chromium's WebRTC library. This
  1403. currently includes Element Android &amp; iOS; for more details, see their
  1404. <a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
  1405. <a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
  1406. <a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
  1407. Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
  1408. </li>
  1409. <li>
  1410. <p>Ensure your firewall allows traffic into the TURN server on the ports
  1411. you've configured it to listen on (By default: 3478 and 5349 for TURN
  1412. traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
  1413. for the UDP relay.)</p>
  1414. </li>
  1415. <li>
  1416. <p>If your TURN server is behind NAT, the NAT gateway must have an external,
  1417. publicly-reachable IP address. You must configure <code>coturn</code> to advertise that
  1418. address to connecting clients:</p>
  1419. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1420. </code></pre>
  1421. <p>You may optionally limit the TURN server to listen only on the local
  1422. address that is mapped by NAT to the external address:</p>
  1423. <pre><code>listening-ip=INTERNAL_TURNSERVER_IPv4_ADDRESS
  1424. </code></pre>
  1425. <p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
  1426. configure <code>coturn</code> to advertise each available address:</p>
  1427. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1428. external-ip=EXTERNAL_NAT_IPv6_ADDRESS
  1429. </code></pre>
  1430. <p>When advertising an external IPv6 address, ensure that the firewall and
  1431. network settings of the system running your TURN server are configured to
  1432. accept IPv6 traffic, and that the TURN server is listening on the local
  1433. IPv6 address that is mapped by NAT to the external IPv6 address.</p>
  1434. </li>
  1435. <li>
  1436. <p>(Re)start the turn server:</p>
  1437. <ul>
  1438. <li>
  1439. <p>If you used the Debian package (or have set up a systemd unit yourself):</p>
  1440. <pre><code class="language-sh">sudo systemctl restart coturn
  1441. </code></pre>
  1442. </li>
  1443. <li>
  1444. <p>If you built from source:</p>
  1445. <pre><code class="language-sh">/usr/local/bin/turnserver -o
  1446. </code></pre>
  1447. </li>
  1448. </ul>
  1449. </li>
  1450. </ol>
  1451. <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>
  1452. <p>The following sections describe how to install <a href="https://github.com/processone/eturnal">eturnal</a>
  1453. (which implements the TURN REST API).</p>
  1454. <h2 id="eturnal-setup"><a class="header" href="#eturnal-setup"><code>eturnal</code> setup</a></h2>
  1455. <h3 id="initial-installation-1"><a class="header" href="#initial-installation-1">Initial installation</a></h3>
  1456. <p>The <code>eturnal</code> TURN server implementation is available from a variety of sources
  1457. such as native package managers, binary packages, installation from source or
  1458. <a href="https://eturnal.net/documentation/code/docker.html">container image</a>. They are
  1459. all described <a href="https://github.com/processone/eturnal#installation">here</a>.</p>
  1460. <p>Quick-Test instructions in a <a href="https://github.com/processone/eturnal/blob/master/QUICK-TEST.md">Linux Shell</a>
  1461. or with <a href="https://github.com/processone/eturnal/blob/master/docker-k8s/QUICK-TEST.md">Docker</a>
  1462. are available as well.</p>
  1463. <h3 id="configuration-1"><a class="header" href="#configuration-1">Configuration</a></h3>
  1464. <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>
  1465. here: <code>/etc/eturnal.yml</code> (and, if not found there, there is a backup file here:
  1466. <code>/opt/eturnal/etc/eturnal.yml</code>). It uses the (indentation-sensitive!) <a href="https://en.wikipedia.org/wiki/YAML">YAML</a>
  1467. format. The file contains further explanations.</p>
  1468. <p>Here are some hints how to configure eturnal on your <a href="https://github.com/processone/eturnal#configuration">host machine</a>
  1469. or when using e.g. <a href="https://eturnal.net/documentation/code/docker.html">Docker</a>.
  1470. You may also further deep dive into the <a href="https://eturnal.net/documentation/">reference documentation</a>.</p>
  1471. <p><code>eturnal</code> runs out of the box with the default configuration. To enable TURN and
  1472. to integrate it with your homeserver, some aspects in <code>eturnal</code>'s default configuration file
  1473. must be edited:</p>
  1474. <ol>
  1475. <li>
  1476. <p>Homeserver's <a href="setup/turn/../../usage/configuration/config_documentation.html#turn_shared_secret"><code>turn_shared_secret</code></a>
  1477. and eturnal's shared <code>secret</code> for authentication</p>
  1478. <p>Both need to have the same value. Uncomment and adjust this line in <code>eturnal</code>'s
  1479. configuration file:</p>
  1480. <pre><code class="language-yaml">secret: &quot;long-and-cryptic&quot; # Shared secret, CHANGE THIS.
  1481. </code></pre>
  1482. <p>One way to generate a <code>secret</code> is with <code>pwgen</code>:</p>
  1483. <pre><code class="language-sh">pwgen -s 64 1
  1484. </code></pre>
  1485. </li>
  1486. <li>
  1487. <p>Public IP address</p>
  1488. <p>If your TURN server is behind NAT, the NAT gateway must have an external,
  1489. publicly-reachable IP address. <code>eturnal</code> tries to autodetect the public IP address,
  1490. however, it may also be configured by uncommenting and adjusting this line, so
  1491. <code>eturnal</code> advertises that address to connecting clients:</p>
  1492. <pre><code class="language-yaml">relay_ipv4_addr: &quot;203.0.113.4&quot; # The server's public IPv4 address.
  1493. </code></pre>
  1494. <p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
  1495. configure <code>eturnal</code> to advertise each available address:</p>
  1496. <pre><code class="language-yaml">relay_ipv4_addr: &quot;203.0.113.4&quot; # The server's public IPv4 address.
  1497. relay_ipv6_addr: &quot;2001:db8::4&quot; # The server's public IPv6 address (optional).
  1498. </code></pre>
  1499. <p>When advertising an external IPv6 address, ensure that the firewall and
  1500. network settings of the system running your TURN server are configured to
  1501. accept IPv6 traffic, and that the TURN server is listening on the local
  1502. IPv6 address that is mapped by NAT to the external IPv6 address.</p>
  1503. </li>
  1504. <li>
  1505. <p>Logging</p>
  1506. <p>If <code>eturnal</code> was started by systemd, log files are written into the
  1507. <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>
  1508. instead, the <code>log_dir</code> option can be set to <code>stdout</code> in the configuration file.</p>
  1509. </li>
  1510. <li>
  1511. <p>Security considerations</p>
  1512. <p>Consider your security settings. TURN lets users request a relay which will
  1513. connect to arbitrary IP addresses and ports. The following configuration is
  1514. suggested as a minimum starting point, <a href="https://eturnal.net/documentation/#blacklist">see also the official documentation</a>:</p>
  1515. <pre><code class="language-yaml">## Reject TURN relaying from/to the following addresses/networks:
  1516. blacklist: # This is the default blacklist.
  1517. - &quot;127.0.0.0/8&quot; # IPv4 loopback.
  1518. - &quot;::1&quot; # IPv6 loopback.
  1519. - recommended # Expands to a number of networks recommended to be
  1520. # blocked, but includes private networks. Those
  1521. # would have to be 'whitelist'ed if eturnal serves
  1522. # local clients/peers within such networks.
  1523. </code></pre>
  1524. <p>To whitelist IP addresses or specific (private) networks, you need to <strong>add</strong> a
  1525. whitelist part into the configuration file, e.g.:</p>
  1526. <pre><code class="language-yaml">whitelist:
  1527. - &quot;192.168.0.0/16&quot;
  1528. - &quot;203.0.113.113&quot;
  1529. - &quot;2001:db8::/64&quot;
  1530. </code></pre>
  1531. <p>The more specific, the better.</p>
  1532. </li>
  1533. <li>
  1534. <p>TURNS (TURN via TLS/DTLS)</p>
  1535. <p>Also consider supporting TLS/DTLS. To do this, adjust the following settings
  1536. in the <code>eturnal.yml</code> configuration file (TLS parts should not be commented anymore):</p>
  1537. <pre><code class="language-yaml">listen:
  1538. - ip: &quot;::&quot;
  1539. port: 3478
  1540. transport: udp
  1541. - ip: &quot;::&quot;
  1542. port: 3478
  1543. transport: tcp
  1544. - ip: &quot;::&quot;
  1545. port: 5349
  1546. transport: tls
  1547. ## TLS certificate/key files (must be readable by 'eturnal' user!):
  1548. tls_crt_file: /etc/eturnal/tls/crt.pem
  1549. tls_key_file: /etc/eturnal/tls/key.pem
  1550. </code></pre>
  1551. <p>In this case, replace the <code>turn:</code> schemes in homeserver's <code>turn_uris</code> settings
  1552. with <code>turns:</code>. More is described <a href="setup/turn/../../usage/configuration/config_documentation.html#turn_uris">here</a>.</p>
  1553. <p>We recommend that you only try to set up TLS/DTLS once you have set up a
  1554. basic installation and got it working.</p>
  1555. <p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
  1556. not work with any Matrix client that uses Chromium's WebRTC library. This
  1557. currently includes Element Android &amp; iOS; for more details, see their
  1558. <a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
  1559. <a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
  1560. <a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
  1561. Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
  1562. </li>
  1563. <li>
  1564. <p>Firewall</p>
  1565. <p>Ensure your firewall allows traffic into the TURN server on the ports
  1566. you've configured it to listen on (By default: 3478 and 5349 for TURN
  1567. traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
  1568. for the UDP relay.)</p>
  1569. </li>
  1570. <li>
  1571. <p>Reload/ restarting <code>eturnal</code></p>
  1572. <p>Changes in the configuration file require <code>eturnal</code> to reload/ restart, this
  1573. can be achieved by:</p>
  1574. <pre><code class="language-sh">eturnalctl reload
  1575. </code></pre>
  1576. <p><code>eturnal</code> performs a configuration check before actually reloading/ restarting
  1577. and provides hints, if something is not correctly configured.</p>
  1578. </li>
  1579. </ol>
  1580. <h3 id="eturnalctl-opterations-script"><a class="header" href="#eturnalctl-opterations-script">eturnalctl opterations script</a></h3>
  1581. <p><code>eturnal</code> offers a handy <a href="https://eturnal.net/documentation/#Operation">operations script</a>
  1582. which can be called e.g. to check, whether the service is up, to restart the service,
  1583. to query how many active sessions exist, to change logging behaviour and so on.</p>
  1584. <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>
  1585. <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>
  1586. <p>In the following documentation, we use the term <code>server_name</code> to refer to that setting
  1587. in your homeserver configuration file. It appears at the ends of user ids, and tells
  1588. other homeservers where they can find your server.</p>
  1589. <p>By default, other homeservers will expect to be able to reach yours via
  1590. your <code>server_name</code>, on port 8448. For example, if you set your <code>server_name</code>
  1591. to <code>example.com</code> (so that your user names look like <code>@user:example.com</code>),
  1592. other servers will try to connect to yours at <code>https://example.com:8448/</code>.</p>
  1593. <p>Delegation is a Matrix feature allowing a homeserver admin to retain a
  1594. <code>server_name</code> of <code>example.com</code> so that user IDs, room aliases, etc continue
  1595. to look like <code>*:example.com</code>, whilst having federation traffic routed
  1596. to a different server and/or port (e.g. <code>synapse.example.com:443</code>).</p>
  1597. <h2 id="well-known-delegation"><a class="header" href="#well-known-delegation">.well-known delegation</a></h2>
  1598. <p>To use this method, you need to be able to configure the server at
  1599. <code>https://&lt;server_name&gt;</code> to serve a file at
  1600. <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>. There are two ways to do this, shown below.</p>
  1601. <p>Note that the <code>.well-known</code> file is hosted on the default port for <code>https</code> (port 443).</p>
  1602. <h3 id="external-server"><a class="header" href="#external-server">External server</a></h3>
  1603. <p>For maximum flexibility, you need to configure an external server such as nginx, Apache
  1604. or HAProxy to serve the <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> file. Setting
  1605. up such a server is out of the scope of this documentation, but note that it is often
  1606. possible to configure your <a href="reverse_proxy.html">reverse proxy</a> for this.</p>
  1607. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> should be configured
  1608. return a JSON structure containing the key <code>m.server</code> like this:</p>
  1609. <pre><code class="language-json">{
  1610. &quot;m.server&quot;: &quot;&lt;synapse.server.name&gt;[:&lt;yourport&gt;]&quot;
  1611. }
  1612. </code></pre>
  1613. <p>In our example (where we want federation traffic to be routed to
  1614. <code>https://synapse.example.com</code>, on port 443), this would mean that
  1615. <code>https://example.com/.well-known/matrix/server</code> should return:</p>
  1616. <pre><code class="language-json">{
  1617. &quot;m.server&quot;: &quot;synapse.example.com:443&quot;
  1618. }
  1619. </code></pre>
  1620. <p>Note, specifying a port is optional. If no port is specified, then it defaults
  1621. to 8448.</p>
  1622. <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>
  1623. <p>If you are able to set up your domain so that <code>https://&lt;server_name&gt;</code> is routed to
  1624. Synapse (i.e., the only change needed is to direct federation traffic to port 443
  1625. instead of port 8448), then it is possible to configure Synapse to serve a suitable
  1626. <code>.well-known/matrix/server</code> file. To do so, add the following to your <code>homeserver.yaml</code>
  1627. file:</p>
  1628. <pre><code class="language-yaml">serve_server_wellknown: true
  1629. </code></pre>
  1630. <p><strong>Note</strong>: this <em>only</em> works if <code>https://&lt;server_name&gt;</code> is routed to Synapse, so is
  1631. generally not suitable if Synapse is hosted at a subdomain such as
  1632. <code>https://synapse.example.com</code>.</p>
  1633. <h2 id="srv-dns-record-delegation"><a class="header" href="#srv-dns-record-delegation">SRV DNS record delegation</a></h2>
  1634. <p>It is also possible to do delegation using a SRV DNS record. However, that is generally
  1635. not recommended, as it can be difficult to configure the TLS certificates correctly in
  1636. this case, and it offers little advantage over <code>.well-known</code> delegation.</p>
  1637. <p>Please keep in mind that server delegation is a function of server-server communication,
  1638. and as such using SRV DNS records will not cover use cases involving client-server comms.
  1639. This means setting global client settings (such as a Jitsi endpoint, or disabling
  1640. creating new rooms as encrypted by default, etc) will still require that you serve a file
  1641. from the <code>https://&lt;server_name&gt;/.well-known/</code> endpoints defined in the spec! If you are
  1642. considering using SRV DNS delegation to avoid serving files from this endpoint, consider
  1643. the impact that you will not be able to change those client-based default values globally,
  1644. and will be relegated to the featureset of the configuration of each individual client.</p>
  1645. <p>However, if you really need it, you can find some documentation on what such a
  1646. 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
  1647. specification</a>.</p>
  1648. <h2 id="delegation-faq"><a class="header" href="#delegation-faq">Delegation FAQ</a></h2>
  1649. <h3 id="when-do-i-need-delegation"><a class="header" href="#when-do-i-need-delegation">When do I need delegation?</a></h3>
  1650. <p>If your homeserver's APIs are accessible on the default federation port (8448)
  1651. and the domain your <code>server_name</code> points to, you do not need any delegation.</p>
  1652. <p>For instance, if you registered <code>example.com</code> and pointed its DNS A record at a
  1653. fresh server, you could install Synapse on that host, giving it a <code>server_name</code>
  1654. of <code>example.com</code>, and once a reverse proxy has been set up to proxy all requests
  1655. sent to the port <code>8448</code> and serve TLS certificates for <code>example.com</code>, you
  1656. wouldn't need any delegation set up.</p>
  1657. <p><strong>However</strong>, if your homeserver's APIs aren't accessible on port 8448 and on the
  1658. domain <code>server_name</code> points to, you will need to let other servers know how to
  1659. find it using delegation.</p>
  1660. <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>
  1661. <p>Generally, using a reverse proxy for both the federation and client traffic is a good
  1662. idea, since it saves handling TLS traffic in Synapse. See
  1663. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a
  1664. reverse proxy.</p>
  1665. <div style="break-before: page; page-break-before: always;"></div><h1 id="upgrading-synapse"><a class="header" href="#upgrading-synapse">Upgrading Synapse</a></h1>
  1666. <p>Before upgrading check if any special steps are required to upgrade from
  1667. the version you currently have installed to the current version of
  1668. Synapse. The extra instructions that may be required are listed later in
  1669. this document.</p>
  1670. <ul>
  1671. <li>
  1672. <p>Check that your versions of Python and PostgreSQL are still
  1673. supported.</p>
  1674. <p>Synapse follows upstream lifecycles for <a href="https://endoflife.date/python">Python</a> and
  1675. <a href="https://endoflife.date/postgresql">PostgreSQL</a>, and removes support for versions
  1676. which are no longer maintained.</p>
  1677. <p>The website <a href="https://endoflife.date">https://endoflife.date</a> also offers convenient
  1678. summaries.</p>
  1679. </li>
  1680. <li>
  1681. <p>If Synapse was installed using <a href="setup/installation.html#prebuilt-packages">prebuilt packages</a>,
  1682. you will need to follow the normal process for upgrading those packages.</p>
  1683. </li>
  1684. <li>
  1685. <p>If Synapse was installed using pip then upgrade to the latest
  1686. version by running:</p>
  1687. <pre><code class="language-bash">pip install --upgrade matrix-synapse
  1688. </code></pre>
  1689. </li>
  1690. <li>
  1691. <p>If Synapse was installed from source, then:</p>
  1692. <ol>
  1693. <li>
  1694. <p>Obtain the latest version of the source code. Git users can run
  1695. <code>git pull</code> to do this.</p>
  1696. </li>
  1697. <li>
  1698. <p>If you're running Synapse in a virtualenv, make sure to activate it before
  1699. upgrading. For example, if Synapse is installed in a virtualenv in <code>~/synapse/env</code> then
  1700. run:</p>
  1701. <pre><code class="language-bash">source ~/synapse/env/bin/activate
  1702. pip install --upgrade .
  1703. </code></pre>
  1704. <p>Include any relevant extras between square brackets, e.g. <code>pip install --upgrade &quot;.[postgres,oidc]&quot;</code>.</p>
  1705. </li>
  1706. <li>
  1707. <p>If you're using <code>poetry</code> to manage a Synapse installation, run:</p>
  1708. <pre><code class="language-bash">poetry install
  1709. </code></pre>
  1710. <p>Include any relevant extras with <code>--extras</code>, e.g. <code>poetry install --extras postgres --extras oidc</code>.
  1711. It's probably easiest to run <code>poetry install --extras all</code>.</p>
  1712. </li>
  1713. <li>
  1714. <p>Restart Synapse:</p>
  1715. <pre><code class="language-bash">synctl restart
  1716. </code></pre>
  1717. </li>
  1718. </ol>
  1719. </li>
  1720. </ul>
  1721. <p>To check whether your update was successful, you can check the running
  1722. server version with:</p>
  1723. <pre><code class="language-bash"># you may need to replace 'localhost:8008' if synapse is not configured
  1724. # to listen on port 8008.
  1725. curl http://localhost:8008/_synapse/admin/v1/server_version
  1726. </code></pre>
  1727. <h2 id="rolling-back-to-older-versions"><a class="header" href="#rolling-back-to-older-versions">Rolling back to older versions</a></h2>
  1728. <p>Rolling back to previous releases can be difficult, due to database
  1729. schema changes between releases. Where we have been able to test the
  1730. rollback process, this will be noted below.</p>
  1731. <p>In general, you will need to undo any changes made during the upgrade
  1732. process, for example:</p>
  1733. <ul>
  1734. <li>
  1735. <p>pip:</p>
  1736. <pre><code class="language-bash">source env/bin/activate
  1737. # replace `1.3.0` accordingly:
  1738. pip install matrix-synapse==1.3.0
  1739. </code></pre>
  1740. </li>
  1741. <li>
  1742. <p>Debian:</p>
  1743. <pre><code class="language-bash"># replace `1.3.0` and `stretch` accordingly:
  1744. wget https://packages.matrix.org/debian/pool/main/m/matrix-synapse-py3/matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1745. dpkg -i matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1746. </code></pre>
  1747. </li>
  1748. </ul>
  1749. <h1 id="upgrading-to-v1930"><a class="header" href="#upgrading-to-v1930">Upgrading to v1.93.0</a></h1>
  1750. <h2 id="minimum-supported-rust-version"><a class="header" href="#minimum-supported-rust-version">Minimum supported Rust version</a></h2>
  1751. <p>The minimum supported Rust version has been increased from v1.60.0 to v1.61.0.
  1752. Users building from source will need to ensure their <code>rustc</code> version is up to
  1753. date.</p>
  1754. <h1 id="upgrading-to-v1900"><a class="header" href="#upgrading-to-v1900">Upgrading to v1.90.0</a></h1>
  1755. <h2 id="app-service-query-parameter-authorization-is-now-a-configuration-option"><a class="header" href="#app-service-query-parameter-authorization-is-now-a-configuration-option">App service query parameter authorization is now a configuration option</a></h2>
  1756. <p>Synapse v1.81.0 deprecated application service authorization via query parameters as this is
  1757. considered insecure - and from Synapse v1.71.0 forwards the application service token has also been sent via
  1758. <a href="https://spec.matrix.org/v1.6/application-service-api/#authorization">the <code>Authorization</code> header</a>], making the insecure
  1759. query parameter authorization redundant. Since removing the ability to continue to use query parameters could break
  1760. backwards compatibility it has now been put behind a configuration option, <code>use_appservice_legacy_authorization</code>.<br />
  1761. This option defaults to false, but can be activated by adding </p>
  1762. <pre><code class="language-yaml">use_appservice_legacy_authorization: true
  1763. </code></pre>
  1764. <p>to your configuration.</p>
  1765. <h1 id="upgrading-to-v1890"><a class="header" href="#upgrading-to-v1890">Upgrading to v1.89.0</a></h1>
  1766. <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>
  1767. <p>Application services can no longer call <code>/register</code> with a <code>user</code> property to create new users.
  1768. The standard <code>username</code> property should be used instead. See the
  1769. <a href="https://spec.matrix.org/v1.7/application-service-api/#server-admin-style-permissions">Application Service specification</a>
  1770. for more information.</p>
  1771. <h1 id="upgrading-to-v1880"><a class="header" href="#upgrading-to-v1880">Upgrading to v1.88.0</a></h1>
  1772. <h2 id="minimum-supported-python-version"><a class="header" href="#minimum-supported-python-version">Minimum supported Python version</a></h2>
  1773. <p>The minimum supported Python version has been increased from v3.7 to v3.8.
  1774. You will need Python 3.8 to run Synapse v1.88.0 (due out July 18th, 2023).</p>
  1775. <p>If you use current versions of the Matrix.org-distributed Debian
  1776. packages or Docker images, no action is required.</p>
  1777. <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>
  1778. <p>As mentioned previously in <a href="upgrade.html#upgrading-to-v1840">Upgrading to v1.84.0</a>, the following deprecated settings
  1779. are being removed in this release of Synapse:</p>
  1780. <ul>
  1781. <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>
  1782. <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>
  1783. <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>
  1784. </ul>
  1785. <p>Please ensure that you have migrated to using <code>main</code> on your shared configuration's <code>instance_map</code>
  1786. (or create one if necessary). This is required if you have <em><strong>any</strong></em> workers at all;
  1787. administrators of single-process (monolith) installations don't need to do anything.</p>
  1788. <p>For an illustrative example, please see <a href="upgrade.html#upgrading-to-v1840">Upgrading to v1.84.0</a> below.</p>
  1789. <h1 id="upgrading-to-v1860"><a class="header" href="#upgrading-to-v1860">Upgrading to v1.86.0</a></h1>
  1790. <h2 id="minimum-supported-rust-version-1"><a class="header" href="#minimum-supported-rust-version-1">Minimum supported Rust version</a></h2>
  1791. <p>The minimum supported Rust version has been increased from v1.58.1 to v1.60.0.
  1792. Users building from source will need to ensure their <code>rustc</code> version is up to
  1793. date.</p>
  1794. <h1 id="upgrading-to-v1850"><a class="header" href="#upgrading-to-v1850">Upgrading to v1.85.0</a></h1>
  1795. <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>
  1796. <p>Application services should ensure they call the <code>/register</code> endpoint with a
  1797. <code>username</code> property. The legacy <code>user</code> property is considered deprecated and
  1798. should no longer be included.</p>
  1799. <p>A future version of Synapse (v1.88.0 or later) will remove support for legacy
  1800. application service login.</p>
  1801. <h1 id="upgrading-to-v1840"><a class="header" href="#upgrading-to-v1840">Upgrading to v1.84.0</a></h1>
  1802. <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>
  1803. <p>When using workers,</p>
  1804. <ul>
  1805. <li><code>worker_replication_host</code></li>
  1806. <li><code>worker_replication_http_port</code></li>
  1807. <li><code>worker_replication_http_tls</code></li>
  1808. </ul>
  1809. <p>should now be removed from individual worker YAML configurations and the main process should instead be added to the <code>instance_map</code>
  1810. in the shared YAML configuration, using the name <code>main</code>.</p>
  1811. <p>The old <code>worker_replication_*</code> settings are now considered deprecated and are expected to be removed in Synapse v1.88.0.</p>
  1812. <h3 id="example-change"><a class="header" href="#example-change">Example change</a></h3>
  1813. <h4 id="before"><a class="header" href="#before">Before:</a></h4>
  1814. <p>Shared YAML</p>
  1815. <pre><code class="language-yaml">instance_map:
  1816. generic_worker1:
  1817. host: localhost
  1818. port: 5678
  1819. tls: false
  1820. </code></pre>
  1821. <p>Worker YAML</p>
  1822. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  1823. worker_name: generic_worker1
  1824. worker_replication_host: localhost
  1825. worker_replication_http_port: 3456
  1826. worker_replication_http_tls: false
  1827. worker_listeners:
  1828. - type: http
  1829. port: 1234
  1830. resources:
  1831. - names: [client, federation]
  1832. - type: http
  1833. port: 5678
  1834. resources:
  1835. - names: [replication]
  1836. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  1837. </code></pre>
  1838. <h4 id="after"><a class="header" href="#after">After:</a></h4>
  1839. <p>Shared YAML</p>
  1840. <pre><code class="language-yaml">instance_map:
  1841. main:
  1842. host: localhost
  1843. port: 3456
  1844. tls: false
  1845. generic_worker1:
  1846. host: localhost
  1847. port: 5678
  1848. tls: false
  1849. </code></pre>
  1850. <p>Worker YAML</p>
  1851. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  1852. worker_name: generic_worker1
  1853. worker_listeners:
  1854. - type: http
  1855. port: 1234
  1856. resources:
  1857. - names: [client, federation]
  1858. - type: http
  1859. port: 5678
  1860. resources:
  1861. - names: [replication]
  1862. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  1863. </code></pre>
  1864. <p>Notes: </p>
  1865. <ul>
  1866. <li><code>tls</code> is optional but mirrors the functionality of <code>worker_replication_http_tls</code></li>
  1867. </ul>
  1868. <h1 id="upgrading-to-v1810"><a class="header" href="#upgrading-to-v1810">Upgrading to v1.81.0</a></h1>
  1869. <h2 id="application-service-path--authentication-deprecations"><a class="header" href="#application-service-path--authentication-deprecations">Application service path &amp; authentication deprecations</a></h2>
  1870. <p>Synapse now attempts the versioned appservice paths before falling back to the
  1871. <a href="https://spec.matrix.org/v1.6/application-service-api/#legacy-routes">legacy paths</a>.
  1872. Usage of the legacy routes should be considered deprecated.</p>
  1873. <p>Additionally, Synapse has supported sending the application service access token
  1874. via <a href="https://spec.matrix.org/v1.6/application-service-api/#authorization">the <code>Authorization</code> header</a>
  1875. since v1.70.0. For backwards compatibility it is <em>also</em> sent as the <code>access_token</code>
  1876. query parameter. This is insecure and should be considered deprecated.</p>
  1877. <p>A future version of Synapse (v1.88.0 or later) will remove support for legacy
  1878. application service routes and query parameter authorization.</p>
  1879. <h1 id="upgrading-to-v1800"><a class="header" href="#upgrading-to-v1800">Upgrading to v1.80.0</a></h1>
  1880. <h2 id="reporting-events-error-code-change"><a class="header" href="#reporting-events-error-code-change">Reporting events error code change</a></h2>
  1881. <p>Before this update, the
  1882. <a href="https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3roomsroomidreporteventid"><code>POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}</code></a>
  1883. endpoint would return a <code>403</code> if a user attempted to report an event that they did not have access to.
  1884. This endpoint will now return a <code>404</code> in this case instead.</p>
  1885. <p>Clients that implement event reporting should check that their error handling code will handle this
  1886. change.</p>
  1887. <h1 id="upgrading-to-v1790"><a class="header" href="#upgrading-to-v1790">Upgrading to v1.79.0</a></h1>
  1888. <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>
  1889. <p>Synapse v1.79.0 deprecates the
  1890. <a href="modules/third_party_rules_callbacks.html#on_threepid_bind"><code>on_threepid_bind</code></a>
  1891. &quot;third-party rules&quot; Synapse module callback method in favour of a new module method,
  1892. <a href="modules/third_party_rules_callbacks.html#on_add_user_third_party_identifier"><code>on_add_user_third_party_identifier</code></a>.
  1893. <code>on_threepid_bind</code> will be removed in a future version of Synapse. You should check whether any Synapse
  1894. modules in use in your deployment are making use of <code>on_threepid_bind</code>, and update them where possible.</p>
  1895. <p>The arguments and functionality of the new method are the same.</p>
  1896. <p>The justification behind the name change is that the old method's name, <code>on_threepid_bind</code>, was
  1897. misleading. A user is considered to &quot;bind&quot; their third-party ID to their Matrix ID only if they
  1898. do so via an <a href="https://spec.matrix.org/latest/identity-service-api/">identity server</a>
  1899. (so that users on other homeservers may find them). But this method was not called in that case -
  1900. it was only called when a user added a third-party identifier on the local homeserver.</p>
  1901. <p>Module developers may also be interested in the related
  1902. <a href="modules/third_party_rules_callbacks.html#on_remove_user_third_party_identifier"><code>on_remove_user_third_party_identifier</code></a>
  1903. module callback method that was also added in Synapse v1.79.0. This new method is called when a
  1904. user removes a third-party identifier from their account.</p>
  1905. <h1 id="upgrading-to-v1780"><a class="header" href="#upgrading-to-v1780">Upgrading to v1.78.0</a></h1>
  1906. <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>
  1907. <p>Synapse 1.78.0 replaces the <code>/_synapse/admin/v1/media/&lt;server_name&gt;/delete</code>
  1908. admin API with an identical endpoint at <code>/_synapse/admin/v1/media/delete</code>. Please
  1909. update your tooling to use the new endpoint. The deprecated version will be removed
  1910. in a future release.</p>
  1911. <h1 id="upgrading-to-v1760"><a class="header" href="#upgrading-to-v1760">Upgrading to v1.76.0</a></h1>
  1912. <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>
  1913. <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>
  1914. <p>Server admins can opt out of this feature for the time being by setting</p>
  1915. <pre><code class="language-yaml">experimental:
  1916. faster_joins: false
  1917. </code></pre>
  1918. <p>in their server config.</p>
  1919. <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>
  1920. <p>Synapse has changed the format of the account data and devices replication
  1921. streams (between workers). This is a forwards- and backwards-incompatible
  1922. change: v1.75 workers cannot process account data replicated by v1.76 workers,
  1923. and vice versa.</p>
  1924. <p>Once all workers are upgraded to v1.76 (or downgraded to v1.75), account data
  1925. and device replication will resume as normal.</p>
  1926. <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>
  1927. <p>The minimum supported version of Poetry is now 1.3.2 (previously 1.2.0, <a href="upgrade.html#upgrading-to-v1670">since
  1928. Synapse 1.67</a>). If you have used <code>poetry install</code> to
  1929. install Synapse from a source checkout, you should upgrade poetry: see its
  1930. <a href="https://python-poetry.org/docs/#installation">installation instructions</a>.
  1931. For all other installation methods, no acction is required.</p>
  1932. <h1 id="upgrading-to-v1740"><a class="header" href="#upgrading-to-v1740">Upgrading to v1.74.0</a></h1>
  1933. <h2 id="unicode-support-in-user-search"><a class="header" href="#unicode-support-in-user-search">Unicode support in user search</a></h2>
  1934. <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>
  1935. <p>If you want to take advantage of this feature you need to install PyICU,
  1936. the ICU native dependency and its development headers
  1937. so that PyICU can build since no prebuilt wheels are available.</p>
  1938. <p>You can follow <a href="https://pypi.org/project/PyICU/">the PyICU documentation</a> to do so,
  1939. and then do <code>pip install matrix-synapse[user-search]</code> for a PyPI install.</p>
  1940. <p>Docker images and Debian packages need nothing specific as they already
  1941. include or specify ICU as an explicit dependency.</p>
  1942. <h2 id="user-directory-rebuild"><a class="header" href="#user-directory-rebuild">User directory rebuild</a></h2>
  1943. <p>Synapse 1.74 queues a background update
  1944. <a href="https://github.com/matrix-org/synapse/pull/14643">to rebuild the user directory</a>,
  1945. in order to fix missing or erroneous entries.</p>
  1946. <p>When this update begins, the user directory will be cleared out and rebuilt from
  1947. scratch. User directory lookups will be incomplete until the rebuild completes.
  1948. Admins can monitor the rebuild's progress by using the
  1949. <a href="usage/administration/admin_api/background_updates.html#status">Background update Admin API</a>.</p>
  1950. <h1 id="upgrading-to-v1730"><a class="header" href="#upgrading-to-v1730">Upgrading to v1.73.0</a></h1>
  1951. <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>
  1952. <p>Synapse v1.69.0 included the deprecation of legacy Prometheus metric names
  1953. and offered an option to disable them.
  1954. Synapse v1.71.0 disabled legacy Prometheus metric names by default.</p>
  1955. <p>This version, v1.73.0, removes those legacy Prometheus metric names entirely.
  1956. This also means that the <code>enable_legacy_metrics</code> configuration option has been
  1957. removed; it will no longer be possible to re-enable the legacy metric names.</p>
  1958. <p>If you use metrics and have not yet updated your Grafana dashboard(s),
  1959. Prometheus console(s) or alerting rule(s), please consider doing so when upgrading
  1960. to this version.
  1961. Note that the included Grafana dashboard was updated in v1.72.0 to correct some
  1962. metric names which were missed when legacy metrics were disabled by default.</p>
  1963. <p>See <a href="upgrade.html#deprecation-of-legacy-prometheus-metric-names">v1.69.0: Deprecation of legacy Prometheus metric names</a>
  1964. for more context.</p>
  1965. <h1 id="upgrading-to-v1720"><a class="header" href="#upgrading-to-v1720">Upgrading to v1.72.0</a></h1>
  1966. <h2 id="dropping-support-for-postgresql-10"><a class="header" href="#dropping-support-for-postgresql-10">Dropping support for PostgreSQL 10</a></h2>
  1967. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>, we've dropped
  1968. support for PostgreSQL 10, as it is no longer supported upstream.</p>
  1969. <p>This release of Synapse requires PostgreSQL 11+.</p>
  1970. <h1 id="upgrading-to-v1710"><a class="header" href="#upgrading-to-v1710">Upgrading to v1.71.0</a></h1>
  1971. <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>
  1972. <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>
  1973. <p>Modules relying on it can instead use the <code>create_login_token</code> method.</p>
  1974. <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>
  1975. <p>To align with spec (changed in
  1976. <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3905">MSC3905</a>), Synapse now
  1977. only considers local users to be interesting. In other words, the <code>users</code> namespace
  1978. regex is only be applied against local users of the homeserver.</p>
  1979. <p>Please note, this probably doesn't affect the expected behavior of your application
  1980. service, since an interesting local user in a room still means all messages in the room
  1981. (from local or remote users) will still be considered interesting. And matching a room
  1982. with the <code>rooms</code> or <code>aliases</code> namespace regex will still consider all events sent in the
  1983. room to be interesting to the application service.</p>
  1984. <p>If one of your application service's <code>users</code> regex was intending to match a remote user,
  1985. this will no longer match as you expect. The behavioral mismatch between matching all
  1986. local users and some remote users is why the spec was changed/clarified and this
  1987. caveat is no longer supported.</p>
  1988. <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>
  1989. <p>Synapse v1.71.0 disables legacy Prometheus metric names by default.
  1990. For administrators that still rely on them and have not yet had chance to update their
  1991. uses of the metrics, it's still possible to specify <code>enable_legacy_metrics: true</code> in
  1992. the configuration to re-enable them temporarily.</p>
  1993. <p>Synapse v1.73.0 will <strong>remove legacy metric names altogether</strong> and at that point,
  1994. it will no longer be possible to re-enable them.</p>
  1995. <p>If you do not use metrics or you have already updated your Grafana dashboard(s),
  1996. Prometheus console(s) and alerting rule(s), there is no action needed.</p>
  1997. <p>See <a href="upgrade.html#deprecation-of-legacy-prometheus-metric-names">v1.69.0: Deprecation of legacy Prometheus metric names</a>.</p>
  1998. <h1 id="upgrading-to-v1690"><a class="header" href="#upgrading-to-v1690">Upgrading to v1.69.0</a></h1>
  1999. <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>
  2000. <p>Synapse now includes information indicating if a receipt applies to a thread when
  2001. replicating it to other workers. This is a forwards- and backwards-incompatible
  2002. change: v1.68 and workers cannot process receipts replicated by v1.69 workers, and
  2003. vice versa.</p>
  2004. <p>Once all workers are upgraded to v1.69 (or downgraded to v1.68), receipts
  2005. replication will resume as normal.</p>
  2006. <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>
  2007. <p>In current versions of Synapse, some Prometheus metrics are emitted under two different names,
  2008. with one of the names being older but non-compliant with OpenMetrics and Prometheus conventions
  2009. and one of the names being newer but compliant.</p>
  2010. <p>Synapse v1.71.0 will turn the old metric names off <em>by default</em>.
  2011. For administrators that still rely on them and have not had chance to update their
  2012. uses of the metrics, it's possible to specify <code>enable_legacy_metrics: true</code> in
  2013. the configuration to re-enable them temporarily.</p>
  2014. <p>Synapse v1.73.0 will <strong>remove legacy metric names altogether</strong> and it will no longer
  2015. be possible to re-enable them.</p>
  2016. <p>The Grafana dashboard, Prometheus recording rules and Prometheus Consoles included
  2017. in the <code>contrib</code> directory in the Synapse repository have been updated to no longer
  2018. rely on the legacy names. These can be used on a current version of Synapse
  2019. because current versions of Synapse emit both old and new names.</p>
  2020. <p>You may need to update your alerting rules or any other rules that depend on
  2021. the names of Prometheus metrics.
  2022. If you want to test your changes before legacy names are disabled by default,
  2023. you may specify <code>enable_legacy_metrics: false</code> in your homeserver configuration.</p>
  2024. <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>
  2025. <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>
  2026. <p>The following method of the module API has been deprecated, and is scheduled to
  2027. be remove in v1.71.0:</p>
  2028. <pre><code class="language-python">def generate_short_term_login_token(
  2029. self,
  2030. user_id: str,
  2031. duration_in_ms: int = (2 * 60 * 1000),
  2032. auth_provider_id: str = &quot;&quot;,
  2033. auth_provider_session_id: Optional[str] = None,
  2034. ) -&gt; str:
  2035. ...
  2036. </code></pre>
  2037. <p>It has been replaced by an asynchronous equivalent:</p>
  2038. <pre><code class="language-python">async def create_login_token(
  2039. self,
  2040. user_id: str,
  2041. duration_in_ms: int = (2 * 60 * 1000),
  2042. auth_provider_id: Optional[str] = None,
  2043. auth_provider_session_id: Optional[str] = None,
  2044. ) -&gt; str:
  2045. ...
  2046. </code></pre>
  2047. <p>Synapse will log a warning when a module uses the deprecated method, to help
  2048. administrators find modules using it.</p>
  2049. <h1 id="upgrading-to-v1680"><a class="header" href="#upgrading-to-v1680">Upgrading to v1.68.0</a></h1>
  2050. <p>Two changes announced in the upgrade notes for v1.67.0 have now landed in v1.68.0.</p>
  2051. <h2 id="sqlite-version-requirement"><a class="header" href="#sqlite-version-requirement">SQLite version requirement</a></h2>
  2052. <p>Synapse now requires a SQLite version of 3.27.0 or higher if SQLite is configured as
  2053. Synapse's database.</p>
  2054. <p>Installations using</p>
  2055. <ul>
  2056. <li>Docker images <a href="https://hub.docker.com/r/matrixdotorg/synapse">from <code>matrixdotorg</code></a>,</li>
  2057. <li>Debian packages <a href="https://packages.matrix.org/">from Matrix.org</a>, or</li>
  2058. <li>a PostgreSQL database</li>
  2059. </ul>
  2060. <p>are not affected.</p>
  2061. <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>
  2062. <p>Building from a source checkout of Synapse now requires a recent Rust compiler
  2063. (currently Rust 1.58.1, but see also the
  2064. <a href="https://matrix-org.github.io/synapse/latest/deprecation_policy.html">Platform Dependency Policy</a>).</p>
  2065. <p>Installations using</p>
  2066. <ul>
  2067. <li>Docker images <a href="https://hub.docker.com/r/matrixdotorg/synapse">from <code>matrixdotorg</code></a>,</li>
  2068. <li>Debian packages <a href="https://packages.matrix.org/">from Matrix.org</a>, or</li>
  2069. <li>PyPI wheels via <code>pip install matrix-synapse</code> (on supported platforms and architectures)</li>
  2070. </ul>
  2071. <p>will not be affected.</p>
  2072. <h1 id="upgrading-to-v1670"><a class="header" href="#upgrading-to-v1670">Upgrading to v1.67.0</a></h1>
  2073. <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>
  2074. <p>Redis support was added in v1.13.0 with it becoming the recommended method in
  2075. v1.18.0. It replaced the old direct TCP connections (which was deprecated as of
  2076. v1.18.0) to the main process. With Redis, rather than all the workers connecting
  2077. to the main process, all the workers and the main process connect to Redis,
  2078. which relays replication commands between processes. This can give a significant
  2079. CPU saving on the main process and is a prerequisite for upcoming
  2080. performance improvements.</p>
  2081. <p>To migrate to Redis add the <a href="./workers.html#shared-configuration"><code>redis</code> config</a>,
  2082. and remove the TCP <code>replication</code> listener from config of the master and
  2083. <code>worker_replication_port</code> from worker config. Note that a HTTP listener with a
  2084. <code>replication</code> resource is still required.</p>
  2085. <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>
  2086. <p>The minimum supported version of poetry is now 1.2. This should only affect
  2087. those installing from a source checkout.</p>
  2088. <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>
  2089. <p>From the next major release (v1.68.0) installing Synapse from a source checkout
  2090. will require a recent Rust compiler. Those using packages or
  2091. <code>pip install matrix-synapse</code> will not be affected.</p>
  2092. <p>The simplest way of installing Rust is via <a href="https://rustup.rs/">rustup.rs</a></p>
  2093. <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>
  2094. <p>From the next major release (v1.68.0) Synapse will require SQLite 3.27.0 or
  2095. higher. Synapse v1.67.0 will be the last major release supporting SQLite
  2096. versions 3.22 to 3.26.</p>
  2097. <p>Those using Docker images or Debian packages from Matrix.org will not be
  2098. affected. If you have installed from source, you should check the version of
  2099. SQLite used by Python with:</p>
  2100. <pre><code class="language-shell">python -c &quot;import sqlite3; print(sqlite3.sqlite_version)&quot;
  2101. </code></pre>
  2102. <p>If this is too old, refer to your distribution for advice on upgrading.</p>
  2103. <h1 id="upgrading-to-v1660"><a class="header" href="#upgrading-to-v1660">Upgrading to v1.66.0</a></h1>
  2104. <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>
  2105. <p>As of this version, Synapse no longer allows the tasks of verifying email address
  2106. ownership, and password reset confirmation, to be delegated to an identity server.
  2107. This removal was previously planned for Synapse 1.64.0, but was
  2108. <a href="https://github.com/matrix-org/synapse/issues/13421">delayed</a> until now to give
  2109. homeserver administrators more notice of the change.</p>
  2110. <p>To continue to allow users to add email addresses to their homeserver accounts,
  2111. and perform password resets, make sure that Synapse is configured with a working
  2112. email server in the <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#email"><code>email</code> configuration
  2113. section</a>
  2114. (including, at a minimum, a <code>notif_from</code> setting.)</p>
  2115. <p>Specifying an <code>email</code> setting under <code>account_threepid_delegates</code> will now cause
  2116. an error at startup.</p>
  2117. <h1 id="upgrading-to-v1640"><a class="header" href="#upgrading-to-v1640">Upgrading to v1.64.0</a></h1>
  2118. <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>
  2119. <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>
  2120. <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.
  2121. <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#email">Consult the configuration documentation for more information.</a></p>
  2122. <p>The option that will be removed is <code>account_threepid_delegates.email</code>.</p>
  2123. <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>
  2124. <p>Synapse now includes a flag indicating if an event is an outlier when
  2125. replicating it to other workers. This is a forwards- and backwards-incompatible
  2126. change: v1.63 and workers cannot process events replicated by v1.64 workers, and
  2127. vice versa.</p>
  2128. <p>Once all workers are upgraded to v1.64 (or downgraded to v1.63), event
  2129. replication will resume as normal.</p>
  2130. <h2 id="frozendict-release"><a class="header" href="#frozendict-release">frozendict release</a></h2>
  2131. <p><a href="https://github.com/Marco-Sulla/python-frozendict/releases/tag/v2.3.3">frozendict 2.3.3</a>
  2132. has recently been released, which fixes a memory leak that occurs during <code>/sync</code>
  2133. requests. We advise server administrators who installed Synapse via pip to upgrade
  2134. frozendict with <code>pip install --upgrade frozendict</code>. The Docker image
  2135. <code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> already
  2136. include the updated library.</p>
  2137. <h1 id="upgrading-to-v1620"><a class="header" href="#upgrading-to-v1620">Upgrading to v1.62.0</a></h1>
  2138. <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>
  2139. <p>As a followup to changes in v1.60.0, the following spam-checker callbacks have changed signature:</p>
  2140. <ul>
  2141. <li><code>user_may_join_room</code></li>
  2142. <li><code>user_may_invite</code></li>
  2143. <li><code>user_may_send_3pid_invite</code></li>
  2144. <li><code>user_may_create_room</code></li>
  2145. <li><code>user_may_create_room_alias</code></li>
  2146. <li><code>user_may_publish_room</code></li>
  2147. <li><code>check_media_file_for_spam</code></li>
  2148. </ul>
  2149. <p>For each of these methods, the previous callback signature has been deprecated.</p>
  2150. <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>
  2151. <p>For instance, if your module implements <code>user_may_join_room</code> as follows:</p>
  2152. <pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
  2153. if ...:
  2154. # Request is spam
  2155. return False
  2156. # Request is not spam
  2157. return True
  2158. </code></pre>
  2159. <p>you should rewrite it as follows:</p>
  2160. <pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
  2161. if ...:
  2162. # Request is spam, mark it as forbidden (you may use some more precise error
  2163. # code if it is useful).
  2164. return synapse.module_api.errors.Codes.FORBIDDEN
  2165. # Request is not spam, mark it as such.
  2166. return synapse.module_api.NOT_SPAM
  2167. </code></pre>
  2168. <h1 id="upgrading-to-v1610"><a class="header" href="#upgrading-to-v1610">Upgrading to v1.61.0</a></h1>
  2169. <h2 id="removal-of-deprecated-communitygroups"><a class="header" href="#removal-of-deprecated-communitygroups">Removal of deprecated community/groups</a></h2>
  2170. <p>This release of Synapse will remove deprecated community/groups from codebase.</p>
  2171. <h3 id="worker-endpoints"><a class="header" href="#worker-endpoints">Worker endpoints</a></h3>
  2172. <p>For those who have deployed workers, following worker endpoints will no longer
  2173. exist and they can be removed from the reverse proxy configuration:</p>
  2174. <ul>
  2175. <li><code>^/_matrix/federation/v1/get_groups_publicised$</code></li>
  2176. <li><code>^/_matrix/client/(r0|v3|unstable)/joined_groups$</code></li>
  2177. <li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups$</code></li>
  2178. <li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups/</code></li>
  2179. <li><code>^/_matrix/federation/v1/groups/</code></li>
  2180. <li><code>^/_matrix/client/(r0|v3|unstable)/groups/</code></li>
  2181. </ul>
  2182. <h1 id="upgrading-to-v1600"><a class="header" href="#upgrading-to-v1600">Upgrading to v1.60.0</a></h1>
  2183. <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>
  2184. <p>This release of Synapse will add a unique index to the <code>state_group_edges</code> table, in order
  2185. to prevent accidentally introducing duplicate information (for example, because a database
  2186. backup was restored multiple times).</p>
  2187. <p>Duplicate rows being present in this table could cause drastic performance problems; see
  2188. <a href="https://github.com/matrix-org/synapse/issues/11779">issue 11779</a> for more details.</p>
  2189. <p>If your Synapse database already has had duplicate rows introduced into this table,
  2190. this could fail, with either of these errors:</p>
  2191. <p><strong>On Postgres:</strong></p>
  2192. <pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
  2193. synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
  2194. ...
  2195. psycopg2.errors.UniqueViolation: could not create unique index &quot;state_group_edges_unique_idx&quot;
  2196. DETAIL: Key (state_group, prev_state_group)=(2, 1) is duplicated.
  2197. </code></pre>
  2198. <p>(The numbers may be different.)</p>
  2199. <p><strong>On SQLite:</strong></p>
  2200. <pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
  2201. synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
  2202. ...
  2203. sqlite3.IntegrityError: UNIQUE constraint failed: state_group_edges.state_group, state_group_edges.prev_state_group
  2204. </code></pre>
  2205. <details>
  2206. <summary><b>Expand this section for steps to resolve this problem</b></summary>
  2207. <h3 id="on-postgres"><a class="header" href="#on-postgres">On Postgres</a></h3>
  2208. <p>Connect to your database with <code>psql</code>.</p>
  2209. <pre><code class="language-sql">BEGIN;
  2210. DELETE FROM state_group_edges WHERE (ctid, state_group, prev_state_group) IN (
  2211. SELECT row_id, state_group, prev_state_group
  2212. FROM (
  2213. SELECT
  2214. ctid AS row_id,
  2215. MIN(ctid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
  2216. state_group,
  2217. prev_state_group
  2218. FROM state_group_edges
  2219. ) AS t1
  2220. WHERE row_id &lt;&gt; min_row_id
  2221. );
  2222. COMMIT;
  2223. </code></pre>
  2224. <h3 id="on-sqlite"><a class="header" href="#on-sqlite">On SQLite</a></h3>
  2225. <p>At the command-line, use <code>sqlite3 path/to/your-homeserver-database.db</code>:</p>
  2226. <pre><code class="language-sql">BEGIN;
  2227. DELETE FROM state_group_edges WHERE (rowid, state_group, prev_state_group) IN (
  2228. SELECT row_id, state_group, prev_state_group
  2229. FROM (
  2230. SELECT
  2231. rowid AS row_id,
  2232. MIN(rowid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
  2233. state_group,
  2234. prev_state_group
  2235. FROM state_group_edges
  2236. )
  2237. WHERE row_id &lt;&gt; min_row_id
  2238. );
  2239. COMMIT;
  2240. </code></pre>
  2241. <h3 id="for-more-details"><a class="header" href="#for-more-details">For more details</a></h3>
  2242. <p><a href="https://github.com/matrix-org/synapse/issues/11779#issuecomment-1131545970">This comment on issue 11779</a>
  2243. has queries that can be used to check a database for this problem in advance.</p>
  2244. </details>
  2245. <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>
  2246. <p>The previous signature has been deprecated.</p>
  2247. <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>
  2248. <p>This is part of an ongoing refactoring of the SpamChecker API to make it less ambiguous and more powerful.</p>
  2249. <p>If your module implements <code>check_event_for_spam</code> as follows:</p>
  2250. <pre><code class="language-python">async def check_event_for_spam(event):
  2251. if ...:
  2252. # Event is spam
  2253. return True
  2254. # Event is not spam
  2255. return False
  2256. </code></pre>
  2257. <p>you should rewrite it as follows:</p>
  2258. <pre><code class="language-python">async def check_event_for_spam(event):
  2259. if ...:
  2260. # Event is spam, mark it as forbidden (you may use some more precise error
  2261. # code if it is useful).
  2262. return synapse.module_api.errors.Codes.FORBIDDEN
  2263. # Event is not spam, mark it as such.
  2264. return synapse.module_api.NOT_SPAM
  2265. </code></pre>
  2266. <h1 id="upgrading-to-v1590"><a class="header" href="#upgrading-to-v1590">Upgrading to v1.59.0</a></h1>
  2267. <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>
  2268. <p>The names of user devices are no longer visible to users on other homeservers by default.
  2269. Device IDs are unaffected, as these are necessary to facilitate end-to-end encryption.</p>
  2270. <p>To re-enable this functionality, set the
  2271. <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>
  2272. homeserver config option to <code>true</code>.</p>
  2273. <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>
  2274. <p>The <code>synapse.app.appservice</code> worker application type allowed you to configure a
  2275. single worker to use to notify application services of new events, as long
  2276. as this functionality was disabled on the main process with <code>notify_appservices: False</code>.
  2277. Further, the <code>synapse.app.user_dir</code> worker application type allowed you to configure
  2278. a single worker to be responsible for updating the user directory, as long as this
  2279. was disabled on the main process with <code>update_user_directory: False</code>.</p>
  2280. <p>To unify Synapse's worker types, the <code>synapse.app.appservice</code> worker application
  2281. type and the <code>notify_appservices</code> configuration option have been deprecated.
  2282. The <code>synapse.app.user_dir</code> worker application type and <code>update_user_directory</code>
  2283. configuration option have also been deprecated.</p>
  2284. <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>
  2285. worker application type is used and that the <code>notify_appservices_from_worker</code> and/or
  2286. <code>update_user_directory_from_worker</code> options are set to the name of a worker.</p>
  2287. <p>For the time being, the old options can be used alongside the new options to make
  2288. it easier to transition between the two configurations, however please note that:</p>
  2289. <ul>
  2290. <li>the options must not contradict each other (otherwise Synapse won't start); and</li>
  2291. <li>the <code>notify_appservices</code> and <code>update_user_directory</code> options will be removed in a future release of Synapse.</li>
  2292. </ul>
  2293. <p>Please see the <a href="workers.html#notifying-application-services"><em>Notifying Application Services</em></a> and
  2294. <a href="workers.html#updating-the-user-directory"><em>Updating the User Directory</em></a> sections of the worker
  2295. documentation for more information.</p>
  2296. <h1 id="upgrading-to-v1580"><a class="header" href="#upgrading-to-v1580">Upgrading to v1.58.0</a></h1>
  2297. <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>
  2298. <p>The non-standard groups/communities feature in Synapse has been disabled by default
  2299. and will be removed in Synapse v1.61.0.</p>
  2300. <h1 id="upgrading-to-v1570"><a class="header" href="#upgrading-to-v1570">Upgrading to v1.57.0</a></h1>
  2301. <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>
  2302. <p>Synapse v1.57.0 includes a <a href="https://github.com/matrix-org/synapse/pull/12209">change</a> to the
  2303. way transaction IDs are managed for application services. If your deployment uses a dedicated
  2304. worker for application service traffic, <strong>it must be stopped</strong> when the database is upgraded
  2305. (which normally happens when the main process is upgraded), to ensure the change is made safely
  2306. without any risk of reusing transaction IDs.</p>
  2307. <p>Deployments which do not use separate worker processes can be upgraded as normal. Similarly,
  2308. deployments where no application services are in use can be upgraded as normal.</p>
  2309. <details>
  2310. <summary><b>Recovering from an incorrect upgrade</b></summary>
  2311. <p>If the database schema is upgraded <em>without</em> stopping the worker responsible
  2312. for AS traffic, then the following error may be given when attempting to start
  2313. a Synapse worker or master process:</p>
  2314. <pre><code>**********************************************************************************
  2315. Error during initialisation:
  2316. Postgres sequence 'application_services_txn_id_seq' is inconsistent with associated
  2317. table 'application_services_txns'. This can happen if Synapse has been downgraded and
  2318. then upgraded again, or due to a bad migration.
  2319. To fix this error, shut down Synapse (including any and all workers)
  2320. and run the following SQL:
  2321. SELECT setval('application_services_txn_id_seq', (
  2322. SELECT GREATEST(MAX(txn_id), 0) FROM application_services_txns
  2323. ));
  2324. See docs/postgres.md for more information.
  2325. There may be more information in the logs.
  2326. **********************************************************************************
  2327. </code></pre>
  2328. <p>This error may also be seen if Synapse is <em>downgraded</em> to an earlier version,
  2329. and then upgraded again to v1.57.0 or later.</p>
  2330. <p>In either case:</p>
  2331. <ol>
  2332. <li>Ensure that the worker responsible for AS traffic is stopped.</li>
  2333. <li>Run the SQL command given in the error message via <code>psql</code>.</li>
  2334. </ol>
  2335. <p>Synapse should then start correctly.</p>
  2336. </details>
  2337. <h1 id="upgrading-to-v1560"><a class="header" href="#upgrading-to-v1560">Upgrading to v1.56.0</a></h1>
  2338. <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>
  2339. <p>Synapse will refuse to start if registration is enabled without email, captcha, or token-based verification unless the new config
  2340. flag <code>enable_registration_without_verification</code> is set to &quot;true&quot;.</p>
  2341. <h2 id="groupscommunities-feature-has-been-deprecated"><a class="header" href="#groupscommunities-feature-has-been-deprecated">Groups/communities feature has been deprecated</a></h2>
  2342. <p>The non-standard groups/communities feature in Synapse has been deprecated and will
  2343. be disabled by default in Synapse v1.58.0.</p>
  2344. <p>You can test disabling it by adding the following to your homeserver configuration:</p>
  2345. <pre><code class="language-yaml">experimental_features:
  2346. groups_enabled: false
  2347. </code></pre>
  2348. <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>
  2349. <p>Synapse now refuses to start when using PostgreSQL with non-<code>C</code> values for <code>COLLATE</code> and
  2350. <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the database section of
  2351. 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>
  2352. for more information and instructions on how to fix a database with incorrect values.</p>
  2353. <h1 id="upgrading-to-v1550"><a class="header" href="#upgrading-to-v1550">Upgrading to v1.55.0</a></h1>
  2354. <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>
  2355. <p>The <code>synctl</code> script
  2356. <a href="https://github.com/matrix-org/synapse/pull/12140">has been made</a> an
  2357. <a href="https://packaging.python.org/en/latest/specifications/entry-points/">entry point</a>
  2358. and no longer exists at the root of Synapse's source tree. If you wish to use
  2359. <code>synctl</code> to manage your homeserver, you should invoke <code>synctl</code> directly, e.g.
  2360. <code>synctl start</code> instead of <code>./synctl start</code> or <code>/path/to/synctl start</code>.</p>
  2361. <p>You will need to ensure <code>synctl</code> is on your <code>PATH</code>.</p>
  2362. <ul>
  2363. <li>This is automatically the case when using
  2364. <a href="https://packages.matrix.org/debian/">Debian packages</a> or
  2365. <a href="https://hub.docker.com/r/matrixdotorg/synapse">docker images</a>
  2366. provided by Matrix.org.</li>
  2367. <li>When installing from a wheel, sdist, or PyPI, a <code>synctl</code> executable is added
  2368. to your Python installation's <code>bin</code>. This should be on your <code>PATH</code>
  2369. automatically, though you might need to activate a virtual environment
  2370. depending on how you installed Synapse.</li>
  2371. </ul>
  2372. <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>
  2373. <p>Synapse v1.55.0 drops support for Mjolnir 1.3.1 and earlier.
  2374. If you use the Mjolnir module to moderate your homeserver,
  2375. please upgrade Mjolnir to version 1.3.2 or later before upgrading Synapse.</p>
  2376. <h1 id="upgrading-to-v1540"><a class="header" href="#upgrading-to-v1540">Upgrading to v1.54.0</a></h1>
  2377. <h2 id="legacy-structured-logging-configuration-removal"><a class="header" href="#legacy-structured-logging-configuration-removal">Legacy structured logging configuration removal</a></h2>
  2378. <p>This release removes support for the <code>structured: true</code> logging configuration
  2379. which was deprecated in Synapse v1.23.0. If your logging configuration contains
  2380. <code>structured: true</code> then it should be modified based on the
  2381. <a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
  2382. <h1 id="upgrading-to-v1530"><a class="header" href="#upgrading-to-v1530">Upgrading to v1.53.0</a></h1>
  2383. <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>
  2384. <p>Per the deprecation notice in Synapse v1.51.0, listeners of type <code>webclient</code>
  2385. are no longer supported and configuring them is a now a configuration error.</p>
  2386. <p>Configuring a non-HTTP(S) <code>web_client_location</code> configuration is is now a
  2387. configuration error. Since the <code>webclient</code> listener is no longer supported, this
  2388. setting only applies to the root path <code>/</code> of Synapse's web server and no longer
  2389. the <code>/_matrix/client/</code> path.</p>
  2390. <h2 id="stablisation-of-msc3231"><a class="header" href="#stablisation-of-msc3231">Stablisation of MSC3231</a></h2>
  2391. <p>The unstable validity-check endpoint for the
  2392. <a href="https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv1registermloginregistration_tokenvalidity">Registration Tokens</a>
  2393. feature has been stabilised and moved from:</p>
  2394. <p><code>/_matrix/client/unstable/org.matrix.msc3231/register/org.matrix.msc3231.login.registration_token/validity</code></p>
  2395. <p>to:</p>
  2396. <p><code>/_matrix/client/v1/register/m.login.registration_token/validity</code></p>
  2397. <p>Please update any relevant reverse proxy or firewall configurations appropriately.</p>
  2398. <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>
  2399. <p>Formerly, entries in the cache were not evicted regardless of whether they were accessed after storing.
  2400. This behavior has now changed. By default entries in the cache are now evicted after 30m of not being accessed.
  2401. To change the default behavior, go to the <code>caches</code> section of the config and change the <code>expire_caches</code> and
  2402. <code>cache_entry_ttl</code> flags as necessary. Please note that these flags replace the <code>expiry_time</code> flag in the config.
  2403. The <code>expiry_time</code> flag will still continue to work, but it has been deprecated and will be removed in the future.</p>
  2404. <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>
  2405. <p>The <code>capabilities</code> of MSC3283 from the REST API <code>/_matrix/client/r0/capabilities</code>
  2406. becomes stable.</p>
  2407. <p>The old <code>capabilities</code></p>
  2408. <ul>
  2409. <li><code>org.matrix.msc3283.set_displayname</code>,</li>
  2410. <li><code>org.matrix.msc3283.set_avatar_url</code> and</li>
  2411. <li><code>org.matrix.msc3283.3pid_changes</code></li>
  2412. </ul>
  2413. <p>are deprecated and scheduled to be removed in Synapse v1.54.0.</p>
  2414. <p>The new <code>capabilities</code></p>
  2415. <ul>
  2416. <li><code>m.set_displayname</code>,</li>
  2417. <li><code>m.set_avatar_url</code> and</li>
  2418. <li><code>m.3pid_changes</code></li>
  2419. </ul>
  2420. <p>are now active by default.</p>
  2421. <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>
  2422. <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>,
  2423. the deprecated <code>user_may_create_room_with_invites</code> module callback has been removed.</p>
  2424. <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>
  2425. 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>
  2426. 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>
  2427. 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>
  2428. <h1 id="upgrading-to-v1520"><a class="header" href="#upgrading-to-v1520">Upgrading to v1.52.0</a></h1>
  2429. <h2 id="twisted-security-release"><a class="header" href="#twisted-security-release">Twisted security release</a></h2>
  2430. <p>Note that <a href="https://github.com/twisted/twisted/releases/tag/twisted-22.1.0">Twisted 22.1.0</a>
  2431. has recently been released, which fixes a <a href="https://github.com/twisted/twisted/security/advisories/GHSA-92x2-jw7w-xvvx">security issue</a>
  2432. within the Twisted library. We do not believe Synapse is affected by this vulnerability,
  2433. though we advise server administrators who installed Synapse via pip to upgrade Twisted
  2434. with <code>pip install --upgrade Twisted treq</code> as a matter of good practice. The Docker image
  2435. <code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> are using the
  2436. updated library.</p>
  2437. <h1 id="upgrading-to-v1510"><a class="header" href="#upgrading-to-v1510">Upgrading to v1.51.0</a></h1>
  2438. <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>
  2439. <p>Listeners of type <code>webclient</code> are deprecated and scheduled to be removed in
  2440. Synapse v1.53.0.</p>
  2441. <p>Similarly, a non-HTTP(S) <code>web_client_location</code> configuration is deprecated and
  2442. will become a configuration error in Synapse v1.53.0.</p>
  2443. <h1 id="upgrading-to-v1500"><a class="header" href="#upgrading-to-v1500">Upgrading to v1.50.0</a></h1>
  2444. <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>
  2445. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  2446. we've dropped support for Python 3.6 and PostgreSQL 9.6, as they are no
  2447. longer supported upstream.</p>
  2448. <p>This release of Synapse requires Python 3.7+ and PostgreSQL 10+.</p>
  2449. <h1 id="upgrading-to-v1470"><a class="header" href="#upgrading-to-v1470">Upgrading to v1.47.0</a></h1>
  2450. <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>
  2451. <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>
  2452. (released on 2021-05-17) and have now been removed:</p>
  2453. <ul>
  2454. <li><code>POST /_synapse/admin/v1/&lt;room_id&gt;/delete</code></li>
  2455. </ul>
  2456. <p>Any scripts still using the above APIs should be converted to use the
  2457. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  2458. <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>
  2459. <p>The <code>user_may_create_room_with_invites</code> is deprecated and will be removed in a future
  2460. version of Synapse. Modules implementing this callback can instead implement
  2461. <a href="https://matrix-org.github.io/synapse/latest/modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a>
  2462. 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>
  2463. module API method to infer whether the invite is happening in the context of creating a
  2464. room.</p>
  2465. <p>We plan to remove this callback in January 2022.</p>
  2466. <h1 id="upgrading-to-v1450"><a class="header" href="#upgrading-to-v1450">Upgrading to v1.45.0</a></h1>
  2467. <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>
  2468. <p>Media storage provider modules that read from the Synapse configuration object (i.e. that
  2469. read the value of <code>hs.config.[...]</code>) now need to specify the configuration section they're
  2470. reading from. This means that if a module reads the value of e.g. <code>hs.config.media_store_path</code>,
  2471. it needs to replace it with <code>hs.config.media.media_store_path</code>.</p>
  2472. <h1 id="upgrading-to-v1440"><a class="header" href="#upgrading-to-v1440">Upgrading to v1.44.0</a></h1>
  2473. <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>
  2474. <p>The <code>url_cache/</code> and <code>url_cache_thumbnails/</code> directories in the media store are
  2475. no longer mirrored to storage providers. These two directories can be safely
  2476. deleted from any configured storage providers to reclaim space.</p>
  2477. <h1 id="upgrading-to-v1430"><a class="header" href="#upgrading-to-v1430">Upgrading to v1.43.0</a></h1>
  2478. <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>
  2479. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#available-worker-applications">available worker applications documentation</a>
  2480. has been updated to reflect that calls to the <code>/spaces</code>, <code>/hierarchy</code>, and
  2481. <code>/summary</code> endpoints can now be routed to workers for both client API and
  2482. federation requests.</p>
  2483. <h1 id="upgrading-to-v1420"><a class="header" href="#upgrading-to-v1420">Upgrading to v1.42.0</a></h1>
  2484. <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>
  2485. <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>
  2486. (released on 2021-01-13) and have now been removed:</p>
  2487. <ul>
  2488. <li><code>POST /_synapse/admin/v1/purge_room</code></li>
  2489. <li><code>POST /_synapse/admin/v1/shutdown_room/&lt;room_id&gt;</code></li>
  2490. </ul>
  2491. <p>Any scripts still using the above APIs should be converted to use the
  2492. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  2493. <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>
  2494. <p>This may affect you if you make use of custom HTML templates for the
  2495. <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
  2496. <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>
  2497. <p>The template is now provided an <code>error</code> variable if the authentication
  2498. process failed. See the default templates linked above for an example.</p>
  2499. <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>
  2500. <p>Users will stop receiving message updates via email for addresses that were
  2501. once, but not still, linked to their account.</p>
  2502. <h1 id="upgrading-to-v1410"><a class="header" href="#upgrading-to-v1410">Upgrading to v1.41.0</a></h1>
  2503. <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>
  2504. <p>Since Synapse 1.6.0 (2019-11-26) you can set a proxy for outbound HTTP requests via
  2505. http_proxy/https_proxy environment variables. This proxy was set for:</p>
  2506. <ul>
  2507. <li>push</li>
  2508. <li>url previews</li>
  2509. <li>phone-home stats</li>
  2510. <li>recaptcha validation</li>
  2511. <li>CAS auth validation</li>
  2512. <li>OpenID Connect</li>
  2513. <li>Federation (checking public key revocation)</li>
  2514. </ul>
  2515. <p>In this version we have added support for outbound requests for:</p>
  2516. <ul>
  2517. <li>Outbound federation</li>
  2518. <li>Downloading remote media</li>
  2519. <li>Fetching public keys of other servers</li>
  2520. </ul>
  2521. <p>These requests use the same proxy configuration. If you have a proxy configuration we
  2522. recommend to verify the configuration. It may be necessary to adjust the <code>no_proxy</code>
  2523. environment variable.</p>
  2524. <p>See <a href="setup/forward_proxy.html">using a forward proxy with Synapse documentation</a> for
  2525. details.</p>
  2526. <h2 id="deprecation-of-template_dir"><a class="header" href="#deprecation-of-template_dir">Deprecation of <code>template_dir</code></a></h2>
  2527. <p>The <code>template_dir</code> settings in the <code>sso</code>, <code>account_validity</code> and <code>email</code> sections of the
  2528. configuration file are now deprecated. Server admins should use the new
  2529. <code>templates.custom_template_directory</code> setting in the configuration file and use one single
  2530. custom template directory for all aforementioned features. Template file names remain
  2531. unchanged. See <a href="https://matrix-org.github.io/synapse/latest/templates.html">the related documentation</a>
  2532. for more information and examples.</p>
  2533. <p>We plan to remove support for these settings in October 2021.</p>
  2534. <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>
  2535. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#synapseappmedia_repository">media repository worker documentation</a>
  2536. has been updated to reflect that calls to <code>/_synapse/admin/v1/users/{userId}/media</code>
  2537. must now be handled by media repository workers. This is due to the new <code>DELETE</code> method
  2538. of this endpoint modifying the media store.</p>
  2539. <h1 id="upgrading-to-v1390"><a class="header" href="#upgrading-to-v1390">Upgrading to v1.39.0</a></h1>
  2540. <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>
  2541. <p>The current third-party rules module interface is deprecated in favour of the new generic
  2542. modules system introduced in Synapse v1.37.0. Authors of third-party rules modules can refer
  2543. to <a href="modules/porting_legacy_module.html">this documentation</a>
  2544. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this documentation</a>
  2545. to update their configuration once the modules they are using have been updated.</p>
  2546. <p>We plan to remove support for the current third-party rules interface in September 2021.</p>
  2547. <h1 id="upgrading-to-v1380"><a class="header" href="#upgrading-to-v1380">Upgrading to v1.38.0</a></h1>
  2548. <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>
  2549. <p>This release includes a database schema update which requires re-indexing one of
  2550. the larger tables in the database, <code>events</code>. This could result in increased
  2551. disk I/O for several hours or days after upgrading while the migration
  2552. completes. Furthermore, because we have to keep the old indexes until the new
  2553. indexes are ready, it could result in a significant, temporary, increase in
  2554. disk space.</p>
  2555. <p>To get a rough idea of the disk space required, check the current size of one
  2556. of the indexes. For example, from a <code>psql</code> shell, run the following sql:</p>
  2557. <pre><code class="language-sql">SELECT pg_size_pretty(pg_relation_size('events_order_room'));
  2558. </code></pre>
  2559. <p>We need to rebuild <strong>four</strong> indexes, so you will need to multiply this result
  2560. by four to give an estimate of the disk space required. For example, on one
  2561. particular server:</p>
  2562. <pre><code>synapse=# select pg_size_pretty(pg_relation_size('events_order_room'));
  2563. pg_size_pretty
  2564. ----------------
  2565. 288 MB
  2566. (1 row)
  2567. </code></pre>
  2568. <p>On this server, it would be wise to ensure that at least 1152MB are free.</p>
  2569. <p>The additional disk space will be freed once the migration completes.</p>
  2570. <p>SQLite databases are unaffected by this change.</p>
  2571. <h1 id="upgrading-to-v1370"><a class="header" href="#upgrading-to-v1370">Upgrading to v1.37.0</a></h1>
  2572. <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>
  2573. <p>The current spam checker interface is deprecated in favour of a new generic modules system.
  2574. Authors of spam checker modules can refer to [this
  2575. documentation](modules/porting_legacy_module.md
  2576. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this
  2577. documentation</a>
  2578. to update their configuration once the modules they are using have been updated.</p>
  2579. <p>We plan to remove support for the current spam checker interface in August 2021.</p>
  2580. <p>More module interfaces will be ported over to this new generic system in future versions
  2581. of Synapse.</p>
  2582. <h1 id="upgrading-to-v1340"><a class="header" href="#upgrading-to-v1340">Upgrading to v1.34.0</a></h1>
  2583. <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>
  2584. <p>The <code>room_invite_state_types</code> configuration setting has been deprecated
  2585. 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
  2586. file</a>.</p>
  2587. <p>If you have set <code>room_invite_state_types</code> to the default value you
  2588. should simply remove it from your configuration file. The default value
  2589. used to be:</p>
  2590. <pre><code class="language-yaml">room_invite_state_types:
  2591. - &quot;m.room.join_rules&quot;
  2592. - &quot;m.room.canonical_alias&quot;
  2593. - &quot;m.room.avatar&quot;
  2594. - &quot;m.room.encryption&quot;
  2595. - &quot;m.room.name&quot;
  2596. </code></pre>
  2597. <p>If you have customised this value, you should remove
  2598. <code>room_invite_state_types</code> and configure <code>room_prejoin_state</code> instead.</p>
  2599. <h1 id="upgrading-to-v1330"><a class="header" href="#upgrading-to-v1330">Upgrading to v1.33.0</a></h1>
  2600. <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>
  2601. <p>This may affect you if you have enabled the account validity feature,
  2602. and have made use of a custom HTML template specified by the
  2603. <code>account_validity.template_dir</code> or
  2604. <code>account_validity.account_renewed_html_path</code> Synapse config options.</p>
  2605. <p>The template can now accept an <code>expiration_ts</code> variable, which
  2606. represents the unix timestamp in milliseconds for the future date of
  2607. 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
  2608. template</a>
  2609. for an example of usage.</p>
  2610. <p>ALso note that a new HTML template, <code>account_previously_renewed.html</code>,
  2611. has been added. This is is shown to users when they attempt to renew
  2612. their account with a valid renewal token that has already been used
  2613. before. The default template contents can been found
  2614. <a href="https://github.com/matrix-org/synapse/blob/release-v1.33.0/synapse/res/templates/account_previously_renewed.html">here</a>,
  2615. and can also accept an <code>expiration_ts</code> variable. This template replaces
  2616. the error message users would previously see upon attempting to use a
  2617. valid renewal token more than once.</p>
  2618. <h1 id="upgrading-to-v1320"><a class="header" href="#upgrading-to-v1320">Upgrading to v1.32.0</a></h1>
  2619. <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>
  2620. <p>This release introduces <a href="https://github.com/matrix-org/synapse/issues/9853">a
  2621. regression</a> that can
  2622. overwhelm connected Prometheus instances. This issue is not present in
  2623. Synapse v1.32.0rc1.</p>
  2624. <p>If you have been affected, please downgrade to 1.31.0. You then may need
  2625. to remove excess writeahead logs in order for Prometheus to recover.
  2626. Instructions for doing so are provided
  2627. <a href="https://github.com/matrix-org/synapse/pull/9854#issuecomment-823472183">here</a>.</p>
  2628. <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>
  2629. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  2630. we've dropped support for Python 3.5 and PostgreSQL 9.5, as they are no
  2631. longer supported upstream.</p>
  2632. <p>This release of Synapse requires Python 3.6+ and PostgreSQL 9.6+ or
  2633. SQLite 3.22+.</p>
  2634. <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>
  2635. <p>The deprecated v1 &quot;list accounts&quot; admin API
  2636. (<code>GET /_synapse/admin/v1/users/&lt;user_id&gt;</code>) has been removed in this
  2637. version.</p>
  2638. <p>The <a href="admin_api/user_admin_api.html#list-accounts">v2 list accounts API</a>
  2639. has been available since Synapse 1.7.0 (2019-12-13), and is accessible
  2640. under <code>GET /_synapse/admin/v2/users</code>.</p>
  2641. <p>The deprecation of the old endpoint was announced with Synapse 1.28.0
  2642. (released on 2021-02-25).</p>
  2643. <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>
  2644. <p>In compliance with the <a href="https://matrix.org/docs/spec/application_service/r0.1.2#server-admin-style-permissions">Application Service
  2645. spec</a>,
  2646. Application Services are now required to use the
  2647. <code>m.login.application_service</code> type when registering users via the
  2648. <code>/_matrix/client/r0/register</code> endpoint. This behaviour was deprecated in
  2649. Synapse v1.30.0.</p>
  2650. <p>Please ensure your Application Services are up to date.</p>
  2651. <h1 id="upgrading-to-v1290"><a class="header" href="#upgrading-to-v1290">Upgrading to v1.29.0</a></h1>
  2652. <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>
  2653. <p>When using Synapse with a reverse proxy (in particular, when using the
  2654. <code>x_forwarded</code> option on an HTTP listener), Synapse now
  2655. expects to receive an <code>X-Forwarded-Proto</code> header on incoming
  2656. HTTP requests. If it is not set, Synapse will log a warning on each
  2657. received request.</p>
  2658. <p>To avoid the warning, administrators using a reverse proxy should ensure
  2659. that the reverse proxy sets <code>X-Forwarded-Proto</code> header to
  2660. <code>https</code> or <code>http</code> to indicate the protocol used
  2661. by the client.</p>
  2662. <p>Synapse also requires the <code>Host</code> header to be preserved.</p>
  2663. <p>See the <a href="reverse_proxy.html">reverse proxy documentation</a>, where the
  2664. example configurations have been updated to show how to set these
  2665. headers.</p>
  2666. <p>(Users of <a href="https://caddyserver.com/">Caddy</a> are unaffected, since we
  2667. believe it sets <code>X-Forwarded-Proto</code> by default.)</p>
  2668. <h1 id="upgrading-to-v1270"><a class="header" href="#upgrading-to-v1270">Upgrading to v1.27.0</a></h1>
  2669. <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>
  2670. <p>This version changes the URI used for callbacks from OAuth2 and SAML2
  2671. identity providers:</p>
  2672. <ul>
  2673. <li>
  2674. <p>If your server is configured for single sign-on via an OpenID
  2675. Connect or OAuth2 identity provider, you will need to add
  2676. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> to the list
  2677. of permitted &quot;redirect URIs&quot; at the identity provider.</p>
  2678. <p>See the <a href="openid.html">OpenID docs</a> for more information on setting
  2679. up OpenID Connect.</p>
  2680. </li>
  2681. <li>
  2682. <p>If your server is configured for single sign-on via a SAML2 identity
  2683. provider, you will need to add
  2684. <code>[synapse public baseurl]/_synapse/client/saml2/authn_response</code> as a
  2685. permitted &quot;ACS location&quot; (also known as &quot;allowed callback URLs&quot;)
  2686. at the identity provider.</p>
  2687. <p>The &quot;Issuer&quot; in the &quot;AuthnRequest&quot; to the SAML2 identity
  2688. provider is also updated to
  2689. <code>[synapse public baseurl]/_synapse/client/saml2/metadata.xml</code>. If
  2690. your SAML2 identity provider uses this property to validate or
  2691. otherwise identify Synapse, its configuration will need to be
  2692. updated to use the new URL. Alternatively you could create a new,
  2693. separate &quot;EntityDescriptor&quot; in your SAML2 identity provider with
  2694. the new URLs and leave the URLs in the existing &quot;EntityDescriptor&quot;
  2695. as they were.</p>
  2696. </li>
  2697. </ul>
  2698. <h2 id="changes-to-html-templates"><a class="header" href="#changes-to-html-templates">Changes to HTML templates</a></h2>
  2699. <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
  2700. autoescape</a>
  2701. enabled for files ending in <code>.html</code>, <code>.htm</code>, and <code>.xml</code>. If you have
  2702. customised these templates and see issues when viewing them you might
  2703. need to update them. It is expected that most configurations will need
  2704. no changes.</p>
  2705. <p>If you have customised the templates <em>names</em> for these templates, it is
  2706. recommended to verify they end in <code>.html</code> to ensure autoescape is
  2707. enabled.</p>
  2708. <p>The above applies to the following templates:</p>
  2709. <ul>
  2710. <li><code>add_threepid.html</code></li>
  2711. <li><code>add_threepid_failure.html</code></li>
  2712. <li><code>add_threepid_success.html</code></li>
  2713. <li><code>notice_expiry.html</code></li>
  2714. <li><code>notice_expiry.html</code></li>
  2715. <li><code>notif_mail.html</code> (which, by default, includes <code>room.html</code> and
  2716. <code>notif.html</code>)</li>
  2717. <li><code>password_reset.html</code></li>
  2718. <li><code>password_reset_confirmation.html</code></li>
  2719. <li><code>password_reset_failure.html</code></li>
  2720. <li><code>password_reset_success.html</code></li>
  2721. <li><code>registration.html</code></li>
  2722. <li><code>registration_failure.html</code></li>
  2723. <li><code>registration_success.html</code></li>
  2724. <li><code>sso_account_deactivated.html</code></li>
  2725. <li><code>sso_auth_bad_user.html</code></li>
  2726. <li><code>sso_auth_confirm.html</code></li>
  2727. <li><code>sso_auth_success.html</code></li>
  2728. <li><code>sso_error.html</code></li>
  2729. <li><code>sso_login_idp_picker.html</code></li>
  2730. <li><code>sso_redirect_confirm.html</code></li>
  2731. </ul>
  2732. <h1 id="upgrading-to-v1260"><a class="header" href="#upgrading-to-v1260">Upgrading to v1.26.0</a></h1>
  2733. <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>
  2734. <p>v1.26.0 includes a lot of large changes. If something problematic
  2735. occurs, you may want to roll-back to a previous version of Synapse.
  2736. Because v1.26.0 also includes a new database schema version, reverting
  2737. that version is also required alongside the generic rollback
  2738. instructions mentioned above. In short, to roll back to v1.25.0 you need
  2739. to:</p>
  2740. <ol>
  2741. <li>
  2742. <p>Stop the server</p>
  2743. </li>
  2744. <li>
  2745. <p>Decrease the schema version in the database:</p>
  2746. <pre><code class="language-sql">UPDATE schema_version SET version = 58;
  2747. </code></pre>
  2748. </li>
  2749. <li>
  2750. <p>Delete the ignored users &amp; chain cover data:</p>
  2751. <pre><code class="language-sql">DROP TABLE IF EXISTS ignored_users;
  2752. UPDATE rooms SET has_auth_chain_index = false;
  2753. </code></pre>
  2754. <p>For PostgreSQL run:</p>
  2755. <pre><code class="language-sql">TRUNCATE event_auth_chain_links;
  2756. TRUNCATE event_auth_chains;
  2757. </code></pre>
  2758. <p>For SQLite run:</p>
  2759. <pre><code class="language-sql">DELETE FROM event_auth_chain_links;
  2760. DELETE FROM event_auth_chains;
  2761. </code></pre>
  2762. </li>
  2763. <li>
  2764. <p>Mark the deltas as not run (so they will re-run on upgrade).</p>
  2765. <pre><code class="language-sql">DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/01ignored_user.py&quot;;
  2766. DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/06chain_cover_index.sql&quot;;
  2767. </code></pre>
  2768. </li>
  2769. <li>
  2770. <p>Downgrade Synapse by following the instructions for your
  2771. installation method in the &quot;Rolling back to older versions&quot;
  2772. section above.</p>
  2773. </li>
  2774. </ol>
  2775. <h1 id="upgrading-to-v1250"><a class="header" href="#upgrading-to-v1250">Upgrading to v1.25.0</a></h1>
  2776. <h2 id="last-release-supporting-python-35"><a class="header" href="#last-release-supporting-python-35">Last release supporting Python 3.5</a></h2>
  2777. <p>This is the last release of Synapse which guarantees support with Python
  2778. 3.5, which passed its upstream End of Life date several months ago.</p>
  2779. <p>We will attempt to maintain support through March 2021, but without
  2780. guarantees.</p>
  2781. <p>In the future, Synapse will follow upstream schedules for ending support
  2782. of older versions of Python and PostgreSQL. Please upgrade to at least
  2783. Python 3.6 and PostgreSQL 9.6 as soon as possible.</p>
  2784. <h2 id="blacklisting-ip-ranges"><a class="header" href="#blacklisting-ip-ranges">Blacklisting IP ranges</a></h2>
  2785. <p>Synapse v1.25.0 includes new settings, <code>ip_range_blacklist</code> and
  2786. <code>ip_range_whitelist</code>, for controlling outgoing requests from Synapse for
  2787. federation, identity servers, push, and for checking key validity for
  2788. third-party invite events. The previous setting,
  2789. <code>federation_ip_range_blacklist</code>, is deprecated. The new
  2790. <code>ip_range_blacklist</code> defaults to private IP ranges if it is not defined.</p>
  2791. <p>If you have never customised <code>federation_ip_range_blacklist</code> it is
  2792. recommended that you remove that setting.</p>
  2793. <p>If you have customised <code>federation_ip_range_blacklist</code> you should update
  2794. the setting name to <code>ip_range_blacklist</code>.</p>
  2795. <p>If you have a custom push server that is reached via private IP space
  2796. you may need to customise <code>ip_range_blacklist</code> or <code>ip_range_whitelist</code>.</p>
  2797. <h1 id="upgrading-to-v1240"><a class="header" href="#upgrading-to-v1240">Upgrading to v1.24.0</a></h1>
  2798. <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>
  2799. <p>This release allows the OpenID Connect mapping provider to perform
  2800. normalisation of the localpart of the Matrix ID. This allows for the
  2801. mapping provider to specify different algorithms, instead of the
  2802. <a href="https://matrix.org/docs/spec/appendices#mapping-from-other-character-sets">default
  2803. way</a>.</p>
  2804. <p>If your Synapse configuration uses a custom mapping provider
  2805. (<code>oidc_config.user_mapping_provider.module</code> is specified and
  2806. not equal to
  2807. <code>synapse.handlers.oidc_handler.JinjaOidcMappingProvider</code>)
  2808. then you <em>must</em> ensure that <code>map_user_attributes</code> of the
  2809. mapping provider performs some normalisation of the
  2810. <code>localpart</code> returned. To match previous behaviour you can
  2811. use the <code>map_username_to_mxid_localpart</code> function provided
  2812. by Synapse. An example is shown below:</p>
  2813. <pre><code class="language-python">from synapse.types import map_username_to_mxid_localpart
  2814. class MyMappingProvider:
  2815. def map_user_attributes(self, userinfo, token):
  2816. # ... your custom logic ...
  2817. sso_user_id = ...
  2818. localpart = map_username_to_mxid_localpart(sso_user_id)
  2819. return {&quot;localpart&quot;: localpart}
  2820. </code></pre>
  2821. <h2 id="removal-historical-synapse-admin-api"><a class="header" href="#removal-historical-synapse-admin-api">Removal historical Synapse Admin API</a></h2>
  2822. <p>Historically, the Synapse Admin API has been accessible under:</p>
  2823. <ul>
  2824. <li><code>/_matrix/client/api/v1/admin</code></li>
  2825. <li><code>/_matrix/client/unstable/admin</code></li>
  2826. <li><code>/_matrix/client/r0/admin</code></li>
  2827. <li><code>/_synapse/admin/v1</code></li>
  2828. </ul>
  2829. <p>The endpoints with <code>/_matrix/client/*</code> prefixes have been removed as of
  2830. v1.24.0. The Admin API is now only accessible under:</p>
  2831. <ul>
  2832. <li><code>/_synapse/admin/v1</code></li>
  2833. </ul>
  2834. <p>The only exception is the <code>/admin/whois</code> endpoint, which is
  2835. <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
  2836. API</a>.</p>
  2837. <p>The deprecation of the old endpoints was announced with Synapse 1.20.0
  2838. (released on 2020-09-22) and makes it easier for homeserver admins to
  2839. lock down external access to the Admin API endpoints.</p>
  2840. <h1 id="upgrading-to-v1230"><a class="header" href="#upgrading-to-v1230">Upgrading to v1.23.0</a></h1>
  2841. <h2 id="structured-logging-configuration-breaking-changes"><a class="header" href="#structured-logging-configuration-breaking-changes">Structured logging configuration breaking changes</a></h2>
  2842. <p>This release deprecates use of the <code>structured: true</code> logging
  2843. configuration for structured logging. If your logging configuration
  2844. contains <code>structured: true</code> then it should be modified based on the
  2845. <a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
  2846. <p>The <code>structured</code> and <code>drains</code> logging options are now deprecated and
  2847. should be replaced by standard logging configuration of <code>handlers</code> and
  2848. <code>formatters</code>.</p>
  2849. <p>A future will release of Synapse will make using <code>structured: true</code> an
  2850. error.</p>
  2851. <h1 id="upgrading-to-v1220"><a class="header" href="#upgrading-to-v1220">Upgrading to v1.22.0</a></h1>
  2852. <h2 id="thirdpartyeventrules-breaking-changes"><a class="header" href="#thirdpartyeventrules-breaking-changes">ThirdPartyEventRules breaking changes</a></h2>
  2853. <p>This release introduces a backwards-incompatible change to modules
  2854. making use of <code>ThirdPartyEventRules</code> in Synapse. If you make use of a
  2855. module defined under the <code>third_party_event_rules</code> config option, please
  2856. make sure it is updated to handle the below change:</p>
  2857. <p>The <code>http_client</code> argument is no longer passed to modules as they are
  2858. initialised. Instead, modules are expected to make use of the
  2859. <code>http_client</code> property on the <code>ModuleApi</code> class. Modules are now passed
  2860. a <code>module_api</code> argument during initialisation, which is an instance of
  2861. <code>ModuleApi</code>. <code>ModuleApi</code> instances have a <code>http_client</code> property which
  2862. acts the same as the <code>http_client</code> argument previously passed to
  2863. <code>ThirdPartyEventRules</code> modules.</p>
  2864. <h1 id="upgrading-to-v1210"><a class="header" href="#upgrading-to-v1210">Upgrading to v1.21.0</a></h1>
  2865. <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>
  2866. <p>The <a href="reverse_proxy.html">reverse proxy documentation</a>
  2867. has been updated to include reverse proxy directives for
  2868. <code>/_synapse/client/*</code> endpoints. As the user password reset flow now uses
  2869. endpoints under this prefix, <strong>you must update your reverse proxy
  2870. configurations for user password reset to work</strong>.</p>
  2871. <p>Additionally, note that the <a href="workers.html">Synapse worker documentation</a> has been updated to</p>
  2872. <p>: state that the <code>/_synapse/client/password_reset/email/submit_token</code>
  2873. endpoint can be handled</p>
  2874. <p>by all workers. If you make use of Synapse's worker feature, please
  2875. update your reverse proxy configuration to reflect this change.</p>
  2876. <h2 id="new-html-templates"><a class="header" href="#new-html-templates">New HTML templates</a></h2>
  2877. <p>A new HTML template,
  2878. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/res/templates/password_reset_confirmation.html">password_reset_confirmation.html</a>,
  2879. has been added to the <code>synapse/res/templates</code> directory. If you are
  2880. using a custom template directory, you may want to copy the template
  2881. over and modify it.</p>
  2882. <p>Note that as of v1.20.0, templates do not need to be included in custom
  2883. template directories for Synapse to start. The default templates will be
  2884. used if a custom template cannot be found.</p>
  2885. <p>This page will appear to the user after clicking a password reset link
  2886. that has been emailed to them.</p>
  2887. <p>To complete password reset, the page must include a way to make a
  2888. <code>POST</code> request to
  2889. <code>/_synapse/client/password_reset/{medium}/submit_token</code> with the query
  2890. parameters from the original link, presented as a URL-encoded form. See
  2891. the file itself for more details.</p>
  2892. <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>
  2893. <p>The <code>saml_error.html</code> template was removed from Synapse and replaced
  2894. with the <code>sso_error.html</code> template. If your Synapse is configured to use
  2895. SAML and a custom <code>sso_redirect_confirm_template_dir</code> configuration then
  2896. any customisations of the <code>saml_error.html</code> template will need to be
  2897. merged into the <code>sso_error.html</code> template. These templates are similar,
  2898. but the parameters are slightly different:</p>
  2899. <ul>
  2900. <li>The <code>msg</code> parameter should be renamed to <code>error_description</code>.</li>
  2901. <li>There is no longer a <code>code</code> parameter for the response code.</li>
  2902. <li>A string <code>error</code> parameter is available that includes a short hint
  2903. of why a user is seeing the error page.</li>
  2904. </ul>
  2905. <h1 id="upgrading-to-v1180"><a class="header" href="#upgrading-to-v1180">Upgrading to v1.18.0</a></h1>
  2906. <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>
  2907. <p>From 10th August 2020, we will no longer publish Docker images with the
  2908. <code>-py3</code> tag suffix. The images tagged with the
  2909. <code>-py3</code> suffix have been identical to the non-suffixed tags
  2910. since release 0.99.0, and the suffix is obsolete.</p>
  2911. <p>On 10th August, we will remove the <code>latest-py3</code> tag.
  2912. Existing per-release tags (such as <code>v1.18.0-py3</code> will not
  2913. be removed, but no new <code>-py3</code> tags will be added.</p>
  2914. <p>Scripts relying on the <code>-py3</code> suffix will need to be
  2915. updated.</p>
  2916. <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>
  2917. <p>When setting up worker processes, we now recommend the use of a Redis
  2918. server for replication. <strong>The old direct TCP connection method is
  2919. deprecated and will be removed in a future release.</strong> See
  2920. the <a href="https://matrix-org.github.io/synapse/v1.66/workers.html">worker documentation</a> for more details.</p>
  2921. <h1 id="upgrading-to-v1140"><a class="header" href="#upgrading-to-v1140">Upgrading to v1.14.0</a></h1>
  2922. <p>This version includes a database update which is run as part of the
  2923. upgrade, and which may take a couple of minutes in the case of a large
  2924. server. Synapse will not respond to HTTP requests while this update is
  2925. taking place.</p>
  2926. <h1 id="upgrading-to-v1130"><a class="header" href="#upgrading-to-v1130">Upgrading to v1.13.0</a></h1>
  2927. <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>
  2928. <p>A bug was introduced in Synapse 1.4.0 which could cause the room
  2929. directory to be incomplete or empty if Synapse was upgraded directly
  2930. from v1.2.1 or earlier, to versions between v1.4.0 and v1.12.x.</p>
  2931. <p>This will <em>not</em> be a problem for Synapse installations which were:</p>
  2932. <p>: - created at v1.4.0 or later,
  2933. - upgraded via v1.3.x, or
  2934. - upgraded straight from v1.2.1 or earlier to v1.13.0 or later.</p>
  2935. <p>If completeness of the room directory is a concern, installations which
  2936. are affected can be repaired as follows:</p>
  2937. <ol>
  2938. <li>
  2939. <p>Run the following sql from a <code>psql</code> or
  2940. <code>sqlite3</code> console:</p>
  2941. <pre><code class="language-sql">INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2942. ('populate_stats_process_rooms', '{}', 'current_state_events_membership');
  2943. INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2944. ('populate_stats_process_users', '{}', 'populate_stats_process_rooms');
  2945. </code></pre>
  2946. </li>
  2947. <li>
  2948. <p>Restart synapse.</p>
  2949. </li>
  2950. </ol>
  2951. <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>
  2952. <p>New templates (<code>sso_auth_confirm.html</code>, <code>sso_auth_success.html</code>, and
  2953. <code>sso_account_deactivated.html</code>) were added to Synapse. If your Synapse
  2954. is configured to use SSO and a custom
  2955. <code>sso_redirect_confirm_template_dir</code> configuration then these templates
  2956. will need to be copied from
  2957. <a href="https://github.com/matrix-org/synapse/tree/develop/synapse/res/templates"><code>synapse/res/templates</code></a> into that directory.</p>
  2958. <h2 id="synapse-sso-plugins-method-deprecation"><a class="header" href="#synapse-sso-plugins-method-deprecation">Synapse SSO Plugins Method Deprecation</a></h2>
  2959. <p>Plugins using the <code>complete_sso_login</code> method of
  2960. <code>synapse.module_api.ModuleApi</code> should update to using the async/await
  2961. version <code>complete_sso_login_async</code> which includes additional checks. The
  2962. non-async version is considered deprecated.</p>
  2963. <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>
  2964. <p>v1.13.0 includes a lot of large changes. If something problematic
  2965. occurs, you may want to roll-back to a previous version of Synapse.
  2966. Because v1.13.0 also includes a new database schema version, reverting
  2967. that version is also required alongside the generic rollback
  2968. instructions mentioned above. In short, to roll back to v1.12.4 you need
  2969. to:</p>
  2970. <ol>
  2971. <li>
  2972. <p>Stop the server</p>
  2973. </li>
  2974. <li>
  2975. <p>Decrease the schema version in the database:</p>
  2976. <pre><code class="language-sql">UPDATE schema_version SET version = 57;
  2977. </code></pre>
  2978. </li>
  2979. <li>
  2980. <p>Downgrade Synapse by following the instructions for your
  2981. installation method in the &quot;Rolling back to older versions&quot;
  2982. section above.</p>
  2983. </li>
  2984. </ol>
  2985. <h1 id="upgrading-to-v1120"><a class="header" href="#upgrading-to-v1120">Upgrading to v1.12.0</a></h1>
  2986. <p>This version includes a database update which is run as part of the
  2987. upgrade, and which may take some time (several hours in the case of a
  2988. large server). Synapse will not respond to HTTP requests while this
  2989. update is taking place.</p>
  2990. <p>This is only likely to be a problem in the case of a server which is
  2991. participating in many rooms.</p>
  2992. <ol start="0">
  2993. <li>
  2994. <p>As with all upgrades, it is recommended that you have a recent
  2995. backup of your database which can be used for recovery in the event
  2996. of any problems.</p>
  2997. </li>
  2998. <li>
  2999. <p>As an initial check to see if you will be affected, you can try
  3000. running the following query from the <code>psql</code> or
  3001. <code>sqlite3</code> console. It is safe to run it while Synapse is
  3002. still running.</p>
  3003. <pre><code class="language-sql">SELECT MAX(q.v) FROM (
  3004. SELECT (
  3005. SELECT ej.json AS v
  3006. FROM state_events se INNER JOIN event_json ej USING (event_id)
  3007. WHERE se.room_id=rooms.room_id AND se.type='m.room.create' AND se.state_key=''
  3008. LIMIT 1
  3009. ) FROM rooms WHERE rooms.room_version IS NULL
  3010. ) q;
  3011. </code></pre>
  3012. <p>This query will take about the same amount of time as the upgrade
  3013. process: ie, if it takes 5 minutes, then it is likely that Synapse
  3014. will be unresponsive for 5 minutes during the upgrade.</p>
  3015. <p>If you consider an outage of this duration to be acceptable, no
  3016. further action is necessary and you can simply start Synapse 1.12.0.</p>
  3017. <p>If you would prefer to reduce the downtime, continue with the steps
  3018. below.</p>
  3019. </li>
  3020. <li>
  3021. <p>The easiest workaround for this issue is to manually create a new
  3022. index before upgrading. On PostgreSQL, his can be done as follows:</p>
  3023. <pre><code class="language-sql">CREATE INDEX CONCURRENTLY tmp_upgrade_1_12_0_index
  3024. ON state_events(room_id) WHERE type = 'm.room.create';
  3025. </code></pre>
  3026. <p>The above query may take some time, but is also safe to run while
  3027. Synapse is running.</p>
  3028. <p>We assume that no SQLite users have databases large enough to be
  3029. affected. If you <em>are</em> affected, you can run a similar query,
  3030. omitting the <code>CONCURRENTLY</code> keyword. Note however that this
  3031. operation may in itself cause Synapse to stop running for some time.
  3032. Synapse admins are reminded that <a href="postgres.html">SQLite is not recommended for use
  3033. outside a test environment</a>.</p>
  3034. </li>
  3035. <li>
  3036. <p>Once the index has been created, the <code>SELECT</code> query in step 1 above
  3037. should complete quickly. It is therefore safe to upgrade to Synapse
  3038. 1.12.0.</p>
  3039. </li>
  3040. <li>
  3041. <p>Once Synapse 1.12.0 has successfully started and is responding to
  3042. HTTP requests, the temporary index can be removed:</p>
  3043. <pre><code class="language-sql">DROP INDEX tmp_upgrade_1_12_0_index;
  3044. </code></pre>
  3045. </li>
  3046. </ol>
  3047. <h1 id="upgrading-to-v1100"><a class="header" href="#upgrading-to-v1100">Upgrading to v1.10.0</a></h1>
  3048. <p>Synapse will now log a warning on start up if used with a PostgreSQL
  3049. database that has a non-recommended locale set.</p>
  3050. <p>See <a href="postgres.html">Postgres</a> for details.</p>
  3051. <h1 id="upgrading-to-v180"><a class="header" href="#upgrading-to-v180">Upgrading to v1.8.0</a></h1>
  3052. <p>Specifying a <code>log_file</code> config option will now cause Synapse to refuse
  3053. to start, and should be replaced by with the <code>log_config</code> option.
  3054. Support for the <code>log_file</code> option was removed in v1.3.0 and has since
  3055. had no effect.</p>
  3056. <h1 id="upgrading-to-v170"><a class="header" href="#upgrading-to-v170">Upgrading to v1.7.0</a></h1>
  3057. <p>In an attempt to configure Synapse in a privacy preserving way, the
  3058. default behaviours of <code>allow_public_rooms_without_auth</code> and
  3059. <code>allow_public_rooms_over_federation</code> have been inverted. This means that
  3060. by default, only authenticated users querying the Client/Server API will
  3061. be able to query the room directory, and relatedly that the server will
  3062. not share room directory information with other servers over federation.</p>
  3063. <p>If your installation does not explicitly set these settings one way or
  3064. the other and you want either setting to be <code>true</code> then it will
  3065. necessary to update your homeserver configuration file accordingly.</p>
  3066. <p>For more details on the surrounding context see our
  3067. <a href="https://matrix.org/blog/2019/11/09/avoiding-unwelcome-visitors-on-private-matrix-servers">explainer</a>.</p>
  3068. <h1 id="upgrading-to-v150"><a class="header" href="#upgrading-to-v150">Upgrading to v1.5.0</a></h1>
  3069. <p>This release includes a database migration which may take several
  3070. minutes to complete if there are a large number (more than a million or
  3071. so) of entries in the <code>devices</code> table. This is only likely to a be a
  3072. problem on very large installations.</p>
  3073. <h1 id="upgrading-to-v140"><a class="header" href="#upgrading-to-v140">Upgrading to v1.4.0</a></h1>
  3074. <h2 id="new-custom-templates"><a class="header" href="#new-custom-templates">New custom templates</a></h2>
  3075. <p>If you have configured a custom template directory with the
  3076. <code>email.template_dir</code> option, be aware that there are new templates
  3077. regarding registration and threepid management (see below) that must be
  3078. included.</p>
  3079. <ul>
  3080. <li><code>registration.html</code> and <code>registration.txt</code></li>
  3081. <li><code>registration_success.html</code> and <code>registration_failure.html</code></li>
  3082. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code></li>
  3083. <li><code>add_threepid_failure.html</code> and <code>add_threepid_success.html</code></li>
  3084. </ul>
  3085. <p>Synapse will expect these files to exist inside the configured template
  3086. directory, and <strong>will fail to start</strong> if they are absent. To view the
  3087. default templates, see
  3088. <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">synapse/res/templates</a>.</p>
  3089. <h2 id="3pid-verification-changes"><a class="header" href="#3pid-verification-changes">3pid verification changes</a></h2>
  3090. <p><strong>Note: As of this release, users will be unable to add phone numbers or
  3091. email addresses to their accounts, without changes to the Synapse
  3092. configuration. This includes adding an email address during
  3093. registration.</strong></p>
  3094. <p>It is possible for a user to associate an email address or phone number
  3095. with their account, for a number of reasons:</p>
  3096. <ul>
  3097. <li>for use when logging in, as an alternative to the user id.</li>
  3098. <li>in the case of email, as an alternative contact to help with account
  3099. recovery.</li>
  3100. <li>in the case of email, to receive notifications of missed messages.</li>
  3101. </ul>
  3102. <p>Before an email address or phone number can be added to a user's
  3103. account, or before such an address is used to carry out a
  3104. password-reset, Synapse must confirm the operation with the owner of the
  3105. email address or phone number. It does this by sending an email or text
  3106. giving the user a link or token to confirm receipt. This process is
  3107. known as '3pid verification'. ('3pid', or 'threepid', stands for
  3108. third-party identifier, and we use it to refer to external identifiers
  3109. such as email addresses and phone numbers.)</p>
  3110. <p>Previous versions of Synapse delegated the task of 3pid verification to
  3111. an identity server by default. In most cases this server is <code>vector.im</code>
  3112. or <code>matrix.org</code>.</p>
  3113. <p>In Synapse 1.4.0, for security and privacy reasons, the homeserver will
  3114. no longer delegate this task to an identity server by default. Instead,
  3115. the server administrator will need to explicitly decide how they would
  3116. like the verification messages to be sent.</p>
  3117. <p>In the medium term, the <code>vector.im</code> and <code>matrix.org</code> identity servers
  3118. will disable support for delegated 3pid verification entirely. However,
  3119. in order to ease the transition, they will retain the capability for a
  3120. limited period. Delegated email verification will be disabled on Monday
  3121. 2nd December 2019 (giving roughly 2 months notice). Disabling delegated
  3122. SMS verification will follow some time after that once SMS verification
  3123. support lands in Synapse.</p>
  3124. <p>Once delegated 3pid verification support has been disabled in the
  3125. <code>vector.im</code> and <code>matrix.org</code> identity servers, all Synapse versions that
  3126. depend on those instances will be unable to verify email and phone
  3127. numbers through them. There are no imminent plans to remove delegated
  3128. 3pid verification from Sydent generally. (Sydent is the identity server
  3129. project that backs the <code>vector.im</code> and <code>matrix.org</code> instances).</p>
  3130. <h3 id="email-1"><a class="header" href="#email-1">Email</a></h3>
  3131. <p>Following upgrade, to continue verifying email (e.g. as part of the
  3132. registration process), admins can either:-</p>
  3133. <ul>
  3134. <li>Configure Synapse to use an email server.</li>
  3135. <li>Run or choose an identity server which allows delegated email
  3136. verification and delegate to it.</li>
  3137. </ul>
  3138. <h4 id="configure-smtp-in-synapse"><a class="header" href="#configure-smtp-in-synapse">Configure SMTP in Synapse</a></h4>
  3139. <p>To configure an SMTP server for Synapse, modify the configuration
  3140. section headed <code>email</code>, and be sure to have at least the
  3141. <code>smtp_host, smtp_port</code> and <code>notif_from</code> fields filled out.</p>
  3142. <p>You may also need to set <code>smtp_user</code>, <code>smtp_pass</code>, and
  3143. <code>require_transport_security</code>.</p>
  3144. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  3145. for more details on these settings.</p>
  3146. <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>
  3147. <p>Some admins will wish to continue using email verification as part of
  3148. the registration process, but will not immediately have an appropriate
  3149. SMTP server at hand.</p>
  3150. <p>To this end, we will continue to support email verification delegation
  3151. via the <code>vector.im</code> and <code>matrix.org</code> identity servers for two months.
  3152. Support for delegated email verification will be disabled on Monday 2nd
  3153. December.</p>
  3154. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  3155. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  3156. server</a>) to handle
  3157. sending confirmation messages via email and SMS.</p>
  3158. <p>So to delegate email verification, in <code>homeserver.yaml</code>, set
  3159. <code>account_threepid_delegates.email</code> to the base URL of an identity
  3160. server. For example:</p>
  3161. <pre><code class="language-yaml">account_threepid_delegates:
  3162. email: https://example.com # Delegate email sending to example.com
  3163. </code></pre>
  3164. <p>Note that <code>account_threepid_delegates.email</code> replaces the deprecated
  3165. <code>email.trust_identity_server_for_password_resets</code>: if
  3166. <code>email.trust_identity_server_for_password_resets</code> is set to <code>true</code>, and
  3167. <code>account_threepid_delegates.email</code> is not set, then the first entry in
  3168. <code>trusted_third_party_id_servers</code> will be used as the
  3169. <code>account_threepid_delegate</code> for email. This is to ensure compatibility
  3170. with existing Synapse installs that set up external server handling for
  3171. these tasks before v1.4.0. If
  3172. <code>email.trust_identity_server_for_password_resets</code> is <code>true</code> and no
  3173. trusted identity server domains are configured, Synapse will report an
  3174. error and refuse to start.</p>
  3175. <p>If <code>email.trust_identity_server_for_password_resets</code> is <code>false</code> or
  3176. absent and no <code>email</code> delegate is configured in
  3177. <code>account_threepid_delegates</code>, then Synapse will send email verification
  3178. messages itself, using the configured SMTP server (see above). that
  3179. type.</p>
  3180. <h3 id="phone-numbers"><a class="header" href="#phone-numbers">Phone numbers</a></h3>
  3181. <p>Synapse does not support phone-number verification itself, so the only
  3182. way to maintain the ability for users to add phone numbers to their
  3183. accounts will be by continuing to delegate phone number verification to
  3184. the <code>matrix.org</code> and <code>vector.im</code> identity servers (or another identity
  3185. server that supports SMS sending).</p>
  3186. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  3187. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  3188. server</a>) to handle
  3189. sending confirmation messages via email and SMS.</p>
  3190. <p>So to delegate phone number verification, in <code>homeserver.yaml</code>, set
  3191. <code>account_threepid_delegates.msisdn</code> to the base URL of an identity
  3192. server. For example:</p>
  3193. <pre><code class="language-yaml">account_threepid_delegates:
  3194. msisdn: https://example.com # Delegate sms sending to example.com
  3195. </code></pre>
  3196. <p>The <code>matrix.org</code> and <code>vector.im</code> identity servers will continue to
  3197. support delegated phone number verification via SMS until such time as
  3198. it is possible for admins to configure their servers to perform phone
  3199. number verification directly. More details will follow in a future
  3200. release.</p>
  3201. <h2 id="rolling-back-to-v131"><a class="header" href="#rolling-back-to-v131">Rolling back to v1.3.1</a></h2>
  3202. <p>If you encounter problems with v1.4.0, it should be possible to roll
  3203. back to v1.3.1, subject to the following:</p>
  3204. <ul>
  3205. <li>
  3206. <p>The 'room statistics' engine was heavily reworked in this release
  3207. (see <a href="https://github.com/matrix-org/synapse/pull/5971">#5971</a>),
  3208. including significant changes to the database schema, which are not
  3209. easily reverted. This will cause the room statistics engine to stop
  3210. updating when you downgrade.</p>
  3211. <p>The room statistics are essentially unused in v1.3.1 (in future
  3212. versions of Synapse, they will be used to populate the room
  3213. directory), so there should be no loss of functionality. However,
  3214. the statistics engine will write errors to the logs, which can be
  3215. avoided by setting the following in <code>homeserver.yaml</code>:</p>
  3216. <pre><code class="language-yaml">stats:
  3217. enabled: false
  3218. </code></pre>
  3219. <p>Don't forget to re-enable it when you upgrade again, in preparation
  3220. for its use in the room directory!</p>
  3221. </li>
  3222. </ul>
  3223. <h1 id="upgrading-to-v120"><a class="header" href="#upgrading-to-v120">Upgrading to v1.2.0</a></h1>
  3224. <p>Some counter metrics have been renamed, with the old names deprecated.
  3225. See <a href="metrics-howto.html#renaming-of-metrics--deprecation-of-old-names-in-12">the metrics
  3226. documentation</a>
  3227. for details.</p>
  3228. <h1 id="upgrading-to-v110"><a class="header" href="#upgrading-to-v110">Upgrading to v1.1.0</a></h1>
  3229. <p>Synapse v1.1.0 removes support for older Python and PostgreSQL versions,
  3230. as outlined in <a href="https://matrix.org/blog/2019/04/08/synapse-deprecating-postgres-9-4-and-python-2-x">our deprecation
  3231. notice</a>.</p>
  3232. <h2 id="minimum-python-version"><a class="header" href="#minimum-python-version">Minimum Python Version</a></h2>
  3233. <p>Synapse v1.1.0 has a minimum Python requirement of Python 3.5. Python
  3234. 3.6 or Python 3.7 are recommended as they have improved internal string
  3235. handling, significantly reducing memory usage.</p>
  3236. <p>If you use current versions of the Matrix.org-distributed Debian
  3237. packages or Docker images, action is not required.</p>
  3238. <p>If you install Synapse in a Python virtual environment, please see
  3239. &quot;Upgrading to v0.34.0&quot; for notes on setting up a new virtualenv under
  3240. Python 3.</p>
  3241. <h2 id="minimum-postgresql-version"><a class="header" href="#minimum-postgresql-version">Minimum PostgreSQL Version</a></h2>
  3242. <p>If using PostgreSQL under Synapse, you will need to use PostgreSQL 9.5
  3243. or above. Please see the <a href="https://www.postgresql.org/docs/11/upgrading.html">PostgreSQL
  3244. documentation</a> for
  3245. more details on upgrading your database.</p>
  3246. <h1 id="upgrading-to-v10"><a class="header" href="#upgrading-to-v10">Upgrading to v1.0</a></h1>
  3247. <h2 id="validation-of-tls-certificates"><a class="header" href="#validation-of-tls-certificates">Validation of TLS certificates</a></h2>
  3248. <p>Synapse v1.0 is the first release to enforce validation of TLS
  3249. certificates for the federation API. It is therefore essential that your
  3250. certificates are correctly configured.</p>
  3251. <p>Note, v1.0 installations will also no longer be able to federate with
  3252. servers that have not correctly configured their certificates.</p>
  3253. <p>In rare cases, it may be desirable to disable certificate checking: for
  3254. example, it might be essential to be able to federate with a given
  3255. legacy server in a closed federation. This can be done in one of two
  3256. ways:-</p>
  3257. <ul>
  3258. <li>Configure the global switch <code>federation_verify_certificates</code> to
  3259. <code>false</code>.</li>
  3260. <li>Configure a whitelist of server domains to trust via
  3261. <code>federation_certificate_verification_whitelist</code>.</li>
  3262. </ul>
  3263. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  3264. for more details on these settings.</p>
  3265. <h2 id="email-2"><a class="header" href="#email-2">Email</a></h2>
  3266. <p>When a user requests a password reset, Synapse will send an email to the
  3267. user to confirm the request.</p>
  3268. <p>Previous versions of Synapse delegated the job of sending this email to
  3269. an identity server. If the identity server was somehow malicious or
  3270. became compromised, it would be theoretically possible to hijack an
  3271. account through this means.</p>
  3272. <p>Therefore, by default, Synapse v1.0 will send the confirmation email
  3273. itself. If Synapse is not configured with an SMTP server, password reset
  3274. via email will be disabled.</p>
  3275. <p>To configure an SMTP server for Synapse, modify the configuration
  3276. section headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>,
  3277. <code>smtp_port</code> and <code>notif_from</code> fields filled out. You may also need to set
  3278. <code>smtp_user</code>, <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  3279. <p>If you are absolutely certain that you wish to continue using an
  3280. identity server for password resets, set
  3281. <code>trust_identity_server_for_password_resets</code> to <code>true</code>.</p>
  3282. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  3283. for more details on these settings.</p>
  3284. <h2 id="new-email-templates"><a class="header" href="#new-email-templates">New email templates</a></h2>
  3285. <p>Some new templates have been added to the default template directory for the purpose of
  3286. the homeserver sending its own password reset emails. If you have configured a
  3287. custom <code>template_dir</code> in your Synapse config, these files will need to be added.</p>
  3288. <p><code>password_reset.html</code> and <code>password_reset.txt</code> are HTML and plain text
  3289. templates respectively that contain the contents of what will be emailed
  3290. to the user upon attempting to reset their password via email.
  3291. <code>password_reset_success.html</code> and <code>password_reset_failure.html</code> are HTML
  3292. files that the content of which (assuming no redirect URL is set) will
  3293. be shown to the user after they attempt to click the link in the email
  3294. sent to them.</p>
  3295. <h1 id="upgrading-to-v0990"><a class="header" href="#upgrading-to-v0990">Upgrading to v0.99.0</a></h1>
  3296. <p>Please be aware that, before Synapse v1.0 is released around March 2019,
  3297. you will need to replace any self-signed certificates with those
  3298. verified by a root CA. Information on how to do so can be found at the
  3299. ACME docs.</p>
  3300. <h1 id="upgrading-to-v0340"><a class="header" href="#upgrading-to-v0340">Upgrading to v0.34.0</a></h1>
  3301. <ol>
  3302. <li>
  3303. <p>This release is the first to fully support Python 3. Synapse will
  3304. now run on Python versions 3.5, or 3.6 (as well as 2.7). We
  3305. recommend switching to Python 3, as it has been shown to give
  3306. performance improvements.</p>
  3307. <p>For users who have installed Synapse into a virtualenv, we recommend
  3308. doing this by creating a new virtualenv. For example:</p>
  3309. <pre><code class="language-sh">virtualenv -p python3 ~/synapse/env3
  3310. source ~/synapse/env3/bin/activate
  3311. pip install matrix-synapse
  3312. </code></pre>
  3313. <p>You can then start synapse as normal, having activated the new
  3314. virtualenv:</p>
  3315. <pre><code class="language-sh">cd ~/synapse
  3316. source env3/bin/activate
  3317. synctl start
  3318. </code></pre>
  3319. <p>Users who have installed from distribution packages should see the
  3320. relevant package documentation. See below for notes on Debian
  3321. packages.</p>
  3322. <ul>
  3323. <li>
  3324. <p>When upgrading to Python 3, you <strong>must</strong> make sure that your log
  3325. files are configured as UTF-8, by adding <code>encoding: utf8</code> to the
  3326. <code>RotatingFileHandler</code> configuration (if you have one) in your
  3327. <code>&lt;server&gt;.log.config</code> file. For example, if your <code>log.config</code>
  3328. file contains:</p>
  3329. <pre><code class="language-yaml">handlers:
  3330. file:
  3331. class: logging.handlers.RotatingFileHandler
  3332. formatter: precise
  3333. filename: homeserver.log
  3334. maxBytes: 104857600
  3335. backupCount: 10
  3336. filters: [context]
  3337. console:
  3338. class: logging.StreamHandler
  3339. formatter: precise
  3340. filters: [context]
  3341. </code></pre>
  3342. <p>Then you should update this to be:</p>
  3343. <pre><code class="language-yaml">handlers:
  3344. file:
  3345. class: logging.handlers.RotatingFileHandler
  3346. formatter: precise
  3347. filename: homeserver.log
  3348. maxBytes: 104857600
  3349. backupCount: 10
  3350. filters: [context]
  3351. encoding: utf8
  3352. console:
  3353. class: logging.StreamHandler
  3354. formatter: precise
  3355. filters: [context]
  3356. </code></pre>
  3357. <p>There is no need to revert this change if downgrading to
  3358. Python 2.</p>
  3359. </li>
  3360. </ul>
  3361. <p>We are also making available Debian packages which will run Synapse
  3362. on Python 3. You can switch to these packages with
  3363. <code>apt-get install matrix-synapse-py3</code>, however, please read
  3364. <a href="https://github.com/matrix-org/synapse/blob/release-v0.34.0/debian/NEWS">debian/NEWS</a>
  3365. before doing so. The existing <code>matrix-synapse</code> packages will
  3366. continue to use Python 2 for the time being.</p>
  3367. </li>
  3368. <li>
  3369. <p>This release removes the <code>riot.im</code> from the default list of trusted
  3370. identity servers.</p>
  3371. <p>If <code>riot.im</code> is in your homeserver's list of
  3372. <code>trusted_third_party_id_servers</code>, you should remove it. It was added
  3373. in case a hypothetical future identity server was put there. If you
  3374. don't remove it, users may be unable to deactivate their accounts.</p>
  3375. </li>
  3376. <li>
  3377. <p>This release no longer installs the (unmaintained) Matrix Console
  3378. web client as part of the default installation. It is possible to
  3379. re-enable it by installing it separately and setting the
  3380. <code>web_client_location</code> config option, but please consider switching
  3381. to another client.</p>
  3382. </li>
  3383. </ol>
  3384. <h1 id="upgrading-to-v0337"><a class="header" href="#upgrading-to-v0337">Upgrading to v0.33.7</a></h1>
  3385. <p>This release removes the example email notification templates from
  3386. <code>res/templates</code> (they are now internal to the python package). This
  3387. should only affect you if you (a) deploy your Synapse instance from a
  3388. git checkout or a github snapshot URL, and (b) have email notifications
  3389. enabled.</p>
  3390. <p>If you have email notifications enabled, you should ensure that
  3391. <code>email.template_dir</code> is either configured to point at a directory where
  3392. you have installed customised templates, or leave it unset to use the
  3393. default templates.</p>
  3394. <h1 id="upgrading-to-v0273"><a class="header" href="#upgrading-to-v0273">Upgrading to v0.27.3</a></h1>
  3395. <p>This release expands the anonymous usage stats sent if the opt-in
  3396. <code>report_stats</code> configuration is set to <code>true</code>. We now capture RSS memory
  3397. and cpu use at a very coarse level. This requires administrators to
  3398. install the optional <code>psutil</code> python module.</p>
  3399. <p>We would appreciate it if you could assist by ensuring this module is
  3400. available and <code>report_stats</code> is enabled. This will let us see if
  3401. performance changes to synapse are having an impact to the general
  3402. community.</p>
  3403. <h1 id="upgrading-to-v0150"><a class="header" href="#upgrading-to-v0150">Upgrading to v0.15.0</a></h1>
  3404. <p>If you want to use the new URL previewing API
  3405. (<code>/_matrix/media/r0/preview_url</code>) then you have to explicitly enable it
  3406. in the config and update your dependencies dependencies. See README.rst
  3407. for details.</p>
  3408. <h1 id="upgrading-to-v0110"><a class="header" href="#upgrading-to-v0110">Upgrading to v0.11.0</a></h1>
  3409. <p>This release includes the option to send anonymous usage stats to
  3410. matrix.org, and requires that administrators explicitly opt in or out by
  3411. setting the <code>report_stats</code> option to either <code>true</code> or <code>false</code>.</p>
  3412. <p>We would really appreciate it if you could help our project out by
  3413. reporting anonymized usage statistics from your homeserver. Only very
  3414. basic aggregate data (e.g. number of users) will be reported, but it
  3415. helps us to track the growth of the Matrix community, and helps us to
  3416. make Matrix a success, as well as to convince other networks that they
  3417. should peer with us.</p>
  3418. <h1 id="upgrading-to-v090"><a class="header" href="#upgrading-to-v090">Upgrading to v0.9.0</a></h1>
  3419. <p>Application services have had a breaking API change in this version.</p>
  3420. <p>They can no longer register themselves with a home server using the AS
  3421. HTTP API. This decision was made because a compromised application
  3422. service with free reign to register any regex in effect grants full
  3423. read/write access to the home server if a regex of <code>.*</code> is used. An
  3424. attack where a compromised AS re-registers itself with <code>.*</code> was deemed
  3425. too big of a security risk to ignore, and so the ability to register
  3426. with the HS remotely has been removed.</p>
  3427. <p>It has been replaced by specifying a list of application service
  3428. registrations in <code>homeserver.yaml</code>:</p>
  3429. <pre><code class="language-yaml">app_service_config_files: [&quot;registration-01.yaml&quot;, &quot;registration-02.yaml&quot;]
  3430. </code></pre>
  3431. <p>Where <code>registration-01.yaml</code> looks like:</p>
  3432. <pre><code class="language-yaml">url: &lt;String&gt; # e.g. &quot;https://my.application.service.com&quot;
  3433. as_token: &lt;String&gt;
  3434. hs_token: &lt;String&gt;
  3435. sender_localpart: &lt;String&gt; # This is a new field which denotes the user_id localpart when using the AS token
  3436. namespaces:
  3437. users:
  3438. - exclusive: &lt;Boolean&gt;
  3439. regex: &lt;String&gt; # e.g. &quot;@prefix_.*&quot;
  3440. aliases:
  3441. - exclusive: &lt;Boolean&gt;
  3442. regex: &lt;String&gt;
  3443. rooms:
  3444. - exclusive: &lt;Boolean&gt;
  3445. regex: &lt;String&gt;
  3446. </code></pre>
  3447. <h1 id="upgrading-to-v080"><a class="header" href="#upgrading-to-v080">Upgrading to v0.8.0</a></h1>
  3448. <p>Servers which use captchas will need to add their public key to:</p>
  3449. <pre><code>static/client/register/register_config.js
  3450. window.matrixRegistrationConfig = {
  3451. recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  3452. };
  3453. </code></pre>
  3454. <p>This is required in order to support registration fallback (typically
  3455. used on mobile devices).</p>
  3456. <h1 id="upgrading-to-v070"><a class="header" href="#upgrading-to-v070">Upgrading to v0.7.0</a></h1>
  3457. <p>New dependencies are:</p>
  3458. <ul>
  3459. <li>pydenticon</li>
  3460. <li>simplejson</li>
  3461. <li>syutil</li>
  3462. <li>matrix-angular-sdk</li>
  3463. </ul>
  3464. <p>To pull in these dependencies in a virtual env, run:</p>
  3465. <pre><code>python synapse/python_dependencies.py | xargs -n 1 pip install
  3466. </code></pre>
  3467. <h1 id="upgrading-to-v060"><a class="header" href="#upgrading-to-v060">Upgrading to v0.6.0</a></h1>
  3468. <p>To pull in new dependencies, run:</p>
  3469. <pre><code>python setup.py develop --user
  3470. </code></pre>
  3471. <p>This update includes a change to the database schema. To upgrade you
  3472. first need to upgrade the database by running:</p>
  3473. <pre><code>python scripts/upgrade_db_to_v0.6.0.py &lt;db&gt; &lt;server_name&gt; &lt;signing_key&gt;
  3474. </code></pre>
  3475. <p>Where <code>&lt;db&gt;</code> is the location of the database,
  3476. <code>&lt;server_name&gt;</code> is the server name as specified in the
  3477. synapse configuration, and <code>&lt;signing_key&gt;</code> is the location
  3478. of the signing key as specified in the synapse configuration.</p>
  3479. <p>This may take some time to complete. Failures of signatures and content
  3480. hashes can safely be ignored.</p>
  3481. <h1 id="upgrading-to-v051"><a class="header" href="#upgrading-to-v051">Upgrading to v0.5.1</a></h1>
  3482. <p>Depending on precisely when you installed v0.5.0 you may have ended up
  3483. with a stale release of the reference matrix webclient installed as a
  3484. python module. To uninstall it and ensure you are depending on the
  3485. latest module, please run:</p>
  3486. <pre><code>$ pip uninstall syweb
  3487. </code></pre>
  3488. <h1 id="upgrading-to-v050"><a class="header" href="#upgrading-to-v050">Upgrading to v0.5.0</a></h1>
  3489. <p>The webclient has been split out into a separate repository/package in
  3490. this release. Before you restart your homeserver you will need to pull
  3491. in the webclient package by running:</p>
  3492. <pre><code>python setup.py develop --user
  3493. </code></pre>
  3494. <p>This release completely changes the database schema and so requires
  3495. upgrading it before starting the new version of the homeserver.</p>
  3496. <p>The script &quot;database-prepare-for-0.5.0.sh&quot; should be used to upgrade
  3497. the database. This will save all user information, such as logins and
  3498. profiles, but will otherwise purge the database. This includes messages,
  3499. which rooms the home server was a member of and room alias mappings.</p>
  3500. <p>If you would like to keep your history, please take a copy of your
  3501. database file and ask for help in #matrix:matrix.org. The upgrade
  3502. process is, unfortunately, non trivial and requires human intervention
  3503. to resolve any resulting conflicts during the upgrade process.</p>
  3504. <p>Before running the command the homeserver should be first completely
  3505. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  3506. <blockquote>
  3507. <p>./scripts/database-prepare-for-0.5.0.sh &quot;homeserver.db&quot;</p>
  3508. </blockquote>
  3509. <p>Once this has successfully completed it will be safe to restart the
  3510. homeserver. You may notice that the homeserver takes a few seconds
  3511. longer to restart than usual as it reinitializes the database.</p>
  3512. <p>On startup of the new version, users can either rejoin remote rooms
  3513. using room aliases or by being reinvited. Alternatively, if any other
  3514. homeserver sends a message to a room that the homeserver was previously
  3515. in the local HS will automatically rejoin the room.</p>
  3516. <h1 id="upgrading-to-v040"><a class="header" href="#upgrading-to-v040">Upgrading to v0.4.0</a></h1>
  3517. <p>This release needs an updated syutil version. Run:</p>
  3518. <pre><code>python setup.py develop
  3519. </code></pre>
  3520. <p>You will also need to upgrade your configuration as the signing key
  3521. format has changed. Run:</p>
  3522. <pre><code>python -m synapse.app.homeserver --config-path &lt;CONFIG&gt; --generate-config
  3523. </code></pre>
  3524. <h1 id="upgrading-to-v030"><a class="header" href="#upgrading-to-v030">Upgrading to v0.3.0</a></h1>
  3525. <p>This registration API now closely matches the login API. This introduces
  3526. a bit more backwards and forwards between the HS and the client, but
  3527. this improves the overall flexibility of the API. You can now GET on
  3528. /register to retrieve a list of valid registration flows. Upon choosing
  3529. one, they are submitted in the same way as login, e.g:</p>
  3530. <pre><code>{
  3531. type: m.login.password,
  3532. user: foo,
  3533. password: bar
  3534. }
  3535. </code></pre>
  3536. <p>The default HS supports 2 flows, with and without Identity Server email
  3537. authentication. Enabling captcha on the HS will add in an extra step to
  3538. all flows: <code>m.login.recaptcha</code> which must be completed before you can
  3539. transition to the next stage. There is a new login type:
  3540. <code>m.login.email.identity</code> which contains the <code>threepidCreds</code> key which
  3541. were previously sent in the original register request. For more
  3542. information on this, see the specification.</p>
  3543. <h2 id="web-client"><a class="header" href="#web-client">Web Client</a></h2>
  3544. <p>The VoIP specification has changed between v0.2.0 and v0.3.0. Users
  3545. should refresh any browser tabs to get the latest web client code. Users
  3546. on v0.2.0 of the web client will not be able to call those on v0.3.0 and
  3547. vice versa.</p>
  3548. <h1 id="upgrading-to-v020"><a class="header" href="#upgrading-to-v020">Upgrading to v0.2.0</a></h1>
  3549. <p>The home server now requires setting up of SSL config before it can run.
  3550. To automatically generate default config use:</p>
  3551. <pre><code>$ python synapse/app/homeserver.py \
  3552. --server-name machine.my.domain.name \
  3553. --bind-port 8448 \
  3554. --config-path homeserver.config \
  3555. --generate-config
  3556. </code></pre>
  3557. <p>This config can be edited if desired, for example to specify a different
  3558. SSL certificate to use. Once done you can run the home server using:</p>
  3559. <pre><code>$ python synapse/app/homeserver.py --config-path homeserver.config
  3560. </code></pre>
  3561. <p>See the README.rst for more information.</p>
  3562. <p>Also note that some config options have been renamed, including:</p>
  3563. <ul>
  3564. <li>&quot;host&quot; to &quot;server-name&quot;</li>
  3565. <li>&quot;database&quot; to &quot;database-path&quot;</li>
  3566. <li>&quot;port&quot; to &quot;bind-port&quot; and &quot;unsecure-port&quot;</li>
  3567. </ul>
  3568. <h1 id="upgrading-to-v001"><a class="header" href="#upgrading-to-v001">Upgrading to v0.0.1</a></h1>
  3569. <p>This release completely changes the database schema and so requires
  3570. upgrading it before starting the new version of the homeserver.</p>
  3571. <p>The script &quot;database-prepare-for-0.0.1.sh&quot; should be used to upgrade
  3572. the database. This will save all user information, such as logins and
  3573. profiles, but will otherwise purge the database. This includes messages,
  3574. which rooms the home server was a member of and room alias mappings.</p>
  3575. <p>Before running the command the homeserver should be first completely
  3576. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  3577. <blockquote>
  3578. <p>./scripts/database-prepare-for-0.0.1.sh &quot;homeserver.db&quot;</p>
  3579. </blockquote>
  3580. <p>Once this has successfully completed it will be safe to restart the
  3581. homeserver. You may notice that the homeserver takes a few seconds
  3582. longer to restart than usual as it reinitializes the database.</p>
  3583. <p>On startup of the new version, users can either rejoin remote rooms
  3584. using room aliases or by being reinvited. Alternatively, if any other
  3585. homeserver sends a message to a room that the homeserver was previously
  3586. in the local HS will automatically rejoin the room.</p>
  3587. <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>
  3588. <p>Federation is the process by which users on different servers can participate
  3589. in the same room. For this to work, those other servers must be able to contact
  3590. yours to send messages.</p>
  3591. <p>The <code>server_name</code> configured in the Synapse configuration file (often
  3592. <code>homeserver.yaml</code>) defines how resources (users, rooms, etc.) will be
  3593. identified (eg: <code>@user:example.com</code>, <code>#room:example.com</code>). By default,
  3594. it is also the domain that other servers will use to try to reach your
  3595. server (via port 8448). This is easy to set up and will work provided
  3596. you set the <code>server_name</code> to match your machine's public DNS hostname.</p>
  3597. <p>For this default configuration to work, you will need to listen for TLS
  3598. connections on port 8448. The preferred way to do that is by using a
  3599. reverse proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions
  3600. on how to correctly set one up.</p>
  3601. <p>In some cases you might not want to run Synapse on the machine that has
  3602. the <code>server_name</code> as its public DNS hostname, or you might want federation
  3603. traffic to use a different port than 8448. For example, you might want to
  3604. have your user names look like <code>@user:example.com</code>, but you want to run
  3605. Synapse on <code>synapse.example.com</code> on port 443. This can be done using
  3606. delegation, which allows an admin to control where federation traffic should
  3607. be sent. See <a href="delegate.html">the delegation documentation</a> for instructions on how to set this up.</p>
  3608. <p>Once federation has been configured, you should be able to join a room over
  3609. federation. A good place to start is <code>#synapse:matrix.org</code> - a room for
  3610. Synapse admins.</p>
  3611. <h2 id="troubleshooting-3"><a class="header" href="#troubleshooting-3">Troubleshooting</a></h2>
  3612. <p>You can use the <a href="https://matrix.org/federationtester">federation tester</a>
  3613. to check if your homeserver is configured correctly. Alternatively try the
  3614. <a href="https://matrix.org/federationtester/api/report?server_name=DOMAIN">JSON API used by the federation tester</a>.
  3615. Note that you'll have to modify this URL to replace <code>DOMAIN</code> with your
  3616. <code>server_name</code>. Hitting the API directly provides extra detail.</p>
  3617. <p>The typical failure mode for federation is that when the server tries to join
  3618. a room, it is rejected with &quot;401: Unauthorized&quot;. Generally this means that other
  3619. servers in the room could not access yours. (Joining a room over federation is
  3620. a complicated dance which requires connections in both directions).</p>
  3621. <p>Another common problem is that people on other servers can't join rooms that
  3622. you invite them to. This can be caused by an incorrectly-configured reverse
  3623. proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions on how
  3624. to correctly configure a reverse proxy.</p>
  3625. <h3 id="known-issues"><a class="header" href="#known-issues">Known issues</a></h3>
  3626. <p><strong>HTTP <code>308 Permanent Redirect</code> redirects are not followed</strong>: Due to missing features
  3627. in the HTTP library used by Synapse, 308 redirects are currently not followed by
  3628. federating servers, which can cause <code>M_UNKNOWN</code> or <code>401 Unauthorized</code> errors. This
  3629. may affect users who are redirecting apex-to-www (e.g. <code>example.com</code> -&gt; <code>www.example.com</code>),
  3630. and especially users of the Kubernetes <em>Nginx Ingress</em> module, which uses 308 redirect
  3631. codes by default. For those Kubernetes users, <a href="https://stackoverflow.com/a/52617528/5096871">this Stackoverflow post</a>
  3632. might be helpful. For other users, switching to a <code>301 Moved Permanently</code> code may be
  3633. an option. 308 redirect codes will be supported properly in a future
  3634. release of Synapse.</p>
  3635. <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>
  3636. <p>If you want to get up and running quickly with a trio of homeservers in a
  3637. private federation, there is a script in the <code>demo</code> directory. This is mainly
  3638. useful just for development purposes. See
  3639. <a href="https://matrix-org.github.io/synapse/develop/development/demo.html">demo scripts</a>.</p>
  3640. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuration-2"><a class="header" href="#configuration-2">Configuration</a></h1>
  3641. <p>This section contains information on tweaking Synapse via the various options in the configuration file. A configuration
  3642. file should have been generated when you <a href="usage/configuration/../../setup/installation.html">installed Synapse</a>.</p>
  3643. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuring-synapse"><a class="header" href="#configuring-synapse">Configuring Synapse</a></h1>
  3644. <p>This is intended as a guide to the Synapse configuration. The behavior of a Synapse instance can be modified
  3645. through the many configuration settings documented here — each config option is explained,
  3646. including what the default is, how to change the default and what sort of behaviour the setting governs.
  3647. Also included is an example configuration for each setting. If you don't want to spend a lot of time
  3648. thinking about options, the config as generated sets sensible defaults for all values. Do note however that the
  3649. database defaults to SQLite, which is not recommended for production usage. You can read more on this subject
  3650. <a href="usage/configuration/../../setup/installation.html#using-postgresql">here</a>.</p>
  3651. <h2 id="config-conventions"><a class="header" href="#config-conventions">Config Conventions</a></h2>
  3652. <p>Configuration options that take a time period can be set using a number
  3653. followed by a letter. Letters have the following meanings:</p>
  3654. <ul>
  3655. <li><code>s</code> = second</li>
  3656. <li><code>m</code> = minute</li>
  3657. <li><code>h</code> = hour</li>
  3658. <li><code>d</code> = day</li>
  3659. <li><code>w</code> = week</li>
  3660. <li><code>y</code> = year</li>
  3661. </ul>
  3662. <p>For example, setting <code>redaction_retention_period: 5m</code> would remove redacted
  3663. messages from the database after 5 minutes, rather than 5 months.</p>
  3664. <p>In addition, configuration options referring to size use the following suffixes:</p>
  3665. <ul>
  3666. <li><code>K</code> = KiB, or 1024 bytes</li>
  3667. <li><code>M</code> = MiB, or 1,048,576 bytes</li>
  3668. <li><code>G</code> = GiB, or 1,073,741,824 bytes</li>
  3669. <li><code>T</code> = TiB, or 1,099,511,627,776 bytes</li>
  3670. </ul>
  3671. <p>For example, setting <code>max_avatar_size: 10M</code> means that Synapse will not accept files larger than 10,485,760 bytes
  3672. for a user avatar.</p>
  3673. <h3 id="yaml"><a class="header" href="#yaml">YAML</a></h3>
  3674. <p>The configuration file is a <a href="https://yaml.org/">YAML</a> file, which means that certain syntax rules
  3675. apply if you want your config file to be read properly. A few helpful things to know:</p>
  3676. <ul>
  3677. <li>
  3678. <p><code>#</code> before any option in the config will comment out that setting and either a default (if available) will
  3679. be applied or Synapse will ignore the setting. Thus, in example #1 below, the setting will be read and
  3680. applied, but in example #2 the setting will not be read and a default will be applied.</p>
  3681. <p>Example #1:</p>
  3682. <pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
  3683. </code></pre>
  3684. <p>Example #2:</p>
  3685. <pre><code class="language-yaml">#pid_file: DATADIR/homeserver.pid
  3686. </code></pre>
  3687. </li>
  3688. <li>
  3689. <p>Indentation matters! The indentation before a setting
  3690. will determine whether a given setting is read as part of another
  3691. setting, or considered on its own. Thus, in example #1, the <code>enabled</code> setting
  3692. is read as a sub-option of the <code>presence</code> setting, and will be properly applied.</p>
  3693. <p>However, the lack of indentation before the <code>enabled</code> setting in example #2 means
  3694. that when reading the config, Synapse will consider both <code>presence</code> and <code>enabled</code> as
  3695. different settings. In this case, <code>presence</code> has no value, and thus a default applied, and <code>enabled</code>
  3696. is an option that Synapse doesn't recognize and thus ignores.</p>
  3697. <p>Example #1:</p>
  3698. <pre><code class="language-yaml">presence:
  3699. enabled: false
  3700. </code></pre>
  3701. <p>Example #2:</p>
  3702. <pre><code class="language-yaml">presence:
  3703. enabled: false
  3704. </code></pre>
  3705. <p>In this manual, all top-level settings (ones with no indentation) are identified
  3706. at the beginning of their section (i.e. &quot;### <code>example_setting</code>&quot;) and
  3707. the sub-options, if any, are identified and listed in the body of the section.
  3708. In addition, each setting has an example of its usage, with the proper indentation
  3709. shown.</p>
  3710. </li>
  3711. </ul>
  3712. <h2 id="modules"><a class="header" href="#modules">Modules</a></h2>
  3713. <p>Server admins can expand Synapse's functionality with external modules.</p>
  3714. <p>See <a href="usage/configuration/../../modules/index.html">here</a> for more
  3715. documentation on how to configure or create custom modules for Synapse.</p>
  3716. <hr />
  3717. <h3 id="modules-1"><a class="header" href="#modules-1"><code>modules</code></a></h3>
  3718. <p>Use the <code>module</code> sub-option to add modules under this option to extend functionality.
  3719. The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
  3720. for the <code>module</code>.</p>
  3721. <p>Defaults to none.</p>
  3722. <p>Example configuration:</p>
  3723. <pre><code class="language-yaml">modules:
  3724. - module: my_super_module.MySuperClass
  3725. config:
  3726. do_thing: true
  3727. - module: my_other_super_module.SomeClass
  3728. config: {}
  3729. </code></pre>
  3730. <hr />
  3731. <h2 id="server"><a class="header" href="#server">Server</a></h2>
  3732. <p>Define your homeserver name and other base options.</p>
  3733. <hr />
  3734. <h3 id="server_name"><a class="header" href="#server_name"><code>server_name</code></a></h3>
  3735. <p>This sets the public-facing domain of the server.</p>
  3736. <p>The <code>server_name</code> name will appear at the end of usernames and room addresses
  3737. created on your server. For example if the <code>server_name</code> was example.com,
  3738. usernames on your server would be in the format <code>@user:example.com</code></p>
  3739. <p>In most cases you should avoid using a matrix specific subdomain such as
  3740. matrix.example.com or synapse.example.com as the <code>server_name</code> for the same
  3741. reasons you wouldn't use user@email.example.com as your email address.
  3742. See <a href="usage/configuration/../../delegate.html">here</a>
  3743. for information on how to host Synapse on a subdomain while preserving
  3744. a clean <code>server_name</code>.</p>
  3745. <p>The <code>server_name</code> cannot be changed later so it is important to
  3746. configure this correctly before you start Synapse. It should be all
  3747. lowercase and may contain an explicit port.</p>
  3748. <p>There is no default for this option.</p>
  3749. <p>Example configuration #1:</p>
  3750. <pre><code class="language-yaml">server_name: matrix.org
  3751. </code></pre>
  3752. <p>Example configuration #2:</p>
  3753. <pre><code class="language-yaml">server_name: localhost:8080
  3754. </code></pre>
  3755. <hr />
  3756. <h3 id="pid_file"><a class="header" href="#pid_file"><code>pid_file</code></a></h3>
  3757. <p>When running Synapse as a daemon, the file to store the pid in. Defaults to none.</p>
  3758. <p>Example configuration:</p>
  3759. <pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
  3760. </code></pre>
  3761. <hr />
  3762. <h3 id="web_client_location"><a class="header" href="#web_client_location"><code>web_client_location</code></a></h3>
  3763. <p>The absolute URL to the web client which <code>/</code> will redirect to. Defaults to none.</p>
  3764. <p>Example configuration:</p>
  3765. <pre><code class="language-yaml">web_client_location: https://riot.example.com/
  3766. </code></pre>
  3767. <hr />
  3768. <h3 id="public_baseurl"><a class="header" href="#public_baseurl"><code>public_baseurl</code></a></h3>
  3769. <p>The public-facing base URL that clients use to access this Homeserver (not
  3770. including _matrix/...). This is the same URL a user might enter into the
  3771. 'Custom Homeserver URL' field on their client. If you use Synapse with a
  3772. reverse proxy, this should be the URL to reach Synapse via the proxy.
  3773. Otherwise, it should be the URL to reach Synapse's client HTTP listener (see
  3774. <a href="usage/configuration/config_documentation.html#listeners">'listeners'</a> below).</p>
  3775. <p>Defaults to <code>https://&lt;server_name&gt;/</code>.</p>
  3776. <p>Example configuration:</p>
  3777. <pre><code class="language-yaml">public_baseurl: https://example.com/
  3778. </code></pre>
  3779. <hr />
  3780. <h3 id="serve_server_wellknown"><a class="header" href="#serve_server_wellknown"><code>serve_server_wellknown</code></a></h3>
  3781. <p>By default, other servers will try to reach our server on port 8448, which can
  3782. be inconvenient in some environments.</p>
  3783. <p>Provided <code>https://&lt;server_name&gt;/</code> on port 443 is routed to Synapse, this
  3784. option configures Synapse to serve a file at <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>.
  3785. This will tell other servers to send traffic to port 443 instead.</p>
  3786. <p>This option currently defaults to false.</p>
  3787. <p>See <a href="usage/configuration/../../delegate.html">Delegation of incoming federation traffic</a> for more
  3788. information.</p>
  3789. <p>Example configuration:</p>
  3790. <pre><code class="language-yaml">serve_server_wellknown: true
  3791. </code></pre>
  3792. <hr />
  3793. <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>
  3794. <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>.
  3795. 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>
  3796. <p>If this option is provided, it parses the given yaml to json and
  3797. serves it on <code>/.well-known/matrix/client</code> endpoint
  3798. alongside the standard properties.</p>
  3799. <p><em>Added in Synapse 1.62.0.</em></p>
  3800. <p>Example configuration:</p>
  3801. <pre><code class="language-yaml">extra_well_known_client_content :
  3802. option1: value1
  3803. option2: value2
  3804. </code></pre>
  3805. <hr />
  3806. <h3 id="soft_file_limit"><a class="header" href="#soft_file_limit"><code>soft_file_limit</code></a></h3>
  3807. <p>Set the soft limit on the number of file descriptors synapse can use.
  3808. Zero is used to indicate synapse should set the soft limit to the hard limit.
  3809. Defaults to 0.</p>
  3810. <p>Example configuration:</p>
  3811. <pre><code class="language-yaml">soft_file_limit: 3
  3812. </code></pre>
  3813. <hr />
  3814. <h3 id="presence"><a class="header" href="#presence"><code>presence</code></a></h3>
  3815. <p>Presence tracking allows users to see the state (e.g online/offline)
  3816. of other local and remote users. Set the <code>enabled</code> sub-option to false to
  3817. disable presence tracking on this homeserver. Defaults to true.
  3818. This option replaces the previous top-level 'use_presence' option.</p>
  3819. <p>Example configuration:</p>
  3820. <pre><code class="language-yaml">presence:
  3821. enabled: false
  3822. </code></pre>
  3823. <hr />
  3824. <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>
  3825. <p>Whether to require authentication to retrieve profile data (avatars, display names) of other
  3826. users through the client API. Defaults to false. Note that profile data is also available
  3827. via the federation API, unless <code>allow_profile_lookup_over_federation</code> is set to false.</p>
  3828. <p>Example configuration:</p>
  3829. <pre><code class="language-yaml">require_auth_for_profile_requests: true
  3830. </code></pre>
  3831. <hr />
  3832. <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>
  3833. <p>Use this option to require a user to share a room with another user in order
  3834. to retrieve their profile information. Only checked on Client-Server
  3835. requests. Profile requests from other servers should be checked by the
  3836. requesting server. Defaults to false.</p>
  3837. <p>Example configuration:</p>
  3838. <pre><code class="language-yaml">limit_profile_requests_to_users_who_share_rooms: true
  3839. </code></pre>
  3840. <hr />
  3841. <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>
  3842. <p>Use this option to prevent a user's profile data from being retrieved and
  3843. displayed in a room until they have joined it. By default, a user's
  3844. profile data is included in an invite event, regardless of the values
  3845. of the above two settings, and whether or not the users share a server.
  3846. Defaults to true.</p>
  3847. <p>Example configuration:</p>
  3848. <pre><code class="language-yaml">include_profile_data_on_invite: false
  3849. </code></pre>
  3850. <hr />
  3851. <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>
  3852. <p>If set to true, removes the need for authentication to access the server's
  3853. public rooms directory through the client API, meaning that anyone can
  3854. query the room directory. Defaults to false.</p>
  3855. <p>Example configuration:</p>
  3856. <pre><code class="language-yaml">allow_public_rooms_without_auth: true
  3857. </code></pre>
  3858. <hr />
  3859. <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>
  3860. <p>If set to true, allows any other homeserver to fetch the server's public
  3861. rooms directory via federation. Defaults to false.</p>
  3862. <p>Example configuration:</p>
  3863. <pre><code class="language-yaml">allow_public_rooms_over_federation: true
  3864. </code></pre>
  3865. <hr />
  3866. <h3 id="default_room_version"><a class="header" href="#default_room_version"><code>default_room_version</code></a></h3>
  3867. <p>The default room version for newly created rooms on this server.</p>
  3868. <p>Known room versions are listed <a href="https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions">here</a></p>
  3869. <p>For example, for room version 1, <code>default_room_version</code> should be set
  3870. to &quot;1&quot;.</p>
  3871. <p>Currently defaults to <a href="https://spec.matrix.org/v1.5/rooms/v10/">&quot;10&quot;</a>.</p>
  3872. <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>
  3873. <p>Example configuration:</p>
  3874. <pre><code class="language-yaml">default_room_version: &quot;8&quot;
  3875. </code></pre>
  3876. <hr />
  3877. <h3 id="gc_thresholds"><a class="header" href="#gc_thresholds"><code>gc_thresholds</code></a></h3>
  3878. <p>The garbage collection threshold parameters to pass to <code>gc.set_threshold</code>, if defined.
  3879. Defaults to none.</p>
  3880. <p>Example configuration:</p>
  3881. <pre><code class="language-yaml">gc_thresholds: [700, 10, 10]
  3882. </code></pre>
  3883. <hr />
  3884. <h3 id="gc_min_interval"><a class="header" href="#gc_min_interval"><code>gc_min_interval</code></a></h3>
  3885. <p>The minimum time in seconds between each GC for a generation, regardless of
  3886. the GC thresholds. This ensures that we don't do GC too frequently. A value of <code>[1s, 10s, 30s]</code>
  3887. indicates that a second must pass between consecutive generation 0 GCs, etc.</p>
  3888. <p>Defaults to <code>[1s, 10s, 30s]</code>.</p>
  3889. <p>Example configuration:</p>
  3890. <pre><code class="language-yaml">gc_min_interval: [0.5s, 30s, 1m]
  3891. </code></pre>
  3892. <hr />
  3893. <h3 id="filter_timeline_limit"><a class="header" href="#filter_timeline_limit"><code>filter_timeline_limit</code></a></h3>
  3894. <p>Set the limit on the returned events in the timeline in the get
  3895. and sync operations. Defaults to 100. A value of -1 means no upper limit.</p>
  3896. <p>Example configuration:</p>
  3897. <pre><code class="language-yaml">filter_timeline_limit: 5000
  3898. </code></pre>
  3899. <hr />
  3900. <h3 id="block_non_admin_invites"><a class="header" href="#block_non_admin_invites"><code>block_non_admin_invites</code></a></h3>
  3901. <p>Whether room invites to users on this server should be blocked
  3902. (except those sent by local server admins). Defaults to false.</p>
  3903. <p>Example configuration:</p>
  3904. <pre><code class="language-yaml">block_non_admin_invites: true
  3905. </code></pre>
  3906. <hr />
  3907. <h3 id="enable_search"><a class="header" href="#enable_search"><code>enable_search</code></a></h3>
  3908. <p>If set to false, new messages will not be indexed for searching and users
  3909. will receive errors when searching for messages. Defaults to true.</p>
  3910. <p>Example configuration:</p>
  3911. <pre><code class="language-yaml">enable_search: false
  3912. </code></pre>
  3913. <hr />
  3914. <h3 id="ip_range_blacklist"><a class="header" href="#ip_range_blacklist"><code>ip_range_blacklist</code></a></h3>
  3915. <p>This option prevents outgoing requests from being sent to the specified blacklisted IP address
  3916. CIDR ranges. If this option is not specified then it defaults to private IP
  3917. address ranges (see the example below).</p>
  3918. <p>The blacklist applies to the outbound requests for federation, identity servers,
  3919. push servers, and for checking key validity for third-party invite events.</p>
  3920. <p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  3921. listed here, since they correspond to unroutable addresses.)</p>
  3922. <p>This option replaces <code>federation_ip_range_blacklist</code> in Synapse v1.25.0.</p>
  3923. <p>Note: The value is ignored when an HTTP proxy is in use.</p>
  3924. <p>Example configuration:</p>
  3925. <pre><code class="language-yaml">ip_range_blacklist:
  3926. - '127.0.0.0/8'
  3927. - '10.0.0.0/8'
  3928. - '172.16.0.0/12'
  3929. - '192.168.0.0/16'
  3930. - '100.64.0.0/10'
  3931. - '192.0.0.0/24'
  3932. - '169.254.0.0/16'
  3933. - '192.88.99.0/24'
  3934. - '198.18.0.0/15'
  3935. - '192.0.2.0/24'
  3936. - '198.51.100.0/24'
  3937. - '203.0.113.0/24'
  3938. - '224.0.0.0/4'
  3939. - '::1/128'
  3940. - 'fe80::/10'
  3941. - 'fc00::/7'
  3942. - '2001:db8::/32'
  3943. - 'ff00::/8'
  3944. - 'fec0::/10'
  3945. </code></pre>
  3946. <hr />
  3947. <h3 id="ip_range_whitelist"><a class="header" href="#ip_range_whitelist"><code>ip_range_whitelist</code></a></h3>
  3948. <p>List of IP address CIDR ranges that should be allowed for federation,
  3949. identity servers, push servers, and for checking key validity for
  3950. third-party invite events. This is useful for specifying exceptions to
  3951. wide-ranging blacklisted target IP ranges - e.g. for communication with
  3952. a push server only visible in your network.</p>
  3953. <p>This whitelist overrides <code>ip_range_blacklist</code> and defaults to an empty
  3954. list.</p>
  3955. <p>Example configuration:</p>
  3956. <pre><code class="language-yaml">ip_range_whitelist:
  3957. - '192.168.1.1'
  3958. </code></pre>
  3959. <hr />
  3960. <h3 id="listeners"><a class="header" href="#listeners"><code>listeners</code></a></h3>
  3961. <p>List of ports that Synapse should listen on, their purpose and their
  3962. configuration.</p>
  3963. <p>Sub-options for each listener include:</p>
  3964. <ul>
  3965. <li>
  3966. <p><code>port</code>: the TCP port to bind to.</p>
  3967. </li>
  3968. <li>
  3969. <p><code>tag</code>: An alias for the port in the logger name. If set the tag is logged instead
  3970. of the port. Default to <code>None</code>, is optional and only valid for listener with <code>type: http</code>.
  3971. See the docs <a href="usage/configuration/../administration/request_log.html">request log format</a>.</p>
  3972. </li>
  3973. <li>
  3974. <p><code>bind_addresses</code>: a list of local addresses to listen on. The default is
  3975. 'all local interfaces'.</p>
  3976. </li>
  3977. <li>
  3978. <p><code>type</code>: the type of listener. Normally <code>http</code>, but other valid options are:</p>
  3979. <ul>
  3980. <li>
  3981. <p><code>manhole</code>: (see the docs <a href="usage/configuration/../../manhole.html">here</a>),</p>
  3982. </li>
  3983. <li>
  3984. <p><code>metrics</code>: (see the docs <a href="usage/configuration/../../metrics-howto.html">here</a>),</p>
  3985. </li>
  3986. </ul>
  3987. </li>
  3988. <li>
  3989. <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>
  3990. </li>
  3991. <li>
  3992. <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
  3993. behind a <a href="usage/configuration/../../reverse_proxy.html">reverse-proxy</a>.</p>
  3994. </li>
  3995. <li>
  3996. <p><code>request_id_header</code>: The header extracted from each incoming request that is
  3997. used as the basis for the request ID. The request ID is used in
  3998. <a href="usage/configuration/../administration/request_log.html#request-log-format">logs</a> and tracing to
  3999. correlate and match up requests. When unset, Synapse will automatically
  4000. generate sequential request IDs. This option is useful when Synapse is behind
  4001. a <a href="usage/configuration/../../reverse_proxy.html">reverse-proxy</a>.</p>
  4002. <p><em>Added in Synapse 1.68.0.</em></p>
  4003. </li>
  4004. <li>
  4005. <p><code>resources</code>: Only valid for an 'http' listener. A list of resources to host
  4006. on this port. Sub-options for each resource are:</p>
  4007. <ul>
  4008. <li>
  4009. <p><code>names</code>: a list of names of HTTP resources. See below for a list of valid resource names.</p>
  4010. </li>
  4011. <li>
  4012. <p><code>compress</code>: set to true to enable gzip compression on HTTP bodies for this resource. This is currently only supported with the
  4013. <code>client</code>, <code>consent</code>, <code>metrics</code> and <code>federation</code> resources.</p>
  4014. </li>
  4015. </ul>
  4016. </li>
  4017. <li>
  4018. <p><code>additional_resources</code>: Only valid for an 'http' listener. A map of
  4019. additional endpoints which should be loaded via dynamic modules.</p>
  4020. </li>
  4021. </ul>
  4022. <p>Unix socket support (<em>Added in Synapse 1.89.0</em>):</p>
  4023. <ul>
  4024. <li><code>path</code>: A path and filename for a Unix socket. Make sure it is located in a
  4025. directory with read and write permissions, and that it already exists (the directory
  4026. will not be created). Defaults to <code>None</code>.
  4027. <ul>
  4028. <li><strong>Note</strong>: The use of both <code>path</code> and <code>port</code> options for the same <code>listener</code> is not
  4029. compatible.</li>
  4030. <li>The <code>x_forwarded</code> option defaults to true when using Unix sockets and can be omitted.</li>
  4031. <li>Other options that would not make sense to use with a UNIX socket, such as
  4032. <code>bind_addresses</code> and <code>tls</code> will be ignored and can be removed.</li>
  4033. </ul>
  4034. </li>
  4035. <li><code>mode</code>: The file permissions to set on the UNIX socket. Defaults to <code>666</code></li>
  4036. <li><strong>Note:</strong> Must be set as <code>type: http</code> (does not support <code>metrics</code> and <code>manhole</code>).
  4037. Also make sure that <code>metrics</code> is not included in <code>resources</code> -&gt; <code>names</code></li>
  4038. </ul>
  4039. <p>Valid resource names are:</p>
  4040. <ul>
  4041. <li>
  4042. <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>
  4043. </li>
  4044. <li>
  4045. <p><code>consent</code>: user consent forms (/_matrix/consent). See <a href="usage/configuration/../../consent_tracking.html">here</a> for more.</p>
  4046. </li>
  4047. <li>
  4048. <p><code>federation</code>: the server-server API (/_matrix/federation). Also implies <code>media</code>, <code>keys</code>, <code>openid</code></p>
  4049. </li>
  4050. <li>
  4051. <p><code>keys</code>: the key discovery API (/_matrix/key).</p>
  4052. </li>
  4053. <li>
  4054. <p><code>media</code>: the media API (/_matrix/media).</p>
  4055. </li>
  4056. <li>
  4057. <p><code>metrics</code>: the metrics interface. See <a href="usage/configuration/../../metrics-howto.html">here</a>. (Not compatible with Unix sockets)</p>
  4058. </li>
  4059. <li>
  4060. <p><code>openid</code>: OpenID authentication. See <a href="usage/configuration/../../openid.html">here</a>.</p>
  4061. </li>
  4062. <li>
  4063. <p><code>replication</code>: the HTTP replication API (/_synapse/replication). See <a href="usage/configuration/../../workers.html">here</a>.</p>
  4064. </li>
  4065. <li>
  4066. <p><code>static</code>: static resources under synapse/static (/_matrix/static). (Mostly useful for 'fallback authentication'.)</p>
  4067. </li>
  4068. <li>
  4069. <p><code>health</code>: the <a href="usage/configuration/../../reverse_proxy.html#health-check-endpoint">health check endpoint</a>. This endpoint
  4070. is by default active for all other resources and does not have to be activated separately.
  4071. This is only useful if you want to use the health endpoint explicitly on a dedicated port or
  4072. for <a href="usage/configuration/../../workers.html">workers</a> and containers without listener e.g.
  4073. <a href="usage/configuration/../../workers.html#notifying-application-services">application services</a>.</p>
  4074. </li>
  4075. </ul>
  4076. <p>Example configuration #1:</p>
  4077. <pre><code class="language-yaml">listeners:
  4078. # TLS-enabled listener: for when matrix traffic is sent directly to synapse.
  4079. #
  4080. # (Note that you will also need to give Synapse a TLS key and certificate: see the TLS section
  4081. # below.)
  4082. #
  4083. - port: 8448
  4084. type: http
  4085. tls: true
  4086. resources:
  4087. - names: [client, federation]
  4088. </code></pre>
  4089. <p>Example configuration #2:</p>
  4090. <pre><code class="language-yaml">listeners:
  4091. # Insecure HTTP listener: for when matrix traffic passes through a reverse proxy
  4092. # that unwraps TLS.
  4093. #
  4094. # If you plan to use a reverse proxy, please see
  4095. # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  4096. #
  4097. - port: 8008
  4098. tls: false
  4099. type: http
  4100. x_forwarded: true
  4101. bind_addresses: ['::1', '127.0.0.1']
  4102. resources:
  4103. - names: [client, federation]
  4104. compress: false
  4105. # example additional_resources:
  4106. additional_resources:
  4107. &quot;/_matrix/my/custom/endpoint&quot;:
  4108. module: my_module.CustomRequestHandler
  4109. config: {}
  4110. # Turn on the twisted ssh manhole service on localhost on the given
  4111. # port.
  4112. - port: 9000
  4113. bind_addresses: ['::1', '127.0.0.1']
  4114. type: manhole
  4115. </code></pre>
  4116. <p>Example configuration #3:</p>
  4117. <pre><code class="language-yaml">listeners:
  4118. # Unix socket listener: Ideal for Synapse deployments behind a reverse proxy, offering
  4119. # lightweight interprocess communication without TCP/IP overhead, avoid port
  4120. # conflicts, and providing enhanced security through system file permissions.
  4121. #
  4122. # Note that x_forwarded will default to true, when using a UNIX socket. Please see
  4123. # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  4124. #
  4125. - path: /var/run/synapse/main_public.sock
  4126. type: http
  4127. resources:
  4128. - names: [client, federation]
  4129. </code></pre>
  4130. <hr />
  4131. <h3 id="manhole_settings"><a class="header" href="#manhole_settings"><code>manhole_settings</code></a></h3>
  4132. <p>Connection settings for the manhole. You can find more information
  4133. on the manhole <a href="usage/configuration/../../manhole.html">here</a>. Manhole sub-options include:</p>
  4134. <ul>
  4135. <li><code>username</code> : the username for the manhole. This defaults to 'matrix'.</li>
  4136. <li><code>password</code>: The password for the manhole. This defaults to 'rabbithole'.</li>
  4137. <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.
  4138. If these are left unset, then hardcoded and non-secret keys are used,
  4139. which could allow traffic to be intercepted if sent over a public network.</li>
  4140. </ul>
  4141. <p>Example configuration:</p>
  4142. <pre><code class="language-yaml">manhole_settings:
  4143. username: manhole
  4144. password: mypassword
  4145. ssh_priv_key_path: CONFDIR/id_rsa
  4146. ssh_pub_key_path: CONFDIR/id_rsa.pub
  4147. </code></pre>
  4148. <hr />
  4149. <h3 id="dummy_events_threshold"><a class="header" href="#dummy_events_threshold"><code>dummy_events_threshold</code></a></h3>
  4150. <p>Forward extremities can build up in a room due to networking delays between
  4151. homeservers. Once this happens in a large room, calculation of the state of
  4152. that room can become quite expensive. To mitigate this, once the number of
  4153. forward extremities reaches a given threshold, Synapse will send an
  4154. <code>org.matrix.dummy_event</code> event, which will reduce the forward extremities
  4155. in the room.</p>
  4156. <p>This setting defines the threshold (i.e. number of forward extremities in the room) at which dummy events are sent.
  4157. The default value is 10.</p>
  4158. <p>Example configuration:</p>
  4159. <pre><code class="language-yaml">dummy_events_threshold: 5
  4160. </code></pre>
  4161. <hr />
  4162. <h3 id="delete_stale_devices_after"><a class="header" href="#delete_stale_devices_after"><code>delete_stale_devices_after</code></a></h3>
  4163. <p>An optional duration. If set, Synapse will run a daily background task to log out and
  4164. delete any device that hasn't been accessed for more than the specified amount of time.</p>
  4165. <p>Defaults to no duration, which means devices are never pruned.</p>
  4166. <p><strong>Note:</strong> This task will always run on the main process, regardless of the value of
  4167. <code>run_background_tasks_on</code>. This is due to workers currently not having the ability to
  4168. delete devices.</p>
  4169. <p>Example configuration:</p>
  4170. <pre><code class="language-yaml">delete_stale_devices_after: 1y
  4171. </code></pre>
  4172. <hr />
  4173. <h3 id="email-3"><a class="header" href="#email-3"><code>email</code></a></h3>
  4174. <p>Configuration for sending emails from Synapse.</p>
  4175. <p>Server admins can configure custom templates for email content. See
  4176. <a href="usage/configuration/../../templates.html">here</a> for more information.</p>
  4177. <p>This setting has the following sub-options:</p>
  4178. <ul>
  4179. <li>
  4180. <p><code>smtp_host</code>: The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.</p>
  4181. </li>
  4182. <li>
  4183. <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>
  4184. <p><em>Changed in Synapse 1.64.0:</em> the default port is now aware of <code>force_tls</code>.</p>
  4185. </li>
  4186. <li>
  4187. <p><code>smtp_user</code> and <code>smtp_pass</code>: Username/password for authentication to the SMTP server. By default, no
  4188. authentication is attempted.</p>
  4189. </li>
  4190. <li>
  4191. <p><code>force_tls</code>: By default, Synapse connects over plain text and then optionally upgrades
  4192. to TLS via STARTTLS. If this option is set to true, TLS is used from the start (Implicit TLS),
  4193. and the option <code>require_transport_security</code> is ignored.
  4194. It is recommended to enable this if supported by your mail server.</p>
  4195. <p><em>New in Synapse 1.64.0.</em></p>
  4196. </li>
  4197. <li>
  4198. <p><code>require_transport_security</code>: Set to true to require TLS transport security for SMTP.
  4199. By default, Synapse will connect over plain text, and will then switch to
  4200. TLS via STARTTLS <em>if the SMTP server supports it</em>. If this option is set,
  4201. Synapse will refuse to connect unless the server supports STARTTLS.</p>
  4202. </li>
  4203. <li>
  4204. <p><code>enable_tls</code>: By default, if the server supports TLS, it will be used, and the server
  4205. must present a certificate that is valid for 'smtp_host'. If this option
  4206. is set to false, TLS will not be used.</p>
  4207. </li>
  4208. <li>
  4209. <p><code>notif_from</code>: defines the &quot;From&quot; address to use when sending emails.
  4210. It must be set if email sending is enabled. The placeholder '%(app)s' will be replaced by the application name,
  4211. which is normally set in <code>app_name</code>, but may be overridden by the
  4212. Matrix client application. Note that the placeholder must be written '%(app)s', including the
  4213. trailing 's'.</p>
  4214. </li>
  4215. <li>
  4216. <p><code>app_name</code>: <code>app_name</code> defines the default value for '%(app)s' in <code>notif_from</code> and email
  4217. subjects. It defaults to 'Matrix'.</p>
  4218. </li>
  4219. <li>
  4220. <p><code>enable_notifs</code>: Set to true to enable sending emails for messages that the user
  4221. has missed. Disabled by default.</p>
  4222. </li>
  4223. <li>
  4224. <p><code>notif_for_new_users</code>: Set to false to disable automatic subscription to email
  4225. notifications for new users. Enabled by default.</p>
  4226. </li>
  4227. <li>
  4228. <p><code>client_base_url</code>: Custom URL for client links within the email notifications. By default
  4229. links will be based on &quot;https://matrix.to&quot;. (This setting used to be called <code>riot_base_url</code>;
  4230. the old name is still supported for backwards-compatibility but is now deprecated.)</p>
  4231. </li>
  4232. <li>
  4233. <p><code>validation_token_lifetime</code>: Configures the time that a validation email will expire after sending.
  4234. Defaults to 1h.</p>
  4235. </li>
  4236. <li>
  4237. <p><code>invite_client_location</code>: The web client location to direct users to during an invite. This is passed
  4238. to the identity server as the <code>org.matrix.web_client_location</code> key. Defaults
  4239. to unset, giving no guidance to the identity server.</p>
  4240. </li>
  4241. <li>
  4242. <p><code>subjects</code>: Subjects to use when sending emails from Synapse. The placeholder '%(app)s' will
  4243. be replaced with the value of the <code>app_name</code> setting, or by a value dictated by the Matrix client application.
  4244. In addition, each subject can use the following placeholders: '%(person)s', which will be replaced by the displayname
  4245. 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
  4246. message(s) have been sent to, e.g. &quot;My super room&quot;. In addition, emails related to account administration will
  4247. can use the '%(server_name)s' placeholder, which will be replaced by the value of the
  4248. <code>server_name</code> setting in your Synapse configuration.</p>
  4249. <p>Here is a list of subjects for notification emails that can be set:</p>
  4250. <ul>
  4251. <li><code>message_from_person_in_room</code>: Subject to use to notify about one message from one or more user(s) in a
  4252. 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>
  4253. <li><code>message_from_person</code>: Subject to use to notify about one message from one or more user(s) in a
  4254. room which doesn't have a name. Defaults to &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;</li>
  4255. <li><code>messages_from_person</code>: Subject to use to notify about multiple messages from one or more users in
  4256. a room which doesn't have a name. Defaults to &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;</li>
  4257. <li><code>messages_in_room</code>: Subject to use to notify about multiple messages in a room which has a
  4258. name. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;</li>
  4259. <li><code>messages_in_room_and_others</code>: Subject to use to notify about multiple messages in multiple rooms.
  4260. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;</li>
  4261. <li><code>messages_from_person_and_others</code>: Subject to use to notify about multiple messages from multiple persons in
  4262. multiple rooms. This is similar to the setting above except it's used when
  4263. the room in which the notification was triggered has no name. Defaults to
  4264. &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;</li>
  4265. <li><code>invite_from_person_to_room</code>: Subject to use to notify about an invite to a room which has a name.
  4266. Defaults to &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;</li>
  4267. <li><code>invite_from_person</code>: Subject to use to notify about an invite to a room which doesn't have a
  4268. name. Defaults to &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;</li>
  4269. <li><code>password_reset</code>: Subject to use when sending a password reset email. Defaults to &quot;[%(server_name)s] Password reset&quot;</li>
  4270. <li><code>email_validation</code>: Subject to use when sending a verification email to assert an address's
  4271. ownership. Defaults to &quot;[%(server_name)s] Validate your email&quot;</li>
  4272. </ul>
  4273. </li>
  4274. </ul>
  4275. <p>Example configuration:</p>
  4276. <pre><code class="language-yaml">email:
  4277. smtp_host: mail.server
  4278. smtp_port: 587
  4279. smtp_user: &quot;exampleusername&quot;
  4280. smtp_pass: &quot;examplepassword&quot;
  4281. force_tls: true
  4282. require_transport_security: true
  4283. enable_tls: false
  4284. notif_from: &quot;Your Friendly %(app)s homeserver &lt;noreply@example.com&gt;&quot;
  4285. app_name: my_branded_matrix_server
  4286. enable_notifs: true
  4287. notif_for_new_users: false
  4288. client_base_url: &quot;http://localhost/riot&quot;
  4289. validation_token_lifetime: 15m
  4290. invite_client_location: https://app.element.io
  4291. subjects:
  4292. message_from_person_in_room: &quot;[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...&quot;
  4293. message_from_person: &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;
  4294. messages_from_person: &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;
  4295. messages_in_room: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;
  4296. messages_in_room_and_others: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;
  4297. messages_from_person_and_others: &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;
  4298. invite_from_person_to_room: &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;
  4299. invite_from_person: &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;
  4300. password_reset: &quot;[%(server_name)s] Password reset&quot;
  4301. email_validation: &quot;[%(server_name)s] Validate your email&quot;
  4302. </code></pre>
  4303. <h2 id="homeserver-blocking"><a class="header" href="#homeserver-blocking">Homeserver blocking</a></h2>
  4304. <p>Useful options for Synapse admins.</p>
  4305. <hr />
  4306. <h3 id="admin_contact"><a class="header" href="#admin_contact"><code>admin_contact</code></a></h3>
  4307. <p>How to reach the server admin, used in <code>ResourceLimitError</code>. Defaults to none.</p>
  4308. <p>Example configuration:</p>
  4309. <pre><code class="language-yaml">admin_contact: 'mailto:admin@server.com'
  4310. </code></pre>
  4311. <hr />
  4312. <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>
  4313. <p>Blocks users from connecting to the homeserver and provides a human-readable reason
  4314. why the connection was blocked. Defaults to false.</p>
  4315. <p>Example configuration:</p>
  4316. <pre><code class="language-yaml">hs_disabled: true
  4317. hs_disabled_message: 'Reason for why the HS is blocked'
  4318. </code></pre>
  4319. <hr />
  4320. <h3 id="limit_usage_by_mau"><a class="header" href="#limit_usage_by_mau"><code>limit_usage_by_mau</code></a></h3>
  4321. <p>This option disables/enables monthly active user blocking. Used in cases where the admin or
  4322. server owner wants to limit to the number of monthly active users. When enabled and a limit is
  4323. reached the server returns a <code>ResourceLimitError</code> with error type <code>Codes.RESOURCE_LIMIT_EXCEEDED</code>.
  4324. Defaults to false. If this is enabled, a value for <code>max_mau_value</code> must also be set.</p>
  4325. <p>See <a href="usage/configuration/../administration/monthly_active_users.html">Monthly Active Users</a> for details on how to configure MAU.</p>
  4326. <p>Example configuration:</p>
  4327. <pre><code class="language-yaml">limit_usage_by_mau: true
  4328. </code></pre>
  4329. <hr />
  4330. <h3 id="max_mau_value"><a class="header" href="#max_mau_value"><code>max_mau_value</code></a></h3>
  4331. <p>This option sets the hard limit of monthly active users above which the server will start
  4332. blocking user actions if <code>limit_usage_by_mau</code> is enabled. Defaults to 0.</p>
  4333. <p>Example configuration:</p>
  4334. <pre><code class="language-yaml">max_mau_value: 50
  4335. </code></pre>
  4336. <hr />
  4337. <h3 id="mau_trial_days"><a class="header" href="#mau_trial_days"><code>mau_trial_days</code></a></h3>
  4338. <p>The option <code>mau_trial_days</code> is a means to add a grace period for active users. It
  4339. means that users must be active for the specified number of days before they
  4340. can be considered active and guards against the case where lots of users
  4341. sign up in a short space of time never to return after their initial
  4342. session. Defaults to 0.</p>
  4343. <p>Example configuration:</p>
  4344. <pre><code class="language-yaml">mau_trial_days: 5
  4345. </code></pre>
  4346. <hr />
  4347. <h3 id="mau_appservice_trial_days"><a class="header" href="#mau_appservice_trial_days"><code>mau_appservice_trial_days</code></a></h3>
  4348. <p>The option <code>mau_appservice_trial_days</code> is similar to <code>mau_trial_days</code>, but applies a different
  4349. trial number if the user was registered by an appservice. A value
  4350. of 0 means no trial days are applied. Appservices not listed in this dictionary
  4351. use the value of <code>mau_trial_days</code> instead.</p>
  4352. <p>Example configuration:</p>
  4353. <pre><code class="language-yaml">mau_appservice_trial_days:
  4354. my_appservice_id: 3
  4355. another_appservice_id: 6
  4356. </code></pre>
  4357. <hr />
  4358. <h3 id="mau_limit_alerting"><a class="header" href="#mau_limit_alerting"><code>mau_limit_alerting</code></a></h3>
  4359. <p>The option <code>mau_limit_alerting</code> is a means of limiting client-side alerting
  4360. should the mau limit be reached. This is useful for small instances
  4361. where the admin has 5 mau seats (say) for 5 specific people and no
  4362. interest increasing the mau limit further. Defaults to true, which
  4363. means that alerting is enabled.</p>
  4364. <p>Example configuration:</p>
  4365. <pre><code class="language-yaml">mau_limit_alerting: false
  4366. </code></pre>
  4367. <hr />
  4368. <h3 id="mau_stats_only"><a class="header" href="#mau_stats_only"><code>mau_stats_only</code></a></h3>
  4369. <p>If enabled, the metrics for the number of monthly active users will
  4370. be populated, however no one will be limited based on these numbers. If <code>limit_usage_by_mau</code>
  4371. is true, this is implied to be true. Defaults to false.</p>
  4372. <p>Example configuration:</p>
  4373. <pre><code class="language-yaml">mau_stats_only: true
  4374. </code></pre>
  4375. <hr />
  4376. <h3 id="mau_limit_reserved_threepids"><a class="header" href="#mau_limit_reserved_threepids"><code>mau_limit_reserved_threepids</code></a></h3>
  4377. <p>Sometimes the server admin will want to ensure certain accounts are
  4378. never blocked by mau checking. These accounts are specified by this option.
  4379. Defaults to none. Add accounts by specifying the <code>medium</code> and <code>address</code> of the
  4380. reserved threepid (3rd party identifier).</p>
  4381. <p>Example configuration:</p>
  4382. <pre><code class="language-yaml">mau_limit_reserved_threepids:
  4383. - medium: 'email'
  4384. address: 'reserved_user@example.com'
  4385. </code></pre>
  4386. <hr />
  4387. <h3 id="server_context"><a class="header" href="#server_context"><code>server_context</code></a></h3>
  4388. <p>This option is used by phonehome stats to group together related servers.
  4389. Defaults to none.</p>
  4390. <p>Example configuration:</p>
  4391. <pre><code class="language-yaml">server_context: context
  4392. </code></pre>
  4393. <hr />
  4394. <h3 id="limit_remote_rooms"><a class="header" href="#limit_remote_rooms"><code>limit_remote_rooms</code></a></h3>
  4395. <p>When this option is enabled, the room &quot;complexity&quot; will be checked before a user
  4396. joins a new remote room. If it is above the complexity limit, the server will
  4397. disallow joining, or will instantly leave. This is useful for homeservers that are
  4398. resource-constrained. Options for this setting include:</p>
  4399. <ul>
  4400. <li><code>enabled</code>: whether this check is enabled. Defaults to false.</li>
  4401. <li><code>complexity</code>: the limit above which rooms cannot be joined. The default is 1.0.</li>
  4402. <li><code>complexity_error</code>: override the error which is returned when the room is too complex with a
  4403. custom message.</li>
  4404. <li><code>admins_can_join</code>: allow server admins to join complex rooms. Default is false.</li>
  4405. </ul>
  4406. <p>Room complexity is an arbitrary measure based on factors such as the number of
  4407. users in the room.</p>
  4408. <p>Example configuration:</p>
  4409. <pre><code class="language-yaml">limit_remote_rooms:
  4410. enabled: true
  4411. complexity: 0.5
  4412. complexity_error: &quot;I can't let you do that, Dave.&quot;
  4413. admins_can_join: true
  4414. </code></pre>
  4415. <hr />
  4416. <h3 id="require_membership_for_aliases"><a class="header" href="#require_membership_for_aliases"><code>require_membership_for_aliases</code></a></h3>
  4417. <p>Whether to require a user to be in the room to add an alias to it.
  4418. Defaults to true.</p>
  4419. <p>Example configuration:</p>
  4420. <pre><code class="language-yaml">require_membership_for_aliases: false
  4421. </code></pre>
  4422. <hr />
  4423. <h3 id="allow_per_room_profiles"><a class="header" href="#allow_per_room_profiles"><code>allow_per_room_profiles</code></a></h3>
  4424. <p>Whether to allow per-room membership profiles through the sending of membership
  4425. events with profile information that differs from the target's global profile.
  4426. Defaults to true.</p>
  4427. <p>Example configuration:</p>
  4428. <pre><code class="language-yaml">allow_per_room_profiles: false
  4429. </code></pre>
  4430. <hr />
  4431. <h3 id="max_avatar_size"><a class="header" href="#max_avatar_size"><code>max_avatar_size</code></a></h3>
  4432. <p>The largest permissible file size in bytes for a user avatar. Defaults to no restriction.
  4433. Use M for MB and K for KB.</p>
  4434. <p>Note that user avatar changes will not work if this is set without using Synapse's media repository.</p>
  4435. <p>Example configuration:</p>
  4436. <pre><code class="language-yaml">max_avatar_size: 10M
  4437. </code></pre>
  4438. <hr />
  4439. <h3 id="allowed_avatar_mimetypes"><a class="header" href="#allowed_avatar_mimetypes"><code>allowed_avatar_mimetypes</code></a></h3>
  4440. <p>The MIME types allowed for user avatars. Defaults to no restriction.</p>
  4441. <p>Note that user avatar changes will not work if this is set without
  4442. using Synapse's media repository.</p>
  4443. <p>Example configuration:</p>
  4444. <pre><code class="language-yaml">allowed_avatar_mimetypes: [&quot;image/png&quot;, &quot;image/jpeg&quot;, &quot;image/gif&quot;]
  4445. </code></pre>
  4446. <hr />
  4447. <h3 id="redaction_retention_period"><a class="header" href="#redaction_retention_period"><code>redaction_retention_period</code></a></h3>
  4448. <p>How long to keep redacted events in unredacted form in the database. After
  4449. this period redacted events get replaced with their redacted form in the DB.</p>
  4450. <p>Synapse will check whether the rentention period has concluded for redacted
  4451. events every 5 minutes. Thus, even if this option is set to <code>0</code>, Synapse may
  4452. still take up to 5 minutes to purge redacted events from the database.</p>
  4453. <p>Defaults to <code>7d</code>. Set to <code>null</code> to disable.</p>
  4454. <p>Example configuration:</p>
  4455. <pre><code class="language-yaml">redaction_retention_period: 28d
  4456. </code></pre>
  4457. <hr />
  4458. <h3 id="forgotten_room_retention_period"><a class="header" href="#forgotten_room_retention_period"><code>forgotten_room_retention_period</code></a></h3>
  4459. <p>How long to keep locally forgotten rooms before purging them from the DB.</p>
  4460. <p>Defaults to <code>null</code>, meaning it's disabled.</p>
  4461. <p>Example configuration:</p>
  4462. <pre><code class="language-yaml">forgotten_room_retention_period: 28d
  4463. </code></pre>
  4464. <hr />
  4465. <h3 id="user_ips_max_age"><a class="header" href="#user_ips_max_age"><code>user_ips_max_age</code></a></h3>
  4466. <p>How long to track users' last seen time and IPs in the database.</p>
  4467. <p>Defaults to <code>28d</code>. Set to <code>null</code> to disable clearing out of old rows.</p>
  4468. <p>Example configuration:</p>
  4469. <pre><code class="language-yaml">user_ips_max_age: 14d
  4470. </code></pre>
  4471. <hr />
  4472. <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>
  4473. <p>Inhibits the <code>/requestToken</code> endpoints from returning an error that might leak
  4474. information about whether an e-mail address is in use or not on this
  4475. homeserver. Defaults to false.
  4476. Note that for some endpoints the error situation is the e-mail already being
  4477. used, and for others the error is entering the e-mail being unused.
  4478. If this option is enabled, instead of returning an error, these endpoints will
  4479. act as if no error happened and return a fake session ID ('sid') to clients.</p>
  4480. <p>Example configuration:</p>
  4481. <pre><code class="language-yaml">request_token_inhibit_3pid_errors: true
  4482. </code></pre>
  4483. <hr />
  4484. <h3 id="next_link_domain_whitelist"><a class="header" href="#next_link_domain_whitelist"><code>next_link_domain_whitelist</code></a></h3>
  4485. <p>A list of domains that the domain portion of <code>next_link</code> parameters
  4486. must match.</p>
  4487. <p>This parameter is optionally provided by clients while requesting
  4488. validation of an email or phone number, and maps to a link that
  4489. users will be automatically redirected to after validation
  4490. succeeds. Clients can make use this parameter to aid the validation
  4491. process.</p>
  4492. <p>The whitelist is applied whether the homeserver or an identity server is handling validation.</p>
  4493. <p>The default value is no whitelist functionality; all domains are
  4494. allowed. Setting this value to an empty list will instead disallow
  4495. all domains.</p>
  4496. <p>Example configuration:</p>
  4497. <pre><code class="language-yaml">next_link_domain_whitelist: [&quot;matrix.org&quot;]
  4498. </code></pre>
  4499. <hr />
  4500. <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>
  4501. <p>These options define templates to use when generating email or HTML page contents.
  4502. The <code>custom_template_directory</code> determines which directory Synapse will try to
  4503. find template files in to use to generate email or HTML page contents.
  4504. If not set, or a file is not found within the template directory, a default
  4505. template from within the Synapse package will be used.</p>
  4506. <p>See <a href="usage/configuration/../../templates.html">here</a> for more
  4507. information about using custom templates.</p>
  4508. <p>Example configuration:</p>
  4509. <pre><code class="language-yaml">templates:
  4510. custom_template_directory: /path/to/custom/templates/
  4511. </code></pre>
  4512. <hr />
  4513. <h3 id="retention"><a class="header" href="#retention"><code>retention</code></a></h3>
  4514. <p>This option and the associated options determine message retention policy at the
  4515. server level.</p>
  4516. <p>Room admins and mods can define a retention period for their rooms using the
  4517. <code>m.room.retention</code> state event, and server admins can cap this period by setting
  4518. the <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> config options.</p>
  4519. <p>If this feature is enabled, Synapse will regularly look for and purge events
  4520. which are older than the room's maximum retention period. Synapse will also
  4521. filter events received over federation so that events that should have been
  4522. purged are ignored and not stored again.</p>
  4523. <p>The message retention policies feature is disabled by default. You can read more
  4524. about this feature <a href="usage/configuration/../../message_retention_policies.html">here</a>.</p>
  4525. <p>This setting has the following sub-options:</p>
  4526. <ul>
  4527. <li>
  4528. <p><code>default_policy</code>: Default retention policy. If set, Synapse will apply it to rooms that lack the
  4529. 'm.room.retention' state event. This option is further specified by the
  4530. <code>min_lifetime</code> and <code>max_lifetime</code> sub-options associated with it. Note that the
  4531. value of <code>min_lifetime</code> doesn't matter much because Synapse doesn't take it into account yet.</p>
  4532. </li>
  4533. <li>
  4534. <p><code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code>: Retention policy limits. If
  4535. set, and the state of a room contains a <code>m.room.retention</code> event in its state
  4536. which contains a <code>min_lifetime</code> or a <code>max_lifetime</code> that's out of these bounds,
  4537. Synapse will cap the room's policy to these limits when running purge jobs.</p>
  4538. </li>
  4539. <li>
  4540. <p><code>purge_jobs</code> and the associated <code>shortest_max_lifetime</code> and <code>longest_max_lifetime</code> sub-options:
  4541. Server admins can define the settings of the background jobs purging the
  4542. events whose lifetime has expired under the <code>purge_jobs</code> section.</p>
  4543. <p>If no configuration is provided for this option, a single job will be set up to delete
  4544. expired events in every room daily.</p>
  4545. <p>Each job's configuration defines which range of message lifetimes the job
  4546. takes care of. For example, if <code>shortest_max_lifetime</code> is '2d' and
  4547. <code>longest_max_lifetime</code> is '3d', the job will handle purging expired events in
  4548. rooms whose state defines a <code>max_lifetime</code> that's both higher than 2 days, and
  4549. lower than or equal to 3 days. Both the minimum and the maximum value of a
  4550. range are optional, e.g. a job with no <code>shortest_max_lifetime</code> and a
  4551. <code>longest_max_lifetime</code> of '3d' will handle every room with a retention policy
  4552. whose <code>max_lifetime</code> is lower than or equal to three days.</p>
  4553. <p>The rationale for this per-job configuration is that some rooms might have a
  4554. retention policy with a low <code>max_lifetime</code>, where history needs to be purged
  4555. of outdated messages on a more frequent basis than for the rest of the rooms
  4556. (e.g. every 12h), but not want that purge to be performed by a job that's
  4557. iterating over every room it knows, which could be heavy on the server.</p>
  4558. <p>If any purge job is configured, it is strongly recommended to have at least
  4559. a single job with neither <code>shortest_max_lifetime</code> nor <code>longest_max_lifetime</code>
  4560. set, or one job without <code>shortest_max_lifetime</code> and one job without
  4561. <code>longest_max_lifetime</code> set. Otherwise some rooms might be ignored, even if
  4562. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> are set, because capping a
  4563. room's policy to these values is done after the policies are retrieved from
  4564. Synapse's database (which is done using the range specified in a purge job's
  4565. configuration).</p>
  4566. </li>
  4567. </ul>
  4568. <p>Example configuration:</p>
  4569. <pre><code class="language-yaml">retention:
  4570. enabled: true
  4571. default_policy:
  4572. min_lifetime: 1d
  4573. max_lifetime: 1y
  4574. allowed_lifetime_min: 1d
  4575. allowed_lifetime_max: 1y
  4576. purge_jobs:
  4577. - longest_max_lifetime: 3d
  4578. interval: 12h
  4579. - shortest_max_lifetime: 3d
  4580. interval: 1d
  4581. </code></pre>
  4582. <hr />
  4583. <h2 id="tls"><a class="header" href="#tls">TLS</a></h2>
  4584. <p>Options related to TLS.</p>
  4585. <hr />
  4586. <h3 id="tls_certificate_path"><a class="header" href="#tls_certificate_path"><code>tls_certificate_path</code></a></h3>
  4587. <p>This option specifies a PEM-encoded X509 certificate for TLS.
  4588. This certificate, as of Synapse 1.0, will need to be a valid and verifiable
  4589. certificate, signed by a recognised Certificate Authority. Defaults to none.</p>
  4590. <p>Be sure to use a <code>.pem</code> file that includes the full certificate chain including
  4591. any intermediate certificates (for instance, if using certbot, use
  4592. <code>fullchain.pem</code> as your certificate, not <code>cert.pem</code>).</p>
  4593. <p>Example configuration:</p>
  4594. <pre><code class="language-yaml">tls_certificate_path: &quot;CONFDIR/SERVERNAME.tls.crt&quot;
  4595. </code></pre>
  4596. <hr />
  4597. <h3 id="tls_private_key_path"><a class="header" href="#tls_private_key_path"><code>tls_private_key_path</code></a></h3>
  4598. <p>PEM-encoded private key for TLS. Defaults to none.</p>
  4599. <p>Example configuration:</p>
  4600. <pre><code class="language-yaml">tls_private_key_path: &quot;CONFDIR/SERVERNAME.tls.key&quot;
  4601. </code></pre>
  4602. <hr />
  4603. <h3 id="federation_verify_certificates"><a class="header" href="#federation_verify_certificates"><code>federation_verify_certificates</code></a></h3>
  4604. <p>Whether to verify TLS server certificates for outbound federation requests.</p>
  4605. <p>Defaults to true. To disable certificate verification, set the option to false.</p>
  4606. <p>Example configuration:</p>
  4607. <pre><code class="language-yaml">federation_verify_certificates: false
  4608. </code></pre>
  4609. <hr />
  4610. <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>
  4611. <p>The minimum TLS version that will be used for outbound federation requests.</p>
  4612. <p>Defaults to <code>&quot;1&quot;</code>. Configurable to <code>&quot;1&quot;</code>, <code>&quot;1.1&quot;</code>, <code>&quot;1.2&quot;</code>, or <code>&quot;1.3&quot;</code>. Note
  4613. that setting this value higher than <code>&quot;1.2&quot;</code> will prevent federation to most
  4614. of the public Matrix network: only configure it to <code>&quot;1.3&quot;</code> if you have an
  4615. entirely private federation setup and you can ensure TLS 1.3 support.</p>
  4616. <p>Example configuration:</p>
  4617. <pre><code class="language-yaml">federation_client_minimum_tls_version: &quot;1.2&quot;
  4618. </code></pre>
  4619. <hr />
  4620. <h3 id="federation_certificate_verification_whitelist"><a class="header" href="#federation_certificate_verification_whitelist"><code>federation_certificate_verification_whitelist</code></a></h3>
  4621. <p>Skip federation certificate verification on a given whitelist
  4622. of domains.</p>
  4623. <p>This setting should only be used in very specific cases, such as
  4624. federation over Tor hidden services and similar. For private networks
  4625. of homeservers, you likely want to use a private CA instead.</p>
  4626. <p>Only effective if <code>federation_verify_certificates</code> is <code>true</code>.</p>
  4627. <p>Example configuration:</p>
  4628. <pre><code class="language-yaml">federation_certificate_verification_whitelist:
  4629. - lon.example.com
  4630. - &quot;*.domain.com&quot;
  4631. - &quot;*.onion&quot;
  4632. </code></pre>
  4633. <hr />
  4634. <h3 id="federation_custom_ca_list"><a class="header" href="#federation_custom_ca_list"><code>federation_custom_ca_list</code></a></h3>
  4635. <p>List of custom certificate authorities for federation traffic.</p>
  4636. <p>This setting should only normally be used within a private network of
  4637. homeservers.</p>
  4638. <p>Note that this list will replace those that are provided by your
  4639. operating environment. Certificates must be in PEM format.</p>
  4640. <p>Example configuration:</p>
  4641. <pre><code class="language-yaml">federation_custom_ca_list:
  4642. - myCA1.pem
  4643. - myCA2.pem
  4644. - myCA3.pem
  4645. </code></pre>
  4646. <hr />
  4647. <h2 id="federation"><a class="header" href="#federation">Federation</a></h2>
  4648. <p>Options related to federation.</p>
  4649. <hr />
  4650. <h3 id="federation_domain_whitelist"><a class="header" href="#federation_domain_whitelist"><code>federation_domain_whitelist</code></a></h3>
  4651. <p>Restrict federation to the given whitelist of domains.
  4652. N.B. we recommend also firewalling your federation listener to limit
  4653. inbound federation traffic as early as possible, rather than relying
  4654. purely on this application-layer restriction. If not specified, the
  4655. default is to whitelist everything.</p>
  4656. <p>Note: this does not stop a server from joining rooms that servers not on the
  4657. whitelist are in. As such, this option is really only useful to establish a
  4658. &quot;private federation&quot;, where a group of servers all whitelist each other and have
  4659. the same whitelist.</p>
  4660. <p>Example configuration:</p>
  4661. <pre><code class="language-yaml">federation_domain_whitelist:
  4662. - lon.example.com
  4663. - nyc.example.com
  4664. - syd.example.com
  4665. </code></pre>
  4666. <hr />
  4667. <h3 id="federation_metrics_domains"><a class="header" href="#federation_metrics_domains"><code>federation_metrics_domains</code></a></h3>
  4668. <p>Report prometheus metrics on the age of PDUs being sent to and received from
  4669. the given domains. This can be used to give an idea of &quot;delay&quot; on inbound
  4670. and outbound federation, though be aware that any delay can be due to problems
  4671. at either end or with the intermediate network.</p>
  4672. <p>By default, no domains are monitored in this way.</p>
  4673. <p>Example configuration:</p>
  4674. <pre><code class="language-yaml">federation_metrics_domains:
  4675. - matrix.org
  4676. - example.com
  4677. </code></pre>
  4678. <hr />
  4679. <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>
  4680. <p>Set to false to disable profile lookup over federation. By default, the
  4681. Federation API allows other homeservers to obtain profile data of any user
  4682. on this homeserver.</p>
  4683. <p>Example configuration:</p>
  4684. <pre><code class="language-yaml">allow_profile_lookup_over_federation: false
  4685. </code></pre>
  4686. <hr />
  4687. <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>
  4688. <p>Set this option to true to allow device display name lookup over federation. By default, the
  4689. Federation API prevents other homeservers from obtaining the display names of any user devices
  4690. on this homeserver.</p>
  4691. <p>Example configuration:</p>
  4692. <pre><code class="language-yaml">allow_device_name_lookup_over_federation: true
  4693. </code></pre>
  4694. <hr />
  4695. <h3 id="federation-1"><a class="header" href="#federation-1"><code>federation</code></a></h3>
  4696. <p>The federation section defines some sub-options related to federation.</p>
  4697. <p>The following options are related to configuring timeout and retry logic for one request,
  4698. independently of the others.
  4699. Short retry algorithm is used when something or someone will wait for the request to have an
  4700. answer, while long retry is used for requests that happen in the background,
  4701. like sending a federation transaction.</p>
  4702. <ul>
  4703. <li><code>client_timeout</code>: timeout for the federation requests. Default to 60s.</li>
  4704. <li><code>max_short_retry_delay</code>: maximum delay to be used for the short retry algo. Default to 2s.</li>
  4705. <li><code>max_long_retry_delay</code>: maximum delay to be used for the short retry algo. Default to 60s.</li>
  4706. <li><code>max_short_retries</code>: maximum number of retries for the short retry algo. Default to 3 attempts.</li>
  4707. <li><code>max_long_retries</code>: maximum number of retries for the long retry algo. Default to 10 attempts.</li>
  4708. </ul>
  4709. <p>The following options control the retry logic when communicating with a specific homeserver destination.
  4710. Unlike the previous configuration options, these values apply across all requests
  4711. for a given destination and the state of the backoff is stored in the database.</p>
  4712. <ul>
  4713. <li><code>destination_min_retry_interval</code>: the initial backoff, after the first request fails. Defaults to 10m.</li>
  4714. <li><code>destination_retry_multiplier</code>: how much we multiply the backoff by after each subsequent fail. Defaults to 2.</li>
  4715. <li><code>destination_max_retry_interval</code>: a cap on the backoff. Defaults to a week.</li>
  4716. </ul>
  4717. <p>Example configuration:</p>
  4718. <pre><code class="language-yaml">federation:
  4719. client_timeout: 180s
  4720. max_short_retry_delay: 7s
  4721. max_long_retry_delay: 100s
  4722. max_short_retries: 5
  4723. max_long_retries: 20
  4724. destination_min_retry_interval: 30s
  4725. destination_retry_multiplier: 5
  4726. destination_max_retry_interval: 12h
  4727. </code></pre>
  4728. <hr />
  4729. <h2 id="caching"><a class="header" href="#caching">Caching</a></h2>
  4730. <p>Options related to caching.</p>
  4731. <hr />
  4732. <h3 id="event_cache_size"><a class="header" href="#event_cache_size"><code>event_cache_size</code></a></h3>
  4733. <p>The number of events to cache in memory. Defaults to 10K. Like other caches,
  4734. this is affected by <code>caches.global_factor</code> (see below).</p>
  4735. <p>Note that this option is not part of the <code>caches</code> section.</p>
  4736. <p>Example configuration:</p>
  4737. <pre><code class="language-yaml">event_cache_size: 15K
  4738. </code></pre>
  4739. <hr />
  4740. <h3 id="caches-and-associated-values"><a class="header" href="#caches-and-associated-values"><code>caches</code> and associated values</a></h3>
  4741. <p>A cache 'factor' is a multiplier that can be applied to each of
  4742. Synapse's caches in order to increase or decrease the maximum
  4743. number of entries that can be stored.</p>
  4744. <p><code>caches</code> can be configured through the following sub-options:</p>
  4745. <ul>
  4746. <li>
  4747. <p><code>global_factor</code>: Controls the global cache factor, which is the default cache factor
  4748. for all caches if a specific factor for that cache is not otherwise
  4749. set.</p>
  4750. <p>This can also be set by the <code>SYNAPSE_CACHE_FACTOR</code> environment
  4751. variable. Setting by environment variable takes priority over
  4752. setting through the config file.</p>
  4753. <p>Defaults to 0.5, which will halve the size of all caches.</p>
  4754. </li>
  4755. <li>
  4756. <p><code>per_cache_factors</code>: A dictionary of cache name to cache factor for that individual
  4757. cache. Overrides the global cache factor for a given cache.</p>
  4758. <p>These can also be set through environment variables comprised
  4759. of <code>SYNAPSE_CACHE_FACTOR_</code> + the name of the cache in capital
  4760. letters and underscores. Setting by environment variable
  4761. takes priority over setting through the config file.
  4762. Ex. <code>SYNAPSE_CACHE_FACTOR_GET_USERS_WHO_SHARE_ROOM_WITH_USER=2.0</code></p>
  4763. <p>Some caches have '*' and other characters that are not
  4764. alphanumeric or underscores. These caches can be named with or
  4765. without the special characters stripped. For example, to specify
  4766. the cache factor for <code>*stateGroupCache*</code> via an environment
  4767. variable would be <code>SYNAPSE_CACHE_FACTOR_STATEGROUPCACHE=2.0</code>.</p>
  4768. </li>
  4769. <li>
  4770. <p><code>expire_caches</code>: Controls whether cache entries are evicted after a specified time
  4771. period. Defaults to true. Set to false to disable this feature. Note that never expiring
  4772. caches may result in excessive memory usage.</p>
  4773. </li>
  4774. <li>
  4775. <p><code>cache_entry_ttl</code>: If <code>expire_caches</code> is enabled, this flag controls how long an entry can
  4776. be in a cache without having been accessed before being evicted.
  4777. Defaults to 30m.</p>
  4778. </li>
  4779. <li>
  4780. <p><code>sync_response_cache_duration</code>: Controls how long the results of a /sync request are
  4781. cached for after a successful response is returned. A higher duration can help clients
  4782. with intermittent connections, at the cost of higher memory usage.
  4783. A value of zero means that sync responses are not cached.
  4784. Defaults to 2m.</p>
  4785. <p><em>Changed in Synapse 1.62.0</em>: The default was changed from 0 to 2m.</p>
  4786. </li>
  4787. <li>
  4788. <p><code>cache_autotuning</code> and its sub-options <code>max_cache_memory_usage</code>, <code>target_cache_memory_usage</code>, and
  4789. <code>min_cache_ttl</code> work in conjunction with each other to maintain a balance between cache memory
  4790. 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>
  4791. to utilize this option, and all three of the options must be specified for this feature to work. This option
  4792. defaults to off, enable it by providing values for the sub-options listed below. Please note that the feature will not work
  4793. and may cause unstable behavior (such as excessive emptying of caches or exceptions) if all of the values are not provided.
  4794. 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
  4795. durations.</p>
  4796. <ul>
  4797. <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.
  4798. They will continue to be evicted until the memory usage drops below the <code>target_memory_usage</code>, set in
  4799. the setting below, or until the <code>min_cache_ttl</code> is hit. There is no default value for this option.</li>
  4800. <li><code>target_cache_memory_usage</code> sets a rough target for the desired memory usage of the caches. There is no default value
  4801. for this option.</li>
  4802. <li><code>min_cache_ttl</code> sets a limit under which newer cache entries are not evicted and is only applied when
  4803. caches are actively being evicted/<code>max_cache_memory_usage</code> has been exceeded. This is to protect hot caches
  4804. from being emptied while Synapse is evicting due to memory. There is no default value for this option.</li>
  4805. </ul>
  4806. </li>
  4807. </ul>
  4808. <p>Example configuration:</p>
  4809. <pre><code class="language-yaml">event_cache_size: 15K
  4810. caches:
  4811. global_factor: 1.0
  4812. per_cache_factors:
  4813. get_users_who_share_room_with_user: 2.0
  4814. sync_response_cache_duration: 2m
  4815. cache_autotuning:
  4816. max_cache_memory_usage: 1024M
  4817. target_cache_memory_usage: 758M
  4818. min_cache_ttl: 5m
  4819. </code></pre>
  4820. <h3 id="reloading-cache-factors"><a class="header" href="#reloading-cache-factors">Reloading cache factors</a></h3>
  4821. <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
  4822. <a href="https://en.wikipedia.org/wiki/SIGHUP"><code>SIGHUP</code></a> signal to Synapse using e.g.</p>
  4823. <pre><code class="language-commandline">kill -HUP [PID_OF_SYNAPSE_PROCESS]
  4824. </code></pre>
  4825. <p>If you are running multiple workers, you must individually update the worker
  4826. config file and send this signal to each worker process.</p>
  4827. <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>
  4828. file in Synapse's <code>contrib</code> directory, you can send a <code>SIGHUP</code> signal by using
  4829. <code>systemctl reload matrix-synapse</code>.</p>
  4830. <hr />
  4831. <h2 id="database"><a class="header" href="#database">Database</a></h2>
  4832. <p>Config options related to database settings.</p>
  4833. <hr />
  4834. <h3 id="database-1"><a class="header" href="#database-1"><code>database</code></a></h3>
  4835. <p>The <code>database</code> setting defines the database that synapse uses to store all of
  4836. its data.</p>
  4837. <p>Associated sub-options:</p>
  4838. <ul>
  4839. <li>
  4840. <p><code>name</code>: this option specifies the database engine to use: either <code>sqlite3</code> (for SQLite)
  4841. or <code>psycopg2</code> (for PostgreSQL). If no name is specified Synapse will default to SQLite.</p>
  4842. </li>
  4843. <li>
  4844. <p><code>txn_limit</code> gives the maximum number of transactions to run per connection
  4845. before reconnecting. Defaults to 0, which means no limit.</p>
  4846. </li>
  4847. <li>
  4848. <p><code>allow_unsafe_locale</code> is an option specific to Postgres. Under the default behavior, Synapse will refuse to
  4849. start if the postgres db is set to a non-C locale. You can override this behavior (which is <em>not</em> recommended)
  4850. by setting <code>allow_unsafe_locale</code> to true. Note that doing so may corrupt your database. You can find more information
  4851. <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>
  4852. </li>
  4853. <li>
  4854. <p><code>args</code> gives options which are passed through to the database engine,
  4855. except for options starting with <code>cp_</code>, which are used to configure the Twisted
  4856. connection pool. For a reference to valid arguments, see:</p>
  4857. <ul>
  4858. <li>for <a href="https://docs.python.org/3/library/sqlite3.html#sqlite3.connect">sqlite</a></li>
  4859. <li>for <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">postgres</a></li>
  4860. <li>for <a href="https://docs.twistedmatrix.com/en/stable/api/twisted.enterprise.adbapi.ConnectionPool.html#__init__">the connection pool</a></li>
  4861. </ul>
  4862. </li>
  4863. </ul>
  4864. <p>For more information on using Synapse with Postgres,
  4865. see <a href="usage/configuration/../../postgres.html">here</a>.</p>
  4866. <p>Example SQLite configuration:</p>
  4867. <pre><code class="language-yaml">database:
  4868. name: sqlite3
  4869. args:
  4870. database: /path/to/homeserver.db
  4871. </code></pre>
  4872. <p>Example Postgres configuration:</p>
  4873. <pre><code class="language-yaml">database:
  4874. name: psycopg2
  4875. txn_limit: 10000
  4876. args:
  4877. user: synapse_user
  4878. password: secretpassword
  4879. database: synapse
  4880. host: localhost
  4881. port: 5432
  4882. cp_min: 5
  4883. cp_max: 10
  4884. </code></pre>
  4885. <hr />
  4886. <h3 id="databases"><a class="header" href="#databases"><code>databases</code></a></h3>
  4887. <p>The <code>databases</code> option allows specifying a mapping between certain database tables and
  4888. database host details, spreading the load of a single Synapse instance across multiple
  4889. database backends. This is often referred to as &quot;database sharding&quot;. This option is only
  4890. supported for PostgreSQL database backends.</p>
  4891. <p><strong>Important note:</strong> This is a supported option, but is not currently used in production by the
  4892. Matrix.org Foundation. Proceed with caution and always make backups.</p>
  4893. <p><code>databases</code> is a dictionary of arbitrarily-named database entries. Each entry is equivalent
  4894. to the value of the <code>database</code> homeserver config option (see above), with the addition of
  4895. a <code>data_stores</code> key. <code>data_stores</code> is an array of strings that specifies the data store(s)
  4896. (a defined label for a set of tables) that should be stored on the associated database
  4897. backend entry.</p>
  4898. <p>The currently defined values for <code>data_stores</code> are:</p>
  4899. <ul>
  4900. <li>
  4901. <p><code>&quot;state&quot;</code>: Database that relates to state groups will be stored in this database.</p>
  4902. <p>Specifically, that means the following tables:</p>
  4903. <ul>
  4904. <li><code>state_groups</code></li>
  4905. <li><code>state_group_edges</code></li>
  4906. <li><code>state_groups_state</code></li>
  4907. </ul>
  4908. <p>And the following sequences:</p>
  4909. <ul>
  4910. <li><code>state_groups_seq_id</code></li>
  4911. </ul>
  4912. </li>
  4913. <li>
  4914. <p><code>&quot;main&quot;</code>: All other database tables and sequences.</p>
  4915. </li>
  4916. </ul>
  4917. <p>All databases will end up with additional tables used for tracking database schema migrations
  4918. and any pending background updates. Synapse will create these automatically on startup when checking for
  4919. and/or performing database schema migrations.</p>
  4920. <p>To migrate an existing database configuration (e.g. all tables on a single database) to a different
  4921. configuration (e.g. the &quot;main&quot; data store on one database, and &quot;state&quot; on another), do the following:</p>
  4922. <ol>
  4923. <li>
  4924. <p>Take a backup of your existing database. Things can and do go wrong and database corruption is no joke!</p>
  4925. </li>
  4926. <li>
  4927. <p>Ensure all pending database migrations have been applied and background updates have run. The simplest
  4928. way to do this is to use the <code>update_synapse_database</code> script supplied with your Synapse installation.</p>
  4929. <pre><code class="language-sh">update_synapse_database --database-config homeserver.yaml --run-background-updates
  4930. </code></pre>
  4931. </li>
  4932. <li>
  4933. <p>Copy over the necessary tables and sequences from one database to the other. Tables relating to database
  4934. migrations, schemas, schema versions and background updates should <strong>not</strong> be copied.</p>
  4935. <p>As an example, say that you'd like to split out the &quot;state&quot; data store from an existing database which
  4936. currently contains all data stores.</p>
  4937. <p>Simply copy the tables and sequences defined above for the &quot;state&quot; datastore from the existing database
  4938. to the secondary database. As noted above, additional tables will be created in the secondary database
  4939. when Synapse is started.</p>
  4940. </li>
  4941. <li>
  4942. <p>Modify/create the <code>databases</code> option in your <code>homeserver.yaml</code> to match the desired database configuration.</p>
  4943. </li>
  4944. <li>
  4945. <p>Start Synapse. Check that it starts up successfully and that things generally seem to be working.</p>
  4946. </li>
  4947. <li>
  4948. <p>Drop the old tables that were copied in step 3.</p>
  4949. </li>
  4950. </ol>
  4951. <p>Only one of the options <code>database</code> or <code>databases</code> may be specified in your config, but not both.</p>
  4952. <p>Example configuration:</p>
  4953. <pre><code class="language-yaml">databases:
  4954. basement_box:
  4955. name: psycopg2
  4956. txn_limit: 10000
  4957. data_stores: [&quot;main&quot;]
  4958. args:
  4959. user: synapse_user
  4960. password: secretpassword
  4961. database: synapse_main
  4962. host: localhost
  4963. port: 5432
  4964. cp_min: 5
  4965. cp_max: 10
  4966. my_other_database:
  4967. name: psycopg2
  4968. txn_limit: 10000
  4969. data_stores: [&quot;state&quot;]
  4970. args:
  4971. user: synapse_user
  4972. password: secretpassword
  4973. database: synapse_state
  4974. host: localhost
  4975. port: 5432
  4976. cp_min: 5
  4977. cp_max: 10
  4978. </code></pre>
  4979. <hr />
  4980. <h2 id="logging"><a class="header" href="#logging">Logging</a></h2>
  4981. <p>Config options related to logging.</p>
  4982. <hr />
  4983. <h3 id="log_config"><a class="header" href="#log_config"><code>log_config</code></a></h3>
  4984. <p>This option specifies a yaml python logging config file as described
  4985. <a href="https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema">here</a>.</p>
  4986. <p>Example configuration:</p>
  4987. <pre><code class="language-yaml">log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  4988. </code></pre>
  4989. <hr />
  4990. <h2 id="ratelimiting"><a class="header" href="#ratelimiting">Ratelimiting</a></h2>
  4991. <p>Options related to ratelimiting in Synapse.</p>
  4992. <p>Each ratelimiting configuration is made of two parameters:</p>
  4993. <ul>
  4994. <li><code>per_second</code>: number of requests a client can send per second.</li>
  4995. <li><code>burst_count</code>: number of requests a client can send before being throttled.</li>
  4996. </ul>
  4997. <hr />
  4998. <h3 id="rc_message"><a class="header" href="#rc_message"><code>rc_message</code></a></h3>
  4999. <p>Ratelimiting settings for client messaging.</p>
  5000. <p>This is a ratelimiting option for messages that ratelimits sending based on the account the client
  5001. is using. It defaults to: <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
  5002. <p>Example configuration:</p>
  5003. <pre><code class="language-yaml">rc_message:
  5004. per_second: 0.5
  5005. burst_count: 15
  5006. </code></pre>
  5007. <hr />
  5008. <h3 id="rc_registration"><a class="header" href="#rc_registration"><code>rc_registration</code></a></h3>
  5009. <p>This option ratelimits registration requests based on the client's IP address.
  5010. It defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  5011. <p>Example configuration:</p>
  5012. <pre><code class="language-yaml">rc_registration:
  5013. per_second: 0.15
  5014. burst_count: 2
  5015. </code></pre>
  5016. <hr />
  5017. <h3 id="rc_registration_token_validity"><a class="header" href="#rc_registration_token_validity"><code>rc_registration_token_validity</code></a></h3>
  5018. <p>This option checks the validity of registration tokens that ratelimits requests based on
  5019. the client's IP address.
  5020. Defaults to <code>per_second: 0.1</code>, <code>burst_count: 5</code>.</p>
  5021. <p>Example configuration:</p>
  5022. <pre><code class="language-yaml">rc_registration_token_validity:
  5023. per_second: 0.3
  5024. burst_count: 6
  5025. </code></pre>
  5026. <hr />
  5027. <h3 id="rc_login"><a class="header" href="#rc_login"><code>rc_login</code></a></h3>
  5028. <p>This option specifies several limits for login:</p>
  5029. <ul>
  5030. <li>
  5031. <p><code>address</code> ratelimits login requests based on the client's IP
  5032. address. Defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  5033. </li>
  5034. <li>
  5035. <p><code>account</code> ratelimits login requests based on the account the
  5036. client is attempting to log into. Defaults to <code>per_second: 0.003</code>,
  5037. <code>burst_count: 5</code>.</p>
  5038. </li>
  5039. <li>
  5040. <p><code>failed_attempts</code> ratelimits login requests based on the account the
  5041. client is attempting to log into, based on the amount of failed login
  5042. attempts for this account. Defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  5043. </li>
  5044. </ul>
  5045. <p>Example configuration:</p>
  5046. <pre><code class="language-yaml">rc_login:
  5047. address:
  5048. per_second: 0.15
  5049. burst_count: 5
  5050. account:
  5051. per_second: 0.18
  5052. burst_count: 4
  5053. failed_attempts:
  5054. per_second: 0.19
  5055. burst_count: 7
  5056. </code></pre>
  5057. <hr />
  5058. <h3 id="rc_admin_redaction"><a class="header" href="#rc_admin_redaction"><code>rc_admin_redaction</code></a></h3>
  5059. <p>This option sets ratelimiting redactions by room admins. If this is not explicitly
  5060. set then it uses the same ratelimiting as per <code>rc_message</code>. This is useful
  5061. to allow room admins to deal with abuse quickly.</p>
  5062. <p>Example configuration:</p>
  5063. <pre><code class="language-yaml">rc_admin_redaction:
  5064. per_second: 1
  5065. burst_count: 50
  5066. </code></pre>
  5067. <hr />
  5068. <h3 id="rc_joins"><a class="header" href="#rc_joins"><code>rc_joins</code></a></h3>
  5069. <p>This option allows for ratelimiting number of rooms a user can join. This setting has the following sub-options:</p>
  5070. <ul>
  5071. <li>
  5072. <p><code>local</code>: ratelimits when users are joining rooms the server is already in.
  5073. Defaults to <code>per_second: 0.1</code>, <code>burst_count: 10</code>.</p>
  5074. </li>
  5075. <li>
  5076. <p><code>remote</code>: ratelimits when users are trying to join rooms not on the server (which
  5077. can be more computationally expensive than restricting locally). Defaults to
  5078. <code>per_second: 0.01</code>, <code>burst_count: 10</code></p>
  5079. </li>
  5080. </ul>
  5081. <p>Example configuration:</p>
  5082. <pre><code class="language-yaml">rc_joins:
  5083. local:
  5084. per_second: 0.2
  5085. burst_count: 15
  5086. remote:
  5087. per_second: 0.03
  5088. burst_count: 12
  5089. </code></pre>
  5090. <hr />
  5091. <h3 id="rc_joins_per_room"><a class="header" href="#rc_joins_per_room"><code>rc_joins_per_room</code></a></h3>
  5092. <p>This option allows admins to ratelimit joins to a room based on the number of recent
  5093. joins (local or remote) to that room. It is intended to mitigate mass-join spam
  5094. waves which target multiple homeservers.</p>
  5095. <p>By default, one join is permitted to a room every second, with an accumulating
  5096. buffer of up to ten instantaneous joins.</p>
  5097. <p>Example configuration (default values):</p>
  5098. <pre><code class="language-yaml">rc_joins_per_room:
  5099. per_second: 1
  5100. burst_count: 10
  5101. </code></pre>
  5102. <p><em>Added in Synapse 1.64.0.</em></p>
  5103. <hr />
  5104. <h3 id="rc_3pid_validation"><a class="header" href="#rc_3pid_validation"><code>rc_3pid_validation</code></a></h3>
  5105. <p>This option ratelimits how often a user or IP can attempt to validate a 3PID.
  5106. Defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  5107. <p>Example configuration:</p>
  5108. <pre><code class="language-yaml">rc_3pid_validation:
  5109. per_second: 0.003
  5110. burst_count: 5
  5111. </code></pre>
  5112. <hr />
  5113. <h3 id="rc_invites"><a class="header" href="#rc_invites"><code>rc_invites</code></a></h3>
  5114. <p>This option sets ratelimiting how often invites can be sent in a room or to a
  5115. specific user. <code>per_room</code> defaults to <code>per_second: 0.3</code>, <code>burst_count: 10</code> and
  5116. <code>per_user</code> defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  5117. <p>Client requests that invite user(s) when <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3createroom">creating a
  5118. room</a>
  5119. will count against the <code>rc_invites.per_room</code> limit, whereas
  5120. client requests to <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidinvite">invite a single user to a
  5121. room</a>
  5122. will count against both the <code>rc_invites.per_user</code> and <code>rc_invites.per_room</code> limits.</p>
  5123. <p>Federation requests to invite a user will count against the <code>rc_invites.per_user</code>
  5124. limit only, as Synapse presumes ratelimiting by room will be done by the sending server.</p>
  5125. <p>The <code>rc_invites.per_user</code> limit applies to the <em>receiver</em> of the invite, rather than the
  5126. sender, meaning that a <code>rc_invite.per_user.burst_count</code> of 5 mandates that a single user
  5127. cannot <em>receive</em> more than a burst of 5 invites at a time.</p>
  5128. <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>
  5129. <p><em>Changed in version 1.63:</em> added the <code>per_issuer</code> limit.</p>
  5130. <p>Example configuration:</p>
  5131. <pre><code class="language-yaml">rc_invites:
  5132. per_room:
  5133. per_second: 0.5
  5134. burst_count: 5
  5135. per_user:
  5136. per_second: 0.004
  5137. burst_count: 3
  5138. per_issuer:
  5139. per_second: 0.5
  5140. burst_count: 5
  5141. </code></pre>
  5142. <hr />
  5143. <h3 id="rc_third_party_invite"><a class="header" href="#rc_third_party_invite"><code>rc_third_party_invite</code></a></h3>
  5144. <p>This option ratelimits 3PID invites (i.e. invites sent to a third-party ID
  5145. such as an email address or a phone number) based on the account that's
  5146. sending the invite. Defaults to <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
  5147. <p>Example configuration:</p>
  5148. <pre><code class="language-yaml">rc_third_party_invite:
  5149. per_second: 0.2
  5150. burst_count: 10
  5151. </code></pre>
  5152. <hr />
  5153. <h3 id="rc_federation"><a class="header" href="#rc_federation"><code>rc_federation</code></a></h3>
  5154. <p>Defines limits on federation requests.</p>
  5155. <p>The <code>rc_federation</code> configuration has the following sub-options:</p>
  5156. <ul>
  5157. <li><code>window_size</code>: window size in milliseconds. Defaults to 1000.</li>
  5158. <li><code>sleep_limit</code>: number of federation requests from a single server in
  5159. a window before the server will delay processing the request. Defaults to 10.</li>
  5160. <li><code>sleep_delay</code>: duration in milliseconds to delay processing events
  5161. from remote servers by if they go over the sleep limit. Defaults to 500.</li>
  5162. <li><code>reject_limit</code>: maximum number of concurrent federation requests
  5163. allowed from a single server. Defaults to 50.</li>
  5164. <li><code>concurrent</code>: number of federation requests to concurrently process
  5165. from a single server. Defaults to 3.</li>
  5166. </ul>
  5167. <p>Example configuration:</p>
  5168. <pre><code class="language-yaml">rc_federation:
  5169. window_size: 750
  5170. sleep_limit: 15
  5171. sleep_delay: 400
  5172. reject_limit: 40
  5173. concurrent: 5
  5174. </code></pre>
  5175. <hr />
  5176. <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>
  5177. <p>Sets outgoing federation transaction frequency for sending read-receipts,
  5178. per-room.</p>
  5179. <p>If we end up trying to send out more read-receipts, they will get buffered up
  5180. into fewer transactions. Defaults to 50.</p>
  5181. <p>Example configuration:</p>
  5182. <pre><code class="language-yaml">federation_rr_transactions_per_room_per_second: 40
  5183. </code></pre>
  5184. <hr />
  5185. <h2 id="media-store"><a class="header" href="#media-store">Media Store</a></h2>
  5186. <p>Config options related to Synapse's media store.</p>
  5187. <hr />
  5188. <h3 id="enable_media_repo"><a class="header" href="#enable_media_repo"><code>enable_media_repo</code></a></h3>
  5189. <p>Enable the media store service in the Synapse master. Defaults to true.
  5190. Set to false if you are using a separate media store worker.</p>
  5191. <p>Example configuration:</p>
  5192. <pre><code class="language-yaml">enable_media_repo: false
  5193. </code></pre>
  5194. <hr />
  5195. <h3 id="media_store_path"><a class="header" href="#media_store_path"><code>media_store_path</code></a></h3>
  5196. <p>Directory where uploaded images and attachments are stored.</p>
  5197. <p>Example configuration:</p>
  5198. <pre><code class="language-yaml">media_store_path: &quot;DATADIR/media_store&quot;
  5199. </code></pre>
  5200. <hr />
  5201. <h3 id="media_storage_providers"><a class="header" href="#media_storage_providers"><code>media_storage_providers</code></a></h3>
  5202. <p>Media storage providers allow media to be stored in different
  5203. locations. Defaults to none. Associated sub-options are:</p>
  5204. <ul>
  5205. <li><code>module</code>: type of resource, e.g. <code>file_system</code>.</li>
  5206. <li><code>store_local</code>: whether to store newly uploaded local files</li>
  5207. <li><code>store_remote</code>: whether to store newly downloaded local files</li>
  5208. <li><code>store_synchronous</code>: whether to wait for successful storage for local uploads</li>
  5209. <li><code>config</code>: sets a path to the resource through the <code>directory</code> option</li>
  5210. </ul>
  5211. <p>Example configuration:</p>
  5212. <pre><code class="language-yaml">media_storage_providers:
  5213. - module: file_system
  5214. store_local: false
  5215. store_remote: false
  5216. store_synchronous: false
  5217. config:
  5218. directory: /mnt/some/other/directory
  5219. </code></pre>
  5220. <hr />
  5221. <h3 id="max_upload_size"><a class="header" href="#max_upload_size"><code>max_upload_size</code></a></h3>
  5222. <p>The largest allowed upload size in bytes.</p>
  5223. <p>If you are using a reverse proxy you may also need to set this value in
  5224. your reverse proxy's config. Defaults to 50M. Notably Nginx has a small max body size by default.
  5225. See <a href="usage/configuration/../../reverse_proxy.html">here</a> for more on using a reverse proxy with Synapse.</p>
  5226. <p>Example configuration:</p>
  5227. <pre><code class="language-yaml">max_upload_size: 60M
  5228. </code></pre>
  5229. <hr />
  5230. <h3 id="max_image_pixels"><a class="header" href="#max_image_pixels"><code>max_image_pixels</code></a></h3>
  5231. <p>Maximum number of pixels that will be thumbnailed. Defaults to 32M.</p>
  5232. <p>Example configuration:</p>
  5233. <pre><code class="language-yaml">max_image_pixels: 35M
  5234. </code></pre>
  5235. <hr />
  5236. <h3 id="prevent_media_downloads_from"><a class="header" href="#prevent_media_downloads_from"><code>prevent_media_downloads_from</code></a></h3>
  5237. <p>A list of domains to never download media from. Media from these
  5238. domains that is already downloaded will not be deleted, but will be
  5239. inaccessible to users. This option does not affect admin APIs trying
  5240. to download/operate on media.</p>
  5241. <p>This will not prevent the listed domains from accessing media themselves.
  5242. It simply prevents users on this server from downloading media originating
  5243. from the listed servers.</p>
  5244. <p>This will have no effect on media originating from the local server.
  5245. This only affects media downloaded from other Matrix servers, to
  5246. 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>
  5247. <p>Defaults to an empty list (nothing blocked).</p>
  5248. <p>Example configuration:</p>
  5249. <pre><code class="language-yaml">prevent_media_downloads_from:
  5250. - evil.example.org
  5251. - evil2.example.org
  5252. </code></pre>
  5253. <hr />
  5254. <h3 id="dynamic_thumbnails"><a class="header" href="#dynamic_thumbnails"><code>dynamic_thumbnails</code></a></h3>
  5255. <p>Whether to generate new thumbnails on the fly to precisely match
  5256. the resolution requested by the client. If true then whenever
  5257. a new resolution is requested by the client the server will
  5258. generate a new thumbnail. If false the server will pick a thumbnail
  5259. from a precalculated list. Defaults to false.</p>
  5260. <p>Example configuration:</p>
  5261. <pre><code class="language-yaml">dynamic_thumbnails: true
  5262. </code></pre>
  5263. <hr />
  5264. <h3 id="thumbnail_sizes"><a class="header" href="#thumbnail_sizes"><code>thumbnail_sizes</code></a></h3>
  5265. <p>List of thumbnails to precalculate when an image is uploaded. Associated sub-options are:</p>
  5266. <ul>
  5267. <li><code>width</code></li>
  5268. <li><code>height</code></li>
  5269. <li><code>method</code>: i.e. <code>crop</code>, <code>scale</code>, etc.</li>
  5270. </ul>
  5271. <p>Example configuration:</p>
  5272. <pre><code class="language-yaml">thumbnail_sizes:
  5273. - width: 32
  5274. height: 32
  5275. method: crop
  5276. - width: 96
  5277. height: 96
  5278. method: crop
  5279. - width: 320
  5280. height: 240
  5281. method: scale
  5282. - width: 640
  5283. height: 480
  5284. method: scale
  5285. - width: 800
  5286. height: 600
  5287. method: scale
  5288. </code></pre>
  5289. <hr />
  5290. <h3 id="media_retention"><a class="header" href="#media_retention"><code>media_retention</code></a></h3>
  5291. <p>Controls whether local media and entries in the remote media cache
  5292. (media that is downloaded from other homeservers) should be removed
  5293. under certain conditions, typically for the purpose of saving space.</p>
  5294. <p>Purging media files will be the carried out by the media worker
  5295. (that is, the worker that has the <code>enable_media_repo</code> homeserver config
  5296. option set to 'true'). This may be the main process.</p>
  5297. <p>The <code>media_retention.local_media_lifetime</code> and
  5298. <code>media_retention.remote_media_lifetime</code> config options control whether
  5299. media will be purged if it has not been accessed in a given amount of
  5300. time. Note that media is 'accessed' when loaded in a room in a client, or
  5301. otherwise downloaded by a local or remote user. If the media has never
  5302. been accessed, the media's creation time is used instead. Both thumbnails
  5303. and the original media will be removed. If either of these options are unset,
  5304. then media of that type will not be purged.</p>
  5305. <p>Local or cached remote media that has been
  5306. <a href="usage/configuration/../../admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantined</a>
  5307. will not be deleted. Similarly, local media that has been marked as
  5308. <a href="usage/configuration/../../admin_api/media_admin_api.html#protecting-media-from-being-quarantined">protected from quarantine</a>
  5309. will not be deleted.</p>
  5310. <p>Example configuration:</p>
  5311. <pre><code class="language-yaml">media_retention:
  5312. local_media_lifetime: 90d
  5313. remote_media_lifetime: 14d
  5314. </code></pre>
  5315. <hr />
  5316. <h3 id="url_preview_enabled"><a class="header" href="#url_preview_enabled"><code>url_preview_enabled</code></a></h3>
  5317. <p>This setting determines whether the preview URL API is enabled.
  5318. It is disabled by default. Set to true to enable. If enabled you must specify a
  5319. <code>url_preview_ip_range_blacklist</code> blacklist.</p>
  5320. <p>Example configuration:</p>
  5321. <pre><code class="language-yaml">url_preview_enabled: true
  5322. </code></pre>
  5323. <hr />
  5324. <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>
  5325. <p>List of IP address CIDR ranges that the URL preview spider is denied
  5326. from accessing. There are no defaults: you must explicitly
  5327. specify a list for URL previewing to work. You should specify any
  5328. internal services in your network that you do not want synapse to try
  5329. to connect to, otherwise anyone in any Matrix room could cause your
  5330. synapse to issue arbitrary GET requests to your internal services,
  5331. causing serious security issues.</p>
  5332. <p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  5333. listed here, since they correspond to unroutable addresses.)</p>
  5334. <p>This must be specified if <code>url_preview_enabled</code> is set. It is recommended that
  5335. you use the following example list as a starting point.</p>
  5336. <p>Note: The value is ignored when an HTTP proxy is in use.</p>
  5337. <p>Example configuration:</p>
  5338. <pre><code class="language-yaml">url_preview_ip_range_blacklist:
  5339. - '127.0.0.0/8'
  5340. - '10.0.0.0/8'
  5341. - '172.16.0.0/12'
  5342. - '192.168.0.0/16'
  5343. - '100.64.0.0/10'
  5344. - '192.0.0.0/24'
  5345. - '169.254.0.0/16'
  5346. - '192.88.99.0/24'
  5347. - '198.18.0.0/15'
  5348. - '192.0.2.0/24'
  5349. - '198.51.100.0/24'
  5350. - '203.0.113.0/24'
  5351. - '224.0.0.0/4'
  5352. - '::1/128'
  5353. - 'fe80::/10'
  5354. - 'fc00::/7'
  5355. - '2001:db8::/32'
  5356. - 'ff00::/8'
  5357. - 'fec0::/10'
  5358. </code></pre>
  5359. <hr />
  5360. <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>
  5361. <p>This option sets a list of IP address CIDR ranges that the URL preview spider is allowed
  5362. to access even if they are specified in <code>url_preview_ip_range_blacklist</code>.
  5363. This is useful for specifying exceptions to wide-ranging blacklisted
  5364. target IP ranges - e.g. for enabling URL previews for a specific private
  5365. website only visible in your network. Defaults to none.</p>
  5366. <p>Example configuration:</p>
  5367. <pre><code class="language-yaml">url_preview_ip_range_whitelist:
  5368. - '192.168.1.1'
  5369. </code></pre>
  5370. <hr />
  5371. <h3 id="url_preview_url_blacklist"><a class="header" href="#url_preview_url_blacklist"><code>url_preview_url_blacklist</code></a></h3>
  5372. <p>Optional list of URL matches that the URL preview spider is
  5373. denied from accessing. You should use <code>url_preview_ip_range_blacklist</code>
  5374. in preference to this, otherwise someone could define a public DNS
  5375. entry that points to a private IP address and circumvent the blacklist.
  5376. This is more useful if you know there is an entire shape of URL that
  5377. you know that will never want synapse to try to spider.</p>
  5378. <p>Each list entry is a dictionary of url component attributes as returned
  5379. by urlparse.urlsplit as applied to the absolute form of the URL. See
  5380. <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit">here</a> for more
  5381. information. Some examples are:</p>
  5382. <ul>
  5383. <li><code>username</code></li>
  5384. <li><code>netloc</code></li>
  5385. <li><code>scheme</code></li>
  5386. <li><code>path</code></li>
  5387. </ul>
  5388. <p>The values of the dictionary are treated as a filename match pattern
  5389. applied to that component of URLs, unless they start with a ^ in which
  5390. case they are treated as a regular expression match. If all the
  5391. specified component matches for a given list item succeed, the URL is
  5392. blacklisted.</p>
  5393. <p>Example configuration:</p>
  5394. <pre><code class="language-yaml">url_preview_url_blacklist:
  5395. # blacklist any URL with a username in its URI
  5396. - username: '*'
  5397. # blacklist all *.google.com URLs
  5398. - netloc: 'google.com'
  5399. - netloc: '*.google.com'
  5400. # blacklist all plain HTTP URLs
  5401. - scheme: 'http'
  5402. # blacklist http(s)://www.acme.com/foo
  5403. - netloc: 'www.acme.com'
  5404. path: '/foo'
  5405. # blacklist any URL with a literal IPv4 address
  5406. - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
  5407. </code></pre>
  5408. <hr />
  5409. <h3 id="max_spider_size"><a class="header" href="#max_spider_size"><code>max_spider_size</code></a></h3>
  5410. <p>The largest allowed URL preview spidering size in bytes. Defaults to 10M.</p>
  5411. <p>Example configuration:</p>
  5412. <pre><code class="language-yaml">max_spider_size: 8M
  5413. </code></pre>
  5414. <hr />
  5415. <h3 id="url_preview_accept_language"><a class="header" href="#url_preview_accept_language"><code>url_preview_accept_language</code></a></h3>
  5416. <p>A list of values for the Accept-Language HTTP header used when
  5417. downloading webpages during URL preview generation. This allows
  5418. Synapse to specify the preferred languages that URL previews should
  5419. be in when communicating with remote servers.</p>
  5420. <p>Each value is a IETF language tag; a 2-3 letter identifier for a
  5421. language, optionally followed by subtags separated by '-', specifying
  5422. a country or region variant.</p>
  5423. <p>Multiple values can be provided, and a weight can be added to each by
  5424. using quality value syntax (;q=). '*' translates to any language.</p>
  5425. <p>Defaults to &quot;en&quot;.</p>
  5426. <p>Example configuration:</p>
  5427. <pre><code class="language-yaml"> url_preview_accept_language:
  5428. - 'en-UK'
  5429. - 'en-US;q=0.9'
  5430. - 'fr;q=0.8'
  5431. - '*;q=0.7'
  5432. </code></pre>
  5433. <hr />
  5434. <h3 id="oembed"><a class="header" href="#oembed"><code>oembed</code></a></h3>
  5435. <p>oEmbed allows for easier embedding content from a website. It can be
  5436. used for generating URLs previews of services which support it. A default list of oEmbed providers
  5437. is included with Synapse. Set <code>disable_default_providers</code> to true to disable using
  5438. these default oEmbed URLs. Use <code>additional_providers</code> to specify additional files with oEmbed configuration (each
  5439. should be in the form of providers.json). By default this list is empty.</p>
  5440. <p>Example configuration:</p>
  5441. <pre><code class="language-yaml">oembed:
  5442. disable_default_providers: true
  5443. additional_providers:
  5444. - oembed/my_providers.json
  5445. </code></pre>
  5446. <hr />
  5447. <h2 id="captcha"><a class="header" href="#captcha">Captcha</a></h2>
  5448. <p>See <a href="usage/configuration/../../CAPTCHA_SETUP.html">here</a> for full details on setting up captcha.</p>
  5449. <hr />
  5450. <h3 id="recaptcha_public_key"><a class="header" href="#recaptcha_public_key"><code>recaptcha_public_key</code></a></h3>
  5451. <p>This homeserver's ReCAPTCHA public key. Must be specified if
  5452. <a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a> is enabled.</p>
  5453. <p>Example configuration:</p>
  5454. <pre><code class="language-yaml">recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  5455. </code></pre>
  5456. <hr />
  5457. <h3 id="recaptcha_private_key"><a class="header" href="#recaptcha_private_key"><code>recaptcha_private_key</code></a></h3>
  5458. <p>This homeserver's ReCAPTCHA private key. Must be specified if
  5459. <a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a> is
  5460. enabled.</p>
  5461. <p>Example configuration:</p>
  5462. <pre><code class="language-yaml">recaptcha_private_key: &quot;YOUR_PRIVATE_KEY&quot;
  5463. </code></pre>
  5464. <hr />
  5465. <h3 id="enable_registration_captcha"><a class="header" href="#enable_registration_captcha"><code>enable_registration_captcha</code></a></h3>
  5466. <p>Set to <code>true</code> to require users to complete a CAPTCHA test when registering an account.
  5467. Requires a valid ReCaptcha public/private key.
  5468. Defaults to <code>false</code>.</p>
  5469. <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>
  5470. <p>Example configuration:</p>
  5471. <pre><code class="language-yaml">enable_registration_captcha: true
  5472. </code></pre>
  5473. <hr />
  5474. <h3 id="recaptcha_siteverify_api"><a class="header" href="#recaptcha_siteverify_api"><code>recaptcha_siteverify_api</code></a></h3>
  5475. <p>The API endpoint to use for verifying <code>m.login.recaptcha</code> responses.
  5476. Defaults to <code>https://www.recaptcha.net/recaptcha/api/siteverify</code>.</p>
  5477. <p>Example configuration:</p>
  5478. <pre><code class="language-yaml">recaptcha_siteverify_api: &quot;https://my.recaptcha.site&quot;
  5479. </code></pre>
  5480. <hr />
  5481. <h2 id="turn"><a class="header" href="#turn">TURN</a></h2>
  5482. <p>Options related to adding a TURN server to Synapse.</p>
  5483. <hr />
  5484. <h3 id="turn_uris"><a class="header" href="#turn_uris"><code>turn_uris</code></a></h3>
  5485. <p>The public URIs of the TURN server to give to clients.</p>
  5486. <p>Example configuration:</p>
  5487. <pre><code class="language-yaml">turn_uris: [turn:example.org]
  5488. </code></pre>
  5489. <hr />
  5490. <h3 id="turn_shared_secret"><a class="header" href="#turn_shared_secret"><code>turn_shared_secret</code></a></h3>
  5491. <p>The shared secret used to compute passwords for the TURN server.</p>
  5492. <p>Example configuration:</p>
  5493. <pre><code class="language-yaml">turn_shared_secret: &quot;YOUR_SHARED_SECRET&quot;
  5494. </code></pre>
  5495. <hr />
  5496. <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>
  5497. <p>The Username and password if the TURN server needs them and does not use a token.</p>
  5498. <p>Example configuration:</p>
  5499. <pre><code class="language-yaml">turn_username: &quot;TURNSERVER_USERNAME&quot;
  5500. turn_password: &quot;TURNSERVER_PASSWORD&quot;
  5501. </code></pre>
  5502. <hr />
  5503. <h3 id="turn_user_lifetime"><a class="header" href="#turn_user_lifetime"><code>turn_user_lifetime</code></a></h3>
  5504. <p>How long generated TURN credentials last. Defaults to 1h.</p>
  5505. <p>Example configuration:</p>
  5506. <pre><code class="language-yaml">turn_user_lifetime: 2h
  5507. </code></pre>
  5508. <hr />
  5509. <h3 id="turn_allow_guests"><a class="header" href="#turn_allow_guests"><code>turn_allow_guests</code></a></h3>
  5510. <p>Whether guests should be allowed to use the TURN server. This defaults to true, otherwise
  5511. VoIP will be unreliable for guests. However, it does introduce a slight security risk as
  5512. it allows users to connect to arbitrary endpoints without having first signed up for a valid account (e.g. by passing a CAPTCHA).</p>
  5513. <p>Example configuration:</p>
  5514. <pre><code class="language-yaml">turn_allow_guests: false
  5515. </code></pre>
  5516. <hr />
  5517. <h2 id="registration"><a class="header" href="#registration">Registration</a></h2>
  5518. <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>
  5519. <hr />
  5520. <h3 id="enable_registration"><a class="header" href="#enable_registration"><code>enable_registration</code></a></h3>
  5521. <p>Enable registration for new users. Defaults to <code>false</code>.</p>
  5522. <p>It is highly recommended that if you enable registration, you set one or more
  5523. or the following options, to avoid abuse of your server by &quot;bots&quot;:</p>
  5524. <ul>
  5525. <li><a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a></li>
  5526. <li><a href="usage/configuration/config_documentation.html#registrations_require_3pid"><code>registrations_require_3pid</code></a></li>
  5527. <li><a href="usage/configuration/config_documentation.html#registration_requires_token"><code>registration_requires_token</code></a></li>
  5528. </ul>
  5529. <p>(In order to enable registration without any verification, you must also set
  5530. <a href="usage/configuration/config_documentation.html#enable_registration_without_verification"><code>enable_registration_without_verification</code></a>.)</p>
  5531. <p>Note that even if this setting is disabled, new accounts can still be created
  5532. via the admin API if
  5533. <a href="usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a> is set.</p>
  5534. <p>Example configuration:</p>
  5535. <pre><code class="language-yaml">enable_registration: true
  5536. </code></pre>
  5537. <hr />
  5538. <h3 id="enable_registration_without_verification"><a class="header" href="#enable_registration_without_verification"><code>enable_registration_without_verification</code></a></h3>
  5539. <p>Enable registration without email or captcha verification. Note: this option is <em>not</em> recommended,
  5540. as registration without verification is a known vector for spam and abuse. Defaults to <code>false</code>. Has no effect
  5541. unless <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> is also enabled.</p>
  5542. <p>Example configuration:</p>
  5543. <pre><code class="language-yaml">enable_registration_without_verification: true
  5544. </code></pre>
  5545. <hr />
  5546. <h3 id="registrations_require_3pid"><a class="header" href="#registrations_require_3pid"><code>registrations_require_3pid</code></a></h3>
  5547. <p>If this is set, users must provide all of the specified types of 3PID when registering an account.</p>
  5548. <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>
  5549. <p>Example configuration:</p>
  5550. <pre><code class="language-yaml">registrations_require_3pid:
  5551. - email
  5552. - msisdn
  5553. </code></pre>
  5554. <hr />
  5555. <h3 id="disable_msisdn_registration"><a class="header" href="#disable_msisdn_registration"><code>disable_msisdn_registration</code></a></h3>
  5556. <p>Explicitly disable asking for MSISDNs from the registration
  5557. flow (overrides <code>registrations_require_3pid</code> if MSISDNs are set as required).</p>
  5558. <p>Example configuration:</p>
  5559. <pre><code class="language-yaml">disable_msisdn_registration: true
  5560. </code></pre>
  5561. <hr />
  5562. <h3 id="allowed_local_3pids"><a class="header" href="#allowed_local_3pids"><code>allowed_local_3pids</code></a></h3>
  5563. <p>Mandate that users are only allowed to associate certain formats of
  5564. 3PIDs with accounts on this server, as specified by the <code>medium</code> and <code>pattern</code> sub-options.</p>
  5565. <p>Example configuration:</p>
  5566. <pre><code class="language-yaml">allowed_local_3pids:
  5567. - medium: email
  5568. pattern: '^[^@]+@matrix\.org$'
  5569. - medium: email
  5570. pattern: '^[^@]+@vector\.im$'
  5571. - medium: msisdn
  5572. pattern: '\+44'
  5573. </code></pre>
  5574. <hr />
  5575. <h3 id="enable_3pid_lookup"><a class="header" href="#enable_3pid_lookup"><code>enable_3pid_lookup</code></a></h3>
  5576. <p>Enable 3PIDs lookup requests to identity servers from this server. Defaults to true.</p>
  5577. <p>Example configuration:</p>
  5578. <pre><code class="language-yaml">enable_3pid_lookup: false
  5579. </code></pre>
  5580. <hr />
  5581. <h3 id="registration_requires_token"><a class="header" href="#registration_requires_token"><code>registration_requires_token</code></a></h3>
  5582. <p>Require users to submit a token during registration.
  5583. Tokens can be managed using the admin <a href="usage/configuration/../administration/admin_api/registration_tokens.html">API</a>.
  5584. Disabling this option will not delete any tokens previously generated.
  5585. Defaults to <code>false</code>. Set to <code>true</code> to enable.</p>
  5586. <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>
  5587. <p>Example configuration:</p>
  5588. <pre><code class="language-yaml">registration_requires_token: true
  5589. </code></pre>
  5590. <hr />
  5591. <h3 id="registration_shared_secret"><a class="header" href="#registration_shared_secret"><code>registration_shared_secret</code></a></h3>
  5592. <p>If set, allows registration of standard or admin accounts by anyone who has the
  5593. shared secret, even if <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> is not
  5594. set.</p>
  5595. <p>This is primarily intended for use with the <code>register_new_matrix_user</code> script
  5596. (see <a href="usage/configuration/../../setup/installation.html#registering-a-user">Registering a user</a>);
  5597. however, the interface is <a href="usage/configuration/../../admin_api/register_api.html">documented</a>.</p>
  5598. <p>See also <a href="usage/configuration/config_documentation.html#registration_shared_secret_path"><code>registration_shared_secret_path</code></a>.</p>
  5599. <p>Example configuration:</p>
  5600. <pre><code class="language-yaml">registration_shared_secret: &lt;PRIVATE STRING&gt;
  5601. </code></pre>
  5602. <hr />
  5603. <h3 id="registration_shared_secret_path"><a class="header" href="#registration_shared_secret_path"><code>registration_shared_secret_path</code></a></h3>
  5604. <p>An alternative to <a href="usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>:
  5605. allows the shared secret to be specified in an external file.</p>
  5606. <p>The file should be a plain text file, containing only the shared secret.</p>
  5607. <p>If this file does not exist, Synapse will create a new shared
  5608. secret on startup and store it in this file.</p>
  5609. <p>Example configuration:</p>
  5610. <pre><code class="language-yaml">registration_shared_secret_path: /path/to/secrets/file
  5611. </code></pre>
  5612. <p><em>Added in Synapse 1.67.0.</em></p>
  5613. <hr />
  5614. <h3 id="bcrypt_rounds"><a class="header" href="#bcrypt_rounds"><code>bcrypt_rounds</code></a></h3>
  5615. <p>Set the number of bcrypt rounds used to generate password hash.
  5616. Larger numbers increase the work factor needed to generate the hash.
  5617. The default number is 12 (which equates to 2^12 rounds).
  5618. N.B. that increasing this will exponentially increase the time required
  5619. to register or login - e.g. 24 =&gt; 2^24 rounds which will take &gt;20 mins.
  5620. Example configuration:</p>
  5621. <pre><code class="language-yaml">bcrypt_rounds: 14
  5622. </code></pre>
  5623. <hr />
  5624. <h3 id="allow_guest_access"><a class="header" href="#allow_guest_access"><code>allow_guest_access</code></a></h3>
  5625. <p>Allows users to register as guests without a password/email/etc, and
  5626. participate in rooms hosted on this server which have been made
  5627. accessible to anonymous users. Defaults to false.</p>
  5628. <p>Example configuration:</p>
  5629. <pre><code class="language-yaml">allow_guest_access: true
  5630. </code></pre>
  5631. <hr />
  5632. <h3 id="default_identity_server"><a class="header" href="#default_identity_server"><code>default_identity_server</code></a></h3>
  5633. <p>The identity server which we suggest that clients should use when users log
  5634. in on this server.</p>
  5635. <p>(By default, no suggestion is made, so it is left up to the client.
  5636. This setting is ignored unless <code>public_baseurl</code> is also explicitly set.)</p>
  5637. <p>Example configuration:</p>
  5638. <pre><code class="language-yaml">default_identity_server: https://matrix.org
  5639. </code></pre>
  5640. <hr />
  5641. <h3 id="account_threepid_delegates"><a class="header" href="#account_threepid_delegates"><code>account_threepid_delegates</code></a></h3>
  5642. <p>Delegate verification of phone numbers to an identity server.</p>
  5643. <p>When a user wishes to add a phone number to their account, we need to verify that they
  5644. actually own that phone number, which requires sending them a text message (SMS).
  5645. Currently Synapse does not support sending those texts itself and instead delegates the
  5646. task to an identity server. The base URI for the identity server to be used is
  5647. specified by the <code>account_threepid_delegates.msisdn</code> option.</p>
  5648. <p>If this is left unspecified, Synapse will not allow users to add phone numbers to
  5649. their account.</p>
  5650. <p>(Servers handling the these requests must answer the <code>/requestToken</code> endpoints defined
  5651. by the Matrix Identity Service API
  5652. <a href="https://matrix.org/docs/spec/identity_service/latest">specification</a>.)</p>
  5653. <p><em>Deprecated in Synapse 1.64.0</em>: The <code>email</code> option is deprecated.</p>
  5654. <p><em>Removed in Synapse 1.66.0</em>: The <code>email</code> option has been removed.
  5655. If present, Synapse will report a configuration error on startup.</p>
  5656. <p>Example configuration:</p>
  5657. <pre><code class="language-yaml">account_threepid_delegates:
  5658. msisdn: http://localhost:8090 # Delegate SMS sending to this local process
  5659. </code></pre>
  5660. <hr />
  5661. <h3 id="enable_set_displayname"><a class="header" href="#enable_set_displayname"><code>enable_set_displayname</code></a></h3>
  5662. <p>Whether users are allowed to change their displayname after it has
  5663. been initially set. Useful when provisioning users based on the
  5664. contents of a third-party directory.</p>
  5665. <p>Does not apply to server administrators. Defaults to true.</p>
  5666. <p>Example configuration:</p>
  5667. <pre><code class="language-yaml">enable_set_displayname: false
  5668. </code></pre>
  5669. <hr />
  5670. <h3 id="enable_set_avatar_url"><a class="header" href="#enable_set_avatar_url"><code>enable_set_avatar_url</code></a></h3>
  5671. <p>Whether users are allowed to change their avatar after it has been
  5672. initially set. Useful when provisioning users based on the contents
  5673. of a third-party directory.</p>
  5674. <p>Does not apply to server administrators. Defaults to true.</p>
  5675. <p>Example configuration:</p>
  5676. <pre><code class="language-yaml">enable_set_avatar_url: false
  5677. </code></pre>
  5678. <hr />
  5679. <h3 id="enable_3pid_changes"><a class="header" href="#enable_3pid_changes"><code>enable_3pid_changes</code></a></h3>
  5680. <p>Whether users can change the third-party IDs associated with their accounts
  5681. (email address and msisdn).</p>
  5682. <p>Defaults to true.</p>
  5683. <p>Example configuration:</p>
  5684. <pre><code class="language-yaml">enable_3pid_changes: false
  5685. </code></pre>
  5686. <hr />
  5687. <h3 id="auto_join_rooms"><a class="header" href="#auto_join_rooms"><code>auto_join_rooms</code></a></h3>
  5688. <p>Users who register on this homeserver will automatically be joined
  5689. to the rooms listed under this option.</p>
  5690. <p>By default, any room aliases included in this list will be created
  5691. as a publicly joinable room when the first user registers for the
  5692. homeserver. If the room already exists, make certain it is a publicly joinable
  5693. room, i.e. the join rule of the room must be set to 'public'. You can find more options
  5694. relating to auto-joining rooms below.</p>
  5695. <p>As Spaces are just rooms under the hood, Space aliases may also be
  5696. used.</p>
  5697. <p>Example configuration:</p>
  5698. <pre><code class="language-yaml">auto_join_rooms:
  5699. - &quot;#exampleroom:example.com&quot;
  5700. - &quot;#anotherexampleroom:example.com&quot;
  5701. </code></pre>
  5702. <hr />
  5703. <h3 id="autocreate_auto_join_rooms"><a class="header" href="#autocreate_auto_join_rooms"><code>autocreate_auto_join_rooms</code></a></h3>
  5704. <p>Where <code>auto_join_rooms</code> are specified, setting this flag ensures that
  5705. the rooms exist by creating them when the first user on the
  5706. homeserver registers. This option will not create Spaces.</p>
  5707. <p>By default the auto-created rooms are publicly joinable from any federated
  5708. server. Use the <code>autocreate_auto_join_rooms_federated</code> and
  5709. <code>autocreate_auto_join_room_preset</code> settings to customise this behaviour.</p>
  5710. <p>Setting to false means that if the rooms are not manually created,
  5711. users cannot be auto-joined since they do not exist.</p>
  5712. <p>Defaults to true.</p>
  5713. <p>Example configuration:</p>
  5714. <pre><code class="language-yaml">autocreate_auto_join_rooms: false
  5715. </code></pre>
  5716. <hr />
  5717. <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>
  5718. <p>Whether the rooms listed in <code>auto_join_rooms</code> that are auto-created are available
  5719. via federation. Only has an effect if <code>autocreate_auto_join_rooms</code> is true.</p>
  5720. <p>Note that whether a room is federated cannot be modified after
  5721. creation.</p>
  5722. <p>Defaults to true: the room will be joinable from other servers.
  5723. Set to false to prevent users from other homeservers from
  5724. joining these rooms.</p>
  5725. <p>Example configuration:</p>
  5726. <pre><code class="language-yaml">autocreate_auto_join_rooms_federated: false
  5727. </code></pre>
  5728. <hr />
  5729. <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>
  5730. <p>The room preset to use when auto-creating one of <code>auto_join_rooms</code>. Only has an
  5731. effect if <code>autocreate_auto_join_rooms</code> is true.</p>
  5732. <p>Possible values for this option are:</p>
  5733. <ul>
  5734. <li>&quot;public_chat&quot;: the room is joinable by anyone, including
  5735. federated servers if <code>autocreate_auto_join_rooms_federated</code> is true (the default).</li>
  5736. <li>&quot;private_chat&quot;: an invitation is required to join these rooms.</li>
  5737. <li>&quot;trusted_private_chat&quot;: an invitation is required to join this room and the invitee is
  5738. assigned a power level of 100 upon joining the room.</li>
  5739. </ul>
  5740. <p>If a value of &quot;private_chat&quot; or &quot;trusted_private_chat&quot; is used then
  5741. <code>auto_join_mxid_localpart</code> must also be configured.</p>
  5742. <p>Defaults to &quot;public_chat&quot;.</p>
  5743. <p>Example configuration:</p>
  5744. <pre><code class="language-yaml">autocreate_auto_join_room_preset: private_chat
  5745. </code></pre>
  5746. <hr />
  5747. <h3 id="auto_join_mxid_localpart"><a class="header" href="#auto_join_mxid_localpart"><code>auto_join_mxid_localpart</code></a></h3>
  5748. <p>The local part of the user id which is used to create <code>auto_join_rooms</code> if
  5749. <code>autocreate_auto_join_rooms</code> is true. If this is not provided then the
  5750. initial user account that registers will be used to create the rooms.</p>
  5751. <p>The user id is also used to invite new users to any auto-join rooms which
  5752. are set to invite-only.</p>
  5753. <p>It <em>must</em> be configured if <code>autocreate_auto_join_room_preset</code> is set to
  5754. &quot;private_chat&quot; or &quot;trusted_private_chat&quot;.</p>
  5755. <p>Note that this must be specified in order for new users to be correctly
  5756. invited to any auto-join rooms which have been set to invite-only (either
  5757. at the time of creation or subsequently).</p>
  5758. <p>Note that, if the room already exists, this user must be joined and
  5759. have the appropriate permissions to invite new members.</p>
  5760. <p>Example configuration:</p>
  5761. <pre><code class="language-yaml">auto_join_mxid_localpart: system
  5762. </code></pre>
  5763. <hr />
  5764. <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>
  5765. <p>When <code>auto_join_rooms</code> is specified, setting this flag to false prevents
  5766. guest accounts from being automatically joined to the rooms.</p>
  5767. <p>Defaults to true.</p>
  5768. <p>Example configuration:</p>
  5769. <pre><code class="language-yaml">auto_join_rooms_for_guests: false
  5770. </code></pre>
  5771. <hr />
  5772. <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>
  5773. <p>Whether to inhibit errors raised when registering a new account if the user ID
  5774. already exists. If turned on, requests to <code>/register/available</code> will always
  5775. show a user ID as available, and Synapse won't raise an error when starting
  5776. a registration with a user ID that already exists. However, Synapse will still
  5777. raise an error if the registration completes and the username conflicts.</p>
  5778. <p>Defaults to false.</p>
  5779. <p>Example configuration:</p>
  5780. <pre><code class="language-yaml">inhibit_user_in_use_error: true
  5781. </code></pre>
  5782. <hr />
  5783. <h2 id="user-session-management"><a class="header" href="#user-session-management">User session management</a></h2>
  5784. <hr />
  5785. <h3 id="session_lifetime"><a class="header" href="#session_lifetime"><code>session_lifetime</code></a></h3>
  5786. <p>Time that a user's session remains valid for, after they log in.</p>
  5787. <p>Note that this is not currently compatible with guest logins.</p>
  5788. <p>Note also that this is calculated at login time: changes are not applied retrospectively to users who have already
  5789. logged in.</p>
  5790. <p>By default, this is infinite.</p>
  5791. <p>Example configuration:</p>
  5792. <pre><code class="language-yaml">session_lifetime: 24h
  5793. </code></pre>
  5794. <hr />
  5795. <h3 id="refresh_access_token_lifetime"><a class="header" href="#refresh_access_token_lifetime"><code>refresh_access_token_lifetime</code></a></h3>
  5796. <p>Time that an access token remains valid for, if the session is using refresh tokens.</p>
  5797. <p>For more information about refresh tokens, please see the <a href="usage/configuration/user_authentication/refresh_tokens.html">manual</a>.</p>
  5798. <p>Note that this only applies to clients which advertise support for refresh tokens.</p>
  5799. <p>Note also that this is calculated at login time and refresh time: changes are not applied to
  5800. existing sessions until they are refreshed.</p>
  5801. <p>By default, this is 5 minutes.</p>
  5802. <p>Example configuration:</p>
  5803. <pre><code class="language-yaml">refreshable_access_token_lifetime: 10m
  5804. </code></pre>
  5805. <hr />
  5806. <h3 id="refresh_token_lifetime-24h"><a class="header" href="#refresh_token_lifetime-24h"><code>refresh_token_lifetime: 24h</code></a></h3>
  5807. <p>Time that a refresh token remains valid for (provided that it is not
  5808. exchanged for another one first).
  5809. This option can be used to automatically log-out inactive sessions.
  5810. Please see the manual for more information.</p>
  5811. <p>Note also that this is calculated at login time and refresh time:
  5812. changes are not applied to existing sessions until they are refreshed.</p>
  5813. <p>By default, this is infinite.</p>
  5814. <p>Example configuration:</p>
  5815. <pre><code class="language-yaml">refresh_token_lifetime: 24h
  5816. </code></pre>
  5817. <hr />
  5818. <h3 id="nonrefreshable_access_token_lifetime"><a class="header" href="#nonrefreshable_access_token_lifetime"><code>nonrefreshable_access_token_lifetime</code></a></h3>
  5819. <p>Time that an access token remains valid for, if the session is NOT
  5820. using refresh tokens.</p>
  5821. <p>Please note that not all clients support refresh tokens, so setting
  5822. this to a short value may be inconvenient for some users who will
  5823. then be logged out frequently.</p>
  5824. <p>Note also that this is calculated at login time: changes are not applied
  5825. retrospectively to existing sessions for users that have already logged in.</p>
  5826. <p>By default, this is infinite.</p>
  5827. <p>Example configuration:</p>
  5828. <pre><code class="language-yaml">nonrefreshable_access_token_lifetime: 24h
  5829. </code></pre>
  5830. <hr />
  5831. <h3 id="ui_auth"><a class="header" href="#ui_auth"><code>ui_auth</code></a></h3>
  5832. <p>The amount of time to allow a user-interactive authentication session to be active.</p>
  5833. <p>This defaults to 0, meaning the user is queried for their credentials
  5834. before every action, but this can be overridden to allow a single
  5835. validation to be re-used. This weakens the protections afforded by
  5836. the user-interactive authentication process, by allowing for multiple
  5837. (and potentially different) operations to use the same validation session.</p>
  5838. <p>This is ignored for potentially &quot;dangerous&quot; operations (including
  5839. deactivating an account, modifying an account password, adding a 3PID,
  5840. and minting additional login tokens).</p>
  5841. <p>Use the <code>session_timeout</code> sub-option here to change the time allowed for credential validation.</p>
  5842. <p>Example configuration:</p>
  5843. <pre><code class="language-yaml">ui_auth:
  5844. session_timeout: &quot;15s&quot;
  5845. </code></pre>
  5846. <hr />
  5847. <h3 id="login_via_existing_session"><a class="header" href="#login_via_existing_session"><code>login_via_existing_session</code></a></h3>
  5848. <p>Matrix supports the ability of an existing session to mint a login token for
  5849. another client.</p>
  5850. <p>Synapse disables this by default as it has security ramifications -- a malicious
  5851. client could use the mechanism to spawn more than one session.</p>
  5852. <p>The duration of time the generated token is valid for can be configured with the
  5853. <code>token_timeout</code> sub-option.</p>
  5854. <p>User-interactive authentication is required when this is enabled unless the
  5855. <code>require_ui_auth</code> sub-option is set to <code>False</code>.</p>
  5856. <p>Example configuration:</p>
  5857. <pre><code class="language-yaml">login_via_existing_session:
  5858. enabled: true
  5859. require_ui_auth: false
  5860. token_timeout: &quot;5m&quot;
  5861. </code></pre>
  5862. <hr />
  5863. <h2 id="metrics"><a class="header" href="#metrics">Metrics</a></h2>
  5864. <p>Config options related to metrics.</p>
  5865. <hr />
  5866. <h3 id="enable_metrics"><a class="header" href="#enable_metrics"><code>enable_metrics</code></a></h3>
  5867. <p>Set to true to enable collection and rendering of performance metrics.
  5868. Defaults to false.</p>
  5869. <p>Example configuration:</p>
  5870. <pre><code class="language-yaml">enable_metrics: true
  5871. </code></pre>
  5872. <hr />
  5873. <h3 id="sentry"><a class="header" href="#sentry"><code>sentry</code></a></h3>
  5874. <p>Use this option to enable sentry integration. Provide the DSN assigned to you by sentry
  5875. with the <code>dsn</code> setting.</p>
  5876. <p>NOTE: While attempts are made to ensure that the logs don't contain
  5877. any sensitive information, this cannot be guaranteed. By enabling
  5878. this option the sentry server may therefore receive sensitive
  5879. information, and it in turn may then disseminate sensitive information
  5880. through insecure notification channels if so configured.</p>
  5881. <p>Example configuration:</p>
  5882. <pre><code class="language-yaml">sentry:
  5883. dsn: &quot;...&quot;
  5884. </code></pre>
  5885. <hr />
  5886. <h3 id="metrics_flags"><a class="header" href="#metrics_flags"><code>metrics_flags</code></a></h3>
  5887. <p>Flags to enable Prometheus metrics which are not suitable to be
  5888. enabled by default, either for performance reasons or limited use.
  5889. Currently the only option is <code>known_servers</code>, which publishes
  5890. <code>synapse_federation_known_servers</code>, a gauge of the number of
  5891. servers this homeserver knows about, including itself. May cause
  5892. performance problems on large homeservers.</p>
  5893. <p>Example configuration:</p>
  5894. <pre><code class="language-yaml">metrics_flags:
  5895. known_servers: true
  5896. </code></pre>
  5897. <hr />
  5898. <h3 id="report_stats"><a class="header" href="#report_stats"><code>report_stats</code></a></h3>
  5899. <p>Whether or not to report homeserver usage statistics. This is originally
  5900. set when generating the config. Set this option to true or false to change the current
  5901. behavior. See
  5902. <a href="usage/configuration/../administration/monitoring/reporting_homeserver_usage_statistics.html">Reporting Homeserver Usage Statistics</a>
  5903. for information on what data is reported.</p>
  5904. <p>Statistics will be reported 5 minutes after Synapse starts, and then every 3 hours
  5905. after that.</p>
  5906. <p>Example configuration:</p>
  5907. <pre><code class="language-yaml">report_stats: true
  5908. </code></pre>
  5909. <hr />
  5910. <h3 id="report_stats_endpoint"><a class="header" href="#report_stats_endpoint"><code>report_stats_endpoint</code></a></h3>
  5911. <p>The endpoint to report homeserver usage statistics to.
  5912. Defaults to https://matrix.org/report-usage-stats/push</p>
  5913. <p>Example configuration:</p>
  5914. <pre><code class="language-yaml">report_stats_endpoint: https://example.com/report-usage-stats/push
  5915. </code></pre>
  5916. <hr />
  5917. <h2 id="api-configuration"><a class="header" href="#api-configuration">API Configuration</a></h2>
  5918. <p>Config settings related to the client/server API</p>
  5919. <hr />
  5920. <h3 id="room_prejoin_state"><a class="header" href="#room_prejoin_state"><code>room_prejoin_state</code></a></h3>
  5921. <p>This setting controls the state that is shared with users upon receiving an
  5922. invite to a room, or in reply to a knock on a room. By default, the following
  5923. state events are shared with users:</p>
  5924. <ul>
  5925. <li><code>m.room.join_rules</code></li>
  5926. <li><code>m.room.canonical_alias</code></li>
  5927. <li><code>m.room.avatar</code></li>
  5928. <li><code>m.room.encryption</code></li>
  5929. <li><code>m.room.name</code></li>
  5930. <li><code>m.room.create</code></li>
  5931. <li><code>m.room.topic</code></li>
  5932. </ul>
  5933. <p>To change the default behavior, use the following sub-options:</p>
  5934. <ul>
  5935. <li>
  5936. <p><code>disable_default_event_types</code>: boolean. Set to <code>true</code> to disable the above
  5937. defaults. If this is enabled, only the event types listed in
  5938. <code>additional_event_types</code> are shared. Defaults to <code>false</code>.</p>
  5939. </li>
  5940. <li>
  5941. <p><code>additional_event_types</code>: A list of additional state events to include in the
  5942. events to be shared. By default, this list is empty (so only the default event
  5943. types are shared).</p>
  5944. <p>Each entry in this list should be either a single string or a list of two
  5945. strings.</p>
  5946. <ul>
  5947. <li>A standalone string <code>t</code> represents all events with type <code>t</code> (i.e.
  5948. with no restrictions on state keys).</li>
  5949. <li>A pair of strings <code>[t, s]</code> represents a single event with type <code>t</code> and
  5950. state key <code>s</code>. The same type can appear in two entries with different state
  5951. keys: in this situation, both state keys are included in prejoin state.</li>
  5952. </ul>
  5953. </li>
  5954. </ul>
  5955. <p>Example configuration:</p>
  5956. <pre><code class="language-yaml">room_prejoin_state:
  5957. disable_default_event_types: false
  5958. additional_event_types:
  5959. # Share all events of type `org.example.custom.event.typeA`
  5960. - org.example.custom.event.typeA
  5961. # Share only events of type `org.example.custom.event.typeB` whose
  5962. # state_key is &quot;foo&quot;
  5963. - [&quot;org.example.custom.event.typeB&quot;, &quot;foo&quot;]
  5964. # Share only events of type `org.example.custom.event.typeC` whose
  5965. # state_key is &quot;bar&quot; or &quot;baz&quot;
  5966. - [&quot;org.example.custom.event.typeC&quot;, &quot;bar&quot;]
  5967. - [&quot;org.example.custom.event.typeC&quot;, &quot;baz&quot;]
  5968. </code></pre>
  5969. <p><em>Changed in Synapse 1.74:</em> admins can filter the events in prejoin state based
  5970. on their state key.</p>
  5971. <hr />
  5972. <h3 id="track_puppeted_user_ips"><a class="header" href="#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a></h3>
  5973. <p>We record the IP address of clients used to access the API for various
  5974. reasons, including displaying it to the user in the &quot;Where you're signed in&quot;
  5975. dialog.</p>
  5976. <p>By default, when puppeting another user via the admin API, the client IP
  5977. address is recorded against the user who created the access token (ie, the
  5978. admin user), and <em>not</em> the puppeted user.</p>
  5979. <p>Set this option to true to also record the IP address against the puppeted
  5980. user. (This also means that the puppeted user will count as an &quot;active&quot; user
  5981. for the purpose of monthly active user tracking - see <code>limit_usage_by_mau</code> etc
  5982. above.)</p>
  5983. <p>Example configuration:</p>
  5984. <pre><code class="language-yaml">track_puppeted_user_ips: true
  5985. </code></pre>
  5986. <hr />
  5987. <h3 id="app_service_config_files"><a class="header" href="#app_service_config_files"><code>app_service_config_files</code></a></h3>
  5988. <p>A list of application service config files to use.</p>
  5989. <p>Example configuration:</p>
  5990. <pre><code class="language-yaml">app_service_config_files:
  5991. - app_service_1.yaml
  5992. - app_service_2.yaml
  5993. </code></pre>
  5994. <hr />
  5995. <h3 id="track_appservice_user_ips"><a class="header" href="#track_appservice_user_ips"><code>track_appservice_user_ips</code></a></h3>
  5996. <p>Defaults to false. Set to true to enable tracking of application service IP addresses.
  5997. Implicitly enables MAU tracking for application service users.</p>
  5998. <p>Example configuration:</p>
  5999. <pre><code class="language-yaml">track_appservice_user_ips: true
  6000. </code></pre>
  6001. <hr />
  6002. <h3 id="use_appservice_legacy_authorization"><a class="header" href="#use_appservice_legacy_authorization"><code>use_appservice_legacy_authorization</code></a></h3>
  6003. <p>Whether to send the application service access tokens via the <code>access_token</code> query parameter
  6004. per older versions of the Matrix specification. Defaults to false. Set to true to enable sending
  6005. access tokens via a query parameter.</p>
  6006. <p>**Enabling this option is considered insecure and is not recommended. **</p>
  6007. <p>Example configuration:</p>
  6008. <pre><code class="language-yaml">use_appservice_legacy_authorization: true
  6009. </code></pre>
  6010. <hr />
  6011. <h3 id="macaroon_secret_key"><a class="header" href="#macaroon_secret_key"><code>macaroon_secret_key</code></a></h3>
  6012. <p>A secret which is used to sign</p>
  6013. <ul>
  6014. <li>access token for guest users,</li>
  6015. <li>short-term login token used during SSO logins (OIDC or SAML2) and</li>
  6016. <li>token used for unsubscribing from email notifications.</li>
  6017. </ul>
  6018. <p>If none is specified, the <code>registration_shared_secret</code> is used, if one is given;
  6019. otherwise, a secret key is derived from the signing key.</p>
  6020. <p>Example configuration:</p>
  6021. <pre><code class="language-yaml">macaroon_secret_key: &lt;PRIVATE STRING&gt;
  6022. </code></pre>
  6023. <hr />
  6024. <h3 id="form_secret"><a class="header" href="#form_secret"><code>form_secret</code></a></h3>
  6025. <p>A secret which is used to calculate HMACs for form values, to stop
  6026. falsification of values. Must be specified for the User Consent
  6027. forms to work.</p>
  6028. <p>Example configuration:</p>
  6029. <pre><code class="language-yaml">form_secret: &lt;PRIVATE STRING&gt;
  6030. </code></pre>
  6031. <hr />
  6032. <h2 id="signing-keys"><a class="header" href="#signing-keys">Signing Keys</a></h2>
  6033. <p>Config options relating to signing keys</p>
  6034. <hr />
  6035. <h3 id="signing_key_path"><a class="header" href="#signing_key_path"><code>signing_key_path</code></a></h3>
  6036. <p>Path to the signing key to sign events and federation requests with.</p>
  6037. <p><em>New in Synapse 1.67</em>: If this file does not exist, Synapse will create a new signing
  6038. key on startup and store it in this file.</p>
  6039. <p>Example configuration:</p>
  6040. <pre><code class="language-yaml">signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  6041. </code></pre>
  6042. <hr />
  6043. <h3 id="old_signing_keys"><a class="header" href="#old_signing_keys"><code>old_signing_keys</code></a></h3>
  6044. <p>The keys that the server used to sign messages with but won't use
  6045. to sign new messages. For each key, <code>key</code> should be the base64-encoded public key, and
  6046. <code>expired_ts</code>should be the time (in milliseconds since the unix epoch) that
  6047. it was last used.</p>
  6048. <p>It is possible to build an entry from an old <code>signing.key</code> file using the
  6049. <code>export_signing_key</code> script which is provided with synapse.</p>
  6050. <p>Example configuration:</p>
  6051. <pre><code class="language-yaml">old_signing_keys:
  6052. &quot;ed25519:id&quot;: { key: &quot;base64string&quot;, expired_ts: 123456789123 }
  6053. </code></pre>
  6054. <hr />
  6055. <h3 id="key_refresh_interval"><a class="header" href="#key_refresh_interval"><code>key_refresh_interval</code></a></h3>
  6056. <p>How long key response published by this server is valid for.
  6057. Used to set the <code>valid_until_ts</code> in <code>/key/v2</code> APIs.
  6058. Determines how quickly servers will query to check which keys
  6059. are still valid. Defaults to 1d.</p>
  6060. <p>Example configuration:</p>
  6061. <pre><code class="language-yaml">key_refresh_interval: 2d
  6062. </code></pre>
  6063. <hr />
  6064. <h3 id="trusted_key_servers"><a class="header" href="#trusted_key_servers"><code>trusted_key_servers</code></a></h3>
  6065. <p>The trusted servers to download signing keys from.</p>
  6066. <p>When we need to fetch a signing key, each server is tried in parallel.</p>
  6067. <p>Normally, the connection to the key server is validated via TLS certificates.
  6068. Additional security can be provided by configuring a <code>verify key</code>, which
  6069. will make synapse check that the response is signed by that key.</p>
  6070. <p>This setting supersedes an older setting named <code>perspectives</code>. The old format
  6071. is still supported for backwards-compatibility, but it is deprecated.</p>
  6072. <p><code>trusted_key_servers</code> defaults to matrix.org, but using it will generate a
  6073. warning on start-up. To suppress this warning, set
  6074. <code>suppress_key_server_warning</code> to true.</p>
  6075. <p>If the use of a trusted key server has to be deactivated, e.g. in a private
  6076. federation or for privacy reasons, this can be realised by setting
  6077. an empty array (<code>trusted_key_servers: []</code>). Then Synapse will request the keys
  6078. directly from the server that owns the keys. If Synapse does not get keys directly
  6079. from the server, the events of this server will be rejected.</p>
  6080. <p>Options for each entry in the list include:</p>
  6081. <ul>
  6082. <li><code>server_name</code>: the name of the server. Required.</li>
  6083. <li><code>verify_keys</code>: an optional map from key id to base64-encoded public key.
  6084. If specified, we will check that the response is signed by at least
  6085. one of the given keys.</li>
  6086. <li><code>accept_keys_insecurely</code>: a boolean. Normally, if <code>verify_keys</code> is unset,
  6087. and <code>federation_verify_certificates</code> is not <code>true</code>, synapse will refuse
  6088. to start, because this would allow anyone who can spoof DNS responses
  6089. to masquerade as the trusted key server. If you know what you are doing
  6090. and are sure that your network environment provides a secure connection
  6091. to the key server, you can set this to <code>true</code> to override this behaviour.</li>
  6092. </ul>
  6093. <p>Example configuration #1:</p>
  6094. <pre><code class="language-yaml">trusted_key_servers:
  6095. - server_name: &quot;my_trusted_server.example.com&quot;
  6096. verify_keys:
  6097. &quot;ed25519:auto&quot;: &quot;abcdefghijklmnopqrstuvwxyzabcdefghijklmopqr&quot;
  6098. - server_name: &quot;my_other_trusted_server.example.com&quot;
  6099. </code></pre>
  6100. <p>Example configuration #2:</p>
  6101. <pre><code class="language-yaml">trusted_key_servers:
  6102. - server_name: &quot;matrix.org&quot;
  6103. </code></pre>
  6104. <hr />
  6105. <h3 id="suppress_key_server_warning"><a class="header" href="#suppress_key_server_warning"><code>suppress_key_server_warning</code></a></h3>
  6106. <p>Set the following to true to disable the warning that is emitted when the
  6107. <code>trusted_key_servers</code> include 'matrix.org'. See above.</p>
  6108. <p>Example configuration:</p>
  6109. <pre><code class="language-yaml">suppress_key_server_warning: true
  6110. </code></pre>
  6111. <hr />
  6112. <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>
  6113. <p>The signing keys to use when acting as a trusted key server. If not specified
  6114. defaults to the server signing key.</p>
  6115. <p>Can contain multiple keys, one per line.</p>
  6116. <p>Example configuration:</p>
  6117. <pre><code class="language-yaml">key_server_signing_keys_path: &quot;key_server_signing_keys.key&quot;
  6118. </code></pre>
  6119. <hr />
  6120. <h2 id="single-sign-on-integration"><a class="header" href="#single-sign-on-integration">Single sign-on integration</a></h2>
  6121. <p>The following settings can be used to make Synapse use a single sign-on
  6122. provider for authentication, instead of its internal password database.</p>
  6123. <p>You will probably also want to set the following options to <code>false</code> to
  6124. disable the regular login/registration flows:</p>
  6125. <ul>
  6126. <li><a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a></li>
  6127. <li><a href="usage/configuration/config_documentation.html#password_config"><code>password_config.enabled</code></a></li>
  6128. </ul>
  6129. <hr />
  6130. <h3 id="saml2_config"><a class="header" href="#saml2_config"><code>saml2_config</code></a></h3>
  6131. <p>Enable SAML2 for registration and login. Uses pysaml2. To learn more about pysaml and
  6132. to find a full list options for configuring pysaml, read the docs <a href="https://pysaml2.readthedocs.io/en/latest/">here</a>.</p>
  6133. <p>At least one of <code>sp_config</code> or <code>config_path</code> must be set in this section to
  6134. enable SAML login. You can either put your entire pysaml config inline using the <code>sp_config</code>
  6135. option, or you can specify a path to a psyaml config file with the sub-option <code>config_path</code>.
  6136. This setting has the following sub-options:</p>
  6137. <ul>
  6138. <li><code>idp_name</code>: A user-facing name for this identity provider, which is used to
  6139. offer the user a choice of login mechanisms.</li>
  6140. <li><code>idp_icon</code>: An optional icon for this identity provider, which is presented
  6141. by clients and Synapse's own IdP picker page. If given, must be an
  6142. MXC URI of the format <code>mxc://&lt;server-name&gt;/&lt;media-id&gt;</code>. (An easy way to
  6143. obtain such an MXC URI is to upload an image to an (unencrypted) room
  6144. and then copy the &quot;url&quot; from the source of the event.)</li>
  6145. <li><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
  6146. to style the login flow according to the identity provider in question.
  6147. See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</li>
  6148. <li><code>sp_config</code>: the configuration for the pysaml2 Service Provider. See pysaml2 docs for format of config.
  6149. Default values will be used for the <code>entityid</code> and <code>service</code> settings,
  6150. so it is not normally necessary to specify them unless you need to
  6151. override them. Here are a few useful sub-options for configuring pysaml:
  6152. <ul>
  6153. <li><code>metadata</code>: Point this to the IdP's metadata. You must provide either a local
  6154. file via the <code>local</code> attribute or (preferably) a URL via the
  6155. <code>remote</code> attribute.</li>
  6156. <li><code>accepted_time_diff: 3</code>: Allowed clock difference in seconds between the homeserver and IdP.
  6157. Defaults to 0.</li>
  6158. <li><code>service</code>: By default, the user has to go to our login page first. If you'd like
  6159. to allow IdP-initiated login, set <code>allow_unsolicited</code> to true under <code>sp</code> in the <code>service</code>
  6160. section.</li>
  6161. </ul>
  6162. </li>
  6163. <li><code>config_path</code>: specify a separate pysaml2 configuration file thusly:
  6164. <code>config_path: &quot;CONFDIR/sp_conf.py&quot;</code></li>
  6165. <li><code>saml_session_lifetime</code>: The lifetime of a SAML session. This defines how long a user has to
  6166. complete the authentication process, if <code>allow_unsolicited</code> is unset. The default is 15 minutes.</li>
  6167. <li><code>user_mapping_provider</code>: Using this option, an external module can be provided as a
  6168. custom solution to mapping attributes returned from a saml provider onto a matrix user. The
  6169. <code>user_mapping_provider</code> has the following attributes:
  6170. <ul>
  6171. <li><code>module</code>: The custom module's class.</li>
  6172. <li><code>config</code>: Custom configuration values for the module. Use the values provided in the
  6173. example if you are using the built-in user_mapping_provider, or provide your own
  6174. config values for a custom class if you are using one. This section will be passed as a Python
  6175. dictionary to the module's <code>parse_config</code> method. The built-in provider takes the following two
  6176. options:
  6177. <ul>
  6178. <li><code>mxid_source_attribute</code>: The SAML attribute (after mapping via the attribute maps) to use
  6179. to derive the Matrix ID from. It is 'uid' by default. Note: This used to be configured by the
  6180. <code>saml2_config.mxid_source_attribute option</code>. If that is still defined, its value will be used instead.</li>
  6181. <li><code>mxid_mapping</code>: The mapping system to use for mapping the saml attribute onto a
  6182. matrix ID. Options include: <code>hexencode</code> (which maps unpermitted characters to '=xx')
  6183. and <code>dotreplace</code> (which replaces unpermitted characters with '.').
  6184. The default is <code>hexencode</code>. Note: This used to be configured by the
  6185. <code>saml2_config.mxid_mapping option</code>. If that is still defined, its value will be used instead.</li>
  6186. </ul>
  6187. </li>
  6188. </ul>
  6189. </li>
  6190. <li><code>grandfathered_mxid_source_attribute</code>: In previous versions of synapse, the mapping from SAML attribute to
  6191. MXID was always calculated dynamically rather than stored in a table. For backwards- compatibility, we will look for <code>user_ids</code>
  6192. matching such a pattern before creating a new account. This setting controls the SAML attribute which will be used for this
  6193. backwards-compatibility lookup. Typically it should be 'uid', but if the attribute maps are changed, it may be necessary to change it.
  6194. The default is 'uid'.</li>
  6195. <li><code>attribute_requirements</code>: It is possible to configure Synapse to only allow logins if SAML attributes
  6196. match particular values. The requirements can be listed under
  6197. <code>attribute_requirements</code> as shown in the example. All of the listed attributes must
  6198. match for the login to be permitted.</li>
  6199. <li><code>idp_entityid</code>: If the metadata XML contains multiple IdP entities then the <code>idp_entityid</code>
  6200. option must be set to the entity to redirect users to.
  6201. Most deployments only have a single IdP entity and so should omit this option.</li>
  6202. </ul>
  6203. <p>Once SAML support is enabled, a metadata file will be exposed at
  6204. <code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/metadata.xml</code>, which you may be able to
  6205. use to configure your SAML IdP with. Alternatively, you can manually configure
  6206. the IdP to use an ACS location of
  6207. <code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/authn_response</code>.</p>
  6208. <p>Example configuration:</p>
  6209. <pre><code class="language-yaml">saml2_config:
  6210. sp_config:
  6211. metadata:
  6212. local: [&quot;saml2/idp.xml&quot;]
  6213. remote:
  6214. - url: https://our_idp/metadata.xml
  6215. accepted_time_diff: 3
  6216. service:
  6217. sp:
  6218. allow_unsolicited: true
  6219. # The examples below are just used to generate our metadata xml, and you
  6220. # may well not need them, depending on your setup. Alternatively you
  6221. # may need a whole lot more detail - see the pysaml2 docs!
  6222. description: [&quot;My awesome SP&quot;, &quot;en&quot;]
  6223. name: [&quot;Test SP&quot;, &quot;en&quot;]
  6224. ui_info:
  6225. display_name:
  6226. - lang: en
  6227. text: &quot;Display Name is the descriptive name of your service.&quot;
  6228. description:
  6229. - lang: en
  6230. text: &quot;Description should be a short paragraph explaining the purpose of the service.&quot;
  6231. information_url:
  6232. - lang: en
  6233. text: &quot;https://example.com/terms-of-service&quot;
  6234. privacy_statement_url:
  6235. - lang: en
  6236. text: &quot;https://example.com/privacy-policy&quot;
  6237. keywords:
  6238. - lang: en
  6239. text: [&quot;Matrix&quot;, &quot;Element&quot;]
  6240. logo:
  6241. - lang: en
  6242. text: &quot;https://example.com/logo.svg&quot;
  6243. width: &quot;200&quot;
  6244. height: &quot;80&quot;
  6245. organization:
  6246. name: Example com
  6247. display_name:
  6248. - [&quot;Example co&quot;, &quot;en&quot;]
  6249. url: &quot;http://example.com&quot;
  6250. contact_person:
  6251. - given_name: Bob
  6252. sur_name: &quot;the Sysadmin&quot;
  6253. email_address&quot;: [&quot;admin@example.com&quot;]
  6254. contact_type&quot;: technical
  6255. saml_session_lifetime: 5m
  6256. user_mapping_provider:
  6257. # Below options are intended for the built-in provider, they should be
  6258. # changed if using a custom module.
  6259. config:
  6260. mxid_source_attribute: displayName
  6261. mxid_mapping: dotreplace
  6262. grandfathered_mxid_source_attribute: upn
  6263. attribute_requirements:
  6264. - attribute: userGroup
  6265. value: &quot;staff&quot;
  6266. - attribute: department
  6267. value: &quot;sales&quot;
  6268. idp_entityid: 'https://our_idp/entityid'
  6269. </code></pre>
  6270. <hr />
  6271. <h3 id="oidc_providers"><a class="header" href="#oidc_providers"><code>oidc_providers</code></a></h3>
  6272. <p>List of OpenID Connect (OIDC) / OAuth 2.0 identity providers, for registration
  6273. and login. See <a href="usage/configuration/../../openid.html">here</a>
  6274. for information on how to configure these options.</p>
  6275. <p>For backwards compatibility, it is also possible to configure a single OIDC
  6276. provider via an <code>oidc_config</code> setting. This is now deprecated and admins are
  6277. advised to migrate to the <code>oidc_providers</code> format. (When doing that migration,
  6278. use <code>oidc</code> for the <code>idp_id</code> to ensure that existing users continue to be
  6279. recognised.)</p>
  6280. <p>Options for each entry include:</p>
  6281. <ul>
  6282. <li>
  6283. <p><code>idp_id</code>: a unique identifier for this identity provider. Used internally
  6284. by Synapse; should be a single word such as 'github'.
  6285. Note that, if this is changed, users authenticating via that provider
  6286. will no longer be recognised as the same user!
  6287. (Use &quot;oidc&quot; here if you are migrating from an old <code>oidc_config</code> configuration.)</p>
  6288. </li>
  6289. <li>
  6290. <p><code>idp_name</code>: A user-facing name for this identity provider, which is used to
  6291. offer the user a choice of login mechanisms.</p>
  6292. </li>
  6293. <li>
  6294. <p><code>idp_icon</code>: An optional icon for this identity provider, which is presented
  6295. by clients and Synapse's own IdP picker page. If given, must be an
  6296. MXC URI of the format <code>mxc://&lt;server-name&gt;/&lt;media-id&gt;</code>. (An easy way to
  6297. obtain such an MXC URI is to upload an image to an (unencrypted) room
  6298. and then copy the &quot;url&quot; from the source of the event.)</p>
  6299. </li>
  6300. <li>
  6301. <p><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
  6302. to style the login flow according to the identity provider in question.
  6303. See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</p>
  6304. </li>
  6305. <li>
  6306. <p><code>discover</code>: set to false to disable the use of the OIDC discovery mechanism
  6307. to discover endpoints. Defaults to true.</p>
  6308. </li>
  6309. <li>
  6310. <p><code>issuer</code>: Required. The OIDC issuer. Used to validate tokens and (if discovery
  6311. is enabled) to discover the provider's endpoints.</p>
  6312. </li>
  6313. <li>
  6314. <p><code>client_id</code>: Required. oauth2 client id to use.</p>
  6315. </li>
  6316. <li>
  6317. <p><code>client_secret</code>: oauth2 client secret to use. May be omitted if
  6318. <code>client_secret_jwt_key</code> is given, or if <code>client_auth_method</code> is 'none'.
  6319. Must be omitted if <code>client_secret_path</code> is specified.</p>
  6320. </li>
  6321. <li>
  6322. <p><code>client_secret_path</code>: path to the oauth2 client secret to use. With that
  6323. it's not necessary to leak secrets into the config file itself.
  6324. Mutually exclusive with <code>client_secret</code>. Can be omitted if
  6325. <code>client_secret_jwt_key</code> is specified.</p>
  6326. <p><em>Added in Synapse 1.91.0.</em></p>
  6327. </li>
  6328. <li>
  6329. <p><code>client_secret_jwt_key</code>: Alternative to client_secret: details of a key used
  6330. to create a JSON Web Token to be used as an OAuth2 client secret. If
  6331. given, must be a dictionary with the following properties:</p>
  6332. <ul>
  6333. <li>
  6334. <p><code>key</code>: a pem-encoded signing key. Must be a suitable key for the
  6335. algorithm specified. Required unless <code>key_file</code> is given.</p>
  6336. </li>
  6337. <li>
  6338. <p><code>key_file</code>: the path to file containing a pem-encoded signing key file.
  6339. Required unless <code>key</code> is given.</p>
  6340. </li>
  6341. <li>
  6342. <p><code>jwt_header</code>: a dictionary giving properties to include in the JWT
  6343. header. Must include the key <code>alg</code>, giving the algorithm used to
  6344. sign the JWT, such as &quot;ES256&quot;, using the JWA identifiers in
  6345. RFC7518.</p>
  6346. </li>
  6347. <li>
  6348. <p><code>jwt_payload</code>: an optional dictionary giving properties to include in
  6349. the JWT payload. Normally this should include an <code>iss</code> key.</p>
  6350. </li>
  6351. </ul>
  6352. </li>
  6353. <li>
  6354. <p><code>client_auth_method</code>: auth method to use when exchanging the token. Valid
  6355. values are <code>client_secret_basic</code> (default), <code>client_secret_post</code> and
  6356. <code>none</code>.</p>
  6357. </li>
  6358. <li>
  6359. <p><code>pkce_method</code>: Whether to use proof key for code exchange when requesting
  6360. and exchanging the token. Valid values are: <code>auto</code>, <code>always</code>, or <code>never</code>. Defaults
  6361. to <code>auto</code>, which uses PKCE if supported during metadata discovery. Set to <code>always</code>
  6362. to force enable PKCE or <code>never</code> to force disable PKCE.</p>
  6363. </li>
  6364. <li>
  6365. <p><code>scopes</code>: list of scopes to request. This should normally include the &quot;openid&quot;
  6366. scope. Defaults to <code>[&quot;openid&quot;]</code>.</p>
  6367. </li>
  6368. <li>
  6369. <p><code>authorization_endpoint</code>: the oauth2 authorization endpoint. Required if
  6370. provider discovery is disabled.</p>
  6371. </li>
  6372. <li>
  6373. <p><code>token_endpoint</code>: the oauth2 token endpoint. Required if provider discovery is
  6374. disabled.</p>
  6375. </li>
  6376. <li>
  6377. <p><code>userinfo_endpoint</code>: the OIDC userinfo endpoint. Required if discovery is
  6378. disabled and the 'openid' scope is not requested.</p>
  6379. </li>
  6380. <li>
  6381. <p><code>jwks_uri</code>: URI where to fetch the JWKS. Required if discovery is disabled and
  6382. the 'openid' scope is used.</p>
  6383. </li>
  6384. <li>
  6385. <p><code>skip_verification</code>: set to 'true' to skip metadata verification. Use this if
  6386. you are connecting to a provider that is not OpenID Connect compliant.
  6387. Defaults to false. Avoid this in production.</p>
  6388. </li>
  6389. <li>
  6390. <p><code>user_profile_method</code>: Whether to fetch the user profile from the userinfo
  6391. endpoint, or to rely on the data returned in the id_token from the <code>token_endpoint</code>.
  6392. Valid values are: <code>auto</code> or <code>userinfo_endpoint</code>.
  6393. Defaults to <code>auto</code>, which uses the userinfo endpoint if <code>openid</code> is
  6394. not included in <code>scopes</code>. Set to <code>userinfo_endpoint</code> to always use the
  6395. userinfo endpoint.</p>
  6396. </li>
  6397. <li>
  6398. <p><code>allow_existing_users</code>: set to true to allow a user logging in via OIDC to
  6399. match a pre-existing account instead of failing. This could be used if
  6400. switching from password logins to OIDC. Defaults to false.</p>
  6401. </li>
  6402. <li>
  6403. <p><code>enable_registration</code>: set to 'false' to disable automatic registration of new
  6404. users. This allows the OIDC SSO flow to be limited to sign in only, rather than
  6405. automatically registering users that have a valid SSO login but do not have
  6406. a pre-registered account. Defaults to true.</p>
  6407. </li>
  6408. <li>
  6409. <p><code>user_mapping_provider</code>: Configuration for how attributes returned from a OIDC
  6410. provider are mapped onto a matrix user. This setting has the following
  6411. sub-properties:</p>
  6412. <ul>
  6413. <li>
  6414. <p><code>module</code>: The class name of a custom mapping module. Default is
  6415. <code>synapse.handlers.oidc.JinjaOidcMappingProvider</code>.
  6416. See <a href="usage/configuration/../../sso_mapping_providers.html#openid-mapping-providers">OpenID Mapping Providers</a>
  6417. for information on implementing a custom mapping provider.</p>
  6418. </li>
  6419. <li>
  6420. <p><code>config</code>: Configuration for the mapping provider module. This section will
  6421. be passed as a Python dictionary to the user mapping provider
  6422. module's <code>parse_config</code> method.</p>
  6423. <p>For the default provider, the following settings are available:</p>
  6424. <ul>
  6425. <li>
  6426. <p><code>subject_template</code>: Jinja2 template for a unique identifier for the user.
  6427. Defaults to <code>{{ user.sub }}</code>, which OpenID Connect compliant providers should provide.</p>
  6428. <p>This replaces and overrides <code>subject_claim</code>.</p>
  6429. </li>
  6430. <li>
  6431. <p><code>subject_claim</code>: name of the claim containing a unique identifier
  6432. for the user. Defaults to 'sub', which OpenID Connect
  6433. compliant providers should provide.</p>
  6434. <p><em>Deprecated in Synapse v1.75.0.</em></p>
  6435. </li>
  6436. <li>
  6437. <p><code>picture_template</code>: Jinja2 template for an url for the user's profile picture.
  6438. Defaults to <code>{{ user.picture }}</code>, which OpenID Connect compliant providers should
  6439. provide and has to refer to a direct image file such as PNG, JPEG, or GIF image file.</p>
  6440. <p>This replaces and overrides <code>picture_claim</code>.</p>
  6441. <p>Currently only supported in monolithic (single-process) server configurations
  6442. where the media repository runs within the Synapse process.</p>
  6443. </li>
  6444. <li>
  6445. <p><code>picture_claim</code>: name of the claim containing an url for the user's profile picture.
  6446. Defaults to 'picture', which OpenID Connect compliant providers should provide
  6447. and has to refer to a direct image file such as PNG, JPEG, or GIF image file.</p>
  6448. <p>Currently only supported in monolithic (single-process) server configurations
  6449. where the media repository runs within the Synapse process.</p>
  6450. <p><em>Deprecated in Synapse v1.75.0.</em></p>
  6451. </li>
  6452. <li>
  6453. <p><code>localpart_template</code>: Jinja2 template for the localpart of the MXID.
  6454. If this is not set, the user will be prompted to choose their
  6455. own username (see the documentation for the <code>sso_auth_account_details.html</code>
  6456. template). This template can use the <code>localpart_from_email</code> filter.</p>
  6457. </li>
  6458. <li>
  6459. <p><code>confirm_localpart</code>: Whether to prompt the user to validate (or
  6460. change) the generated localpart (see the documentation for the
  6461. 'sso_auth_account_details.html' template), instead of
  6462. registering the account right away.</p>
  6463. </li>
  6464. <li>
  6465. <p><code>display_name_template</code>: Jinja2 template for the display name to set
  6466. on first login. If unset, no displayname will be set.</p>
  6467. </li>
  6468. <li>
  6469. <p><code>email_template</code>: Jinja2 template for the email address of the user.
  6470. If unset, no email address will be added to the account.</p>
  6471. </li>
  6472. <li>
  6473. <p><code>extra_attributes</code>: a map of Jinja2 templates for extra attributes
  6474. to send back to the client during login. Note that these are non-standard and clients will ignore them
  6475. without modifications.</p>
  6476. </li>
  6477. </ul>
  6478. </li>
  6479. </ul>
  6480. <p>When rendering, the Jinja2 templates are given a 'user' variable,
  6481. which is set to the claims returned by the UserInfo Endpoint and/or
  6482. in the ID Token.</p>
  6483. </li>
  6484. <li>
  6485. <p><code>backchannel_logout_enabled</code>: set to <code>true</code> to process OIDC Back-Channel Logout notifications.
  6486. Those notifications are expected to be received on <code>/_synapse/client/oidc/backchannel_logout</code>.
  6487. Defaults to <code>false</code>.</p>
  6488. </li>
  6489. <li>
  6490. <p><code>backchannel_logout_ignore_sub</code>: by default, the OIDC Back-Channel Logout feature checks that the
  6491. <code>sub</code> claim matches the subject claim received during login. This check can be disabled by setting
  6492. this to <code>true</code>. Defaults to <code>false</code>.</p>
  6493. <p>You might want to disable this if the <code>subject_claim</code> returned by the mapping provider is not <code>sub</code>.</p>
  6494. </li>
  6495. </ul>
  6496. <p>It is possible to configure Synapse to only allow logins if certain attributes
  6497. match particular values in the OIDC userinfo. The requirements can be listed under
  6498. <code>attribute_requirements</code> as shown here:</p>
  6499. <pre><code class="language-yaml">attribute_requirements:
  6500. - attribute: family_name
  6501. value: &quot;Stephensson&quot;
  6502. - attribute: groups
  6503. value: &quot;admin&quot;
  6504. </code></pre>
  6505. <p>All of the listed attributes must match for the login to be permitted. Additional attributes can be added to
  6506. userinfo by expanding the <code>scopes</code> section of the OIDC config to retrieve
  6507. additional information from the OIDC provider.</p>
  6508. <p>If the OIDC claim is a list, then the attribute must match any value in the list.
  6509. Otherwise, it must exactly match the value of the claim. Using the example
  6510. above, the <code>family_name</code> claim MUST be &quot;Stephensson&quot;, but the <code>groups</code>
  6511. claim MUST contain &quot;admin&quot;.</p>
  6512. <p>Example configuration:</p>
  6513. <pre><code class="language-yaml">oidc_providers:
  6514. # Generic example
  6515. #
  6516. - idp_id: my_idp
  6517. idp_name: &quot;My OpenID provider&quot;
  6518. idp_icon: &quot;mxc://example.com/mediaid&quot;
  6519. discover: false
  6520. issuer: &quot;https://accounts.example.com/&quot;
  6521. client_id: &quot;provided-by-your-issuer&quot;
  6522. client_secret: &quot;provided-by-your-issuer&quot;
  6523. client_auth_method: client_secret_post
  6524. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6525. authorization_endpoint: &quot;https://accounts.example.com/oauth2/auth&quot;
  6526. token_endpoint: &quot;https://accounts.example.com/oauth2/token&quot;
  6527. userinfo_endpoint: &quot;https://accounts.example.com/userinfo&quot;
  6528. jwks_uri: &quot;https://accounts.example.com/.well-known/jwks.json&quot;
  6529. skip_verification: true
  6530. enable_registration: true
  6531. user_mapping_provider:
  6532. config:
  6533. subject_claim: &quot;id&quot;
  6534. localpart_template: &quot;{{ user.login }}&quot;
  6535. display_name_template: &quot;{{ user.name }}&quot;
  6536. email_template: &quot;{{ user.email }}&quot;
  6537. attribute_requirements:
  6538. - attribute: userGroup
  6539. value: &quot;synapseUsers&quot;
  6540. </code></pre>
  6541. <hr />
  6542. <h3 id="cas_config"><a class="header" href="#cas_config"><code>cas_config</code></a></h3>
  6543. <p>Enable Central Authentication Service (CAS) for registration and login.
  6544. Has the following sub-options:</p>
  6545. <ul>
  6546. <li>
  6547. <p><code>enabled</code>: Set this to true to enable authorization against a CAS server.
  6548. Defaults to false.</p>
  6549. </li>
  6550. <li>
  6551. <p><code>idp_name</code>: A user-facing name for this identity provider, which is used to
  6552. offer the user a choice of login mechanisms.</p>
  6553. </li>
  6554. <li>
  6555. <p><code>idp_icon</code>: An optional icon for this identity provider, which is presented
  6556. by clients and Synapse's own IdP picker page. If given, must be an
  6557. MXC URI of the format <code>mxc://&lt;server-name&gt;/&lt;media-id&gt;</code>. (An easy way to
  6558. obtain such an MXC URI is to upload an image to an (unencrypted) room
  6559. and then copy the &quot;url&quot; from the source of the event.)</p>
  6560. </li>
  6561. <li>
  6562. <p><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
  6563. to style the login flow according to the identity provider in question.
  6564. See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</p>
  6565. </li>
  6566. <li>
  6567. <p><code>server_url</code>: The URL of the CAS authorization endpoint.</p>
  6568. </li>
  6569. <li>
  6570. <p><code>protocol_version</code>: The CAS protocol version, defaults to none (version 3 is required if you want to use &quot;required_attributes&quot;).</p>
  6571. </li>
  6572. <li>
  6573. <p><code>displayname_attribute</code>: The attribute of the CAS response to use as the display name.
  6574. If no name is given here, no displayname will be set.</p>
  6575. </li>
  6576. <li>
  6577. <p><code>required_attributes</code>: It is possible to configure Synapse to only allow logins if CAS attributes
  6578. match particular values. All of the keys given below must exist
  6579. and the values must match the given value. Alternately if the given value
  6580. is <code>None</code> then any value is allowed (the attribute just must exist).
  6581. All of the listed attributes must match for the login to be permitted.</p>
  6582. </li>
  6583. <li>
  6584. <p><code>enable_registration</code>: set to 'false' to disable automatic registration of new
  6585. users. This allows the CAS SSO flow to be limited to sign in only, rather than
  6586. automatically registering users that have a valid SSO login but do not have
  6587. a pre-registered account. Defaults to true.</p>
  6588. <p><em>Added in Synapse 1.93.0.</em></p>
  6589. </li>
  6590. </ul>
  6591. <p>Example configuration:</p>
  6592. <pre><code class="language-yaml">cas_config:
  6593. enabled: true
  6594. server_url: &quot;https://cas-server.com&quot;
  6595. protocol_version: 3
  6596. displayname_attribute: name
  6597. required_attributes:
  6598. userGroup: &quot;staff&quot;
  6599. department: None
  6600. enable_registration: true
  6601. </code></pre>
  6602. <hr />
  6603. <h3 id="sso"><a class="header" href="#sso"><code>sso</code></a></h3>
  6604. <p>Additional settings to use with single-sign on systems such as OpenID Connect,
  6605. SAML2 and CAS.</p>
  6606. <p>Server admins can configure custom templates for pages related to SSO. See
  6607. <a href="usage/configuration/../../templates.html">here</a> for more information.</p>
  6608. <p>Options include:</p>
  6609. <ul>
  6610. <li><code>client_whitelist</code>: A list of client URLs which are whitelisted so that the user does not
  6611. have to confirm giving access to their account to the URL. Any client
  6612. whose URL starts with an entry in the following list will not be subject
  6613. to an additional confirmation step after the SSO login is completed.
  6614. WARNING: An entry such as &quot;https://my.client&quot; is insecure, because it
  6615. will also match &quot;https://my.client.evil.site&quot;, exposing your users to
  6616. phishing attacks from evil.site. To avoid this, include a slash after the
  6617. hostname: &quot;https://my.client/&quot;.
  6618. The login fallback page (used by clients that don't natively support the
  6619. required login flows) is whitelisted in addition to any URLs in this list.
  6620. By default, this list contains only the login fallback page.</li>
  6621. <li><code>update_profile_information</code>: Use this setting to keep a user's profile fields in sync with information from
  6622. the identity provider. Currently only syncing the displayname is supported. Fields
  6623. are checked on every SSO login, and are updated if necessary.
  6624. Note that enabling this option will override user profile information,
  6625. regardless of whether users have opted-out of syncing that
  6626. information when first signing in. Defaults to false.</li>
  6627. </ul>
  6628. <p>Example configuration:</p>
  6629. <pre><code class="language-yaml">sso:
  6630. client_whitelist:
  6631. - https://riot.im/develop
  6632. - https://my.custom.client/
  6633. update_profile_information: true
  6634. </code></pre>
  6635. <hr />
  6636. <h3 id="jwt_config"><a class="header" href="#jwt_config"><code>jwt_config</code></a></h3>
  6637. <p>JSON web token integration. The following settings can be used to make
  6638. Synapse JSON web tokens for authentication, instead of its internal
  6639. password database.</p>
  6640. <p>Each JSON Web Token needs to contain a &quot;sub&quot; (subject) claim, which is
  6641. used as the localpart of the mxid.</p>
  6642. <p>Additionally, the expiration time (&quot;exp&quot;), not before time (&quot;nbf&quot;),
  6643. and issued at (&quot;iat&quot;) claims are validated if present.</p>
  6644. <p>Note that this is a non-standard login type and client support is
  6645. expected to be non-existent.</p>
  6646. <p>See <a href="usage/configuration/../../jwt.html">here</a> for more.</p>
  6647. <p>Additional sub-options for this setting include:</p>
  6648. <ul>
  6649. <li><code>enabled</code>: Set to true to enable authorization using JSON web
  6650. tokens. Defaults to false.</li>
  6651. <li><code>secret</code>: This is either the private shared secret or the public key used to
  6652. decode the contents of the JSON web token. Required if <code>enabled</code> is set to true.</li>
  6653. <li><code>algorithm</code>: The algorithm used to sign (or HMAC) the JSON web token.
  6654. Supported algorithms are listed
  6655. <a href="https://docs.authlib.org/en/latest/specs/rfc7518.html">here (section JWS)</a>.
  6656. Required if <code>enabled</code> is set to true.</li>
  6657. <li><code>subject_claim</code>: Name of the claim containing a unique identifier for the user.
  6658. Optional, defaults to <code>sub</code>.</li>
  6659. <li><code>issuer</code>: The issuer to validate the &quot;iss&quot; claim against. Optional. If provided the
  6660. &quot;iss&quot; claim will be required and validated for all JSON web tokens.</li>
  6661. <li><code>audiences</code>: A list of audiences to validate the &quot;aud&quot; claim against. Optional.
  6662. If provided the &quot;aud&quot; claim will be required and validated for all JSON web tokens.
  6663. Note that if the &quot;aud&quot; claim is included in a JSON web token then
  6664. validation will fail without configuring audiences.</li>
  6665. </ul>
  6666. <p>Example configuration:</p>
  6667. <pre><code class="language-yaml">jwt_config:
  6668. enabled: true
  6669. secret: &quot;provided-by-your-issuer&quot;
  6670. algorithm: &quot;provided-by-your-issuer&quot;
  6671. subject_claim: &quot;name_of_claim&quot;
  6672. issuer: &quot;provided-by-your-issuer&quot;
  6673. audiences:
  6674. - &quot;provided-by-your-issuer&quot;
  6675. </code></pre>
  6676. <hr />
  6677. <h3 id="password_config"><a class="header" href="#password_config"><code>password_config</code></a></h3>
  6678. <p>Use this setting to enable password-based logins.</p>
  6679. <p>This setting has the following sub-options:</p>
  6680. <ul>
  6681. <li><code>enabled</code>: Defaults to true.
  6682. Set to false to disable password authentication.
  6683. Set to <code>only_for_reauth</code> to allow users with existing passwords to use them
  6684. to log in and reauthenticate, whilst preventing new users from setting passwords.</li>
  6685. <li><code>localdb_enabled</code>: Set to false to disable authentication against the local password
  6686. database. This is ignored if <code>enabled</code> is false, and is only useful
  6687. if you have other <code>password_providers</code>. Defaults to true.</li>
  6688. <li><code>pepper</code>: Set the value here to a secret random string for extra security.
  6689. DO NOT CHANGE THIS AFTER INITIAL SETUP!</li>
  6690. <li><code>policy</code>: Define and enforce a password policy, such as minimum lengths for passwords, etc.
  6691. Each parameter is optional. This is an implementation of MSC2000. Parameters are as follows:
  6692. <ul>
  6693. <li><code>enabled</code>: Defaults to false. Set to true to enable.</li>
  6694. <li><code>minimum_length</code>: Minimum accepted length for a password. Defaults to 0.</li>
  6695. <li><code>require_digit</code>: Whether a password must contain at least one digit.
  6696. Defaults to false.</li>
  6697. <li><code>require_symbol</code>: Whether a password must contain at least one symbol.
  6698. A symbol is any character that's not a number or a letter. Defaults to false.</li>
  6699. <li><code>require_lowercase</code>: Whether a password must contain at least one lowercase letter.
  6700. Defaults to false.</li>
  6701. <li><code>require_uppercase</code>: Whether a password must contain at least one uppercase letter.
  6702. Defaults to false.</li>
  6703. </ul>
  6704. </li>
  6705. </ul>
  6706. <p>Example configuration:</p>
  6707. <pre><code class="language-yaml">password_config:
  6708. enabled: false
  6709. localdb_enabled: false
  6710. pepper: &quot;EVEN_MORE_SECRET&quot;
  6711. policy:
  6712. enabled: true
  6713. minimum_length: 15
  6714. require_digit: true
  6715. require_symbol: true
  6716. require_lowercase: true
  6717. require_uppercase: true
  6718. </code></pre>
  6719. <hr />
  6720. <h2 id="push"><a class="header" href="#push">Push</a></h2>
  6721. <p>Configuration settings related to push notifications</p>
  6722. <hr />
  6723. <h3 id="push-1"><a class="header" href="#push-1"><code>push</code></a></h3>
  6724. <p>This setting defines options for push notifications.</p>
  6725. <p>This option has a number of sub-options. They are as follows:</p>
  6726. <ul>
  6727. <li><code>enabled</code>: Enables or disables push notification calculation. Note, disabling this will also
  6728. stop unread counts being calculated for rooms. This mode of operation is intended
  6729. for homeservers which may only have bots or appservice users connected, or are otherwise
  6730. not interested in push/unread counters. This is enabled by default.</li>
  6731. <li><code>include_content</code>: Clients requesting push notifications can either have the body of
  6732. the message sent in the notification poke along with other details
  6733. like the sender, or just the event ID and room ID (<code>event_id_only</code>).
  6734. If clients choose the to have the body sent, this option controls whether the
  6735. notification request includes the content of the event (other details
  6736. like the sender are still included). If <code>event_id_only</code> is enabled, it
  6737. has no effect.
  6738. For modern android devices the notification content will still appear
  6739. because it is loaded by the app. iPhone, however will send a
  6740. notification saying only that a message arrived and who it came from.
  6741. Defaults to true. Set to false to only include the event ID and room ID in push notification payloads.</li>
  6742. <li><code>group_unread_count_by_room: false</code>: When a push notification is received, an unread count is also sent.
  6743. This number can either be calculated as the number of unread messages for the user, or the number of <em>rooms</em> the
  6744. user has unread messages in. Defaults to true, meaning push clients will see the number of
  6745. rooms with unread messages in them. Set to false to instead send the number
  6746. of unread messages.</li>
  6747. <li><code>jitter_delay</code>: Delays push notifications by a random amount up to the given
  6748. duration. Useful for mitigating timing attacks. Optional, defaults to no
  6749. delay. <em>Added in Synapse 1.84.0.</em></li>
  6750. </ul>
  6751. <p>Example configuration:</p>
  6752. <pre><code class="language-yaml">push:
  6753. enabled: true
  6754. include_content: false
  6755. group_unread_count_by_room: false
  6756. jitter_delay: &quot;10s&quot;
  6757. </code></pre>
  6758. <hr />
  6759. <h2 id="rooms"><a class="header" href="#rooms">Rooms</a></h2>
  6760. <p>Config options relating to rooms.</p>
  6761. <hr />
  6762. <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>
  6763. <p>Controls whether locally-created rooms should be end-to-end encrypted by
  6764. default.</p>
  6765. <p>Possible options are &quot;all&quot;, &quot;invite&quot;, and &quot;off&quot;. They are defined as:</p>
  6766. <ul>
  6767. <li>&quot;all&quot;: any locally-created room</li>
  6768. <li>&quot;invite&quot;: any room created with the <code>private_chat</code> or <code>trusted_private_chat</code>
  6769. room creation presets</li>
  6770. <li>&quot;off&quot;: this option will take no effect</li>
  6771. </ul>
  6772. <p>The default value is &quot;off&quot;.</p>
  6773. <p>Note that this option will only affect rooms created after it is set. It
  6774. will also not affect rooms created by other servers.</p>
  6775. <p>Example configuration:</p>
  6776. <pre><code class="language-yaml">encryption_enabled_by_default_for_room_type: invite
  6777. </code></pre>
  6778. <hr />
  6779. <h3 id="user_directory"><a class="header" href="#user_directory"><code>user_directory</code></a></h3>
  6780. <p>This setting defines options related to the user directory.</p>
  6781. <p>This option has the following sub-options:</p>
  6782. <ul>
  6783. <li>
  6784. <p><code>enabled</code>: Defines whether users can search the user directory. If false then
  6785. empty responses are returned to all queries. Defaults to true.</p>
  6786. </li>
  6787. <li>
  6788. <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.
  6789. If false, search results will only contain users
  6790. visible in public rooms and users sharing a room with the requester.
  6791. Defaults to false.</p>
  6792. <p>NB. If you set this to true, and the last time the user_directory search
  6793. indexes were (re)built was before Synapse 1.44, you'll have to
  6794. rebuild the indexes in order to search through all known users.</p>
  6795. <p>These indexes are built the first time Synapse starts; admins can
  6796. manually trigger a rebuild via the API following the instructions
  6797. <a href="usage/configuration/../administration/admin_api/background_updates.html#run">for running background updates</a>,
  6798. set to true to return search results containing all known users, even if that
  6799. user does not share a room with the requester.</p>
  6800. </li>
  6801. <li>
  6802. <p><code>prefer_local_users</code>: Defines whether to prefer local users in search query results.
  6803. If set to true, local users are more likely to appear above remote users when searching the
  6804. user directory. Defaults to false.</p>
  6805. </li>
  6806. <li>
  6807. <p><code>show_locked_users</code>: Defines whether to show locked users in search query results. Defaults to false.</p>
  6808. </li>
  6809. </ul>
  6810. <p>Example configuration:</p>
  6811. <pre><code class="language-yaml">user_directory:
  6812. enabled: false
  6813. search_all_users: true
  6814. prefer_local_users: true
  6815. show_locked_users: true
  6816. </code></pre>
  6817. <hr />
  6818. <h3 id="user_consent"><a class="header" href="#user_consent"><code>user_consent</code></a></h3>
  6819. <p>For detailed instructions on user consent configuration, see <a href="usage/configuration/../../consent_tracking.html">here</a>.</p>
  6820. <p>Parts of this section are required if enabling the <code>consent</code> resource under
  6821. <a href="usage/configuration/config_documentation.html#listeners"><code>listeners</code></a>, in particular <code>template_dir</code> and <code>version</code>.</p>
  6822. <ul>
  6823. <li>
  6824. <p><code>template_dir</code>: gives the location of the templates for the HTML forms.
  6825. This directory should contain one subdirectory per language (eg, <code>en</code>, <code>fr</code>),
  6826. and each language directory should contain the policy document (named as
  6827. <version>.html) and a success page (success.html).</p>
  6828. </li>
  6829. <li>
  6830. <p><code>version</code>: specifies the 'current' version of the policy document. It defines
  6831. the version to be served by the consent resource if there is no 'v'
  6832. parameter.</p>
  6833. </li>
  6834. <li>
  6835. <p><code>server_notice_content</code>: if enabled, will send a user a &quot;Server Notice&quot;
  6836. asking them to consent to the privacy policy. The <a href="usage/configuration/config_documentation.html#server_notices"><code>server_notices</code> section</a>
  6837. must also be configured for this to work. Notices will <em>not</em> be sent to
  6838. guest users unless <code>send_server_notice_to_guests</code> is set to true.</p>
  6839. </li>
  6840. <li>
  6841. <p><code>block_events_error</code>, if set, will block any attempts to send events
  6842. until the user consents to the privacy policy. The value of the setting is
  6843. used as the text of the error.</p>
  6844. </li>
  6845. <li>
  6846. <p><code>require_at_registration</code>, if enabled, will add a step to the registration
  6847. process, similar to how captcha works. Users will be required to accept the
  6848. policy before their account is created.</p>
  6849. </li>
  6850. <li>
  6851. <p><code>policy_name</code> is the display name of the policy users will see when registering
  6852. for an account. Has no effect unless <code>require_at_registration</code> is enabled.
  6853. Defaults to &quot;Privacy Policy&quot;.</p>
  6854. </li>
  6855. </ul>
  6856. <p>Example configuration:</p>
  6857. <pre><code class="language-yaml">user_consent:
  6858. template_dir: res/templates/privacy
  6859. version: 1.0
  6860. server_notice_content:
  6861. msgtype: m.text
  6862. body: &gt;-
  6863. To continue using this homeserver you must review and agree to the
  6864. terms and conditions at %(consent_uri)s
  6865. send_server_notice_to_guests: true
  6866. block_events_error: &gt;-
  6867. To continue using this homeserver you must review and agree to the
  6868. terms and conditions at %(consent_uri)s
  6869. require_at_registration: false
  6870. policy_name: Privacy Policy
  6871. </code></pre>
  6872. <hr />
  6873. <h3 id="stats"><a class="header" href="#stats"><code>stats</code></a></h3>
  6874. <p>Settings for local room and user statistics collection. See <a href="usage/configuration/../../room_and_user_statistics.html">here</a>
  6875. for more.</p>
  6876. <ul>
  6877. <li><code>enabled</code>: Set to false to disable room and user statistics. Note that doing
  6878. so may cause certain features (such as the room directory) not to work
  6879. correctly. Defaults to true.</li>
  6880. </ul>
  6881. <p>Example configuration:</p>
  6882. <pre><code class="language-yaml">stats:
  6883. enabled: false
  6884. </code></pre>
  6885. <hr />
  6886. <h3 id="server_notices"><a class="header" href="#server_notices"><code>server_notices</code></a></h3>
  6887. <p>Use this setting to enable a room which can be used to send notices
  6888. from the server to users. It is a special room which users cannot leave; notices
  6889. in the room come from a special &quot;notices&quot; user id.</p>
  6890. <p>If you use this setting, you <em>must</em> define the <code>system_mxid_localpart</code>
  6891. sub-setting, which defines the id of the user which will be used to send the
  6892. notices.</p>
  6893. <p>Sub-options for this setting include:</p>
  6894. <ul>
  6895. <li><code>system_mxid_display_name</code>: set the display name of the &quot;notices&quot; user</li>
  6896. <li><code>system_mxid_avatar_url</code>: set the avatar for the &quot;notices&quot; user</li>
  6897. <li><code>room_name</code>: set the room name of the server notices room</li>
  6898. </ul>
  6899. <p>Example configuration:</p>
  6900. <pre><code class="language-yaml">server_notices:
  6901. system_mxid_localpart: notices
  6902. system_mxid_display_name: &quot;Server Notices&quot;
  6903. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  6904. room_name: &quot;Server Notices&quot;
  6905. </code></pre>
  6906. <hr />
  6907. <h3 id="enable_room_list_search"><a class="header" href="#enable_room_list_search"><code>enable_room_list_search</code></a></h3>
  6908. <p>Set to false to disable searching the public room list. When disabled
  6909. blocks searching local and remote room lists for local and remote
  6910. users by always returning an empty list for all queries. Defaults to true.</p>
  6911. <p>Example configuration:</p>
  6912. <pre><code class="language-yaml">enable_room_list_search: false
  6913. </code></pre>
  6914. <hr />
  6915. <h3 id="alias_creation_rules"><a class="header" href="#alias_creation_rules"><code>alias_creation_rules</code></a></h3>
  6916. <p>The <code>alias_creation_rules</code> option controls who is allowed to create aliases
  6917. on this server.</p>
  6918. <p>The format of this option is a list of rules that contain globs that
  6919. match against user_id, room_id and the new alias (fully qualified with
  6920. server name). The action in the first rule that matches is taken,
  6921. which can currently either be &quot;allow&quot; or &quot;deny&quot;.</p>
  6922. <p>Missing user_id/room_id/alias fields default to &quot;*&quot;.</p>
  6923. <p>If no rules match the request is denied. An empty list means no one
  6924. can create aliases.</p>
  6925. <p>Options for the rules include:</p>
  6926. <ul>
  6927. <li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
  6928. <li><code>alias</code>: Matches against the alias being created. Defaults to &quot;*&quot;.</li>
  6929. <li><code>room_id</code>: Matches against the room ID the alias is being pointed at. Defaults to &quot;*&quot;</li>
  6930. <li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow.</li>
  6931. </ul>
  6932. <p>Example configuration:</p>
  6933. <pre><code class="language-yaml">alias_creation_rules:
  6934. - user_id: &quot;bad_user&quot;
  6935. alias: &quot;spammy_alias&quot;
  6936. room_id: &quot;*&quot;
  6937. action: deny
  6938. </code></pre>
  6939. <hr />
  6940. <h3 id="room_list_publication_rules"><a class="header" href="#room_list_publication_rules"><code>room_list_publication_rules</code></a></h3>
  6941. <p>The <code>room_list_publication_rules</code> option controls who can publish and
  6942. which rooms can be published in the public room list.</p>
  6943. <p>The format of this option is the same as that for
  6944. <code>alias_creation_rules</code>.</p>
  6945. <p>If the room has one or more aliases associated with it, only one of
  6946. the aliases needs to match the alias rule. If there are no aliases
  6947. then only rules with <code>alias: *</code> match.</p>
  6948. <p>If no rules match the request is denied. An empty list means no one
  6949. can publish rooms.</p>
  6950. <p>Options for the rules include:</p>
  6951. <ul>
  6952. <li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
  6953. <li><code>alias</code>: Matches against any current local or canonical aliases associated with the room. Defaults to &quot;*&quot;.</li>
  6954. <li><code>room_id</code>: Matches against the room ID being published. Defaults to &quot;*&quot;.</li>
  6955. <li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow.</li>
  6956. </ul>
  6957. <p>Example configuration:</p>
  6958. <pre><code class="language-yaml">room_list_publication_rules:
  6959. - user_id: &quot;*&quot;
  6960. alias: &quot;*&quot;
  6961. room_id: &quot;*&quot;
  6962. action: allow
  6963. </code></pre>
  6964. <hr />
  6965. <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>
  6966. <p>The <code>default_power_level_content_override</code> option controls the default power
  6967. levels for rooms.</p>
  6968. <p>Useful if you know that your users need special permissions in rooms
  6969. that they create (e.g. to send particular types of state events without
  6970. needing an elevated power level). This takes the same shape as the
  6971. <code>power_level_content_override</code> parameter in the /createRoom API, but
  6972. is applied before that parameter.</p>
  6973. <p>Note that each key provided inside a preset (for example <code>events</code> in the example
  6974. below) will overwrite all existing defaults inside that key. So in the example
  6975. below, newly-created private_chat rooms will have no rules for any event types
  6976. except <code>com.example.foo</code>.</p>
  6977. <p>Example configuration:</p>
  6978. <pre><code class="language-yaml">default_power_level_content_override:
  6979. private_chat: { &quot;events&quot;: { &quot;com.example.foo&quot; : 0 } }
  6980. trusted_private_chat: null
  6981. public_chat: null
  6982. </code></pre>
  6983. <hr />
  6984. <h3 id="forget_rooms_on_leave"><a class="header" href="#forget_rooms_on_leave"><code>forget_rooms_on_leave</code></a></h3>
  6985. <p>Set to true to automatically forget rooms for users when they leave them, either
  6986. normally or via a kick or ban. Defaults to false.</p>
  6987. <p>Example configuration:</p>
  6988. <pre><code class="language-yaml">forget_rooms_on_leave: false
  6989. </code></pre>
  6990. <hr />
  6991. <h3 id="exclude_rooms_from_sync"><a class="header" href="#exclude_rooms_from_sync"><code>exclude_rooms_from_sync</code></a></h3>
  6992. <p>A list of rooms to exclude from sync responses. This is useful for server
  6993. administrators wishing to group users into a room without these users being able
  6994. to see it from their client.</p>
  6995. <p>By default, no room is excluded.</p>
  6996. <p>Example configuration:</p>
  6997. <pre><code class="language-yaml">exclude_rooms_from_sync:
  6998. - !foo:example.com
  6999. </code></pre>
  7000. <hr />
  7001. <h2 id="opentracing"><a class="header" href="#opentracing">Opentracing</a></h2>
  7002. <p>Configuration options related to Opentracing support.</p>
  7003. <hr />
  7004. <h3 id="opentracing-1"><a class="header" href="#opentracing-1"><code>opentracing</code></a></h3>
  7005. <p>These settings enable and configure opentracing, which implements distributed tracing.
  7006. This allows you to observe the causal chains of events across servers
  7007. including requests, key lookups etc., across any server running
  7008. synapse or any other services which support opentracing
  7009. (specifically those implemented with Jaeger).</p>
  7010. <p>Sub-options include:</p>
  7011. <ul>
  7012. <li><code>enabled</code>: whether tracing is enabled. Set to true to enable. Disabled by default.</li>
  7013. <li><code>homeserver_whitelist</code>: The list of homeservers we wish to send and receive span contexts and span baggage.
  7014. See <a href="usage/configuration/../../opentracing.html">here</a> for more.
  7015. This is a list of regexes which are matched against the <code>server_name</code> of the homeserver.
  7016. By default, it is empty, so no servers are matched.</li>
  7017. <li><code>force_tracing_for_users</code>: # A list of the matrix IDs of users whose requests will always be traced,
  7018. even if the tracing system would otherwise drop the traces due to probabilistic sampling.
  7019. By default, the list is empty.</li>
  7020. <li><code>jaeger_config</code>: Jaeger can be configured to sample traces at different rates.
  7021. All configuration options provided by Jaeger can be set here. Jaeger's configuration is
  7022. mostly related to trace sampling which is documented <a href="https://www.jaegertracing.io/docs/latest/sampling/">here</a>.</li>
  7023. </ul>
  7024. <p>Example configuration:</p>
  7025. <pre><code class="language-yaml">opentracing:
  7026. enabled: true
  7027. homeserver_whitelist:
  7028. - &quot;.*&quot;
  7029. force_tracing_for_users:
  7030. - &quot;@user1:server_name&quot;
  7031. - &quot;@user2:server_name&quot;
  7032. jaeger_config:
  7033. sampler:
  7034. type: const
  7035. param: 1
  7036. logging:
  7037. false
  7038. </code></pre>
  7039. <hr />
  7040. <h2 id="coordinating-workers"><a class="header" href="#coordinating-workers">Coordinating workers</a></h2>
  7041. <p>Configuration options related to workers which belong in the main config file
  7042. (usually called <code>homeserver.yaml</code>).
  7043. A Synapse deployment can scale horizontally by running multiple Synapse processes
  7044. called <em>workers</em>. Incoming requests are distributed between workers to handle higher
  7045. loads. Some workers are privileged and can accept requests from other workers.</p>
  7046. <p>As a result, the worker configuration is divided into two parts.</p>
  7047. <ol>
  7048. <li>The first part (in this section of the manual) defines which shardable tasks
  7049. are delegated to privileged workers. This allows unprivileged workers to make
  7050. requests to a privileged worker to act on their behalf.</li>
  7051. <li><a href="usage/configuration/config_documentation.html#individual-worker-configuration">The second part</a>
  7052. controls the behaviour of individual workers in isolation.</li>
  7053. </ol>
  7054. <p>For guidance on setting up workers, see the <a href="usage/configuration/../../workers.html">worker documentation</a>.</p>
  7055. <hr />
  7056. <h3 id="worker_replication_secret"><a class="header" href="#worker_replication_secret"><code>worker_replication_secret</code></a></h3>
  7057. <p>A shared secret used by the replication APIs on the main process to authenticate
  7058. HTTP requests from workers.</p>
  7059. <p>The default, this value is omitted (equivalently <code>null</code>), which means that
  7060. traffic between the workers and the main process is not authenticated.</p>
  7061. <p>Example configuration:</p>
  7062. <pre><code class="language-yaml">worker_replication_secret: &quot;secret_secret&quot;
  7063. </code></pre>
  7064. <hr />
  7065. <h3 id="start_pushers"><a class="header" href="#start_pushers"><code>start_pushers</code></a></h3>
  7066. <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>
  7067. <p>Controls sending of push notifications on the main process. Set to <code>false</code>
  7068. if using a <a href="usage/configuration/../../workers.html#synapseapppusher">pusher worker</a>. Defaults to <code>true</code>.</p>
  7069. <p>Example configuration:</p>
  7070. <pre><code class="language-yaml">start_pushers: false
  7071. </code></pre>
  7072. <hr />
  7073. <h3 id="pusher_instances"><a class="header" href="#pusher_instances"><code>pusher_instances</code></a></h3>
  7074. <p>It is possible to scale the processes that handle sending push notifications to <a href="https://github.com/matrix-org/sygnal">sygnal</a>
  7075. 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
  7076. a <code>pusher_instances</code> map. Doing so will remove handling of this function from the main
  7077. process. Multiple workers can be added to this map, in which case the work is balanced
  7078. across them. Ensure the main process and all pusher workers are restarted after changing
  7079. this option.</p>
  7080. <p>Example configuration for a single worker:</p>
  7081. <pre><code class="language-yaml">pusher_instances:
  7082. - pusher_worker1
  7083. </code></pre>
  7084. <p>And for multiple workers:</p>
  7085. <pre><code class="language-yaml">pusher_instances:
  7086. - pusher_worker1
  7087. - pusher_worker2
  7088. </code></pre>
  7089. <hr />
  7090. <h3 id="send_federation"><a class="header" href="#send_federation"><code>send_federation</code></a></h3>
  7091. <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>
  7092. <p>Controls sending of outbound federation transactions on the main process.
  7093. Set to <code>false</code> if using a <a href="usage/configuration/../../workers.html#synapseappfederation_sender">federation sender worker</a>.
  7094. Defaults to <code>true</code>.</p>
  7095. <p>Example configuration:</p>
  7096. <pre><code class="language-yaml">send_federation: false
  7097. </code></pre>
  7098. <hr />
  7099. <h3 id="federation_sender_instances"><a class="header" href="#federation_sender_instances"><code>federation_sender_instances</code></a></h3>
  7100. <p>It is possible to scale the processes that handle sending outbound federation requests
  7101. 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
  7102. a <code>federation_sender_instances</code> map. Doing so will remove handling of this function from
  7103. the main process. Multiple workers can be added to this map, in which case the work is
  7104. balanced across them.</p>
  7105. <p>This configuration setting must be shared between all workers handling federation
  7106. sending, and if changed all federation sender workers must be stopped at the same time
  7107. and then started, to ensure that all instances are running with the same config (otherwise
  7108. events may be dropped).</p>
  7109. <p>Example configuration for a single worker:</p>
  7110. <pre><code class="language-yaml">federation_sender_instances:
  7111. - federation_sender1
  7112. </code></pre>
  7113. <p>And for multiple workers:</p>
  7114. <pre><code class="language-yaml">federation_sender_instances:
  7115. - federation_sender1
  7116. - federation_sender2
  7117. </code></pre>
  7118. <hr />
  7119. <h3 id="instance_map"><a class="header" href="#instance_map"><code>instance_map</code></a></h3>
  7120. <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
  7121. replication listener of the worker, if configured, and to the main process. Each worker
  7122. declared under <a href="usage/configuration/../../workers.html#stream-writers"><code>stream_writers</code></a> and
  7123. <a href="usage/configuration/config_documentation.html#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a> needs a HTTP
  7124. replication listener, and that listener should be included in the <code>instance_map</code>. The
  7125. main process also needs an entry on the <code>instance_map</code>, and it should be listed under
  7126. <code>main</code> <strong>if even one other worker exists</strong>. Ensure the port matches with what is
  7127. declared inside the <code>listener</code> block for a <code>replication</code> listener.</p>
  7128. <p>Example configuration:</p>
  7129. <pre><code class="language-yaml">instance_map:
  7130. main:
  7131. host: localhost
  7132. port: 8030
  7133. worker1:
  7134. host: localhost
  7135. port: 8034
  7136. </code></pre>
  7137. <p>Example configuration(#2, for UNIX sockets):</p>
  7138. <pre><code class="language-yaml">instance_map:
  7139. main:
  7140. path: /var/run/synapse/main_replication.sock
  7141. worker1:
  7142. path: /var/run/synapse/worker1_replication.sock
  7143. </code></pre>
  7144. <hr />
  7145. <h3 id="stream_writers"><a class="header" href="#stream_writers"><code>stream_writers</code></a></h3>
  7146. <p>Experimental: When using workers you can define which workers should
  7147. handle writing to streams such as event persistence and typing notifications.
  7148. Any worker specified here must also be in the <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>.</p>
  7149. <p>See the list of available streams in the
  7150. <a href="usage/configuration/../../workers.html#stream-writers">worker documentation</a>.</p>
  7151. <p>Example configuration:</p>
  7152. <pre><code class="language-yaml">stream_writers:
  7153. events: worker1
  7154. typing: worker1
  7155. </code></pre>
  7156. <hr />
  7157. <h3 id="outbound_federation_restricted_to"><a class="header" href="#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a></h3>
  7158. <p>When using workers, you can restrict outbound federation traffic to only go through a
  7159. specific subset of workers. Any worker specified here must also be in the
  7160. <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>.
  7161. <a href="usage/configuration/config_documentation.html#worker_replication_secret"><code>worker_replication_secret</code></a> must also be configured to
  7162. authorize inter-worker communication.</p>
  7163. <pre><code class="language-yaml">outbound_federation_restricted_to:
  7164. - federation_sender1
  7165. - federation_sender2
  7166. </code></pre>
  7167. <h2>Also see the <a href="usage/configuration/../../workers.html#restrict-outbound-federation-traffic-to-a-specific-set-of-workers">worker
  7168. documentation</a>
  7169. for more info.</h2>
  7170. <h3 id="run_background_tasks_on"><a class="header" href="#run_background_tasks_on"><code>run_background_tasks_on</code></a></h3>
  7171. <p>The <a href="usage/configuration/../../workers.html#background-tasks">worker</a> that is used to run
  7172. background tasks (e.g. cleaning up expired data). If not provided this
  7173. defaults to the main process.</p>
  7174. <p>Example configuration:</p>
  7175. <pre><code class="language-yaml">run_background_tasks_on: worker1
  7176. </code></pre>
  7177. <hr />
  7178. <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>
  7179. <p>The <a href="usage/configuration/../../workers.html#updating-the-user-directory">worker</a> that is used to
  7180. update the user directory. If not provided this defaults to the main process.</p>
  7181. <p>Example configuration:</p>
  7182. <pre><code class="language-yaml">update_user_directory_from_worker: worker1
  7183. </code></pre>
  7184. <p><em>Added in Synapse 1.59.0.</em></p>
  7185. <hr />
  7186. <h3 id="notify_appservices_from_worker"><a class="header" href="#notify_appservices_from_worker"><code>notify_appservices_from_worker</code></a></h3>
  7187. <p>The <a href="usage/configuration/../../workers.html#notifying-application-services">worker</a> that is used to
  7188. send output traffic to Application Services. If not provided this defaults
  7189. to the main process.</p>
  7190. <p>Example configuration:</p>
  7191. <pre><code class="language-yaml">notify_appservices_from_worker: worker1
  7192. </code></pre>
  7193. <p><em>Added in Synapse 1.59.0.</em></p>
  7194. <hr />
  7195. <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>
  7196. <p>The <a href="usage/configuration/../../workers.html#synapseappmedia_repository">worker</a> that is used to run
  7197. background tasks for media repository. If running multiple media repositories
  7198. you must configure a single instance to run the background tasks. If not provided
  7199. this defaults to the main process or your single <code>media_repository</code> worker.</p>
  7200. <p>Example configuration:</p>
  7201. <pre><code class="language-yaml">media_instance_running_background_jobs: worker1
  7202. </code></pre>
  7203. <p><em>Added in Synapse 1.16.0.</em></p>
  7204. <hr />
  7205. <h3 id="redis"><a class="header" href="#redis"><code>redis</code></a></h3>
  7206. <p>Configuration for Redis when using workers. This <em>must</em> be enabled when using workers.
  7207. This setting has the following sub-options:</p>
  7208. <ul>
  7209. <li>
  7210. <p><code>enabled</code>: whether to use Redis support. Defaults to false.</p>
  7211. </li>
  7212. <li>
  7213. <p><code>host</code> and <code>port</code>: Optional host and port to use to connect to redis. Defaults to
  7214. localhost and 6379</p>
  7215. </li>
  7216. <li>
  7217. <p><code>path</code>: The full path to a local Unix socket file. <strong>If this is used, <code>host</code> and
  7218. <code>port</code> are ignored.</strong> Defaults to `/tmp/redis.sock'</p>
  7219. </li>
  7220. <li>
  7221. <p><code>password</code>: Optional password if configured on the Redis instance.</p>
  7222. </li>
  7223. <li>
  7224. <p><code>dbid</code>: Optional redis dbid if needs to connect to specific redis logical db.</p>
  7225. </li>
  7226. <li>
  7227. <p><code>use_tls</code>: Whether to use tls connection. Defaults to false.</p>
  7228. </li>
  7229. <li>
  7230. <p><code>certificate_file</code>: Optional path to the certificate file</p>
  7231. </li>
  7232. <li>
  7233. <p><code>private_key_file</code>: Optional path to the private key file</p>
  7234. </li>
  7235. <li>
  7236. <p><code>ca_file</code>: Optional path to the CA certificate file. Use this one or:</p>
  7237. </li>
  7238. <li>
  7239. <p><code>ca_path</code>: Optional path to the folder containing the CA certificate file</p>
  7240. <p><em>Added in Synapse 1.78.0.</em></p>
  7241. <p><em>Changed in Synapse 1.84.0: Added use_tls, certificate_file, private_key_file, ca_file and ca_path attributes</em></p>
  7242. <p><em>Changed in Synapse 1.85.0: Added path option to use a local Unix socket</em></p>
  7243. </li>
  7244. </ul>
  7245. <p>Example configuration:</p>
  7246. <pre><code class="language-yaml">redis:
  7247. enabled: true
  7248. host: localhost
  7249. port: 6379
  7250. password: &lt;secret_password&gt;
  7251. dbid: &lt;dbid&gt;
  7252. #use_tls: True
  7253. #certificate_file: &lt;path_to_the_certificate_file&gt;
  7254. #private_key_file: &lt;path_to_the_private_key_file&gt;
  7255. #ca_file: &lt;path_to_the_ca_certificate_file&gt;
  7256. </code></pre>
  7257. <hr />
  7258. <h2 id="individual-worker-configuration"><a class="header" href="#individual-worker-configuration">Individual worker configuration</a></h2>
  7259. <p>These options configure an individual worker, in its worker configuration file.
  7260. They should be not be provided when configuring the main process.</p>
  7261. <p>Note also the configuration above for
  7262. <a href="usage/configuration/config_documentation.html#coordinating-workers">coordinating a cluster of workers</a>.</p>
  7263. <p>For guidance on setting up workers, see the <a href="usage/configuration/../../workers.html">worker documentation</a>.</p>
  7264. <hr />
  7265. <h3 id="worker_app"><a class="header" href="#worker_app"><code>worker_app</code></a></h3>
  7266. <p>The type of worker. The currently available worker applications are listed
  7267. in <a href="usage/configuration/../../workers.html#available-worker-applications">worker documentation</a>.</p>
  7268. <p>The most common worker is the
  7269. <a href="usage/configuration/../../workers.html#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a>.</p>
  7270. <p>Example configuration:</p>
  7271. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  7272. </code></pre>
  7273. <hr />
  7274. <h3 id="worker_name"><a class="header" href="#worker_name"><code>worker_name</code></a></h3>
  7275. <p>A unique name for the worker. The worker needs a name to be addressed in
  7276. further parameters and identification in log files. We strongly recommend
  7277. giving each worker a unique <code>worker_name</code>.</p>
  7278. <p>Example configuration:</p>
  7279. <pre><code class="language-yaml">worker_name: generic_worker1
  7280. </code></pre>
  7281. <hr />
  7282. <h3 id="worker_listeners"><a class="header" href="#worker_listeners"><code>worker_listeners</code></a></h3>
  7283. <p>A worker can handle HTTP requests. To do so, a <code>worker_listeners</code> option
  7284. must be declared, in the same way as the <a href="usage/configuration/config_documentation.html#listeners"><code>listeners</code> option</a>
  7285. in the shared config.</p>
  7286. <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>
  7287. will need to include a <code>replication</code> listener here, in order to accept internal HTTP
  7288. requests from other workers.</p>
  7289. <p>Example configuration:</p>
  7290. <pre><code class="language-yaml">worker_listeners:
  7291. - type: http
  7292. port: 8083
  7293. resources:
  7294. - names: [client, federation]
  7295. </code></pre>
  7296. <p>Example configuration(#2, using UNIX sockets with a <code>replication</code> listener):</p>
  7297. <pre><code class="language-yaml">worker_listeners:
  7298. - type: http
  7299. path: /var/run/synapse/worker_public.sock
  7300. resources:
  7301. - names: [client, federation]
  7302. - type: http
  7303. path: /var/run/synapse/worker_replication.sock
  7304. resources:
  7305. - names: [replication]
  7306. </code></pre>
  7307. <hr />
  7308. <h3 id="worker_manhole"><a class="header" href="#worker_manhole"><code>worker_manhole</code></a></h3>
  7309. <p>A worker may have a listener for <a href="usage/configuration/../../manhole.html"><code>manhole</code></a>.
  7310. It allows server administrators to access a Python shell on the worker.</p>
  7311. <p>Example configuration:</p>
  7312. <pre><code class="language-yaml">worker_manhole: 9000
  7313. </code></pre>
  7314. <p>This is a short form for:</p>
  7315. <pre><code class="language-yaml">worker_listeners:
  7316. - port: 9000
  7317. bind_addresses: ['127.0.0.1']
  7318. type: manhole
  7319. </code></pre>
  7320. <p>It needs also an additional <a href="usage/configuration/config_documentation.html#manhole_settings"><code>manhole_settings</code></a> configuration.</p>
  7321. <hr />
  7322. <h3 id="worker_daemonize"><a class="header" href="#worker_daemonize"><code>worker_daemonize</code></a></h3>
  7323. <p>Specifies whether the worker should be started as a daemon process.
  7324. If Synapse is being managed by <a href="usage/configuration/../../systemd-with-workers/">systemd</a>, this option
  7325. must be omitted or set to <code>false</code>.</p>
  7326. <p>Defaults to <code>false</code>.</p>
  7327. <p>Example configuration:</p>
  7328. <pre><code class="language-yaml">worker_daemonize: true
  7329. </code></pre>
  7330. <hr />
  7331. <h3 id="worker_pid_file"><a class="header" href="#worker_pid_file"><code>worker_pid_file</code></a></h3>
  7332. <p>When running a worker as a daemon, we need a place to store the
  7333. <a href="https://en.wikipedia.org/wiki/Process_identifier">PID</a> of the worker.
  7334. This option defines the location of that &quot;pid file&quot;.</p>
  7335. <p>This option is required if <code>worker_daemonize</code> is <code>true</code> and ignored
  7336. otherwise. It has no default.</p>
  7337. <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>
  7338. <p>Example configuration:</p>
  7339. <pre><code class="language-yaml">worker_pid_file: DATADIR/generic_worker1.pid
  7340. </code></pre>
  7341. <hr />
  7342. <h3 id="worker_log_config"><a class="header" href="#worker_log_config"><code>worker_log_config</code></a></h3>
  7343. <p>This option specifies a yaml python logging config file as described
  7344. <a href="https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema">here</a>.
  7345. 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>
  7346. <p>Example configuration:</p>
  7347. <pre><code class="language-yaml">worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  7348. </code></pre>
  7349. <hr />
  7350. <h2 id="background-updates"><a class="header" href="#background-updates">Background Updates</a></h2>
  7351. <p>Configuration settings related to background updates.</p>
  7352. <hr />
  7353. <h3 id="background_updates"><a class="header" href="#background_updates"><code>background_updates</code></a></h3>
  7354. <p>Background updates are database updates that are run in the background in batches.
  7355. The duration, minimum batch size, default batch size, whether to sleep between batches and if so, how long to
  7356. sleep can all be configured. This is helpful to speed up or slow down the updates.
  7357. This setting has the following sub-options:</p>
  7358. <ul>
  7359. <li><code>background_update_duration_ms</code>: How long in milliseconds to run a batch of background updates for. Defaults to 100.
  7360. Set a different time to change the default.</li>
  7361. <li><code>sleep_enabled</code>: Whether to sleep between updates. Defaults to true. Set to false to change the default.</li>
  7362. <li><code>sleep_duration_ms</code>: If sleeping between updates, how long in milliseconds to sleep for. Defaults to 1000.
  7363. Set a duration to change the default.</li>
  7364. <li><code>min_batch_size</code>: Minimum size a batch of background updates can be. Must be greater than 0. Defaults to 1.
  7365. Set a size to change the default.</li>
  7366. <li><code>default_batch_size</code>: The batch size to use for the first iteration of a new background update. The default is 100.
  7367. Set a size to change the default.</li>
  7368. </ul>
  7369. <p>Example configuration:</p>
  7370. <pre><code class="language-yaml">background_updates:
  7371. background_update_duration_ms: 500
  7372. sleep_enabled: false
  7373. sleep_duration_ms: 300
  7374. min_batch_size: 10
  7375. default_batch_size: 50
  7376. </code></pre>
  7377. <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>
  7378. <p>Below is a sample homeserver configuration file. The homeserver configuration file
  7379. can be tweaked to change the behaviour of your homeserver. A restart of the server is
  7380. generally required to apply any changes made to this file.</p>
  7381. <p>Note that the contents below are <em>not</em> intended to be copied and used as the basis for
  7382. a real homeserver.yaml. Instead, if you are starting from scratch, please generate
  7383. a fresh config using Synapse by following the instructions in
  7384. <a href="usage/configuration/../../setup/installation.html">Installation</a>.</p>
  7385. <p>Documentation for all configuration options can be found in the
  7386. <a href="usage/configuration/./config_documentation.html">Configuration Manual</a>.</p>
  7387. <pre><code class="language-yaml"># This file is maintained as an up-to-date snapshot of the default
  7388. # homeserver.yaml configuration generated by Synapse. You can find a
  7389. # complete accounting of possible configuration options at
  7390. # https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
  7391. #
  7392. # It is *not* intended to be copied and used as the basis for a real
  7393. # homeserver.yaml. Instead, if you are starting from scratch, please generate
  7394. # a fresh config using Synapse by following the instructions in
  7395. # https://matrix-org.github.io/synapse/latest/setup/installation.html.
  7396. #
  7397. ################################################################################
  7398. # Configuration file for Synapse.
  7399. #
  7400. # This is a YAML file: see [1] for a quick introduction. Note in particular
  7401. # that *indentation is important*: all the elements of a list or dictionary
  7402. # should have the same indentation.
  7403. #
  7404. # [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
  7405. #
  7406. # For more information on how to configure Synapse, including a complete accounting of
  7407. # each option, go to docs/usage/configuration/config_documentation.md or
  7408. # https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
  7409. server_name: &quot;SERVERNAME&quot;
  7410. pid_file: DATADIR/homeserver.pid
  7411. listeners:
  7412. - port: 8008
  7413. tls: false
  7414. type: http
  7415. x_forwarded: true
  7416. bind_addresses: ['::1', '127.0.0.1']
  7417. resources:
  7418. - names: [client, federation]
  7419. compress: false
  7420. database:
  7421. name: sqlite3
  7422. args:
  7423. database: DATADIR/homeserver.db
  7424. log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  7425. media_store_path: DATADIR/media_store
  7426. signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  7427. trusted_key_servers:
  7428. - server_name: &quot;matrix.org&quot;
  7429. </code></pre>
  7430. <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>
  7431. <p>Below is a sample logging configuration file. This file can be tweaked to control how your
  7432. homeserver will output logs. The value of the <code>log_config</code> option in your homeserver config
  7433. should be the path to this file.</p>
  7434. <p>To apply changes made to this file, send Synapse a SIGHUP signal (or, if using <code>systemd</code>, run
  7435. <code>systemctl reload</code> on the Synapse service).</p>
  7436. <p>Note that a default logging configuration (shown below) is created automatically alongside
  7437. the homeserver config when following the <a href="usage/configuration/../../setup/installation.html">installation instructions</a>.
  7438. It should be named <code>&lt;SERVERNAME&gt;.log.config</code> by default.</p>
  7439. <pre><code class="language-yaml"># Log configuration for Synapse.
  7440. #
  7441. # This is a YAML file containing a standard Python logging configuration
  7442. # dictionary. See [1] for details on the valid settings.
  7443. #
  7444. # Synapse also supports structured logging for machine readable logs which can
  7445. # be ingested by ELK stacks. See [2] for details.
  7446. #
  7447. # [1]: https://docs.python.org/3/library/logging.config.html#configuration-dictionary-schema
  7448. # [2]: https://matrix-org.github.io/synapse/latest/structured_logging.html
  7449. version: 1
  7450. formatters:
  7451. precise:
  7452. format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s'
  7453. handlers:
  7454. file:
  7455. class: logging.handlers.TimedRotatingFileHandler
  7456. formatter: precise
  7457. filename: /var/log/matrix-synapse/homeserver.log
  7458. when: midnight
  7459. backupCount: 3 # Does not include the current log file.
  7460. encoding: utf8
  7461. # Default to buffering writes to log file for efficiency.
  7462. # WARNING/ERROR logs will still be flushed immediately, but there will be a
  7463. # delay (of up to `period` seconds, or until the buffer is full with
  7464. # `capacity` messages) before INFO/DEBUG logs get written.
  7465. buffer:
  7466. class: synapse.logging.handlers.PeriodicallyFlushingMemoryHandler
  7467. target: file
  7468. # The capacity is the maximum number of log lines that are buffered
  7469. # before being written to disk. Increasing this will lead to better
  7470. # performance, at the expensive of it taking longer for log lines to
  7471. # be written to disk.
  7472. # This parameter is required.
  7473. capacity: 10
  7474. # Logs with a level at or above the flush level will cause the buffer to
  7475. # be flushed immediately.
  7476. # Default value: 40 (ERROR)
  7477. # Other values: 50 (CRITICAL), 30 (WARNING), 20 (INFO), 10 (DEBUG)
  7478. flushLevel: 30 # Flush immediately for WARNING logs and higher
  7479. # The period of time, in seconds, between forced flushes.
  7480. # Messages will not be delayed for longer than this time.
  7481. # Default value: 5 seconds
  7482. period: 5
  7483. # A handler that writes logs to stderr. Unused by default, but can be used
  7484. # instead of &quot;buffer&quot; and &quot;file&quot; in the logger handlers.
  7485. console:
  7486. class: logging.StreamHandler
  7487. formatter: precise
  7488. loggers:
  7489. synapse.storage.SQL:
  7490. # beware: increasing this to DEBUG will make synapse log sensitive
  7491. # information such as access tokens.
  7492. level: INFO
  7493. root:
  7494. level: INFO
  7495. # Write logs to the `buffer` handler, which will buffer them together in memory,
  7496. # then write them to a file.
  7497. #
  7498. # Replace &quot;buffer&quot; with &quot;console&quot; to log to stderr instead.
  7499. #
  7500. handlers: [buffer]
  7501. disable_existing_loggers: false
  7502. </code></pre>
  7503. <div style="break-before: page; page-break-before: always;"></div><h1 id="structured-logging"><a class="header" href="#structured-logging">Structured Logging</a></h1>
  7504. <p>A structured logging system can be useful when your logs are destined for a
  7505. machine to parse and process. By maintaining its machine-readable characteristics,
  7506. it enables more efficient searching and aggregations when consumed by software
  7507. such as the <a href="https://opensource.com/article/18/9/open-source-log-aggregation-tools">ELK stack</a>.</p>
  7508. <p>Synapse's structured logging system is configured via the file that Synapse's
  7509. <code>log_config</code> config option points to. The file should include a formatter which
  7510. uses the <code>synapse.logging.TerseJsonFormatter</code> class included with Synapse and a
  7511. handler which uses the above formatter.</p>
  7512. <p>There is also a <code>synapse.logging.JsonFormatter</code> option which does not include
  7513. a timestamp in the resulting JSON. This is useful if the log ingester adds its
  7514. own timestamp.</p>
  7515. <p>A structured logging configuration looks similar to the following:</p>
  7516. <pre><code class="language-yaml">version: 1
  7517. formatters:
  7518. structured:
  7519. class: synapse.logging.TerseJsonFormatter
  7520. handlers:
  7521. file:
  7522. class: logging.handlers.TimedRotatingFileHandler
  7523. formatter: structured
  7524. filename: /path/to/my/logs/homeserver.log
  7525. when: midnight
  7526. backupCount: 3 # Does not include the current log file.
  7527. encoding: utf8
  7528. loggers:
  7529. synapse:
  7530. level: INFO
  7531. handlers: [remote]
  7532. synapse.storage.SQL:
  7533. level: WARNING
  7534. </code></pre>
  7535. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  7536. with the SQL layer at 'WARNING', and will log to a file, stored as JSON.</p>
  7537. <p>It is also possible to configure Synapse to log to a remote endpoint by using the
  7538. <code>synapse.logging.RemoteHandler</code> class included with Synapse. It takes the
  7539. following arguments:</p>
  7540. <ul>
  7541. <li><code>host</code>: Hostname or IP address of the log aggregator.</li>
  7542. <li><code>port</code>: Numerical port to contact on the host.</li>
  7543. <li><code>maximum_buffer</code>: (Optional, defaults to 1000) The maximum buffer size to allow.</li>
  7544. </ul>
  7545. <p>A remote structured logging configuration looks similar to the following:</p>
  7546. <pre><code class="language-yaml">version: 1
  7547. formatters:
  7548. structured:
  7549. class: synapse.logging.TerseJsonFormatter
  7550. handlers:
  7551. remote:
  7552. class: synapse.logging.RemoteHandler
  7553. formatter: structured
  7554. host: 10.1.2.3
  7555. port: 9999
  7556. loggers:
  7557. synapse:
  7558. level: INFO
  7559. handlers: [remote]
  7560. synapse.storage.SQL:
  7561. level: WARNING
  7562. </code></pre>
  7563. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  7564. with the SQL layer at 'WARNING', and will log JSON formatted messages to a
  7565. remote endpoint at 10.1.2.3:9999.</p>
  7566. <div style="break-before: page; page-break-before: always;"></div><h1 id="templates"><a class="header" href="#templates">Templates</a></h1>
  7567. <p>Synapse uses parametrised templates to generate the content of emails it sends and
  7568. webpages it shows to users.</p>
  7569. <p>By default, Synapse will use the templates listed <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">here</a>.
  7570. Server admins can configure an additional directory for Synapse to look for templates
  7571. in, allowing them to specify custom templates:</p>
  7572. <pre><code class="language-yaml">templates:
  7573. custom_template_directory: /path/to/custom/templates/
  7574. </code></pre>
  7575. <p>If this setting is not set, or the files named below are not found within the directory,
  7576. default templates from within the Synapse package will be used.</p>
  7577. <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>.
  7578. Templates rendered by Jinja 2 can also access two functions on top of the functions
  7579. already available as part of Jinja 2:</p>
  7580. <pre><code class="language-python">format_ts(value: int, format: str) -&gt; str
  7581. </code></pre>
  7582. <p>Formats a timestamp in milliseconds.</p>
  7583. <p>Example: <code>reason.last_sent_ts|format_ts(&quot;%c&quot;)</code></p>
  7584. <pre><code class="language-python">mxc_to_http(value: str, width: int, height: int, resize_method: str = &quot;crop&quot;) -&gt; str
  7585. </code></pre>
  7586. <p>Turns a <code>mxc://</code> URL for media content into an HTTP(S) one using the homeserver's
  7587. <code>public_baseurl</code> configuration setting as the URL's base.</p>
  7588. <p>Example: <code>message.sender_avatar_url|mxc_to_http(32,32)</code></p>
  7589. <pre><code class="language-python">localpart_from_email(address: str) -&gt; str
  7590. </code></pre>
  7591. <p>Returns the local part of an email address (e.g. <code>alice</code> in <code>alice@example.com</code>).</p>
  7592. <p>Example: <code>user.email_address|localpart_from_email</code></p>
  7593. <h2 id="email-templates"><a class="header" href="#email-templates">Email templates</a></h2>
  7594. <p>Below are the templates Synapse will look for when generating the content of an email:</p>
  7595. <ul>
  7596. <li><code>notif_mail.html</code> and <code>notif_mail.txt</code>: The contents of email notifications of missed
  7597. events.
  7598. When rendering, this template is given the following variables:
  7599. <ul>
  7600. <li><code>user_display_name</code>: the display name for the user receiving the notification</li>
  7601. <li><code>unsubscribe_link</code>: the link users can click to unsubscribe from email notifications</li>
  7602. <li><code>summary_text</code>: a summary of the notification(s). The text used can be customised
  7603. by configuring the various settings in the <code>email.subjects</code> section of the
  7604. configuration file.</li>
  7605. <li><code>rooms</code>: a list of rooms containing events to include in the email. Each element is
  7606. an object with the following attributes:
  7607. <ul>
  7608. <li><code>title</code>: a human-readable name for the room</li>
  7609. <li><code>hash</code>: a hash of the ID of the room</li>
  7610. <li><code>invite</code>: a boolean, which is <code>True</code> if the room is an invite the user hasn't
  7611. accepted yet, <code>False</code> otherwise</li>
  7612. <li><code>notifs</code>: a list of events, or an empty list if <code>invite</code> is <code>True</code>. Each element
  7613. is an object with the following attributes:
  7614. <ul>
  7615. <li><code>link</code>: a <code>matrix.to</code> link to the event</li>
  7616. <li><code>ts</code>: the time in milliseconds at which the event was received</li>
  7617. <li><code>messages</code>: a list of messages containing one message before the event, the
  7618. message in the event, and one message after the event. Each element is an
  7619. object with the following attributes:
  7620. <ul>
  7621. <li><code>event_type</code>: the type of the event</li>
  7622. <li><code>is_historical</code>: a boolean, which is <code>False</code> if the message is the one
  7623. that triggered the notification, <code>True</code> otherwise</li>
  7624. <li><code>id</code>: the ID of the event</li>
  7625. <li><code>ts</code>: the time in milliseconds at which the event was sent</li>
  7626. <li><code>sender_name</code>: the display name for the event's sender</li>
  7627. <li><code>sender_avatar_url</code>: the avatar URL (as a <code>mxc://</code> URL) for the event's
  7628. sender</li>
  7629. <li><code>sender_hash</code>: a hash of the user ID of the sender</li>
  7630. <li><code>msgtype</code>: the type of the message</li>
  7631. <li><code>body_text_html</code>: html representation of the message</li>
  7632. <li><code>body_text_plain</code>: plaintext representation of the message</li>
  7633. <li><code>image_url</code>: mxc url of an image, when &quot;msgtype&quot; is &quot;m.image&quot;</li>
  7634. </ul>
  7635. </li>
  7636. </ul>
  7637. </li>
  7638. <li><code>link</code>: a <code>matrix.to</code> link to the room</li>
  7639. <li><code>avator_url</code>: url to the room's avator</li>
  7640. </ul>
  7641. </li>
  7642. <li><code>reason</code>: information on the event that triggered the email to be sent. It's an
  7643. object with the following attributes:
  7644. <ul>
  7645. <li><code>room_id</code>: the ID of the room the event was sent in</li>
  7646. <li><code>room_name</code>: a human-readable name for the room the event was sent in</li>
  7647. <li><code>now</code>: the current time in milliseconds</li>
  7648. <li><code>received_at</code>: the time in milliseconds at which the event was received</li>
  7649. <li><code>delay_before_mail_ms</code>: the amount of time in milliseconds Synapse always waits
  7650. before ever emailing about a notification (to give the user a chance to respond
  7651. to other push or notice the window)</li>
  7652. <li><code>last_sent_ts</code>: the time in milliseconds at which a notification was last sent
  7653. for an event in this room</li>
  7654. <li><code>throttle_ms</code>: the minimum amount of time in milliseconds between two
  7655. notifications can be sent for this room</li>
  7656. </ul>
  7657. </li>
  7658. </ul>
  7659. </li>
  7660. <li><code>password_reset.html</code> and <code>password_reset.txt</code>: The contents of password reset emails
  7661. sent by the homeserver.
  7662. When rendering, these templates are given a <code>link</code> variable which contains the link the
  7663. user must click in order to reset their password.</li>
  7664. <li><code>registration.html</code> and <code>registration.txt</code>: The contents of address verification emails
  7665. sent during registration.
  7666. When rendering, these templates are given a <code>link</code> variable which contains the link the
  7667. user must click in order to validate their email address.</li>
  7668. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code>: The contents of address verification emails
  7669. sent when an address is added to a Matrix account.
  7670. When rendering, these templates are given a <code>link</code> variable which contains the link the
  7671. user must click in order to validate their email address.</li>
  7672. </ul>
  7673. <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>
  7674. <p>Below are the templates Synapse will look for when generating pages related to
  7675. registration and password reset:</p>
  7676. <ul>
  7677. <li><code>password_reset_confirmation.html</code>: An HTML page that a user will see when they follow
  7678. the link in the password reset email. The user will be asked to confirm the action
  7679. before their password is reset.
  7680. When rendering, this template is given the following variables:
  7681. <ul>
  7682. <li><code>sid</code>: the session ID for the password reset</li>
  7683. <li><code>token</code>: the token for the password reset</li>
  7684. <li><code>client_secret</code>: the client secret for the password reset</li>
  7685. </ul>
  7686. </li>
  7687. <li><code>password_reset_success.html</code> and <code>password_reset_failure.html</code>: HTML pages for success
  7688. and failure that a user will see when they confirm the password reset flow using the
  7689. page above.
  7690. When rendering, <code>password_reset_success.html</code> is given no variable, and
  7691. <code>password_reset_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  7692. for the password reset failure. </li>
  7693. <li><code>registration_success.html</code> and <code>registration_failure.html</code>: HTML pages for success and
  7694. failure that a user will see when they follow the link in an address verification email
  7695. sent during registration.
  7696. When rendering, <code>registration_success.html</code> is given no variable, and
  7697. <code>registration_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  7698. for the registration failure.</li>
  7699. <li><code>add_threepid_success.html</code> and <code>add_threepid_failure.html</code>: HTML pages for success and
  7700. failure that a user will see when they follow the link in an address verification email
  7701. sent when an address is added to a Matrix account.
  7702. When rendering, <code>add_threepid_success.html</code> is given no variable, and
  7703. <code>add_threepid_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  7704. for the registration failure.</li>
  7705. </ul>
  7706. <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>
  7707. <p>Below are the templates Synapse will look for when generating pages related to SSO:</p>
  7708. <ul>
  7709. <li><code>sso_login_idp_picker.html</code>: HTML page to prompt the user to choose an
  7710. Identity Provider during login.
  7711. This is only used if multiple SSO Identity Providers are configured.
  7712. When rendering, this template is given the following variables:
  7713. <ul>
  7714. <li><code>redirect_url</code>: the URL that the user will be redirected to after
  7715. login.</li>
  7716. <li><code>server_name</code>: the homeserver's name.</li>
  7717. <li><code>providers</code>: a list of available Identity Providers. Each element is
  7718. an object with the following attributes:
  7719. <ul>
  7720. <li><code>idp_id</code>: unique identifier for the IdP</li>
  7721. <li><code>idp_name</code>: user-facing name for the IdP</li>
  7722. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  7723. for the IdP</li>
  7724. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  7725. for the brand of the IdP
  7726. The rendered HTML page should contain a form which submits its results
  7727. back as a GET request, with the following query parameters:</li>
  7728. </ul>
  7729. </li>
  7730. <li><code>redirectUrl</code>: the client redirect URI (ie, the <code>redirect_url</code> passed
  7731. to the template)</li>
  7732. <li><code>idp</code>: the 'idp_id' of the chosen IDP.</li>
  7733. </ul>
  7734. </li>
  7735. <li><code>sso_auth_account_details.html</code>: HTML page to prompt new users to enter a
  7736. userid and confirm other details. This is only shown if the
  7737. SSO implementation (with any <code>user_mapping_provider</code>) does not return
  7738. a localpart.
  7739. When rendering, this template is given the following variables:
  7740. <ul>
  7741. <li><code>server_name</code>: the homeserver's name.</li>
  7742. <li><code>idp</code>: details of the SSO Identity Provider that the user logged in
  7743. with: an object with the following attributes:
  7744. <ul>
  7745. <li><code>idp_id</code>: unique identifier for the IdP</li>
  7746. <li><code>idp_name</code>: user-facing name for the IdP</li>
  7747. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  7748. for the IdP</li>
  7749. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  7750. for the brand of the IdP</li>
  7751. </ul>
  7752. </li>
  7753. <li><code>user_attributes</code>: an object containing details about the user that
  7754. we received from the IdP. May have the following attributes:
  7755. <ul>
  7756. <li><code>display_name</code>: the user's display name</li>
  7757. <li><code>emails</code>: a list of email addresses</li>
  7758. <li><code>localpart</code>: the local part of the Matrix user ID to register,
  7759. if <code>localpart_template</code> is set in the mapping provider configuration (empty
  7760. string if not)
  7761. The template should render a form which submits the following fields:</li>
  7762. </ul>
  7763. </li>
  7764. <li><code>username</code>: the localpart of the user's chosen user id</li>
  7765. </ul>
  7766. </li>
  7767. <li><code>sso_new_user_consent.html</code>: HTML page allowing the user to consent to the
  7768. server's terms and conditions. This is only shown for new users, and only if
  7769. <code>user_consent.require_at_registration</code> is set.
  7770. When rendering, this template is given the following variables:
  7771. <ul>
  7772. <li><code>server_name</code>: the homeserver's name.</li>
  7773. <li><code>user_id</code>: the user's matrix proposed ID.</li>
  7774. <li><code>user_profile.display_name</code>: the user's proposed display name, if any.</li>
  7775. <li>consent_version: the version of the terms that the user will be
  7776. shown</li>
  7777. <li><code>terms_url</code>: a link to the page showing the terms.
  7778. The template should render a form which submits the following fields:</li>
  7779. <li><code>accepted_version</code>: the version of the terms accepted by the user
  7780. (ie, 'consent_version' from the input variables).</li>
  7781. </ul>
  7782. </li>
  7783. <li><code>sso_redirect_confirm.html</code>: HTML page for a confirmation step before redirecting back
  7784. to the client with the login token.
  7785. When rendering, this template is given the following variables:
  7786. <ul>
  7787. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  7788. <li><code>display_url</code>: the same as <code>redirect_url</code>, but with the query
  7789. parameters stripped. The intention is to have a
  7790. human-readable URL to show to users, not to use it as
  7791. the final address to redirect to.</li>
  7792. <li><code>server_name</code>: the homeserver's name.</li>
  7793. <li><code>new_user</code>: a boolean indicating whether this is the user's first time
  7794. logging in.</li>
  7795. <li><code>user_id</code>: the user's matrix ID.</li>
  7796. <li><code>user_profile.avatar_url</code>: an MXC URI for the user's avatar, if any.
  7797. <code>None</code> if the user has not set an avatar.</li>
  7798. <li><code>user_profile.display_name</code>: the user's display name. <code>None</code> if the user
  7799. has not set a display name.</li>
  7800. </ul>
  7801. </li>
  7802. <li><code>sso_auth_confirm.html</code>: HTML page which notifies the user that they are authenticating
  7803. to confirm an operation on their account during the user interactive authentication
  7804. process.
  7805. When rendering, this template is given the following variables:
  7806. <ul>
  7807. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  7808. <li><code>description</code>: the operation which the user is being asked to confirm</li>
  7809. <li><code>idp</code>: details of the Identity Provider that we will use to confirm
  7810. the user's identity: an object with the following attributes:
  7811. <ul>
  7812. <li><code>idp_id</code>: unique identifier for the IdP</li>
  7813. <li><code>idp_name</code>: user-facing name for the IdP</li>
  7814. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  7815. for the IdP</li>
  7816. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  7817. for the brand of the IdP</li>
  7818. </ul>
  7819. </li>
  7820. </ul>
  7821. </li>
  7822. <li><code>sso_auth_success.html</code>: HTML page shown after a successful user interactive
  7823. authentication session.
  7824. Note that this page must include the JavaScript which notifies of a successful
  7825. authentication (see https://matrix.org/docs/spec/client_server/r0.6.0#fallback).
  7826. This template has no additional variables.</li>
  7827. <li><code>sso_auth_bad_user.html</code>: HTML page shown after a user-interactive authentication
  7828. session which does not map correctly onto the expected user.
  7829. When rendering, this template is given the following variables:
  7830. <ul>
  7831. <li><code>server_name</code>: the homeserver's name.</li>
  7832. <li><code>user_id_to_verify</code>: the MXID of the user that we are trying to
  7833. validate.</li>
  7834. </ul>
  7835. </li>
  7836. <li><code>sso_account_deactivated.html</code>: HTML page shown during single sign-on if a deactivated
  7837. user (according to Synapse's database) attempts to login.
  7838. This template has no additional variables.</li>
  7839. <li><code>sso_error.html</code>: HTML page to display to users if something goes wrong during the
  7840. OpenID Connect authentication process.
  7841. When rendering, this template is given two variables:
  7842. <ul>
  7843. <li><code>error</code>: the technical name of the error</li>
  7844. <li><code>error_description</code>: a human-readable message for the error</li>
  7845. </ul>
  7846. </li>
  7847. </ul>
  7848. <div style="break-before: page; page-break-before: always;"></div><h1 id="user-authentication"><a class="header" href="#user-authentication">User Authentication</a></h1>
  7849. <p>Synapse supports multiple methods of authenticating users, either out-of-the-box or through custom pluggable
  7850. authentication modules.</p>
  7851. <p>Included in Synapse is support for authenticating users via:</p>
  7852. <ul>
  7853. <li>A username and password.</li>
  7854. <li>An email address and password.</li>
  7855. <li>Single Sign-On through the SAML, Open ID Connect or CAS protocols.</li>
  7856. <li>JSON Web Tokens.</li>
  7857. <li>An administrator's shared secret.</li>
  7858. </ul>
  7859. <p>Synapse can additionally be extended to support custom authentication schemes through optional &quot;password auth provider&quot;
  7860. modules.</p>
  7861. <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>
  7862. <p>Synapse supports single sign-on through the SAML, Open ID Connect or CAS protocols.
  7863. LDAP and other login methods are supported through first and third-party password
  7864. auth provider modules.</p>
  7865. <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>
  7866. <p>Synapse can be configured to use an OpenID Connect Provider (OP) for
  7867. authentication, instead of its own local password database.</p>
  7868. <p>Any OP should work with Synapse, as long as it supports the authorization code
  7869. flow. There are a few options for that:</p>
  7870. <ul>
  7871. <li>
  7872. <p>start a local OP. Synapse has been tested with <a href="https://www.ory.sh/docs/hydra/">Hydra</a> and
  7873. <a href="https://github.com/dexidp/dex">Dex</a>. Note that for an OP to work, it should be served under a
  7874. secure (HTTPS) origin. A certificate signed with a self-signed, locally
  7875. trusted CA should work. In that case, start Synapse with a <code>SSL_CERT_FILE</code>
  7876. environment variable set to the path of the CA.</p>
  7877. </li>
  7878. <li>
  7879. <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
  7880. <a href="https://www.okta.com/">Okta</a>. Synapse has been tested with Auth0 and Google.</p>
  7881. </li>
  7882. </ul>
  7883. <p>It may also be possible to use other OAuth2 providers which provide the
  7884. <a href="https://tools.ietf.org/html/rfc6749#section-4.1">authorization code grant type</a>,
  7885. such as <a href="https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps">Github</a>.</p>
  7886. <h2 id="preparing-synapse"><a class="header" href="#preparing-synapse">Preparing Synapse</a></h2>
  7887. <p>The OpenID integration in Synapse uses the
  7888. <a href="https://pypi.org/project/Authlib/"><code>authlib</code></a> library, which must be installed
  7889. as follows:</p>
  7890. <ul>
  7891. <li>
  7892. <p>The relevant libraries are included in the Docker images and Debian packages
  7893. provided by <code>matrix.org</code> so no further action is needed.</p>
  7894. </li>
  7895. <li>
  7896. <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>
  7897. </li>
  7898. <li>
  7899. <p>For other installation mechanisms, see the documentation provided by the
  7900. maintainer.</p>
  7901. </li>
  7902. </ul>
  7903. <p>To enable the OpenID integration, you should then add a section to the <code>oidc_providers</code>
  7904. setting in your configuration file.
  7905. See the <a href="usage/configuration/config_documentation.html#oidc_providers">configuration manual</a> for some sample settings, as well as
  7906. the text below for example configurations for specific providers.</p>
  7907. <h2 id="oidc-back-channel-logout"><a class="header" href="#oidc-back-channel-logout">OIDC Back-Channel Logout</a></h2>
  7908. <p>Synapse supports receiving <a href="https://openid.net/specs/openid-connect-backchannel-1_0.html">OpenID Connect Back-Channel Logout</a> notifications.</p>
  7909. <p>This lets the OpenID Connect Provider notify Synapse when a user logs out, so that Synapse can end that user session.
  7910. 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>
  7911. <h2 id="sample-configs"><a class="header" href="#sample-configs">Sample configs</a></h2>
  7912. <p>Here are a few configs for providers that should work with Synapse.</p>
  7913. <h3 id="microsoft-azure-active-directory"><a class="header" href="#microsoft-azure-active-directory">Microsoft Azure Active Directory</a></h3>
  7914. <p>Azure AD can act as an OpenID Connect Provider. Register a new application under
  7915. <em>App registrations</em> in the Azure AD management console. The RedirectURI for your
  7916. application should point to your matrix server:
  7917. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  7918. <p>Go to <em>Certificates &amp; secrets</em> and register a new client secret. Make note of your
  7919. Directory (tenant) ID as it will be used in the Azure links.
  7920. Edit your Synapse config file and change the <code>oidc_config</code> section:</p>
  7921. <pre><code class="language-yaml">oidc_providers:
  7922. - idp_id: microsoft
  7923. idp_name: Microsoft
  7924. issuer: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/v2.0&quot;
  7925. client_id: &quot;&lt;client id&gt;&quot;
  7926. client_secret: &quot;&lt;client secret&gt;&quot;
  7927. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7928. authorization_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/authorize&quot;
  7929. token_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/token&quot;
  7930. userinfo_endpoint: &quot;https://graph.microsoft.com/oidc/userinfo&quot;
  7931. user_mapping_provider:
  7932. config:
  7933. localpart_template: &quot;{{ user.preferred_username.split('@')[0] }}&quot;
  7934. display_name_template: &quot;{{ user.name }}&quot;
  7935. </code></pre>
  7936. <h3 id="apple"><a class="header" href="#apple">Apple</a></h3>
  7937. <p>Configuring &quot;Sign in with Apple&quot; (SiWA) requires an Apple Developer account.</p>
  7938. <p>You will need to create a new &quot;Services ID&quot; for SiWA, and create and download a
  7939. private key with &quot;SiWA&quot; enabled.</p>
  7940. <p>As well as the private key file, you will need:</p>
  7941. <ul>
  7942. <li>Client ID: the &quot;identifier&quot; you gave the &quot;Services ID&quot;</li>
  7943. <li>Team ID: a 10-character ID associated with your developer account.</li>
  7944. <li>Key ID: the 10-character identifier for the key.</li>
  7945. </ul>
  7946. <p><a href="https://help.apple.com/developer-account/?lang=en#/dev77c875b7e">Apple's developer documentation</a>
  7947. has more information on setting up SiWA.</p>
  7948. <p>The synapse config will look like this:</p>
  7949. <pre><code class="language-yaml"> - idp_id: apple
  7950. idp_name: Apple
  7951. issuer: &quot;https://appleid.apple.com&quot;
  7952. client_id: &quot;your-client-id&quot; # Set to the &quot;identifier&quot; for your &quot;ServicesID&quot;
  7953. client_auth_method: &quot;client_secret_post&quot;
  7954. client_secret_jwt_key:
  7955. key_file: &quot;/path/to/AuthKey_KEYIDCODE.p8&quot; # point to your key file
  7956. jwt_header:
  7957. alg: ES256
  7958. kid: &quot;KEYIDCODE&quot; # Set to the 10-char Key ID
  7959. jwt_payload:
  7960. iss: TEAMIDCODE # Set to the 10-char Team ID
  7961. scopes: [&quot;name&quot;, &quot;email&quot;, &quot;openid&quot;]
  7962. authorization_endpoint: https://appleid.apple.com/auth/authorize?response_mode=form_post
  7963. user_mapping_provider:
  7964. config:
  7965. email_template: &quot;{{ user.email }}&quot;
  7966. </code></pre>
  7967. <h3 id="auth0"><a class="header" href="#auth0">Auth0</a></h3>
  7968. <p><a href="https://auth0.com/">Auth0</a> is a hosted SaaS IdP solution.</p>
  7969. <ol>
  7970. <li>
  7971. <p>Create a regular web application for Synapse</p>
  7972. </li>
  7973. <li>
  7974. <p>Set the Allowed Callback URLs to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  7975. </li>
  7976. <li>
  7977. <p>Add a rule with any name to add the <code>preferred_username</code> claim.
  7978. (See https://auth0.com/docs/customize/rules/create-rules for more information on how to create rules.)</p>
  7979. <details>
  7980. <summary>Code sample</summary>
  7981. <pre><code class="language-js">function addPersistenceAttribute(user, context, callback) {
  7982. user.user_metadata = user.user_metadata || {};
  7983. user.user_metadata.preferred_username = user.user_metadata.preferred_username || user.user_id;
  7984. context.idToken.preferred_username = user.user_metadata.preferred_username;
  7985. auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
  7986. .then(function(){
  7987. callback(null, user, context);
  7988. })
  7989. .catch(function(err){
  7990. callback(err);
  7991. });
  7992. }
  7993. </code></pre>
  7994. </li>
  7995. </ol>
  7996. </details>
  7997. <p>Synapse config:</p>
  7998. <pre><code class="language-yaml">oidc_providers:
  7999. - idp_id: auth0
  8000. idp_name: Auth0
  8001. issuer: &quot;https://your-tier.eu.auth0.com/&quot; # TO BE FILLED
  8002. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8003. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8004. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  8005. user_mapping_provider:
  8006. config:
  8007. localpart_template: &quot;{{ user.preferred_username }}&quot;
  8008. display_name_template: &quot;{{ user.name }}&quot;
  8009. </code></pre>
  8010. <h3 id="authentik"><a class="header" href="#authentik">Authentik</a></h3>
  8011. <p><a href="https://goauthentik.io/">Authentik</a> is an open-source IdP solution.</p>
  8012. <ol>
  8013. <li>Create a provider in Authentik, with type OAuth2/OpenID.</li>
  8014. <li>The parameters are:</li>
  8015. </ol>
  8016. <ul>
  8017. <li>Client Type: Confidential</li>
  8018. <li>JWT Algorithm: RS256</li>
  8019. <li>Scopes: OpenID, Email and Profile</li>
  8020. <li>RSA Key: Select any available key</li>
  8021. <li>Redirect URIs: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8022. </ul>
  8023. <ol start="3">
  8024. <li>Create an application for synapse in Authentik and link it to the provider.</li>
  8025. <li>Note the slug of your application, Client ID and Client Secret.</li>
  8026. </ol>
  8027. <p>Note: RSA keys must be used for signing for Authentik, ECC keys do not work.</p>
  8028. <p>Synapse config:</p>
  8029. <pre><code class="language-yaml">oidc_providers:
  8030. - idp_id: authentik
  8031. idp_name: authentik
  8032. discover: true
  8033. issuer: &quot;https://your.authentik.example.org/application/o/your-app-slug/&quot; # TO BE FILLED: domain and slug
  8034. client_id: &quot;your client id&quot; # TO BE FILLED
  8035. client_secret: &quot;your client secret&quot; # TO BE FILLED
  8036. scopes:
  8037. - &quot;openid&quot;
  8038. - &quot;profile&quot;
  8039. - &quot;email&quot;
  8040. user_mapping_provider:
  8041. config:
  8042. localpart_template: &quot;{{ user.preferred_username }}&quot;
  8043. 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.
  8044. </code></pre>
  8045. <h3 id="dex"><a class="header" href="#dex">Dex</a></h3>
  8046. <p><a href="https://github.com/dexidp/dex">Dex</a> is a simple, open-source OpenID Connect Provider.
  8047. Although it is designed to help building a full-blown provider with an
  8048. external database, it can be configured with static passwords in a config file.</p>
  8049. <p>Follow the <a href="https://dexidp.io/docs/getting-started/">Getting Started guide</a>
  8050. to install Dex.</p>
  8051. <p>Edit <code>examples/config-dev.yaml</code> config file from the Dex repo to add a client:</p>
  8052. <pre><code class="language-yaml">staticClients:
  8053. - id: synapse
  8054. secret: secret
  8055. redirectURIs:
  8056. - '[synapse public baseurl]/_synapse/client/oidc/callback'
  8057. name: 'Synapse'
  8058. </code></pre>
  8059. <p>Run with <code>dex serve examples/config-dev.yaml</code>.</p>
  8060. <p>Synapse config:</p>
  8061. <pre><code class="language-yaml">oidc_providers:
  8062. - idp_id: dex
  8063. idp_name: &quot;My Dex server&quot;
  8064. skip_verification: true # This is needed as Dex is served on an insecure endpoint
  8065. issuer: &quot;http://127.0.0.1:5556/dex&quot;
  8066. client_id: &quot;synapse&quot;
  8067. client_secret: &quot;secret&quot;
  8068. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  8069. user_mapping_provider:
  8070. config:
  8071. localpart_template: &quot;{{ user.name }}&quot;
  8072. display_name_template: &quot;{{ user.name|capitalize }}&quot;
  8073. </code></pre>
  8074. <h3 id="django-oauth-toolkit"><a class="header" href="#django-oauth-toolkit">Django OAuth Toolkit</a></h3>
  8075. <p><a href="https://github.com/jazzband/django-oauth-toolkit">django-oauth-toolkit</a> is a
  8076. Django application providing out of the box all the endpoints, data and logic
  8077. needed to add OAuth2 capabilities to your Django projects. It supports
  8078. <a href="https://django-oauth-toolkit.readthedocs.io/en/latest/oidc.html">OpenID Connect too</a>.</p>
  8079. <p>Configuration on Django's side:</p>
  8080. <ol>
  8081. <li>Add an application: <code>https://example.com/admin/oauth2_provider/application/add/</code> and choose parameters like this:</li>
  8082. </ol>
  8083. <ul>
  8084. <li><code>Redirect uris</code>: <code>https://synapse.example.com/_synapse/client/oidc/callback</code></li>
  8085. <li><code>Client type</code>: <code>Confidential</code></li>
  8086. <li><code>Authorization grant type</code>: <code>Authorization code</code></li>
  8087. <li><code>Algorithm</code>: <code>HMAC with SHA-2 256</code></li>
  8088. </ul>
  8089. <ol start="2">
  8090. <li>
  8091. <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>
  8092. <details>
  8093. <summary>Code sample</summary>
  8094. <pre><code class="language-python">class CustomOAuth2Validator(OAuth2Validator):
  8095. def get_additional_claims(self, request):
  8096. return {
  8097. &quot;sub&quot;: request.user.email,
  8098. &quot;email&quot;: request.user.email,
  8099. &quot;first_name&quot;: request.user.first_name,
  8100. &quot;last_name&quot;: request.user.last_name,
  8101. }
  8102. </code></pre>
  8103. </details>
  8104. </li>
  8105. </ol>
  8106. <p>Your synapse config is then:</p>
  8107. <pre><code class="language-yaml">oidc_providers:
  8108. - idp_id: django_example
  8109. idp_name: &quot;Django Example&quot;
  8110. issuer: &quot;https://example.com/o/&quot;
  8111. client_id: &quot;your-client-id&quot; # CHANGE ME
  8112. client_secret: &quot;your-client-secret&quot; # CHANGE ME
  8113. scopes: [&quot;openid&quot;]
  8114. user_profile_method: &quot;userinfo_endpoint&quot; # needed because oauth-toolkit does not include user information in the authorization response
  8115. user_mapping_provider:
  8116. config:
  8117. localpart_template: &quot;{{ user.email.split('@')[0] }}&quot;
  8118. display_name_template: &quot;{{ user.first_name }} {{ user.last_name }}&quot;
  8119. email_template: &quot;{{ user.email }}&quot;
  8120. </code></pre>
  8121. <h3 id="facebook"><a class="header" href="#facebook">Facebook</a></h3>
  8122. <ol start="0">
  8123. <li>You will need a Facebook developer account. You can register for one
  8124. <a href="https://developers.facebook.com/async/registration/">here</a>.</li>
  8125. <li>On the <a href="https://developers.facebook.com/apps/">apps</a> page of the developer
  8126. console, &quot;Create App&quot;, and choose &quot;Build Connected Experiences&quot;.</li>
  8127. <li>Once the app is created, add &quot;Facebook Login&quot; and choose &quot;Web&quot;. You don't
  8128. need to go through the whole form here.</li>
  8129. <li>In the left-hand menu, open &quot;Products&quot;/&quot;Facebook Login&quot;/&quot;Settings&quot;.
  8130. <ul>
  8131. <li>Add <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> as an OAuth Redirect
  8132. URL.</li>
  8133. </ul>
  8134. </li>
  8135. <li>In the left-hand menu, open &quot;Settings/Basic&quot;. Here you can copy the &quot;App ID&quot;
  8136. and &quot;App Secret&quot; for use below.</li>
  8137. </ol>
  8138. <p>Synapse config:</p>
  8139. <pre><code class="language-yaml"> - idp_id: facebook
  8140. idp_name: Facebook
  8141. idp_brand: &quot;facebook&quot; # optional: styling hint for clients
  8142. discover: false
  8143. issuer: &quot;https://www.facebook.com&quot;
  8144. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8145. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8146. scopes: [&quot;openid&quot;, &quot;email&quot;]
  8147. authorization_endpoint: &quot;https://facebook.com/dialog/oauth&quot;
  8148. token_endpoint: &quot;https://graph.facebook.com/v9.0/oauth/access_token&quot;
  8149. jwks_uri: &quot;https://www.facebook.com/.well-known/oauth/openid/jwks/&quot;
  8150. user_mapping_provider:
  8151. config:
  8152. display_name_template: &quot;{{ user.name }}&quot;
  8153. email_template: &quot;{{ user.email }}&quot;
  8154. </code></pre>
  8155. <p>Relevant documents:</p>
  8156. <ul>
  8157. <li><a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow">Manually Build a Login Flow</a></li>
  8158. <li><a href="https://developers.facebook.com/docs/graph-api/using-graph-api/">Using Facebook's Graph API</a></li>
  8159. <li><a href="https://developers.facebook.com/docs/graph-api/reference/user">Reference to the User endpoint</a></li>
  8160. </ul>
  8161. <p>Facebook do have an <a href="https://www.facebook.com/.well-known/openid-configuration">OIDC discovery endpoint</a>,
  8162. but it has a <code>response_types_supported</code> which excludes &quot;code&quot; (which we rely on, and
  8163. is even mentioned in their <a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#login">documentation</a>),
  8164. so we have to disable discovery and configure the URIs manually.</p>
  8165. <h3 id="github"><a class="header" href="#github">GitHub</a></h3>
  8166. <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
  8167. just a regular OAuth2 provider.</p>
  8168. <p>The <a href="https://developer.github.com/v3/users/#get-the-authenticated-user"><code>/user</code> API endpoint</a>
  8169. can be used to retrieve information on the authenticated user. As the Synapse
  8170. login mechanism needs an attribute to uniquely identify users, and that endpoint
  8171. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  8172. <ol>
  8173. <li>Create a new OAuth application: <a href="https://github.com/settings/applications/new">https://github.com/settings/applications/new</a>.</li>
  8174. <li>Set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  8175. </ol>
  8176. <p>Synapse config:</p>
  8177. <pre><code class="language-yaml">oidc_providers:
  8178. - idp_id: github
  8179. idp_name: Github
  8180. idp_brand: &quot;github&quot; # optional: styling hint for clients
  8181. discover: false
  8182. issuer: &quot;https://github.com/&quot;
  8183. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8184. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8185. authorization_endpoint: &quot;https://github.com/login/oauth/authorize&quot;
  8186. token_endpoint: &quot;https://github.com/login/oauth/access_token&quot;
  8187. userinfo_endpoint: &quot;https://api.github.com/user&quot;
  8188. scopes: [&quot;read:user&quot;]
  8189. user_mapping_provider:
  8190. config:
  8191. subject_claim: &quot;id&quot;
  8192. localpart_template: &quot;{{ user.login }}&quot;
  8193. display_name_template: &quot;{{ user.name }}&quot;
  8194. </code></pre>
  8195. <h3 id="gitlab"><a class="header" href="#gitlab">GitLab</a></h3>
  8196. <ol>
  8197. <li>Create a <a href="https://gitlab.com/profile/applications">new application</a>.</li>
  8198. <li>Add the <code>read_user</code> and <code>openid</code> scopes.</li>
  8199. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8200. </ol>
  8201. <p>Synapse config:</p>
  8202. <pre><code class="language-yaml">oidc_providers:
  8203. - idp_id: gitlab
  8204. idp_name: Gitlab
  8205. idp_brand: &quot;gitlab&quot; # optional: styling hint for clients
  8206. issuer: &quot;https://gitlab.com/&quot;
  8207. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8208. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8209. client_auth_method: &quot;client_secret_post&quot;
  8210. scopes: [&quot;openid&quot;, &quot;read_user&quot;]
  8211. user_profile_method: &quot;userinfo_endpoint&quot;
  8212. user_mapping_provider:
  8213. config:
  8214. localpart_template: '{{ user.nickname }}'
  8215. display_name_template: '{{ user.name }}'
  8216. </code></pre>
  8217. <h3 id="gitea"><a class="header" href="#gitea">Gitea</a></h3>
  8218. <p>Gitea is, like Github, not an OpenID provider, but just an OAuth2 provider.</p>
  8219. <p>The <a href="https://try.gitea.io/api/swagger#/user/userGetCurrent"><code>/user</code> API endpoint</a>
  8220. can be used to retrieve information on the authenticated user. As the Synapse
  8221. login mechanism needs an attribute to uniquely identify users, and that endpoint
  8222. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  8223. <ol>
  8224. <li>Create a new application.</li>
  8225. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8226. </ol>
  8227. <p>Synapse config:</p>
  8228. <pre><code class="language-yaml">oidc_providers:
  8229. - idp_id: gitea
  8230. idp_name: Gitea
  8231. discover: false
  8232. issuer: &quot;https://your-gitea.com/&quot;
  8233. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8234. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8235. client_auth_method: client_secret_post
  8236. scopes: [] # Gitea doesn't support Scopes
  8237. authorization_endpoint: &quot;https://your-gitea.com/login/oauth/authorize&quot;
  8238. token_endpoint: &quot;https://your-gitea.com/login/oauth/access_token&quot;
  8239. userinfo_endpoint: &quot;https://your-gitea.com/api/v1/user&quot;
  8240. user_mapping_provider:
  8241. config:
  8242. subject_claim: &quot;id&quot;
  8243. localpart_template: &quot;{{ user.login }}&quot;
  8244. display_name_template: &quot;{{ user.full_name }}&quot;
  8245. </code></pre>
  8246. <h3 id="google"><a class="header" href="#google">Google</a></h3>
  8247. <p><a href="https://developers.google.com/identity/protocols/oauth2/openid-connect">Google</a> is an OpenID certified authentication and authorisation provider.</p>
  8248. <ol>
  8249. <li>Set up a project in the Google API Console (see
  8250. <a href="https://developers.google.com/identity/protocols/oauth2/openid-connect#appsetup">documentation</a>).</li>
  8251. <li>Add an &quot;OAuth Client ID&quot; for a Web Application under &quot;Credentials&quot;.</li>
  8252. <li>Copy the Client ID and Client Secret, and add the following to your synapse config:
  8253. <pre><code class="language-yaml">oidc_providers:
  8254. - idp_id: google
  8255. idp_name: Google
  8256. idp_brand: &quot;google&quot; # optional: styling hint for clients
  8257. issuer: &quot;https://accounts.google.com/&quot;
  8258. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8259. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8260. scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;] # email is optional, read below
  8261. user_mapping_provider:
  8262. config:
  8263. localpart_template: &quot;{{ user.given_name|lower }}&quot;
  8264. display_name_template: &quot;{{ user.name }}&quot;
  8265. email_template: &quot;{{ user.email }}&quot; # needs &quot;email&quot; in scopes above
  8266. </code></pre>
  8267. </li>
  8268. <li>Back in the Google console, add this Authorized redirect URI: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  8269. </ol>
  8270. <h3 id="keycloak"><a class="header" href="#keycloak">Keycloak</a></h3>
  8271. <p><a href="https://www.keycloak.org/docs/latest/server_admin/#sso-protocols">Keycloak</a> is an opensource IdP maintained by Red Hat.</p>
  8272. <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.
  8273. 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>
  8274. <p>Follow the <a href="https://www.keycloak.org/guides">Getting Started Guide</a> to install Keycloak and set up a realm.</p>
  8275. <ol>
  8276. <li>
  8277. <p>Click <code>Clients</code> in the sidebar and click <code>Create</code></p>
  8278. </li>
  8279. <li>
  8280. <p>Fill in the fields as below:</p>
  8281. </li>
  8282. </ol>
  8283. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  8284. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  8285. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  8286. </tbody></table>
  8287. <ol start="3">
  8288. <li>Click <code>Save</code></li>
  8289. <li>Fill in the fields as below:</li>
  8290. </ol>
  8291. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  8292. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  8293. <tr><td>Enabled</td><td><code>On</code></td></tr>
  8294. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  8295. <tr><td>Access Type</td><td><code>confidential</code></td></tr>
  8296. <tr><td>Valid Redirect URIs</td><td><code>[synapse public baseurl]/_synapse/client/oidc/callback</code></td></tr>
  8297. <tr><td>Backchannel Logout URL (optional)</td><td> <code>[synapse public baseurl]/_synapse/client/oidc/backchannel_logout</code></td></tr>
  8298. <tr><td>Backchannel Logout Session Required (optional)</td><td> <code>On</code></td></tr>
  8299. </tbody></table>
  8300. <ol start="5">
  8301. <li>Click <code>Save</code></li>
  8302. <li>On the Credentials tab, update the fields:</li>
  8303. </ol>
  8304. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  8305. <tr><td>Client Authenticator</td><td><code>Client ID and Secret</code></td></tr>
  8306. </tbody></table>
  8307. <ol start="7">
  8308. <li>Click <code>Regenerate Secret</code></li>
  8309. <li>Copy Secret</li>
  8310. </ol>
  8311. <pre><code class="language-yaml">oidc_providers:
  8312. - idp_id: keycloak
  8313. idp_name: &quot;My KeyCloak server&quot;
  8314. issuer: &quot;https://127.0.0.1:8443/realms/{realm_name}&quot;
  8315. client_id: &quot;synapse&quot;
  8316. client_secret: &quot;copy secret generated from above&quot;
  8317. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  8318. user_mapping_provider:
  8319. config:
  8320. localpart_template: &quot;{{ user.preferred_username }}&quot;
  8321. display_name_template: &quot;{{ user.name }}&quot;
  8322. backchannel_logout_enabled: true # Optional
  8323. </code></pre>
  8324. <h3 id="lemonldap"><a class="header" href="#lemonldap">LemonLDAP</a></h3>
  8325. <p><a href="https://lemonldap-ng.org/">LemonLDAP::NG</a> is an open-source IdP solution.</p>
  8326. <ol>
  8327. <li>Create an OpenID Connect Relying Parties in LemonLDAP::NG</li>
  8328. <li>The parameters are:</li>
  8329. </ol>
  8330. <ul>
  8331. <li>Client ID under the basic menu of the new Relying Parties (<code>Options &gt; Basic &gt; Client ID</code>)</li>
  8332. <li>Client secret (<code>Options &gt; Basic &gt; Client secret</code>)</li>
  8333. <li>JWT Algorithm: RS256 within the security menu of the new Relying Parties
  8334. (<code>Options &gt; Security &gt; ID Token signature algorithm</code> and <code>Options &gt; Security &gt; Access Token signature algorithm</code>)</li>
  8335. <li>Scopes: OpenID, Email and Profile</li>
  8336. <li>Allowed redirection addresses for login (<code>Options &gt; Basic &gt; Allowed redirection addresses for login</code> ) :
  8337. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8338. </ul>
  8339. <p>Synapse config:</p>
  8340. <pre><code class="language-yaml">oidc_providers:
  8341. - idp_id: lemonldap
  8342. idp_name: lemonldap
  8343. discover: true
  8344. issuer: &quot;https://auth.example.org/&quot; # TO BE FILLED: replace with your domain
  8345. client_id: &quot;your client id&quot; # TO BE FILLED
  8346. client_secret: &quot;your client secret&quot; # TO BE FILLED
  8347. scopes:
  8348. - &quot;openid&quot;
  8349. - &quot;profile&quot;
  8350. - &quot;email&quot;
  8351. user_mapping_provider:
  8352. config:
  8353. localpart_template: &quot;{{ user.preferred_username }}}&quot;
  8354. # 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.
  8355. display_name_template: &quot;{{ user.preferred_username|capitalize }}&quot;
  8356. </code></pre>
  8357. <h3 id="mastodon"><a class="header" href="#mastodon">Mastodon</a></h3>
  8358. <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>
  8359. <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>
  8360. <p>This example assumes that:</p>
  8361. <ul>
  8362. <li>the Mastodon instance website URL is <code>https://your.mastodon.instance.url</code>, and</li>
  8363. <li>Synapse will be registered as an app named <code>my_synapse_app</code>.</li>
  8364. </ul>
  8365. <p>Send the following request, substituting the value of <code>synapse_public_baseurl</code> from your Synapse installation.</p>
  8366. <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
  8367. </code></pre>
  8368. <p>You should receive a response similar to the following. Make sure to save it.</p>
  8369. <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;}
  8370. </code></pre>
  8371. <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>
  8372. <pre><code class="language-yaml">oidc_providers:
  8373. - idp_id: my_mastodon
  8374. idp_name: &quot;Mastodon Instance Example&quot;
  8375. discover: false
  8376. issuer: &quot;https://your.mastodon.instance.url/@admin&quot;
  8377. client_id: &quot;someclientid_123&quot;
  8378. client_secret: &quot;someclientsecret_123&quot;
  8379. authorization_endpoint: &quot;https://your.mastodon.instance.url/oauth/authorize&quot;
  8380. token_endpoint: &quot;https://your.mastodon.instance.url/oauth/token&quot;
  8381. userinfo_endpoint: &quot;https://your.mastodon.instance.url/api/v1/accounts/verify_credentials&quot;
  8382. scopes: [&quot;read&quot;]
  8383. user_mapping_provider:
  8384. config:
  8385. subject_template: &quot;{{ user.id }}&quot;
  8386. localpart_template: &quot;{{ user.username }}&quot;
  8387. display_name_template: &quot;{{ user.display_name }}&quot;
  8388. </code></pre>
  8389. <p>Note that the fields <code>client_id</code> and <code>client_secret</code> are taken from the CURL response above.</p>
  8390. <h3 id="shibboleth-with-oidc-plugin"><a class="header" href="#shibboleth-with-oidc-plugin">Shibboleth with OIDC Plugin</a></h3>
  8391. <p><a href="https://www.shibboleth.net/">Shibboleth</a> is an open Standard IdP solution widely used by Universities.</p>
  8392. <ol>
  8393. <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>
  8394. <li>Create a new config on the IdP Side, ensure that the <code>client_id</code> and <code>client_secret</code>
  8395. are randomly generated data.</li>
  8396. </ol>
  8397. <pre><code class="language-json">{
  8398. &quot;client_id&quot;: &quot;SOME-CLIENT-ID&quot;,
  8399. &quot;client_secret&quot;: &quot;SOME-SUPER-SECRET-SECRET&quot;,
  8400. &quot;response_types&quot;: [&quot;code&quot;],
  8401. &quot;grant_types&quot;: [&quot;authorization_code&quot;],
  8402. &quot;scope&quot;: &quot;openid profile email&quot;,
  8403. &quot;redirect_uris&quot;: [&quot;https://[synapse public baseurl]/_synapse/client/oidc/callback&quot;]
  8404. }
  8405. </code></pre>
  8406. <p>Synapse config:</p>
  8407. <pre><code class="language-yaml">oidc_providers:
  8408. # Shibboleth IDP
  8409. #
  8410. - idp_id: shibboleth
  8411. idp_name: &quot;Shibboleth Login&quot;
  8412. discover: true
  8413. issuer: &quot;https://YOUR-IDP-URL.TLD&quot;
  8414. client_id: &quot;YOUR_CLIENT_ID&quot;
  8415. client_secret: &quot;YOUR-CLIENT-SECRECT-FROM-YOUR-IDP&quot;
  8416. scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;]
  8417. allow_existing_users: true
  8418. user_profile_method: &quot;userinfo_endpoint&quot;
  8419. user_mapping_provider:
  8420. config:
  8421. subject_claim: &quot;sub&quot;
  8422. localpart_template: &quot;{{ user.sub.split('@')[0] }}&quot;
  8423. display_name_template: &quot;{{ user.name }}&quot;
  8424. email_template: &quot;{{ user.email }}&quot;
  8425. </code></pre>
  8426. <h3 id="twitch"><a class="header" href="#twitch">Twitch</a></h3>
  8427. <ol>
  8428. <li>Setup a developer account on <a href="https://dev.twitch.tv/">Twitch</a></li>
  8429. <li>Obtain the OAuth 2.0 credentials by <a href="https://dev.twitch.tv/console/apps/">creating an app</a></li>
  8430. <li>Add this OAuth Redirect URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  8431. </ol>
  8432. <p>Synapse config:</p>
  8433. <pre><code class="language-yaml">oidc_providers:
  8434. - idp_id: twitch
  8435. idp_name: Twitch
  8436. issuer: &quot;https://id.twitch.tv/oauth2/&quot;
  8437. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8438. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8439. client_auth_method: &quot;client_secret_post&quot;
  8440. user_mapping_provider:
  8441. config:
  8442. localpart_template: &quot;{{ user.preferred_username }}&quot;
  8443. display_name_template: &quot;{{ user.name }}&quot;
  8444. </code></pre>
  8445. <h3 id="twitter"><a class="header" href="#twitter">Twitter</a></h3>
  8446. <p><em>Using Twitter as an identity provider requires using Synapse 1.75.0 or later.</em></p>
  8447. <ol>
  8448. <li>Setup a developer account on <a href="https://developer.twitter.com/en/portal/dashboard">Twitter</a></li>
  8449. <li>Create a project &amp; app.</li>
  8450. <li>Enable user authentication and under &quot;Type of App&quot; choose &quot;Web App, Automated App or Bot&quot;.</li>
  8451. <li>Under &quot;App info&quot; set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  8452. <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>
  8453. </ol>
  8454. <p>Synapse config:</p>
  8455. <pre><code class="language-yaml">oidc_providers:
  8456. - idp_id: twitter
  8457. idp_name: Twitter
  8458. idp_brand: &quot;twitter&quot; # optional: styling hint for clients
  8459. discover: false # Twitter is not OpenID compliant.
  8460. issuer: &quot;https://twitter.com/&quot;
  8461. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8462. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  8463. pkce_method: &quot;always&quot;
  8464. # offline.access providers refresh tokens, tweet.read and users.read needed for userinfo request.
  8465. scopes: [&quot;offline.access&quot;, &quot;tweet.read&quot;, &quot;users.read&quot;]
  8466. authorization_endpoint: https://twitter.com/i/oauth2/authorize
  8467. token_endpoint: https://api.twitter.com/2/oauth2/token
  8468. userinfo_endpoint: https://api.twitter.com/2/users/me?user.fields=profile_image_url
  8469. user_mapping_provider:
  8470. config:
  8471. subject_template: &quot;{{ user.data.id }}&quot;
  8472. localpart_template: &quot;{{ user.data.username }}&quot;
  8473. display_name_template: &quot;{{ user.data.name }}&quot;
  8474. picture_template: &quot;{{ user.data.profile_image_url }}&quot;
  8475. </code></pre>
  8476. <h3 id="xwiki"><a class="header" href="#xwiki">XWiki</a></h3>
  8477. <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>
  8478. <p>Synapse config:</p>
  8479. <pre><code class="language-yaml">oidc_providers:
  8480. - idp_id: xwiki
  8481. idp_name: &quot;XWiki&quot;
  8482. issuer: &quot;https://myxwikihost/xwiki/oidc/&quot;
  8483. client_id: &quot;your-client-id&quot; # TO BE FILLED
  8484. client_auth_method: none
  8485. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  8486. user_profile_method: &quot;userinfo_endpoint&quot;
  8487. user_mapping_provider:
  8488. config:
  8489. localpart_template: &quot;{{ user.preferred_username }}&quot;
  8490. display_name_template: &quot;{{ user.name }}&quot;
  8491. </code></pre>
  8492. <div style="break-before: page; page-break-before: always;"></div><h1 id="saml"><a class="header" href="#saml">SAML</a></h1>
  8493. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language">Security Assertion
  8494. Markup Language</a>
  8495. (SAML) protocol natively.</p>
  8496. <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
  8497. file</a> for more details.</p>
  8498. <div style="break-before: page; page-break-before: always;"></div><h1 id="cas"><a class="header" href="#cas">CAS</a></h1>
  8499. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Central_Authentication_Service">Central Authentication
  8500. Service protocol</a>
  8501. (CAS) natively.</p>
  8502. <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>
  8503. sections of the configuration manual for more details.</p>
  8504. <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>
  8505. <p>A mapping provider is a Python class (loaded via a Python module) that
  8506. works out how to map attributes of a SSO response to Matrix-specific
  8507. user attributes. Details such as user ID localpart, displayname, and even avatar
  8508. URLs are all things that can be mapped from talking to a SSO service.</p>
  8509. <p>As an example, a SSO service may return the email address
  8510. &quot;john.smith@example.com&quot; for a user, whereas Synapse will need to figure out how
  8511. to turn that into a displayname when creating a Matrix user for this individual.
  8512. It may choose <code>John Smith</code>, or <code>Smith, John [Example.com]</code> or any number of
  8513. variations. As each Synapse configuration may want something different, this is
  8514. where SAML mapping providers come into play.</p>
  8515. <p>SSO mapping providers are currently supported for OpenID and SAML SSO
  8516. configurations. Please see the details below for how to implement your own.</p>
  8517. <p>It is up to the mapping provider whether the user should be assigned a predefined
  8518. Matrix ID based on the SSO attributes, or if the user should be allowed to
  8519. choose their own username.</p>
  8520. <p>In the first case - where users are automatically allocated a Matrix ID - it is
  8521. the responsibility of the mapping provider to normalise the SSO attributes and
  8522. map them to a valid Matrix ID. The <a href="https://spec.matrix.org/latest/appendices/#user-identifiers">specification for Matrix
  8523. IDs</a> has some
  8524. information about what is considered valid.</p>
  8525. <p>If the mapping provider does not assign a Matrix ID, then Synapse will
  8526. automatically serve an HTML page allowing the user to pick their own username.</p>
  8527. <p>External mapping providers are provided to Synapse in the form of an external
  8528. Python module. You can retrieve this module from <a href="https://pypi.org">PyPI</a> or elsewhere,
  8529. but it must be importable via Synapse (e.g. it must be in the same virtualenv
  8530. as Synapse). The Synapse config is then modified to point to the mapping provider
  8531. (and optionally provide additional configuration for it).</p>
  8532. <h2 id="openid-mapping-providers"><a class="header" href="#openid-mapping-providers">OpenID Mapping Providers</a></h2>
  8533. <p>The OpenID mapping provider can be customized by editing the
  8534. <a href="usage/configuration/config_documentation.html#oidc_providers"><code>oidc_providers.user_mapping_provider.module</code></a>
  8535. config option.</p>
  8536. <p><code>oidc_providers.user_mapping_provider.config</code> allows you to provide custom
  8537. configuration options to the module. Check with the module's documentation for
  8538. what options it provides (if any). The options listed by default are for the
  8539. user mapping provider built in to Synapse. If using a custom module, you should
  8540. comment these options out and use those specified by the module instead.</p>
  8541. <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>
  8542. <p>A custom mapping provider must specify the following methods:</p>
  8543. <ul>
  8544. <li><code>def __init__(self, parsed_config)</code>
  8545. <ul>
  8546. <li>Arguments:
  8547. <ul>
  8548. <li><code>parsed_config</code> - A configuration object that is the return value of the
  8549. <code>parse_config</code> method. You should set any configuration options needed by
  8550. the module here.</li>
  8551. </ul>
  8552. </li>
  8553. </ul>
  8554. </li>
  8555. <li><code>def parse_config(config)</code>
  8556. <ul>
  8557. <li>This method should have the <code>@staticmethod</code> decoration.</li>
  8558. <li>Arguments:
  8559. <ul>
  8560. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  8561. <code>oidc_providers.user_mapping_provider.config</code> homeserver config option.
  8562. Runs on homeserver startup. Providers should extract and validate
  8563. any option values they need here.</li>
  8564. </ul>
  8565. </li>
  8566. <li>Whatever is returned will be passed back to the user mapping provider module's
  8567. <code>__init__</code> method during construction.</li>
  8568. </ul>
  8569. </li>
  8570. <li><code>def get_remote_user_id(self, userinfo)</code>
  8571. <ul>
  8572. <li>Arguments:
  8573. <ul>
  8574. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  8575. information from.</li>
  8576. </ul>
  8577. </li>
  8578. <li>This method must return a string, which is the unique, immutable identifier
  8579. for the user. Commonly the <code>sub</code> claim of the response.</li>
  8580. </ul>
  8581. </li>
  8582. <li><code>async def map_user_attributes(self, userinfo, token, failures)</code>
  8583. <ul>
  8584. <li>This method must be async.</li>
  8585. <li>Arguments:
  8586. <ul>
  8587. <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>
  8588. object to extract user information from.</li>
  8589. <li><code>token</code> - A dictionary which includes information necessary to make
  8590. further requests to the OpenID provider.</li>
  8591. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  8592. mxid localpart mapping has failed. This should be used
  8593. to create a deduplicated mxid localpart which should be
  8594. returned instead. For example, if this method returns
  8595. <code>john.doe</code> as the value of <code>localpart</code> in the returned
  8596. dict, and that is already taken on the homeserver, this
  8597. method will be called again with the same parameters but
  8598. with failures=1. The method should then return a different
  8599. <code>localpart</code> value, such as <code>john.doe1</code>.</li>
  8600. </ul>
  8601. </li>
  8602. <li>Returns a dictionary with two keys:
  8603. <ul>
  8604. <li><code>localpart</code>: A string, used to generate the Matrix ID. If this is
  8605. <code>None</code>, the user is prompted to pick their own username. This is only used
  8606. during a user's first login. Once a localpart has been associated with a
  8607. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  8608. <li><code>confirm_localpart</code>: A boolean. If set to <code>True</code>, when a <code>localpart</code>
  8609. string is returned from this method, Synapse will prompt the user to
  8610. either accept this localpart or pick their own username. Otherwise this
  8611. option has no effect. If omitted, defaults to <code>False</code>.</li>
  8612. <li><code>display_name</code>: An optional string, the display name for the user.</li>
  8613. <li><code>emails</code>: A list of strings, the email address(es) to associate with
  8614. this user. If omitted, defaults to an empty list.</li>
  8615. </ul>
  8616. </li>
  8617. </ul>
  8618. </li>
  8619. <li><code>async def get_extra_attributes(self, userinfo, token)</code>
  8620. <ul>
  8621. <li>
  8622. <p>This method must be async.</p>
  8623. </li>
  8624. <li>
  8625. <p>Arguments:</p>
  8626. <ul>
  8627. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  8628. information from.</li>
  8629. <li><code>token</code> - A dictionary which includes information necessary to make
  8630. further requests to the OpenID provider.</li>
  8631. </ul>
  8632. </li>
  8633. <li>
  8634. <p>Returns a dictionary that is suitable to be serialized to JSON. This
  8635. will be returned as part of the response during a successful login.</p>
  8636. <p>Note that care should be taken to not overwrite any of the parameters
  8637. usually returned as part of the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3login">login response</a>.</p>
  8638. </li>
  8639. </ul>
  8640. </li>
  8641. </ul>
  8642. <h3 id="default-openid-mapping-provider"><a class="header" href="#default-openid-mapping-provider">Default OpenID Mapping Provider</a></h3>
  8643. <p>Synapse has a built-in OpenID mapping provider if a custom provider isn't
  8644. specified in the config. It is located at
  8645. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/oidc.py"><code>synapse.handlers.oidc.JinjaOidcMappingProvider</code></a>.</p>
  8646. <h2 id="saml-mapping-providers"><a class="header" href="#saml-mapping-providers">SAML Mapping Providers</a></h2>
  8647. <p>The SAML mapping provider can be customized by editing the
  8648. <a href="usage/configuration/config_documentation.html#saml2_config"><code>saml2_config.user_mapping_provider.module</code></a>
  8649. config option.</p>
  8650. <p><code>saml2_config.user_mapping_provider.config</code> allows you to provide custom
  8651. configuration options to the module. Check with the module's documentation for
  8652. what options it provides (if any). The options listed by default are for the
  8653. user mapping provider built in to Synapse. If using a custom module, you should
  8654. comment these options out and use those specified by the module instead.</p>
  8655. <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>
  8656. <p>A custom mapping provider must specify the following methods:</p>
  8657. <ul>
  8658. <li><code>def __init__(self, parsed_config, module_api)</code>
  8659. <ul>
  8660. <li>Arguments:
  8661. <ul>
  8662. <li><code>parsed_config</code> - A configuration object that is the return value of the
  8663. <code>parse_config</code> method. You should set any configuration options needed by
  8664. the module here.</li>
  8665. <li><code>module_api</code> - a <code>synapse.module_api.ModuleApi</code> object which provides the
  8666. stable API available for extension modules.</li>
  8667. </ul>
  8668. </li>
  8669. </ul>
  8670. </li>
  8671. <li><code>def parse_config(config)</code>
  8672. <ul>
  8673. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  8674. <li>Arguments:
  8675. <ul>
  8676. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  8677. <code>saml_config.user_mapping_provider.config</code> homeserver config option.
  8678. Runs on homeserver startup. Providers should extract and validate
  8679. any option values they need here.</li>
  8680. </ul>
  8681. </li>
  8682. <li>Whatever is returned will be passed back to the user mapping provider module's
  8683. <code>__init__</code> method during construction.</li>
  8684. </ul>
  8685. </li>
  8686. <li><code>def get_saml_attributes(config)</code>
  8687. <ul>
  8688. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  8689. <li>Arguments:
  8690. <ul>
  8691. <li><code>config</code> - A object resulting from a call to <code>parse_config</code>.</li>
  8692. </ul>
  8693. </li>
  8694. <li>Returns a tuple of two sets. The first set equates to the SAML auth
  8695. response attributes that are required for the module to function, whereas
  8696. the second set consists of those attributes which can be used if available,
  8697. but are not necessary.</li>
  8698. </ul>
  8699. </li>
  8700. <li><code>def get_remote_user_id(self, saml_response, client_redirect_url)</code>
  8701. <ul>
  8702. <li>Arguments:
  8703. <ul>
  8704. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  8705. information from.</li>
  8706. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  8707. redirected to.</li>
  8708. </ul>
  8709. </li>
  8710. <li>This method must return a string, which is the unique, immutable identifier
  8711. for the user. Commonly the <code>uid</code> claim of the response.</li>
  8712. </ul>
  8713. </li>
  8714. <li><code>def saml_response_to_user_attributes(self, saml_response, failures, client_redirect_url)</code>
  8715. <ul>
  8716. <li>
  8717. <p>Arguments:</p>
  8718. <ul>
  8719. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  8720. information from.</li>
  8721. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  8722. mxid localpart mapping has failed. This should be used
  8723. to create a deduplicated mxid localpart which should be
  8724. returned instead. For example, if this method returns
  8725. <code>john.doe</code> as the value of <code>mxid_localpart</code> in the returned
  8726. dict, and that is already taken on the homeserver, this
  8727. method will be called again with the same parameters but
  8728. with failures=1. The method should then return a different
  8729. <code>mxid_localpart</code> value, such as <code>john.doe1</code>.</li>
  8730. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  8731. redirected to.</li>
  8732. </ul>
  8733. </li>
  8734. <li>
  8735. <p>This method must return a dictionary, which will then be used by Synapse
  8736. to build a new user. The following keys are allowed:</p>
  8737. <ul>
  8738. <li><code>mxid_localpart</code> - A string, the mxid localpart of the new user. If this is
  8739. <code>None</code>, the user is prompted to pick their own username. This is only used
  8740. during a user's first login. Once a localpart has been associated with a
  8741. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  8742. <li><code>displayname</code> - The displayname of the new user. If not provided, will default to
  8743. the value of <code>mxid_localpart</code>.</li>
  8744. <li><code>emails</code> - A list of emails for the new user. If not provided, will
  8745. default to an empty list.</li>
  8746. </ul>
  8747. <p>Alternatively it can raise a <code>synapse.api.errors.RedirectException</code> to
  8748. redirect the user to another page. This is useful to prompt the user for
  8749. additional information, e.g. if you want them to provide their own username.
  8750. It is the responsibility of the mapping provider to either redirect back
  8751. to <code>client_redirect_url</code> (including any additional information) or to
  8752. complete registration using methods from the <code>ModuleApi</code>.</p>
  8753. </li>
  8754. </ul>
  8755. </li>
  8756. </ul>
  8757. <h3 id="default-saml-mapping-provider"><a class="header" href="#default-saml-mapping-provider">Default SAML Mapping Provider</a></h3>
  8758. <p>Synapse has a built-in SAML mapping provider if a custom provider isn't
  8759. specified in the config. It is located at
  8760. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/saml.py"><code>synapse.handlers.saml.DefaultSamlMappingProvider</code></a>.</p>
  8761. <div style="break-before: page; page-break-before: always;"></div><h2 style="color:red">
  8762. This page of the Synapse documentation is now deprecated. For up to date
  8763. documentation on setting up or writing a password auth provider module, please see
  8764. <a href="modules/index.html">this page</a>.
  8765. </h2>
  8766. <h1 id="password-auth-provider-modules"><a class="header" href="#password-auth-provider-modules">Password auth provider modules</a></h1>
  8767. <p>Password auth providers offer a way for server administrators to
  8768. integrate their Synapse installation with an existing authentication
  8769. system.</p>
  8770. <p>A password auth provider is a Python class which is dynamically loaded
  8771. into Synapse, and provides a number of methods by which it can integrate
  8772. with the authentication system.</p>
  8773. <p>This document serves as a reference for those looking to implement their
  8774. own password auth providers. Additionally, here is a list of known
  8775. password auth provider module implementations:</p>
  8776. <ul>
  8777. <li><a href="https://github.com/matrix-org/matrix-synapse-ldap3/">matrix-synapse-ldap3</a></li>
  8778. <li><a href="https://github.com/devture/matrix-synapse-shared-secret-auth">matrix-synapse-shared-secret-auth</a></li>
  8779. <li><a href="https://github.com/ma1uta/matrix-synapse-rest-password-provider">matrix-synapse-rest-password-provider</a></li>
  8780. </ul>
  8781. <h2 id="required-methods"><a class="header" href="#required-methods">Required methods</a></h2>
  8782. <p>Password auth provider classes must provide the following methods:</p>
  8783. <ul>
  8784. <li>
  8785. <p><code>parse_config(config)</code>
  8786. This method is passed the <code>config</code> object for this module from the
  8787. homeserver configuration file.</p>
  8788. <p>It should perform any appropriate sanity checks on the provided
  8789. configuration, and return an object which is then passed into
  8790. <code>__init__</code>.</p>
  8791. <p>This method should have the <code>@staticmethod</code> decoration.</p>
  8792. </li>
  8793. <li>
  8794. <p><code>__init__(self, config, account_handler)</code></p>
  8795. <p>The constructor is passed the config object returned by
  8796. <code>parse_config</code>, and a <code>synapse.module_api.ModuleApi</code> object which
  8797. allows the password provider to check if accounts exist and/or create
  8798. new ones.</p>
  8799. </li>
  8800. </ul>
  8801. <h2 id="optional-methods"><a class="header" href="#optional-methods">Optional methods</a></h2>
  8802. <p>Password auth provider classes may optionally provide the following methods:</p>
  8803. <ul>
  8804. <li>
  8805. <p><code>get_db_schema_files(self)</code></p>
  8806. <p>This method, if implemented, should return an Iterable of
  8807. <code>(name, stream)</code> pairs of database schema files. Each file is applied
  8808. in turn at initialisation, and a record is then made in the database
  8809. so that it is not re-applied on the next start.</p>
  8810. </li>
  8811. <li>
  8812. <p><code>get_supported_login_types(self)</code></p>
  8813. <p>This method, if implemented, should return a <code>dict</code> mapping from a
  8814. login type identifier (such as <code>m.login.password</code>) to an iterable
  8815. giving the fields which must be provided by the user in the submission
  8816. to <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-login">the <code>/login</code> API</a>.
  8817. These fields are passed in the <code>login_dict</code> dictionary to <code>check_auth</code>.</p>
  8818. <p>For example, if a password auth provider wants to implement a custom
  8819. login type of <code>com.example.custom_login</code>, where the client is expected
  8820. to pass the fields <code>secret1</code> and <code>secret2</code>, the provider should
  8821. implement this method and return the following dict:</p>
  8822. <pre><code class="language-python">{&quot;com.example.custom_login&quot;: (&quot;secret1&quot;, &quot;secret2&quot;)}
  8823. </code></pre>
  8824. </li>
  8825. <li>
  8826. <p><code>check_auth(self, username, login_type, login_dict)</code></p>
  8827. <p>This method does the real work. If implemented, it
  8828. will be called for each login attempt where the login type matches one
  8829. of the keys returned by <code>get_supported_login_types</code>.</p>
  8830. <p>It is passed the (possibly unqualified) <code>user</code> field provided by the client,
  8831. the login type, and a dictionary of login secrets passed by the
  8832. client.</p>
  8833. <p>The method should return an <code>Awaitable</code> object, which resolves
  8834. to the canonical <code>@localpart:domain</code> user ID if authentication is
  8835. successful, and <code>None</code> if not.</p>
  8836. <p>Alternatively, the <code>Awaitable</code> can resolve to a <code>(str, func)</code> tuple, in
  8837. which case the second field is a callback which will be called with
  8838. the result from the <code>/login</code> call (including <code>access_token</code>,
  8839. <code>device_id</code>, etc.)</p>
  8840. </li>
  8841. <li>
  8842. <p><code>check_3pid_auth(self, medium, address, password)</code></p>
  8843. <p>This method, if implemented, is called when a user attempts to
  8844. register or log in with a third party identifier, such as email. It is
  8845. passed the medium (ex. &quot;email&quot;), an address (ex.
  8846. &quot;<a href="mailto:jdoe@example.com">jdoe@example.com</a>&quot;) and the user's password.</p>
  8847. <p>The method should return an <code>Awaitable</code> object, which resolves
  8848. to a <code>str</code> containing the user's (canonical) User id if
  8849. authentication was successful, and <code>None</code> if not.</p>
  8850. <p>As with <code>check_auth</code>, the <code>Awaitable</code> may alternatively resolve to a
  8851. <code>(user_id, callback)</code> tuple.</p>
  8852. </li>
  8853. <li>
  8854. <p><code>check_password(self, user_id, password)</code></p>
  8855. <p>This method provides a simpler interface than
  8856. <code>get_supported_login_types</code> and <code>check_auth</code> for password auth
  8857. providers that just want to provide a mechanism for validating
  8858. <code>m.login.password</code> logins.</p>
  8859. <p>If implemented, it will be called to check logins with an
  8860. <code>m.login.password</code> login type. It is passed a qualified
  8861. <code>@localpart:domain</code> user id, and the password provided by the user.</p>
  8862. <p>The method should return an <code>Awaitable</code> object, which resolves
  8863. to <code>True</code> if authentication is successful, and <code>False</code> if not.</p>
  8864. </li>
  8865. <li>
  8866. <p><code>on_logged_out(self, user_id, device_id, access_token)</code></p>
  8867. <p>This method, if implemented, is called when a user logs out. It is
  8868. passed the qualified user ID, the ID of the deactivated device (if
  8869. any: access tokens are occasionally created without an associated
  8870. device ID), and the (now deactivated) access token.</p>
  8871. <p>It may return an <code>Awaitable</code> object; the logout request will
  8872. wait for the <code>Awaitable</code> to complete, but the result is ignored.</p>
  8873. </li>
  8874. </ul>
  8875. <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>
  8876. <p>Synapse comes with a non-standard login type to support
  8877. <a href="https://en.wikipedia.org/wiki/JSON_Web_Token">JSON Web Tokens</a>. In general the
  8878. documentation for
  8879. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#login">the login endpoint</a>
  8880. is still valid (and the mechanism works similarly to the
  8881. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#token-based">token based login</a>).</p>
  8882. <p>To log in using a JSON Web Token, clients should submit a <code>/login</code> request as
  8883. follows:</p>
  8884. <pre><code class="language-json">{
  8885. &quot;type&quot;: &quot;org.matrix.login.jwt&quot;,
  8886. &quot;token&quot;: &quot;&lt;jwt&gt;&quot;
  8887. }
  8888. </code></pre>
  8889. <p>The <code>token</code> field should include the JSON web token with the following claims:</p>
  8890. <ul>
  8891. <li>A claim that encodes the local part of the user ID is required. By default,
  8892. the <code>sub</code> (subject) claim is used, or a custom claim can be set in the
  8893. configuration file.</li>
  8894. <li>The expiration time (<code>exp</code>), not before time (<code>nbf</code>), and issued at (<code>iat</code>)
  8895. claims are optional, but validated if present.</li>
  8896. <li>The issuer (<code>iss</code>) claim is optional, but required and validated if configured.</li>
  8897. <li>The audience (<code>aud</code>) claim is optional, but required and validated if configured.
  8898. Providing the audience claim when not configured will cause validation to fail.</li>
  8899. </ul>
  8900. <p>In the case that the token is not valid, the homeserver must respond with
  8901. <code>403 Forbidden</code> and an error code of <code>M_FORBIDDEN</code>.</p>
  8902. <p>As with other login types, there are additional fields (e.g. <code>device_id</code> and
  8903. <code>initial_device_display_name</code>) which can be included in the above request.</p>
  8904. <h2 id="preparing-synapse-1"><a class="header" href="#preparing-synapse-1">Preparing Synapse</a></h2>
  8905. <p>The JSON Web Token integration in Synapse uses the
  8906. <a href="https://docs.authlib.org/en/latest/index.html"><code>Authlib</code></a> library, which must be installed
  8907. as follows:</p>
  8908. <ul>
  8909. <li>
  8910. <p>The relevant libraries are included in the Docker images and Debian packages
  8911. provided by <code>matrix.org</code> so no further action is needed.</p>
  8912. </li>
  8913. <li>
  8914. <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>
  8915. </li>
  8916. <li>
  8917. <p>For other installation mechanisms, see the documentation provided by the
  8918. maintainer.</p>
  8919. </li>
  8920. </ul>
  8921. <p>To enable the JSON web token integration, you should then add a <code>jwt_config</code> option
  8922. to your configuration file. See the <a href="usage/configuration/config_documentation.html#jwt_config">configuration manual</a> for some
  8923. sample settings.</p>
  8924. <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>
  8925. <p>Although JSON Web Tokens are typically generated from an external server, the
  8926. example below uses a locally generated JWT.</p>
  8927. <ol>
  8928. <li>
  8929. <p>Configure Synapse with JWT logins, note that this example uses a pre-shared
  8930. secret and an algorithm of HS256:</p>
  8931. <pre><code class="language-yaml">jwt_config:
  8932. enabled: true
  8933. secret: &quot;my-secret-token&quot;
  8934. algorithm: &quot;HS256&quot;
  8935. </code></pre>
  8936. </li>
  8937. <li>
  8938. <p>Generate a JSON web token:</p>
  8939. <p>You can use the following short Python snippet to generate a JWT
  8940. protected by an HMAC.
  8941. Take care that the <code>secret</code> and the algorithm given in the <code>header</code> match
  8942. the entries from <code>jwt_config</code> above.</p>
  8943. <pre><code class="language-python">from authlib.jose import jwt
  8944. header = {&quot;alg&quot;: &quot;HS256&quot;}
  8945. payload = {&quot;sub&quot;: &quot;user1&quot;, &quot;aud&quot;: [&quot;audience&quot;]}
  8946. secret = &quot;my-secret-token&quot;
  8947. result = jwt.encode(header, payload, secret)
  8948. print(result.decode(&quot;ascii&quot;))
  8949. </code></pre>
  8950. </li>
  8951. <li>
  8952. <p>Query for the login types and ensure <code>org.matrix.login.jwt</code> is there:</p>
  8953. <pre><code class="language-bash">curl http://localhost:8080/_matrix/client/r0/login
  8954. </code></pre>
  8955. </li>
  8956. <li>
  8957. <p>Login used the generated JSON web token from above:</p>
  8958. <pre><code class="language-bash">$ curl http://localhost:8082/_matrix/client/r0/login -X POST \
  8959. --data '{&quot;type&quot;:&quot;org.matrix.login.jwt&quot;,&quot;token&quot;:&quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.Ag71GT8v01UO3w80aqRPTeuVPBIBZkYhNTJJ-_-zQIc&quot;}'
  8960. {
  8961. &quot;access_token&quot;: &quot;&lt;access token&gt;&quot;,
  8962. &quot;device_id&quot;: &quot;ACBDEFGHI&quot;,
  8963. &quot;home_server&quot;: &quot;localhost:8080&quot;,
  8964. &quot;user_id&quot;: &quot;@test-user:localhost:8480&quot;
  8965. }
  8966. </code></pre>
  8967. </li>
  8968. </ol>
  8969. <p>You should now be able to use the returned access token to query the client API.</p>
  8970. <div style="break-before: page; page-break-before: always;"></div><h1 id="refresh-tokens"><a class="header" href="#refresh-tokens">Refresh Tokens</a></h1>
  8971. <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>
  8972. <h2 id="background-and-motivation"><a class="header" href="#background-and-motivation">Background and motivation</a></h2>
  8973. <p>Synapse users' sessions are identified by <strong>access tokens</strong>; access tokens are
  8974. issued to users on login. Each session gets a unique access token which identifies
  8975. it; the access token must be kept secret as it grants access to the user's account.</p>
  8976. <p>Traditionally, these access tokens were eternally valid (at least until the user
  8977. explicitly chose to log out).</p>
  8978. <p>In some cases, it may be desirable for these access tokens to expire so that the
  8979. potential damage caused by leaking an access token is reduced.
  8980. On the other hand, forcing a user to re-authenticate (log in again) often might
  8981. be too much of an inconvenience.</p>
  8982. <p><strong>Refresh tokens</strong> are a mechanism to avoid some of this inconvenience whilst
  8983. still getting most of the benefits of short access token lifetimes.
  8984. Refresh tokens are also a concept present in OAuth 2 — further reading is available
  8985. <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.5">here</a>.</p>
  8986. <p>When refresh tokens are in use, both an access token and a refresh token will be
  8987. issued to users on login. The access token will expire after a predetermined amount
  8988. of time, but otherwise works in the same way as before. When the access token is
  8989. close to expiring (or has expired), the user's client should present the homeserver
  8990. (Synapse) with the refresh token.</p>
  8991. <p>The homeserver will then generate a new access token and refresh token for the user
  8992. and return them. The old refresh token is invalidated and can not be used again*.</p>
  8993. <p>Finally, refresh tokens also make it possible for sessions to be logged out if they
  8994. are inactive for too long, before the session naturally ends; see the configuration
  8995. guide below.</p>
  8996. <p>*To prevent issues if clients lose connection half-way through refreshing a token,
  8997. the refresh token is only invalidated once the new access token has been used at
  8998. least once. For all intents and purposes, the above simplification is sufficient.</p>
  8999. <h2 id="caveats"><a class="header" href="#caveats">Caveats</a></h2>
  9000. <p>There are some caveats:</p>
  9001. <ul>
  9002. <li>If a third party gets both your access token and refresh token, they will be able to
  9003. continue to enjoy access to your session.
  9004. <ul>
  9005. <li>This is still an improvement because you (the user) will notice when <em>your</em>
  9006. session expires and you're not able to use your refresh token.
  9007. That would be a giveaway that someone else has compromised your session.
  9008. You would be able to log in again and terminate that session.
  9009. Previously (with long-lived access tokens), a third party that has your access
  9010. token could go undetected for a very long time.</li>
  9011. </ul>
  9012. </li>
  9013. <li>Clients need to implement support for refresh tokens in order for them to be a
  9014. useful mechanism.
  9015. <ul>
  9016. <li>It is up to homeserver administrators if they want to issue long-lived access
  9017. tokens to clients not implementing refresh tokens.
  9018. <ul>
  9019. <li>For compatibility, it is likely that they should, at least until client support
  9020. is widespread.
  9021. <ul>
  9022. <li>Users with clients that support refresh tokens will still benefit from the
  9023. added security; it's not possible to downgrade a session to using long-lived
  9024. access tokens so this effectively gives users the choice.</li>
  9025. </ul>
  9026. </li>
  9027. <li>In a closed environment where all users use known clients, this may not be
  9028. an issue as the homeserver administrator can know if the clients have refresh
  9029. token support. In that case, the non-refreshable access token lifetime
  9030. may be set to a short duration so that a similar level of security is provided.</li>
  9031. </ul>
  9032. </li>
  9033. </ul>
  9034. </li>
  9035. </ul>
  9036. <h2 id="configuration-guide"><a class="header" href="#configuration-guide">Configuration Guide</a></h2>
  9037. <p>The following configuration options, in the <code>registration</code> section, are related:</p>
  9038. <ul>
  9039. <li><code>session_lifetime</code>: maximum length of a session, even if it's refreshed.
  9040. In other words, the client must log in again after this time period.
  9041. In most cases, this can be unset (infinite) or set to a long time (years or months).</li>
  9042. <li><code>refreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  9043. by clients supporting refresh tokens.
  9044. This should be short; a good value might be 5 minutes (<code>5m</code>).</li>
  9045. <li><code>nonrefreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  9046. by clients which don't support refresh tokens.
  9047. Make this short if you want to effectively force use of refresh tokens.
  9048. Make this long if you don't want to inconvenience users of clients which don't
  9049. support refresh tokens (by forcing them to frequently re-authenticate using
  9050. login credentials).</li>
  9051. <li><code>refresh_token_lifetime</code>: lifetime of refresh tokens.
  9052. In other words, the client must refresh within this time period to maintain its session.
  9053. Unless you want to log inactive sessions out, it is often fine to use a long
  9054. value here or even leave it unset (infinite).
  9055. Beware that making it too short will inconvenience clients that do not connect
  9056. very often, including mobile clients and clients of infrequent users (by making
  9057. it more difficult for them to refresh in time, which may force them to need to
  9058. re-authenticate using login credentials).</li>
  9059. </ul>
  9060. <p><strong>Note:</strong> All four options above only apply when tokens are created (by logging in or refreshing).
  9061. Changes to these settings do not apply retroactively.</p>
  9062. <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>
  9063. <p>If you'd like to force sessions to be logged out upon inactivity, you can enable
  9064. refreshable access token expiry and refresh token expiry.</p>
  9065. <p>This works because a client must refresh at least once within a period of
  9066. <code>refresh_token_lifetime</code> in order to maintain valid credentials to access the
  9067. account.</p>
  9068. <p>(It's suggested that <code>refresh_token_lifetime</code> should be longer than
  9069. <code>refreshable_access_token_lifetime</code> and this section assumes that to be the case
  9070. for simplicity.)</p>
  9071. <p>Note: this will only affect sessions using refresh tokens. You may wish to
  9072. set a short <code>nonrefreshable_access_token_lifetime</code> to prevent this being bypassed
  9073. by clients that do not support refresh tokens.</p>
  9074. <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>
  9075. <p>It may be desirable to permit some short periods of inactivity, for example to
  9076. accommodate brief outages in client connectivity.</p>
  9077. <p>The following model aims to provide guidance for choosing <code>refresh_token_lifetime</code>
  9078. and <code>refreshable_access_token_lifetime</code> to satisfy requirements of the form:</p>
  9079. <ol>
  9080. <li>inactivity longer than <code>L</code> <strong>MUST</strong> cause the session to be logged out; and</li>
  9081. <li>inactivity shorter than <code>S</code> <strong>MUST NOT</strong> cause the session to be logged out.</li>
  9082. </ol>
  9083. <p>This model makes the weakest assumption that all active clients will refresh as
  9084. needed to maintain an active access token, but no sooner.
  9085. <em>In reality, clients may refresh more often than this model assumes, but the
  9086. above requirements will still hold.</em></p>
  9087. <p>To satisfy the above model,</p>
  9088. <ul>
  9089. <li><code>refresh_token_lifetime</code> should be set to <code>L</code>; and</li>
  9090. <li><code>refreshable_access_token_lifetime</code> should be set to <code>L - S</code>.</li>
  9091. </ul>
  9092. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-2"><a class="header" href="#overview-2">Overview</a></h1>
  9093. <p>A captcha can be enabled on your homeserver to help prevent bots from registering
  9094. accounts. Synapse currently uses Google's reCAPTCHA service which requires API keys
  9095. from Google.</p>
  9096. <h2 id="getting-api-keys"><a class="header" href="#getting-api-keys">Getting API keys</a></h2>
  9097. <ol>
  9098. <li>Create a new site at <a href="https://www.google.com/recaptcha/admin/create">https://www.google.com/recaptcha/admin/create</a></li>
  9099. <li>Set the label to anything you want</li>
  9100. <li>Set the type to reCAPTCHA v2 using the &quot;I'm not a robot&quot; Checkbox option.
  9101. This is the only type of captcha that works with Synapse.</li>
  9102. <li>Add the public hostname for your server, as set in <code>public_baseurl</code>
  9103. in <code>homeserver.yaml</code>, to the list of authorized domains. If you have not set
  9104. <code>public_baseurl</code>, use <code>server_name</code>.</li>
  9105. <li>Agree to the terms of service and submit.</li>
  9106. <li>Copy your site key and secret key and add them to your <code>homeserver.yaml</code>
  9107. configuration file
  9108. <pre><code class="language-yaml">recaptcha_public_key: YOUR_SITE_KEY
  9109. recaptcha_private_key: YOUR_SECRET_KEY
  9110. </code></pre>
  9111. </li>
  9112. <li>Enable the CAPTCHA for new registrations
  9113. <pre><code class="language-yaml">enable_registration_captcha: true
  9114. </code></pre>
  9115. </li>
  9116. <li>Go to the settings page for the CAPTCHA you just created</li>
  9117. <li>Uncheck the &quot;Verify the origin of reCAPTCHA solutions&quot; checkbox so that the
  9118. captcha can be displayed in any client. If you do not disable this option then you
  9119. must specify the domains of every client that is allowed to display the CAPTCHA.</li>
  9120. </ol>
  9121. <h2 id="configuring-ip-used-for-auth"><a class="header" href="#configuring-ip-used-for-auth">Configuring IP used for auth</a></h2>
  9122. <p>The reCAPTCHA API requires that the IP address of the user who solved the
  9123. CAPTCHA is sent. If the client is connecting through a proxy or load balancer,
  9124. it may be required to use the <code>X-Forwarded-For</code> (XFF) header instead of the origin
  9125. IP address. This can be configured using the <code>x_forwarded</code> directive in the
  9126. listeners section of the <code>homeserver.yaml</code> configuration file.</p>
  9127. <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>
  9128. <p>The registration of new application services depends on the homeserver used.
  9129. In synapse, you need to create a new configuration file for your AS and add it
  9130. to the list specified under the <code>app_service_config_files</code> config
  9131. option in your synapse config.</p>
  9132. <p>For example:</p>
  9133. <pre><code class="language-yaml">app_service_config_files:
  9134. - /home/matrix/.synapse/&lt;your-AS&gt;.yaml
  9135. </code></pre>
  9136. <p>The format of the AS configuration file is as follows:</p>
  9137. <pre><code class="language-yaml">id: &lt;your-AS-id&gt;
  9138. url: &lt;base url of AS&gt;
  9139. as_token: &lt;token AS will add to requests to HS&gt;
  9140. hs_token: &lt;token HS will add to requests to AS&gt;
  9141. sender_localpart: &lt;localpart of AS user&gt;
  9142. namespaces:
  9143. users: # List of users we're interested in
  9144. - exclusive: &lt;bool&gt;
  9145. regex: &lt;regex&gt;
  9146. group_id: &lt;group&gt;
  9147. - ...
  9148. aliases: [] # List of aliases we're interested in
  9149. rooms: [] # List of room ids we're interested in
  9150. </code></pre>
  9151. <p><code>exclusive</code>: If enabled, only this application service is allowed to register users in its namespace(s).
  9152. <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>
  9153. <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>
  9154. <div style="break-before: page; page-break-before: always;"></div><h1 id="server-notices"><a class="header" href="#server-notices">Server Notices</a></h1>
  9155. <p>'Server Notices' are a new feature introduced in Synapse 0.30. They provide a
  9156. channel whereby server administrators can send messages to users on the server.</p>
  9157. <p>They are used as part of communication of the server polices (see
  9158. <a href="consent_tracking.html">Consent Tracking</a>), however the intention is that
  9159. they may also find a use for features such as &quot;Message of the day&quot;.</p>
  9160. <p>This is a feature specific to Synapse, but it uses standard Matrix
  9161. communication mechanisms, so should work with any Matrix client.</p>
  9162. <h2 id="user-experience"><a class="header" href="#user-experience">User experience</a></h2>
  9163. <p>When the user is first sent a server notice, they will get an invitation to a
  9164. room (typically called 'Server Notices', though this is configurable in
  9165. <code>homeserver.yaml</code>). They will be <strong>unable to reject</strong> this invitation -
  9166. attempts to do so will receive an error.</p>
  9167. <p>Once they accept the invitation, they will see the notice message in the room
  9168. history; it will appear to have come from the 'server notices user' (see
  9169. below).</p>
  9170. <p>The user is prevented from sending any messages in this room by the power
  9171. levels.</p>
  9172. <p>Having joined the room, the user can leave the room if they want. Subsequent
  9173. server notices will then cause a new room to be created.</p>
  9174. <h2 id="synapse-configuration"><a class="header" href="#synapse-configuration">Synapse configuration</a></h2>
  9175. <p>Server notices come from a specific user id on the server. Server
  9176. administrators are free to choose the user id - something like <code>server</code> is
  9177. suggested, meaning the notices will come from
  9178. <code>@server:&lt;your_server_name&gt;</code>. Once the Server Notices user is configured, that
  9179. user id becomes a special, privileged user, so administrators should ensure
  9180. that <strong>it is not already allocated</strong>.</p>
  9181. <p>In order to support server notices, it is necessary to add some configuration
  9182. to the <code>homeserver.yaml</code> file. In particular, you should add a <code>server_notices</code>
  9183. section, which should look like this:</p>
  9184. <pre><code class="language-yaml">server_notices:
  9185. system_mxid_localpart: server
  9186. system_mxid_display_name: &quot;Server Notices&quot;
  9187. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  9188. room_name: &quot;Server Notices&quot;
  9189. </code></pre>
  9190. <p>The only compulsory setting is <code>system_mxid_localpart</code>, which defines the user
  9191. id of the Server Notices user, as above. <code>room_name</code> defines the name of the
  9192. room which will be created.</p>
  9193. <p><code>system_mxid_display_name</code> and <code>system_mxid_avatar_url</code> can be used to set the
  9194. displayname and avatar of the Server Notices user.</p>
  9195. <h2 id="sending-notices"><a class="header" href="#sending-notices">Sending notices</a></h2>
  9196. <p>To send server notices to users you can use the
  9197. <a href="admin_api/server_notices.html">admin_api</a>.</p>
  9198. <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>
  9199. <p>Synapse 0.30 introduces support for tracking whether users have agreed to the
  9200. terms and conditions set by the administrator of a server - and blocking access
  9201. to the server until they have.</p>
  9202. <p>There are several parts to this functionality; each requires some specific
  9203. configuration in <code>homeserver.yaml</code> to be enabled.</p>
  9204. <p>Note that various parts of the configuration and this document refer to the
  9205. &quot;privacy policy&quot;: agreement with a privacy policy is one particular use of this
  9206. feature, but of course administrators can specify other terms and conditions
  9207. unrelated to &quot;privacy&quot; per se.</p>
  9208. <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>
  9209. <p>Synapse can be configured to serve the user a simple policy form with an
  9210. &quot;accept&quot; button. Clicking &quot;Accept&quot; records the user's acceptance in the
  9211. database and shows a success page.</p>
  9212. <p>To enable this, first create templates for the policy and success pages.
  9213. These should be stored on the local filesystem.</p>
  9214. <p>These templates use the <a href="http://jinja.pocoo.org">Jinja2</a> templating language,
  9215. and <a href="https://github.com/matrix-org/synapse/tree/develop/docs/privacy_policy_templates/">docs/privacy_policy_templates</a>
  9216. gives examples of the sort of thing that can be done.</p>
  9217. <p>Note that the templates must be stored under a name giving the language of the
  9218. template - currently this must always be <code>en</code> (for &quot;English&quot;);
  9219. internationalisation support is intended for the future.</p>
  9220. <p>The template for the policy itself should be versioned and named according to
  9221. the version: for example <code>1.0.html</code>. The version of the policy which the user
  9222. has agreed to is stored in the database.</p>
  9223. <p>Once the templates are in place, make the following changes to <code>homeserver.yaml</code>:</p>
  9224. <ol>
  9225. <li>
  9226. <p>Add a <code>user_consent</code> section, which should look like:</p>
  9227. <pre><code class="language-yaml">user_consent:
  9228. template_dir: privacy_policy_templates
  9229. version: 1.0
  9230. </code></pre>
  9231. <p><code>template_dir</code> points to the directory containing the policy
  9232. templates. <code>version</code> defines the version of the policy which will be served
  9233. to the user. In the example above, Synapse will serve
  9234. <code>privacy_policy_templates/en/1.0.html</code>.</p>
  9235. </li>
  9236. <li>
  9237. <p>Add a <code>form_secret</code> setting at the top level:</p>
  9238. <pre><code class="language-yaml">form_secret: &quot;&lt;unique secret&gt;&quot;
  9239. </code></pre>
  9240. <p>This should be set to an arbitrary secret string (try <code>pwgen -y 30</code> to
  9241. generate suitable secrets).</p>
  9242. <p>More on what this is used for below.</p>
  9243. </li>
  9244. <li>
  9245. <p>Add <code>consent</code> wherever the <code>client</code> resource is currently enabled in the
  9246. <code>listeners</code> configuration. For example:</p>
  9247. <pre><code class="language-yaml">listeners:
  9248. - port: 8008
  9249. resources:
  9250. - names:
  9251. - client
  9252. - consent
  9253. </code></pre>
  9254. </li>
  9255. </ol>
  9256. <p>Finally, ensure that <code>jinja2</code> is installed. If you are using a virtualenv, this
  9257. should be a matter of <code>pip install Jinja2</code>. On debian, try <code>apt-get install python-jinja2</code>.</p>
  9258. <p>Once this is complete, and the server has been restarted, try visiting
  9259. <code>https://&lt;server&gt;/_matrix/consent</code>. If correctly configured, this should give
  9260. an error &quot;Missing string query parameter 'u'&quot;. It is now possible to manually
  9261. construct URIs where users can give their consent.</p>
  9262. <h3 id="enabling-consent-tracking-at-registration"><a class="header" href="#enabling-consent-tracking-at-registration">Enabling consent tracking at registration</a></h3>
  9263. <ol>
  9264. <li>
  9265. <p>Add the following to your configuration:</p>
  9266. <pre><code class="language-yaml">user_consent:
  9267. require_at_registration: true
  9268. policy_name: &quot;Privacy Policy&quot; # or whatever you'd like to call the policy
  9269. </code></pre>
  9270. </li>
  9271. <li>
  9272. <p>In your consent templates, make use of the <code>public_version</code> variable to
  9273. see if an unauthenticated user is viewing the page. This is typically
  9274. wrapped around the form that would be used to actually agree to the document:</p>
  9275. <pre><code class="language-html">{% if not public_version %}
  9276. &lt;!-- The variables used here are only provided when the 'u' param is given to the homeserver --&gt;
  9277. &lt;form method=&quot;post&quot; action=&quot;consent&quot;&gt;
  9278. &lt;input type=&quot;hidden&quot; name=&quot;v&quot; value=&quot;{{version}}&quot;/&gt;
  9279. &lt;input type=&quot;hidden&quot; name=&quot;u&quot; value=&quot;{{user}}&quot;/&gt;
  9280. &lt;input type=&quot;hidden&quot; name=&quot;h&quot; value=&quot;{{userhmac}}&quot;/&gt;
  9281. &lt;input type=&quot;submit&quot; value=&quot;Sure thing!&quot;/&gt;
  9282. &lt;/form&gt;
  9283. {% endif %}
  9284. </code></pre>
  9285. </li>
  9286. <li>
  9287. <p>Restart Synapse to apply the changes.</p>
  9288. </li>
  9289. </ol>
  9290. <p>Visiting <code>https://&lt;server&gt;/_matrix/consent</code> should now give you a view of the privacy
  9291. document. This is what users will be able to see when registering for accounts.</p>
  9292. <h3 id="constructing-the-consent-uri"><a class="header" href="#constructing-the-consent-uri">Constructing the consent URI</a></h3>
  9293. <p>It may be useful to manually construct the &quot;consent URI&quot; for a given user - for
  9294. instance, in order to send them an email asking them to consent. To do this,
  9295. take the base <code>https://&lt;server&gt;/_matrix/consent</code> URL and add the following
  9296. query parameters:</p>
  9297. <ul>
  9298. <li>
  9299. <p><code>u</code>: the user id of the user. This can either be a full MXID
  9300. (<code>@user:server.com</code>) or just the localpart (<code>user</code>).</p>
  9301. </li>
  9302. <li>
  9303. <p><code>h</code>: hex-encoded HMAC-SHA256 of <code>u</code> using the <code>form_secret</code> as a key. It is
  9304. possible to calculate this on the commandline with something like:</p>
  9305. <pre><code class="language-bash">echo -n '&lt;user&gt;' | openssl sha256 -hmac '&lt;form_secret&gt;'
  9306. </code></pre>
  9307. <p>This should result in a URI which looks something like:
  9308. <code>https://&lt;server&gt;/_matrix/consent?u=&lt;user&gt;&amp;h=68a152465a4d...</code>.</p>
  9309. </li>
  9310. </ul>
  9311. <p>Note that not providing a <code>u</code> parameter will be interpreted as wanting to view
  9312. the document from an unauthenticated perspective, such as prior to registration.
  9313. Therefore, the <code>h</code> parameter is not required in this scenario. To enable this
  9314. behaviour, set <code>require_at_registration</code> to <code>true</code> in your <code>user_consent</code> config.</p>
  9315. <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>
  9316. <p>It is possible to configure Synapse to send a <a href="server_notices.html">server
  9317. notice</a> to anybody who has not yet agreed to the current
  9318. version of the policy. To do so:</p>
  9319. <ul>
  9320. <li>
  9321. <p>ensure that the consent resource is configured, as in the previous section</p>
  9322. </li>
  9323. <li>
  9324. <p>ensure that server notices are configured, as in <a href="server_notices.html">the server notice documentation</a>.</p>
  9325. </li>
  9326. <li>
  9327. <p>Add <code>server_notice_content</code> under <code>user_consent</code> in <code>homeserver.yaml</code>. For
  9328. example:</p>
  9329. <pre><code class="language-yaml">user_consent:
  9330. server_notice_content:
  9331. msgtype: m.text
  9332. body: &gt;-
  9333. Please give your consent to the privacy policy at %(consent_uri)s.
  9334. </code></pre>
  9335. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  9336. consent uri for that user.</p>
  9337. </li>
  9338. <li>
  9339. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  9340. URI that clients use to connect to the server. (It is used to construct
  9341. <code>consent_uri</code> in the server notice.)</p>
  9342. </li>
  9343. </ul>
  9344. <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>
  9345. <p>Synapse can be configured to block any attempts to join rooms or send messages
  9346. until the user has given their agreement to the policy. (Joining the server
  9347. notices room is exempted from this).</p>
  9348. <p>To enable this, add <code>block_events_error</code> under <code>user_consent</code>. For example:</p>
  9349. <pre><code class="language-yaml">user_consent:
  9350. block_events_error: &gt;-
  9351. You can't send any messages until you consent to the privacy policy at
  9352. %(consent_uri)s.
  9353. </code></pre>
  9354. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  9355. consent uri for that user.</p>
  9356. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  9357. URI that clients use to connect to the server. (It is used to construct
  9358. <code>consent_uri</code> in the error.)</p>
  9359. <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>
  9360. <p>The user directory is maintained based on users that are 'visible' to the homeserver -
  9361. i.e. ones which are local to the server and ones which any local user shares a
  9362. room with.</p>
  9363. <p>The directory info is stored in various tables, which can sometimes get out of
  9364. sync (although this is considered a bug). If this happens, for now the
  9365. solution to fix it is to use the <a href="usage/administration/admin_api/background_updates.html#run">admin API</a>
  9366. and execute the job <code>regenerate_directory</code>. This should then start a background task to
  9367. flush the current tables and regenerate the directory. Depending on the size
  9368. of your homeserver (number of users and rooms) this can take a while.</p>
  9369. <h2 id="data-model"><a class="header" href="#data-model">Data model</a></h2>
  9370. <p>There are five relevant tables that collectively form the &quot;user directory&quot;.
  9371. Three of them track a list of all known users. The last two (collectively called
  9372. the &quot;search tables&quot;) track which users are visible to each other.</p>
  9373. <p>From all of these tables we exclude three types of local user:</p>
  9374. <ul>
  9375. <li>support users</li>
  9376. <li>appservice users</li>
  9377. <li>deactivated users</li>
  9378. </ul>
  9379. <p>A description of each table follows:</p>
  9380. <ul>
  9381. <li>
  9382. <p><code>user_directory</code>. This contains the user ID, display name and avatar of each user.</p>
  9383. <ul>
  9384. <li>Because there is only one directory entry per user, it is important that it
  9385. only contain publicly visible information. Otherwise, this will leak the
  9386. nickname or avatar used in a private room.</li>
  9387. <li>Indexed on rooms. Indexed on users.</li>
  9388. </ul>
  9389. </li>
  9390. <li>
  9391. <p><code>user_directory_search</code>. To be joined to <code>user_directory</code>. It contains an extra
  9392. column that enables full text search based on user IDs and display names.
  9393. Different schemas for SQLite and Postgres are used.</p>
  9394. <ul>
  9395. <li>Indexed on the full text search data. Indexed on users.</li>
  9396. </ul>
  9397. </li>
  9398. <li>
  9399. <p><code>user_directory_stream_pos</code>. When the initial background update to populate
  9400. the directory is complete, we record a stream position here. This indicates
  9401. that synapse should now listen for room changes and incrementally update
  9402. the directory where necessary. (See <a href="development/synapse_architecture/streams.html">stream positions</a>.)</p>
  9403. </li>
  9404. <li>
  9405. <p><code>users_in_public_rooms</code>. Contains associations between users and the public
  9406. rooms they're in. Used to determine which users are in public rooms and should
  9407. be publicly visible in the directory. Both local and remote users are tracked.</p>
  9408. </li>
  9409. <li>
  9410. <p><code>users_who_share_private_rooms</code>. Rows are triples <code>(L, M, room id)</code> where <code>L</code>
  9411. is a local user and <code>M</code> is a local or remote user. <code>L</code> and <code>M</code> should be
  9412. different, but this isn't enforced by a constraint.</p>
  9413. <p>Note that if two local users share a room then there will be two entries:
  9414. <code>(user1, user2, !room_id)</code> and <code>(user2, user1, !room_id)</code>.</p>
  9415. </li>
  9416. </ul>
  9417. <h2 id="configuration-options"><a class="header" href="#configuration-options">Configuration options</a></h2>
  9418. <p>The exact way user search works can be tweaked via some server-level
  9419. <a href="usage/configuration/config_documentation.html#user_directory">configuration options</a>.</p>
  9420. <p>The information is not repeated here, but the options are mentioned below.</p>
  9421. <h2 id="search-algorithm"><a class="header" href="#search-algorithm">Search algorithm</a></h2>
  9422. <p>If <code>search_all_users</code> is <code>false</code>, then results are limited to users who:</p>
  9423. <ol>
  9424. <li>Are found in the <code>users_in_public_rooms</code> table, or</li>
  9425. <li>Are found in the <code>users_who_share_private_rooms</code> where <code>L</code> is the requesting
  9426. user and <code>M</code> is the search result.</li>
  9427. </ol>
  9428. <p>Otherwise, if <code>search_all_users</code> is <code>true</code>, no such limits are placed and all
  9429. users known to the server (matching the search query) will be returned.</p>
  9430. <p>By default, locked users are not returned. If <code>show_locked_users</code> is <code>true</code> then
  9431. no filtering on the locked status of a user is done.</p>
  9432. <p>The user provided search term is lowercased and normalized using <a href="https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization">NFKC</a>,
  9433. this treats the string as case-insensitive, canonicalizes different forms of the
  9434. same text, and maps some &quot;roughly equivalent&quot; characters together.</p>
  9435. <p>The search term is then split into words:</p>
  9436. <ul>
  9437. <li>If <a href="https://en.wikipedia.org/wiki/International_Components_for_Unicode">ICU</a> is
  9438. available, then the system's <a href="https://unicode-org.github.io/icu/userguide/locale/#default-locales">default locale</a>
  9439. will be used to break the search term into words. (See the
  9440. <a href="setup/installation.html">installation instructions</a> for how to install ICU.)</li>
  9441. <li>If unavailable, then runs of ASCII characters, numbers, underscores, and hyphens
  9442. are considered words.</li>
  9443. </ul>
  9444. <p>The queries for PostgreSQL and SQLite are detailed below, by their overall goal
  9445. is to find matching users, preferring users who are &quot;real&quot; (e.g. not bots,
  9446. not deactivated). It is assumed that real users will have an display name and
  9447. avatar set.</p>
  9448. <h3 id="postgresql"><a class="header" href="#postgresql">PostgreSQL</a></h3>
  9449. <p>The above words are then transformed into two queries:</p>
  9450. <ol>
  9451. <li>&quot;exact&quot; which matches the parsed words exactly (using <a href="https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES"><code>to_tsquery</code></a>);</li>
  9452. <li>&quot;prefix&quot; which matches the parsed words as prefixes (using <code>to_tsquery</code>).</li>
  9453. </ol>
  9454. <p>Results are composed of all rows in the <code>user_directory_search</code> table whose information
  9455. matches one (or both) of these queries. Results are ordered by calculating a weighted
  9456. score for each result, higher scores are returned first:</p>
  9457. <ul>
  9458. <li>4x if a user ID exists.</li>
  9459. <li>1.2x if the user has a display name set.</li>
  9460. <li>1.2x if the user has an avatar set.</li>
  9461. <li>0x-3x by the full text search results using the <a href="https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING"><code>ts_rank_cd</code> function</a>
  9462. against the &quot;exact&quot; search query; this has four variables with the following weightings:
  9463. <ul>
  9464. <li><code>D</code>: 0.1 for the user ID's domain</li>
  9465. <li><code>C</code>: 0.1 for unused</li>
  9466. <li><code>B</code>: 0.9 for the user's display name (or an empty string if it is not set)</li>
  9467. <li><code>A</code>: 0.1 for the user ID's localpart</li>
  9468. </ul>
  9469. </li>
  9470. <li>0x-1x by the full text search results using the <code>ts_rank_cd</code> function against the
  9471. &quot;prefix&quot; search query. (Using the same weightings as above.)</li>
  9472. <li>If <code>prefer_local_users</code> is <code>true</code>, then 2x if the user is local to the homeserver.</li>
  9473. </ul>
  9474. <p>Note that <code>ts_rank_cd</code> returns a weight between 0 and 1. The initial weighting of
  9475. all results is 1.</p>
  9476. <h3 id="sqlite"><a class="header" href="#sqlite">SQLite</a></h3>
  9477. <p>Results are composed of all rows in the <code>user_directory_search</code> whose information
  9478. matches the query. Results are ordered by the following information, with each
  9479. subsequent column used as a tiebreaker, for each result:</p>
  9480. <ol>
  9481. <li>By the <a href="https://www.sqlite.org/windowfunctions.html#built_in_window_functions"><code>rank</code></a>
  9482. of the full text search results using the <a href="https://www.sqlite.org/fts3.html#matchinfo"><code>matchinfo</code> function</a>. Higher
  9483. ranks are returned first.</li>
  9484. <li>If <code>prefer_local_users</code> is <code>true</code>, then users local to the homeserver are
  9485. returned first.</li>
  9486. <li>Users with a display name set are returned first.</li>
  9487. <li>Users with an avatar set are returned first.</li>
  9488. </ol>
  9489. <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>
  9490. <p>Synapse admins can enable support for message retention policies on
  9491. their homeserver. Message retention policies exist at a room level,
  9492. follow the semantics described in
  9493. <a href="https://github.com/matrix-org/matrix-doc/blob/matthew/msc1763/proposals/1763-configurable-retention-periods.md">MSC1763</a>,
  9494. and allow server and room admins to configure how long messages should
  9495. be kept in a homeserver's database before being purged from it.
  9496. <strong>Please note that, as this feature isn't part of the Matrix
  9497. specification yet, this implementation is to be considered as
  9498. experimental.</strong></p>
  9499. <p>A message retention policy is mainly defined by its <code>max_lifetime</code>
  9500. parameter, which defines how long a message can be kept around after
  9501. it was sent to the room. If a room doesn't have a message retention
  9502. policy, and there's no default one for a given server, then no message
  9503. sent in that room is ever purged on that server.</p>
  9504. <p>MSC1763 also specifies semantics for a <code>min_lifetime</code> parameter which
  9505. defines the amount of time after which an event <em>can</em> get purged (after
  9506. it was sent to the room), but Synapse doesn't currently support it
  9507. beyond registering it.</p>
  9508. <p>Both <code>max_lifetime</code> and <code>min_lifetime</code> are optional parameters.</p>
  9509. <p>Note that message retention policies don't apply to state events.</p>
  9510. <p>Once an event reaches its expiry date (defined as the time it was sent
  9511. plus the value for <code>max_lifetime</code> in the room), two things happen:</p>
  9512. <ul>
  9513. <li>Synapse stops serving the event to clients via any endpoint.</li>
  9514. <li>The message gets picked up by the next purge job (see the &quot;Purge jobs&quot;
  9515. section) and is removed from Synapse's database.</li>
  9516. </ul>
  9517. <p>Since purge jobs don't run continuously, this means that an event might
  9518. stay in a server's database for longer than the value for <code>max_lifetime</code>
  9519. in the room would allow, though hidden from clients.</p>
  9520. <p>Similarly, if a server (with support for message retention policies
  9521. enabled) receives from another server an event that should have been
  9522. purged according to its room's policy, then the receiving server will
  9523. process and store that event until it's picked up by the next purge job,
  9524. though it will always hide it from clients.</p>
  9525. <p>Synapse requires at least one message in each room, so it will never
  9526. delete the last message in a room. It will, however, hide it from
  9527. clients.</p>
  9528. <h2 id="server-configuration"><a class="header" href="#server-configuration">Server configuration</a></h2>
  9529. <p>Support for this feature can be enabled and configured by adding a the
  9530. <code>retention</code> in the Synapse configuration file (see
  9531. <a href="usage/configuration/config_documentation.html#retention">configuration manual</a>).</p>
  9532. <p>To enable support for message retention policies, set the setting
  9533. <code>enabled</code> in this section to <code>true</code>.</p>
  9534. <h3 id="default-policy"><a class="header" href="#default-policy">Default policy</a></h3>
  9535. <p>A default message retention policy is a policy defined in Synapse's
  9536. configuration that is used by Synapse for every room that doesn't have a
  9537. message retention policy configured in its state. This allows server
  9538. admins to ensure that messages are never kept indefinitely in a server's
  9539. database. </p>
  9540. <p>A default policy can be defined as such, by adding the <code>retention</code> option in
  9541. the configuration file and adding these sub-options:</p>
  9542. <pre><code class="language-yaml">default_policy:
  9543. min_lifetime: 1d
  9544. max_lifetime: 1y
  9545. </code></pre>
  9546. <p>Here, <code>min_lifetime</code> and <code>max_lifetime</code> have the same meaning and level
  9547. of support as previously described. They can be expressed either as a
  9548. duration (using the units <code>s</code> (seconds), <code>m</code> (minutes), <code>h</code> (hours),
  9549. <code>d</code> (days), <code>w</code> (weeks) and <code>y</code> (years)) or as a number of milliseconds.</p>
  9550. <h3 id="purge-jobs"><a class="header" href="#purge-jobs">Purge jobs</a></h3>
  9551. <p>Purge jobs are the jobs that Synapse runs in the background to purge
  9552. expired events from the database. They are only run if support for
  9553. message retention policies is enabled in the server's configuration. If
  9554. no configuration for purge jobs is configured by the server admin,
  9555. Synapse will use a default configuration, which is described here in the
  9556. <a href="usage/configuration/config_documentation.html#retention">configuration manual</a>.</p>
  9557. <p>Some server admins might want a finer control on when events are removed
  9558. depending on an event's room's policy. This can be done by setting the
  9559. <code>purge_jobs</code> sub-section in the <code>retention</code> section of the configuration
  9560. file. An example of such configuration could be:</p>
  9561. <pre><code class="language-yaml">purge_jobs:
  9562. - longest_max_lifetime: 3d
  9563. interval: 12h
  9564. - shortest_max_lifetime: 3d
  9565. longest_max_lifetime: 1w
  9566. interval: 1d
  9567. - shortest_max_lifetime: 1w
  9568. interval: 2d
  9569. </code></pre>
  9570. <p>In this example, we define three jobs:</p>
  9571. <ul>
  9572. <li>one that runs twice a day (every 12 hours) and purges events in rooms
  9573. which policy's <code>max_lifetime</code> is lower or equal to 3 days.</li>
  9574. <li>one that runs once a day and purges events in rooms which policy's
  9575. <code>max_lifetime</code> is between 3 days and a week.</li>
  9576. <li>one that runs once every 2 days and purges events in rooms which
  9577. policy's <code>max_lifetime</code> is greater than a week.</li>
  9578. </ul>
  9579. <p>Note that this example is tailored to show different configurations and
  9580. features slightly more jobs than it's probably necessary (in practice, a
  9581. server admin would probably consider it better to replace the two last
  9582. jobs with one that runs once a day and handles rooms which
  9583. policy's <code>max_lifetime</code> is greater than 3 days).</p>
  9584. <p>Keep in mind, when configuring these jobs, that a purge job can become
  9585. quite heavy on the server if it targets many rooms, therefore prefer
  9586. having jobs with a low interval that target a limited set of rooms. Also
  9587. make sure to include a job with no minimum and one with no maximum to
  9588. make sure your configuration handles every policy.</p>
  9589. <p>As previously mentioned in this documentation, while a purge job that
  9590. runs e.g. every day means that an expired event might stay in the
  9591. database for up to a day after its expiry, Synapse hides expired events
  9592. from clients as soon as they expire, so the event is not visible to
  9593. local users between its expiry date and the moment it gets purged from
  9594. the server's database.</p>
  9595. <h3 id="lifetime-limits"><a class="header" href="#lifetime-limits">Lifetime limits</a></h3>
  9596. <p>Server admins can set limits on the values of <code>max_lifetime</code> to use when
  9597. purging old events in a room. These limits can be defined under the
  9598. <code>retention</code> option in the configuration file:</p>
  9599. <pre><code class="language-yaml">allowed_lifetime_min: 1d
  9600. allowed_lifetime_max: 1y
  9601. </code></pre>
  9602. <p>The limits are considered when running purge jobs. If necessary, the
  9603. effective value of <code>max_lifetime</code> will be brought between
  9604. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> (inclusive).
  9605. This means that, if the value of <code>max_lifetime</code> defined in the room's state
  9606. is lower than <code>allowed_lifetime_min</code>, the value of <code>allowed_lifetime_min</code>
  9607. will be used instead. Likewise, if the value of <code>max_lifetime</code> is higher
  9608. than <code>allowed_lifetime_max</code>, the value of <code>allowed_lifetime_max</code> will be
  9609. used instead.</p>
  9610. <p>In the example above, we ensure Synapse never deletes events that are less
  9611. than one day old, and that it always deletes events that are over a year
  9612. old.</p>
  9613. <p>If a default policy is set, and its <code>max_lifetime</code> value is lower than
  9614. <code>allowed_lifetime_min</code> or higher than <code>allowed_lifetime_max</code>, the same
  9615. process applies.</p>
  9616. <p>Both parameters are optional; if one is omitted Synapse won't use it to
  9617. adjust the effective value of <code>max_lifetime</code>.</p>
  9618. <p>Like other settings in this section, these parameters can be expressed
  9619. either as a duration or as a number of milliseconds.</p>
  9620. <h2 id="room-configuration"><a class="header" href="#room-configuration">Room configuration</a></h2>
  9621. <p>To configure a room's message retention policy, a room's admin or
  9622. moderator needs to send a state event in that room with the type
  9623. <code>m.room.retention</code> and the following content:</p>
  9624. <pre><code class="language-json">{
  9625. &quot;max_lifetime&quot;: ...
  9626. }
  9627. </code></pre>
  9628. <p>In this event's content, the <code>max_lifetime</code> parameter has the same
  9629. meaning as previously described, and needs to be expressed in
  9630. milliseconds. The event's content can also include a <code>min_lifetime</code>
  9631. parameter, which has the same meaning and limited support as previously
  9632. described.</p>
  9633. <p>Note that over every server in the room, only the ones with support for
  9634. message retention policies will actually remove expired events. This
  9635. support is currently not enabled by default in Synapse.</p>
  9636. <h2 id="note-on-reclaiming-disk-space"><a class="header" href="#note-on-reclaiming-disk-space">Note on reclaiming disk space</a></h2>
  9637. <p>While purge jobs actually delete data from the database, the disk space
  9638. used by the database might not decrease immediately on the database's
  9639. host. However, even though the database engine won't free up the disk
  9640. space, it will start writing new data into where the purged data was.</p>
  9641. <p>If you want to reclaim the freed disk space anyway and return it to the
  9642. operating system, the server admin needs to run <code>VACUUM FULL;</code> (or
  9643. <code>VACUUM;</code> for SQLite databases) on Synapse's database (see the related
  9644. <a href="https://www.postgresql.org/docs/current/sql-vacuum.html">PostgreSQL documentation</a>).</p>
  9645. <div style="break-before: page; page-break-before: always;"></div><h1 id="modules-2"><a class="header" href="#modules-2">Modules</a></h1>
  9646. <p>Synapse supports extending its functionality by configuring external modules.</p>
  9647. <p><strong>Note</strong>: When using third-party modules, you effectively allow someone else to run
  9648. custom code on your Synapse homeserver. Server admins are encouraged to verify the
  9649. provenance of the modules they use on their homeserver and make sure the modules aren't
  9650. running malicious code on their instance.</p>
  9651. <h2 id="using-modules"><a class="header" href="#using-modules">Using modules</a></h2>
  9652. <p>To use a module on Synapse, add it to the <code>modules</code> section of the configuration file:</p>
  9653. <pre><code class="language-yaml">modules:
  9654. - module: my_super_module.MySuperClass
  9655. config:
  9656. do_thing: true
  9657. - module: my_other_super_module.SomeClass
  9658. config: {}
  9659. </code></pre>
  9660. <p>Each module is defined by a path to a Python class as well as a configuration. This
  9661. information for a given module should be available in the module's own documentation.</p>
  9662. <h2 id="using-multiple-modules"><a class="header" href="#using-multiple-modules">Using multiple modules</a></h2>
  9663. <p>The order in which modules are listed in this section is important. When processing an
  9664. action that can be handled by several modules, Synapse will always prioritise the module
  9665. that appears first (i.e. is the highest in the list). This means:</p>
  9666. <ul>
  9667. <li>If several modules register the same callback, the callback registered by the module
  9668. that appears first is used.</li>
  9669. <li>If several modules try to register a handler for the same HTTP path, only the handler
  9670. registered by the module that appears first is used. Handlers registered by the other
  9671. module(s) are ignored and Synapse will log a warning message about them.</li>
  9672. </ul>
  9673. <p>Note that Synapse doesn't allow multiple modules implementing authentication checkers via
  9674. the password auth provider feature for the same login type with different fields. If this
  9675. happens, Synapse will refuse to start.</p>
  9676. <h2 id="current-status"><a class="header" href="#current-status">Current status</a></h2>
  9677. <p>We are currently in the process of migrating module interfaces to this system. While some
  9678. interfaces might be compatible with it, others still require configuring modules in
  9679. another part of Synapse's configuration file.</p>
  9680. <p>Currently, only the following pre-existing interfaces are compatible with this new system:</p>
  9681. <ul>
  9682. <li>spam checker</li>
  9683. <li>third-party rules</li>
  9684. <li>presence router</li>
  9685. <li>password auth providers</li>
  9686. </ul>
  9687. <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>
  9688. <p>A module is a Python class that uses Synapse's module API to interact with the
  9689. homeserver. It can register callbacks that Synapse will call on specific operations, as
  9690. well as web resources to attach to Synapse's web server.</p>
  9691. <p>When instantiated, a module is given its parsed configuration as well as an instance of
  9692. the <code>synapse.module_api.ModuleApi</code> class. The configuration is a dictionary, and is
  9693. either the output of the module's <code>parse_config</code> static method (see below), or the
  9694. configuration associated with the module in Synapse's configuration file.</p>
  9695. <p>See the documentation for the <code>ModuleApi</code> class
  9696. <a href="https://github.com/matrix-org/synapse/blob/master/synapse/module_api/__init__.py">here</a>.</p>
  9697. <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>
  9698. <p>If Synapse is running with other modules configured, the order each module appears in
  9699. within the <code>modules</code> section of the Synapse configuration file might restrict what it can
  9700. or cannot register. See <a href="modules/index.html#using-multiple-modules">this section</a> for more
  9701. information.</p>
  9702. <p>On top of the rules listed in the link above, if a callback returns a value that should
  9703. cause the current operation to fail (e.g. if a callback checking an event returns with a
  9704. value that should cause the event to be denied), Synapse will fail the operation and
  9705. ignore any subsequent callbacks that should have been run after this one.</p>
  9706. <p>The documentation for each callback mentions how Synapse behaves when
  9707. multiple modules implement it.</p>
  9708. <h2 id="handling-the-modules-configuration"><a class="header" href="#handling-the-modules-configuration">Handling the module's configuration</a></h2>
  9709. <p>A module can implement the following static method:</p>
  9710. <pre><code class="language-python">@staticmethod
  9711. def parse_config(config: dict) -&gt; Any
  9712. </code></pre>
  9713. <p>This method is given a dictionary resulting from parsing the YAML configuration for the
  9714. module. It may modify it (for example by parsing durations expressed as strings (e.g.
  9715. &quot;5d&quot;) into milliseconds, etc.), and return the modified dictionary. It may also verify
  9716. that the configuration is correct, and raise an instance of
  9717. <code>synapse.module_api.errors.ConfigError</code> if not.</p>
  9718. <h2 id="registering-a-web-resource"><a class="header" href="#registering-a-web-resource">Registering a web resource</a></h2>
  9719. <p>Modules can register web resources onto Synapse's web server using the following module
  9720. API method:</p>
  9721. <pre><code class="language-python">def ModuleApi.register_web_resource(path: str, resource: IResource) -&gt; None
  9722. </code></pre>
  9723. <p>The path is the full absolute path to register the resource at. For example, if you
  9724. register a resource for the path <code>/_synapse/client/my_super_module/say_hello</code>, Synapse
  9725. will serve it at <code>http(s)://[HS_URL]/_synapse/client/my_super_module/say_hello</code>. Note
  9726. that Synapse does not allow registering resources for several sub-paths in the <code>/_matrix</code>
  9727. namespace (such as anything under <code>/_matrix/client</code> for example). It is strongly
  9728. recommended that modules register their web resources under the <code>/_synapse/client</code>
  9729. namespace.</p>
  9730. <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>
  9731. interface (such as <a href="https://docs.twistedmatrix.com/en/stable/api/twisted.web.resource.Resource.html">Resource</a>).</p>
  9732. <p>Only one resource can be registered for a given path. If several modules attempt to
  9733. register a resource for the same path, the module that appears first in Synapse's
  9734. configuration file takes priority.</p>
  9735. <p>Modules <strong>must</strong> register their web resources in their <code>__init__</code> method.</p>
  9736. <h2 id="registering-a-callback"><a class="header" href="#registering-a-callback">Registering a callback</a></h2>
  9737. <p>Modules can use Synapse's module API to register callbacks. Callbacks are functions that
  9738. Synapse will call when performing specific actions. Callbacks must be asynchronous (unless
  9739. specified otherwise), and are split in categories. A single module may implement callbacks
  9740. from multiple categories, and is under no obligation to implement all callbacks from the
  9741. categories it registers callbacks for.</p>
  9742. <p>Modules can register callbacks using one of the module API's <code>register_[...]_callbacks</code>
  9743. methods. The callback functions are passed to these methods as keyword arguments, with
  9744. the callback name as the argument name and the function as its value. A
  9745. <code>register_[...]_callbacks</code> method exists for each category.</p>
  9746. <p>Callbacks for each category can be found on their respective page of the
  9747. <a href="https://matrix-org.github.io/synapse">Synapse documentation website</a>.</p>
  9748. <h2 id="caching-1"><a class="header" href="#caching-1">Caching</a></h2>
  9749. <p><em>Added in Synapse 1.74.0.</em></p>
  9750. <p>Modules can leverage Synapse's caching tools to manage their own cached functions. This
  9751. can be helpful for modules that need to repeatedly request the same data from the database
  9752. or a remote service.</p>
  9753. <p>Functions that need to be wrapped with a cache need to be decorated with a <code>@cached()</code>
  9754. decorator (which can be imported from <code>synapse.module_api</code>) and registered with the
  9755. <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>
  9756. API when initialising the module. If the module needs to invalidate an entry in a cache,
  9757. 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>
  9758. API, with the function to invalidate the cache of and the key(s) of the entry to
  9759. invalidate.</p>
  9760. <p>Below is an example of a simple module using a cached function:</p>
  9761. <pre><code class="language-python">from typing import Any
  9762. from synapse.module_api import cached, ModuleApi
  9763. class MyModule:
  9764. def __init__(self, config: Any, api: ModuleApi):
  9765. self.api = api
  9766. # Register the cached function so Synapse knows how to correctly invalidate
  9767. # entries for it.
  9768. self.api.register_cached_function(self.get_user_from_id)
  9769. @cached()
  9770. async def get_department_for_user(self, user_id: str) -&gt; str:
  9771. &quot;&quot;&quot;A function with a cache.&quot;&quot;&quot;
  9772. # Request a department from an external service.
  9773. return await self.http_client.get_json(
  9774. &quot;https://int.example.com/users&quot;, {&quot;user_id&quot;: user_id)
  9775. )[&quot;department&quot;]
  9776. async def do_something_with_users(self) -&gt; None:
  9777. &quot;&quot;&quot;Calls the cached function and then invalidates an entry in its cache.&quot;&quot;&quot;
  9778. user_id = &quot;@alice:example.com&quot;
  9779. # Get the user. Since get_department_for_user is wrapped with a cache,
  9780. # the return value for this user_id will be cached.
  9781. department = await self.get_department_for_user(user_id)
  9782. # Do something with `department`...
  9783. # Let's say something has changed with our user, and the entry we have for
  9784. # them in the cache is out of date, so we want to invalidate it.
  9785. await self.api.invalidate_cache(self.get_department_for_user, (user_id,))
  9786. </code></pre>
  9787. <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>
  9788. <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>
  9789. <p>Spam checker callbacks allow module developers to implement spam mitigation actions for
  9790. Synapse instances. Spam checker callbacks can be registered using the module API's
  9791. <code>register_spam_checker_callbacks</code> method.</p>
  9792. <h2 id="callbacks"><a class="header" href="#callbacks">Callbacks</a></h2>
  9793. <p>The available spam checker callbacks are:</p>
  9794. <h3 id="check_event_for_spam"><a class="header" href="#check_event_for_spam"><code>check_event_for_spam</code></a></h3>
  9795. <p><em>First introduced in Synapse v1.37.0</em></p>
  9796. <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>
  9797. <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]
  9798. </code></pre>
  9799. <p>Called when receiving an event from a client or via federation. The callback must return one of:</p>
  9800. <ul>
  9801. <li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9802. decide to reject it.</li>
  9803. <li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9804. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
  9805. <li>(deprecated) a non-<code>Codes</code> <code>str</code> to reject the operation and specify an error message. Note that clients
  9806. typically will not localize the error message to the user's preferred locale.</li>
  9807. <li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
  9808. <li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
  9809. </ul>
  9810. <p>If multiple modules implement this callback, they will be considered in order. If a
  9811. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9812. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9813. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9814. this callback.</p>
  9815. <h3 id="user_may_join_room"><a class="header" href="#user_may_join_room"><code>user_may_join_room</code></a></h3>
  9816. <p><em>First introduced in Synapse v1.37.0</em></p>
  9817. <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>
  9818. <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]
  9819. </code></pre>
  9820. <p>Called when a user is trying to join a room. The user is represented by their Matrix user ID (e.g.
  9821. <code>@alice:example.com</code>) and the room is represented by its Matrix ID (e.g.
  9822. <code>!room:example.com</code>). The module is also given a boolean to indicate whether the user
  9823. currently has a pending invite in the room.</p>
  9824. <p>This callback isn't called if the join is performed by a server administrator, or in the
  9825. context of a room creation.</p>
  9826. <p>The callback must return one of:</p>
  9827. <ul>
  9828. <li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9829. decide to reject it.</li>
  9830. <li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9831. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
  9832. <li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
  9833. <li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
  9834. </ul>
  9835. <p>If multiple modules implement this callback, they will be considered in order. If a
  9836. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9837. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9838. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9839. this callback.</p>
  9840. <h3 id="user_may_invite"><a class="header" href="#user_may_invite"><code>user_may_invite</code></a></h3>
  9841. <p><em>First introduced in Synapse v1.37.0</em></p>
  9842. <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>
  9843. <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]
  9844. </code></pre>
  9845. <p>Called when processing an invitation. Both inviter and invitee are
  9846. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  9847. <p>The callback must return one of:</p>
  9848. <ul>
  9849. <li>
  9850. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9851. decide to reject it.</p>
  9852. </li>
  9853. <li>
  9854. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9855. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9856. </li>
  9857. <li>
  9858. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9859. </li>
  9860. <li>
  9861. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9862. </li>
  9863. </ul>
  9864. <p>If multiple modules implement this callback, they will be considered in order. If a
  9865. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9866. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9867. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9868. this callback.</p>
  9869. <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>
  9870. <p><em>First introduced in Synapse v1.45.0</em></p>
  9871. <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>
  9872. <pre><code class="language-python">async def user_may_send_3pid_invite(
  9873. inviter: str,
  9874. medium: str,
  9875. address: str,
  9876. room_id: str,
  9877. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
  9878. </code></pre>
  9879. <p>Called when processing an invitation using a third-party identifier (also called a 3PID,
  9880. e.g. an email address or a phone number). </p>
  9881. <p>The inviter is represented by their Matrix user ID (e.g. <code>@alice:example.com</code>), and the
  9882. invitee is represented by its medium (e.g. &quot;email&quot;) and its address
  9883. (e.g. <code>alice@example.com</code>). See <a href="https://matrix.org/docs/spec/appendices#pid-types">the Matrix specification</a>
  9884. for more information regarding third-party identifiers.</p>
  9885. <p>For example, a call to this callback to send an invitation to the email address
  9886. <code>alice@example.com</code> would look like this:</p>
  9887. <pre><code class="language-python">await user_may_send_3pid_invite(
  9888. &quot;@bob:example.com&quot;, # The inviter's user ID
  9889. &quot;email&quot;, # The medium of the 3PID to invite
  9890. &quot;alice@example.com&quot;, # The address of the 3PID to invite
  9891. &quot;!some_room:example.com&quot;, # The ID of the room to send the invite into
  9892. )
  9893. </code></pre>
  9894. <p><strong>Note</strong>: If the third-party identifier is already associated with a matrix user ID,
  9895. <a href="modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a> will be used instead.</p>
  9896. <p>The callback must return one of:</p>
  9897. <ul>
  9898. <li>
  9899. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9900. decide to reject it.</p>
  9901. </li>
  9902. <li>
  9903. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9904. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9905. </li>
  9906. <li>
  9907. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9908. </li>
  9909. <li>
  9910. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9911. </li>
  9912. </ul>
  9913. <p>If multiple modules implement this callback, they will be considered in order. If a
  9914. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9915. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9916. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9917. this callback.</p>
  9918. <h3 id="user_may_create_room"><a class="header" href="#user_may_create_room"><code>user_may_create_room</code></a></h3>
  9919. <p><em>First introduced in Synapse v1.37.0</em></p>
  9920. <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>
  9921. <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]
  9922. </code></pre>
  9923. <p>Called when processing a room creation request.</p>
  9924. <p>The callback must return one of:</p>
  9925. <ul>
  9926. <li>
  9927. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9928. decide to reject it.</p>
  9929. </li>
  9930. <li>
  9931. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9932. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9933. </li>
  9934. <li>
  9935. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9936. </li>
  9937. <li>
  9938. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9939. </li>
  9940. </ul>
  9941. <p>If multiple modules implement this callback, they will be considered in order. If a
  9942. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9943. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9944. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9945. this callback.</p>
  9946. <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>
  9947. <p><em>First introduced in Synapse v1.37.0</em></p>
  9948. <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>
  9949. <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]
  9950. </code></pre>
  9951. <p>Called when trying to associate an alias with an existing room.</p>
  9952. <p>The callback must return one of:</p>
  9953. <ul>
  9954. <li>
  9955. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9956. decide to reject it.</p>
  9957. </li>
  9958. <li>
  9959. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9960. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9961. </li>
  9962. <li>
  9963. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9964. </li>
  9965. <li>
  9966. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9967. </li>
  9968. </ul>
  9969. <p>If multiple modules implement this callback, they will be considered in order. If a
  9970. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9971. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  9972. be used. If this happens, Synapse will not call any of the subsequent implementations of
  9973. this callback.</p>
  9974. <h3 id="user_may_publish_room"><a class="header" href="#user_may_publish_room"><code>user_may_publish_room</code></a></h3>
  9975. <p><em>First introduced in Synapse v1.37.0</em></p>
  9976. <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>
  9977. <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]
  9978. </code></pre>
  9979. <p>Called when trying to publish a room to the homeserver's public rooms directory.</p>
  9980. <p>The callback must return one of:</p>
  9981. <ul>
  9982. <li>
  9983. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  9984. decide to reject it.</p>
  9985. </li>
  9986. <li>
  9987. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  9988. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  9989. </li>
  9990. <li>
  9991. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  9992. </li>
  9993. <li>
  9994. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  9995. </li>
  9996. </ul>
  9997. <p>If multiple modules implement this callback, they will be considered in order. If a
  9998. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  9999. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  10000. be used. If this happens, Synapse will not call any of the subsequent implementations of
  10001. this callback.</p>
  10002. <h3 id="check_username_for_spam"><a class="header" href="#check_username_for_spam"><code>check_username_for_spam</code></a></h3>
  10003. <p><em>First introduced in Synapse v1.37.0</em></p>
  10004. <pre><code class="language-python">async def check_username_for_spam(user_profile: synapse.module_api.UserProfile) -&gt; bool
  10005. </code></pre>
  10006. <p>Called when computing search results in the user directory. The module must return a
  10007. <code>bool</code> indicating whether the given user should be excluded from user directory
  10008. searches. Return <code>True</code> to indicate that the user is spammy and exclude them from
  10009. search results; otherwise return <code>False</code>.</p>
  10010. <p>The profile is represented as a dictionary with the following keys:</p>
  10011. <ul>
  10012. <li><code>user_id: str</code>. The Matrix ID for this user.</li>
  10013. <li><code>display_name: Optional[str]</code>. The user's display name, or <code>None</code> if this user
  10014. has not set a display name.</li>
  10015. <li><code>avatar_url: Optional[str]</code>. The <code>mxc://</code> URL to the user's avatar, or <code>None</code>
  10016. if this user has not set an avatar.</li>
  10017. </ul>
  10018. <p>The module is given a copy of the original dictionary, so modifying it from within the
  10019. module cannot modify a user's profile when included in user directory search results.</p>
  10020. <p>If multiple modules implement this callback, they will be considered in order. If a
  10021. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  10022. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  10023. any of the subsequent implementations of this callback.</p>
  10024. <h3 id="check_registration_for_spam"><a class="header" href="#check_registration_for_spam"><code>check_registration_for_spam</code></a></h3>
  10025. <p><em>First introduced in Synapse v1.37.0</em></p>
  10026. <pre><code class="language-python">async def check_registration_for_spam(
  10027. email_threepid: Optional[dict],
  10028. username: Optional[str],
  10029. request_info: Collection[Tuple[str, str]],
  10030. auth_provider_id: Optional[str] = None,
  10031. ) -&gt; &quot;synapse.spam_checker_api.RegistrationBehaviour&quot;
  10032. </code></pre>
  10033. <p>Called when registering a new user. The module must return a <code>RegistrationBehaviour</code>
  10034. indicating whether the registration can go through or must be denied, or whether the user
  10035. may be allowed to register but will be shadow banned.</p>
  10036. <p>The arguments passed to this callback are:</p>
  10037. <ul>
  10038. <li><code>email_threepid</code>: The email address used for registering, if any.</li>
  10039. <li><code>username</code>: The username the user would like to register. Can be <code>None</code>, meaning that
  10040. Synapse will generate one later.</li>
  10041. <li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
  10042. second item is an IP address. These user agents and IP addresses are the ones that were
  10043. used during the registration process.</li>
  10044. <li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
  10045. </ul>
  10046. <p>If multiple modules implement this callback, they will be considered in order. If a
  10047. callback returns <code>RegistrationBehaviour.ALLOW</code>, Synapse falls through to the next one.
  10048. The value of the first callback that does not return <code>RegistrationBehaviour.ALLOW</code> will
  10049. be used. If this happens, Synapse will not call any of the subsequent implementations of
  10050. this callback.</p>
  10051. <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>
  10052. <p><em>First introduced in Synapse v1.37.0</em></p>
  10053. <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>
  10054. <pre><code class="language-python">async def check_media_file_for_spam(
  10055. file_wrapper: &quot;synapse.media.media_storage.ReadableFileWrapper&quot;,
  10056. file_info: &quot;synapse.media._base.FileInfo&quot;,
  10057. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
  10058. </code></pre>
  10059. <p>Called when storing a local or remote file.</p>
  10060. <p>The callback must return one of:</p>
  10061. <ul>
  10062. <li>
  10063. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  10064. decide to reject it.</p>
  10065. </li>
  10066. <li>
  10067. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  10068. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  10069. </li>
  10070. <li>
  10071. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  10072. </li>
  10073. <li>
  10074. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  10075. </li>
  10076. </ul>
  10077. <p>If multiple modules implement this callback, they will be considered in order. If a
  10078. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  10079. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  10080. be used. If this happens, Synapse will not call any of the subsequent implementations of
  10081. this callback.</p>
  10082. <h3 id="should_drop_federated_event"><a class="header" href="#should_drop_federated_event"><code>should_drop_federated_event</code></a></h3>
  10083. <p><em>First introduced in Synapse v1.60.0</em></p>
  10084. <pre><code class="language-python">async def should_drop_federated_event(event: &quot;synapse.events.EventBase&quot;) -&gt; bool
  10085. </code></pre>
  10086. <p>Called when checking whether a remote server can federate an event with us. <strong>Returning
  10087. <code>True</code> from this function will silently drop a federated event and split-brain our view
  10088. of a room's DAG, and thus you shouldn't use this callback unless you know what you are
  10089. doing.</strong></p>
  10090. <p>If multiple modules implement this callback, they will be considered in order. If a
  10091. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  10092. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  10093. any of the subsequent implementations of this callback.</p>
  10094. <h3 id="check_login_for_spam"><a class="header" href="#check_login_for_spam"><code>check_login_for_spam</code></a></h3>
  10095. <p><em>First introduced in Synapse v1.87.0</em></p>
  10096. <pre><code class="language-python">async def check_login_for_spam(
  10097. user_id: str,
  10098. device_id: Optional[str],
  10099. initial_display_name: Optional[str],
  10100. request_info: Collection[Tuple[Optional[str], str]],
  10101. auth_provider_id: Optional[str] = None,
  10102. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;]
  10103. </code></pre>
  10104. <p>Called when a user logs in.</p>
  10105. <p>The arguments passed to this callback are:</p>
  10106. <ul>
  10107. <li><code>user_id</code>: The user ID the user is logging in with</li>
  10108. <li><code>device_id</code>: The device ID the user is re-logging into.</li>
  10109. <li><code>initial_display_name</code>: The device display name, if any.</li>
  10110. <li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
  10111. second item is an IP address. These user agents and IP addresses are the ones that were
  10112. used during the login process.</li>
  10113. <li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
  10114. </ul>
  10115. <p>If multiple modules implement this callback, they will be considered in order. If a
  10116. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  10117. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  10118. be used. If this happens, Synapse will not call any of the subsequent implementations of
  10119. this callback.</p>
  10120. <p><em>Note:</em> This will not be called when a user registers.</p>
  10121. <h2 id="example"><a class="header" href="#example">Example</a></h2>
  10122. <p>The example below is a module that implements the spam checker callback
  10123. <code>check_event_for_spam</code> to deny any message sent by users whose Matrix user IDs are
  10124. mentioned in a configured list, and registers a web resource to the path
  10125. <code>/_synapse/client/list_spam_checker/is_evil</code> that returns a JSON object indicating
  10126. whether the provided user appears in that list.</p>
  10127. <pre><code class="language-python">import json
  10128. from typing import Union
  10129. from twisted.web.resource import Resource
  10130. from twisted.web.server import Request
  10131. from synapse.module_api import ModuleApi
  10132. class IsUserEvilResource(Resource):
  10133. def __init__(self, config):
  10134. super(IsUserEvilResource, self).__init__()
  10135. self.evil_users = config.get(&quot;evil_users&quot;) or []
  10136. def render_GET(self, request: Request):
  10137. user = request.args.get(b&quot;user&quot;)[0].decode()
  10138. request.setHeader(b&quot;Content-Type&quot;, b&quot;application/json&quot;)
  10139. return json.dumps({&quot;evil&quot;: user in self.evil_users}).encode()
  10140. class ListSpamChecker:
  10141. def __init__(self, config: dict, api: ModuleApi):
  10142. self.api = api
  10143. self.evil_users = config.get(&quot;evil_users&quot;) or []
  10144. self.api.register_spam_checker_callbacks(
  10145. check_event_for_spam=self.check_event_for_spam,
  10146. )
  10147. self.api.register_web_resource(
  10148. path=&quot;/_synapse/client/list_spam_checker/is_evil&quot;,
  10149. resource=IsUserEvilResource(config),
  10150. )
  10151. async def check_event_for_spam(self, event: &quot;synapse.events.EventBase&quot;) -&gt; Union[Literal[&quot;NOT_SPAM&quot;], Codes]:
  10152. if event.sender in self.evil_users:
  10153. return Codes.FORBIDDEN
  10154. else:
  10155. return synapse.module_api.NOT_SPAM
  10156. </code></pre>
  10157. <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>
  10158. <p>Third party rules callbacks allow module developers to add extra checks to verify the
  10159. validity of incoming events. Third party event rules callbacks can be registered using
  10160. the module API's <code>register_third_party_rules_callbacks</code> method.</p>
  10161. <h2 id="callbacks-1"><a class="header" href="#callbacks-1">Callbacks</a></h2>
  10162. <p>The available third party rules callbacks are:</p>
  10163. <h3 id="check_event_allowed"><a class="header" href="#check_event_allowed"><code>check_event_allowed</code></a></h3>
  10164. <p><em>First introduced in Synapse v1.39.0</em></p>
  10165. <pre><code class="language-python">async def check_event_allowed(
  10166. event: &quot;synapse.events.EventBase&quot;,
  10167. state_events: &quot;synapse.types.StateMap&quot;,
  10168. ) -&gt; Tuple[bool, Optional[dict]]
  10169. </code></pre>
  10170. <p><strong><span style="color:red">
  10171. This callback is very experimental and can and will break without notice. Module developers
  10172. are encouraged to implement <code>check_event_for_spam</code> from the spam checker category instead.
  10173. </span></strong></p>
  10174. <p>Called when processing any incoming event, with the event and a <code>StateMap</code>
  10175. representing the current state of the room the event is being sent into. A <code>StateMap</code> is
  10176. a dictionary that maps tuples containing an event type and a state key to the
  10177. corresponding state event. For example retrieving the room's <code>m.room.create</code> event from
  10178. the <code>state_events</code> argument would look like this: <code>state_events.get((&quot;m.room.create&quot;, &quot;&quot;))</code>.
  10179. The module must return a boolean indicating whether the event can be allowed.</p>
  10180. <p>Note that this callback function processes incoming events coming via federation
  10181. traffic (on top of client traffic). This means denying an event might cause the local
  10182. copy of the room's history to diverge from that of remote servers. This may cause
  10183. federation issues in the room. It is strongly recommended to only deny events using this
  10184. callback function if the sender is a local user, or in a private federation in which all
  10185. servers are using the same module, with the same configuration.</p>
  10186. <p>If the boolean returned by the module is <code>True</code>, it may also tell Synapse to replace the
  10187. event with new data by returning the new event's data as a dictionary. In order to do
  10188. that, it is recommended the module calls <code>event.get_dict()</code> to get the current event as a
  10189. dictionary, and modify the returned dictionary accordingly.</p>
  10190. <p>If <code>check_event_allowed</code> raises an exception, the module is assumed to have failed.
  10191. The event will not be accepted but is not treated as explicitly rejected, either.
  10192. An HTTP request causing the module check will likely result in a 500 Internal
  10193. Server Error.</p>
  10194. <p>When the boolean returned by the module is <code>False</code>, the event is rejected.
  10195. (Module developers should not use exceptions for rejection.)</p>
  10196. <p>Note that replacing the event only works for events sent by local users, not for events
  10197. received over federation.</p>
  10198. <p>If multiple modules implement this callback, they will be considered in order. If a
  10199. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10200. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10201. any of the subsequent implementations of this callback.</p>
  10202. <h3 id="on_create_room"><a class="header" href="#on_create_room"><code>on_create_room</code></a></h3>
  10203. <p><em>First introduced in Synapse v1.39.0</em></p>
  10204. <pre><code class="language-python">async def on_create_room(
  10205. requester: &quot;synapse.types.Requester&quot;,
  10206. request_content: dict,
  10207. is_requester_admin: bool,
  10208. ) -&gt; None
  10209. </code></pre>
  10210. <p>Called when processing a room creation request, with the <code>Requester</code> object for the user
  10211. performing the request, a dictionary representing the room creation request's JSON body
  10212. (see <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom">the spec</a>
  10213. for a list of possible parameters), and a boolean indicating whether the user performing
  10214. the request is a server admin.</p>
  10215. <p>Modules can modify the <code>request_content</code> (by e.g. adding events to its <code>initial_state</code>),
  10216. or deny the room's creation by raising a <code>module_api.errors.SynapseError</code>.</p>
  10217. <p>If multiple modules implement this callback, they will be considered in order. If a
  10218. callback returns without raising an exception, Synapse falls through to the next one. The
  10219. room creation will be forbidden as soon as one of the callbacks raises an exception. If
  10220. this happens, Synapse will not call any of the subsequent implementations of this
  10221. callback.</p>
  10222. <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>
  10223. <p><em>First introduced in Synapse v1.39.0</em></p>
  10224. <pre><code class="language-python">async def check_threepid_can_be_invited(
  10225. medium: str,
  10226. address: str,
  10227. state_events: &quot;synapse.types.StateMap&quot;,
  10228. ) -&gt; bool:
  10229. </code></pre>
  10230. <p>Called when processing an invite via a third-party identifier (i.e. email or phone number).
  10231. The module must return a boolean indicating whether the invite can go through.</p>
  10232. <p>If multiple modules implement this callback, they will be considered in order. If a
  10233. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10234. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10235. any of the subsequent implementations of this callback.</p>
  10236. <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>
  10237. <p><em>First introduced in Synapse v1.39.0</em></p>
  10238. <pre><code class="language-python">async def check_visibility_can_be_modified(
  10239. room_id: str,
  10240. state_events: &quot;synapse.types.StateMap&quot;,
  10241. new_visibility: str,
  10242. ) -&gt; bool:
  10243. </code></pre>
  10244. <p>Called when changing the visibility of a room in the local public room directory. The
  10245. visibility is a string that's either &quot;public&quot; or &quot;private&quot;. The module must return a
  10246. boolean indicating whether the change can go through.</p>
  10247. <p>If multiple modules implement this callback, they will be considered in order. If a
  10248. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10249. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10250. any of the subsequent implementations of this callback.</p>
  10251. <h3 id="on_new_event"><a class="header" href="#on_new_event"><code>on_new_event</code></a></h3>
  10252. <p><em>First introduced in Synapse v1.47.0</em></p>
  10253. <pre><code class="language-python">async def on_new_event(
  10254. event: &quot;synapse.events.EventBase&quot;,
  10255. state_events: &quot;synapse.types.StateMap&quot;,
  10256. ) -&gt; None:
  10257. </code></pre>
  10258. <p>Called after sending an event into a room. The module is passed the event, as well
  10259. as the state of the room <em>after</em> the event. This means that if the event is a state event,
  10260. it will be included in this state.</p>
  10261. <p>Note that this callback is called when the event has already been processed and stored
  10262. into the room, which means this callback cannot be used to deny persisting the event. To
  10263. 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>
  10264. <p>For any given event, this callback will be called on every worker process, even if that worker will not end up
  10265. acting on that event. This callback will not be called for events that are marked as rejected.</p>
  10266. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10267. <h3 id="check_can_shutdown_room"><a class="header" href="#check_can_shutdown_room"><code>check_can_shutdown_room</code></a></h3>
  10268. <p><em>First introduced in Synapse v1.55.0</em></p>
  10269. <pre><code class="language-python">async def check_can_shutdown_room(
  10270. user_id: str, room_id: str,
  10271. ) -&gt; bool:
  10272. </code></pre>
  10273. <p>Called when an admin user requests the shutdown of a room. The module must return a
  10274. boolean indicating whether the shutdown can go through. If the callback returns <code>False</code>,
  10275. the shutdown will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
  10276. <p>If multiple modules implement this callback, they will be considered in order. If a
  10277. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10278. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10279. any of the subsequent implementations of this callback.</p>
  10280. <h3 id="check_can_deactivate_user"><a class="header" href="#check_can_deactivate_user"><code>check_can_deactivate_user</code></a></h3>
  10281. <p><em>First introduced in Synapse v1.55.0</em></p>
  10282. <pre><code class="language-python">async def check_can_deactivate_user(
  10283. user_id: str, by_admin: bool,
  10284. ) -&gt; bool:
  10285. </code></pre>
  10286. <p>Called when the deactivation of a user is requested. User deactivation can be
  10287. performed by an admin or the user themselves, so developers are encouraged to check the
  10288. requester when implementing this callback. The module must return a
  10289. boolean indicating whether the deactivation can go through. If the callback returns <code>False</code>,
  10290. the deactivation will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
  10291. <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>
  10292. <p>If multiple modules implement this callback, they will be considered in order. If a
  10293. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10294. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10295. any of the subsequent implementations of this callback.</p>
  10296. <h3 id="on_profile_update"><a class="header" href="#on_profile_update"><code>on_profile_update</code></a></h3>
  10297. <p><em>First introduced in Synapse v1.54.0</em></p>
  10298. <pre><code class="language-python">async def on_profile_update(
  10299. user_id: str,
  10300. new_profile: &quot;synapse.module_api.ProfileInfo&quot;,
  10301. by_admin: bool,
  10302. deactivation: bool,
  10303. ) -&gt; None:
  10304. </code></pre>
  10305. <p>Called after updating a local user's profile. The update can be triggered either by the
  10306. user themselves or a server admin. The update can also be triggered by a user being
  10307. deactivated (in which case their display name is set to an empty string (<code>&quot;&quot;</code>) and the
  10308. avatar URL is set to <code>None</code>). The module is passed the Matrix ID of the user whose profile
  10309. has been updated, their new profile, as well as a <code>by_admin</code> boolean that is <code>True</code> if the
  10310. update was triggered by a server admin (and <code>False</code> otherwise), and a <code>deactivated</code>
  10311. boolean that is <code>True</code> if the update is a result of the user being deactivated.</p>
  10312. <p>Note that the <code>by_admin</code> boolean is also <code>True</code> if the profile change happens as a result
  10313. of the user logging in through Single Sign-On, or if a server admin updates their own
  10314. profile.</p>
  10315. <p>Per-room profile changes do not trigger this callback to be called. Synapse administrators
  10316. wishing this callback to be called on every profile change are encouraged to disable
  10317. per-room profiles globally using the <code>allow_per_room_profiles</code> configuration setting in
  10318. Synapse's configuration file.
  10319. This callback is not called when registering a user, even when setting it through the
  10320. <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>
  10321. module callback.</p>
  10322. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10323. <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>
  10324. <p><em>First introduced in Synapse v1.54.0</em></p>
  10325. <pre><code class="language-python">async def on_user_deactivation_status_changed(
  10326. user_id: str, deactivated: bool, by_admin: bool
  10327. ) -&gt; None:
  10328. </code></pre>
  10329. <p>Called after deactivating a local user, or reactivating them through the admin API. The
  10330. deactivation can be triggered either by the user themselves or a server admin. The module
  10331. is passed the Matrix ID of the user whose status is changed, as well as a <code>deactivated</code>
  10332. boolean that is <code>True</code> if the user is being deactivated and <code>False</code> if they're being
  10333. reactivated, and a <code>by_admin</code> boolean that is <code>True</code> if the deactivation was triggered by
  10334. a server admin (and <code>False</code> otherwise). This latter <code>by_admin</code> boolean is always <code>True</code>
  10335. if the user is being reactivated, as this operation can only be performed through the
  10336. admin API.</p>
  10337. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10338. <h3 id="on_threepid_bind"><a class="header" href="#on_threepid_bind"><code>on_threepid_bind</code></a></h3>
  10339. <p><em>First introduced in Synapse v1.56.0</em></p>
  10340. <p><strong><span style="color:red">
  10341. This callback is deprecated in favour of the <code>on_add_user_third_party_identifier</code> callback, which
  10342. features the same functionality. The only difference is in name.
  10343. </span></strong></p>
  10344. <pre><code class="language-python">async def on_threepid_bind(user_id: str, medium: str, address: str) -&gt; None:
  10345. </code></pre>
  10346. <p>Called after creating an association between a local user and a third-party identifier
  10347. (email address, phone number). The module is given the Matrix ID of the user the
  10348. association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
  10349. third-party identifier.</p>
  10350. <p>Note that this callback is <em>not</em> called after a successful association on an <em>identity
  10351. server</em>.</p>
  10352. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10353. <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>
  10354. <p><em>First introduced in Synapse v1.79.0</em></p>
  10355. <pre><code class="language-python">async def on_add_user_third_party_identifier(user_id: str, medium: str, address: str) -&gt; None:
  10356. </code></pre>
  10357. <p>Called after successfully creating an association between a user and a third-party identifier
  10358. (email address, phone number). The module is given the Matrix ID of the user the
  10359. association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
  10360. third-party identifier (i.e. an email address).</p>
  10361. <p>Note that this callback is <em>not</em> called if a user attempts to bind their third-party identifier
  10362. 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>
  10363. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10364. <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>
  10365. <p><em>First introduced in Synapse v1.79.0</em></p>
  10366. <pre><code class="language-python">async def on_remove_user_third_party_identifier(user_id: str, medium: str, address: str) -&gt; None:
  10367. </code></pre>
  10368. <p>Called after successfully removing an association between a user and a third-party identifier
  10369. (email address, phone number). The module is given the Matrix ID of the user the
  10370. association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
  10371. third-party identifier (i.e. an email address).</p>
  10372. <p>Note that this callback is <em>not</em> called if a user attempts to unbind their third-party
  10373. 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>
  10374. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10375. <h2 id="example-1"><a class="header" href="#example-1">Example</a></h2>
  10376. <p>The example below is a module that implements the third-party rules callback
  10377. <code>check_event_allowed</code> to censor incoming messages as dictated by a third-party service.</p>
  10378. <pre><code class="language-python">from typing import Optional, Tuple
  10379. from synapse.module_api import ModuleApi
  10380. _DEFAULT_CENSOR_ENDPOINT = &quot;https://my-internal-service.local/censor-event&quot;
  10381. class EventCensorer:
  10382. def __init__(self, config: dict, api: ModuleApi):
  10383. self.api = api
  10384. self._endpoint = config.get(&quot;endpoint&quot;, _DEFAULT_CENSOR_ENDPOINT)
  10385. self.api.register_third_party_rules_callbacks(
  10386. check_event_allowed=self.check_event_allowed,
  10387. )
  10388. async def check_event_allowed(
  10389. self,
  10390. event: &quot;synapse.events.EventBase&quot;,
  10391. state_events: &quot;synapse.types.StateMap&quot;,
  10392. ) -&gt; Tuple[bool, Optional[dict]]:
  10393. event_dict = event.get_dict()
  10394. new_event_content = await self.api.http_client.post_json_get_json(
  10395. uri=self._endpoint, post_json=event_dict,
  10396. )
  10397. event_dict[&quot;content&quot;] = new_event_content
  10398. return event_dict
  10399. </code></pre>
  10400. <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>
  10401. <p>Presence router callbacks allow module developers to specify additional users (local or remote)
  10402. to receive certain presence updates from local users. Presence router callbacks can be
  10403. registered using the module API's <code>register_presence_router_callbacks</code> method.</p>
  10404. <h2 id="callbacks-2"><a class="header" href="#callbacks-2">Callbacks</a></h2>
  10405. <p>The available presence router callbacks are:</p>
  10406. <h3 id="get_users_for_states"><a class="header" href="#get_users_for_states"><code>get_users_for_states</code></a></h3>
  10407. <p><em>First introduced in Synapse v1.42.0</em></p>
  10408. <pre><code class="language-python">async def get_users_for_states(
  10409. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  10410. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]
  10411. </code></pre>
  10412. <p><strong>Requires</strong> <code>get_interested_users</code> to also be registered</p>
  10413. <p>Called when processing updates to the presence state of one or more users. This callback can
  10414. be used to instruct the server to forward that presence state to specific users. The module
  10415. must return a dictionary that maps from Matrix user IDs (which can be local or remote) to the
  10416. <code>UserPresenceState</code> changes that they should be forwarded.</p>
  10417. <p>Synapse will then attempt to send the specified presence updates to each user when possible.</p>
  10418. <p>If multiple modules implement this callback, Synapse merges all the dictionaries returned
  10419. by the callbacks. If multiple callbacks return a dictionary containing the same key,
  10420. Synapse concatenates the sets associated with this key from each dictionary. </p>
  10421. <h3 id="get_interested_users"><a class="header" href="#get_interested_users"><code>get_interested_users</code></a></h3>
  10422. <p><em>First introduced in Synapse v1.42.0</em></p>
  10423. <pre><code class="language-python">async def get_interested_users(
  10424. user_id: str
  10425. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]
  10426. </code></pre>
  10427. <p><strong>Requires</strong> <code>get_users_for_states</code> to also be registered</p>
  10428. <p>Called when determining which users someone should be able to see the presence state of. This
  10429. callback should return complementary results to <code>get_users_for_state</code> or the presence information
  10430. may not be properly forwarded.</p>
  10431. <p>The callback is given the Matrix user ID for a local user that is requesting presence data and
  10432. should return the Matrix user IDs of the users whose presence state they are allowed to
  10433. query. The returned users can be local or remote. </p>
  10434. <p>Alternatively the callback can return <code>synapse.module_api.PRESENCE_ALL_USERS</code>
  10435. to indicate that the user should receive updates from all known users.</p>
  10436. <p>If multiple modules implement this callback, they will be considered in order. Synapse
  10437. calls each callback one by one, and use a concatenation of all the <code>set</code>s returned by the
  10438. callbacks. If one callback returns <code>synapse.module_api.PRESENCE_ALL_USERS</code>, Synapse uses
  10439. this value instead. If this happens, Synapse does not call any of the subsequent
  10440. implementations of this callback.</p>
  10441. <h2 id="example-2"><a class="header" href="#example-2">Example</a></h2>
  10442. <p>The example below is a module that implements both presence router callbacks, and ensures
  10443. that <code>@alice:example.org</code> receives all presence updates from <code>@bob:example.com</code> and
  10444. <code>@charlie:somewhere.org</code>, regardless of whether Alice shares a room with any of them.</p>
  10445. <pre><code class="language-python">from typing import Dict, Iterable, Set, Union
  10446. from synapse.module_api import ModuleApi
  10447. class CustomPresenceRouter:
  10448. def __init__(self, config: dict, api: ModuleApi):
  10449. self.api = api
  10450. self.api.register_presence_router_callbacks(
  10451. get_users_for_states=self.get_users_for_states,
  10452. get_interested_users=self.get_interested_users,
  10453. )
  10454. async def get_users_for_states(
  10455. self,
  10456. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  10457. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]:
  10458. res = {}
  10459. for update in state_updates:
  10460. if (
  10461. update.user_id == &quot;@bob:example.com&quot;
  10462. or update.user_id == &quot;@charlie:somewhere.org&quot;
  10463. ):
  10464. res.setdefault(&quot;@alice:example.com&quot;, set()).add(update)
  10465. return res
  10466. async def get_interested_users(
  10467. self,
  10468. user_id: str,
  10469. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]:
  10470. if user_id == &quot;@alice:example.com&quot;:
  10471. return {&quot;@bob:example.com&quot;, &quot;@charlie:somewhere.org&quot;}
  10472. return set()
  10473. </code></pre>
  10474. <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>
  10475. <p>Account validity callbacks allow module developers to add extra steps to verify the
  10476. validity on an account, i.e. see if a user can be granted access to their account on the
  10477. Synapse instance. Account validity callbacks can be registered using the module API's
  10478. <code>register_account_validity_callbacks</code> method.</p>
  10479. <p>The available account validity callbacks are:</p>
  10480. <h3 id="is_user_expired"><a class="header" href="#is_user_expired"><code>is_user_expired</code></a></h3>
  10481. <p><em>First introduced in Synapse v1.39.0</em></p>
  10482. <pre><code class="language-python">async def is_user_expired(user: str) -&gt; Optional[bool]
  10483. </code></pre>
  10484. <p>Called when processing any authenticated request (except for logout requests). The module
  10485. can return a <code>bool</code> to indicate whether the user has expired and should be locked out of
  10486. their account, or <code>None</code> if the module wasn't able to figure it out. The user is
  10487. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  10488. <p>If the module returns <code>True</code>, the current request will be denied with the error code
  10489. <code>ORG_MATRIX_EXPIRED_ACCOUNT</code> and the HTTP status code 403. Note that this doesn't
  10490. invalidate the user's access token.</p>
  10491. <p>If multiple modules implement this callback, they will be considered in order. If a
  10492. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  10493. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  10494. any of the subsequent implementations of this callback.</p>
  10495. <h3 id="on_user_registration"><a class="header" href="#on_user_registration"><code>on_user_registration</code></a></h3>
  10496. <p><em>First introduced in Synapse v1.39.0</em></p>
  10497. <pre><code class="language-python">async def on_user_registration(user: str) -&gt; None
  10498. </code></pre>
  10499. <p>Called after successfully registering a user, in case the module needs to perform extra
  10500. operations to keep track of them. (e.g. add them to a database table). The user is
  10501. represented by their Matrix user ID.</p>
  10502. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10503. <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>
  10504. <p>Password auth providers offer a way for server administrators to integrate
  10505. their Synapse installation with an external authentication system. The callbacks can be
  10506. registered by using the Module API's <code>register_password_auth_provider_callbacks</code> method.</p>
  10507. <h2 id="callbacks-3"><a class="header" href="#callbacks-3">Callbacks</a></h2>
  10508. <h3 id="auth_checkers"><a class="header" href="#auth_checkers"><code>auth_checkers</code></a></h3>
  10509. <p><em>First introduced in Synapse v1.46.0</em></p>
  10510. <pre><code class="language-python">auth_checkers: Dict[Tuple[str, Tuple[str, ...]], Callable]
  10511. </code></pre>
  10512. <p>A dict mapping from tuples of a login type identifier (such as <code>m.login.password</code>) and a
  10513. tuple of field names (such as <code>(&quot;password&quot;, &quot;secret_thing&quot;)</code>) to authentication checking
  10514. callbacks, which should be of the following form:</p>
  10515. <pre><code class="language-python">async def check_auth(
  10516. user: str,
  10517. login_type: str,
  10518. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  10519. ) -&gt; Optional[
  10520. Tuple[
  10521. str,
  10522. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  10523. ]
  10524. ]
  10525. </code></pre>
  10526. <p>The login type and field names should be provided by the user in the
  10527. request to the <code>/login</code> API. <a href="https://matrix.org/docs/spec/client_server/latest#authentication-types">The Matrix specification</a>
  10528. defines some types, however user defined ones are also allowed.</p>
  10529. <p>The callback is passed the <code>user</code> field provided by the client (which might not be in
  10530. <code>@username:server</code> form), the login type, and a dictionary of login secrets passed by
  10531. the client.</p>
  10532. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  10533. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the
  10534. <code>/login</code> request. If the module doesn't wish to return a callback, it must return <code>None</code>
  10535. instead.</p>
  10536. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  10537. <p>Note that the user is not automatically registered, the <code>register_user(..)</code> method of
  10538. the <a href="modules/writing_a_module.html">module API</a> can be used to lazily create users.</p>
  10539. <p>If multiple modules register an auth checker for the same login type but with different
  10540. fields, Synapse will refuse to start.</p>
  10541. <p>If multiple modules register an auth checker for the same login type with the same fields,
  10542. then the callbacks will be executed in order, until one returns a Matrix User ID (and
  10543. optionally a callback). In that case, the return value of that callback will be accepted
  10544. and subsequent callbacks will not be fired. If every callback returns <code>None</code>, then the
  10545. authentication fails.</p>
  10546. <h3 id="check_3pid_auth"><a class="header" href="#check_3pid_auth"><code>check_3pid_auth</code></a></h3>
  10547. <p><em>First introduced in Synapse v1.46.0</em></p>
  10548. <pre><code class="language-python">async def check_3pid_auth(
  10549. medium: str,
  10550. address: str,
  10551. password: str,
  10552. ) -&gt; Optional[
  10553. Tuple[
  10554. str,
  10555. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  10556. ]
  10557. ]
  10558. </code></pre>
  10559. <p>Called when a user attempts to register or log in with a third party identifier,
  10560. such as email. It is passed the medium (eg. <code>email</code>), an address (eg. <code>jdoe@example.com</code>)
  10561. and the user's password.</p>
  10562. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  10563. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the <code>/login</code> request.
  10564. If the module doesn't wish to return a callback, it must return None instead.</p>
  10565. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  10566. <p>If multiple modules implement this callback, they will be considered in order. If a
  10567. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  10568. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  10569. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  10570. the authentication is denied.</p>
  10571. <h3 id="on_logged_out"><a class="header" href="#on_logged_out"><code>on_logged_out</code></a></h3>
  10572. <p><em>First introduced in Synapse v1.46.0</em></p>
  10573. <pre><code class="language-python">async def on_logged_out(
  10574. user_id: str,
  10575. device_id: Optional[str],
  10576. access_token: str
  10577. ) -&gt; None
  10578. </code></pre>
  10579. <p>Called during a logout request for a user. It is passed the qualified user ID, the ID of the
  10580. deactivated device (if any: access tokens are occasionally created without an associated
  10581. device ID), and the (now deactivated) access token.</p>
  10582. <p>Deleting the related pushers is done after calling <code>on_logged_out</code>, so you can rely on them
  10583. to still be present.</p>
  10584. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10585. <h3 id="get_username_for_registration"><a class="header" href="#get_username_for_registration"><code>get_username_for_registration</code></a></h3>
  10586. <p><em>First introduced in Synapse v1.52.0</em></p>
  10587. <pre><code class="language-python">async def get_username_for_registration(
  10588. uia_results: Dict[str, Any],
  10589. params: Dict[str, Any],
  10590. ) -&gt; Optional[str]
  10591. </code></pre>
  10592. <p>Called when registering a new user. The module can return a username to set for the user
  10593. being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  10594. username for this user. If a username is returned, it will be used as the local part of a
  10595. user's full Matrix ID (e.g. it's <code>alice</code> in <code>@alice:example.com</code>).</p>
  10596. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  10597. has been completed by the user. It is not called when registering a user via SSO. It is
  10598. passed two dictionaries, which include the information that the user has provided during
  10599. the registration process.</p>
  10600. <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>
  10601. flow followed by the user. Its keys are the identifiers of every step involved in the flow,
  10602. associated with either a boolean value indicating whether the step was correctly completed,
  10603. or additional information (e.g. email address, phone number...). A list of most existing
  10604. identifiers can be found in the <a href="https://spec.matrix.org/v1.1/client-server-api/#authentication-types">Matrix specification</a>.
  10605. Here's an example featuring all currently supported keys:</p>
  10606. <pre><code class="language-python">{
  10607. &quot;m.login.dummy&quot;: True, # Dummy authentication
  10608. &quot;m.login.terms&quot;: True, # User has accepted the terms of service for the homeserver
  10609. &quot;m.login.recaptcha&quot;: True, # User has completed the recaptcha challenge
  10610. &quot;m.login.email.identity&quot;: { # User has provided and verified an email address
  10611. &quot;medium&quot;: &quot;email&quot;,
  10612. &quot;address&quot;: &quot;alice@example.com&quot;,
  10613. &quot;validated_at&quot;: 1642701357084,
  10614. },
  10615. &quot;m.login.msisdn&quot;: { # User has provided and verified a phone number
  10616. &quot;medium&quot;: &quot;msisdn&quot;,
  10617. &quot;address&quot;: &quot;33123456789&quot;,
  10618. &quot;validated_at&quot;: 1642701357084,
  10619. },
  10620. &quot;m.login.registration_token&quot;: &quot;sometoken&quot;, # User has registered through a registration token
  10621. }
  10622. </code></pre>
  10623. <p>The second dictionary contains the parameters provided by the user's client in the request
  10624. to <code>/_matrix/client/v3/register</code>. See the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3register">Matrix specification</a>
  10625. for a complete list of these parameters.</p>
  10626. <p>If the module cannot, or does not wish to, generate a username for this user, it must
  10627. return <code>None</code>.</p>
  10628. <p>If multiple modules implement this callback, they will be considered in order. If a
  10629. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  10630. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  10631. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  10632. the username provided by the user is used, if any (otherwise one is automatically
  10633. generated).</p>
  10634. <h3 id="get_displayname_for_registration"><a class="header" href="#get_displayname_for_registration"><code>get_displayname_for_registration</code></a></h3>
  10635. <p><em>First introduced in Synapse v1.54.0</em></p>
  10636. <pre><code class="language-python">async def get_displayname_for_registration(
  10637. uia_results: Dict[str, Any],
  10638. params: Dict[str, Any],
  10639. ) -&gt; Optional[str]
  10640. </code></pre>
  10641. <p>Called when registering a new user. The module can return a display name to set for the
  10642. user being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  10643. display name for this user.</p>
  10644. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  10645. has been completed by the user. It is not called when registering a user via SSO. It is
  10646. passed two dictionaries, which include the information that the user has provided during
  10647. the registration process. These dictionaries are identical to the ones passed to
  10648. <a href="modules/password_auth_provider_callbacks.html#get_username_for_registration"><code>get_username_for_registration</code></a>, so refer to the
  10649. documentation of this callback for more information about them.</p>
  10650. <p>If multiple modules implement this callback, they will be considered in order. If a
  10651. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  10652. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  10653. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  10654. the username will be used (e.g. <code>alice</code> if the user being registered is <code>@alice:example.com</code>).</p>
  10655. <h2 id="is_3pid_allowed"><a class="header" href="#is_3pid_allowed"><code>is_3pid_allowed</code></a></h2>
  10656. <p><em>First introduced in Synapse v1.53.0</em></p>
  10657. <pre><code class="language-python">async def is_3pid_allowed(self, medium: str, address: str, registration: bool) -&gt; bool
  10658. </code></pre>
  10659. <p>Called when attempting to bind a third-party identifier (i.e. an email address or a phone
  10660. number). The module is given the medium of the third-party identifier (which is <code>email</code> if
  10661. the identifier is an email address, or <code>msisdn</code> if the identifier is a phone number) and
  10662. its address, as well as a boolean indicating whether the attempt to bind is happening as
  10663. part of registering a new user. The module must return a boolean indicating whether the
  10664. identifier can be allowed to be bound to an account on the local homeserver.</p>
  10665. <p>If multiple modules implement this callback, they will be considered in order. If a
  10666. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  10667. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  10668. any of the subsequent implementations of this callback.</p>
  10669. <h2 id="example-3"><a class="header" href="#example-3">Example</a></h2>
  10670. <p>The example module below implements authentication checkers for two different login types: </p>
  10671. <ul>
  10672. <li><code>my.login.type</code>
  10673. <ul>
  10674. <li>Expects a <code>my_field</code> field to be sent to <code>/login</code></li>
  10675. <li>Is checked by the method: <code>self.check_my_login</code></li>
  10676. </ul>
  10677. </li>
  10678. <li><code>m.login.password</code> (defined in <a href="https://matrix.org/docs/spec/client_server/latest#password-based">the spec</a>)
  10679. <ul>
  10680. <li>Expects a <code>password</code> field to be sent to <code>/login</code></li>
  10681. <li>Is checked by the method: <code>self.check_pass</code></li>
  10682. </ul>
  10683. </li>
  10684. </ul>
  10685. <pre><code class="language-python">from typing import Awaitable, Callable, Optional, Tuple
  10686. import synapse
  10687. from synapse import module_api
  10688. class MyAuthProvider:
  10689. def __init__(self, config: dict, api: module_api):
  10690. self.api = api
  10691. self.credentials = {
  10692. &quot;bob&quot;: &quot;building&quot;,
  10693. &quot;@scoop:matrix.org&quot;: &quot;digging&quot;,
  10694. }
  10695. api.register_password_auth_provider_callbacks(
  10696. auth_checkers={
  10697. (&quot;my.login_type&quot;, (&quot;my_field&quot;,)): self.check_my_login,
  10698. (&quot;m.login.password&quot;, (&quot;password&quot;,)): self.check_pass,
  10699. },
  10700. )
  10701. async def check_my_login(
  10702. self,
  10703. username: str,
  10704. login_type: str,
  10705. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  10706. ) -&gt; Optional[
  10707. Tuple[
  10708. str,
  10709. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  10710. ]
  10711. ]:
  10712. if login_type != &quot;my.login_type&quot;:
  10713. return None
  10714. if self.credentials.get(username) == login_dict.get(&quot;my_field&quot;):
  10715. return (self.api.get_qualified_user_id(username), None)
  10716. async def check_pass(
  10717. self,
  10718. username: str,
  10719. login_type: str,
  10720. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  10721. ) -&gt; Optional[
  10722. Tuple[
  10723. str,
  10724. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  10725. ]
  10726. ]:
  10727. if login_type != &quot;m.login.password&quot;:
  10728. return None
  10729. if self.credentials.get(username) == login_dict.get(&quot;password&quot;):
  10730. return (self.api.get_qualified_user_id(username), None)
  10731. </code></pre>
  10732. <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>
  10733. <p>Background update controller callbacks allow module developers to control (e.g. rate-limit)
  10734. how database background updates are run. A database background update is an operation
  10735. Synapse runs on its database in the background after it starts. It's usually used to run
  10736. database operations that would take too long if they were run at the same time as schema
  10737. updates (which are run on startup) and delay Synapse's startup too much: populating a
  10738. table with a big amount of data, adding an index on a big table, deleting superfluous data,
  10739. etc.</p>
  10740. <p>Background update controller callbacks can be registered using the module API's
  10741. <code>register_background_update_controller_callbacks</code> method. Only the first module (in order
  10742. of appearance in Synapse's configuration file) calling this method can register background
  10743. update controller callbacks, subsequent calls are ignored.</p>
  10744. <p>The available background update controller callbacks are:</p>
  10745. <h3 id="on_update"><a class="header" href="#on_update"><code>on_update</code></a></h3>
  10746. <p><em>First introduced in Synapse v1.49.0</em></p>
  10747. <pre><code class="language-python">def on_update(update_name: str, database_name: str, one_shot: bool) -&gt; AsyncContextManager[int]
  10748. </code></pre>
  10749. <p>Called when about to do an iteration of a background update. The module is given the name
  10750. of the update, the name of the database, and a flag to indicate whether the background
  10751. update will happen in one go and may take a long time (e.g. creating indices). If this last
  10752. argument is set to <code>False</code>, the update will be run in batches.</p>
  10753. <p>The module must return an async context manager. It will be entered before Synapse runs a
  10754. background update; this should return the desired duration of the iteration, in
  10755. milliseconds.</p>
  10756. <p>The context manager will be exited when the iteration completes. Note that the duration
  10757. returned by the context manager is a target, and an iteration may take substantially longer
  10758. or shorter. If the <code>one_shot</code> flag is set to <code>True</code>, the duration returned is ignored.</p>
  10759. <p><strong>Note</strong>: Unlike most module callbacks in Synapse, this one is <em>synchronous</em>. This is
  10760. because asynchronous operations are expected to be run by the async context manager.</p>
  10761. <p>This callback is required when registering any other background update controller callback.</p>
  10762. <h3 id="default_batch_size"><a class="header" href="#default_batch_size"><code>default_batch_size</code></a></h3>
  10763. <p><em>First introduced in Synapse v1.49.0</em></p>
  10764. <pre><code class="language-python">async def default_batch_size(update_name: str, database_name: str) -&gt; int
  10765. </code></pre>
  10766. <p>Called before the first iteration of a background update, with the name of the update and
  10767. of the database. The module must return the number of elements to process in this first
  10768. iteration.</p>
  10769. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  10770. <h3 id="min_batch_size"><a class="header" href="#min_batch_size"><code>min_batch_size</code></a></h3>
  10771. <p><em>First introduced in Synapse v1.49.0</em></p>
  10772. <pre><code class="language-python">async def min_batch_size(update_name: str, database_name: str) -&gt; int
  10773. </code></pre>
  10774. <p>Called before running a new batch for a background update, with the name of the update and
  10775. of the database. The module must return an integer representing the minimum number of
  10776. elements to process in this iteration. This number must be at least 1, and is used to
  10777. ensure that progress is always made.</p>
  10778. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  10779. <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>
  10780. <p>Account data callbacks allow module developers to react to changes of the account data
  10781. of local users. Account data callbacks can be registered using the module API's
  10782. <code>register_account_data_callbacks</code> method.</p>
  10783. <h2 id="callbacks-4"><a class="header" href="#callbacks-4">Callbacks</a></h2>
  10784. <p>The available account data callbacks are:</p>
  10785. <h3 id="on_account_data_updated"><a class="header" href="#on_account_data_updated"><code>on_account_data_updated</code></a></h3>
  10786. <p><em>First introduced in Synapse v1.57.0</em></p>
  10787. <pre><code class="language-python">async def on_account_data_updated(
  10788. user_id: str,
  10789. room_id: Optional[str],
  10790. account_data_type: str,
  10791. content: &quot;synapse.module_api.JsonDict&quot;,
  10792. ) -&gt; None:
  10793. </code></pre>
  10794. <p>Called after user's account data has been updated. The module is given the
  10795. Matrix ID of the user whose account data is changing, the room ID the data is associated
  10796. with, the type associated with the change, as well as the new content. If the account
  10797. data is not associated with a specific room, then the room ID is <code>None</code>.</p>
  10798. <p>This callback is triggered when new account data is added or when the data associated with
  10799. a given type (and optionally room) changes. This includes deletion, since in Matrix,
  10800. deleting account data consists of replacing the data associated with a given type
  10801. (and optionally room) with an empty dictionary (<code>{}</code>).</p>
  10802. <p>Note that this doesn't trigger when changing the tags associated with a room, as these are
  10803. processed separately by Synapse.</p>
  10804. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  10805. <h2 id="example-4"><a class="header" href="#example-4">Example</a></h2>
  10806. <p>The example below is a module that implements the <code>on_account_data_updated</code> callback, and
  10807. sends an event to an audit room when a user changes their account data.</p>
  10808. <pre><code class="language-python">import json
  10809. import attr
  10810. from typing import Any, Dict, Optional
  10811. from synapse.module_api import JsonDict, ModuleApi
  10812. from synapse.module_api.errors import ConfigError
  10813. @attr.s(auto_attribs=True)
  10814. class CustomAccountDataConfig:
  10815. audit_room: str
  10816. sender: str
  10817. class CustomAccountDataModule:
  10818. def __init__(self, config: CustomAccountDataConfig, api: ModuleApi):
  10819. self.api = api
  10820. self.config = config
  10821. self.api.register_account_data_callbacks(
  10822. on_account_data_updated=self.log_new_account_data,
  10823. )
  10824. @staticmethod
  10825. def parse_config(config: Dict[str, Any]) -&gt; CustomAccountDataConfig:
  10826. def check_in_config(param: str):
  10827. if param not in config:
  10828. raise ConfigError(f&quot;'{param}' is required&quot;)
  10829. check_in_config(&quot;audit_room&quot;)
  10830. check_in_config(&quot;sender&quot;)
  10831. return CustomAccountDataConfig(
  10832. audit_room=config[&quot;audit_room&quot;],
  10833. sender=config[&quot;sender&quot;],
  10834. )
  10835. async def log_new_account_data(
  10836. self,
  10837. user_id: str,
  10838. room_id: Optional[str],
  10839. account_data_type: str,
  10840. content: JsonDict,
  10841. ) -&gt; None:
  10842. content_raw = json.dumps(content)
  10843. msg_content = f&quot;{user_id} has changed their account data for type {account_data_type} to: {content_raw}&quot;
  10844. if room_id is not None:
  10845. msg_content += f&quot; (in room {room_id})&quot;
  10846. await self.api.create_and_send_event_into_room(
  10847. {
  10848. &quot;room_id&quot;: self.config.audit_room,
  10849. &quot;sender&quot;: self.config.sender,
  10850. &quot;type&quot;: &quot;m.room.message&quot;,
  10851. &quot;content&quot;: {
  10852. &quot;msgtype&quot;: &quot;m.text&quot;,
  10853. &quot;body&quot;: msg_content
  10854. }
  10855. }
  10856. )
  10857. </code></pre>
  10858. <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>
  10859. <p>In order to port a module that uses Synapse's old module interface, its author needs to:</p>
  10860. <ul>
  10861. <li>ensure the module's callbacks are all asynchronous.</li>
  10862. <li>register their callbacks using one or more of the <code>register_[...]_callbacks</code> methods
  10863. 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>
  10864. for more info).</li>
  10865. </ul>
  10866. <p>Additionally, if the module is packaged with an additional web resource, the module
  10867. should register this resource in its <code>__init__</code> method using the <code>register_web_resource</code>
  10868. method from the <code>ModuleApi</code> class (see <a href="modules/writing_a_module.html#registering-a-web-resource">this section</a> for
  10869. more info).</p>
  10870. <p>There is no longer a <code>get_db_schema_files</code> callback provided for password auth provider modules. Any
  10871. changes to the database should now be made by the module using the module API class.</p>
  10872. <p>The module's author should also update any example in the module's configuration to only
  10873. use the new <code>modules</code> section in Synapse's configuration file (see <a href="modules/index.html#using-modules">this section</a>
  10874. for more info).</p>
  10875. <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>
  10876. <p>For small instances it is recommended to run Synapse in the default monolith mode.
  10877. For larger instances where performance is a concern it can be helpful to split
  10878. out functionality into multiple separate python processes. These processes are
  10879. called 'workers', and are (eventually) intended to scale horizontally
  10880. independently.</p>
  10881. <p>Synapse's worker support is under active development and subject to change as
  10882. we attempt to rapidly scale ever larger Synapse instances. However we are
  10883. documenting it here to help admins needing a highly scalable Synapse instance
  10884. similar to the one running <code>matrix.org</code>.</p>
  10885. <p>All processes continue to share the same database instance, and as such,
  10886. workers only work with PostgreSQL-based Synapse deployments. SQLite should only
  10887. be used for demo purposes and any admin considering workers should already be
  10888. running PostgreSQL.</p>
  10889. <p>See also <a href="https://matrix.org/blog/2020/11/03/how-we-fixed-synapses-scalability">Matrix.org blog post</a>
  10890. for a higher level overview.</p>
  10891. <h2 id="main-processworker-communication"><a class="header" href="#main-processworker-communication">Main process/worker communication</a></h2>
  10892. <p>The processes communicate with each other via a Synapse-specific protocol called
  10893. 'replication' (analogous to MySQL- or Postgres-style database replication) which
  10894. feeds streams of newly written data between processes so they can be kept in
  10895. sync with the database state.</p>
  10896. <p>When configured to do so, Synapse uses a
  10897. <a href="https://redis.io/docs/manual/pubsub/">Redis pub/sub channel</a> to send the replication
  10898. stream between all configured Synapse processes. Additionally, processes may
  10899. make HTTP requests to each other, primarily for operations which need to wait
  10900. for a reply ─ such as sending an event.</p>
  10901. <p>All the workers and the main process connect to Redis, which relays replication
  10902. commands between processes.</p>
  10903. <p>If Redis support is enabled Synapse will use it as a shared cache, as well as a
  10904. pub/sub mechanism.</p>
  10905. <p>See the <a href="workers.html#architectural-diagram">Architectural diagram</a> section at the end for
  10906. a visualisation of what this looks like.</p>
  10907. <h2 id="setting-up-workers"><a class="header" href="#setting-up-workers">Setting up workers</a></h2>
  10908. <p>A Redis server is required to manage the communication between the processes.
  10909. The Redis server should be installed following the normal procedure for your
  10910. distribution (e.g. <code>apt install redis-server</code> on Debian). It is safe to use an
  10911. existing Redis deployment if you have one.</p>
  10912. <p>Once installed, check that Redis is running and accessible from the host running
  10913. Synapse, for example by executing <code>echo PING | nc -q1 localhost 6379</code> and seeing
  10914. a response of <code>+PONG</code>.</p>
  10915. <p>The appropriate dependencies must also be installed for Synapse. If using a
  10916. virtualenv, these can be installed with:</p>
  10917. <pre><code class="language-sh">pip install &quot;matrix-synapse[redis]&quot;
  10918. </code></pre>
  10919. <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
  10920. <code>matrix.org</code> and in the docker images at
  10921. https://hub.docker.com/r/matrixdotorg/synapse/.</p>
  10922. <p>To make effective use of the workers, you will need to configure an HTTP
  10923. reverse-proxy such as nginx or haproxy, which will direct incoming requests to
  10924. the correct worker, or to the main synapse instance. See
  10925. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a reverse
  10926. proxy.</p>
  10927. <p>When using workers, each worker process has its own configuration file which
  10928. contains settings specific to that worker, such as the HTTP listener that it
  10929. provides (if any), logging configuration, etc.</p>
  10930. <p>Normally, the worker processes are configured to read from a shared
  10931. configuration file as well as the worker-specific configuration files. This
  10932. makes it easier to keep common configuration settings synchronised across all
  10933. the processes.</p>
  10934. <p>The main process is somewhat special in this respect: it does not normally
  10935. need its own configuration file and can take all of its configuration from the
  10936. shared configuration file.</p>
  10937. <h3 id="shared-configuration"><a class="header" href="#shared-configuration">Shared configuration</a></h3>
  10938. <p>Normally, only a few changes are needed to make an existing configuration
  10939. file suitable for use with workers:</p>
  10940. <ul>
  10941. <li>First, you need to enable an
  10942. <a href="usage/configuration/config_documentation.html#listeners">&quot;HTTP replication listener&quot;</a>
  10943. for the main process</li>
  10944. <li>Secondly, you need to enable
  10945. <a href="usage/configuration/config_documentation.html#redis">redis-based replication</a></li>
  10946. <li>You will need to add an <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>
  10947. with the <code>main</code> process defined, as well as the relevant connection information from
  10948. it's HTTP <code>replication</code> listener (defined in step 1 above).
  10949. <ul>
  10950. <li>Note that the <code>host</code> defined is the address the worker needs to look for the <code>main</code>
  10951. process at, not necessarily the same address that is bound to.</li>
  10952. <li>If you are using Unix sockets for the <code>replication</code> resource, make sure to
  10953. use a <code>path</code> to the socket file instead of a <code>port</code>.</li>
  10954. </ul>
  10955. </li>
  10956. <li>Optionally, a <a href="usage/configuration/config_documentation.html#worker_replication_secret">shared secret</a>
  10957. can be used to authenticate HTTP traffic between workers. For example:</li>
  10958. </ul>
  10959. <pre><code class="language-yaml"># extend the existing `listeners` section. This defines the ports that the
  10960. # main process will listen on.
  10961. listeners:
  10962. # The HTTP replication port
  10963. - port: 9093
  10964. bind_address: '127.0.0.1'
  10965. type: http
  10966. resources:
  10967. - names: [replication]
  10968. # Add a random shared secret to authenticate traffic.
  10969. worker_replication_secret: &quot;&quot;
  10970. redis:
  10971. enabled: true
  10972. instance_map:
  10973. main:
  10974. host: 'localhost'
  10975. port: 9093
  10976. </code></pre>
  10977. <p>See the <a href="usage/configuration/config_documentation.html">configuration manual</a>
  10978. for the full documentation of each option.</p>
  10979. <p>Under <strong>no circumstances</strong> should the replication listener be exposed to the
  10980. public internet; replication traffic is:</p>
  10981. <ul>
  10982. <li>always unencrypted</li>
  10983. <li>unauthenticated, unless <a href="usage/configuration/config_documentation.html#worker_replication_secret"><code>worker_replication_secret</code></a>
  10984. is configured</li>
  10985. </ul>
  10986. <h3 id="worker-configuration"><a class="header" href="#worker-configuration">Worker configuration</a></h3>
  10987. <p>In the config file for each worker, you must specify:</p>
  10988. <ul>
  10989. <li>The type of worker (<a href="usage/configuration/config_documentation.html#worker_app"><code>worker_app</code></a>).
  10990. The currently available worker applications are listed <a href="workers.html#available-worker-applications">below</a>.</li>
  10991. <li>A unique name for the worker (<a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>).</li>
  10992. <li>If handling HTTP requests, a <a href="usage/configuration/config_documentation.html#worker_listeners"><code>worker_listeners</code></a> option
  10993. with an <code>http</code> listener.</li>
  10994. <li><strong>Synapse 1.72 and older:</strong> if handling the <code>^/_matrix/client/v3/keys/upload</code> endpoint, the HTTP URI for
  10995. 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>
  10996. </ul>
  10997. <p>For example:</p>
  10998. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  10999. worker_name: generic_worker1
  11000. worker_listeners:
  11001. - type: http
  11002. port: 8083
  11003. x_forwarded: true
  11004. resources:
  11005. - names: [client, federation]
  11006. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  11007. </code></pre>
  11008. <p>...is a full configuration for a generic worker instance, which will expose a
  11009. plain HTTP endpoint on port 8083 separately serving various endpoints, e.g.
  11010. <code>/sync</code>, which are listed below.</p>
  11011. <p>Obviously you should configure your reverse-proxy to route the relevant
  11012. endpoints to the worker (<code>localhost:8083</code> in the above example).</p>
  11013. <h3 id="running-synapse-with-workers"><a class="header" href="#running-synapse-with-workers">Running Synapse with workers</a></h3>
  11014. <p>Finally, you need to start your worker processes. This can be done with either
  11015. <code>synctl</code> or your distribution's preferred service manager such as <code>systemd</code>. We
  11016. recommend the use of <code>systemd</code> where available: for information on setting up
  11017. <code>systemd</code> to start synapse workers, see
  11018. <a href="systemd-with-workers/">Systemd with Workers</a>. To use <code>synctl</code>, see
  11019. <a href="synctl_workers.html">Using synctl with Workers</a>.</p>
  11020. <h2 id="start-synapse-with-poetry"><a class="header" href="#start-synapse-with-poetry">Start Synapse with Poetry</a></h2>
  11021. <p>The following applies to Synapse installations that have been installed from source using <code>poetry</code>.</p>
  11022. <p>You can start the main Synapse process with Poetry by running the following command:</p>
  11023. <pre><code class="language-console">poetry run synapse_homeserver --config-file [your homeserver.yaml]
  11024. </code></pre>
  11025. <p>For worker setups, you can run the following command</p>
  11026. <pre><code class="language-console">poetry run synapse_worker --config-file [your homeserver.yaml] --config-file [your worker.yaml]
  11027. </code></pre>
  11028. <h2 id="available-worker-applications"><a class="header" href="#available-worker-applications">Available worker applications</a></h2>
  11029. <h3 id="synapseappgeneric_worker"><a class="header" href="#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a></h3>
  11030. <p>This worker can handle API requests matching the following regular expressions.
  11031. These endpoints can be routed to any worker. If a worker is set up to handle a
  11032. stream then, for maximum efficiency, additional endpoints should be routed to that
  11033. worker: refer to the <a href="workers.html#stream-writers">stream writers</a> section below for further
  11034. information.</p>
  11035. <pre><code># Sync requests
  11036. ^/_matrix/client/(r0|v3)/sync$
  11037. ^/_matrix/client/(api/v1|r0|v3)/events$
  11038. ^/_matrix/client/(api/v1|r0|v3)/initialSync$
  11039. ^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$
  11040. # Federation requests
  11041. ^/_matrix/federation/v1/event/
  11042. ^/_matrix/federation/v1/state/
  11043. ^/_matrix/federation/v1/state_ids/
  11044. ^/_matrix/federation/v1/backfill/
  11045. ^/_matrix/federation/v1/get_missing_events/
  11046. ^/_matrix/federation/v1/publicRooms
  11047. ^/_matrix/federation/v1/query/
  11048. ^/_matrix/federation/v1/make_join/
  11049. ^/_matrix/federation/v1/make_leave/
  11050. ^/_matrix/federation/(v1|v2)/send_join/
  11051. ^/_matrix/federation/(v1|v2)/send_leave/
  11052. ^/_matrix/federation/(v1|v2)/invite/
  11053. ^/_matrix/federation/v1/event_auth/
  11054. ^/_matrix/federation/v1/timestamp_to_event/
  11055. ^/_matrix/federation/v1/exchange_third_party_invite/
  11056. ^/_matrix/federation/v1/user/devices/
  11057. ^/_matrix/key/v2/query
  11058. ^/_matrix/federation/v1/hierarchy/
  11059. # Inbound federation transaction request
  11060. ^/_matrix/federation/v1/send/
  11061. # Client API requests
  11062. ^/_matrix/client/(api/v1|r0|v3|unstable)/createRoom$
  11063. ^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$
  11064. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$
  11065. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$
  11066. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$
  11067. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$
  11068. ^/_matrix/client/v1/rooms/.*/hierarchy$
  11069. ^/_matrix/client/(v1|unstable)/rooms/.*/relations/
  11070. ^/_matrix/client/v1/rooms/.*/threads$
  11071. ^/_matrix/client/unstable/im.nheko.summary/rooms/.*/summary$
  11072. ^/_matrix/client/(r0|v3|unstable)/account/3pid$
  11073. ^/_matrix/client/(r0|v3|unstable)/account/whoami$
  11074. ^/_matrix/client/(r0|v3|unstable)/devices$
  11075. ^/_matrix/client/versions$
  11076. ^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$
  11077. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event/
  11078. ^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms$
  11079. ^/_matrix/client/v1/rooms/.*/timestamp_to_event$
  11080. ^/_matrix/client/(api/v1|r0|v3|unstable/.*)/rooms/.*/aliases
  11081. ^/_matrix/client/(api/v1|r0|v3|unstable)/search$
  11082. ^/_matrix/client/(r0|v3|unstable)/user/.*/filter(/|$)
  11083. ^/_matrix/client/(api/v1|r0|v3|unstable)/directory/room/.*$
  11084. ^/_matrix/client/(r0|v3|unstable)/capabilities$
  11085. ^/_matrix/client/(r0|v3|unstable)/notifications$
  11086. # Encryption requests
  11087. ^/_matrix/client/(r0|v3|unstable)/keys/query$
  11088. ^/_matrix/client/(r0|v3|unstable)/keys/changes$
  11089. ^/_matrix/client/(r0|v3|unstable)/keys/claim$
  11090. ^/_matrix/client/(r0|v3|unstable)/room_keys/
  11091. ^/_matrix/client/(r0|v3|unstable)/keys/upload/
  11092. # Registration/login requests
  11093. ^/_matrix/client/(api/v1|r0|v3|unstable)/login$
  11094. ^/_matrix/client/(r0|v3|unstable)/register$
  11095. ^/_matrix/client/(r0|v3|unstable)/register/available$
  11096. ^/_matrix/client/v1/register/m.login.registration_token/validity$
  11097. ^/_matrix/client/(r0|v3|unstable)/password_policy$
  11098. # Event sending requests
  11099. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact
  11100. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send
  11101. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state/
  11102. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$
  11103. ^/_matrix/client/(api/v1|r0|v3|unstable)/join/
  11104. ^/_matrix/client/(api/v1|r0|v3|unstable)/knock/
  11105. ^/_matrix/client/(api/v1|r0|v3|unstable)/profile/
  11106. # Account data requests
  11107. ^/_matrix/client/(r0|v3|unstable)/.*/tags
  11108. ^/_matrix/client/(r0|v3|unstable)/.*/account_data
  11109. # Receipts requests
  11110. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
  11111. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
  11112. # Presence requests
  11113. ^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
  11114. # User directory search requests
  11115. ^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  11116. </code></pre>
  11117. <p>Additionally, the following REST endpoints can be handled for GET requests:</p>
  11118. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/pushrules/
  11119. </code></pre>
  11120. <p>Pagination requests can also be handled, but all requests for a given
  11121. room must be routed to the same instance. Additionally, care must be taken to
  11122. ensure that the purge history admin API is not used while pagination requests
  11123. for the room are in flight:</p>
  11124. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$
  11125. </code></pre>
  11126. <p>Additionally, the following endpoints should be included if Synapse is configured
  11127. to use SSO (you only need to include the ones for whichever SSO provider you're
  11128. using):</p>
  11129. <pre><code># for all SSO providers
  11130. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/sso/redirect
  11131. ^/_synapse/client/pick_idp$
  11132. ^/_synapse/client/pick_username
  11133. ^/_synapse/client/new_user_consent$
  11134. ^/_synapse/client/sso_register$
  11135. # OpenID Connect requests.
  11136. ^/_synapse/client/oidc/callback$
  11137. # SAML requests.
  11138. ^/_synapse/client/saml2/authn_response$
  11139. # CAS requests.
  11140. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/cas/ticket$
  11141. </code></pre>
  11142. <p>Ensure that all SSO logins go to a single process.
  11143. For multiple workers not handling the SSO endpoints properly, see
  11144. <a href="https://github.com/matrix-org/synapse/issues/7530">#7530</a> and
  11145. <a href="https://github.com/matrix-org/synapse/issues/9427">#9427</a>.</p>
  11146. <p>Note that a <a href="usage/configuration/config_documentation.html#listeners">HTTP listener</a>
  11147. with <code>client</code> and <code>federation</code> <code>resources</code> must be configured in the
  11148. <a href="usage/configuration/config_documentation.html#worker_listeners"><code>worker_listeners</code></a>
  11149. option in the worker config.</p>
  11150. <h4 id="load-balancing"><a class="header" href="#load-balancing">Load balancing</a></h4>
  11151. <p>It is possible to run multiple instances of this worker app, with incoming requests
  11152. being load-balanced between them by the reverse-proxy. However, different endpoints
  11153. have different characteristics and so admins
  11154. may wish to run multiple groups of workers handling different endpoints so that
  11155. load balancing can be done in different ways.</p>
  11156. <p>For <code>/sync</code> and <code>/initialSync</code> requests it will be more efficient if all
  11157. requests from a particular user are routed to a single instance. This can
  11158. be done in reverse proxy by extracting username part from the users access token.</p>
  11159. <p>Admins may additionally wish to separate out <code>/sync</code>
  11160. requests that have a <code>since</code> query parameter from those that don't (and
  11161. <code>/initialSync</code>), as requests that don't are known as &quot;initial sync&quot; that happens
  11162. when a user logs in on a new device and can be <em>very</em> resource intensive, so
  11163. isolating these requests will stop them from interfering with other users ongoing
  11164. syncs.</p>
  11165. <p>Example <code>nginx</code> configuration snippet that handles the cases above. This is just an
  11166. example and probably requires some changes according to your particular setup:</p>
  11167. <pre><code class="language-nginx"># Choose sync worker based on the existence of &quot;since&quot; query parameter
  11168. map $arg_since $sync {
  11169. default synapse_sync;
  11170. '' synapse_initial_sync;
  11171. }
  11172. # Extract username from access token passed as URL parameter
  11173. map $arg_access_token $accesstoken_from_urlparam {
  11174. # Defaults to just passing back the whole accesstoken
  11175. default $arg_access_token;
  11176. # Try to extract username part from accesstoken URL parameter
  11177. &quot;~syt_(?&lt;username&gt;.*?)_.*&quot; $username;
  11178. }
  11179. # Extract username from access token passed as authorization header
  11180. map $http_authorization $mxid_localpart {
  11181. # Defaults to just passing back the whole accesstoken
  11182. default $http_authorization;
  11183. # Try to extract username part from accesstoken header
  11184. &quot;~Bearer syt_(?&lt;username&gt;.*?)_.*&quot; $username;
  11185. # if no authorization-header exist, try mapper for URL parameter &quot;access_token&quot;
  11186. &quot;&quot; $accesstoken_from_urlparam;
  11187. }
  11188. upstream synapse_initial_sync {
  11189. # Use the username mapper result for hash key
  11190. hash $mxid_localpart consistent;
  11191. server 127.0.0.1:8016;
  11192. server 127.0.0.1:8036;
  11193. }
  11194. upstream synapse_sync {
  11195. # Use the username mapper result for hash key
  11196. hash $mxid_localpart consistent;
  11197. server 127.0.0.1:8013;
  11198. server 127.0.0.1:8037;
  11199. server 127.0.0.1:8038;
  11200. server 127.0.0.1:8039;
  11201. }
  11202. # Sync initial/normal
  11203. location ~ ^/_matrix/client/(r0|v3)/sync$ {
  11204. proxy_pass http://$sync;
  11205. }
  11206. # Normal sync
  11207. location ~ ^/_matrix/client/(api/v1|r0|v3)/events$ {
  11208. proxy_pass http://synapse_sync;
  11209. }
  11210. # Initial_sync
  11211. location ~ ^/_matrix/client/(api/v1|r0|v3)/initialSync$ {
  11212. proxy_pass http://synapse_initial_sync;
  11213. }
  11214. location ~ ^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$ {
  11215. proxy_pass http://synapse_initial_sync;
  11216. }
  11217. </code></pre>
  11218. <p>Federation and client requests can be balanced via simple round robin.</p>
  11219. <p>The inbound federation transaction request <code>^/_matrix/federation/v1/send/</code>
  11220. should be balanced by source IP so that transactions from the same remote server
  11221. go to the same process.</p>
  11222. <p>Registration/login requests can be handled separately purely to help ensure that
  11223. unexpected load doesn't affect new logins and sign ups.</p>
  11224. <p>Finally, event sending requests can be balanced by the room ID in the URI (or
  11225. the full URI, or even just round robin), the room ID is the path component after
  11226. <code>/rooms/</code>. If there is a large bridge connected that is sending or may send lots
  11227. of events, then a dedicated set of workers can be provisioned to limit the
  11228. effects of bursts of events from that bridge on events sent by normal users.</p>
  11229. <h4 id="stream-writers"><a class="header" href="#stream-writers">Stream writers</a></h4>
  11230. <p>Additionally, the writing of specific streams (such as events) can be moved off
  11231. of the main process to a particular worker.</p>
  11232. <p>To enable this, the worker must have:</p>
  11233. <ul>
  11234. <li>An <a href="usage/configuration/config_documentation.html#listeners">HTTP <code>replication</code> listener</a> configured,</li>
  11235. <li>Have a <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>
  11236. and be listed in the <a href="usage/configuration/config_documentation.html#instance_map"><code>instance_map</code></a>
  11237. config. </li>
  11238. <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>
  11239. </ul>
  11240. <p>Note: The same worker can handle multiple streams, but unless otherwise documented,
  11241. each stream can only have a single writer.</p>
  11242. <p>For example, to move event persistence off to a dedicated worker, the shared
  11243. configuration would include:</p>
  11244. <pre><code class="language-yaml">instance_map:
  11245. main:
  11246. host: localhost
  11247. port: 8030
  11248. event_persister1:
  11249. host: localhost
  11250. port: 8034
  11251. stream_writers:
  11252. events: event_persister1
  11253. </code></pre>
  11254. <p>An example for a stream writer instance:</p>
  11255. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  11256. worker_name: event_persister1
  11257. worker_listeners:
  11258. - type: http
  11259. port: 8034
  11260. resources:
  11261. - names: [replication]
  11262. # Enable listener if this stream writer handles endpoints for the `typing` or
  11263. # `to_device` streams. Uses a different port to the `replication` listener to
  11264. # avoid exposing the `replication` listener publicly.
  11265. #
  11266. #- type: http
  11267. # port: 8035
  11268. # x_forwarded: true
  11269. # resources:
  11270. # - names: [client]
  11271. worker_log_config: /etc/matrix-synapse/event-persister-log.yaml
  11272. </code></pre>
  11273. <p>Some of the streams have associated endpoints which, for maximum efficiency, should
  11274. be routed to the workers handling that stream. See below for the currently supported
  11275. streams and the endpoints associated with them:</p>
  11276. <h5 id="the-events-stream"><a class="header" href="#the-events-stream">The <code>events</code> stream</a></h5>
  11277. <p>The <code>events</code> stream experimentally supports having multiple writer workers, where load
  11278. is sharded between them by room ID. Each writer is called an <em>event persister</em>. They are
  11279. responsible for</p>
  11280. <ul>
  11281. <li>receiving new events,</li>
  11282. <li>linking them to those already in the room <a href="development/room-dag-concepts.html">DAG</a>,</li>
  11283. <li>persisting them to the DB, and finally</li>
  11284. <li>updating the events stream.</li>
  11285. </ul>
  11286. <p>Because load is sharded in this way, you <em>must</em> restart all worker instances when
  11287. adding or removing event persisters.</p>
  11288. <p>An <code>event_persister</code> should not be mistaken for an <code>event_creator</code>.
  11289. An <code>event_creator</code> listens for requests from clients to create new events and does
  11290. so. It will then pass those events over HTTP replication to any configured event
  11291. persisters (or the main process if none are configured).</p>
  11292. <p>Note that <code>event_creator</code>s and <code>event_persister</code>s are implemented using the same
  11293. <a href="workers.html#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a>.</p>
  11294. <p>An example <a href="usage/configuration/config_documentation.html#stream_writers"><code>stream_writers</code></a>
  11295. configuration with multiple writers:</p>
  11296. <pre><code class="language-yaml">stream_writers:
  11297. events:
  11298. - event_persister1
  11299. - event_persister2
  11300. </code></pre>
  11301. <h5 id="the-typing-stream"><a class="header" href="#the-typing-stream">The <code>typing</code> stream</a></h5>
  11302. <p>The following endpoints should be routed directly to the worker configured as
  11303. the stream writer for the <code>typing</code> stream:</p>
  11304. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/typing
  11305. </code></pre>
  11306. <h5 id="the-to_device-stream"><a class="header" href="#the-to_device-stream">The <code>to_device</code> stream</a></h5>
  11307. <p>The following endpoints should be routed directly to the worker configured as
  11308. the stream writer for the <code>to_device</code> stream:</p>
  11309. <pre><code>^/_matrix/client/(r0|v3|unstable)/sendToDevice/
  11310. </code></pre>
  11311. <h5 id="the-account_data-stream"><a class="header" href="#the-account_data-stream">The <code>account_data</code> stream</a></h5>
  11312. <p>The following endpoints should be routed directly to the worker configured as
  11313. the stream writer for the <code>account_data</code> stream:</p>
  11314. <pre><code>^/_matrix/client/(r0|v3|unstable)/.*/tags
  11315. ^/_matrix/client/(r0|v3|unstable)/.*/account_data
  11316. </code></pre>
  11317. <h5 id="the-receipts-stream"><a class="header" href="#the-receipts-stream">The <code>receipts</code> stream</a></h5>
  11318. <p>The following endpoints should be routed directly to the worker configured as
  11319. the stream writer for the <code>receipts</code> stream:</p>
  11320. <pre><code>^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
  11321. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
  11322. </code></pre>
  11323. <h5 id="the-presence-stream"><a class="header" href="#the-presence-stream">The <code>presence</code> stream</a></h5>
  11324. <p>The following endpoints should be routed directly to the worker configured as
  11325. the stream writer for the <code>presence</code> stream:</p>
  11326. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
  11327. </code></pre>
  11328. <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>
  11329. <p>The
  11330. <a href="usage/configuration/config_documentation.html#outbound_federation_restricted_to"><code>outbound_federation_restricted_to</code></a>
  11331. configuration is useful to make sure outbound federation traffic only goes through a
  11332. specified subset of workers. This allows you to set more strict access controls (like a
  11333. firewall) for all workers and only allow the <code>federation_sender</code>'s to contact the
  11334. outside world.</p>
  11335. <pre><code class="language-yaml">instance_map:
  11336. main:
  11337. host: localhost
  11338. port: 8030
  11339. federation_sender1:
  11340. host: localhost
  11341. port: 8034
  11342. outbound_federation_restricted_to:
  11343. - federation_sender1
  11344. worker_replication_secret: &quot;secret_secret&quot;
  11345. </code></pre>
  11346. <h4 id="background-tasks"><a class="header" href="#background-tasks">Background tasks</a></h4>
  11347. <p>There is also support for moving background tasks to a separate
  11348. worker. Background tasks are run periodically or started via replication. Exactly
  11349. which tasks are configured to run depends on your Synapse configuration (e.g. if
  11350. stats is enabled). This worker doesn't handle any REST endpoints itself.</p>
  11351. <p>To enable this, the worker must have a unique
  11352. <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>
  11353. and can be configured to run background tasks. For example, to move background tasks
  11354. to a dedicated worker, the shared configuration would include:</p>
  11355. <pre><code class="language-yaml">run_background_tasks_on: background_worker
  11356. </code></pre>
  11357. <p>You might also wish to investigate the
  11358. <a href="workers.html#updating-the-user-directory"><code>update_user_directory_from_worker</code></a> and
  11359. <a href="workers.html#synapseappmedia_repository"><code>media_instance_running_background_jobs</code></a> settings.</p>
  11360. <p>An example for a dedicated background worker instance:</p>
  11361. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  11362. worker_name: background_worker
  11363. worker_log_config: /etc/matrix-synapse/background-worker-log.yaml
  11364. </code></pre>
  11365. <h4 id="updating-the-user-directory"><a class="header" href="#updating-the-user-directory">Updating the User Directory</a></h4>
  11366. <p>You can designate one generic worker to update the user directory.</p>
  11367. <p>Specify its name in the <a href="usage/configuration/config_documentation.html#update_user_directory_from_worker">shared configuration</a>
  11368. as follows:</p>
  11369. <pre><code class="language-yaml">update_user_directory_from_worker: worker_name
  11370. </code></pre>
  11371. <p>This work cannot be load-balanced; please ensure the main process is restarted
  11372. after setting this option in the shared configuration!</p>
  11373. <p>User directory updates allow REST endpoints matching the following regular
  11374. expressions to work:</p>
  11375. <pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  11376. </code></pre>
  11377. <p>The above endpoints can be routed to any worker, though you may choose to route
  11378. it to the chosen user directory worker.</p>
  11379. <p>This style of configuration supersedes the legacy <code>synapse.app.user_dir</code>
  11380. worker application type.</p>
  11381. <h4 id="notifying-application-services"><a class="header" href="#notifying-application-services">Notifying Application Services</a></h4>
  11382. <p>You can designate one generic worker to send output traffic to Application Services.
  11383. Doesn't handle any REST endpoints itself, but you should specify its name in the
  11384. <a href="usage/configuration/config_documentation.html#notify_appservices_from_worker">shared configuration</a>
  11385. as follows:</p>
  11386. <pre><code class="language-yaml">notify_appservices_from_worker: worker_name
  11387. </code></pre>
  11388. <p>This work cannot be load-balanced; please ensure the main process is restarted
  11389. after setting this option in the shared configuration!</p>
  11390. <p>This style of configuration supersedes the legacy <code>synapse.app.appservice</code>
  11391. worker application type.</p>
  11392. <h4 id="push-notifications"><a class="header" href="#push-notifications">Push Notifications</a></h4>
  11393. <p>You can designate generic worker to sending push notifications to
  11394. a <a href="https://spec.matrix.org/v1.5/push-gateway-api/">push gateway</a> such as
  11395. <a href="https://github.com/matrix-org/sygnal">sygnal</a> and email.</p>
  11396. <p>This will stop the main process sending push notifications.</p>
  11397. <p>The workers responsible for sending push notifications can be defined using the
  11398. <a href="usage/configuration/config_documentation.html#pusher_instances"><code>pusher_instances</code></a>
  11399. option. For example:</p>
  11400. <pre><code class="language-yaml">pusher_instances:
  11401. - pusher_worker1
  11402. - pusher_worker2
  11403. </code></pre>
  11404. <p>Multiple workers can be added to this map, in which case the work is balanced
  11405. across them. Ensure the main process and all pusher workers are restarted after changing
  11406. this option.</p>
  11407. <p>These workers don't need to accept incoming HTTP requests to send push notifications,
  11408. so no additional reverse proxy configuration is required for pusher workers.</p>
  11409. <p>This style of configuration supersedes the legacy <code>synapse.app.pusher</code>
  11410. worker application type.</p>
  11411. <h3 id="synapseapppusher"><a class="header" href="#synapseapppusher"><code>synapse.app.pusher</code></a></h3>
  11412. <p>It is likely this option will be deprecated in the future and is not recommended for new
  11413. installations. Instead, <a href="workers.html#push-notifications">use <code>synapse.app.generic_worker</code> with the <code>pusher_instances</code></a>.</p>
  11414. <p>Handles sending push notifications to sygnal and email. Doesn't handle any
  11415. REST endpoints itself, but you should set
  11416. <a href="usage/configuration/config_documentation.html#start_pushers"><code>start_pushers: false</code></a> in the
  11417. shared configuration file to stop the main synapse sending push notifications.</p>
  11418. <p>To run multiple instances at once the
  11419. <a href="usage/configuration/config_documentation.html#pusher_instances"><code>pusher_instances</code></a>
  11420. option should list all pusher instances by their
  11421. <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>, e.g.:</p>
  11422. <pre><code class="language-yaml">start_pushers: false
  11423. pusher_instances:
  11424. - pusher_worker1
  11425. - pusher_worker2
  11426. </code></pre>
  11427. <p>An example for a pusher instance:</p>
  11428. <pre><code class="language-yaml">worker_app: synapse.app.pusher
  11429. worker_name: pusher_worker1
  11430. worker_log_config: /etc/matrix-synapse/pusher-worker-log.yaml
  11431. </code></pre>
  11432. <h3 id="synapseappappservice"><a class="header" href="#synapseappappservice"><code>synapse.app.appservice</code></a></h3>
  11433. <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
  11434. <code>notify_appservices_from_worker</code> option instead.</a></p>
  11435. <p>Handles sending output traffic to Application Services. Doesn't handle any
  11436. REST endpoints itself, but you should set <code>notify_appservices: False</code> in the
  11437. shared configuration file to stop the main synapse sending appservice notifications.</p>
  11438. <p>Note this worker cannot be load-balanced: only one instance should be active.</p>
  11439. <h3 id="synapseappfederation_sender"><a class="header" href="#synapseappfederation_sender"><code>synapse.app.federation_sender</code></a></h3>
  11440. <p>It is likely this option will be deprecated in the future and not recommended for
  11441. 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>
  11442. <p>Handles sending federation traffic to other servers. Doesn't handle any
  11443. REST endpoints itself, but you should set
  11444. <a href="usage/configuration/config_documentation.html#send_federation"><code>send_federation: false</code></a>
  11445. in the shared configuration file to stop the main synapse sending this traffic.</p>
  11446. <p>If running multiple federation senders then you must list each
  11447. instance in the
  11448. <a href="usage/configuration/config_documentation.html#federation_sender_instances"><code>federation_sender_instances</code></a>
  11449. option by their
  11450. <a href="usage/configuration/config_documentation.html#worker_name"><code>worker_name</code></a>.
  11451. All instances must be stopped and started when adding or removing instances.
  11452. For example:</p>
  11453. <pre><code class="language-yaml">send_federation: false
  11454. federation_sender_instances:
  11455. - federation_sender1
  11456. - federation_sender2
  11457. </code></pre>
  11458. <p>An example for a federation sender instance:</p>
  11459. <pre><code class="language-yaml">worker_app: synapse.app.federation_sender
  11460. worker_name: federation_sender1
  11461. worker_log_config: /etc/matrix-synapse/federation-sender-log.yaml
  11462. </code></pre>
  11463. <h3 id="synapseappmedia_repository"><a class="header" href="#synapseappmedia_repository"><code>synapse.app.media_repository</code></a></h3>
  11464. <p>Handles the media repository. It can handle all endpoints starting with:</p>
  11465. <pre><code>/_matrix/media/
  11466. </code></pre>
  11467. <p>... and the following regular expressions matching media-specific administration APIs:</p>
  11468. <pre><code>^/_synapse/admin/v1/purge_media_cache$
  11469. ^/_synapse/admin/v1/room/.*/media.*$
  11470. ^/_synapse/admin/v1/user/.*/media.*$
  11471. ^/_synapse/admin/v1/media/.*$
  11472. ^/_synapse/admin/v1/quarantine_media/.*$
  11473. ^/_synapse/admin/v1/users/.*/media$
  11474. </code></pre>
  11475. <p>You should also set
  11476. <a href="usage/configuration/config_documentation.html#enable_media_repo"><code>enable_media_repo: False</code></a>
  11477. in the shared configuration
  11478. file to stop the main synapse running background jobs related to managing the
  11479. media repository. Note that doing so will prevent the main process from being
  11480. able to handle the above endpoints.</p>
  11481. <p>In the <code>media_repository</code> worker configuration file, configure the
  11482. <a href="usage/configuration/config_documentation.html#listeners">HTTP listener</a> to
  11483. expose the <code>media</code> resource. For example:</p>
  11484. <pre><code class="language-yaml">worker_app: synapse.app.media_repository
  11485. worker_name: media_worker
  11486. worker_listeners:
  11487. - type: http
  11488. port: 8085
  11489. x_forwarded: true
  11490. resources:
  11491. - names: [media]
  11492. worker_log_config: /etc/matrix-synapse/media-worker-log.yaml
  11493. </code></pre>
  11494. <p>Note that if running multiple media repositories they must be on the same server
  11495. and you must specify a single instance to run the background tasks in the
  11496. <a href="usage/configuration/config_documentation.html#media_instance_running_background_jobs">shared configuration</a>,
  11497. e.g.:</p>
  11498. <pre><code class="language-yaml">media_instance_running_background_jobs: &quot;media-repository-1&quot;
  11499. </code></pre>
  11500. <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>
  11501. <h3 id="synapseappuser_dir"><a class="header" href="#synapseappuser_dir"><code>synapse.app.user_dir</code></a></h3>
  11502. <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
  11503. <code>update_user_directory_from_worker</code> option instead.</a></p>
  11504. <p>Handles searches in the user directory. It can handle REST endpoints matching
  11505. the following regular expressions:</p>
  11506. <pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  11507. </code></pre>
  11508. <p>When using this worker you must also set <code>update_user_directory: false</code> in the
  11509. shared configuration file to stop the main synapse running background
  11510. jobs related to updating the user directory.</p>
  11511. <p>Above endpoint is not <em>required</em> to be routed to this worker. By default,
  11512. <code>update_user_directory</code> is set to <code>true</code>, which means the main process
  11513. will handle updates. All workers configured with <code>client</code> can handle the above
  11514. endpoint as long as either this worker or the main process are configured to
  11515. handle it, and are online.</p>
  11516. <p>If <code>update_user_directory</code> is set to <code>false</code>, and this worker is not running,
  11517. the above endpoint may give outdated results.</p>
  11518. <h3 id="historical-apps"><a class="header" href="#historical-apps">Historical apps</a></h3>
  11519. <p>The following used to be separate worker application types, but are now
  11520. equivalent to <code>synapse.app.generic_worker</code>:</p>
  11521. <ul>
  11522. <li><code>synapse.app.client_reader</code></li>
  11523. <li><code>synapse.app.event_creator</code></li>
  11524. <li><code>synapse.app.federation_reader</code></li>
  11525. <li><code>synapse.app.federation_sender</code></li>
  11526. <li><code>synapse.app.frontend_proxy</code></li>
  11527. <li><code>synapse.app.pusher</code></li>
  11528. <li><code>synapse.app.synchrotron</code></li>
  11529. </ul>
  11530. <h2 id="migration-from-old-config"><a class="header" href="#migration-from-old-config">Migration from old config</a></h2>
  11531. <p>A main change that has occurred is the merging of worker apps into
  11532. <code>synapse.app.generic_worker</code>. This change is backwards compatible and so no
  11533. changes to the config are required.</p>
  11534. <p>To migrate apps to use <code>synapse.app.generic_worker</code> simply update the
  11535. <code>worker_app</code> option in the worker configs, and where worker are started (e.g.
  11536. in systemd service files, but not required for synctl).</p>
  11537. <h2 id="architectural-diagram"><a class="header" href="#architectural-diagram">Architectural diagram</a></h2>
  11538. <p>The following shows an example setup using Redis and a reverse proxy:</p>
  11539. <pre><code> Clients &amp; Federation
  11540. |
  11541. v
  11542. +-----------+
  11543. | |
  11544. | Reverse |
  11545. | Proxy |
  11546. | |
  11547. +-----------+
  11548. | | |
  11549. | | | HTTP requests
  11550. +-------------------+ | +-----------+
  11551. | +---+ |
  11552. | | |
  11553. v v v
  11554. +--------------+ +--------------+ +--------------+ +--------------+
  11555. | Main | | Generic | | Generic | | Event |
  11556. | Process | | Worker 1 | | Worker 2 | | Persister |
  11557. +--------------+ +--------------+ +--------------+ +--------------+
  11558. ^ ^ | ^ | | ^ | | ^ ^
  11559. | | | | | | | | | | |
  11560. | | | | | HTTP | | | | | |
  11561. | +----------+&lt;--|---|---------+&lt;--|---|---------+ | |
  11562. | | +-------------|--&gt;+-------------+ |
  11563. | | | |
  11564. | | | |
  11565. v v v v
  11566. ======================================================================
  11567. Redis pub/sub channel
  11568. </code></pre>
  11569. <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>
  11570. <p>If you want to use <code>synctl</code> to manage your synapse processes, you will need to
  11571. create an an additional configuration file for the main synapse process. That
  11572. configuration should look like this:</p>
  11573. <pre><code class="language-yaml">worker_app: synapse.app.homeserver
  11574. </code></pre>
  11575. <p>Additionally, each worker app must be configured with the name of a &quot;pid file&quot;,
  11576. to which it will write its process ID when it starts. For example, for a
  11577. synchrotron, you might write:</p>
  11578. <pre><code class="language-yaml">worker_pid_file: /home/matrix/synapse/worker1.pid
  11579. </code></pre>
  11580. <p>Finally, to actually run your worker-based synapse, you must pass synctl the <code>-a</code>
  11581. commandline option to tell it to operate on all the worker configurations found
  11582. in the given directory, e.g.:</p>
  11583. <pre><code class="language-sh">synctl -a $CONFIG/workers start
  11584. </code></pre>
  11585. <p>Currently one should always restart all workers when restarting or upgrading
  11586. synapse, unless you explicitly know it's safe not to. For instance, restarting
  11587. synapse without restarting all the synchrotrons may result in broken typing
  11588. notifications.</p>
  11589. <p>To manipulate a specific worker, you pass the -w option to synctl:</p>
  11590. <pre><code class="language-sh">synctl -w $CONFIG/workers/worker1.yaml restart
  11591. </code></pre>
  11592. <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>
  11593. <p>This is a setup for managing synapse with systemd, including support for
  11594. managing workers. It provides a <code>matrix-synapse</code> service for the master, as
  11595. well as a <code>matrix-synapse-worker@</code> service template for any workers you
  11596. require. Additionally, to group the required services, it sets up a
  11597. <code>matrix-synapse.target</code>.</p>
  11598. <p>See the folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/system/">system</a>
  11599. for the systemd unit files.</p>
  11600. <p>The folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/workers/">workers</a>
  11601. contains an example configuration for the <code>generic_worker</code> worker.</p>
  11602. <h2 id="synapse-configuration-files"><a class="header" href="#synapse-configuration-files">Synapse configuration files</a></h2>
  11603. <p>See <a href="systemd-with-workers/../workers.html">the worker documentation</a> for information on how to set up the
  11604. configuration files and reverse-proxy correctly.
  11605. Below is a sample <code>generic_worker</code> worker configuration file.</p>
  11606. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  11607. worker_name: generic_worker1
  11608. worker_listeners:
  11609. - type: http
  11610. port: 8083
  11611. x_forwarded: true
  11612. resources:
  11613. - names: [client, federation]
  11614. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  11615. </code></pre>
  11616. <p>Systemd manages daemonization itself, so ensure that none of the configuration
  11617. files set either <code>daemonize</code> or <code>worker_daemonize</code>.</p>
  11618. <p>The config files of all workers are expected to be located in
  11619. <code>/etc/matrix-synapse/workers</code>. If you want to use a different location, edit
  11620. the provided <code>*.service</code> files accordingly.</p>
  11621. <p>There is no need for a separate configuration file for the master process.</p>
  11622. <h2 id="set-up"><a class="header" href="#set-up">Set up</a></h2>
  11623. <ol>
  11624. <li>Adjust synapse configuration files as above.</li>
  11625. <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>
  11626. to <code>/etc/systemd/system</code>.</li>
  11627. <li>Run <code>systemctl daemon-reload</code> to tell systemd to load the new unit files.</li>
  11628. <li>Run <code>systemctl enable matrix-synapse.service</code>. This will configure the
  11629. synapse master process to be started as part of the <code>matrix-synapse.target</code>
  11630. target.</li>
  11631. <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
  11632. should be a corresponding configuration file.
  11633. <code>/etc/matrix-synapse/workers/&lt;worker_name&gt;.yaml</code>.</li>
  11634. <li>Start all the synapse processes with <code>systemctl start matrix-synapse.target</code>.</li>
  11635. <li>Tell systemd to start synapse on boot with <code>systemctl enable matrix-synapse.target</code>.</li>
  11636. </ol>
  11637. <h2 id="usage"><a class="header" href="#usage">Usage</a></h2>
  11638. <p>Once the services are correctly set up, you can use the following commands
  11639. to manage your synapse installation:</p>
  11640. <pre><code class="language-sh"># Restart Synapse master and all workers
  11641. systemctl restart matrix-synapse.target
  11642. # Stop Synapse and all workers
  11643. systemctl stop matrix-synapse.target
  11644. # Restart the master alone
  11645. systemctl start matrix-synapse.service
  11646. # Restart a specific worker (eg. generic_worker); the master is
  11647. # unaffected by this.
  11648. systemctl restart matrix-synapse-worker@generic_worker.service
  11649. # Add a new worker (assuming all configs are set up already)
  11650. systemctl enable matrix-synapse-worker@federation_writer.service
  11651. systemctl restart matrix-synapse.target
  11652. </code></pre>
  11653. <h2 id="hardening"><a class="header" href="#hardening">Hardening</a></h2>
  11654. <p><strong>Optional:</strong> If further hardening is desired, the file
  11655. <code>override-hardened.conf</code> may be copied from
  11656. <a href="https://github.com/matrix-org/synapse/tree/develop/contrib/systemd/">contrib/systemd/override-hardened.conf</a>
  11657. in this repository to the location
  11658. <code>/etc/systemd/system/matrix-synapse.service.d/override-hardened.conf</code> (the
  11659. directory may have to be created). It enables certain sandboxing features in
  11660. systemd to further secure the synapse service. You may read the comments to
  11661. understand what the override file is doing. The same file will need to be copied to
  11662. <code>/etc/systemd/system/matrix-synapse-worker@.service.d/override-hardened-worker.conf</code>
  11663. (this directory may also have to be created) in order to apply the same
  11664. hardening options to any worker processes.</p>
  11665. <p>Once these files have been copied to their appropriate locations, simply reload
  11666. systemd's manager config files and restart all Synapse services to apply the hardening options. They will automatically
  11667. be applied at every restart as long as the override files are present at the
  11668. specified locations.</p>
  11669. <pre><code class="language-sh">systemctl daemon-reload
  11670. # Restart services
  11671. systemctl restart matrix-synapse.target
  11672. </code></pre>
  11673. <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
  11674. the changes being applied at a glance.</p>
  11675. <div style="break-before: page; page-break-before: always;"></div><h1 id="administration"><a class="header" href="#administration">Administration</a></h1>
  11676. <p>This section contains information on managing your Synapse homeserver. This includes:</p>
  11677. <ul>
  11678. <li>Managing users, rooms and media via the Admin API.</li>
  11679. <li>Setting up metrics and monitoring to give you insight into your homeserver's health.</li>
  11680. <li>Configuring structured logging.</li>
  11681. </ul>
  11682. <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>
  11683. <h2 id="authenticate-as-a-server-admin"><a class="header" href="#authenticate-as-a-server-admin">Authenticate as a server admin</a></h2>
  11684. <p>Many of the API calls in the admin api will require an <code>access_token</code> for a
  11685. server admin. (Note that a server admin is distinct from a room admin.)</p>
  11686. <p>An existing user can be marked as a server admin by updating the database directly.</p>
  11687. <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>
  11688. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  11689. </code></pre>
  11690. <p>A new server admin user can also be created using the <code>register_new_matrix_user</code>
  11691. command. This is a script that is distributed as part of synapse. It is possibly
  11692. already on your <code>$PATH</code> depending on how Synapse was installed.</p>
  11693. <p>Finding your user's <code>access_token</code> is client-dependent, but will usually be shown in the client's settings.</p>
  11694. <h2 id="making-an-admin-api-request"><a class="header" href="#making-an-admin-api-request">Making an Admin API request</a></h2>
  11695. <p>For security reasons, we <a href="usage/administration/admin_api/../../../reverse_proxy.html#synapse-administration-endpoints">recommend</a>
  11696. that the Admin API (<code>/_synapse/admin/...</code>) should be hidden from public view using a
  11697. reverse proxy. This means you should typically query the Admin API from a terminal on
  11698. the machine which runs Synapse.</p>
  11699. <p>Once you have your <code>access_token</code>, you will need to authenticate each request to an Admin API endpoint by
  11700. providing the token as either a query parameter or a request header. To add it as a request header in cURL:</p>
  11701. <pre><code class="language-sh">curl --header &quot;Authorization: Bearer &lt;access_token&gt;&quot; &lt;the_rest_of_your_API_request&gt;
  11702. </code></pre>
  11703. <p>For example, suppose we want to
  11704. <a href="usage/administration/admin_api/../../../admin_api/user_admin_api.html#query-user-account">query the account</a> of the user
  11705. <code>@foo:bar.com</code>. We need an admin access token (e.g.
  11706. <code>syt_AjfVef2_L33JNpafeif_0feKJfeaf0CQpoZk</code>), and we need to know which port
  11707. Synapse's <a href="usage/administration/admin_api/../../configuration/config_documentation.html#listeners"><code>client</code> listener</a> is listening
  11708. on (e.g. <code>8008</code>). Then we can use the following command to request the account
  11709. information from the Admin API.</p>
  11710. <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
  11711. </code></pre>
  11712. <p>For more details on access tokens in Matrix, please refer to the complete
  11713. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#using-access-tokens">matrix spec documentation</a>.</p>
  11714. <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>
  11715. <p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
  11716. <p>This API allows a server administrator to manage the validity of an account. To
  11717. use it, you must enable the account validity feature (under
  11718. <code>account_validity</code>) in Synapse's configuration.</p>
  11719. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11720. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  11721. <h2 id="renew-account"><a class="header" href="#renew-account">Renew account</a></h2>
  11722. <p>This API extends the validity of an account by as much time as configured in the
  11723. <code>period</code> parameter from the <code>account_validity</code> configuration.</p>
  11724. <p>The API is:</p>
  11725. <pre><code>POST /_synapse/admin/v1/account_validity/validity
  11726. </code></pre>
  11727. <p>with the following body:</p>
  11728. <pre><code class="language-json">{
  11729. &quot;user_id&quot;: &quot;&lt;user ID for the account to renew&gt;&quot;,
  11730. &quot;expiration_ts&quot;: 0,
  11731. &quot;enable_renewal_emails&quot;: true
  11732. }
  11733. </code></pre>
  11734. <p><code>expiration_ts</code> is an optional parameter and overrides the expiration date,
  11735. which otherwise defaults to now + validity period.</p>
  11736. <p><code>enable_renewal_emails</code> is also an optional parameter and enables/disables
  11737. sending renewal emails to the user. Defaults to true.</p>
  11738. <p>The API returns with the new expiration date for this account, as a timestamp in
  11739. milliseconds since epoch:</p>
  11740. <pre><code class="language-json">{
  11741. &quot;expiration_ts&quot;: 0
  11742. }
  11743. </code></pre>
  11744. <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>
  11745. <p>This API allows a server administrator to manage the background updates being
  11746. run against the database.</p>
  11747. <h2 id="status"><a class="header" href="#status">Status</a></h2>
  11748. <p>This API gets the current status of the background updates.</p>
  11749. <p>The API is:</p>
  11750. <pre><code>GET /_synapse/admin/v1/background_updates/status
  11751. </code></pre>
  11752. <p>Returning:</p>
  11753. <pre><code class="language-json">{
  11754. &quot;enabled&quot;: true,
  11755. &quot;current_updates&quot;: {
  11756. &quot;&lt;db_name&gt;&quot;: {
  11757. &quot;name&quot;: &quot;&lt;background_update_name&gt;&quot;,
  11758. &quot;total_item_count&quot;: 50,
  11759. &quot;total_duration_ms&quot;: 10000.0,
  11760. &quot;average_items_per_ms&quot;: 2.2,
  11761. },
  11762. }
  11763. }
  11764. </code></pre>
  11765. <p><code>enabled</code> whether the background updates are enabled or disabled.</p>
  11766. <p><code>db_name</code> the database name (usually Synapse is configured with a single database named 'master').</p>
  11767. <p>For each update:</p>
  11768. <p><code>name</code> the name of the update.
  11769. <code>total_item_count</code> total number of &quot;items&quot; processed (the meaning of 'items' depends on the update in question).
  11770. <code>total_duration_ms</code> how long the background process has been running, not including time spent sleeping.
  11771. <code>average_items_per_ms</code> how many items are processed per millisecond based on an exponential average.</p>
  11772. <h2 id="enabled"><a class="header" href="#enabled">Enabled</a></h2>
  11773. <p>This API allow pausing background updates.</p>
  11774. <p>Background updates should <em>not</em> be paused for significant periods of time, as
  11775. this can affect the performance of Synapse.</p>
  11776. <p><em>Note</em>: This won't persist over restarts.</p>
  11777. <p><em>Note</em>: This won't cancel any update query that is currently running. This is
  11778. usually fine since most queries are short lived, except for <code>CREATE INDEX</code>
  11779. background updates which won't be cancelled once started.</p>
  11780. <p>The API is:</p>
  11781. <pre><code>POST /_synapse/admin/v1/background_updates/enabled
  11782. </code></pre>
  11783. <p>with the following body:</p>
  11784. <pre><code class="language-json">{
  11785. &quot;enabled&quot;: false
  11786. }
  11787. </code></pre>
  11788. <p><code>enabled</code> sets whether the background updates are enabled or disabled.</p>
  11789. <p>The API returns the <code>enabled</code> param.</p>
  11790. <pre><code class="language-json">{
  11791. &quot;enabled&quot;: false
  11792. }
  11793. </code></pre>
  11794. <p>There is also a <code>GET</code> version which returns the <code>enabled</code> state.</p>
  11795. <h2 id="run"><a class="header" href="#run">Run</a></h2>
  11796. <p>This API schedules a specific background update to run. The job starts immediately after calling the API.</p>
  11797. <p>The API is:</p>
  11798. <pre><code>POST /_synapse/admin/v1/background_updates/start_job
  11799. </code></pre>
  11800. <p>with the following body:</p>
  11801. <pre><code class="language-json">{
  11802. &quot;job_name&quot;: &quot;populate_stats_process_rooms&quot;
  11803. }
  11804. </code></pre>
  11805. <p>The following JSON body parameters are available:</p>
  11806. <ul>
  11807. <li><code>job_name</code> - A string which job to run. Valid values are:
  11808. <ul>
  11809. <li><code>populate_stats_process_rooms</code> - Recalculate the stats for all rooms.</li>
  11810. <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>
  11811. </ul>
  11812. </li>
  11813. </ul>
  11814. <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>
  11815. <p>This API returns information about reported events.</p>
  11816. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11817. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  11818. <p>The api is:</p>
  11819. <pre><code>GET /_synapse/admin/v1/event_reports?from=0&amp;limit=10
  11820. </code></pre>
  11821. <p>It returns a JSON body like the following:</p>
  11822. <pre><code class="language-json">{
  11823. &quot;event_reports&quot;: [
  11824. {
  11825. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  11826. &quot;id&quot;: 2,
  11827. &quot;reason&quot;: &quot;foo&quot;,
  11828. &quot;score&quot;: -100,
  11829. &quot;received_ts&quot;: 1570897107409,
  11830. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  11831. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  11832. &quot;name&quot;: &quot;Matrix HQ&quot;,
  11833. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  11834. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  11835. },
  11836. {
  11837. &quot;event_id&quot;: &quot;$3IcdZsDaN_En-S1DF4EMCy3v4gNRKeOJs8W5qTOKj4I&quot;,
  11838. &quot;id&quot;: 3,
  11839. &quot;reason&quot;: &quot;bar&quot;,
  11840. &quot;score&quot;: -100,
  11841. &quot;received_ts&quot;: 1598889612059,
  11842. &quot;canonical_alias&quot;: &quot;#alias2:matrix.org&quot;,
  11843. &quot;room_id&quot;: &quot;!eGvUQuTCkHGVwNMOjv:matrix.org&quot;,
  11844. &quot;name&quot;: &quot;Your room name here&quot;,
  11845. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  11846. &quot;user_id&quot;: &quot;@bar:matrix.org&quot;
  11847. }
  11848. ],
  11849. &quot;next_token&quot;: 2,
  11850. &quot;total&quot;: 4
  11851. }
  11852. </code></pre>
  11853. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again with <code>from</code>
  11854. set to the value of <code>next_token</code>. This will return a new page.</p>
  11855. <p>If the endpoint does not return a <code>next_token</code> then there are no more reports to
  11856. paginate through.</p>
  11857. <p><strong>URL parameters:</strong></p>
  11858. <ul>
  11859. <li><code>limit</code>: integer - Is optional but is used for pagination, denoting the maximum number
  11860. of items to return in this call. Defaults to <code>100</code>.</li>
  11861. <li><code>from</code>: integer - Is optional but used for pagination, denoting the offset in the
  11862. returned results. This should be treated as an opaque value and not explicitly set to
  11863. anything other than the return value of <code>next_token</code> from a previous call. Defaults to <code>0</code>.</li>
  11864. <li><code>dir</code>: string - Direction of event report order. Whether to fetch the most recent
  11865. first (<code>b</code>) or the oldest first (<code>f</code>). Defaults to <code>b</code>.</li>
  11866. <li><code>user_id</code>: string - Is optional and filters to only return users with user IDs that
  11867. contain this value. This is the user who reported the event and wrote the reason.</li>
  11868. <li><code>room_id</code>: string - Is optional and filters to only return rooms with room IDs that
  11869. contain this value.</li>
  11870. </ul>
  11871. <p><strong>Response</strong></p>
  11872. <p>The following fields are returned in the JSON response body:</p>
  11873. <ul>
  11874. <li><code>id</code>: integer - ID of event report.</li>
  11875. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  11876. report was sent.</li>
  11877. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  11878. <li><code>name</code>: string - The name of the room.</li>
  11879. <li><code>event_id</code>: string - The ID of the reported event.</li>
  11880. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  11881. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank or <code>null</code>.</li>
  11882. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  11883. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;. May be <code>null</code>.</li>
  11884. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  11885. was reported.</li>
  11886. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  11887. have a canonical alias set.</li>
  11888. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  11889. <li><code>total</code>: integer - Total number of event reports related to the query
  11890. (<code>user_id</code> and <code>room_id</code>).</li>
  11891. </ul>
  11892. <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>
  11893. <p>This API returns information about a specific event report.</p>
  11894. <p>The api is:</p>
  11895. <pre><code>GET /_synapse/admin/v1/event_reports/&lt;report_id&gt;
  11896. </code></pre>
  11897. <p>It returns a JSON body like the following:</p>
  11898. <pre><code class="language-json">{
  11899. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  11900. &quot;event_json&quot;: {
  11901. &quot;auth_events&quot;: [
  11902. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;,
  11903. &quot;$oggsNXxzPFRE3y53SUNd7nsj69-QzKv03a1RucHu-ws&quot;
  11904. ],
  11905. &quot;content&quot;: {
  11906. &quot;body&quot;: &quot;matrix.org: This Week in Matrix&quot;,
  11907. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  11908. &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;,
  11909. &quot;msgtype&quot;: &quot;m.notice&quot;
  11910. },
  11911. &quot;depth&quot;: 546,
  11912. &quot;hashes&quot;: {
  11913. &quot;sha256&quot;: &quot;xK1//xnmvHJIOvbgXlkI8eEqdvoMmihVDJ9J4SNlsAw&quot;
  11914. },
  11915. &quot;origin&quot;: &quot;matrix.org&quot;,
  11916. &quot;origin_server_ts&quot;: 1592291711430,
  11917. &quot;prev_events&quot;: [
  11918. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;
  11919. ],
  11920. &quot;prev_state&quot;: [],
  11921. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  11922. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  11923. &quot;signatures&quot;: {
  11924. &quot;matrix.org&quot;: {
  11925. &quot;ed25519:a_JaEG&quot;: &quot;cs+OUKW/iHx5pEidbWxh0UiNNHwe46Ai9LwNz+Ah16aWDNszVIe2gaAcVZfvNsBhakQTew51tlKmL2kspXk/Dg&quot;
  11926. }
  11927. },
  11928. &quot;type&quot;: &quot;m.room.message&quot;,
  11929. &quot;unsigned&quot;: {
  11930. &quot;age_ts&quot;: 1592291711430
  11931. }
  11932. },
  11933. &quot;id&quot;: &lt;report_id&gt;,
  11934. &quot;reason&quot;: &quot;foo&quot;,
  11935. &quot;score&quot;: -100,
  11936. &quot;received_ts&quot;: 1570897107409,
  11937. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  11938. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  11939. &quot;name&quot;: &quot;Matrix HQ&quot;,
  11940. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  11941. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  11942. }
  11943. </code></pre>
  11944. <p><strong>URL parameters:</strong></p>
  11945. <ul>
  11946. <li><code>report_id</code>: string - The ID of the event report.</li>
  11947. </ul>
  11948. <p><strong>Response</strong></p>
  11949. <p>The following fields are returned in the JSON response body:</p>
  11950. <ul>
  11951. <li><code>id</code>: integer - ID of event report.</li>
  11952. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  11953. report was sent.</li>
  11954. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  11955. <li><code>name</code>: string - The name of the room.</li>
  11956. <li><code>event_id</code>: string - The ID of the reported event.</li>
  11957. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  11958. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank.</li>
  11959. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  11960. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;.</li>
  11961. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  11962. was reported.</li>
  11963. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  11964. have a canonical alias set.</li>
  11965. <li><code>event_json</code>: object - Details of the original event that was reported.</li>
  11966. </ul>
  11967. <h1 id="delete-a-specific-event-report"><a class="header" href="#delete-a-specific-event-report">Delete a specific event report</a></h1>
  11968. <p>This API deletes a specific event report. If the request is successful, the response body
  11969. will be an empty JSON object.</p>
  11970. <p>The api is:</p>
  11971. <pre><code>DELETE /_synapse/admin/v1/event_reports/&lt;report_id&gt;
  11972. </code></pre>
  11973. <p><strong>URL parameters:</strong></p>
  11974. <ul>
  11975. <li><code>report_id</code>: string - The ID of the event report.</li>
  11976. </ul>
  11977. <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>
  11978. <p>This API allows a server administrator to enable or disable some experimental features on a per-user
  11979. basis. The currently supported features are: </p>
  11980. <ul>
  11981. <li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3026">MSC3026</a>: busy
  11982. presence state enabled</li>
  11983. <li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3881">MSC3881</a>: enable remotely toggling push notifications
  11984. for another client </li>
  11985. <li><a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3967">MSC3967</a>: do not require
  11986. UIA when first uploading cross-signing keys. </li>
  11987. </ul>
  11988. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11989. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  11990. <h2 id="enablingdisabling-features"><a class="header" href="#enablingdisabling-features">Enabling/Disabling Features</a></h2>
  11991. <p>This API allows a server administrator to enable experimental features for a given user. The request must
  11992. provide a body containing the user id and listing the features to enable/disable in the following format:</p>
  11993. <pre><code class="language-json">{
  11994. &quot;features&quot;: {
  11995. &quot;msc3026&quot;:true,
  11996. &quot;msc3881&quot;:true
  11997. }
  11998. }
  11999. </code></pre>
  12000. <p>where true is used to enable the feature, and false is used to disable the feature.</p>
  12001. <p>The API is:</p>
  12002. <pre><code>PUT /_synapse/admin/v1/experimental_features/&lt;user_id&gt;
  12003. </code></pre>
  12004. <h2 id="listing-enabled-features"><a class="header" href="#listing-enabled-features">Listing Enabled Features</a></h2>
  12005. <p>To list which features are enabled/disabled for a given user send a request to the following API:</p>
  12006. <pre><code>GET /_synapse/admin/v1/experimental_features/&lt;user_id&gt;
  12007. </code></pre>
  12008. <p>It will return a list of possible features and indicate whether they are enabled or disabled for the
  12009. user like so:</p>
  12010. <pre><code class="language-json">{
  12011. &quot;features&quot;: {
  12012. &quot;msc3026&quot;: true,
  12013. &quot;msc3881&quot;: false,
  12014. &quot;msc3967&quot;: false
  12015. }
  12016. }
  12017. </code></pre>
  12018. <div style="break-before: page; page-break-before: always;"></div><h1 id="querying-media"><a class="header" href="#querying-media">Querying media</a></h1>
  12019. <p>These APIs allow extracting media information from the homeserver.</p>
  12020. <p>Details about the format of the <code>media_id</code> and storage of the media in the file system
  12021. are documented under <a href="admin_api/../media_repository.html">media repository</a>.</p>
  12022. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12023. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12024. <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>
  12025. <p>This API gets a list of known media in a room.
  12026. However, it only shows media from unencrypted events or rooms.</p>
  12027. <p>The API is:</p>
  12028. <pre><code>GET /_synapse/admin/v1/room/&lt;room_id&gt;/media
  12029. </code></pre>
  12030. <p>The API returns a JSON body like the following:</p>
  12031. <pre><code class="language-json">{
  12032. &quot;local&quot;: [
  12033. &quot;mxc://localhost/xwvutsrqponmlkjihgfedcba&quot;,
  12034. &quot;mxc://localhost/abcdefghijklmnopqrstuvwx&quot;
  12035. ],
  12036. &quot;remote&quot;: [
  12037. &quot;mxc://matrix.org/xwvutsrqponmlkjihgfedcba&quot;,
  12038. &quot;mxc://matrix.org/abcdefghijklmnopqrstuvwx&quot;
  12039. ]
  12040. }
  12041. </code></pre>
  12042. <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>
  12043. <p>Listing all media that has been uploaded by a local user can be achieved through
  12044. the use of the
  12045. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>
  12046. Admin API.</p>
  12047. <h1 id="quarantine-media"><a class="header" href="#quarantine-media">Quarantine media</a></h1>
  12048. <p>Quarantining media means that it is marked as inaccessible by users. It applies
  12049. to any local media, and any locally-cached copies of remote media.</p>
  12050. <p>The media file itself (and any thumbnails) is not deleted from the server.</p>
  12051. <h2 id="quarantining-media-by-id"><a class="header" href="#quarantining-media-by-id">Quarantining media by ID</a></h2>
  12052. <p>This API quarantines a single piece of local or remote media.</p>
  12053. <p>Request:</p>
  12054. <pre><code>POST /_synapse/admin/v1/media/quarantine/&lt;server_name&gt;/&lt;media_id&gt;
  12055. {}
  12056. </code></pre>
  12057. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  12058. form of <code>abcdefg12345...</code>.</p>
  12059. <p>Response:</p>
  12060. <pre><code class="language-json">{}
  12061. </code></pre>
  12062. <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>
  12063. <p>This API removes a single piece of local or remote media from quarantine.</p>
  12064. <p>Request:</p>
  12065. <pre><code>POST /_synapse/admin/v1/media/unquarantine/&lt;server_name&gt;/&lt;media_id&gt;
  12066. {}
  12067. </code></pre>
  12068. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  12069. form of <code>abcdefg12345...</code>.</p>
  12070. <p>Response:</p>
  12071. <pre><code class="language-json">{}
  12072. </code></pre>
  12073. <h2 id="quarantining-media-in-a-room"><a class="header" href="#quarantining-media-in-a-room">Quarantining media in a room</a></h2>
  12074. <p>This API quarantines all local and remote media in a room.</p>
  12075. <p>Request:</p>
  12076. <pre><code>POST /_synapse/admin/v1/room/&lt;room_id&gt;/media/quarantine
  12077. {}
  12078. </code></pre>
  12079. <p>Where <code>room_id</code> is in the form of <code>!roomid12345:example.org</code>.</p>
  12080. <p>Response:</p>
  12081. <pre><code class="language-json">{
  12082. &quot;num_quarantined&quot;: 10
  12083. }
  12084. </code></pre>
  12085. <p>The following fields are returned in the JSON response body:</p>
  12086. <ul>
  12087. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  12088. </ul>
  12089. <p>Note that there is a legacy endpoint, <code>POST /_synapse/admin/v1/quarantine_media/&lt;room_id&gt;</code>, that operates the same.
  12090. However, it is deprecated and may be removed in a future release.</p>
  12091. <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>
  12092. <p>This API quarantines all <em>local</em> media that a <em>local</em> user has uploaded. That is to say, if
  12093. you would like to quarantine media uploaded by a user on a remote homeserver, you should
  12094. instead use one of the other APIs.</p>
  12095. <p>Request:</p>
  12096. <pre><code>POST /_synapse/admin/v1/user/&lt;user_id&gt;/media/quarantine
  12097. {}
  12098. </code></pre>
  12099. <p>URL Parameters</p>
  12100. <ul>
  12101. <li><code>user_id</code>: string - User ID in the form of <code>@bob:example.org</code></li>
  12102. </ul>
  12103. <p>Response:</p>
  12104. <pre><code class="language-json">{
  12105. &quot;num_quarantined&quot;: 10
  12106. }
  12107. </code></pre>
  12108. <p>The following fields are returned in the JSON response body:</p>
  12109. <ul>
  12110. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  12111. </ul>
  12112. <h2 id="protecting-media-from-being-quarantined"><a class="header" href="#protecting-media-from-being-quarantined">Protecting media from being quarantined</a></h2>
  12113. <p>This API protects a single piece of local media from being quarantined using the
  12114. above APIs. This is useful for sticker packs and other shared media which you do
  12115. not want to get quarantined, especially when
  12116. <a href="admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantining media in a room</a>.</p>
  12117. <p>Request:</p>
  12118. <pre><code>POST /_synapse/admin/v1/media/protect/&lt;media_id&gt;
  12119. {}
  12120. </code></pre>
  12121. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  12122. <p>Response:</p>
  12123. <pre><code class="language-json">{}
  12124. </code></pre>
  12125. <h2 id="unprotecting-media-from-being-quarantined"><a class="header" href="#unprotecting-media-from-being-quarantined">Unprotecting media from being quarantined</a></h2>
  12126. <p>This API reverts the protection of a media.</p>
  12127. <p>Request:</p>
  12128. <pre><code>POST /_synapse/admin/v1/media/unprotect/&lt;media_id&gt;
  12129. {}
  12130. </code></pre>
  12131. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  12132. <p>Response:</p>
  12133. <pre><code class="language-json">{}
  12134. </code></pre>
  12135. <h1 id="delete-local-media"><a class="header" href="#delete-local-media">Delete local media</a></h1>
  12136. <p>This API deletes the <em>local</em> media from the disk of your own server.
  12137. This includes any local thumbnails and copies of media downloaded from
  12138. remote homeservers.
  12139. This API will not affect media that has been uploaded to external
  12140. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).
  12141. See also <a href="admin_api/media_admin_api.html#purge-remote-media-api">Purge Remote Media API</a>.</p>
  12142. <h2 id="delete-a-specific-local-media"><a class="header" href="#delete-a-specific-local-media">Delete a specific local media</a></h2>
  12143. <p>Delete a specific <code>media_id</code>.</p>
  12144. <p>Request:</p>
  12145. <pre><code>DELETE /_synapse/admin/v1/media/&lt;server_name&gt;/&lt;media_id&gt;
  12146. {}
  12147. </code></pre>
  12148. <p>URL Parameters</p>
  12149. <ul>
  12150. <li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>)</li>
  12151. <li><code>media_id</code>: string - The ID of the media (e.g <code>abcdefghijklmnopqrstuvwx</code>)</li>
  12152. </ul>
  12153. <p>Response:</p>
  12154. <pre><code class="language-json">{
  12155. &quot;deleted_media&quot;: [
  12156. &quot;abcdefghijklmnopqrstuvwx&quot;
  12157. ],
  12158. &quot;total&quot;: 1
  12159. }
  12160. </code></pre>
  12161. <p>The following fields are returned in the JSON response body:</p>
  12162. <ul>
  12163. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  12164. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  12165. </ul>
  12166. <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>
  12167. <p>Request:</p>
  12168. <pre><code>POST /_synapse/admin/v1/media/delete?before_ts=&lt;before_ts&gt;
  12169. {}
  12170. </code></pre>
  12171. <p><em>Deprecated in Synapse v1.78.0:</em> This API is available at the deprecated endpoint:</p>
  12172. <pre><code>POST /_synapse/admin/v1/media/&lt;server_name&gt;/delete?before_ts=&lt;before_ts&gt;
  12173. {}
  12174. </code></pre>
  12175. <p>URL Parameters</p>
  12176. <ul>
  12177. <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>
  12178. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  12179. Files that were last used before this timestamp will be deleted. It is the timestamp of
  12180. last access, not the timestamp when the file was created.</li>
  12181. <li><code>size_gt</code>: Optional - string representing a positive integer - Size of the media in bytes.
  12182. Files that are larger will be deleted. Defaults to <code>0</code>.</li>
  12183. <li><code>keep_profiles</code>: Optional - string representing a boolean - Switch to also delete files
  12184. that are still used in image data (e.g user profile, room avatar).
  12185. If <code>false</code> these files will be deleted. Defaults to <code>true</code>.</li>
  12186. </ul>
  12187. <p>Response:</p>
  12188. <pre><code class="language-json">{
  12189. &quot;deleted_media&quot;: [
  12190. &quot;abcdefghijklmnopqrstuvwx&quot;,
  12191. &quot;abcdefghijklmnopqrstuvwz&quot;
  12192. ],
  12193. &quot;total&quot;: 2
  12194. }
  12195. </code></pre>
  12196. <p>The following fields are returned in the JSON response body:</p>
  12197. <ul>
  12198. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  12199. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  12200. </ul>
  12201. <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>
  12202. <p>You can find details of how to delete multiple media uploaded by a user in
  12203. <a href="admin_api/user_admin_api.html#delete-media-uploaded-by-a-user">User Admin API</a>.</p>
  12204. <h1 id="purge-remote-media-api"><a class="header" href="#purge-remote-media-api">Purge Remote Media API</a></h1>
  12205. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  12206. <p>The API is:</p>
  12207. <pre><code>POST /_synapse/admin/v1/purge_media_cache?before_ts=&lt;unix_timestamp_in_ms&gt;
  12208. {}
  12209. </code></pre>
  12210. <p>URL Parameters</p>
  12211. <ul>
  12212. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  12213. All cached media that was last accessed before this timestamp will be removed.</li>
  12214. </ul>
  12215. <p>Response:</p>
  12216. <pre><code class="language-json">{
  12217. &quot;deleted&quot;: 10
  12218. }
  12219. </code></pre>
  12220. <p>The following fields are returned in the JSON response body:</p>
  12221. <ul>
  12222. <li><code>deleted</code>: integer - The number of media items successfully deleted</li>
  12223. </ul>
  12224. <p>If the user re-requests purged remote media, synapse will re-request the media
  12225. from the originating server.</p>
  12226. <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>
  12227. <p>The purge history API allows server admins to purge historic events from their
  12228. database, reclaiming disk space.</p>
  12229. <p>Depending on the amount of history being purged a call to the API may take
  12230. several minutes or longer. During this period users will not be able to
  12231. paginate further back in the room from the point being purged from.</p>
  12232. <p>Note that Synapse requires at least one message in each room, so it will never
  12233. delete the last message in a room.</p>
  12234. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12235. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12236. <p>The API is:</p>
  12237. <pre><code>POST /_synapse/admin/v1/purge_history/&lt;room_id&gt;[/&lt;event_id&gt;]
  12238. </code></pre>
  12239. <p>By default, events sent by local users are not deleted, as they may represent
  12240. the only copies of this content in existence. (Events sent by remote users are
  12241. deleted.)</p>
  12242. <p>Room state data (such as joins, leaves, topic) is always preserved.</p>
  12243. <p>To delete local message events as well, set <code>delete_local_events</code> in the body:</p>
  12244. <pre><code class="language-json">{
  12245. &quot;delete_local_events&quot;: true
  12246. }
  12247. </code></pre>
  12248. <p>The caller must specify the point in the room to purge up to. This can be
  12249. specified by including an event_id in the URI, or by setting a
  12250. <code>purge_up_to_event_id</code> or <code>purge_up_to_ts</code> in the request body. If an event
  12251. id is given, that event (and others at the same graph depth) will be retained.
  12252. If <code>purge_up_to_ts</code> is given, it should be a timestamp since the unix epoch,
  12253. in milliseconds.</p>
  12254. <p>The API starts the purge running, and returns immediately with a JSON body with
  12255. a purge id:</p>
  12256. <pre><code class="language-json">{
  12257. &quot;purge_id&quot;: &quot;&lt;opaque id&gt;&quot;
  12258. }
  12259. </code></pre>
  12260. <h2 id="purge-status-query"><a class="header" href="#purge-status-query">Purge status query</a></h2>
  12261. <p>It is possible to poll for updates on recent purges with a second API;</p>
  12262. <pre><code>GET /_synapse/admin/v1/purge_history_status/&lt;purge_id&gt;
  12263. </code></pre>
  12264. <p>This API returns a JSON body like the following:</p>
  12265. <pre><code class="language-json">{
  12266. &quot;status&quot;: &quot;active&quot;
  12267. }
  12268. </code></pre>
  12269. <p>The status will be one of <code>active</code>, <code>complete</code>, or <code>failed</code>.</p>
  12270. <p>If <code>status</code> is <code>failed</code> there will be a string <code>error</code> with the error message.</p>
  12271. <h2 id="reclaim-disk-space-postgres"><a class="header" href="#reclaim-disk-space-postgres">Reclaim disk space (Postgres)</a></h2>
  12272. <p>To reclaim the disk space and return it to the operating system, you need to run
  12273. <code>VACUUM FULL;</code> on the database.</p>
  12274. <p><a href="https://www.postgresql.org/docs/current/sql-vacuum.html">https://www.postgresql.org/docs/current/sql-vacuum.html</a></p>
  12275. <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>
  12276. <p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
  12277. <p>This API allows for the creation of users in an administrative and
  12278. non-interactive way. This is generally used for bootstrapping a Synapse
  12279. instance with administrator accounts.</p>
  12280. <p>To authenticate yourself to the server, you will need both the shared secret
  12281. (<a href="admin_api/../usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>
  12282. in the homeserver configuration), and a one-time nonce. If the registration
  12283. shared secret is not configured, this API is not enabled.</p>
  12284. <p>To fetch the nonce, you need to request one from the API:</p>
  12285. <pre><code>&gt; GET /_synapse/admin/v1/register
  12286. &lt; {&quot;nonce&quot;: &quot;thisisanonce&quot;}
  12287. </code></pre>
  12288. <p>Once you have the nonce, you can make a <code>POST</code> to the same URL with a JSON
  12289. body containing the nonce, username, password, whether they are an admin
  12290. (optional, False by default), and a HMAC digest of the content. Also you can
  12291. set the displayname (optional, <code>username</code> by default).</p>
  12292. <p>As an example:</p>
  12293. <pre><code>&gt; POST /_synapse/admin/v1/register
  12294. &gt; {
  12295. &quot;nonce&quot;: &quot;thisisanonce&quot;,
  12296. &quot;username&quot;: &quot;pepper_roni&quot;,
  12297. &quot;displayname&quot;: &quot;Pepper Roni&quot;,
  12298. &quot;password&quot;: &quot;pizza&quot;,
  12299. &quot;admin&quot;: true,
  12300. &quot;mac&quot;: &quot;mac_digest_here&quot;
  12301. }
  12302. &lt; {
  12303. &quot;access_token&quot;: &quot;token_here&quot;,
  12304. &quot;user_id&quot;: &quot;@pepper_roni:localhost&quot;,
  12305. &quot;home_server&quot;: &quot;test&quot;,
  12306. &quot;device_id&quot;: &quot;device_id_here&quot;
  12307. }
  12308. </code></pre>
  12309. <p>The MAC is the hex digest output of the HMAC-SHA1 algorithm, with the key being
  12310. the shared secret and the content being the nonce, user, password, either the
  12311. string &quot;admin&quot; or &quot;notadmin&quot;, and optionally the user_type
  12312. each separated by NULs.</p>
  12313. <p>Here is an easy way to generate the HMAC digest if you have Bash and OpenSSL:</p>
  12314. <pre><code class="language-bash"># Update these values and then paste this code block into a bash terminal
  12315. nonce='thisisanonce'
  12316. username='pepper_roni'
  12317. password='pizza'
  12318. admin='admin'
  12319. secret='shared_secret'
  12320. printf '%s\0%s\0%s\0%s' &quot;$nonce&quot; &quot;$username&quot; &quot;$password&quot; &quot;$admin&quot; |
  12321. openssl sha1 -hmac &quot;$secret&quot; |
  12322. awk '{print $2}'
  12323. </code></pre>
  12324. <p>For an example of generation in Python:</p>
  12325. <pre><code class="language-python">import hmac, hashlib
  12326. def generate_mac(nonce, user, password, admin=False, user_type=None):
  12327. mac = hmac.new(
  12328. key=shared_secret,
  12329. digestmod=hashlib.sha1,
  12330. )
  12331. mac.update(nonce.encode('utf8'))
  12332. mac.update(b&quot;\x00&quot;)
  12333. mac.update(user.encode('utf8'))
  12334. mac.update(b&quot;\x00&quot;)
  12335. mac.update(password.encode('utf8'))
  12336. mac.update(b&quot;\x00&quot;)
  12337. mac.update(b&quot;admin&quot; if admin else b&quot;notadmin&quot;)
  12338. if user_type:
  12339. mac.update(b&quot;\x00&quot;)
  12340. mac.update(user_type.encode('utf8'))
  12341. return mac.hexdigest()
  12342. </code></pre>
  12343. <div style="break-before: page; page-break-before: always;"></div><h1 id="registration-tokens"><a class="header" href="#registration-tokens">Registration Tokens</a></h1>
  12344. <p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
  12345. <p>This API allows you to manage tokens which can be used to authenticate
  12346. registration requests, as proposed in
  12347. <a href="https://github.com/matrix-org/matrix-doc/blob/main/proposals/3231-token-authenticated-registration.md">MSC3231</a>
  12348. and stabilised in version 1.2 of the Matrix specification.
  12349. To use it, you will need to enable the <code>registration_requires_token</code> config
  12350. option, and authenticate by providing an <code>access_token</code> for a server admin:
  12351. see <a href="usage/administration/admin_api/../admin_api/">Admin API</a>.</p>
  12352. <h2 id="registration-token-objects"><a class="header" href="#registration-token-objects">Registration token objects</a></h2>
  12353. <p>Most endpoints make use of JSON objects that contain details about tokens.
  12354. These objects have the following fields:</p>
  12355. <ul>
  12356. <li><code>token</code>: The token which can be used to authenticate registration.</li>
  12357. <li><code>uses_allowed</code>: The number of times the token can be used to complete a
  12358. registration before it becomes invalid.</li>
  12359. <li><code>pending</code>: The number of pending uses the token has. When someone uses
  12360. the token to authenticate themselves, the pending counter is incremented
  12361. so that the token is not used more than the permitted number of times.
  12362. When the person completes registration the pending counter is decremented,
  12363. and the completed counter is incremented.</li>
  12364. <li><code>completed</code>: The number of times the token has been used to successfully
  12365. complete a registration.</li>
  12366. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  12367. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  12368. To convert this into a human-readable form you can remove the milliseconds
  12369. and use the <code>date</code> command. For example, <code>date -d '@1625394937'</code>.</li>
  12370. </ul>
  12371. <h2 id="list-all-tokens"><a class="header" href="#list-all-tokens">List all tokens</a></h2>
  12372. <p>Lists all tokens and details about them. If the request is successful, the top
  12373. level JSON object will have a <code>registration_tokens</code> key which is an array of
  12374. registration token objects.</p>
  12375. <pre><code>GET /_synapse/admin/v1/registration_tokens
  12376. </code></pre>
  12377. <p>Optional query parameters:</p>
  12378. <ul>
  12379. <li><code>valid</code>: <code>true</code> or <code>false</code>. If <code>true</code>, only valid tokens are returned.
  12380. If <code>false</code>, only tokens that have expired or have had all uses exhausted are
  12381. returned. If omitted, all tokens are returned regardless of validity.</li>
  12382. </ul>
  12383. <p>Example:</p>
  12384. <pre><code>GET /_synapse/admin/v1/registration_tokens
  12385. </code></pre>
  12386. <pre><code>200 OK
  12387. {
  12388. &quot;registration_tokens&quot;: [
  12389. {
  12390. &quot;token&quot;: &quot;abcd&quot;,
  12391. &quot;uses_allowed&quot;: 3,
  12392. &quot;pending&quot;: 0,
  12393. &quot;completed&quot;: 1,
  12394. &quot;expiry_time&quot;: null
  12395. },
  12396. {
  12397. &quot;token&quot;: &quot;pqrs&quot;,
  12398. &quot;uses_allowed&quot;: 2,
  12399. &quot;pending&quot;: 1,
  12400. &quot;completed&quot;: 1,
  12401. &quot;expiry_time&quot;: null
  12402. },
  12403. {
  12404. &quot;token&quot;: &quot;wxyz&quot;,
  12405. &quot;uses_allowed&quot;: null,
  12406. &quot;pending&quot;: 0,
  12407. &quot;completed&quot;: 9,
  12408. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  12409. }
  12410. ]
  12411. }
  12412. </code></pre>
  12413. <p>Example using the <code>valid</code> query parameter:</p>
  12414. <pre><code>GET /_synapse/admin/v1/registration_tokens?valid=false
  12415. </code></pre>
  12416. <pre><code>200 OK
  12417. {
  12418. &quot;registration_tokens&quot;: [
  12419. {
  12420. &quot;token&quot;: &quot;pqrs&quot;,
  12421. &quot;uses_allowed&quot;: 2,
  12422. &quot;pending&quot;: 1,
  12423. &quot;completed&quot;: 1,
  12424. &quot;expiry_time&quot;: null
  12425. },
  12426. {
  12427. &quot;token&quot;: &quot;wxyz&quot;,
  12428. &quot;uses_allowed&quot;: null,
  12429. &quot;pending&quot;: 0,
  12430. &quot;completed&quot;: 9,
  12431. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  12432. }
  12433. ]
  12434. }
  12435. </code></pre>
  12436. <h2 id="get-one-token"><a class="header" href="#get-one-token">Get one token</a></h2>
  12437. <p>Get details about a single token. If the request is successful, the response
  12438. body will be a registration token object.</p>
  12439. <pre><code>GET /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  12440. </code></pre>
  12441. <p>Path parameters:</p>
  12442. <ul>
  12443. <li><code>token</code>: The registration token to return details of.</li>
  12444. </ul>
  12445. <p>Example:</p>
  12446. <pre><code>GET /_synapse/admin/v1/registration_tokens/abcd
  12447. </code></pre>
  12448. <pre><code>200 OK
  12449. {
  12450. &quot;token&quot;: &quot;abcd&quot;,
  12451. &quot;uses_allowed&quot;: 3,
  12452. &quot;pending&quot;: 0,
  12453. &quot;completed&quot;: 1,
  12454. &quot;expiry_time&quot;: null
  12455. }
  12456. </code></pre>
  12457. <h2 id="create-token"><a class="header" href="#create-token">Create token</a></h2>
  12458. <p>Create a new registration token. If the request is successful, the newly created
  12459. token will be returned as a registration token object in the response body.</p>
  12460. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  12461. </code></pre>
  12462. <p>The request body must be a JSON object and can contain the following fields:</p>
  12463. <ul>
  12464. <li><code>token</code>: The registration token. A string of no more than 64 characters that
  12465. consists only of characters matched by the regex <code>[A-Za-z0-9._~-]</code>.
  12466. Default: randomly generated.</li>
  12467. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  12468. a registration before it becomes invalid.
  12469. Default: <code>null</code> (unlimited uses).</li>
  12470. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  12471. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  12472. You could use, for example, <code>date '+%s000' -d 'tomorrow'</code>.
  12473. Default: <code>null</code> (token does not expire).</li>
  12474. <li><code>length</code>: The length of the token randomly generated if <code>token</code> is not
  12475. specified. Must be between 1 and 64 inclusive. Default: <code>16</code>.</li>
  12476. </ul>
  12477. <p>If a field is omitted the default is used.</p>
  12478. <p>Example using defaults:</p>
  12479. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  12480. {}
  12481. </code></pre>
  12482. <pre><code>200 OK
  12483. {
  12484. &quot;token&quot;: &quot;0M-9jbkf2t_Tgiw1&quot;,
  12485. &quot;uses_allowed&quot;: null,
  12486. &quot;pending&quot;: 0,
  12487. &quot;completed&quot;: 0,
  12488. &quot;expiry_time&quot;: null
  12489. }
  12490. </code></pre>
  12491. <p>Example specifying some fields:</p>
  12492. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  12493. {
  12494. &quot;token&quot;: &quot;defg&quot;,
  12495. &quot;uses_allowed&quot;: 1
  12496. }
  12497. </code></pre>
  12498. <pre><code>200 OK
  12499. {
  12500. &quot;token&quot;: &quot;defg&quot;,
  12501. &quot;uses_allowed&quot;: 1,
  12502. &quot;pending&quot;: 0,
  12503. &quot;completed&quot;: 0,
  12504. &quot;expiry_time&quot;: null
  12505. }
  12506. </code></pre>
  12507. <h2 id="update-token"><a class="header" href="#update-token">Update token</a></h2>
  12508. <p>Update the number of allowed uses or expiry time of a token. If the request is
  12509. successful, the updated token will be returned as a registration token object
  12510. in the response body.</p>
  12511. <pre><code>PUT /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  12512. </code></pre>
  12513. <p>Path parameters:</p>
  12514. <ul>
  12515. <li><code>token</code>: The registration token to update.</li>
  12516. </ul>
  12517. <p>The request body must be a JSON object and can contain the following fields:</p>
  12518. <ul>
  12519. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  12520. a registration before it becomes invalid. By setting <code>uses_allowed</code> to <code>0</code>
  12521. the token can be easily made invalid without deleting it.
  12522. If <code>null</code> the token will have an unlimited number of uses.</li>
  12523. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  12524. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  12525. If <code>null</code> the token will not expire.</li>
  12526. </ul>
  12527. <p>If a field is omitted its value is not modified.</p>
  12528. <p>Example:</p>
  12529. <pre><code>PUT /_synapse/admin/v1/registration_tokens/defg
  12530. {
  12531. &quot;expiry_time&quot;: 4781243146000 // 2121-07-06 11:05:46 UTC
  12532. }
  12533. </code></pre>
  12534. <pre><code>200 OK
  12535. {
  12536. &quot;token&quot;: &quot;defg&quot;,
  12537. &quot;uses_allowed&quot;: 1,
  12538. &quot;pending&quot;: 0,
  12539. &quot;completed&quot;: 0,
  12540. &quot;expiry_time&quot;: 4781243146000
  12541. }
  12542. </code></pre>
  12543. <h2 id="delete-token"><a class="header" href="#delete-token">Delete token</a></h2>
  12544. <p>Delete a registration token. If the request is successful, the response body
  12545. will be an empty JSON object.</p>
  12546. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  12547. </code></pre>
  12548. <p>Path parameters:</p>
  12549. <ul>
  12550. <li><code>token</code>: The registration token to delete.</li>
  12551. </ul>
  12552. <p>Example:</p>
  12553. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/wxyz
  12554. </code></pre>
  12555. <pre><code>200 OK
  12556. {}
  12557. </code></pre>
  12558. <h2 id="errors"><a class="header" href="#errors">Errors</a></h2>
  12559. <p>If a request fails a &quot;standard error response&quot; will be returned as defined in
  12560. the <a href="https://matrix.org/docs/spec/client_server/r0.6.1#api-standards">Matrix Client-Server API specification</a>.</p>
  12561. <p>For example, if the token specified in a path parameter does not exist a
  12562. <code>404 Not Found</code> error will be returned.</p>
  12563. <pre><code>GET /_synapse/admin/v1/registration_tokens/1234
  12564. </code></pre>
  12565. <pre><code>404 Not Found
  12566. {
  12567. &quot;errcode&quot;: &quot;M_NOT_FOUND&quot;,
  12568. &quot;error&quot;: &quot;No such registration token: 1234&quot;
  12569. }
  12570. </code></pre>
  12571. <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>
  12572. <p>This API allows an administrator to join an user account with a given <code>user_id</code>
  12573. to a room with a given <code>room_id_or_alias</code>. You can only modify the membership of
  12574. local users. The server administrator must be in the room and have permission to
  12575. invite users.</p>
  12576. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12577. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12578. <h2 id="parameters"><a class="header" href="#parameters">Parameters</a></h2>
  12579. <p>The following parameters are available:</p>
  12580. <ul>
  12581. <li><code>user_id</code> - Fully qualified user: for example, <code>@user:server.com</code>.</li>
  12582. <li><code>room_id_or_alias</code> - The room identifier or alias to join: for example,
  12583. <code>!636q39766251:server.com</code>.</li>
  12584. </ul>
  12585. <h2 id="usage-1"><a class="header" href="#usage-1">Usage</a></h2>
  12586. <pre><code>POST /_synapse/admin/v1/join/&lt;room_id_or_alias&gt;
  12587. {
  12588. &quot;user_id&quot;: &quot;@user:server.com&quot;
  12589. }
  12590. </code></pre>
  12591. <p>Response:</p>
  12592. <pre><code class="language-json">{
  12593. &quot;room_id&quot;: &quot;!636q39766251:server.com&quot;
  12594. }
  12595. </code></pre>
  12596. <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>
  12597. <p>The List Room admin API allows server admins to get a list of rooms on their
  12598. server. There are various parameters available that allow for filtering and
  12599. sorting the returned list. This API supports pagination.</p>
  12600. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12601. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12602. <p><strong>Parameters</strong></p>
  12603. <p>The following query parameters are available:</p>
  12604. <ul>
  12605. <li>
  12606. <p><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</p>
  12607. </li>
  12608. <li>
  12609. <p><code>limit</code> - Maximum amount of rooms to return. Defaults to <code>100</code>.</p>
  12610. </li>
  12611. <li>
  12612. <p><code>order_by</code> - The method in which to sort the returned list of rooms. Valid values are:</p>
  12613. <ul>
  12614. <li><code>alphabetical</code> - Same as <code>name</code>. This is deprecated.</li>
  12615. <li><code>size</code> - Same as <code>joined_members</code>. This is deprecated.</li>
  12616. <li><code>name</code> - Rooms are ordered alphabetically by room name. This is the default.</li>
  12617. <li><code>canonical_alias</code> - Rooms are ordered alphabetically by main alias address of the room.</li>
  12618. <li><code>joined_members</code> - Rooms are ordered by the number of members. Largest to smallest.</li>
  12619. <li><code>joined_local_members</code> - Rooms are ordered by the number of local members. Largest to smallest.</li>
  12620. <li><code>version</code> - Rooms are ordered by room version. Largest to smallest.</li>
  12621. <li><code>creator</code> - Rooms are ordered alphabetically by creator of the room.</li>
  12622. <li><code>encryption</code> - Rooms are ordered alphabetically by the end-to-end encryption algorithm.</li>
  12623. <li><code>federatable</code> - Rooms are ordered by whether the room is federatable.</li>
  12624. <li><code>public</code> - Rooms are ordered by visibility in room list.</li>
  12625. <li><code>join_rules</code> - Rooms are ordered alphabetically by join rules of the room.</li>
  12626. <li><code>guest_access</code> - Rooms are ordered alphabetically by guest access option of the room.</li>
  12627. <li><code>history_visibility</code> - Rooms are ordered alphabetically by visibility of history of the room.</li>
  12628. <li><code>state_events</code> - Rooms are ordered by number of state events. Largest to smallest.</li>
  12629. </ul>
  12630. </li>
  12631. <li>
  12632. <p><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  12633. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  12634. </li>
  12635. <li>
  12636. <p><code>search_term</code> - Filter rooms by their room name, canonical alias and room id.
  12637. Specifically, rooms are selected if the search term is contained in</p>
  12638. <ul>
  12639. <li>the room's name,</li>
  12640. <li>the local part of the room's canonical alias, or</li>
  12641. <li>the complete (local and server part) room's id (case sensitive).</li>
  12642. </ul>
  12643. <p>Defaults to no filtering.</p>
  12644. </li>
  12645. </ul>
  12646. <p><strong>Response</strong></p>
  12647. <p>The following fields are possible in the JSON response body:</p>
  12648. <ul>
  12649. <li><code>rooms</code> - An array of objects, each containing information about a room.
  12650. <ul>
  12651. <li>Room objects contain the following fields:
  12652. <ul>
  12653. <li><code>room_id</code> - The ID of the room.</li>
  12654. <li><code>name</code> - The name of the room.</li>
  12655. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  12656. <li><code>joined_members</code> - How many users are currently in the room.</li>
  12657. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  12658. <li><code>version</code> - The version of the room as a string.</li>
  12659. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  12660. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  12661. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  12662. <li><code>public</code> - Whether the room is visible in room directory.</li>
  12663. <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>
  12664. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  12665. <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>
  12666. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  12667. <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>
  12668. </ul>
  12669. </li>
  12670. </ul>
  12671. </li>
  12672. <li><code>offset</code> - The current pagination offset in rooms. This parameter should be
  12673. used instead of <code>next_token</code> for room offset as <code>next_token</code> is
  12674. not intended to be parsed.</li>
  12675. <li><code>total_rooms</code> - The total number of rooms this query can return. Using this
  12676. and <code>offset</code>, you have enough information to know the current
  12677. progression through the list.</li>
  12678. <li><code>next_batch</code> - If this field is present, we know that there are potentially
  12679. more rooms on the server that did not all fit into this response.
  12680. We can use <code>next_batch</code> to get the &quot;next page&quot; of results. To do
  12681. so, simply repeat your request, setting the <code>from</code> parameter to
  12682. the value of <code>next_batch</code>.</li>
  12683. <li><code>prev_batch</code> - If this field is present, it is possible to paginate backwards.
  12684. Use <code>prev_batch</code> for the <code>from</code> value in the next request to
  12685. get the &quot;previous page&quot; of results.</li>
  12686. </ul>
  12687. <p>The API is:</p>
  12688. <p>A standard request with no filtering:</p>
  12689. <pre><code>GET /_synapse/admin/v1/rooms
  12690. </code></pre>
  12691. <p>A response body like the following is returned:</p>
  12692. <pre><code class="language-json">{
  12693. &quot;rooms&quot;: [
  12694. {
  12695. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  12696. &quot;name&quot;: &quot;Matrix HQ&quot;,
  12697. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  12698. &quot;joined_members&quot;: 8326,
  12699. &quot;joined_local_members&quot;: 2,
  12700. &quot;version&quot;: &quot;1&quot;,
  12701. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12702. &quot;encryption&quot;: null,
  12703. &quot;federatable&quot;: true,
  12704. &quot;public&quot;: true,
  12705. &quot;join_rules&quot;: &quot;invite&quot;,
  12706. &quot;guest_access&quot;: null,
  12707. &quot;history_visibility&quot;: &quot;shared&quot;,
  12708. &quot;state_events&quot;: 93534,
  12709. &quot;room_type&quot;: &quot;m.space&quot;
  12710. },
  12711. ... (8 hidden items) ...
  12712. {
  12713. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  12714. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  12715. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  12716. &quot;joined_members&quot;: 314,
  12717. &quot;joined_local_members&quot;: 20,
  12718. &quot;version&quot;: &quot;4&quot;,
  12719. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12720. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  12721. &quot;federatable&quot;: true,
  12722. &quot;public&quot;: false,
  12723. &quot;join_rules&quot;: &quot;invite&quot;,
  12724. &quot;guest_access&quot;: null,
  12725. &quot;history_visibility&quot;: &quot;shared&quot;,
  12726. &quot;state_events&quot;: 8345,
  12727. &quot;room_type&quot;: null
  12728. }
  12729. ],
  12730. &quot;offset&quot;: 0,
  12731. &quot;total_rooms&quot;: 10
  12732. }
  12733. </code></pre>
  12734. <p>Filtering by room name:</p>
  12735. <pre><code>GET /_synapse/admin/v1/rooms?search_term=TWIM
  12736. </code></pre>
  12737. <p>A response body like the following is returned:</p>
  12738. <pre><code class="language-json">{
  12739. &quot;rooms&quot;: [
  12740. {
  12741. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  12742. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  12743. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  12744. &quot;joined_members&quot;: 314,
  12745. &quot;joined_local_members&quot;: 20,
  12746. &quot;version&quot;: &quot;4&quot;,
  12747. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12748. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  12749. &quot;federatable&quot;: true,
  12750. &quot;public&quot;: false,
  12751. &quot;join_rules&quot;: &quot;invite&quot;,
  12752. &quot;guest_access&quot;: null,
  12753. &quot;history_visibility&quot;: &quot;shared&quot;,
  12754. &quot;state_events&quot;: 8,
  12755. &quot;room_type&quot;: null
  12756. }
  12757. ],
  12758. &quot;offset&quot;: 0,
  12759. &quot;total_rooms&quot;: 1
  12760. }
  12761. </code></pre>
  12762. <p>Paginating through a list of rooms:</p>
  12763. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size
  12764. </code></pre>
  12765. <p>A response body like the following is returned:</p>
  12766. <pre><code class="language-json">{
  12767. &quot;rooms&quot;: [
  12768. {
  12769. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  12770. &quot;name&quot;: &quot;Matrix HQ&quot;,
  12771. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  12772. &quot;joined_members&quot;: 8326,
  12773. &quot;joined_local_members&quot;: 2,
  12774. &quot;version&quot;: &quot;1&quot;,
  12775. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12776. &quot;encryption&quot;: null,
  12777. &quot;federatable&quot;: true,
  12778. &quot;public&quot;: true,
  12779. &quot;join_rules&quot;: &quot;invite&quot;,
  12780. &quot;guest_access&quot;: null,
  12781. &quot;history_visibility&quot;: &quot;shared&quot;,
  12782. &quot;state_events&quot;: 93534,
  12783. &quot;room_type&quot;: null
  12784. },
  12785. ... (98 hidden items) ...
  12786. {
  12787. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  12788. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  12789. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  12790. &quot;joined_members&quot;: 314,
  12791. &quot;joined_local_members&quot;: 20,
  12792. &quot;version&quot;: &quot;4&quot;,
  12793. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12794. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  12795. &quot;federatable&quot;: true,
  12796. &quot;public&quot;: false,
  12797. &quot;join_rules&quot;: &quot;invite&quot;,
  12798. &quot;guest_access&quot;: null,
  12799. &quot;history_visibility&quot;: &quot;shared&quot;,
  12800. &quot;state_events&quot;: 8345,
  12801. &quot;room_type&quot;: &quot;m.space&quot;
  12802. }
  12803. ],
  12804. &quot;offset&quot;: 0,
  12805. &quot;total_rooms&quot;: 150,
  12806. &quot;next_token&quot;: 100
  12807. }
  12808. </code></pre>
  12809. <p>The presence of the <code>next_token</code> parameter tells us that there are more rooms
  12810. than returned in this request, and we need to make another request to get them.
  12811. To get the next batch of room results, we repeat our request, setting the <code>from</code>
  12812. parameter to the value of <code>next_token</code>.</p>
  12813. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size&amp;from=100
  12814. </code></pre>
  12815. <p>A response body like the following is returned:</p>
  12816. <pre><code class="language-json">{
  12817. &quot;rooms&quot;: [
  12818. {
  12819. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  12820. &quot;name&quot;: &quot;Music Theory&quot;,
  12821. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  12822. &quot;joined_members&quot;: 127,
  12823. &quot;joined_local_members&quot;: 2,
  12824. &quot;version&quot;: &quot;1&quot;,
  12825. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12826. &quot;encryption&quot;: null,
  12827. &quot;federatable&quot;: true,
  12828. &quot;public&quot;: true,
  12829. &quot;join_rules&quot;: &quot;invite&quot;,
  12830. &quot;guest_access&quot;: null,
  12831. &quot;history_visibility&quot;: &quot;shared&quot;,
  12832. &quot;state_events&quot;: 93534,
  12833. &quot;room_type&quot;: &quot;m.space&quot;
  12834. },
  12835. ... (48 hidden items) ...
  12836. {
  12837. &quot;room_id&quot;: &quot;!twcBhHVdZlQWuuxBhN:termina.org.uk&quot;,
  12838. &quot;name&quot;: &quot;weechat-matrix&quot;,
  12839. &quot;canonical_alias&quot;: &quot;#weechat-matrix:termina.org.uk&quot;,
  12840. &quot;joined_members&quot;: 137,
  12841. &quot;joined_local_members&quot;: 20,
  12842. &quot;version&quot;: &quot;4&quot;,
  12843. &quot;creator&quot;: &quot;@foo:termina.org.uk&quot;,
  12844. &quot;encryption&quot;: null,
  12845. &quot;federatable&quot;: true,
  12846. &quot;public&quot;: true,
  12847. &quot;join_rules&quot;: &quot;invite&quot;,
  12848. &quot;guest_access&quot;: null,
  12849. &quot;history_visibility&quot;: &quot;shared&quot;,
  12850. &quot;state_events&quot;: 8345,
  12851. &quot;room_type&quot;: null
  12852. }
  12853. ],
  12854. &quot;offset&quot;: 100,
  12855. &quot;prev_batch&quot;: 0,
  12856. &quot;total_rooms&quot;: 150
  12857. }
  12858. </code></pre>
  12859. <p>Once the <code>next_token</code> parameter is no longer present, we know we've reached the
  12860. end of the list.</p>
  12861. <h1 id="room-details-api"><a class="header" href="#room-details-api">Room Details API</a></h1>
  12862. <p>The Room Details admin API allows server admins to get all details of a room.</p>
  12863. <p>The following fields are possible in the JSON response body:</p>
  12864. <ul>
  12865. <li><code>room_id</code> - The ID of the room.</li>
  12866. <li><code>name</code> - The name of the room.</li>
  12867. <li><code>topic</code> - The topic of the room.</li>
  12868. <li><code>avatar</code> - The <code>mxc</code> URI to the avatar of the room.</li>
  12869. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  12870. <li><code>joined_members</code> - How many users are currently in the room.</li>
  12871. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  12872. <li><code>joined_local_devices</code> - How many local devices are currently in the room.</li>
  12873. <li><code>version</code> - The version of the room as a string.</li>
  12874. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  12875. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  12876. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  12877. <li><code>public</code> - Whether the room is visible in room directory.</li>
  12878. <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>
  12879. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  12880. <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>
  12881. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  12882. <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.
  12883. If the room does not define a type, the value will be <code>null</code>.</li>
  12884. <li><code>forgotten</code> - Whether all local users have
  12885. <a href="https://spec.matrix.org/latest/client-server-api/#leaving-rooms">forgotten</a> the room.</li>
  12886. </ul>
  12887. <p>The API is:</p>
  12888. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;
  12889. </code></pre>
  12890. <p>A response body like the following is returned:</p>
  12891. <pre><code class="language-json">{
  12892. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  12893. &quot;name&quot;: &quot;Music Theory&quot;,
  12894. &quot;avatar&quot;: &quot;mxc://matrix.org/AQDaVFlbkQoErdOgqWRgiGSV&quot;,
  12895. &quot;topic&quot;: &quot;Theory, Composition, Notation, Analysis&quot;,
  12896. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  12897. &quot;joined_members&quot;: 127,
  12898. &quot;joined_local_members&quot;: 2,
  12899. &quot;joined_local_devices&quot;: 2,
  12900. &quot;version&quot;: &quot;1&quot;,
  12901. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  12902. &quot;encryption&quot;: null,
  12903. &quot;federatable&quot;: true,
  12904. &quot;public&quot;: true,
  12905. &quot;join_rules&quot;: &quot;invite&quot;,
  12906. &quot;guest_access&quot;: null,
  12907. &quot;history_visibility&quot;: &quot;shared&quot;,
  12908. &quot;state_events&quot;: 93534,
  12909. &quot;room_type&quot;: &quot;m.space&quot;,
  12910. &quot;forgotten&quot;: false
  12911. }
  12912. </code></pre>
  12913. <p><em>Changed in Synapse 1.66:</em> Added the <code>forgotten</code> key to the response body.</p>
  12914. <h1 id="room-members-api"><a class="header" href="#room-members-api">Room Members API</a></h1>
  12915. <p>The Room Members admin API allows server admins to get a list of all members of a room.</p>
  12916. <p>The response includes the following fields:</p>
  12917. <ul>
  12918. <li><code>members</code> - A list of all the members that are present in the room, represented by their ids.</li>
  12919. <li><code>total</code> - Total number of members in the room.</li>
  12920. </ul>
  12921. <p>The API is:</p>
  12922. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/members
  12923. </code></pre>
  12924. <p>A response body like the following is returned:</p>
  12925. <pre><code class="language-json">{
  12926. &quot;members&quot;: [
  12927. &quot;@foo:matrix.org&quot;,
  12928. &quot;@bar:matrix.org&quot;,
  12929. &quot;@foobar:matrix.org&quot;
  12930. ],
  12931. &quot;total&quot;: 3
  12932. }
  12933. </code></pre>
  12934. <h1 id="room-state-api"><a class="header" href="#room-state-api">Room State API</a></h1>
  12935. <p>The Room State admin API allows server admins to get a list of all state events in a room.</p>
  12936. <p>The response includes the following fields:</p>
  12937. <ul>
  12938. <li><code>state</code> - The current state of the room at the time of request.</li>
  12939. </ul>
  12940. <p>The API is:</p>
  12941. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/state
  12942. </code></pre>
  12943. <p>A response body like the following is returned:</p>
  12944. <pre><code class="language-json">{
  12945. &quot;state&quot;: [
  12946. {&quot;type&quot;: &quot;m.room.create&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  12947. {&quot;type&quot;: &quot;m.room.power_levels&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  12948. {&quot;type&quot;: &quot;m.room.name&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true}
  12949. ]
  12950. }
  12951. </code></pre>
  12952. <h1 id="room-messages-api"><a class="header" href="#room-messages-api">Room Messages API</a></h1>
  12953. <p>The Room Messages admin API allows server admins to get all messages
  12954. sent to a room in a given timeframe. There are various parameters available
  12955. that allow for filtering and ordering the returned list. This API supports pagination.</p>
  12956. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12957. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  12958. <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>
  12959. <p>The API is:</p>
  12960. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/messages
  12961. </code></pre>
  12962. <p><strong>Parameters</strong></p>
  12963. <p>The following path parameters are required:</p>
  12964. <ul>
  12965. <li><code>room_id</code> - The ID of the room you wish you fetch messages from.</li>
  12966. </ul>
  12967. <p>The following query parameters are available:</p>
  12968. <ul>
  12969. <li><code>from</code> (required) - The token to start returning events from. This token can be obtained from a prev_batch
  12970. or next_batch token returned by the /sync endpoint, or from an end token returned by a previous request to this endpoint.</li>
  12971. <li><code>to</code> - The token to stop returning events at.</li>
  12972. <li><code>limit</code> - The maximum number of events to return. Defaults to <code>10</code>.</li>
  12973. <li><code>filter</code> - A JSON RoomEventFilter to filter returned events with.</li>
  12974. <li><code>dir</code> - The direction to return events from. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  12975. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  12976. </ul>
  12977. <p><strong>Response</strong></p>
  12978. <p>The following fields are possible in the JSON response body:</p>
  12979. <ul>
  12980. <li><code>chunk</code> - A list of room events. The order depends on the dir parameter.
  12981. 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>
  12982. <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.
  12983. If no further events are available, this property is omitted from the response.</li>
  12984. <li><code>start</code> - A token corresponding to the start of chunk.</li>
  12985. <li><code>state</code> - A list of state events relevant to showing the chunk.</li>
  12986. </ul>
  12987. <p><strong>Example</strong></p>
  12988. <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>
  12989. <pre><code class="language-json">{
  12990. &quot;chunk&quot;: [
  12991. {
  12992. &quot;content&quot;: {
  12993. &quot;body&quot;: &quot;This is an example text message&quot;,
  12994. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  12995. &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;,
  12996. &quot;msgtype&quot;: &quot;m.text&quot;
  12997. },
  12998. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  12999. &quot;origin_server_ts&quot;: 1432735824653,
  13000. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13001. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13002. &quot;type&quot;: &quot;m.room.message&quot;,
  13003. &quot;unsigned&quot;: {
  13004. &quot;age&quot;: 1234
  13005. }
  13006. },
  13007. {
  13008. &quot;content&quot;: {
  13009. &quot;name&quot;: &quot;The room name&quot;
  13010. },
  13011. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13012. &quot;origin_server_ts&quot;: 1432735824653,
  13013. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13014. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13015. &quot;state_key&quot;: &quot;&quot;,
  13016. &quot;type&quot;: &quot;m.room.name&quot;,
  13017. &quot;unsigned&quot;: {
  13018. &quot;age&quot;: 1234
  13019. }
  13020. },
  13021. {
  13022. &quot;content&quot;: {
  13023. &quot;body&quot;: &quot;Gangnam Style&quot;,
  13024. &quot;info&quot;: {
  13025. &quot;duration&quot;: 2140786,
  13026. &quot;h&quot;: 320,
  13027. &quot;mimetype&quot;: &quot;video/mp4&quot;,
  13028. &quot;size&quot;: 1563685,
  13029. &quot;thumbnail_info&quot;: {
  13030. &quot;h&quot;: 300,
  13031. &quot;mimetype&quot;: &quot;image/jpeg&quot;,
  13032. &quot;size&quot;: 46144,
  13033. &quot;w&quot;: 300
  13034. },
  13035. &quot;thumbnail_url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;,
  13036. &quot;w&quot;: 480
  13037. },
  13038. &quot;msgtype&quot;: &quot;m.video&quot;,
  13039. &quot;url&quot;: &quot;mxc://example.org/a526eYUSFFxlgbQYZmo442&quot;
  13040. },
  13041. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13042. &quot;origin_server_ts&quot;: 1432735824653,
  13043. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13044. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13045. &quot;type&quot;: &quot;m.room.message&quot;,
  13046. &quot;unsigned&quot;: {
  13047. &quot;age&quot;: 1234
  13048. }
  13049. }
  13050. ],
  13051. &quot;end&quot;: &quot;t47409-4357353_219380_26003_2265&quot;,
  13052. &quot;start&quot;: &quot;t47429-4392820_219380_26003_2265&quot;
  13053. }
  13054. </code></pre>
  13055. <h1 id="room-timestamp-to-event-api"><a class="header" href="#room-timestamp-to-event-api">Room Timestamp to Event API</a></h1>
  13056. <p>The Room Timestamp to Event API endpoint fetches the <code>event_id</code> of the closest event to the given
  13057. timestamp (<code>ts</code> query parameter) in the given direction (<code>dir</code> query parameter).</p>
  13058. <p>Useful for cases like jump to date so you can start paginating messages from
  13059. a given date in the archive.</p>
  13060. <p>The API is:</p>
  13061. <pre><code> GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/timestamp_to_event
  13062. </code></pre>
  13063. <p><strong>Parameters</strong></p>
  13064. <p>The following path parameters are required:</p>
  13065. <ul>
  13066. <li><code>room_id</code> - The ID of the room you wish to check.</li>
  13067. </ul>
  13068. <p>The following query parameters are available:</p>
  13069. <ul>
  13070. <li><code>ts</code> - a timestamp in milliseconds where we will find the closest event in
  13071. the given direction.</li>
  13072. <li><code>dir</code> - can be <code>f</code> or <code>b</code> to indicate forwards and backwards in time from the
  13073. given timestamp. Defaults to <code>f</code>.</li>
  13074. </ul>
  13075. <p><strong>Response</strong></p>
  13076. <ul>
  13077. <li><code>event_id</code> - converted from timestamp</li>
  13078. </ul>
  13079. <h1 id="block-room-api"><a class="header" href="#block-room-api">Block Room API</a></h1>
  13080. <p>The Block Room admin API allows server admins to block and unblock rooms,
  13081. and query to see if a given room is blocked.
  13082. This API can be used to pre-emptively block a room, even if it's unknown to this
  13083. homeserver. Users will be prevented from joining a blocked room.</p>
  13084. <h2 id="block-or-unblock-a-room"><a class="header" href="#block-or-unblock-a-room">Block or unblock a room</a></h2>
  13085. <p>The API is:</p>
  13086. <pre><code>PUT /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  13087. </code></pre>
  13088. <p>with a body of:</p>
  13089. <pre><code class="language-json">{
  13090. &quot;block&quot;: true
  13091. }
  13092. </code></pre>
  13093. <p>A response body like the following is returned:</p>
  13094. <pre><code class="language-json">{
  13095. &quot;block&quot;: true
  13096. }
  13097. </code></pre>
  13098. <p><strong>Parameters</strong></p>
  13099. <p>The following parameters should be set in the URL:</p>
  13100. <ul>
  13101. <li><code>room_id</code> - The ID of the room.</li>
  13102. </ul>
  13103. <p>The following JSON body parameters are available:</p>
  13104. <ul>
  13105. <li><code>block</code> - If <code>true</code> the room will be blocked and if <code>false</code> the room will be unblocked.</li>
  13106. </ul>
  13107. <p><strong>Response</strong></p>
  13108. <p>The following fields are possible in the JSON response body:</p>
  13109. <ul>
  13110. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  13111. </ul>
  13112. <h2 id="get-block-status"><a class="header" href="#get-block-status">Get block status</a></h2>
  13113. <p>The API is:</p>
  13114. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  13115. </code></pre>
  13116. <p>A response body like the following is returned:</p>
  13117. <pre><code class="language-json">{
  13118. &quot;block&quot;: true,
  13119. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  13120. }
  13121. </code></pre>
  13122. <p><strong>Parameters</strong></p>
  13123. <p>The following parameters should be set in the URL:</p>
  13124. <ul>
  13125. <li><code>room_id</code> - The ID of the room.</li>
  13126. </ul>
  13127. <p><strong>Response</strong></p>
  13128. <p>The following fields are possible in the JSON response body:</p>
  13129. <ul>
  13130. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  13131. <li><code>user_id</code> - An optional string. If the room is blocked (<code>block</code> is <code>true</code>) shows
  13132. the user who has add the room to blocking list. Otherwise it is not displayed.</li>
  13133. </ul>
  13134. <h1 id="delete-room-api"><a class="header" href="#delete-room-api">Delete Room API</a></h1>
  13135. <p>The Delete Room admin API allows server admins to remove rooms from the server
  13136. and block these rooms.</p>
  13137. <p>Shuts down a room. Moves all local users and room aliases automatically to a
  13138. new room if <code>new_room_user_id</code> is set. Otherwise local users only
  13139. leave the room without any information.</p>
  13140. <p>The new room will be created with the user specified by the <code>new_room_user_id</code> parameter
  13141. as room administrator and will contain a message explaining what happened. Users invited
  13142. to the new room will have power level <code>-10</code> by default, and thus be unable to speak.</p>
  13143. <p>If <code>block</code> is <code>true</code>, users will be prevented from joining the old room.
  13144. This option can in <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> also be used to pre-emptively
  13145. block a room, even if it's unknown to this homeserver. In this case, the room will be
  13146. blocked, and no further action will be taken. If <code>block</code> is <code>false</code>, attempting to
  13147. delete an unknown room is invalid and will be rejected as a bad request.</p>
  13148. <p>This API will remove all trace of the old room from your database after removing
  13149. all local users. If <code>purge</code> is <code>true</code> (the default), all traces of the old room will
  13150. be removed from your database after removing all local users. If you do not want
  13151. this to happen, set <code>purge</code> to <code>false</code>.
  13152. Depending on the amount of history being purged, a call to the API may take
  13153. several minutes or longer.</p>
  13154. <p>The local server will only have the power to move local user and room aliases to
  13155. the new room. Users on other servers will be unaffected.</p>
  13156. <h2 id="version-1-old-version"><a class="header" href="#version-1-old-version">Version 1 (old version)</a></h2>
  13157. <p>This version works synchronously. That means you only get the response once the server has
  13158. finished the action, which may take a long time. If you request the same action
  13159. a second time, and the server has not finished the first one, the second request will block.
  13160. This is fixed in version 2 of this API. The parameters are the same in both APIs.
  13161. This API will become deprecated in the future.</p>
  13162. <p>The API is:</p>
  13163. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id&gt;
  13164. </code></pre>
  13165. <p>with a body of:</p>
  13166. <pre><code class="language-json">{
  13167. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  13168. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  13169. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  13170. &quot;block&quot;: true,
  13171. &quot;purge&quot;: true
  13172. }
  13173. </code></pre>
  13174. <p>A response body like the following is returned:</p>
  13175. <pre><code class="language-json">{
  13176. &quot;kicked_users&quot;: [
  13177. &quot;@foobar:example.com&quot;
  13178. ],
  13179. &quot;failed_to_kick_users&quot;: [],
  13180. &quot;local_aliases&quot;: [
  13181. &quot;#badroom:example.com&quot;,
  13182. &quot;#evilsaloon:example.com&quot;
  13183. ],
  13184. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  13185. }
  13186. </code></pre>
  13187. <p>The parameters and response values have the same format as
  13188. <a href="admin_api/rooms.html#version-2-new-version">version 2</a> of the API.</p>
  13189. <h2 id="version-2-new-version"><a class="header" href="#version-2-new-version">Version 2 (new version)</a></h2>
  13190. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  13191. <p>This version works asynchronously, meaning you get the response from server immediately
  13192. while the server works on that task in background. You can then request the status of the action
  13193. to check if it has completed.</p>
  13194. <p>The API is:</p>
  13195. <pre><code>DELETE /_synapse/admin/v2/rooms/&lt;room_id&gt;
  13196. </code></pre>
  13197. <p>with a body of:</p>
  13198. <pre><code class="language-json">{
  13199. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  13200. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  13201. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  13202. &quot;block&quot;: true,
  13203. &quot;purge&quot;: true
  13204. }
  13205. </code></pre>
  13206. <p>The API starts the shut down and purge running, and returns immediately with a JSON body with
  13207. a purge id:</p>
  13208. <pre><code class="language-json">{
  13209. &quot;delete_id&quot;: &quot;&lt;opaque id&gt;&quot;
  13210. }
  13211. </code></pre>
  13212. <p><strong>Parameters</strong></p>
  13213. <p>The following parameters should be set in the URL:</p>
  13214. <ul>
  13215. <li><code>room_id</code> - The ID of the room.</li>
  13216. </ul>
  13217. <p>The following JSON body parameters are available:</p>
  13218. <ul>
  13219. <li><code>new_room_user_id</code> - Optional. If set, a new room will be created with this user ID
  13220. as the creator and admin, and all users in the old room will be moved into that
  13221. room. If not set, no new room will be created and the users will just be removed
  13222. from the old room. The user ID must be on the local server, but does not necessarily
  13223. have to belong to a registered user.</li>
  13224. <li><code>room_name</code> - Optional. A string representing the name of the room that new users will be
  13225. invited to. Defaults to <code>Content Violation Notification</code></li>
  13226. <li><code>message</code> - Optional. A string containing the first message that will be sent as
  13227. <code>new_room_user_id</code> in the new room. Ideally this will clearly convey why the
  13228. 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>
  13229. <li><code>block</code> - Optional. If set to <code>true</code>, this room will be added to a blocking list,
  13230. preventing future attempts to join the room. Rooms can be blocked
  13231. even if they're not yet known to the homeserver (only with
  13232. <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> of the API). Defaults to <code>false</code>.</li>
  13233. <li><code>purge</code> - Optional. If set to <code>true</code>, it will remove all traces of the room from your database.
  13234. Defaults to <code>true</code>.</li>
  13235. <li><code>force_purge</code> - Optional, and ignored unless <code>purge</code> is <code>true</code>. If set to <code>true</code>, it
  13236. will force a purge to go ahead even if there are local users still in the room. Do not
  13237. use this unless a regular <code>purge</code> operation fails, as it could leave those users'
  13238. clients in a confused state.</li>
  13239. </ul>
  13240. <p>The JSON body must not be empty. The body must be at least <code>{}</code>.</p>
  13241. <h2 id="status-of-deleting-rooms"><a class="header" href="#status-of-deleting-rooms">Status of deleting rooms</a></h2>
  13242. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  13243. <p>It is possible to query the status of the background task for deleting rooms.
  13244. The status can be queried up to 24 hours after completion of the task,
  13245. or until Synapse is restarted (whichever happens first).</p>
  13246. <h3 id="query-by-room_id"><a class="header" href="#query-by-room_id">Query by <code>room_id</code></a></h3>
  13247. <p>With this API you can get the status of all active deletion tasks, and all those completed in the last 24h,
  13248. for the given <code>room_id</code>.</p>
  13249. <p>The API is:</p>
  13250. <pre><code>GET /_synapse/admin/v2/rooms/&lt;room_id&gt;/delete_status
  13251. </code></pre>
  13252. <p>A response body like the following is returned:</p>
  13253. <pre><code class="language-json">{
  13254. &quot;results&quot;: [
  13255. {
  13256. &quot;delete_id&quot;: &quot;delete_id1&quot;,
  13257. &quot;status&quot;: &quot;failed&quot;,
  13258. &quot;error&quot;: &quot;error message&quot;,
  13259. &quot;shutdown_room&quot;: {
  13260. &quot;kicked_users&quot;: [],
  13261. &quot;failed_to_kick_users&quot;: [],
  13262. &quot;local_aliases&quot;: [],
  13263. &quot;new_room_id&quot;: null
  13264. }
  13265. }, {
  13266. &quot;delete_id&quot;: &quot;delete_id2&quot;,
  13267. &quot;status&quot;: &quot;purging&quot;,
  13268. &quot;shutdown_room&quot;: {
  13269. &quot;kicked_users&quot;: [
  13270. &quot;@foobar:example.com&quot;
  13271. ],
  13272. &quot;failed_to_kick_users&quot;: [],
  13273. &quot;local_aliases&quot;: [
  13274. &quot;#badroom:example.com&quot;,
  13275. &quot;#evilsaloon:example.com&quot;
  13276. ],
  13277. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  13278. }
  13279. }
  13280. ]
  13281. }
  13282. </code></pre>
  13283. <p><strong>Parameters</strong></p>
  13284. <p>The following parameters should be set in the URL:</p>
  13285. <ul>
  13286. <li><code>room_id</code> - The ID of the room.</li>
  13287. </ul>
  13288. <h3 id="query-by-delete_id"><a class="header" href="#query-by-delete_id">Query by <code>delete_id</code></a></h3>
  13289. <p>With this API you can get the status of one specific task by <code>delete_id</code>.</p>
  13290. <p>The API is:</p>
  13291. <pre><code>GET /_synapse/admin/v2/rooms/delete_status/&lt;delete_id&gt;
  13292. </code></pre>
  13293. <p>A response body like the following is returned:</p>
  13294. <pre><code class="language-json">{
  13295. &quot;status&quot;: &quot;purging&quot;,
  13296. &quot;shutdown_room&quot;: {
  13297. &quot;kicked_users&quot;: [
  13298. &quot;@foobar:example.com&quot;
  13299. ],
  13300. &quot;failed_to_kick_users&quot;: [],
  13301. &quot;local_aliases&quot;: [
  13302. &quot;#badroom:example.com&quot;,
  13303. &quot;#evilsaloon:example.com&quot;
  13304. ],
  13305. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  13306. }
  13307. }
  13308. </code></pre>
  13309. <p><strong>Parameters</strong></p>
  13310. <p>The following parameters should be set in the URL:</p>
  13311. <ul>
  13312. <li><code>delete_id</code> - The ID for this delete.</li>
  13313. </ul>
  13314. <h3 id="response"><a class="header" href="#response">Response</a></h3>
  13315. <p>The following fields are returned in the JSON response body:</p>
  13316. <ul>
  13317. <li><code>results</code> - An array of objects, each containing information about one task.
  13318. This field is omitted from the result when you query by <code>delete_id</code>.
  13319. Task objects contain the following fields:
  13320. <ul>
  13321. <li><code>delete_id</code> - The ID for this purge if you query by <code>room_id</code>.</li>
  13322. <li><code>status</code> - The status will be one of:
  13323. <ul>
  13324. <li><code>shutting_down</code> - The process is removing users from the room.</li>
  13325. <li><code>purging</code> - The process is purging the room and event data from database.</li>
  13326. <li><code>complete</code> - The process has completed successfully.</li>
  13327. <li><code>failed</code> - The process is aborted, an error has occurred.</li>
  13328. </ul>
  13329. </li>
  13330. <li><code>error</code> - A string that shows an error message if <code>status</code> is <code>failed</code>.
  13331. Otherwise this field is hidden.</li>
  13332. <li><code>shutdown_room</code> - An object containing information about the result of shutting down the room.
  13333. <em>Note:</em> The result is shown after removing the room members.
  13334. The delete process can still be running. Please pay attention to the <code>status</code>.
  13335. <ul>
  13336. <li><code>kicked_users</code> - An array of users (<code>user_id</code>) that were kicked.</li>
  13337. <li><code>failed_to_kick_users</code> - An array of users (<code>user_id</code>) that that were not kicked.</li>
  13338. <li><code>local_aliases</code> - An array of strings representing the local aliases that were
  13339. migrated from the old room to the new.</li>
  13340. <li><code>new_room_id</code> - A string representing the room ID of the new room, or <code>null</code> if
  13341. no such room was created.</li>
  13342. </ul>
  13343. </li>
  13344. </ul>
  13345. </li>
  13346. </ul>
  13347. <h2 id="undoing-room-deletions"><a class="header" href="#undoing-room-deletions">Undoing room deletions</a></h2>
  13348. <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,
  13349. the structure can and does change without notice.</p>
  13350. <p>First, it's important to understand that a room deletion is very destructive. Undoing a deletion is not as simple as pretending it
  13351. 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
  13352. to recover at all:</p>
  13353. <ul>
  13354. <li>If the room was invite-only, your users will need to be re-invited.</li>
  13355. <li>If the room no longer has any members at all, it'll be impossible to rejoin.</li>
  13356. <li>The first user to rejoin will have to do so via an alias on a different
  13357. server (or receive an invite from a user on a different server).</li>
  13358. </ul>
  13359. <p>With all that being said, if you still want to try and recover the room:</p>
  13360. <ol>
  13361. <li>
  13362. <p>If the room was <code>block</code>ed, you must unblock it on your server. This can be
  13363. accomplished as follows:</p>
  13364. <ol>
  13365. <li>For safety reasons, shut down Synapse.</li>
  13366. <li>In the database, run <code>DELETE FROM blocked_rooms WHERE room_id = '!example:example.org';</code>
  13367. <ul>
  13368. <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>
  13369. <li>The room ID is the same one supplied to the delete room API, not the Content Violation room.</li>
  13370. </ul>
  13371. </li>
  13372. <li>Restart Synapse.</li>
  13373. </ol>
  13374. <p>This step is unnecessary if <code>block</code> was not set.</p>
  13375. </li>
  13376. <li>
  13377. <p>Any room aliases on your server that pointed to the deleted room may have
  13378. been deleted, or redirected to the Content Violation room. These will need
  13379. to be restored manually.</p>
  13380. </li>
  13381. <li>
  13382. <p>Users on your server that were in the deleted room will have been kicked
  13383. from the room. Consider whether you want to update their membership
  13384. (possibly via the <a href="admin_api/room_membership.html">Edit Room Membership API</a>) or let
  13385. them handle rejoining themselves.</p>
  13386. </li>
  13387. <li>
  13388. <p>If <code>new_room_user_id</code> was given, a 'Content Violation' will have been
  13389. created. Consider whether you want to delete that roomm.</p>
  13390. </li>
  13391. </ol>
  13392. <h1 id="make-room-admin-api"><a class="header" href="#make-room-admin-api">Make Room Admin API</a></h1>
  13393. <p>Grants another user the highest power available to a local user who is in the room.
  13394. If the user is not in the room, and it is not publicly joinable, then invite the user.</p>
  13395. <p>By default the server admin (the caller) is granted power, but another user can
  13396. optionally be specified, e.g.:</p>
  13397. <pre><code>POST /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/make_room_admin
  13398. {
  13399. &quot;user_id&quot;: &quot;@foo:example.com&quot;
  13400. }
  13401. </code></pre>
  13402. <h1 id="forward-extremities-admin-api"><a class="header" href="#forward-extremities-admin-api">Forward Extremities Admin API</a></h1>
  13403. <p>Enables querying and deleting forward extremities from rooms. When a lot of forward
  13404. extremities accumulate in a room, performance can become degraded. For details, see
  13405. <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.</p>
  13406. <h2 id="check-for-forward-extremities"><a class="header" href="#check-for-forward-extremities">Check for forward extremities</a></h2>
  13407. <p>To check the status of forward extremities for a room:</p>
  13408. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  13409. </code></pre>
  13410. <p>A response as follows will be returned:</p>
  13411. <pre><code class="language-json">{
  13412. &quot;count&quot;: 1,
  13413. &quot;results&quot;: [
  13414. {
  13415. &quot;event_id&quot;: &quot;$M5SP266vsnxctfwFgFLNceaCo3ujhRtg_NiiHabcdefgh&quot;,
  13416. &quot;state_group&quot;: 439,
  13417. &quot;depth&quot;: 123,
  13418. &quot;received_ts&quot;: 1611263016761
  13419. }
  13420. ]
  13421. }
  13422. </code></pre>
  13423. <h2 id="deleting-forward-extremities"><a class="header" href="#deleting-forward-extremities">Deleting forward extremities</a></h2>
  13424. <p><strong>WARNING</strong>: Please ensure you know what you're doing and have read
  13425. the related issue <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.
  13426. Under no situations should this API be executed as an automated maintenance task!</p>
  13427. <p>If a room has lots of forward extremities, the extra can be
  13428. deleted as follows:</p>
  13429. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  13430. </code></pre>
  13431. <p>A response as follows will be returned, indicating the amount of forward extremities
  13432. that were deleted.</p>
  13433. <pre><code class="language-json">{
  13434. &quot;deleted&quot;: 1
  13435. }
  13436. </code></pre>
  13437. <h1 id="event-context-api"><a class="header" href="#event-context-api">Event Context API</a></h1>
  13438. <p>This API lets a client find the context of an event. This is designed primarily to investigate abuse reports.</p>
  13439. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/context/&lt;event_id&gt;
  13440. </code></pre>
  13441. <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>
  13442. <p>Example response:</p>
  13443. <pre><code class="language-json">{
  13444. &quot;end&quot;: &quot;t29-57_2_0_2&quot;,
  13445. &quot;events_after&quot;: [
  13446. {
  13447. &quot;content&quot;: {
  13448. &quot;body&quot;: &quot;This is an example text message&quot;,
  13449. &quot;msgtype&quot;: &quot;m.text&quot;,
  13450. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  13451. &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;
  13452. },
  13453. &quot;type&quot;: &quot;m.room.message&quot;,
  13454. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13455. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13456. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13457. &quot;origin_server_ts&quot;: 1432735824653,
  13458. &quot;unsigned&quot;: {
  13459. &quot;age&quot;: 1234
  13460. }
  13461. }
  13462. ],
  13463. &quot;event&quot;: {
  13464. &quot;content&quot;: {
  13465. &quot;body&quot;: &quot;filename.jpg&quot;,
  13466. &quot;info&quot;: {
  13467. &quot;h&quot;: 398,
  13468. &quot;w&quot;: 394,
  13469. &quot;mimetype&quot;: &quot;image/jpeg&quot;,
  13470. &quot;size&quot;: 31037
  13471. },
  13472. &quot;url&quot;: &quot;mxc://example.org/JWEIFJgwEIhweiWJE&quot;,
  13473. &quot;msgtype&quot;: &quot;m.image&quot;
  13474. },
  13475. &quot;type&quot;: &quot;m.room.message&quot;,
  13476. &quot;event_id&quot;: &quot;$f3h4d129462ha:example.com&quot;,
  13477. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13478. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13479. &quot;origin_server_ts&quot;: 1432735824653,
  13480. &quot;unsigned&quot;: {
  13481. &quot;age&quot;: 1234
  13482. }
  13483. },
  13484. &quot;events_before&quot;: [
  13485. {
  13486. &quot;content&quot;: {
  13487. &quot;body&quot;: &quot;something-important.doc&quot;,
  13488. &quot;filename&quot;: &quot;something-important.doc&quot;,
  13489. &quot;info&quot;: {
  13490. &quot;mimetype&quot;: &quot;application/msword&quot;,
  13491. &quot;size&quot;: 46144
  13492. },
  13493. &quot;msgtype&quot;: &quot;m.file&quot;,
  13494. &quot;url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;
  13495. },
  13496. &quot;type&quot;: &quot;m.room.message&quot;,
  13497. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13498. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13499. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13500. &quot;origin_server_ts&quot;: 1432735824653,
  13501. &quot;unsigned&quot;: {
  13502. &quot;age&quot;: 1234
  13503. }
  13504. }
  13505. ],
  13506. &quot;start&quot;: &quot;t27-54_2_0_2&quot;,
  13507. &quot;state&quot;: [
  13508. {
  13509. &quot;content&quot;: {
  13510. &quot;creator&quot;: &quot;@example:example.org&quot;,
  13511. &quot;room_version&quot;: &quot;1&quot;,
  13512. &quot;m.federate&quot;: true,
  13513. &quot;predecessor&quot;: {
  13514. &quot;event_id&quot;: &quot;$something:example.org&quot;,
  13515. &quot;room_id&quot;: &quot;!oldroom:example.org&quot;
  13516. }
  13517. },
  13518. &quot;type&quot;: &quot;m.room.create&quot;,
  13519. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13520. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13521. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13522. &quot;origin_server_ts&quot;: 1432735824653,
  13523. &quot;unsigned&quot;: {
  13524. &quot;age&quot;: 1234
  13525. },
  13526. &quot;state_key&quot;: &quot;&quot;
  13527. },
  13528. {
  13529. &quot;content&quot;: {
  13530. &quot;membership&quot;: &quot;join&quot;,
  13531. &quot;avatar_url&quot;: &quot;mxc://example.org/SEsfnsuifSDFSSEF&quot;,
  13532. &quot;displayname&quot;: &quot;Alice Margatroid&quot;
  13533. },
  13534. &quot;type&quot;: &quot;m.room.member&quot;,
  13535. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  13536. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  13537. &quot;sender&quot;: &quot;@example:example.org&quot;,
  13538. &quot;origin_server_ts&quot;: 1432735824653,
  13539. &quot;unsigned&quot;: {
  13540. &quot;age&quot;: 1234
  13541. },
  13542. &quot;state_key&quot;: &quot;@alice:example.org&quot;
  13543. }
  13544. ]
  13545. }
  13546. </code></pre>
  13547. <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>
  13548. <p>The API to send notices is as follows:</p>
  13549. <pre><code>POST /_synapse/admin/v1/send_server_notice
  13550. </code></pre>
  13551. <p>or:</p>
  13552. <pre><code>PUT /_synapse/admin/v1/send_server_notice/{txnId}
  13553. </code></pre>
  13554. <p>You will need to authenticate with an access token for an admin user.</p>
  13555. <p>When using the <code>PUT</code> form, retransmissions with the same transaction ID will be
  13556. ignored in the same way as with <code>PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}</code>.</p>
  13557. <p>The request body should look something like the following:</p>
  13558. <pre><code class="language-json">{
  13559. &quot;user_id&quot;: &quot;@target_user:server_name&quot;,
  13560. &quot;content&quot;: {
  13561. &quot;msgtype&quot;: &quot;m.text&quot;,
  13562. &quot;body&quot;: &quot;This is my message&quot;
  13563. }
  13564. }
  13565. </code></pre>
  13566. <p>You can optionally include the following additional parameters:</p>
  13567. <ul>
  13568. <li><code>type</code>: the type of event. Defaults to <code>m.room.message</code>.</li>
  13569. <li><code>state_key</code>: Setting this will result in a state event being sent.</li>
  13570. </ul>
  13571. <p>Once the notice has been sent, the API will return the following response:</p>
  13572. <pre><code class="language-json">{
  13573. &quot;event_id&quot;: &quot;&lt;event_id&gt;&quot;
  13574. }
  13575. </code></pre>
  13576. <p>Note that server notices must be enabled in <code>homeserver.yaml</code> before this API
  13577. can be used. See <a href="admin_api/../server_notices.html">the server notices documentation</a> for more information.</p>
  13578. <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>
  13579. <p>Returns information about all local media usage of users. Gives the
  13580. possibility to filter them by time and user.</p>
  13581. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  13582. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  13583. <p>The API is:</p>
  13584. <pre><code>GET /_synapse/admin/v1/statistics/users/media
  13585. </code></pre>
  13586. <p>A response body like the following is returned:</p>
  13587. <pre><code class="language-json">{
  13588. &quot;users&quot;: [
  13589. {
  13590. &quot;displayname&quot;: &quot;foo_user_0&quot;,
  13591. &quot;media_count&quot;: 2,
  13592. &quot;media_length&quot;: 134,
  13593. &quot;user_id&quot;: &quot;@foo_user_0:test&quot;
  13594. },
  13595. {
  13596. &quot;displayname&quot;: &quot;foo_user_1&quot;,
  13597. &quot;media_count&quot;: 2,
  13598. &quot;media_length&quot;: 134,
  13599. &quot;user_id&quot;: &quot;@foo_user_1:test&quot;
  13600. }
  13601. ],
  13602. &quot;next_token&quot;: 3,
  13603. &quot;total&quot;: 10
  13604. }
  13605. </code></pre>
  13606. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint
  13607. again with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  13608. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  13609. reports to paginate through.</p>
  13610. <p><strong>Parameters</strong></p>
  13611. <p>The following parameters should be set in the URL:</p>
  13612. <ul>
  13613. <li><code>limit</code>: string representing a positive integer - Is optional but is
  13614. used for pagination, denoting the maximum number of items to return
  13615. in this call. Defaults to <code>100</code>.</li>
  13616. <li><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  13617. denoting the offset in the returned results. This should be treated as an opaque value
  13618. and not explicitly set to anything other than the return value of <code>next_token</code> from a
  13619. previous call. Defaults to <code>0</code>.</li>
  13620. <li><code>order_by</code> - string - The method in which to sort the returned list of users. Valid values are:
  13621. <ul>
  13622. <li><code>user_id</code> - Users are ordered alphabetically by <code>user_id</code>. This is the default.</li>
  13623. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  13624. <li><code>media_length</code> - Users are ordered by the total size of uploaded media in bytes.
  13625. Smallest to largest.</li>
  13626. <li><code>media_count</code> - Users are ordered by number of uploaded media. Smallest to largest.</li>
  13627. </ul>
  13628. </li>
  13629. <li><code>from_ts</code> - string representing a positive integer - Considers only
  13630. files created at this timestamp or later. Unix timestamp in ms.</li>
  13631. <li><code>until_ts</code> - string representing a positive integer - Considers only
  13632. files created at this timestamp or earlier. Unix timestamp in ms.</li>
  13633. <li><code>search_term</code> - string - Filter users by their user ID localpart <strong>or</strong> displayname.
  13634. The search term can be found in any part of the string.
  13635. Defaults to no filtering.</li>
  13636. <li><code>dir</code> - string - Direction of order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  13637. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  13638. </ul>
  13639. <p><strong>Response</strong></p>
  13640. <p>The following fields are returned in the JSON response body:</p>
  13641. <ul>
  13642. <li><code>users</code> - An array of objects, each containing information
  13643. about the user and their local media. Objects contain the following fields:
  13644. <ul>
  13645. <li><code>displayname</code> - string - Displayname of this user.</li>
  13646. <li><code>media_count</code> - integer - Number of uploaded media by this user.</li>
  13647. <li><code>media_length</code> - integer - Size of uploaded media in bytes by this user.</li>
  13648. <li><code>user_id</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  13649. </ul>
  13650. </li>
  13651. <li><code>next_token</code> - integer - Opaque value used for pagination. See above.</li>
  13652. <li><code>total</code> - integer - Total number of users after filtering.</li>
  13653. </ul>
  13654. <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>
  13655. <p>Returns the 10 largest rooms and an estimate of how much space in the database
  13656. they are taking.</p>
  13657. <p>This does not include the size of any associated media associated with the room.</p>
  13658. <p>Returns an error on SQLite.</p>
  13659. <p><em>Note:</em> This uses the planner statistics from PostgreSQL to do the estimates,
  13660. which means that the returned information can vary widely from reality. However,
  13661. it should be enough to get a rough idea of where database disk space is going.</p>
  13662. <p>The API is:</p>
  13663. <pre><code>GET /_synapse/admin/v1/statistics/database/rooms
  13664. </code></pre>
  13665. <p>A response body like the following is returned:</p>
  13666. <pre><code class="language-json">{
  13667. &quot;rooms&quot;: [
  13668. {
  13669. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  13670. &quot;estimated_size&quot;: 47325417353
  13671. }
  13672. ],
  13673. }
  13674. </code></pre>
  13675. <p><strong>Response</strong></p>
  13676. <p>The following fields are returned in the JSON response body:</p>
  13677. <ul>
  13678. <li><code>rooms</code> - An array of objects, sorted by largest room first. Objects contain
  13679. the following fields:
  13680. <ul>
  13681. <li><code>room_id</code> - string - The room ID.</li>
  13682. <li><code>estimated_size</code> - integer - Estimated disk space used in bytes by the room
  13683. in the database.</li>
  13684. </ul>
  13685. </li>
  13686. </ul>
  13687. <p><em>Added in Synapse 1.83.0</em></p>
  13688. <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>
  13689. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  13690. for a server admin: see <a href="admin_api/../usage/administration/admin_api/">Admin API</a>.</p>
  13691. <h2 id="query-user-account"><a class="header" href="#query-user-account">Query User Account</a></h2>
  13692. <p>This API returns information about a specific user account.</p>
  13693. <p>The api is:</p>
  13694. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;
  13695. </code></pre>
  13696. <p>It returns a JSON body like the following:</p>
  13697. <pre><code class="language-jsonc">{
  13698. &quot;name&quot;: &quot;@user:example.com&quot;,
  13699. &quot;displayname&quot;: &quot;User&quot;, // can be null if not set
  13700. &quot;threepids&quot;: [
  13701. {
  13702. &quot;medium&quot;: &quot;email&quot;,
  13703. &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;,
  13704. &quot;added_at&quot;: 1586458409743,
  13705. &quot;validated_at&quot;: 1586458409743
  13706. },
  13707. {
  13708. &quot;medium&quot;: &quot;email&quot;,
  13709. &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;,
  13710. &quot;added_at&quot;: 1586458409743,
  13711. &quot;validated_at&quot;: 1586458409743
  13712. }
  13713. ],
  13714. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;, // can be null if not set
  13715. &quot;is_guest&quot;: 0,
  13716. &quot;admin&quot;: 0,
  13717. &quot;deactivated&quot;: 0,
  13718. &quot;erased&quot;: false,
  13719. &quot;shadow_banned&quot;: 0,
  13720. &quot;creation_ts&quot;: 1560432506,
  13721. &quot;appservice_id&quot;: null,
  13722. &quot;consent_server_notice_sent&quot;: null,
  13723. &quot;consent_version&quot;: null,
  13724. &quot;consent_ts&quot;: null,
  13725. &quot;external_ids&quot;: [
  13726. {
  13727. &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
  13728. &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
  13729. },
  13730. {
  13731. &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
  13732. &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
  13733. }
  13734. ],
  13735. &quot;user_type&quot;: null,
  13736. &quot;locked&quot;: false
  13737. }
  13738. </code></pre>
  13739. <p>URL parameters:</p>
  13740. <ul>
  13741. <li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
  13742. </ul>
  13743. <h2 id="create-or-modify-account"><a class="header" href="#create-or-modify-account">Create or modify account</a></h2>
  13744. <p>This API allows an administrator to create or modify a user account with a
  13745. specific <code>user_id</code>.</p>
  13746. <p>This api is:</p>
  13747. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;
  13748. </code></pre>
  13749. <p>with a body of:</p>
  13750. <pre><code class="language-json">{
  13751. &quot;password&quot;: &quot;user_password&quot;,
  13752. &quot;logout_devices&quot;: false,
  13753. &quot;displayname&quot;: &quot;Alice Marigold&quot;,
  13754. &quot;avatar_url&quot;: &quot;mxc://example.com/abcde12345&quot;,
  13755. &quot;threepids&quot;: [
  13756. {
  13757. &quot;medium&quot;: &quot;email&quot;,
  13758. &quot;address&quot;: &quot;alice@example.com&quot;
  13759. },
  13760. {
  13761. &quot;medium&quot;: &quot;email&quot;,
  13762. &quot;address&quot;: &quot;alice@domain.org&quot;
  13763. }
  13764. ],
  13765. &quot;external_ids&quot;: [
  13766. {
  13767. &quot;auth_provider&quot;: &quot;example&quot;,
  13768. &quot;external_id&quot;: &quot;12345&quot;
  13769. },
  13770. {
  13771. &quot;auth_provider&quot;: &quot;example2&quot;,
  13772. &quot;external_id&quot;: &quot;abc54321&quot;
  13773. }
  13774. ],
  13775. &quot;admin&quot;: false,
  13776. &quot;deactivated&quot;: false,
  13777. &quot;user_type&quot;: null,
  13778. &quot;locked&quot;: false
  13779. }
  13780. </code></pre>
  13781. <p>Returns HTTP status code:</p>
  13782. <ul>
  13783. <li><code>201</code> - When a new user object was created.</li>
  13784. <li><code>200</code> - When a user was modified.</li>
  13785. </ul>
  13786. <p>URL parameters:</p>
  13787. <ul>
  13788. <li><code>user_id</code> - A fully-qualified user id. For example, <code>@user:server.com</code>.</li>
  13789. </ul>
  13790. <p>Body parameters:</p>
  13791. <ul>
  13792. <li>
  13793. <p><code>password</code> - <strong>string</strong>, optional. If provided, the user's password is updated and all
  13794. devices are logged out, unless <code>logout_devices</code> is set to <code>false</code>.</p>
  13795. </li>
  13796. <li>
  13797. <p><code>logout_devices</code> - <strong>bool</strong>, optional, defaults to <code>true</code>. If set to <code>false</code>, devices aren't
  13798. logged out even when <code>password</code> is provided.</p>
  13799. </li>
  13800. <li>
  13801. <p><code>displayname</code> - <strong>string</strong>, optional. If set to an empty string (<code>&quot;&quot;</code>), the user's display name
  13802. will be removed.</p>
  13803. </li>
  13804. <li>
  13805. <p><code>avatar_url</code> - <strong>string</strong>, optional. Must be a
  13806. <a href="https://matrix.org/docs/spec/client_server/r0.6.0#matrix-content-mxc-uris">MXC URI</a>.
  13807. If set to an empty string (<code>&quot;&quot;</code>), the user's avatar is removed.</p>
  13808. </li>
  13809. <li>
  13810. <p><code>threepids</code> - <strong>array</strong>, optional. If provided, the user's third-party IDs (email, msisdn) are
  13811. entirely replaced with the given list. Each item in the array is an object with the following
  13812. fields:</p>
  13813. <ul>
  13814. <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>
  13815. <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
  13816. <code>447470274584</code> (for a phone number with country code &quot;44&quot;) and <code>19254857364</code> (for a phone number
  13817. with country code &quot;1&quot;) for <code>msisdn</code>.
  13818. Note: If a threepid is removed from a user via this option, Synapse will also attempt to remove
  13819. that threepid from any identity servers it is aware has a binding for it.</li>
  13820. </ul>
  13821. </li>
  13822. <li>
  13823. <p><code>external_ids</code> - <strong>array</strong>, optional. Allow setting the identifier of the external identity
  13824. provider for SSO (Single sign-on). More details are in the configuration manual under the
  13825. 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>
  13826. <ul>
  13827. <li><code>auth_provider</code> - <strong>string</strong>, required. The unique, internal ID of the external identity provider.
  13828. The same as <code>idp_id</code> from the homeserver configuration. Note that no error is raised if the
  13829. provided value is not in the homeserver configuration.</li>
  13830. <li><code>external_id</code> - <strong>string</strong>, required. An identifier for the user in the external identity provider.
  13831. When the user logs in to the identity provider, this must be the unique ID that they map to.</li>
  13832. </ul>
  13833. </li>
  13834. <li>
  13835. <p><code>admin</code> - <strong>bool</strong>, optional, defaults to <code>false</code>. Whether the user is a homeserver administrator,
  13836. granting them access to the Admin API, among other things.</p>
  13837. </li>
  13838. <li>
  13839. <p><code>deactivated</code> - <strong>bool</strong>, optional. If unspecified, deactivation state will be left unchanged.</p>
  13840. <p>Note: the <code>password</code> field must also be set if both of the following are true:</p>
  13841. <ul>
  13842. <li><code>deactivated</code> is set to <code>false</code> and the user was previously deactivated (you are reactivating this user)</li>
  13843. <li>Users are allowed to set their password on this homeserver (both <code>password_config.enabled</code> and
  13844. <code>password_config.localdb_enabled</code> config options are set to <code>true</code>).
  13845. Users' passwords are wiped upon account deactivation, hence the need to set a new one here.</li>
  13846. </ul>
  13847. <p>Note: a user cannot be erased with this API. For more details on
  13848. deactivating and erasing users see <a href="admin_api/user_admin_api.html#deactivate-account">Deactivate Account</a>.</p>
  13849. </li>
  13850. <li>
  13851. <p><code>locked</code> - <strong>bool</strong>, optional. If unspecified, locked state will be left unchanged.</p>
  13852. </li>
  13853. <li>
  13854. <p><code>user_type</code> - <strong>string</strong> or null, optional. If not provided, the user type will be
  13855. not be changed. If <code>null</code> is given, the user type will be cleared.
  13856. Other allowed options are: <code>bot</code> and <code>support</code>.</p>
  13857. </li>
  13858. </ul>
  13859. <h2 id="list-accounts"><a class="header" href="#list-accounts">List Accounts</a></h2>
  13860. <p>This API returns all local user accounts.
  13861. By default, the response is ordered by ascending user ID.</p>
  13862. <pre><code>GET /_synapse/admin/v2/users?from=0&amp;limit=10&amp;guests=false
  13863. </code></pre>
  13864. <p>A response body like the following is returned:</p>
  13865. <pre><code class="language-json">{
  13866. &quot;users&quot;: [
  13867. {
  13868. &quot;name&quot;: &quot;&lt;user_id1&gt;&quot;,
  13869. &quot;is_guest&quot;: 0,
  13870. &quot;admin&quot;: 0,
  13871. &quot;user_type&quot;: null,
  13872. &quot;deactivated&quot;: 0,
  13873. &quot;erased&quot;: false,
  13874. &quot;shadow_banned&quot;: 0,
  13875. &quot;displayname&quot;: &quot;&lt;User One&gt;&quot;,
  13876. &quot;avatar_url&quot;: null,
  13877. &quot;creation_ts&quot;: 1560432668000,
  13878. &quot;locked&quot;: false
  13879. }, {
  13880. &quot;name&quot;: &quot;&lt;user_id2&gt;&quot;,
  13881. &quot;is_guest&quot;: 0,
  13882. &quot;admin&quot;: 1,
  13883. &quot;user_type&quot;: null,
  13884. &quot;deactivated&quot;: 0,
  13885. &quot;erased&quot;: false,
  13886. &quot;shadow_banned&quot;: 0,
  13887. &quot;displayname&quot;: &quot;&lt;User Two&gt;&quot;,
  13888. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
  13889. &quot;creation_ts&quot;: 1561550621000,
  13890. &quot;locked&quot;: false
  13891. }
  13892. ],
  13893. &quot;next_token&quot;: &quot;100&quot;,
  13894. &quot;total&quot;: 200
  13895. }
  13896. </code></pre>
  13897. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  13898. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  13899. <p>If the endpoint does not return a <code>next_token</code> then there are no more users
  13900. to paginate through.</p>
  13901. <p><strong>Parameters</strong></p>
  13902. <p>The following parameters should be set in the URL:</p>
  13903. <ul>
  13904. <li>
  13905. <p><code>user_id</code> - Is optional and filters to only return users with user IDs
  13906. that contain this value. This parameter is ignored when using the <code>name</code> parameter.</p>
  13907. </li>
  13908. <li>
  13909. <p><code>name</code> - Is optional and filters to only return users with user ID localparts
  13910. <strong>or</strong> displaynames that contain this value.</p>
  13911. </li>
  13912. <li>
  13913. <p><code>guests</code> - string representing a bool - Is optional and if <code>false</code> will <strong>exclude</strong> guest users.
  13914. Defaults to <code>true</code> to include guest users. This parameter is not supported when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
  13915. </li>
  13916. <li>
  13917. <p><code>admins</code> - Optional flag to filter admins. If <code>true</code>, only admins are queried. If <code>false</code>, admins are excluded from
  13918. the query. When the flag is absent (the default), <strong>both</strong> admins and non-admins are included in the search results.</p>
  13919. </li>
  13920. <li>
  13921. <p><code>deactivated</code> - string representing a bool - Is optional and if <code>true</code> will <strong>include</strong> deactivated users.
  13922. Defaults to <code>false</code> to exclude deactivated users.</p>
  13923. </li>
  13924. <li>
  13925. <p><code>limit</code> - string representing a positive integer - Is optional but is used for pagination,
  13926. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  13927. </li>
  13928. <li>
  13929. <p><code>from</code> - string representing a positive integer - Is optional but used for pagination,
  13930. denoting the offset in the returned results. This should be treated as an opaque value and
  13931. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  13932. Defaults to <code>0</code>.</p>
  13933. </li>
  13934. <li>
  13935. <p><code>order_by</code> - The method by which to sort the returned list of users.
  13936. If the ordered field has duplicates, the second order is always by ascending <code>name</code>,
  13937. which guarantees a stable ordering. Valid values are:</p>
  13938. <ul>
  13939. <li><code>name</code> - Users are ordered alphabetically by <code>name</code>. This is the default.</li>
  13940. <li><code>is_guest</code> - Users are ordered by <code>is_guest</code> status.</li>
  13941. <li><code>admin</code> - Users are ordered by <code>admin</code> status.</li>
  13942. <li><code>user_type</code> - Users are ordered alphabetically by <code>user_type</code>.</li>
  13943. <li><code>deactivated</code> - Users are ordered by <code>deactivated</code> status.</li>
  13944. <li><code>shadow_banned</code> - Users are ordered by <code>shadow_banned</code> status.</li>
  13945. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  13946. <li><code>avatar_url</code> - Users are ordered alphabetically by avatar URL.</li>
  13947. <li><code>creation_ts</code> - Users are ordered by when the users was created in ms.</li>
  13948. <li><code>last_seen_ts</code> - Users are ordered by when the user was lastly seen in ms.</li>
  13949. </ul>
  13950. </li>
  13951. <li>
  13952. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  13953. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  13954. </li>
  13955. <li>
  13956. <p><code>not_user_type</code> - Exclude certain user types, such as bot users, from the request.
  13957. Can be provided multiple times. Possible values are <code>bot</code>, <code>support</code> or &quot;empty string&quot;.
  13958. &quot;empty string&quot; here means to exclude users without a type.</p>
  13959. </li>
  13960. <li>
  13961. <p><code>locked</code> - string representing a bool - Is optional and if <code>true</code> will <strong>include</strong> locked users.
  13962. Defaults to <code>false</code> to exclude locked users. Note: Introduced in v1.93.</p>
  13963. </li>
  13964. </ul>
  13965. <p>Caution. The database only has indexes on the columns <code>name</code> and <code>creation_ts</code>.
  13966. This means that if a different sort order is used (<code>is_guest</code>, <code>admin</code>,
  13967. <code>user_type</code>, <code>deactivated</code>, <code>shadow_banned</code>, <code>avatar_url</code> or <code>displayname</code>),
  13968. this can cause a large load on the database, especially for large environments.</p>
  13969. <p><strong>Response</strong></p>
  13970. <p>The following fields are returned in the JSON response body:</p>
  13971. <ul>
  13972. <li>
  13973. <p><code>users</code> - An array of objects, each containing information about an user.
  13974. User objects contain the following fields:</p>
  13975. <ul>
  13976. <li><code>name</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  13977. <li><code>is_guest</code> - bool - Status if that user is a guest account.</li>
  13978. <li><code>admin</code> - bool - Status if that user is a server administrator.</li>
  13979. <li><code>user_type</code> - string - Type of the user. Normal users are type <code>None</code>.
  13980. This allows user type specific behaviour. There are also types <code>support</code> and <code>bot</code>. </li>
  13981. <li><code>deactivated</code> - bool - Status if that user has been marked as deactivated.</li>
  13982. <li><code>erased</code> - bool - Status if that user has been marked as erased.</li>
  13983. <li><code>shadow_banned</code> - bool - Status if that user has been marked as shadow banned.</li>
  13984. <li><code>displayname</code> - string - The user's display name if they have set one.</li>
  13985. <li><code>avatar_url</code> - string - The user's avatar URL if they have set one.</li>
  13986. <li><code>creation_ts</code> - integer - The user's creation timestamp in ms.</li>
  13987. <li><code>last_seen_ts</code> - integer - The user's last activity timestamp in ms.</li>
  13988. <li><code>locked</code> - bool - Status if that user has been marked as locked. Note: Introduced in v1.93.</li>
  13989. </ul>
  13990. </li>
  13991. <li>
  13992. <p><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</p>
  13993. </li>
  13994. <li>
  13995. <p><code>total</code> - integer - Total number of media.</p>
  13996. </li>
  13997. </ul>
  13998. <p><em>Added in Synapse 1.93:</em> the <code>locked</code> query parameter and response field.</p>
  13999. <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>
  14000. <p>This API returns information about the active sessions for a specific user.</p>
  14001. <p>The endpoints are:</p>
  14002. <pre><code>GET /_synapse/admin/v1/whois/&lt;user_id&gt;
  14003. </code></pre>
  14004. <p>and:</p>
  14005. <pre><code>GET /_matrix/client/r0/admin/whois/&lt;userId&gt;
  14006. </code></pre>
  14007. <p>See also: <a href="https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-admin-whois-userid">Client Server
  14008. API Whois</a>.</p>
  14009. <p>It returns a JSON body like the following:</p>
  14010. <pre><code class="language-json">{
  14011. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;,
  14012. &quot;devices&quot;: {
  14013. &quot;&quot;: {
  14014. &quot;sessions&quot;: [
  14015. {
  14016. &quot;connections&quot;: [
  14017. {
  14018. &quot;ip&quot;: &quot;1.2.3.4&quot;,
  14019. &quot;last_seen&quot;: 1417222374433,
  14020. &quot;user_agent&quot;: &quot;Mozilla/5.0 ...&quot;
  14021. },
  14022. {
  14023. &quot;ip&quot;: &quot;1.2.3.10&quot;,
  14024. &quot;last_seen&quot;: 1417222374500,
  14025. &quot;user_agent&quot;: &quot;Dalvik/2.1.0 ...&quot;
  14026. }
  14027. ]
  14028. }
  14029. ]
  14030. }
  14031. }
  14032. }
  14033. </code></pre>
  14034. <p><code>last_seen</code> is measured in milliseconds since the Unix epoch.</p>
  14035. <h2 id="deactivate-account"><a class="header" href="#deactivate-account">Deactivate Account</a></h2>
  14036. <p>This API deactivates an account. It removes active access tokens, resets the
  14037. password, and deletes third-party IDs (to prevent the user requesting a
  14038. password reset).</p>
  14039. <p>It can also mark the user as GDPR-erased. This means messages sent by the
  14040. user will still be visible by anyone that was in the room when these messages
  14041. were sent, but hidden from users joining the room afterwards.</p>
  14042. <p>The api is:</p>
  14043. <pre><code>POST /_synapse/admin/v1/deactivate/&lt;user_id&gt;
  14044. </code></pre>
  14045. <p>with a body of:</p>
  14046. <pre><code class="language-json">{
  14047. &quot;erase&quot;: true
  14048. }
  14049. </code></pre>
  14050. <p>The erase parameter is optional and defaults to <code>false</code>.
  14051. An empty body may be passed for backwards compatibility.</p>
  14052. <p>The following actions are performed when deactivating an user:</p>
  14053. <ul>
  14054. <li>Try to unbind 3PIDs from the identity server</li>
  14055. <li>Remove all 3PIDs from the homeserver</li>
  14056. <li>Delete all devices and E2EE keys</li>
  14057. <li>Delete all access tokens</li>
  14058. <li>Delete all pushers</li>
  14059. <li>Delete the password hash</li>
  14060. <li>Removal from all rooms the user is a member of</li>
  14061. <li>Remove the user from the user directory</li>
  14062. <li>Reject all pending invites</li>
  14063. <li>Remove all account validity information related to the user</li>
  14064. <li>Remove the arbitrary data store known as <em>account data</em>. For example, this includes:
  14065. <ul>
  14066. <li>list of ignored users;</li>
  14067. <li>push rules;</li>
  14068. <li>secret storage keys; and</li>
  14069. <li>cross-signing keys.</li>
  14070. </ul>
  14071. </li>
  14072. </ul>
  14073. <p>The following additional actions are performed during deactivation if <code>erase</code>
  14074. is set to <code>true</code>:</p>
  14075. <ul>
  14076. <li>Remove the user's display name</li>
  14077. <li>Remove the user's avatar URL</li>
  14078. <li>Mark the user as erased</li>
  14079. </ul>
  14080. <p>The following actions are <strong>NOT</strong> performed. The list may be incomplete.</p>
  14081. <ul>
  14082. <li>Remove mappings of SSO IDs</li>
  14083. <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>
  14084. <li>Delete sent and received messages</li>
  14085. <li>Remove the user's creation (registration) timestamp</li>
  14086. <li><a href="admin_api/user_admin_api.html#override-ratelimiting-for-users">Remove rate limit overrides</a></li>
  14087. <li>Remove from monthly active users</li>
  14088. <li>Remove user's consent information (consent version and timestamp)</li>
  14089. </ul>
  14090. <h2 id="reset-password"><a class="header" href="#reset-password">Reset password</a></h2>
  14091. <p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
  14092. <p>Changes the password of another user. This will automatically log the user out of all their devices.</p>
  14093. <p>The api is:</p>
  14094. <pre><code>POST /_synapse/admin/v1/reset_password/&lt;user_id&gt;
  14095. </code></pre>
  14096. <p>with a body of:</p>
  14097. <pre><code class="language-json">{
  14098. &quot;new_password&quot;: &quot;&lt;secret&gt;&quot;,
  14099. &quot;logout_devices&quot;: true
  14100. }
  14101. </code></pre>
  14102. <p>The parameter <code>new_password</code> is required.
  14103. The parameter <code>logout_devices</code> is optional and defaults to <code>true</code>.</p>
  14104. <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>
  14105. <p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
  14106. <p>The api is:</p>
  14107. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  14108. </code></pre>
  14109. <p>A response body like the following is returned:</p>
  14110. <pre><code class="language-json">{
  14111. &quot;admin&quot;: true
  14112. }
  14113. </code></pre>
  14114. <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>
  14115. <p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
  14116. <p>Note that you cannot demote yourself.</p>
  14117. <p>The api is:</p>
  14118. <pre><code>PUT /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  14119. </code></pre>
  14120. <p>with a body of:</p>
  14121. <pre><code class="language-json">{
  14122. &quot;admin&quot;: true
  14123. }
  14124. </code></pre>
  14125. <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>
  14126. <p>Gets a list of all <code>room_id</code> that a specific <code>user_id</code> is member.</p>
  14127. <p>The API is:</p>
  14128. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/joined_rooms
  14129. </code></pre>
  14130. <p>A response body like the following is returned:</p>
  14131. <pre><code class="language-json"> {
  14132. &quot;joined_rooms&quot;: [
  14133. &quot;!DuGcnbhHGaSZQoNQR:matrix.org&quot;,
  14134. &quot;!ZtSaPCawyWtxfWiIy:matrix.org&quot;
  14135. ],
  14136. &quot;total&quot;: 2
  14137. }
  14138. </code></pre>
  14139. <p>The server returns the list of rooms of which the user and the server
  14140. are member. If the user is local, all the rooms of which the user is
  14141. member are returned.</p>
  14142. <p><strong>Parameters</strong></p>
  14143. <p>The following parameters should be set in the URL:</p>
  14144. <ul>
  14145. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14146. </ul>
  14147. <p><strong>Response</strong></p>
  14148. <p>The following fields are returned in the JSON response body:</p>
  14149. <ul>
  14150. <li><code>joined_rooms</code> - An array of <code>room_id</code>.</li>
  14151. <li><code>total</code> - Number of rooms.</li>
  14152. </ul>
  14153. <h2 id="account-data"><a class="header" href="#account-data">Account Data</a></h2>
  14154. <p>Gets information about account data for a specific <code>user_id</code>.</p>
  14155. <p>The API is:</p>
  14156. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/accountdata
  14157. </code></pre>
  14158. <p>A response body like the following is returned:</p>
  14159. <pre><code class="language-json">{
  14160. &quot;account_data&quot;: {
  14161. &quot;global&quot;: {
  14162. &quot;m.secret_storage.key.LmIGHTg5W&quot;: {
  14163. &quot;algorithm&quot;: &quot;m.secret_storage.v1.aes-hmac-sha2&quot;,
  14164. &quot;iv&quot;: &quot;fwjNZatxg==&quot;,
  14165. &quot;mac&quot;: &quot;eWh9kNnLWZUNOgnc=&quot;
  14166. },
  14167. &quot;im.vector.hide_profile&quot;: {
  14168. &quot;hide_profile&quot;: true
  14169. },
  14170. &quot;org.matrix.preview_urls&quot;: {
  14171. &quot;disable&quot;: false
  14172. },
  14173. &quot;im.vector.riot.breadcrumb_rooms&quot;: {
  14174. &quot;rooms&quot;: [
  14175. &quot;!LxcBDAsDUVAfJDEo:matrix.org&quot;,
  14176. &quot;!MAhRxqasbItjOqxu:matrix.org&quot;
  14177. ]
  14178. },
  14179. &quot;m.accepted_terms&quot;: {
  14180. &quot;accepted&quot;: [
  14181. &quot;https://example.org/somewhere/privacy-1.2-en.html&quot;,
  14182. &quot;https://example.org/somewhere/terms-2.0-en.html&quot;
  14183. ]
  14184. },
  14185. &quot;im.vector.setting.breadcrumbs&quot;: {
  14186. &quot;recent_rooms&quot;: [
  14187. &quot;!MAhRxqasbItqxuEt:matrix.org&quot;,
  14188. &quot;!ZtSaPCawyWtxiImy:matrix.org&quot;
  14189. ]
  14190. }
  14191. },
  14192. &quot;rooms&quot;: {
  14193. &quot;!GUdfZSHUJibpiVqHYd:matrix.org&quot;: {
  14194. &quot;m.fully_read&quot;: {
  14195. &quot;event_id&quot;: &quot;$156334540fYIhZ:matrix.org&quot;
  14196. }
  14197. },
  14198. &quot;!tOZwOOiqwCYQkLhV:matrix.org&quot;: {
  14199. &quot;m.fully_read&quot;: {
  14200. &quot;event_id&quot;: &quot;$xjsIyp4_NaVl2yPvIZs_k1Jl8tsC_Sp23wjqXPno&quot;
  14201. }
  14202. }
  14203. }
  14204. }
  14205. }
  14206. </code></pre>
  14207. <p><strong>Parameters</strong></p>
  14208. <p>The following parameters should be set in the URL:</p>
  14209. <ul>
  14210. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14211. </ul>
  14212. <p><strong>Response</strong></p>
  14213. <p>The following fields are returned in the JSON response body:</p>
  14214. <ul>
  14215. <li><code>account_data</code> - A map containing the account data for the user
  14216. <ul>
  14217. <li><code>global</code> - A map containing the global account data for the user</li>
  14218. <li><code>rooms</code> - A map containing the account data per room for the user</li>
  14219. </ul>
  14220. </li>
  14221. </ul>
  14222. <h2 id="user-media"><a class="header" href="#user-media">User media</a></h2>
  14223. <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>
  14224. <p>Gets a list of all local media that a specific <code>user_id</code> has created.
  14225. These are media that the user has uploaded themselves
  14226. (<a href="admin_api/../media_repository.html#local-media">local media</a>), as well as
  14227. <a href="admin_api/../media_repository.html#url-previews">URL preview images</a> requested by the user if the
  14228. <a href="admin_api/../usage/configuration/config_documentation.html#url_preview_enabled">feature is enabled</a>.</p>
  14229. <p>By default, the response is ordered by descending creation date and ascending media ID.
  14230. The newest media is on top. You can change the order with parameters
  14231. <code>order_by</code> and <code>dir</code>.</p>
  14232. <p>The API is:</p>
  14233. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/media
  14234. </code></pre>
  14235. <p>A response body like the following is returned:</p>
  14236. <pre><code class="language-json">{
  14237. &quot;media&quot;: [
  14238. {
  14239. &quot;created_ts&quot;: 100400,
  14240. &quot;last_access_ts&quot;: null,
  14241. &quot;media_id&quot;: &quot;qXhyRzulkwLsNHTbpHreuEgo&quot;,
  14242. &quot;media_length&quot;: 67,
  14243. &quot;media_type&quot;: &quot;image/png&quot;,
  14244. &quot;quarantined_by&quot;: null,
  14245. &quot;safe_from_quarantine&quot;: false,
  14246. &quot;upload_name&quot;: &quot;test1.png&quot;
  14247. },
  14248. {
  14249. &quot;created_ts&quot;: 200400,
  14250. &quot;last_access_ts&quot;: null,
  14251. &quot;media_id&quot;: &quot;FHfiSnzoINDatrXHQIXBtahw&quot;,
  14252. &quot;media_length&quot;: 67,
  14253. &quot;media_type&quot;: &quot;image/png&quot;,
  14254. &quot;quarantined_by&quot;: null,
  14255. &quot;safe_from_quarantine&quot;: false,
  14256. &quot;upload_name&quot;: &quot;test2.png&quot;
  14257. }
  14258. ],
  14259. &quot;next_token&quot;: 3,
  14260. &quot;total&quot;: 2
  14261. }
  14262. </code></pre>
  14263. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  14264. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  14265. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  14266. reports to paginate through.</p>
  14267. <p><strong>Parameters</strong></p>
  14268. <p>The following parameters should be set in the URL:</p>
  14269. <ul>
  14270. <li>
  14271. <p><code>user_id</code> - string - fully qualified: for example, <code>@user:server.com</code>.</p>
  14272. </li>
  14273. <li>
  14274. <p><code>limit</code>: string representing a positive integer - Is optional but is used for pagination,
  14275. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  14276. </li>
  14277. <li>
  14278. <p><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  14279. denoting the offset in the returned results. This should be treated as an opaque value and
  14280. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  14281. Defaults to <code>0</code>.</p>
  14282. </li>
  14283. <li>
  14284. <p><code>order_by</code> - The method by which to sort the returned list of media.
  14285. If the ordered field has duplicates, the second order is always by ascending <code>media_id</code>,
  14286. which guarantees a stable ordering. Valid values are:</p>
  14287. <ul>
  14288. <li><code>media_id</code> - Media are ordered alphabetically by <code>media_id</code>.</li>
  14289. <li><code>upload_name</code> - Media are ordered alphabetically by name the media was uploaded with.</li>
  14290. <li><code>created_ts</code> - Media are ordered by when the content was uploaded in ms.
  14291. Smallest to largest. This is the default.</li>
  14292. <li><code>last_access_ts</code> - Media are ordered by when the content was last accessed in ms.
  14293. Smallest to largest.</li>
  14294. <li><code>media_length</code> - Media are ordered by length of the media in bytes.
  14295. Smallest to largest.</li>
  14296. <li><code>media_type</code> - Media are ordered alphabetically by MIME-type.</li>
  14297. <li><code>quarantined_by</code> - Media are ordered alphabetically by the user ID that
  14298. initiated the quarantine request for this media.</li>
  14299. <li><code>safe_from_quarantine</code> - Media are ordered by the status if this media is safe
  14300. from quarantining.</li>
  14301. </ul>
  14302. </li>
  14303. <li>
  14304. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  14305. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  14306. </li>
  14307. </ul>
  14308. <p>If neither <code>order_by</code> nor <code>dir</code> is set, the default order is newest media on top
  14309. (corresponds to <code>order_by</code> = <code>created_ts</code> and <code>dir</code> = <code>b</code>).</p>
  14310. <p>Caution. The database only has indexes on the columns <code>media_id</code>,
  14311. <code>user_id</code> and <code>created_ts</code>. This means that if a different sort order is used
  14312. (<code>upload_name</code>, <code>last_access_ts</code>, <code>media_length</code>, <code>media_type</code>,
  14313. <code>quarantined_by</code> or <code>safe_from_quarantine</code>), this can cause a large load on the
  14314. database, especially for large environments.</p>
  14315. <p><strong>Response</strong></p>
  14316. <p>The following fields are returned in the JSON response body:</p>
  14317. <ul>
  14318. <li><code>media</code> - An array of objects, each containing information about a media.
  14319. Media objects contain the following fields:
  14320. <ul>
  14321. <li><code>created_ts</code> - integer - Timestamp when the content was uploaded in ms.</li>
  14322. <li><code>last_access_ts</code> - integer - Timestamp when the content was last accessed in ms.</li>
  14323. <li><code>media_id</code> - string - The id used to refer to the media. Details about the format
  14324. are documented under
  14325. <a href="admin_api/../media_repository.html">media repository</a>.</li>
  14326. <li><code>media_length</code> - integer - Length of the media in bytes.</li>
  14327. <li><code>media_type</code> - string - The MIME-type of the media.</li>
  14328. <li><code>quarantined_by</code> - string - The user ID that initiated the quarantine request
  14329. for this media.</li>
  14330. <li><code>safe_from_quarantine</code> - bool - Status if this media is safe from quarantining.</li>
  14331. <li><code>upload_name</code> - string - The name the media was uploaded with.</li>
  14332. </ul>
  14333. </li>
  14334. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  14335. <li><code>total</code> - integer - Total number of media.</li>
  14336. </ul>
  14337. <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>
  14338. <p>This API deletes the <em>local</em> media from the disk of your own server
  14339. that a specific <code>user_id</code> has created. This includes any local thumbnails.</p>
  14340. <p>This API will not affect media that has been uploaded to external
  14341. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).</p>
  14342. <p>By default, the API deletes media ordered by descending creation date and ascending media ID.
  14343. The newest media is deleted first. You can change the order with parameters
  14344. <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>
  14345. <p>The API is:</p>
  14346. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/media
  14347. </code></pre>
  14348. <p>A response body like the following is returned:</p>
  14349. <pre><code class="language-json">{
  14350. &quot;deleted_media&quot;: [
  14351. &quot;abcdefghijklmnopqrstuvwx&quot;
  14352. ],
  14353. &quot;total&quot;: 1
  14354. }
  14355. </code></pre>
  14356. <p>The following fields are returned in the JSON response body:</p>
  14357. <ul>
  14358. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  14359. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  14360. </ul>
  14361. <p><strong>Note</strong>: There is no <code>next_token</code>. This is not useful for deleting media, because
  14362. after deleting media the remaining media have a new order.</p>
  14363. <p><strong>Parameters</strong></p>
  14364. <p>This API has the same parameters as
  14365. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>.
  14366. With the parameters you can for example limit the number of files to delete at once or
  14367. delete largest/smallest or newest/oldest files first.</p>
  14368. <h2 id="login-as-a-user"><a class="header" href="#login-as-a-user">Login as a user</a></h2>
  14369. <p><strong>Note:</strong> This API is disabled when MSC3861 is enabled. <a href="https://github.com/matrix-org/synapse/pull/15582">See #15582</a></p>
  14370. <p>Get an access token that can be used to authenticate as that user. Useful for
  14371. when admins wish to do actions on behalf of a user.</p>
  14372. <p>The API is:</p>
  14373. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/login
  14374. {}
  14375. </code></pre>
  14376. <p>An optional <code>valid_until_ms</code> field can be specified in the request body as an
  14377. integer timestamp that specifies when the token should expire. By default tokens
  14378. do not expire. Note that this API does not allow a user to login as themselves
  14379. (to create more tokens).</p>
  14380. <p>A response body like the following is returned:</p>
  14381. <pre><code class="language-json">{
  14382. &quot;access_token&quot;: &quot;&lt;opaque_access_token_string&gt;&quot;
  14383. }
  14384. </code></pre>
  14385. <p>This API does <em>not</em> generate a new device for the user, and so will not appear
  14386. their <code>/devices</code> list, and in general the target user should not be able to
  14387. tell they have been logged in as.</p>
  14388. <p>To expire the token call the standard <code>/logout</code> API with the token.</p>
  14389. <p>Note: The token will expire if the <em>admin</em> user calls <code>/logout/all</code> from any
  14390. of their devices, but the token will <em>not</em> expire if the target user does the
  14391. same.</p>
  14392. <h2 id="user-devices"><a class="header" href="#user-devices">User devices</a></h2>
  14393. <h3 id="list-all-devices"><a class="header" href="#list-all-devices">List all devices</a></h3>
  14394. <p>Gets information about all devices for a specific <code>user_id</code>.</p>
  14395. <p>The API is:</p>
  14396. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices
  14397. </code></pre>
  14398. <p>A response body like the following is returned:</p>
  14399. <pre><code class="language-json">{
  14400. &quot;devices&quot;: [
  14401. {
  14402. &quot;device_id&quot;: &quot;QBUAZIFURK&quot;,
  14403. &quot;display_name&quot;: &quot;android&quot;,
  14404. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  14405. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  14406. &quot;last_seen_ts&quot;: 1474491775024,
  14407. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  14408. },
  14409. {
  14410. &quot;device_id&quot;: &quot;AUIECTSRND&quot;,
  14411. &quot;display_name&quot;: &quot;ios&quot;,
  14412. &quot;last_seen_ip&quot;: &quot;1.2.3.5&quot;,
  14413. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  14414. &quot;last_seen_ts&quot;: 1474491775025,
  14415. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  14416. }
  14417. ],
  14418. &quot;total&quot;: 2
  14419. }
  14420. </code></pre>
  14421. <p><strong>Parameters</strong></p>
  14422. <p>The following parameters should be set in the URL:</p>
  14423. <ul>
  14424. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14425. </ul>
  14426. <p><strong>Response</strong></p>
  14427. <p>The following fields are returned in the JSON response body:</p>
  14428. <ul>
  14429. <li>
  14430. <p><code>devices</code> - An array of objects, each containing information about a device.
  14431. Device objects contain the following fields:</p>
  14432. <ul>
  14433. <li><code>device_id</code> - Identifier of device.</li>
  14434. <li><code>display_name</code> - Display name set by the user for this device.
  14435. Absent if no name has been set.</li>
  14436. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  14437. (May be a few minutes out of date, for efficiency reasons).</li>
  14438. <li><code>last_seen_user_agent</code> - The user agent of the device when it was last seen.
  14439. (May be a few minutes out of date, for efficiency reasons).</li>
  14440. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  14441. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  14442. <li><code>user_id</code> - Owner of device.</li>
  14443. </ul>
  14444. </li>
  14445. <li>
  14446. <p><code>total</code> - Total number of user's devices.</p>
  14447. </li>
  14448. </ul>
  14449. <h3 id="create-a-device"><a class="header" href="#create-a-device">Create a device</a></h3>
  14450. <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>
  14451. exists already.</p>
  14452. <p>The API is:</p>
  14453. <pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/devices
  14454. {
  14455. &quot;device_id&quot;: &quot;QBUAZIFURK&quot;
  14456. }
  14457. </code></pre>
  14458. <p>An empty JSON dict is returned.</p>
  14459. <p><strong>Parameters</strong></p>
  14460. <p>The following parameters should be set in the URL:</p>
  14461. <ul>
  14462. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14463. </ul>
  14464. <p>The following fields are required in the JSON request body:</p>
  14465. <ul>
  14466. <li><code>device_id</code> - The device ID to create.</li>
  14467. </ul>
  14468. <h3 id="delete-multiple-devices"><a class="header" href="#delete-multiple-devices">Delete multiple devices</a></h3>
  14469. <p>Deletes the given devices for a specific <code>user_id</code>, and invalidates
  14470. any access token associated with them.</p>
  14471. <p>The API is:</p>
  14472. <pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/delete_devices
  14473. {
  14474. &quot;devices&quot;: [
  14475. &quot;QBUAZIFURK&quot;,
  14476. &quot;AUIECTSRND&quot;
  14477. ]
  14478. }
  14479. </code></pre>
  14480. <p>An empty JSON dict is returned.</p>
  14481. <p><strong>Parameters</strong></p>
  14482. <p>The following parameters should be set in the URL:</p>
  14483. <ul>
  14484. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14485. </ul>
  14486. <p>The following fields are required in the JSON request body:</p>
  14487. <ul>
  14488. <li><code>devices</code> - The list of device IDs to delete.</li>
  14489. </ul>
  14490. <h3 id="show-a-device"><a class="header" href="#show-a-device">Show a device</a></h3>
  14491. <p>Gets information on a single device, by <code>device_id</code> for a specific <code>user_id</code>.</p>
  14492. <p>The API is:</p>
  14493. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  14494. </code></pre>
  14495. <p>A response body like the following is returned:</p>
  14496. <pre><code class="language-json">{
  14497. &quot;device_id&quot;: &quot;&lt;device_id&gt;&quot;,
  14498. &quot;display_name&quot;: &quot;android&quot;,
  14499. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  14500. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  14501. &quot;last_seen_ts&quot;: 1474491775024,
  14502. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  14503. }
  14504. </code></pre>
  14505. <p><strong>Parameters</strong></p>
  14506. <p>The following parameters should be set in the URL:</p>
  14507. <ul>
  14508. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14509. <li><code>device_id</code> - The device to retrieve.</li>
  14510. </ul>
  14511. <p><strong>Response</strong></p>
  14512. <p>The following fields are returned in the JSON response body:</p>
  14513. <ul>
  14514. <li><code>device_id</code> - Identifier of device.</li>
  14515. <li><code>display_name</code> - Display name set by the user for this device.
  14516. Absent if no name has been set.</li>
  14517. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  14518. (May be a few minutes out of date, for efficiency reasons).
  14519. <ul>
  14520. <li><code>last_seen_user_agent</code> - The user agent of the device when it was last seen.
  14521. (May be a few minutes out of date, for efficiency reasons).</li>
  14522. </ul>
  14523. </li>
  14524. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  14525. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  14526. <li><code>user_id</code> - Owner of device.</li>
  14527. </ul>
  14528. <h3 id="update-a-device"><a class="header" href="#update-a-device">Update a device</a></h3>
  14529. <p>Updates the metadata on the given <code>device_id</code> for a specific <code>user_id</code>.</p>
  14530. <p>The API is:</p>
  14531. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  14532. {
  14533. &quot;display_name&quot;: &quot;My other phone&quot;
  14534. }
  14535. </code></pre>
  14536. <p>An empty JSON dict is returned.</p>
  14537. <p><strong>Parameters</strong></p>
  14538. <p>The following parameters should be set in the URL:</p>
  14539. <ul>
  14540. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14541. <li><code>device_id</code> - The device to update.</li>
  14542. </ul>
  14543. <p>The following fields are required in the JSON request body:</p>
  14544. <ul>
  14545. <li><code>display_name</code> - The new display name for this device. If not given,
  14546. the display name is unchanged.</li>
  14547. </ul>
  14548. <h3 id="delete-a-device"><a class="header" href="#delete-a-device">Delete a device</a></h3>
  14549. <p>Deletes the given <code>device_id</code> for a specific <code>user_id</code>,
  14550. and invalidates any access token associated with it.</p>
  14551. <p>The API is:</p>
  14552. <pre><code>DELETE /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  14553. {}
  14554. </code></pre>
  14555. <p>An empty JSON dict is returned.</p>
  14556. <p><strong>Parameters</strong></p>
  14557. <p>The following parameters should be set in the URL:</p>
  14558. <ul>
  14559. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14560. <li><code>device_id</code> - The device to delete.</li>
  14561. </ul>
  14562. <h2 id="list-all-pushers"><a class="header" href="#list-all-pushers">List all pushers</a></h2>
  14563. <p>Gets information about all pushers for a specific <code>user_id</code>.</p>
  14564. <p>The API is:</p>
  14565. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/pushers
  14566. </code></pre>
  14567. <p>A response body like the following is returned:</p>
  14568. <pre><code class="language-json">{
  14569. &quot;pushers&quot;: [
  14570. {
  14571. &quot;app_display_name&quot;:&quot;HTTP Push Notifications&quot;,
  14572. &quot;app_id&quot;:&quot;m.http&quot;,
  14573. &quot;data&quot;: {
  14574. &quot;url&quot;:&quot;example.com&quot;
  14575. },
  14576. &quot;device_display_name&quot;:&quot;pushy push&quot;,
  14577. &quot;kind&quot;:&quot;http&quot;,
  14578. &quot;lang&quot;:&quot;None&quot;,
  14579. &quot;profile_tag&quot;:&quot;&quot;,
  14580. &quot;pushkey&quot;:&quot;a@example.com&quot;
  14581. }
  14582. ],
  14583. &quot;total&quot;: 1
  14584. }
  14585. </code></pre>
  14586. <p><strong>Parameters</strong></p>
  14587. <p>The following parameters should be set in the URL:</p>
  14588. <ul>
  14589. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  14590. </ul>
  14591. <p><strong>Response</strong></p>
  14592. <p>The following fields are returned in the JSON response body:</p>
  14593. <ul>
  14594. <li>
  14595. <p><code>pushers</code> - An array containing the current pushers for the user</p>
  14596. <ul>
  14597. <li>
  14598. <p><code>app_display_name</code> - string - A string that will allow the user to identify
  14599. what application owns this pusher.</p>
  14600. </li>
  14601. <li>
  14602. <p><code>app_id</code> - string - This is a reverse-DNS style identifier for the application.
  14603. Max length, 64 chars.</p>
  14604. </li>
  14605. <li>
  14606. <p><code>data</code> - A dictionary of information for the pusher implementation itself.</p>
  14607. <ul>
  14608. <li>
  14609. <p><code>url</code> - string - Required if <code>kind</code> is <code>http</code>. The URL to use to send
  14610. notifications to.</p>
  14611. </li>
  14612. <li>
  14613. <p><code>format</code> - string - The format to use when sending notifications to the
  14614. Push Gateway.</p>
  14615. </li>
  14616. </ul>
  14617. </li>
  14618. <li>
  14619. <p><code>device_display_name</code> - string - A string that will allow the user to identify
  14620. what device owns this pusher.</p>
  14621. </li>
  14622. <li>
  14623. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  14624. this pusher executes.</p>
  14625. </li>
  14626. <li>
  14627. <p><code>kind</code> - string - The kind of pusher. &quot;http&quot; is a pusher that sends HTTP pokes.</p>
  14628. </li>
  14629. <li>
  14630. <p><code>lang</code> - string - The preferred language for receiving notifications
  14631. (e.g. 'en' or 'en-US')</p>
  14632. </li>
  14633. <li>
  14634. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  14635. this pusher executes.</p>
  14636. </li>
  14637. <li>
  14638. <p><code>pushkey</code> - string - This is a unique identifier for this pusher.
  14639. Max length, 512 bytes.</p>
  14640. </li>
  14641. </ul>
  14642. </li>
  14643. <li>
  14644. <p><code>total</code> - integer - Number of pushers.</p>
  14645. </li>
  14646. </ul>
  14647. <p>See also the
  14648. <a href="https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-pushers">Client-Server API Spec on pushers</a>.</p>
  14649. <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>
  14650. <p>Shadow-banning is a useful tool for moderating malicious or egregiously abusive users.
  14651. A shadow-banned users receives successful responses to their client-server API requests,
  14652. but the events are not propagated into rooms. This can be an effective tool as it
  14653. (hopefully) takes longer for the user to realise they are being moderated before
  14654. pivoting to another account.</p>
  14655. <p>Shadow-banning a user should be used as a tool of last resort and may lead to confusing
  14656. or broken behaviour for the client. A shadow-banned user will not receive any
  14657. notification and it is generally more appropriate to ban or kick abusive users.
  14658. A shadow-banned user will be unable to contact anyone on the server.</p>
  14659. <p>To shadow-ban a user the API is:</p>
  14660. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  14661. </code></pre>
  14662. <p>To un-shadow-ban a user the API is:</p>
  14663. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  14664. </code></pre>
  14665. <p>An empty JSON dict is returned in both cases.</p>
  14666. <p><strong>Parameters</strong></p>
  14667. <p>The following parameters should be set in the URL:</p>
  14668. <ul>
  14669. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  14670. be local.</li>
  14671. </ul>
  14672. <h2 id="override-ratelimiting-for-users"><a class="header" href="#override-ratelimiting-for-users">Override ratelimiting for users</a></h2>
  14673. <p>This API allows to override or disable ratelimiting for a specific user.
  14674. There are specific APIs to set, get and delete a ratelimit.</p>
  14675. <h3 id="get-status-of-ratelimit"><a class="header" href="#get-status-of-ratelimit">Get status of ratelimit</a></h3>
  14676. <p>The API is:</p>
  14677. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  14678. </code></pre>
  14679. <p>A response body like the following is returned:</p>
  14680. <pre><code class="language-json">{
  14681. &quot;messages_per_second&quot;: 0,
  14682. &quot;burst_count&quot;: 0
  14683. }
  14684. </code></pre>
  14685. <p><strong>Parameters</strong></p>
  14686. <p>The following parameters should be set in the URL:</p>
  14687. <ul>
  14688. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  14689. be local.</li>
  14690. </ul>
  14691. <p><strong>Response</strong></p>
  14692. <p>The following fields are returned in the JSON response body:</p>
  14693. <ul>
  14694. <li><code>messages_per_second</code> - integer - The number of actions that can
  14695. be performed in a second. <code>0</code> mean that ratelimiting is disabled for this user.</li>
  14696. <li><code>burst_count</code> - integer - How many actions that can be performed before
  14697. being limited.</li>
  14698. </ul>
  14699. <p>If <strong>no</strong> custom ratelimit is set, an empty JSON dict is returned.</p>
  14700. <pre><code class="language-json">{}
  14701. </code></pre>
  14702. <h3 id="set-ratelimit"><a class="header" href="#set-ratelimit">Set ratelimit</a></h3>
  14703. <p>The API is:</p>
  14704. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  14705. </code></pre>
  14706. <p>A response body like the following is returned:</p>
  14707. <pre><code class="language-json">{
  14708. &quot;messages_per_second&quot;: 0,
  14709. &quot;burst_count&quot;: 0
  14710. }
  14711. </code></pre>
  14712. <p><strong>Parameters</strong></p>
  14713. <p>The following parameters should be set in the URL:</p>
  14714. <ul>
  14715. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  14716. be local.</li>
  14717. </ul>
  14718. <p>Body parameters:</p>
  14719. <ul>
  14720. <li><code>messages_per_second</code> - positive integer, optional. The number of actions that can
  14721. be performed in a second. Defaults to <code>0</code>.</li>
  14722. <li><code>burst_count</code> - positive integer, optional. How many actions that can be performed
  14723. before being limited. Defaults to <code>0</code>.</li>
  14724. </ul>
  14725. <p>To disable users' ratelimit set both values to <code>0</code>.</p>
  14726. <p><strong>Response</strong></p>
  14727. <p>The following fields are returned in the JSON response body:</p>
  14728. <ul>
  14729. <li><code>messages_per_second</code> - integer - The number of actions that can
  14730. be performed in a second.</li>
  14731. <li><code>burst_count</code> - integer - How many actions that can be performed before
  14732. being limited.</li>
  14733. </ul>
  14734. <h3 id="delete-ratelimit"><a class="header" href="#delete-ratelimit">Delete ratelimit</a></h3>
  14735. <p>The API is:</p>
  14736. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  14737. </code></pre>
  14738. <p>An empty JSON dict is returned.</p>
  14739. <pre><code class="language-json">{}
  14740. </code></pre>
  14741. <p><strong>Parameters</strong></p>
  14742. <p>The following parameters should be set in the URL:</p>
  14743. <ul>
  14744. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  14745. be local.</li>
  14746. </ul>
  14747. <h2 id="check-username-availability"><a class="header" href="#check-username-availability">Check username availability</a></h2>
  14748. <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
  14749. API</a>
  14750. for more information.</p>
  14751. <p>This endpoint will work even if registration is disabled on the server, unlike
  14752. <code>/_matrix/client/r0/register/available</code>.</p>
  14753. <p>The API is:</p>
  14754. <pre><code>GET /_synapse/admin/v1/username_available?username=$localpart
  14755. </code></pre>
  14756. <p>The request and response format is the same as the
  14757. <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>
  14758. <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>
  14759. <p>The API is:</p>
  14760. <pre><code>GET /_synapse/admin/v1/auth_providers/$provider/users/$external_id
  14761. </code></pre>
  14762. <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>
  14763. <pre><code class="language-json">{
  14764. &quot;user_id&quot;: &quot;@hello:example.org&quot;
  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>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>
  14771. <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>
  14772. </ul>
  14773. <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>
  14774. <p><strong>Errors</strong></p>
  14775. <p>Returns a <code>404</code> HTTP status code if no user was found, with a response body like this:</p>
  14776. <pre><code class="language-json">{
  14777. &quot;errcode&quot;:&quot;M_NOT_FOUND&quot;,
  14778. &quot;error&quot;:&quot;User not found&quot;
  14779. }
  14780. </code></pre>
  14781. <p><em>Added in Synapse 1.68.0.</em></p>
  14782. <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>
  14783. <p>The API is:</p>
  14784. <pre><code>GET /_synapse/admin/v1/threepid/$medium/users/$address
  14785. </code></pre>
  14786. <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>
  14787. <pre><code class="language-json">{
  14788. &quot;user_id&quot;: &quot;@hello:example.org&quot;
  14789. }
  14790. </code></pre>
  14791. <p><strong>Parameters</strong></p>
  14792. <p>The following parameters should be set in the URL:</p>
  14793. <ul>
  14794. <li><code>medium</code> - Kind of third-party ID, either <code>email</code> or <code>msisdn</code>.</li>
  14795. <li><code>address</code> - Value of the third-party ID.</li>
  14796. </ul>
  14797. <p>The <code>address</code> may have characters that are not URL-safe, so it is advised to URL-encode those parameters.</p>
  14798. <p><strong>Errors</strong></p>
  14799. <p>Returns a <code>404</code> HTTP status code if no user was found, with a response body like this:</p>
  14800. <pre><code class="language-json">{
  14801. &quot;errcode&quot;:&quot;M_NOT_FOUND&quot;,
  14802. &quot;error&quot;:&quot;User not found&quot;
  14803. }
  14804. </code></pre>
  14805. <p><em>Added in Synapse 1.72.0.</em></p>
  14806. <div style="break-before: page; page-break-before: always;"></div><h1 id="version-api"><a class="header" href="#version-api">Version API</a></h1>
  14807. <p>This API returns the running Synapse version.
  14808. This is useful when a Synapse instance
  14809. is behind a proxy that does not forward the 'Server' header (which also
  14810. contains Synapse version information).</p>
  14811. <p>The api is:</p>
  14812. <pre><code>GET /_synapse/admin/v1/server_version
  14813. </code></pre>
  14814. <p>It returns a JSON body like the following:</p>
  14815. <pre><code class="language-json">{
  14816. &quot;server_version&quot;: &quot;0.99.2rc1 (b=develop, abcdef123)&quot;
  14817. }
  14818. </code></pre>
  14819. <p><em>Changed in Synapse 1.94.0:</em> The <code>python_version</code> key was removed from the
  14820. response body.</p>
  14821. <div style="break-before: page; page-break-before: always;"></div><h1 id="federation-api"><a class="header" href="#federation-api">Federation API</a></h1>
  14822. <p>This API allows a server administrator to manage Synapse's federation with other homeservers.</p>
  14823. <p>Note: This API is new, experimental and &quot;subject to change&quot;.</p>
  14824. <h2 id="list-of-destinations"><a class="header" href="#list-of-destinations">List of destinations</a></h2>
  14825. <p>This API gets the current destination retry timing info for all remote servers.</p>
  14826. <p>The list contains all the servers with which the server federates,
  14827. regardless of whether an error occurred or not.
  14828. If an error occurs, it may take up to 20 minutes for the error to be displayed here,
  14829. as a complete retry must have failed.</p>
  14830. <p>The API is:</p>
  14831. <p>A standard request with no filtering:</p>
  14832. <pre><code>GET /_synapse/admin/v1/federation/destinations
  14833. </code></pre>
  14834. <p>A response body like the following is returned:</p>
  14835. <pre><code class="language-json">{
  14836. &quot;destinations&quot;:[
  14837. {
  14838. &quot;destination&quot;: &quot;matrix.org&quot;,
  14839. &quot;retry_last_ts&quot;: 1557332397936,
  14840. &quot;retry_interval&quot;: 3000000,
  14841. &quot;failure_ts&quot;: 1557329397936,
  14842. &quot;last_successful_stream_ordering&quot;: null
  14843. }
  14844. ],
  14845. &quot;total&quot;: 1
  14846. }
  14847. </code></pre>
  14848. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  14849. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  14850. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  14851. to paginate through.</p>
  14852. <p><strong>Parameters</strong></p>
  14853. <p>The following query parameters are available:</p>
  14854. <ul>
  14855. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  14856. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  14857. <li><code>order_by</code> - The method in which to sort the returned list of destinations.
  14858. Valid values are:
  14859. <ul>
  14860. <li><code>destination</code> - Destinations are ordered alphabetically by remote server name.
  14861. This is the default.</li>
  14862. <li><code>retry_last_ts</code> - Destinations are ordered by time of last retry attempt in ms.</li>
  14863. <li><code>retry_interval</code> - Destinations are ordered by how long until next retry in ms.</li>
  14864. <li><code>failure_ts</code> - Destinations are ordered by when the server started failing in ms.</li>
  14865. <li><code>last_successful_stream_ordering</code> - Destinations are ordered by the stream ordering
  14866. of the most recent successfully-sent PDU.</li>
  14867. </ul>
  14868. </li>
  14869. <li><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  14870. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  14871. </ul>
  14872. <p><em>Caution:</em> The database only has an index on the column <code>destination</code>.
  14873. This means that if a different sort order is used,
  14874. this can cause a large load on the database, especially for large environments.</p>
  14875. <p><strong>Response</strong></p>
  14876. <p>The following fields are returned in the JSON response body:</p>
  14877. <ul>
  14878. <li><code>destinations</code> - An array of objects, each containing information about a destination.
  14879. Destination objects contain the following fields:
  14880. <ul>
  14881. <li><code>destination</code> - string - Name of the remote server to federate.</li>
  14882. <li><code>retry_last_ts</code> - integer - The last time Synapse tried and failed to reach the
  14883. remote server, in ms. This is <code>0</code> if the last attempt to communicate with the
  14884. remote server was successful.</li>
  14885. <li><code>retry_interval</code> - integer - How long since the last time Synapse tried to reach
  14886. the remote server before trying again, in ms. This is <code>0</code> if no further retrying occurring.</li>
  14887. <li><code>failure_ts</code> - nullable integer - The first time Synapse tried and failed to reach the
  14888. remote server, in ms. This is <code>null</code> if communication with the remote server has never failed.</li>
  14889. <li><code>last_successful_stream_ordering</code> - nullable integer - The stream ordering of the most
  14890. recent successfully-sent <a href="usage/administration/admin_api/../understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  14891. to this destination, or <code>null</code> if this information has not been tracked yet.</li>
  14892. </ul>
  14893. </li>
  14894. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  14895. <li><code>total</code> - integer - Total number of destinations.</li>
  14896. </ul>
  14897. <h2 id="destination-details-api"><a class="header" href="#destination-details-api">Destination Details API</a></h2>
  14898. <p>This API gets the retry timing info for a specific remote server.</p>
  14899. <p>The API is:</p>
  14900. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;
  14901. </code></pre>
  14902. <p>A response body like the following is returned:</p>
  14903. <pre><code class="language-json">{
  14904. &quot;destination&quot;: &quot;matrix.org&quot;,
  14905. &quot;retry_last_ts&quot;: 1557332397936,
  14906. &quot;retry_interval&quot;: 3000000,
  14907. &quot;failure_ts&quot;: 1557329397936,
  14908. &quot;last_successful_stream_ordering&quot;: null
  14909. }
  14910. </code></pre>
  14911. <p><strong>Parameters</strong></p>
  14912. <p>The following parameters should be set in the URL:</p>
  14913. <ul>
  14914. <li><code>destination</code> - Name of the remote server.</li>
  14915. </ul>
  14916. <p><strong>Response</strong></p>
  14917. <p>The response fields are the same like in the <code>destinations</code> array in
  14918. <a href="usage/administration/admin_api/federation.html#list-of-destinations">List of destinations</a> response.</p>
  14919. <h2 id="destination-rooms"><a class="header" href="#destination-rooms">Destination rooms</a></h2>
  14920. <p>This API gets the rooms that federate with a specific remote server.</p>
  14921. <p>The API is:</p>
  14922. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/rooms
  14923. </code></pre>
  14924. <p>A response body like the following is returned:</p>
  14925. <pre><code class="language-json">{
  14926. &quot;rooms&quot;:[
  14927. {
  14928. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  14929. &quot;stream_ordering&quot;: 8326
  14930. },
  14931. {
  14932. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  14933. &quot;stream_ordering&quot;: 93534
  14934. }
  14935. ],
  14936. &quot;total&quot;: 2
  14937. }
  14938. </code></pre>
  14939. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  14940. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  14941. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  14942. to paginate through.</p>
  14943. <p><strong>Parameters</strong></p>
  14944. <p>The following parameters should be set in the URL:</p>
  14945. <ul>
  14946. <li><code>destination</code> - Name of the remote server.</li>
  14947. </ul>
  14948. <p>The following query parameters are available:</p>
  14949. <ul>
  14950. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  14951. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  14952. <li><code>dir</code> - Direction of room order by <code>room_id</code>. Either <code>f</code> for forwards or <code>b</code> for
  14953. backwards. Defaults to <code>f</code>.</li>
  14954. </ul>
  14955. <p><strong>Response</strong></p>
  14956. <p>The following fields are returned in the JSON response body:</p>
  14957. <ul>
  14958. <li><code>rooms</code> - An array of objects, each containing information about a room.
  14959. Room objects contain the following fields:
  14960. <ul>
  14961. <li><code>room_id</code> - string - The ID of the room.</li>
  14962. <li><code>stream_ordering</code> - integer - The stream ordering of the most recent
  14963. successfully-sent <a href="usage/administration/admin_api/../understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  14964. to this destination in this room.</li>
  14965. </ul>
  14966. </li>
  14967. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  14968. <li><code>total</code> - integer - Total number of destinations.</li>
  14969. </ul>
  14970. <h2 id="reset-connection-timeout"><a class="header" href="#reset-connection-timeout">Reset connection timeout</a></h2>
  14971. <p>Synapse makes federation requests to other homeservers. If a federation request fails,
  14972. Synapse will mark the destination homeserver as offline, preventing any future requests
  14973. to that server for a &quot;cooldown&quot; period. This period grows over time if the server
  14974. continues to fail its responses
  14975. (<a href="https://en.wikipedia.org/wiki/Exponential_backoff">exponential backoff</a>).</p>
  14976. <p>Admins can cancel the cooldown period with this API.</p>
  14977. <p>This API resets the retry timing for a specific remote server and tries to connect to
  14978. the remote server again. It does not wait for the next <code>retry_interval</code>.
  14979. The connection must have previously run into an error and <code>retry_last_ts</code>
  14980. (<a href="usage/administration/admin_api/federation.html#destination-details-api">Destination Details API</a>) must not be equal to <code>0</code>.</p>
  14981. <p>The connection attempt is carried out in the background and can take a while
  14982. even if the API already returns the http status 200.</p>
  14983. <p>The API is:</p>
  14984. <pre><code>POST /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/reset_connection
  14985. {}
  14986. </code></pre>
  14987. <p><strong>Parameters</strong></p>
  14988. <p>The following parameters should be set in the URL:</p>
  14989. <ul>
  14990. <li><code>destination</code> - Name of the remote server.</li>
  14991. </ul>
  14992. <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>
  14993. <p>The &quot;manhole&quot; allows server administrators to access a Python shell on a running
  14994. Synapse installation. This is a very powerful mechanism for administration and
  14995. debugging.</p>
  14996. <p><strong><em>Security Warning</em></strong></p>
  14997. <p>Note that this will give administrative access to synapse to <strong>all users</strong> with
  14998. shell access to the server. It should therefore <strong>not</strong> be enabled in
  14999. environments where untrusted users have shell access.</p>
  15000. <h2 id="configuring-the-manhole"><a class="header" href="#configuring-the-manhole">Configuring the manhole</a></h2>
  15001. <p>To enable it, first add the <code>manhole</code> listener configuration in your
  15002. <code>homeserver.yaml</code>. You can find information on how to do that
  15003. in the <a href="usage/configuration/config_documentation.html#manhole_settings">configuration manual</a>.
  15004. The configuration is slightly different if you're using docker.</p>
  15005. <h4 id="docker-config"><a class="header" href="#docker-config">Docker config</a></h4>
  15006. <p>If you are using Docker, set <code>bind_addresses</code> to <code>['0.0.0.0']</code> as shown:</p>
  15007. <pre><code class="language-yaml">listeners:
  15008. - port: 9000
  15009. bind_addresses: ['0.0.0.0']
  15010. type: manhole
  15011. </code></pre>
  15012. <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
  15013. <code>manhole</code> port forwarding. The <code>-p 127.0.0.1:9000:9000</code> below is important: it
  15014. ensures that access to the <code>manhole</code> is only possible for local users.</p>
  15015. <pre><code class="language-bash">docker run -d --name synapse \
  15016. --mount type=volume,src=synapse-data,dst=/data \
  15017. -p 8008:8008 \
  15018. -p 127.0.0.1:9000:9000 \
  15019. matrixdotorg/synapse:latest
  15020. </code></pre>
  15021. <h4 id="native-config"><a class="header" href="#native-config">Native config</a></h4>
  15022. <p>If you are not using docker, set <code>bind_addresses</code> to <code>['::1', '127.0.0.1']</code> as shown.
  15023. The <code>bind_addresses</code> in the example below is important: it ensures that access to the
  15024. <code>manhole</code> is only possible for local users).</p>
  15025. <pre><code class="language-yaml">listeners:
  15026. - port: 9000
  15027. bind_addresses: ['::1', '127.0.0.1']
  15028. type: manhole
  15029. </code></pre>
  15030. <h3 id="security-settings"><a class="header" href="#security-settings">Security settings</a></h3>
  15031. <p>The following config options are available:</p>
  15032. <ul>
  15033. <li><code>username</code> - The username for the manhole (defaults to <code>matrix</code>)</li>
  15034. <li><code>password</code> - The password for the manhole (defaults to <code>rabbithole</code>)</li>
  15035. <li><code>ssh_priv_key</code> - The path to a private SSH key (defaults to a hardcoded value)</li>
  15036. <li><code>ssh_pub_key</code> - The path to a public SSH key (defaults to a hardcoded value)</li>
  15037. </ul>
  15038. <p>For example:</p>
  15039. <pre><code class="language-yaml">manhole_settings:
  15040. username: manhole
  15041. password: mypassword
  15042. ssh_priv_key: &quot;/home/synapse/manhole_keys/id_rsa&quot;
  15043. ssh_pub_key: &quot;/home/synapse/manhole_keys/id_rsa.pub&quot;
  15044. </code></pre>
  15045. <h2 id="accessing-synapse-manhole"><a class="header" href="#accessing-synapse-manhole">Accessing synapse manhole</a></h2>
  15046. <p>Then restart synapse, and point an ssh client at port 9000 on localhost, using
  15047. the username and password configured in <code>homeserver.yaml</code> - with the default
  15048. configuration, this would be:</p>
  15049. <pre><code class="language-bash">ssh -p9000 matrix@localhost
  15050. </code></pre>
  15051. <p>Then enter the password when prompted (the default is <code>rabbithole</code>).</p>
  15052. <p>This gives a Python REPL in which <code>hs</code> gives access to the
  15053. <code>synapse.server.HomeServer</code> object - which in turn gives access to many other
  15054. parts of the process.</p>
  15055. <p>Note that, prior to Synapse 1.41, any call which returns a coroutine will need to be wrapped in <code>ensureDeferred</code>.</p>
  15056. <p>As a simple example, retrieving an event from the database:</p>
  15057. <pre><code class="language-pycon">&gt;&gt;&gt; from twisted.internet import defer
  15058. &gt;&gt;&gt; defer.ensureDeferred(hs.get_datastores().main.get_event('$1416420717069yeQaw:matrix.org'))
  15059. &lt;Deferred at 0x7ff253fc6998 current result: &lt;FrozenEvent event_id='$1416420717069yeQaw:matrix.org', type='m.room.create', state_key=''&gt;&gt;
  15060. </code></pre>
  15061. <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>
  15062. <ol>
  15063. <li>
  15064. <p>Install Prometheus:</p>
  15065. <p>Follow instructions at
  15066. <a href="http://prometheus.io/docs/introduction/install/">http://prometheus.io/docs/introduction/install/</a></p>
  15067. </li>
  15068. <li>
  15069. <p>Enable Synapse metrics:</p>
  15070. <p>In <code>homeserver.yaml</code>, make sure <code>enable_metrics</code> is
  15071. set to <code>True</code>.</p>
  15072. </li>
  15073. <li>
  15074. <p>Enable the <code>/_synapse/metrics</code> Synapse endpoint that Prometheus uses to
  15075. collect data:</p>
  15076. <p>There are two methods of enabling the metrics endpoint in Synapse.</p>
  15077. <p>The first serves the metrics as a part of the usual web server and
  15078. can be enabled by adding the <code>metrics</code> resource to the existing
  15079. listener as such as in this example:</p>
  15080. <pre><code class="language-yaml">listeners:
  15081. - port: 8008
  15082. tls: false
  15083. type: http
  15084. x_forwarded: true
  15085. bind_addresses: ['::1', '127.0.0.1']
  15086. resources:
  15087. # added &quot;metrics&quot; in this line
  15088. - names: [client, federation, metrics]
  15089. compress: false
  15090. </code></pre>
  15091. <p>This provides a simple way of adding metrics to your Synapse
  15092. installation, and serves under <code>/_synapse/metrics</code>. If you do not
  15093. wish your metrics be publicly exposed, you will need to either
  15094. filter it out at your load balancer, or use the second method.</p>
  15095. <p>The second method runs the metrics server on a different port, in a
  15096. different thread to Synapse. This can make it more resilient to
  15097. heavy load meaning metrics cannot be retrieved, and can be exposed
  15098. to just internal networks easier. The served metrics are available
  15099. over HTTP only, and will be available at <code>/_synapse/metrics</code>.</p>
  15100. <p>Add a new listener to homeserver.yaml as in this example:</p>
  15101. <pre><code class="language-yaml">listeners:
  15102. - port: 8008
  15103. tls: false
  15104. type: http
  15105. x_forwarded: true
  15106. bind_addresses: ['::1', '127.0.0.1']
  15107. resources:
  15108. - names: [client, federation]
  15109. compress: false
  15110. # beginning of the new metrics listener
  15111. - port: 9000
  15112. type: metrics
  15113. bind_addresses: ['::1', '127.0.0.1']
  15114. </code></pre>
  15115. </li>
  15116. <li>
  15117. <p>Restart Synapse.</p>
  15118. </li>
  15119. <li>
  15120. <p>Add a Prometheus target for Synapse.</p>
  15121. <p>It needs to set the <code>metrics_path</code> to a non-default value (under
  15122. <code>scrape_configs</code>):</p>
  15123. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  15124. scrape_interval: 15s
  15125. metrics_path: &quot;/_synapse/metrics&quot;
  15126. static_configs:
  15127. - targets: [&quot;my.server.here:port&quot;]
  15128. </code></pre>
  15129. <p>where <code>my.server.here</code> is the IP address of Synapse, and <code>port</code> is
  15130. the listener port configured with the <code>metrics</code> resource.</p>
  15131. <p>If your prometheus is older than 1.5.2, you will need to replace
  15132. <code>static_configs</code> in the above with <code>target_groups</code>.</p>
  15133. </li>
  15134. <li>
  15135. <p>Restart Prometheus.</p>
  15136. </li>
  15137. <li>
  15138. <p>Consider using the <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana/">grafana dashboard</a>
  15139. and required <a href="https://github.com/matrix-org/synapse/tree/master/contrib/prometheus/">recording rules</a> </p>
  15140. </li>
  15141. </ol>
  15142. <h2 id="monitoring-workers"><a class="header" href="#monitoring-workers">Monitoring workers</a></h2>
  15143. <p>To monitor a Synapse installation using <a href="workers.html">workers</a>,
  15144. every worker needs to be monitored independently, in addition to
  15145. the main homeserver process. This is because workers don't send
  15146. their metrics to the main homeserver process, but expose them
  15147. directly (if they are configured to do so).</p>
  15148. <p>To allow collecting metrics from a worker, you need to add a
  15149. <code>metrics</code> listener to its configuration, by adding the following
  15150. under <code>worker_listeners</code>:</p>
  15151. <pre><code class="language-yaml"> - type: metrics
  15152. bind_address: ''
  15153. port: 9101
  15154. </code></pre>
  15155. <p>The <code>bind_address</code> and <code>port</code> parameters should be set so that
  15156. the resulting listener can be reached by prometheus, and they
  15157. don't clash with an existing worker.
  15158. With this example, the worker's metrics would then be available
  15159. on <code>http://127.0.0.1:9101</code>.</p>
  15160. <p>Example Prometheus target for Synapse with workers:</p>
  15161. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  15162. scrape_interval: 15s
  15163. metrics_path: &quot;/_synapse/metrics&quot;
  15164. static_configs:
  15165. - targets: [&quot;my.server.here:port&quot;]
  15166. labels:
  15167. instance: &quot;my.server&quot;
  15168. job: &quot;master&quot;
  15169. index: 1
  15170. - targets: [&quot;my.workerserver.here:port&quot;]
  15171. labels:
  15172. instance: &quot;my.server&quot;
  15173. job: &quot;generic_worker&quot;
  15174. index: 1
  15175. - targets: [&quot;my.workerserver.here:port&quot;]
  15176. labels:
  15177. instance: &quot;my.server&quot;
  15178. job: &quot;generic_worker&quot;
  15179. index: 2
  15180. - targets: [&quot;my.workerserver.here:port&quot;]
  15181. labels:
  15182. instance: &quot;my.server&quot;
  15183. job: &quot;media_repository&quot;
  15184. index: 1
  15185. </code></pre>
  15186. <p>Labels (<code>instance</code>, <code>job</code>, <code>index</code>) can be defined as anything.
  15187. The labels are used to group graphs in grafana.</p>
  15188. <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>
  15189. <p>Synapse 1.2 updates the Prometheus metrics to match the naming
  15190. convention of the upstream <code>prometheus_client</code>. The old names are
  15191. considered deprecated and will be removed in a future version of
  15192. Synapse.
  15193. <strong>The old names will be disabled by default in Synapse v1.71.0 and removed
  15194. altogether in Synapse v1.73.0.</strong></p>
  15195. <table><thead><tr><th>New Name</th><th>Old Name</th></tr></thead><tbody>
  15196. <tr><td>python_gc_objects_collected_total</td><td>python_gc_objects_collected</td></tr>
  15197. <tr><td>python_gc_objects_uncollectable_total</td><td>python_gc_objects_uncollectable</td></tr>
  15198. <tr><td>python_gc_collections_total</td><td>python_gc_collections</td></tr>
  15199. <tr><td>process_cpu_seconds_total</td><td>process_cpu_seconds</td></tr>
  15200. <tr><td>synapse_federation_client_sent_transactions_total</td><td>synapse_federation_client_sent_transactions</td></tr>
  15201. <tr><td>synapse_federation_client_events_processed_total</td><td>synapse_federation_client_events_processed</td></tr>
  15202. <tr><td>synapse_event_processing_loop_count_total</td><td>synapse_event_processing_loop_count</td></tr>
  15203. <tr><td>synapse_event_processing_loop_room_count_total</td><td>synapse_event_processing_loop_room_count</td></tr>
  15204. <tr><td>synapse_util_caches_cache_hits</td><td>synapse_util_caches_cache:hits</td></tr>
  15205. <tr><td>synapse_util_caches_cache_size</td><td>synapse_util_caches_cache:size</td></tr>
  15206. <tr><td>synapse_util_caches_cache_evicted_size</td><td>synapse_util_caches_cache:evicted_size</td></tr>
  15207. <tr><td>synapse_util_caches_cache</td><td>synapse_util_caches_cache:total</td></tr>
  15208. <tr><td>synapse_util_caches_response_cache_size</td><td>synapse_util_caches_response_cache:size</td></tr>
  15209. <tr><td>synapse_util_caches_response_cache_hits</td><td>synapse_util_caches_response_cache:hits</td></tr>
  15210. <tr><td>synapse_util_caches_response_cache_evicted_size</td><td>synapse_util_caches_response_cache:evicted_size</td></tr>
  15211. <tr><td>synapse_util_metrics_block_count_total</td><td>synapse_util_metrics_block_count</td></tr>
  15212. <tr><td>synapse_util_metrics_block_time_seconds_total</td><td>synapse_util_metrics_block_time_seconds</td></tr>
  15213. <tr><td>synapse_util_metrics_block_ru_utime_seconds_total</td><td>synapse_util_metrics_block_ru_utime_seconds</td></tr>
  15214. <tr><td>synapse_util_metrics_block_ru_stime_seconds_total</td><td>synapse_util_metrics_block_ru_stime_seconds</td></tr>
  15215. <tr><td>synapse_util_metrics_block_db_txn_count_total</td><td>synapse_util_metrics_block_db_txn_count</td></tr>
  15216. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds_total</td><td>synapse_util_metrics_block_db_txn_duration_seconds</td></tr>
  15217. <tr><td>synapse_util_metrics_block_db_sched_duration_seconds_total</td><td>synapse_util_metrics_block_db_sched_duration_seconds</td></tr>
  15218. <tr><td>synapse_background_process_start_count_total</td><td>synapse_background_process_start_count</td></tr>
  15219. <tr><td>synapse_background_process_ru_utime_seconds_total</td><td>synapse_background_process_ru_utime_seconds</td></tr>
  15220. <tr><td>synapse_background_process_ru_stime_seconds_total</td><td>synapse_background_process_ru_stime_seconds</td></tr>
  15221. <tr><td>synapse_background_process_db_txn_count_total</td><td>synapse_background_process_db_txn_count</td></tr>
  15222. <tr><td>synapse_background_process_db_txn_duration_seconds_total</td><td>synapse_background_process_db_txn_duration_seconds</td></tr>
  15223. <tr><td>synapse_background_process_db_sched_duration_seconds_total</td><td>synapse_background_process_db_sched_duration_seconds</td></tr>
  15224. <tr><td>synapse_storage_events_persisted_events_total</td><td>synapse_storage_events_persisted_events</td></tr>
  15225. <tr><td>synapse_storage_events_persisted_events_sep_total</td><td>synapse_storage_events_persisted_events_sep</td></tr>
  15226. <tr><td>synapse_storage_events_state_delta_total</td><td>synapse_storage_events_state_delta</td></tr>
  15227. <tr><td>synapse_storage_events_state_delta_single_event_total</td><td>synapse_storage_events_state_delta_single_event</td></tr>
  15228. <tr><td>synapse_storage_events_state_delta_reuse_delta_total</td><td>synapse_storage_events_state_delta_reuse_delta</td></tr>
  15229. <tr><td>synapse_federation_server_received_pdus_total</td><td>synapse_federation_server_received_pdus</td></tr>
  15230. <tr><td>synapse_federation_server_received_edus_total</td><td>synapse_federation_server_received_edus</td></tr>
  15231. <tr><td>synapse_handler_presence_notified_presence_total</td><td>synapse_handler_presence_notified_presence</td></tr>
  15232. <tr><td>synapse_handler_presence_federation_presence_out_total</td><td>synapse_handler_presence_federation_presence_out</td></tr>
  15233. <tr><td>synapse_handler_presence_presence_updates_total</td><td>synapse_handler_presence_presence_updates</td></tr>
  15234. <tr><td>synapse_handler_presence_timers_fired_total</td><td>synapse_handler_presence_timers_fired</td></tr>
  15235. <tr><td>synapse_handler_presence_federation_presence_total</td><td>synapse_handler_presence_federation_presence</td></tr>
  15236. <tr><td>synapse_handler_presence_bump_active_time_total</td><td>synapse_handler_presence_bump_active_time</td></tr>
  15237. <tr><td>synapse_federation_client_sent_edus_total</td><td>synapse_federation_client_sent_edus</td></tr>
  15238. <tr><td>synapse_federation_client_sent_pdu_destinations_count_total</td><td>synapse_federation_client_sent_pdu_destinations:count</td></tr>
  15239. <tr><td>synapse_federation_client_sent_pdu_destinations_total</td><td>synapse_federation_client_sent_pdu_destinations:total</td></tr>
  15240. <tr><td>synapse_handlers_appservice_events_processed_total</td><td>synapse_handlers_appservice_events_processed</td></tr>
  15241. <tr><td>synapse_notifier_notified_events_total</td><td>synapse_notifier_notified_events</td></tr>
  15242. <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>
  15243. <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>
  15244. <tr><td>synapse_http_httppusher_http_pushes_processed_total</td><td>synapse_http_httppusher_http_pushes_processed</td></tr>
  15245. <tr><td>synapse_http_httppusher_http_pushes_failed_total</td><td>synapse_http_httppusher_http_pushes_failed</td></tr>
  15246. <tr><td>synapse_http_httppusher_badge_updates_processed_total</td><td>synapse_http_httppusher_badge_updates_processed</td></tr>
  15247. <tr><td>synapse_http_httppusher_badge_updates_failed_total</td><td>synapse_http_httppusher_badge_updates_failed</td></tr>
  15248. <tr><td>synapse_admin_mau_current</td><td>synapse_admin_mau:current</td></tr>
  15249. <tr><td>synapse_admin_mau_max</td><td>synapse_admin_mau:max</td></tr>
  15250. <tr><td>synapse_admin_mau_registered_reserved_users</td><td>synapse_admin_mau:registered_reserved_users</td></tr>
  15251. </tbody></table>
  15252. <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>
  15253. <p>The duplicated metrics deprecated in Synapse 0.27.0 have been removed.</p>
  15254. <p>All time duration-based metrics have been changed to be seconds. This
  15255. affects:</p>
  15256. <table><thead><tr><th>msec -&gt; sec metrics</th></tr></thead><tbody>
  15257. <tr><td>python_gc_time</td></tr>
  15258. <tr><td>python_twisted_reactor_tick_time</td></tr>
  15259. <tr><td>synapse_storage_query_time</td></tr>
  15260. <tr><td>synapse_storage_schedule_time</td></tr>
  15261. <tr><td>synapse_storage_transaction_time</td></tr>
  15262. </tbody></table>
  15263. <p>Several metrics have been changed to be histograms, which sort entries
  15264. into buckets and allow better analysis. The following metrics are now
  15265. histograms:</p>
  15266. <table><thead><tr><th>Altered metrics</th></tr></thead><tbody>
  15267. <tr><td>python_gc_time</td></tr>
  15268. <tr><td>python_twisted_reactor_pending_calls</td></tr>
  15269. <tr><td>python_twisted_reactor_tick_time</td></tr>
  15270. <tr><td>synapse_http_server_response_time_seconds</td></tr>
  15271. <tr><td>synapse_storage_query_time</td></tr>
  15272. <tr><td>synapse_storage_schedule_time</td></tr>
  15273. <tr><td>synapse_storage_transaction_time</td></tr>
  15274. </tbody></table>
  15275. <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>
  15276. <p>Synapse 0.27.0 begins the process of rationalising the duplicate
  15277. <code>*:count</code> metrics reported for the resource tracking for code blocks and
  15278. HTTP requests.</p>
  15279. <p>At the same time, the corresponding <code>*:total</code> metrics are being renamed,
  15280. as the <code>:total</code> suffix no longer makes sense in the absence of a
  15281. corresponding <code>:count</code> metric.</p>
  15282. <p>To enable a graceful migration path, this release just adds new names
  15283. for the metrics being renamed. A future release will remove the old
  15284. ones.</p>
  15285. <p>The following table shows the new metrics, and the old metrics which
  15286. they are replacing.</p>
  15287. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  15288. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_timer:count</td></tr>
  15289. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_utime:count</td></tr>
  15290. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_stime:count</td></tr>
  15291. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_count:count</td></tr>
  15292. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_duration:count</td></tr>
  15293. <tr><td>synapse_util_metrics_block_time_seconds</td><td>synapse_util_metrics_block_timer:total</td></tr>
  15294. <tr><td>synapse_util_metrics_block_ru_utime_seconds</td><td>synapse_util_metrics_block_ru_utime:total</td></tr>
  15295. <tr><td>synapse_util_metrics_block_ru_stime_seconds</td><td>synapse_util_metrics_block_ru_stime:total</td></tr>
  15296. <tr><td>synapse_util_metrics_block_db_txn_count</td><td>synapse_util_metrics_block_db_txn_count:total</td></tr>
  15297. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds</td><td>synapse_util_metrics_block_db_txn_duration:total</td></tr>
  15298. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_requests</td></tr>
  15299. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_time:count</td></tr>
  15300. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_utime:count</td></tr>
  15301. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_stime:count</td></tr>
  15302. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_count:count</td></tr>
  15303. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_duration:count</td></tr>
  15304. <tr><td>synapse_http_server_response_time_seconds</td><td>synapse_http_server_response_time:total</td></tr>
  15305. <tr><td>synapse_http_server_response_ru_utime_seconds</td><td>synapse_http_server_response_ru_utime:total</td></tr>
  15306. <tr><td>synapse_http_server_response_ru_stime_seconds</td><td>synapse_http_server_response_ru_stime:total</td></tr>
  15307. <tr><td>synapse_http_server_response_db_txn_count</td><td>synapse_http_server_response_db_txn_count:total</td></tr>
  15308. <tr><td>synapse_http_server_response_db_txn_duration_seconds</td><td>synapse_http_server_response_db_txn_duration:total</td></tr>
  15309. </tbody></table>
  15310. <h2 id="standard-metric-names"><a class="header" href="#standard-metric-names">Standard Metric Names</a></h2>
  15311. <p>As of synapse version 0.18.2, the format of the process-wide metrics has
  15312. been changed to fit prometheus standard naming conventions. Additionally
  15313. the units have been changed to seconds, from milliseconds.</p>
  15314. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  15315. <tr><td>process_cpu_user_seconds_total</td><td>process_resource_utime / 1000</td></tr>
  15316. <tr><td>process_cpu_system_seconds_total</td><td>process_resource_stime / 1000</td></tr>
  15317. <tr><td>process_open_fds (no 'type' label)</td><td>process_fds</td></tr>
  15318. </tbody></table>
  15319. <p>The python-specific counts of garbage collector performance have been
  15320. renamed.</p>
  15321. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  15322. <tr><td>python_gc_time</td><td>reactor_gc_time</td></tr>
  15323. <tr><td>python_gc_unreachable_total</td><td>reactor_gc_unreachable</td></tr>
  15324. <tr><td>python_gc_counts</td><td>reactor_gc_counts</td></tr>
  15325. </tbody></table>
  15326. <p>The twisted-specific reactor metrics have been renamed.</p>
  15327. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  15328. <tr><td>python_twisted_reactor_pending_calls</td><td>reactor_pending_calls</td></tr>
  15329. <tr><td>python_twisted_reactor_tick_time</td><td>reactor_tick_time</td></tr>
  15330. </tbody></table>
  15331. <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>
  15332. <p>When generating your Synapse configuration file, you are asked whether you
  15333. would like to report usage statistics to Matrix.org. These statistics
  15334. provide the foundation a glimpse into the number of Synapse homeservers
  15335. participating in the network, as well as statistics such as the number of
  15336. rooms being created and messages being sent. This feature is sometimes
  15337. affectionately called &quot;phone home&quot; stats. Reporting
  15338. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats">is optional</a>
  15339. and the reporting endpoint
  15340. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats_endpoint">can be configured</a>,
  15341. in case you would like to instead report statistics from a set of homeservers
  15342. to your own infrastructure.</p>
  15343. <p>This documentation aims to define the statistics available and the
  15344. homeserver configuration options that exist to tweak it.</p>
  15345. <h2 id="available-statistics"><a class="header" href="#available-statistics">Available Statistics</a></h2>
  15346. <p>The following statistics are sent to the configured reporting endpoint:</p>
  15347. <table><thead><tr><th>Statistic Name</th><th>Type</th><th>Description</th></tr></thead><tbody>
  15348. <tr><td><code>homeserver</code></td><td>string</td><td>The homeserver's server name.</td></tr>
  15349. <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>
  15350. <tr><td><code>cpu_average</code></td><td>int</td><td>CPU time in % of a single core (not % of all cores).</td></tr>
  15351. <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>
  15352. <tr><td><code>timestamp</code></td><td>int</td><td>The current time, represented as the number of seconds since the epoch.</td></tr>
  15353. <tr><td><code>uptime_seconds</code></td><td>int</td><td>The number of seconds since the homeserver was last started.</td></tr>
  15354. <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>
  15355. <tr><td><code>total_users</code></td><td>int</td><td>The number of registered users on the homeserver.</td></tr>
  15356. <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>
  15357. <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>
  15358. <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>
  15359. <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>
  15360. <tr><td><code>total_room_count</code></td><td>int</td><td>The total number of rooms present on the homeserver.</td></tr>
  15361. <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>
  15362. <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>
  15363. <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>
  15364. <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>
  15365. <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>
  15366. <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>
  15367. <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>
  15368. <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>
  15369. <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>
  15370. <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>
  15371. <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>
  15372. <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>
  15373. <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>
  15374. <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>
  15375. <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>
  15376. <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>
  15377. <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>
  15378. <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>
  15379. </tbody></table>
  15380. <div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
  15381. <p>Native matrix users and guests are always counted. If the
  15382. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a>
  15383. option is set to <code>true</code>, &quot;puppeted&quot; users (users that an Application Service have performed
  15384. <a href="https://spec.matrix.org/v1.3/application-service-api/#identity-assertion">an action on behalf of</a>)
  15385. will also be counted. Note that an Application Service can &quot;puppet&quot; any user in their
  15386. <a href="https://spec.matrix.org/v1.3/application-service-api/#registration">user namespace</a>,
  15387. not only users that the Application Service has created. If this happens, the Application Service
  15388. will additionally be counted as a user (irrespective of <code>track_puppeted_user_ips</code>).</p>
  15389. </div>
  15390. <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>
  15391. <p>If statistics reporting is enabled, the endpoint that Synapse sends metrics to is configured by the
  15392. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats_endpoint"><code>report_stats_endpoint</code></a> config
  15393. option. By default, statistics are sent to Matrix.org.</p>
  15394. <p>If you would like to set up your own statistics collection server and send metrics there, you may
  15395. consider using one of the following known implementations:</p>
  15396. <ul>
  15397. <li><a href="https://github.com/matrix-org/panopticon">Matrix.org's Panopticon</a></li>
  15398. <li><a href="https://gitlab.com/famedly/infra/services/barad-dur">Famedly's Barad-dûr</a></li>
  15399. </ul>
  15400. <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>
  15401. <p>Synapse can be configured to record the number of monthly active users (also referred to as MAU) on a given homeserver.
  15402. For clarity's sake, MAU only tracks local users.</p>
  15403. <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>
  15404. are calculated differently. The <code>monthly_active_users</code> from the usage stats does not take into account any
  15405. of the rules below, and counts any users who have made a request to the homeserver in the last 30 days.</p>
  15406. <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>
  15407. <h2 id="calculating-active-users"><a class="header" href="#calculating-active-users">Calculating active users</a></h2>
  15408. <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
  15409. calculating the MAU figure, any users with a recorded action in the last 30 days are considered part of the cohort. Days are measured
  15410. as a rolling window from the current system time to 30 days ago.</p>
  15411. <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>
  15412. <p>A user is <strong>never</strong> considered active if they are either:</p>
  15413. <ul>
  15414. <li>Part of the trial day cohort (described below)</li>
  15415. <li>Owned by an application service.
  15416. <ul>
  15417. <li>Note: This <strong>only</strong> covers users that are part of an application service <code>namespaces.users</code> registration. The namespace
  15418. must also be marked as <code>exclusive</code>.</li>
  15419. </ul>
  15420. </li>
  15421. </ul>
  15422. <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>
  15423. they register with a 3pid that is included in the config field <code>mau_limits_reserved_threepids</code>.</p>
  15424. <p>The Prometheus metric for MAU is refreshed every 5 minutes.</p>
  15425. <p>Once an hour, Synapse checks to see if any users are inactive (with only activity timestamps later than 30 days). These users
  15426. are removed from the active users cohort. If they then become active, they are immediately restored to the cohort.</p>
  15427. <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
  15428. perform actions they will eventually be removed from the cohort.</p>
  15429. <h3 id="trial-days"><a class="header" href="#trial-days">Trial days</a></h3>
  15430. <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
  15431. trial period if their registration timestamp (also known as the <code>creation_ts</code>) is less than <code>mau_trial_days</code> old.</p>
  15432. <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>
  15433. <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.
  15434. 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>
  15435. <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>
  15436. <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
  15437. homeserver will begin to block some actions.</p>
  15438. <p>Individual users matching <strong>any</strong> of the below criteria never have their actions blocked:</p>
  15439. <ul>
  15440. <li>Considered part of the cohort of MAU users.</li>
  15441. <li>Considered part of the trial period.</li>
  15442. <li>Registered as a <code>support</code> user.</li>
  15443. <li>Application service users if <code>track_appservice_user_ips</code> is NOT set.</li>
  15444. </ul>
  15445. <p>Please not that server admins are <strong>not</strong> exempt from blocking.</p>
  15446. <p>The following actions are blocked when the MAU limit is exceeded:</p>
  15447. <ul>
  15448. <li>Logging in</li>
  15449. <li>Sending events</li>
  15450. <li>Creating rooms</li>
  15451. <li>Syncing</li>
  15452. </ul>
  15453. <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>
  15454. config value.</p>
  15455. <p>When a request is blocked, the response will have the <code>errcode</code> <code>M_RESOURCE_LIMIT_EXCEEDED</code>.</p>
  15456. <h2 id="metrics-1"><a class="header" href="#metrics-1">Metrics</a></h2>
  15457. <p>Synapse records several different prometheus metrics for MAU.</p>
  15458. <p><code>synapse_admin_mau_current</code> records the current MAU figure for native (non-application-service) users.</p>
  15459. <p><code>synapse_admin_mau_max</code> records the maximum MAU as dictated by the <code>max_mau_value</code> config value.</p>
  15460. <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
  15461. to filter by a specific service ID. This <em>also</em> includes non-application-service users under <code>app_service=native</code> .</p>
  15462. <p><code>synapse_admin_mau_registered_reserved_users</code> records the number of users specified in <code>mau_limits_reserved_threepids</code> which have
  15463. registered accounts on the homeserver.</p>
  15464. <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>
  15465. <p>It is possible to monitor much of the internal state of Synapse using <a href="https://prometheus.io">Prometheus</a>
  15466. metrics and <a href="https://grafana.com/">Grafana</a>.
  15467. A guide for configuring Synapse to provide metrics is available <a href="usage/administration/../../metrics-howto.html">here</a>
  15468. and information on setting up Grafana is <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana">here</a>.
  15469. In this setup, Prometheus will periodically scrape the information Synapse provides and
  15470. store a record of it over time. Grafana is then used as an interface to query and
  15471. present this information through a series of pretty graphs.</p>
  15472. <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>
  15473. <h2 id="message-event-send-time"><a class="header" href="#message-event-send-time">Message Event Send Time</a></h2>
  15474. <p><img src="https://user-images.githubusercontent.com/1342360/82239409-a1c8e900-9930-11ea-8081-e4614e0c63f4.png" alt="image" /></p>
  15475. <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>
  15476. <h2 id="transaction-count-and-transaction-duration"><a class="header" href="#transaction-count-and-transaction-duration">Transaction Count and Transaction Duration</a></h2>
  15477. <p><img src="https://user-images.githubusercontent.com/1342360/82239985-8d392080-9931-11ea-80d0-843ab2f22e1e.png" alt="image" /></p>
  15478. <p><img src="https://user-images.githubusercontent.com/1342360/82240050-ab068580-9931-11ea-98f1-f94671cbac9a.png" alt="image" /></p>
  15479. <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>
  15480. <p><img src="https://user-images.githubusercontent.com/1342360/82240192-e86b1300-9931-11ea-9aac-3e2c9bfa6fdc.png" alt="image" /></p>
  15481. <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>
  15482. <p><img src="https://user-images.githubusercontent.com/1342360/82240467-62030100-9932-11ea-8db9-917f2d977fe1.png" alt="image" /></p>
  15483. <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>
  15484. <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>
  15485. <h2 id="federation-2"><a class="header" href="#federation-2">Federation</a></h2>
  15486. <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>
  15487. <ul>
  15488. <li>PDU (Persistent Data Unit) - room events: messages, state events (join/leave), etc. These are permanently stored in the database.</li>
  15489. <li>EDU (Ephemeral Data Unit) - other data, which need not be stored permanently, such as read receipts, typing notifications.</li>
  15490. </ul>
  15491. <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>
  15492. <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>
  15493. <h2 id="caches"><a class="header" href="#caches">Caches</a></h2>
  15494. <p><img src="https://user-images.githubusercontent.com/1342360/82240572-8b239180-9932-11ea-96ff-6b5f0e57ebe5.png" alt="image" /></p>
  15495. <p><img src="https://user-images.githubusercontent.com/1342360/82240666-b8703f80-9932-11ea-86af-9f663988d8da.png" alt="image" /></p>
  15496. <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>
  15497. <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>
  15498. <p><img src="https://user-images.githubusercontent.com/1342360/82240766-de95df80-9932-11ea-8c15-5acfc57c48da.png" alt="image" /></p>
  15499. <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>
  15500. <h2 id="forward-extremities"><a class="header" href="#forward-extremities">Forward Extremities</a></h2>
  15501. <p><img src="https://user-images.githubusercontent.com/1342360/82241440-13566680-9934-11ea-8b88-ba468db937ed.png" alt="image" /></p>
  15502. <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>
  15503. <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>
  15504. <h2 id="garbage-collection"><a class="header" href="#garbage-collection">Garbage Collection</a></h2>
  15505. <p><img src="https://user-images.githubusercontent.com/1342360/82241911-da6ac180-9934-11ea-9a0d-a311fe22acd0.png" alt="image" /></p>
  15506. <p>Large spikes in garbage collection times (bigger than shown here, I'm talking in the
  15507. multiple seconds range), can cause lots of problems in Synapse performance. It's more an
  15508. indicator of problems, and a symptom of other problems though, so check other graphs for what might be causing it.</p>
  15509. <h2 id="final-thoughts"><a class="header" href="#final-thoughts">Final Thoughts</a></h2>
  15510. <p>If you're still having performance problems with your Synapse instance and you've
  15511. tried everything you can, it may just be a lack of system resources. Consider adding
  15512. more CPU and RAM, and make use of <a href="usage/administration/../../workers.html">worker mode</a>
  15513. to make use of multiple CPU cores / multiple machines for your homeserver.</p>
  15514. <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>
  15515. <h2 id="size-of-full-matrix-db"><a class="header" href="#size-of-full-matrix-db">Size of full matrix db</a></h2>
  15516. <pre><code class="language-sql">SELECT pg_size_pretty( pg_database_size( 'matrix' ) );
  15517. </code></pre>
  15518. <h3 id="result-example"><a class="header" href="#result-example">Result example:</a></h3>
  15519. <pre><code>pg_size_pretty
  15520. ----------------
  15521. 6420 MB
  15522. (1 row)
  15523. </code></pre>
  15524. <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>
  15525. <pre><code class="language-sql">SELECT relname, n_live_tup AS &quot;rows&quot;
  15526. FROM pg_stat_user_tables
  15527. ORDER BY n_live_tup DESC
  15528. LIMIT 20;
  15529. </code></pre>
  15530. <p>This query is quick, but may be very approximate, for exact number of rows use:</p>
  15531. <pre><code class="language-sql">SELECT COUNT(*) FROM &lt;table_name&gt;;
  15532. </code></pre>
  15533. <h3 id="result-example-1"><a class="header" href="#result-example-1">Result example:</a></h3>
  15534. <pre><code>state_groups_state - 161687170
  15535. event_auth - 8584785
  15536. event_edges - 6995633
  15537. event_json - 6585916
  15538. event_reference_hashes - 6580990
  15539. events - 6578879
  15540. received_transactions - 5713989
  15541. event_to_state_groups - 4873377
  15542. stream_ordering_to_exterm - 4136285
  15543. current_state_delta_stream - 3770972
  15544. event_search - 3670521
  15545. state_events - 2845082
  15546. room_memberships - 2785854
  15547. cache_invalidation_stream - 2448218
  15548. state_groups - 1255467
  15549. state_group_edges - 1229849
  15550. current_state_events - 1222905
  15551. users_in_public_rooms - 364059
  15552. device_lists_stream - 326903
  15553. user_directory_search - 316433
  15554. </code></pre>
  15555. <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>
  15556. <pre><code class="language-sql">SELECT nspname || '.' || relname AS &quot;relation&quot;,
  15557. pg_size_pretty(pg_total_relation_size(c.oid)) AS &quot;total_size&quot;
  15558. FROM pg_class c
  15559. LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
  15560. WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  15561. AND c.relkind &lt;&gt; 'i'
  15562. AND nspname !~ '^pg_toast'
  15563. ORDER BY pg_total_relation_size(c.oid) DESC
  15564. LIMIT 20;
  15565. </code></pre>
  15566. <h3 id="result-example-2"><a class="header" href="#result-example-2">Result example:</a></h3>
  15567. <pre><code>public.state_groups_state - 27 GB
  15568. public.event_json - 9855 MB
  15569. public.events - 3675 MB
  15570. public.event_edges - 3404 MB
  15571. public.received_transactions - 2745 MB
  15572. public.event_reference_hashes - 1864 MB
  15573. public.event_auth - 1775 MB
  15574. public.stream_ordering_to_exterm - 1663 MB
  15575. public.event_search - 1370 MB
  15576. public.room_memberships - 1050 MB
  15577. public.event_to_state_groups - 948 MB
  15578. public.current_state_delta_stream - 711 MB
  15579. public.state_events - 611 MB
  15580. public.presence_stream - 530 MB
  15581. public.current_state_events - 525 MB
  15582. public.cache_invalidation_stream - 466 MB
  15583. public.receipts_linearized - 279 MB
  15584. public.state_groups - 160 MB
  15585. public.device_lists_remote_cache - 124 MB
  15586. public.state_group_edges - 122 MB
  15587. </code></pre>
  15588. <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>
  15589. <p>You get the same information when you use the
  15590. <a href="usage/administration/../../admin_api/rooms.html#list-room-api">admin API</a>
  15591. and set parameter <code>order_by=state_events</code>.</p>
  15592. <pre><code class="language-sql">SELECT r.name, s.room_id, s.current_state_events
  15593. FROM room_stats_current s
  15594. LEFT JOIN room_stats_state r USING (room_id)
  15595. ORDER BY current_state_events DESC
  15596. LIMIT 20;
  15597. </code></pre>
  15598. <p>and by state_group_events count:</p>
  15599. <pre><code class="language-sql">SELECT rss.name, s.room_id, COUNT(s.room_id)
  15600. FROM state_groups_state s
  15601. LEFT JOIN room_stats_state rss USING (room_id)
  15602. GROUP BY s.room_id, rss.name
  15603. ORDER BY COUNT(s.room_id) DESC
  15604. LIMIT 20;
  15605. </code></pre>
  15606. <p>plus same, but with join removed for performance reasons:</p>
  15607. <pre><code class="language-sql">SELECT s.room_id, COUNT(s.room_id)
  15608. FROM state_groups_state s
  15609. GROUP BY s.room_id
  15610. ORDER BY COUNT(s.room_id) DESC
  15611. LIMIT 20;
  15612. </code></pre>
  15613. <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>
  15614. <pre><code class="language-sql">SELECT e.room_id, r.name, COUNT(e.event_id) cnt
  15615. FROM events e
  15616. LEFT JOIN room_stats_state r USING (room_id)
  15617. WHERE e.origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 day') * 1000
  15618. GROUP BY e.room_id, r.name
  15619. ORDER BY cnt DESC
  15620. LIMIT 20;
  15621. </code></pre>
  15622. <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>
  15623. <p>Caution. This query does not use any indexes, can be slow and create load on the database.</p>
  15624. <pre><code class="language-sql">SELECT COUNT(*), sender
  15625. FROM events
  15626. WHERE (type = 'm.room.encrypted' OR type = 'm.room.message')
  15627. AND origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 month') * 1000
  15628. GROUP BY sender
  15629. ORDER BY COUNT(*) DESC
  15630. LIMIT 20;
  15631. </code></pre>
  15632. <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>
  15633. <pre><code class="language-sql">SELECT e.room_id, r.name, e.event_id, e.type, e.content, j.json
  15634. FROM events e
  15635. LEFT JOIN event_json j USING (room_id)
  15636. LEFT JOIN room_stats_state r USING (room_id)
  15637. WHERE sender = '@LOGIN:example.com'
  15638. AND e.type = 'm.room.message'
  15639. ORDER BY stream_ordering DESC
  15640. LIMIT 100;
  15641. </code></pre>
  15642. <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>
  15643. <p><strong>Sort and order with bash</strong></p>
  15644. <pre><code class="language-bash">echo &quot;SELECT event_json.room_id, room_stats_state.name FROM event_json, room_stats_state \
  15645. WHERE room_stats_state.room_id = event_json.room_id&quot; | psql -d synapse -h localhost -U synapse_user -t \
  15646. | sort | uniq -c | sort -n
  15647. </code></pre>
  15648. <p>Documentation for <code>psql</code> command line parameters: https://www.postgresql.org/docs/current/app-psql.html</p>
  15649. <p><strong>Sort and order with SQL</strong></p>
  15650. <pre><code class="language-sql">SELECT COUNT(*), event_json.room_id, room_stats_state.name
  15651. FROM event_json, room_stats_state
  15652. WHERE room_stats_state.room_id = event_json.room_id
  15653. GROUP BY event_json.room_id, room_stats_state.name
  15654. ORDER BY COUNT(*) DESC
  15655. LIMIT 50;
  15656. </code></pre>
  15657. <h3 id="result-example-3"><a class="header" href="#result-example-3">Result example:</a></h3>
  15658. <pre><code> 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix
  15659. 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix (TWIM)
  15660. 17799 !iDIOImbmXxwNngznsa:matrix.org | Linux in Russian
  15661. 18739 !GnEEPYXUhoaHbkFBNX:matrix.org | Riot Android
  15662. 23373 !QtykxKocfZaZOUrTwp:matrix.org | Matrix HQ
  15663. 39504 !gTQfWzbYncrtNrvEkB:matrix.org | ru.[matrix]
  15664. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot
  15665. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot Web/Desktop
  15666. </code></pre>
  15667. <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>
  15668. <p>You get the same information when you use the
  15669. <a href="usage/administration/../../admin_api/rooms.html#room-details-api">admin API</a>.</p>
  15670. <pre><code class="language-sql">SELECT rss.room_id, rss.name, rss.canonical_alias, rss.topic, rss.encryption,
  15671. rsc.joined_members, rsc.local_users_in_room, rss.join_rules
  15672. FROM room_stats_state rss
  15673. LEFT JOIN room_stats_current rsc USING (room_id)
  15674. WHERE room_id IN (
  15675. '!OGEhHVWSdvArJzumhm:matrix.org',
  15676. '!YTvKGNlinIzlkMTVRl:matrix.org'
  15677. );
  15678. </code></pre>
  15679. <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>
  15680. <pre><code class="language-sql">SELECT user_id, device_id, user_agent, TO_TIMESTAMP(last_seen / 1000) AS &quot;last_seen&quot;
  15681. FROM devices
  15682. WHERE last_seen &lt; DATE_PART('epoch', NOW() - INTERVAL '3 month') * 1000;
  15683. </code></pre>
  15684. <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>
  15685. <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>
  15686. <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>
  15687. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  15688. <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>
  15689. <p>This API deletes the <em>local</em> media from the disk of your own server.</p>
  15690. <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>
  15691. <p>The purge history API allows server admins to purge historic events from their database, reclaiming disk space.</p>
  15692. <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>
  15693. <p>Tool for compressing (deduplicating) <code>state_groups_state</code> table.</p>
  15694. <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>
  15695. <p>Some easy SQL that reports useful stats about your Synapse database.</p>
  15696. <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>
  15697. <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>
  15698. <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>
  15699. <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>
  15700. <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>
  15701. <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>
  15702. <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>
  15703. <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>
  15704. <p>A full state group just records the event id for each piece of state in the room at that point.</p>
  15705. <h2 id="known-bugs-with-state-groups"><a class="header" href="#known-bugs-with-state-groups">Known bugs with state groups</a></h2>
  15706. <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>
  15707. <h2 id="compression-tool"><a class="header" href="#compression-tool">Compression tool</a></h2>
  15708. <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>
  15709. <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>
  15710. <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>
  15711. <p>See the following for how to decode the dense data available from the default logging configuration.</p>
  15712. <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]
  15713. -AAAAAAAAAAAAAAAAAAAAA- -BBBBBBBBBBBBBBBBBBBBBB- -C- -DD- -EEEEEE- -FFFFFFFFF- -GG- -HHHHHHHHHHHHHHHHHHHHHHH- -IIIIII- -JJJJJJJ- -KKKKKK-, -LLLLLL- -MMMMMMM- -NNNNNN- O -P- -QQ- -RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR- -SSSSSSSSSSSS- -TTTTTT-
  15714. </code></pre>
  15715. <table><thead><tr><th>Part</th><th>Explanation</th></tr></thead><tbody>
  15716. <tr><td>AAAA</td><td>Timestamp request was logged (not received)</td></tr>
  15717. <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>
  15718. <tr><td>CCCC</td><td>Line number in code</td></tr>
  15719. <tr><td>DDDD</td><td>Log Level</td></tr>
  15720. <tr><td>EEEE</td><td>Request Identifier (This identifier is shared by related log lines)</td></tr>
  15721. <tr><td>FFFF</td><td>Source IP (Or X-Forwarded-For if enabled)</td></tr>
  15722. <tr><td>GGGG</td><td>Server Port</td></tr>
  15723. <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>
  15724. <tr><td>IIII</td><td>Total Time to process the request</td></tr>
  15725. <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>
  15726. <tr><td>KKKK</td><td>Userland CPU time</td></tr>
  15727. <tr><td>LLLL</td><td>System CPU time</td></tr>
  15728. <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>
  15729. <tr><td>NNNN</td><td>Total time waiting for response to DB queries across all parallel DB work from this request</td></tr>
  15730. <tr><td>OOOO</td><td>Count of DB transactions performed</td></tr>
  15731. <tr><td>PPPP</td><td>Response body size</td></tr>
  15732. <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>
  15733. <tr><td>RRRR</td><td>Request</td></tr>
  15734. <tr><td>SSSS</td><td>User-agent</td></tr>
  15735. <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>
  15736. </tbody></table>
  15737. <p>MMMM / NNNN can be greater than IIII if there are multiple slow database queries
  15738. running in parallel.</p>
  15739. <p>Some actions can result in multiple identical http requests, which will return
  15740. the same data, but only the first request will report time/transactions in
  15741. <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
  15742. response and will simultaneously return with the first request, but with very
  15743. small processing times.</p>
  15744. <div style="break-before: page; page-break-before: always;"></div><h2 id="admin-faq"><a class="header" href="#admin-faq">Admin FAQ</a></h2>
  15745. <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>
  15746. <p>If your server already has an admin account you should use the
  15747. <a href="usage/administration/../../admin_api/user_admin_api.html#change-whether-a-user-is-a-server-administrator-or-not">User Admin API</a>
  15748. to promote other accounts to become admins.</p>
  15749. <p>If you don't have any admin accounts yet you won't be able to use the admin API,
  15750. so you'll have to edit the database manually. Manually editing the database is
  15751. generally not recommended so once you have an admin account: use the admin APIs
  15752. to make further changes.</p>
  15753. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  15754. </code></pre>
  15755. <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>
  15756. <p>Run this sql query on your db:</p>
  15757. <pre><code class="language-sql">SELECT * FROM destinations;
  15758. </code></pre>
  15759. <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>
  15760. <p>Run this sql query on your db:</p>
  15761. <pre><code class="language-sql">SELECT DISTINCT split_part(state_key, ':', 2)
  15762. FROM current_state_events
  15763. WHERE room_id = '!cURbafjkfsMDVwdRDQ:matrix.org' AND membership = 'join';
  15764. </code></pre>
  15765. <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>
  15766. <pre><code class="language-sql">SELECT NAME from users;
  15767. </code></pre>
  15768. <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>
  15769. <p>Synapse includes a Python command to export data for a specific user. It takes the homeserver
  15770. configuration file and the full Matrix ID of the user to export:</p>
  15771. <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;
  15772. </code></pre>
  15773. <p>If you uses <a href="usage/administration/../../development/dependencies.html#managing-dependencies-with-poetry">Poetry</a>
  15774. to run Synapse:</p>
  15775. <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;
  15776. </code></pre>
  15777. <p>The directory to store the export data in can be customised with the
  15778. <code>--output-directory</code> parameter; ensure that the provided directory is
  15779. empty. If this parameter is not provided, Synapse defaults to creating
  15780. a temporary directory (which starts with &quot;synapse-exfiltrate&quot;) in <code>/tmp</code>,
  15781. <code>/var/tmp</code>, or <code>/usr/tmp</code>, in that order.</p>
  15782. <p>The exported data has the following layout:</p>
  15783. <pre><code>output-directory
  15784. ├───rooms
  15785. │ └───&lt;room_id&gt;
  15786. │ ├───events
  15787. │ ├───state
  15788. │ ├───invite_state
  15789. │ └───knock_state
  15790. ├───user_data
  15791. │ ├───account_data
  15792. │ │ ├───global
  15793. │ │ └───&lt;room_id&gt;
  15794. │ ├───connections
  15795. │ ├───devices
  15796. │ └───profile
  15797. └───media_ids
  15798. └───&lt;media_id&gt;
  15799. </code></pre>
  15800. <p>The <code>media_ids</code> folder contains only the metadata of the media uploaded by the user.
  15801. It does not contain the media itself.
  15802. Furthermore, only the <code>media_ids</code> that Synapse manages itself are exported.
  15803. If another media repository (e.g. <a href="https://github.com/turt2live/matrix-media-repo">matrix-media-repo</a>)
  15804. is used, the data must be exported separately.</p>
  15805. <p>With the <code>media_ids</code> the media files can be downloaded.
  15806. Media that have been sent in encrypted rooms are only retrieved in encrypted form.
  15807. The following script can help with download the media files:</p>
  15808. <pre><code class="language-bash">#!/usr/bin/env bash
  15809. # Parameters
  15810. #
  15811. # source_directory: Directory which contains the export with the media_ids.
  15812. # target_directory: Directory into which all files are to be downloaded.
  15813. # repository_url: Address of the media repository resp. media worker.
  15814. # serverName: Name of the server (`server_name` from homeserver.yaml).
  15815. #
  15816. # Example:
  15817. # ./download_media.sh /tmp/export_data/media_ids/ /tmp/export_data/media_files/ http://localhost:8008 matrix.example.com
  15818. source_directory=$1
  15819. target_directory=$2
  15820. repository_url=$3
  15821. serverName=$4
  15822. mkdir -p $target_directory
  15823. for file in $source_directory/*; do
  15824. filename=$(basename ${file})
  15825. url=$repository_url/_matrix/media/v3/download/$serverName/$filename
  15826. echo &quot;Downloading $filename - $url&quot;
  15827. if ! wget -o /dev/null -P $target_directory $url; then
  15828. echo &quot;Could not download $filename&quot;
  15829. fi
  15830. done
  15831. </code></pre>
  15832. <h2 id="manually-resetting-passwords"><a class="header" href="#manually-resetting-passwords">Manually resetting passwords</a></h2>
  15833. <p>Users can reset their password through their client. Alternatively, a server admin
  15834. can reset a user's password using the <a href="usage/administration/../../admin_api/user_admin_api.html#reset-password">admin API</a>.</p>
  15835. <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>
  15836. <p>Deleting your database is unlikely to make anything better.</p>
  15837. <p>It's easy to make the mistake of thinking that you can start again from a clean
  15838. slate by dropping your database, but things don't work like that in a federated
  15839. network: lots of other servers have information about your server.</p>
  15840. <p>For example: other servers might think that you are in a room, your server will
  15841. think that you are not, and you'll probably be unable to interact with that room
  15842. in a sensible way ever again.</p>
  15843. <p>In general, there are better solutions to any problem than dropping the database.
  15844. Come and seek help in https://matrix.to/#/#synapse:matrix.org.</p>
  15845. <p>There are two exceptions when it might be sensible to delete your database and start again:</p>
  15846. <ul>
  15847. <li>You have <em>never</em> joined any rooms which are federated with other servers. For
  15848. instance, a local deployment which the outside world can't talk to.</li>
  15849. <li>You are changing the <code>server_name</code> in the homeserver configuration. In effect
  15850. this makes your server a completely new one from the point of view of the network,
  15851. so in this case it makes sense to start with a clean database.
  15852. (In both cases you probably also want to clear out the media_store.)</li>
  15853. </ul>
  15854. <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>
  15855. <p>Using the following curl command:</p>
  15856. <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;
  15857. </code></pre>
  15858. <p><code>&lt;access-token&gt;</code> - can be obtained in riot by looking in the riot settings, down the bottom is:
  15859. Access Token:&lt;click to reveal&gt;</p>
  15860. <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>
  15861. <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>
  15862. <p>Synapse tags each log line according to the HTTP request it is processing. When
  15863. it finishes processing each request, it logs a line containing the words
  15864. <code>Processed request: </code>. For example:</p>
  15865. <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;
  15866. </code></pre>
  15867. <p>Here we can see that the request has been tagged with <code>GET-37</code>. (The tag depends
  15868. on the method of the HTTP request, so might start with <code>GET-</code>, <code>PUT-</code>, <code>POST-</code>,
  15869. <code>OPTIONS-</code> or <code>DELETE-</code>.) So to find all lines corresponding to this request, we can do:</p>
  15870. <pre><code class="language-console">grep 'GET-37' homeserver.log
  15871. </code></pre>
  15872. <p>If you want to paste that output into a github issue or matrix room, please
  15873. remember to surround it with triple-backticks (```) to make it legible
  15874. (see <a href="https://help.github.com/en/articles/basic-writing-and-formatting-syntax#quoting-code">quoting code</a>).</p>
  15875. <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>
  15876. <p>See <a href="usage/administration/request_log.html">Request log format</a>.</p>
  15877. <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>
  15878. <pre><code class="language-sql">SELECT s.canonical_alias, g.room_id, count(*) AS num_rows
  15879. FROM
  15880. state_groups_state AS g,
  15881. room_stats_state AS s
  15882. WHERE g.room_id = s.room_id
  15883. GROUP BY s.canonical_alias, g.room_id
  15884. ORDER BY num_rows desc
  15885. LIMIT 10;
  15886. </code></pre>
  15887. <p>You can also use the <a href="usage/administration/../../admin_api/rooms.html#list-room-api">List Room API</a>
  15888. and <code>order_by</code> <code>state_events</code>.</p>
  15889. <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>
  15890. <p>The typical failure mode here is that you send an invitation to someone
  15891. to join a room or direct chat, but when they go to accept it, they get an
  15892. error (typically along the lines of &quot;Invalid signature&quot;). They might see
  15893. something like the following in their logs:</p>
  15894. <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;
  15895. </code></pre>
  15896. <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>
  15897. <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>
  15898. <p>First, ensure you are running the latest version of Synapse, using Python 3
  15899. with a <a href="usage/administration/../../postgres.html">PostgreSQL database</a>.</p>
  15900. <p>Synapse's architecture is quite RAM hungry currently - we deliberately
  15901. cache a lot of recent room data and metadata in RAM in order to speed up
  15902. common requests. We'll improve this in the future, but for now the easiest
  15903. way to either reduce the RAM usage (at the risk of slowing things down)
  15904. is to set the almost-undocumented <code>SYNAPSE_CACHE_FACTOR</code> environment
  15905. variable. The default is 0.5, which can be decreased to reduce RAM usage
  15906. in memory constrained environments, or increased if performance starts to
  15907. degrade.</p>
  15908. <p>However, degraded performance due to a low cache factor, common on
  15909. machines with slow disks, often leads to explosions in memory use due
  15910. backlogged requests. In this case, reducing the cache factor will make
  15911. things worse. Instead, try increasing it drastically. 2.0 is a good
  15912. starting value.</p>
  15913. <p>Using <a href="https://jemalloc.net">libjemalloc</a> can also yield a significant
  15914. improvement in overall memory use, and especially in terms of giving back
  15915. RAM to the OS. To use it, the library must simply be put in the
  15916. LD_PRELOAD environment variable when launching Synapse. On Debian, this
  15917. can be done by installing the <code>libjemalloc1</code> package and adding this
  15918. line to <code>/etc/default/matrix-synapse</code>:</p>
  15919. <pre><code>LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.1
  15920. </code></pre>
  15921. <p>This made a significant difference on Python 2.7 - it's unclear how
  15922. much of an improvement it provides on Python 3.x.</p>
  15923. <p>If you're encountering high CPU use by the Synapse process itself, you
  15924. may be affected by a bug with presence tracking that leads to a
  15925. massive excess of outgoing federation requests (see <a href="https://github.com/matrix-org/synapse/issues/3971">discussion</a>). If metrics
  15926. indicate that your server is also issuing far more outgoing federation
  15927. requests than can be accounted for by your users' activity, this is a
  15928. likely cause. The misbehavior can be worked around by disabling presence
  15929. in the Synapse config file: <a href="usage/administration/../configuration/config_documentation.html#presence">see here</a>.</p>
  15930. <h2 id="running-out-of-file-handles"><a class="header" href="#running-out-of-file-handles">Running out of File Handles</a></h2>
  15931. <p>If Synapse runs out of file handles, it typically fails badly - live-locking
  15932. at 100% CPU, and/or failing to accept new TCP connections (blocking the
  15933. connecting client). Matrix currently can legitimately use a lot of file handles,
  15934. thanks to busy rooms like <code>#matrix:matrix.org</code> containing hundreds of participating
  15935. servers. The first time a server talks in a room it will try to connect
  15936. simultaneously to all participating servers, which could exhaust the available
  15937. file descriptors between DNS queries &amp; HTTPS sockets, especially if DNS is slow
  15938. to respond. (We need to improve the routing algorithm used to be better than
  15939. full mesh, but as of March 2019 this hasn't happened yet).</p>
  15940. <p>If you hit this failure mode, we recommend increasing the maximum number of
  15941. open file handles to be at least 4096 (assuming a default of 1024 or 256).
  15942. This is typically done by editing <code>/etc/security/limits.conf</code></p>
  15943. <p>Separately, Synapse may leak file handles if inbound HTTP requests get stuck
  15944. during processing - e.g. blocked behind a lock or talking to a remote server etc.
  15945. This is best diagnosed by matching up the 'Received request' and 'Processed request'
  15946. log lines and looking for any 'Processed request' lines which take more than
  15947. 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
  15948. you see this failure mode so we can help debug it, however.</p>
  15949. <div style="break-before: page; page-break-before: always;"></div><h1 id="contributing"><a class="header" href="#contributing">Contributing</a></h1>
  15950. <p>This document aims to get you started with contributing to Synapse!</p>
  15951. <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>
  15952. <p>Everyone is welcome to contribute code to <a href="https://github.com/matrix-org">matrix.org
  15953. projects</a>, provided that they are willing to
  15954. license their contributions under the same license as the project itself. We
  15955. follow a simple 'inbound=outbound' model for contributions: the act of
  15956. submitting an 'inbound' contribution means that the contributor agrees to
  15957. license the code under the same terms as the project's overall 'outbound'
  15958. license - in our case, this is almost always Apache Software License v2 (see
  15959. <a href="https://github.com/matrix-org/synapse/blob/develop/LICENSE">LICENSE</a>).</p>
  15960. <h1 id="2-what-do-i-need"><a class="header" href="#2-what-do-i-need">2. What do I need?</a></h1>
  15961. <p>If you are running Windows, the Windows Subsystem for Linux (WSL) is strongly
  15962. recommended for development. More information about WSL can be found at
  15963. <a href="https://docs.microsoft.com/en-us/windows/wsl/install">https://docs.microsoft.com/en-us/windows/wsl/install</a>. Running Synapse natively
  15964. on Windows is not officially supported.</p>
  15965. <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>
  15966. <p>A recent version of the Rust compiler is needed to build the native modules. The
  15967. easiest way of installing the latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
  15968. <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>
  15969. <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>
  15970. <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>
  15971. <p>For some tests, you will need <a href="https://docs.docker.com/get-docker/">a recent version of Docker</a>.</p>
  15972. <h1 id="3-get-the-source"><a class="header" href="#3-get-the-source">3. Get the source.</a></h1>
  15973. <p>The preferred and easiest way to contribute changes is to fork the relevant
  15974. 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
  15975. changes into our repo.</p>
  15976. <p>Please base your changes on the <code>develop</code> branch.</p>
  15977. <pre><code class="language-sh">git clone git@github.com:YOUR_GITHUB_USER_NAME/synapse.git
  15978. git checkout develop
  15979. </code></pre>
  15980. <p>If you need help getting started with git, this is beyond the scope of the document, but you
  15981. can find many good git tutorials on the web.</p>
  15982. <h1 id="4-install-the-dependencies"><a class="header" href="#4-install-the-dependencies">4. Install the dependencies</a></h1>
  15983. <p>Before installing the Python dependencies, make sure you have installed a recent version
  15984. of Rust (see the &quot;What do I need?&quot; section above). The easiest way of installing the
  15985. latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
  15986. <p>Synapse uses the <a href="https://python-poetry.org/">poetry</a> project to manage its dependencies
  15987. and development environment. Once you have installed Python 3 and added the
  15988. source, you should install <code>poetry</code>.
  15989. Of their installation methods, we recommend
  15990. <a href="https://python-poetry.org/docs/#installing-with-pipx">installing <code>poetry</code> using <code>pipx</code></a>,</p>
  15991. <pre><code class="language-shell">pip install --user pipx
  15992. pipx install poetry
  15993. </code></pre>
  15994. <p>but see poetry's <a href="https://python-poetry.org/docs/#installation">installation instructions</a>
  15995. for other installation methods.</p>
  15996. <p>Developing Synapse requires Poetry version 1.3.2 or later.</p>
  15997. <p>Next, open a terminal and install dependencies as follows:</p>
  15998. <pre><code class="language-sh">cd path/where/you/have/cloned/the/repository
  15999. poetry install --extras all
  16000. </code></pre>
  16001. <p>This will install the runtime and developer dependencies for the project. Be sure to check
  16002. that the <code>poetry install</code> step completed cleanly.</p>
  16003. <h2 id="running-synapse-via-poetry"><a class="header" href="#running-synapse-via-poetry">Running Synapse via poetry</a></h2>
  16004. <p>To start a local instance of Synapse in the locked poetry environment, create a config file:</p>
  16005. <pre><code class="language-sh">cp docs/sample_config.yaml homeserver.yaml
  16006. cp docs/sample_log_config.yaml log_config.yaml
  16007. </code></pre>
  16008. <p>Now edit <code>homeserver.yaml</code>, things you might want to change include:</p>
  16009. <ul>
  16010. <li>Set a <code>server_name</code></li>
  16011. <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>
  16012. <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>
  16013. <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>
  16014. </ul>
  16015. <p>And then run Synapse with the following command:</p>
  16016. <pre><code class="language-sh">poetry run python -m synapse.app.homeserver -c homeserver.yaml
  16017. </code></pre>
  16018. <p>If you get an error like the following:</p>
  16019. <pre><code>importlib.metadata.PackageNotFoundError: matrix-synapse
  16020. </code></pre>
  16021. <p>this probably indicates that the <code>poetry install</code> step did not complete cleanly - go back and
  16022. resolve any issues and re-run until successful.</p>
  16023. <h1 id="5-get-in-touch"><a class="header" href="#5-get-in-touch">5. Get in touch.</a></h1>
  16024. <p>Join our developer community on Matrix: <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>!</p>
  16025. <h1 id="6-pick-an-issue"><a class="header" href="#6-pick-an-issue">6. Pick an issue.</a></h1>
  16026. <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>
  16027. to work on.</p>
  16028. <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>
  16029. <p>There is a growing amount of documentation located in the
  16030. <a href="https://github.com/matrix-org/synapse/tree/develop/docs"><code>docs</code></a>
  16031. directory, with a rendered version <a href="https://matrix-org.github.io/synapse">available online</a>.
  16032. This documentation is intended primarily for sysadmins running their
  16033. own Synapse instance, as well as developers interacting externally with
  16034. Synapse.
  16035. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/development"><code>docs/development</code></a>
  16036. exists primarily to house documentation for
  16037. Synapse developers.
  16038. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/admin_api"><code>docs/admin_api</code></a> houses documentation
  16039. regarding Synapse's Admin API, which is used mostly by sysadmins and external
  16040. service developers.</p>
  16041. <p>Synapse's code style is documented <a href="development/../code_style.html">here</a>. Please follow
  16042. it, including the conventions for <a href="development/../code_style.html#configuration-code-and-documentation-format">configuration
  16043. options and documentation</a>.</p>
  16044. <p>We welcome improvements and additions to our documentation itself! When
  16045. writing new pages, please
  16046. <a href="https://github.com/matrix-org/synapse/tree/develop/docs#adding-to-the-documentation">build <code>docs</code> to a book</a>
  16047. to check that your contributions render correctly. The docs are written in
  16048. <a href="https://guides.github.com/features/mastering-markdown/">GitHub-Flavoured Markdown</a>.</p>
  16049. <p>Some documentation also exists in <a href="https://github.com/matrix-org/synapse/wiki">Synapse's GitHub
  16050. Wiki</a>, although this is primarily
  16051. contributed to by community authors.</p>
  16052. <p>When changes are made to any Rust code then you must call either <code>poetry install</code>
  16053. or <code>maturin develop</code> (if installed) to rebuild the Rust code. Using <a href="https://github.com/PyO3/maturin"><code>maturin</code></a>
  16054. is quicker than <code>poetry install</code>, so is recommended when making frequent
  16055. changes to the Rust code.</p>
  16056. <h1 id="8-test-test-test"><a class="header" href="#8-test-test-test">8. Test, test, test!</a></h1>
  16057. <p><a name="test-test-test" id="test-test-test"></a></p>
  16058. <p>While you're developing and before submitting a patch, you'll
  16059. want to test your code.</p>
  16060. <h2 id="run-the-linters"><a class="header" href="#run-the-linters">Run the linters.</a></h2>
  16061. <p>The linters look at your code and do two things:</p>
  16062. <ul>
  16063. <li>ensure that your code follows the coding style adopted by the project;</li>
  16064. <li>catch a number of errors in your code.</li>
  16065. </ul>
  16066. <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>
  16067. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh
  16068. </code></pre>
  16069. <p>Note that this script <em>will modify your files</em> to fix styling errors.
  16070. Make sure that you have saved all your files.</p>
  16071. <p>If you wish to restrict the linters to only the files changed since the last commit
  16072. (much faster!), you can instead run:</p>
  16073. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh -d
  16074. </code></pre>
  16075. <p>Or if you know exactly which files you wish to lint, you can instead run:</p>
  16076. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh path/to/file1.py path/to/file2.py path/to/folder
  16077. </code></pre>
  16078. <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>
  16079. <p>The unit tests run parts of Synapse, including your changes, to see if anything
  16080. was broken. They are slower than the linters but will typically catch more errors.</p>
  16081. <pre><code class="language-sh">poetry run trial tests
  16082. </code></pre>
  16083. <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>
  16084. <pre><code class="language-sh">poetry run trial -j4 tests
  16085. </code></pre>
  16086. <p>If you wish to only run <em>some</em> unit tests, you may specify
  16087. another module instead of <code>tests</code> - or a test class or a method:</p>
  16088. <pre><code class="language-sh">poetry run trial tests.rest.admin.test_room tests.handlers.test_admin.ExfiltrateData.test_invite
  16089. </code></pre>
  16090. <p>If your tests fail, you may wish to look at the logs (the default log level is <code>ERROR</code>):</p>
  16091. <pre><code class="language-sh">less _trial_temp/test.log
  16092. </code></pre>
  16093. <p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>:</p>
  16094. <pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG poetry run trial tests
  16095. </code></pre>
  16096. <p>By default, tests will use an in-memory SQLite database for test data. For additional
  16097. help with debugging, one can use an on-disk SQLite database file instead, in order to
  16098. review database state during and after running tests. This can be done by setting
  16099. the <code>SYNAPSE_TEST_PERSIST_SQLITE_DB</code> environment variable. Doing so will cause the
  16100. database state to be stored in a file named <code>test.db</code> under the trial process'
  16101. working directory. Typically, this ends up being <code>_trial_temp/test.db</code>. For example:</p>
  16102. <pre><code class="language-sh">SYNAPSE_TEST_PERSIST_SQLITE_DB=1 poetry run trial tests
  16103. </code></pre>
  16104. <p>The database file can then be inspected with:</p>
  16105. <pre><code class="language-sh">sqlite3 _trial_temp/test.db
  16106. </code></pre>
  16107. <p>Note that the database file is cleared at the beginning of each test run. Thus it
  16108. will always only contain the data generated by the <em>last run test</em>. Though generally
  16109. when debugging, one is only running a single test anyway.</p>
  16110. <h3 id="running-tests-under-postgresql"><a class="header" href="#running-tests-under-postgresql">Running tests under PostgreSQL</a></h3>
  16111. <p>Invoking <code>trial</code> as above will use an in-memory SQLite database. This is great for
  16112. quick development and testing. However, we recommend using a PostgreSQL database
  16113. in production (and indeed, we have some code paths specific to each database).
  16114. This means that we need to run our unit tests against PostgreSQL too. Our CI does
  16115. this automatically for pull requests and release candidates, but it's sometimes
  16116. useful to reproduce this locally.</p>
  16117. <h4 id="using-docker"><a class="header" href="#using-docker">Using Docker</a></h4>
  16118. <p>The easiest way to do so is to run Postgres via a docker container. In one
  16119. terminal:</p>
  16120. <pre><code class="language-shell">docker run --rm -e POSTGRES_PASSWORD=mysecretpassword -e POSTGRES_USER=postgres -e POSTGRES_DB=postgres -p 5432:5432 postgres:14
  16121. </code></pre>
  16122. <p>If you see an error like</p>
  16123. <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.
  16124. </code></pre>
  16125. <p>then something is already bound to port 5432. You're probably already running postgres locally.</p>
  16126. <p>Once you have a postgres server running, invoke <code>trial</code> in a second terminal:</p>
  16127. <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
  16128. </code></pre>
  16129. <h4 id="using-an-existing-postgres-installation"><a class="header" href="#using-an-existing-postgres-installation">Using an existing Postgres installation</a></h4>
  16130. <p>If you have postgres already installed on your system, you can run <code>trial</code> with the
  16131. following environment variables matching your configuration:</p>
  16132. <ul>
  16133. <li><code>SYNAPSE_POSTGRES</code> to anything nonempty</li>
  16134. <li><code>SYNAPSE_POSTGRES_HOST</code> (optional if it's the default: UNIX socket)</li>
  16135. <li><code>SYNAPSE_POSTGRES_PORT</code> (optional if it's the default: 5432)</li>
  16136. <li><code>SYNAPSE_POSTGRES_USER</code> (optional if using a UNIX socket)</li>
  16137. <li><code>SYNAPSE_POSTGRES_PASSWORD</code> (optional if using a UNIX socket)</li>
  16138. </ul>
  16139. <p>For example:</p>
  16140. <pre><code class="language-shell">export SYNAPSE_POSTGRES=1
  16141. export SYNAPSE_POSTGRES_HOST=localhost
  16142. export SYNAPSE_POSTGRES_USER=postgres
  16143. export SYNAPSE_POSTGRES_PASSWORD=mydevenvpassword
  16144. trial
  16145. </code></pre>
  16146. <p>You don't need to specify the host, user, port or password if your Postgres
  16147. server is set to authenticate you over the UNIX socket (i.e. if the <code>psql</code> command
  16148. works without further arguments).</p>
  16149. <p>Your Postgres account needs to be able to create databases; see the postgres
  16150. docs for <a href="https://www.postgresql.org/docs/current/sql-alterrole.html"><code>ALTER ROLE</code></a>.</p>
  16151. <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>
  16152. <p>The integration tests are a more comprehensive suite of tests. They
  16153. run a full version of Synapse, including your changes, to check if
  16154. anything was broken. They are slower than the unit tests but will
  16155. typically catch more errors.</p>
  16156. <p>The following command will let you run the integration test with the most common
  16157. configuration:</p>
  16158. <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
  16159. </code></pre>
  16160. <p>(Note that the paths must be full paths! You could also write <code>$(realpath relative/path)</code> if needed.)</p>
  16161. <p>This configuration should generally cover your needs.</p>
  16162. <ul>
  16163. <li>To run with Postgres, supply the <code>-e POSTGRES=1 -e MULTI_POSTGRES=1</code> environment flags.</li>
  16164. <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>
  16165. </ul>
  16166. <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>
  16167. <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>
  16168. <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>
  16169. <p>It's often nice to develop on Synapse and write Complement tests at the same time.
  16170. Here is how to run your local Synapse checkout against your local Complement checkout.</p>
  16171. <p>(checkout <a href="https://github.com/matrix-org/complement"><code>complement</code></a> alongside your <code>synapse</code> checkout)</p>
  16172. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh
  16173. </code></pre>
  16174. <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>
  16175. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
  16176. </code></pre>
  16177. <p>To run a specific test, you can specify the whole name structure:</p>
  16178. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages/parallel/Historical_events_resolve_in_the_correct_order
  16179. </code></pre>
  16180. <p>The above will run a monolithic (single-process) Synapse with SQLite as the database. For other configurations, try:</p>
  16181. <ul>
  16182. <li>Passing <code>POSTGRES=1</code> as an environment variable to use the Postgres database instead.</li>
  16183. <li>Passing <code>WORKERS=1</code> as an environment variable to use a workerised setup instead. This option implies the use of Postgres.
  16184. <ul>
  16185. <li>If setting <code>WORKERS=1</code>, optionally set <code>WORKER_TYPES=</code> to declare which worker
  16186. types you wish to test. A simple comma-delimited string containing the worker types
  16187. defined from the <code>WORKERS_CONFIG</code> template in
  16188. <a href="https://github.com/matrix-org/synapse/blob/develop/docker/configure_workers_and_start.py#L54">here</a>.
  16189. A safe example would be <code>WORKER_TYPES=&quot;federation_inbound, federation_sender, synchrotron&quot;</code>.
  16190. See the <a href="development/../workers.html">worker documentation</a> for additional information on workers.</li>
  16191. </ul>
  16192. </li>
  16193. <li>Passing <code>ASYNCIO_REACTOR=1</code> as an environment variable to use the Twisted asyncio reactor instead of the default one.</li>
  16194. <li>Passing <code>PODMAN=1</code> will use the <a href="https://podman.io/">podman</a> container runtime, instead of docker.</li>
  16195. <li>Passing <code>UNIX_SOCKETS=1</code> will utilise Unix socket functionality for Synapse, Redis, and Postgres(when applicable).</li>
  16196. </ul>
  16197. <p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>, e.g:</p>
  16198. <pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
  16199. </code></pre>
  16200. <h3 id="prettier-formatting-with-gotestfmt"><a class="header" href="#prettier-formatting-with-gotestfmt">Prettier formatting with <code>gotestfmt</code></a></h3>
  16201. <p>If you want to format the output of the tests the same way as it looks in CI,
  16202. install <a href="https://github.com/GoTestTools/gotestfmt">gotestfmt</a>.</p>
  16203. <p>You can then use this incantation to format the tests appropriately:</p>
  16204. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -json | gotestfmt -hide successful-tests
  16205. </code></pre>
  16206. <p>(Remove <code>-hide successful-tests</code> if you don't want to hide successful tests.)</p>
  16207. <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>
  16208. <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>
  16209. <ol>
  16210. <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>
  16211. <li>Start the Complement tests</li>
  16212. <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>
  16213. <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>
  16214. <li>Install sqlite (database driver), <code>apt-get update &amp;&amp; apt-get install -y sqlite3</code></li>
  16215. <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>
  16216. </ol>
  16217. <h1 id="9-submit-your-patch"><a class="header" href="#9-submit-your-patch">9. Submit your patch.</a></h1>
  16218. <p>Once you're happy with your patch, it's time to prepare a Pull Request.</p>
  16219. <p>To prepare a Pull Request, please:</p>
  16220. <ol>
  16221. <li>verify that <a href="development/contributing_guide.html#test-test-test">all the tests pass</a>, including the coding style;</li>
  16222. <li><a href="development/contributing_guide.html#sign-off">sign off</a> your contribution;</li>
  16223. <li><code>git push</code> your commit to your fork of Synapse;</li>
  16224. <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>
  16225. <li>add a <a href="development/contributing_guide.html#changelog">changelog entry</a> and push it to your Pull Request;</li>
  16226. <li>that's it for now, a non-draft pull request will automatically request review from the team;</li>
  16227. <li>if you need to update your PR, please avoid rebasing and just add new commits to your branch.</li>
  16228. </ol>
  16229. <h2 id="changelog"><a class="header" href="#changelog">Changelog</a></h2>
  16230. <p>All changes, even minor ones, need a corresponding changelog / newsfragment
  16231. entry. These are managed by <a href="https://github.com/twisted/towncrier">Towncrier</a>.</p>
  16232. <p>To create a changelog entry, make a new file in the <code>changelog.d</code> directory named
  16233. in the format of <code>PRnumber.type</code>. The type can be one of the following:</p>
  16234. <ul>
  16235. <li><code>feature</code></li>
  16236. <li><code>bugfix</code></li>
  16237. <li><code>docker</code> (for updates to the Docker image)</li>
  16238. <li><code>doc</code> (for updates to the documentation)</li>
  16239. <li><code>removal</code> (also used for deprecations)</li>
  16240. <li><code>misc</code> (for internal-only changes)</li>
  16241. </ul>
  16242. <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
  16243. release, so the content of the file should be a short description of your
  16244. change in the same style as the rest of the changelog. The file can contain Markdown
  16245. formatting, and must end with a full stop (.) or an exclamation mark (!) for
  16246. consistency.</p>
  16247. <p>Adding credits to the changelog is encouraged, we value your
  16248. contributions and would like to have you shouted out in the release notes!</p>
  16249. <p>For example, a fix in PR #1234 would have its changelog entry in
  16250. <code>changelog.d/1234.bugfix</code>, and contain content like:</p>
  16251. <blockquote>
  16252. <p>The security levels of Florbs are now validated when received
  16253. via the <code>/federation/florb</code> endpoint. Contributed by Jane Matrix.</p>
  16254. </blockquote>
  16255. <p>If there are multiple pull requests involved in a single bugfix/feature/etc,
  16256. then the content for each <code>changelog.d</code> file should be the same. Towncrier will
  16257. merge the matching files together into a single changelog entry when we come to
  16258. release.</p>
  16259. <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>
  16260. <p>Obviously, you don't know if you should call your newsfile
  16261. <code>1234.bugfix</code> or <code>5678.bugfix</code> until you create the PR, which leads to a
  16262. chicken-and-egg problem.</p>
  16263. <p>There are two options for solving this:</p>
  16264. <ol>
  16265. <li>
  16266. <p>Open the PR without a changelog file, see what number you got, and <em>then</em>
  16267. add the changelog file to your branch, or:</p>
  16268. </li>
  16269. <li>
  16270. <p>Look at the <a href="https://github.com/matrix-org/synapse/issues?q=">list of all
  16271. issues/PRs</a>, add one to the
  16272. highest number you see, and quickly open the PR before somebody else claims
  16273. your number.</p>
  16274. <p><a href="https://github.com/richvdh/scripts/blob/master/next_github_number.sh">This
  16275. script</a>
  16276. might be helpful if you find yourself doing this a lot.</p>
  16277. </li>
  16278. </ol>
  16279. <p>Sorry, we know it's a bit fiddly, but it's <em>really</em> helpful for us when we come
  16280. to put together a release!</p>
  16281. <h3 id="debian-changelog"><a class="header" href="#debian-changelog">Debian changelog</a></h3>
  16282. <p>Changes which affect the debian packaging files (in <code>debian</code>) are an
  16283. exception to the rule that all changes require a <code>changelog.d</code> file.</p>
  16284. <p>In this case, you will need to add an entry to the debian changelog for the
  16285. next release. For this, run the following command:</p>
  16286. <pre><code>dch
  16287. </code></pre>
  16288. <p>This will make up a new version number (if there isn't already an unreleased
  16289. version in flight), and open an editor where you can add a new changelog entry.
  16290. (Our release process will ensure that the version number and maintainer name is
  16291. corrected for the release.)</p>
  16292. <p>If your change affects both the debian packaging <em>and</em> files outside the debian
  16293. directory, you will need both a regular newsfragment <em>and</em> an entry in the
  16294. debian changelog. (Though typically such changes should be submitted as two
  16295. separate pull requests.)</p>
  16296. <h2 id="sign-off"><a class="header" href="#sign-off">Sign off</a></h2>
  16297. <p>In order to have a concrete record that your contribution is intentional
  16298. and you agree to license it under the same terms as the project's license, we've adopted the
  16299. same lightweight approach that the Linux Kernel
  16300. <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>,
  16301. <a href="https://github.com/docker/docker/blob/master/CONTRIBUTING.md">Docker</a>, and many other
  16302. projects use: the DCO (<a href="http://developercertificate.org/">Developer Certificate of Origin</a>).
  16303. This is a simple declaration that you wrote
  16304. the contribution or otherwise have the right to contribute it to Matrix:</p>
  16305. <pre><code>Developer Certificate of Origin
  16306. Version 1.1
  16307. Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
  16308. 660 York Street, Suite 102,
  16309. San Francisco, CA 94110 USA
  16310. Everyone is permitted to copy and distribute verbatim copies of this
  16311. license document, but changing it is not allowed.
  16312. Developer's Certificate of Origin 1.1
  16313. By making a contribution to this project, I certify that:
  16314. (a) The contribution was created in whole or in part by me and I
  16315. have the right to submit it under the open source license
  16316. indicated in the file; or
  16317. (b) The contribution is based upon previous work that, to the best
  16318. of my knowledge, is covered under an appropriate open source
  16319. license and I have the right under that license to submit that
  16320. work with modifications, whether created in whole or in part
  16321. by me, under the same open source license (unless I am
  16322. permitted to submit under a different license), as indicated
  16323. in the file; or
  16324. (c) The contribution was provided directly to me by some other
  16325. person who certified (a), (b) or (c) and I have not modified
  16326. it.
  16327. (d) I understand and agree that this project and the contribution
  16328. are public and that a record of the contribution (including all
  16329. personal information I submit with it, including my sign-off) is
  16330. maintained indefinitely and may be redistributed consistent with
  16331. this project or the open source license(s) involved.
  16332. </code></pre>
  16333. <p>If you agree to this for your contribution, then all that's needed is to
  16334. include the line in your commit or pull request comment:</p>
  16335. <pre><code>Signed-off-by: Your Name &lt;your@email.example.org&gt;
  16336. </code></pre>
  16337. <p>We accept contributions under a legally identifiable name, such as
  16338. your name on government documentation or common-law names (names
  16339. claimed by legitimate usage or repute). Unfortunately, we cannot
  16340. accept anonymous contributions at this time.</p>
  16341. <p>Git allows you to add this signoff automatically when using the <code>-s</code>
  16342. flag to <code>git commit</code>, which uses the name and email set in your
  16343. <code>user.name</code> and <code>user.email</code> git configs.</p>
  16344. <h3 id="private-sign-off"><a class="header" href="#private-sign-off">Private Sign off</a></h3>
  16345. <p>If you would like to provide your legal name privately to the Matrix.org
  16346. Foundation (instead of in a public commit or comment), you can do so
  16347. by emailing your legal name and a link to the pull request to
  16348. <a href="mailto:dco@matrix.org?subject=Private%20sign%20off">dco@matrix.org</a>.
  16349. It helps to include &quot;sign off&quot; or similar in the subject line. You will then
  16350. be instructed further.</p>
  16351. <p>Once private sign off is complete, doing so for future contributions will not
  16352. be required.</p>
  16353. <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>
  16354. <p>Once the Pull Request is opened, you will see a few things:</p>
  16355. <ol>
  16356. <li>our automated CI (Continuous Integration) pipeline will run (again) the linters, the unit tests, the integration tests and more;</li>
  16357. <li>one or more of the developers will take a look at your Pull Request and offer feedback.</li>
  16358. </ol>
  16359. <p>From this point, you should:</p>
  16360. <ol>
  16361. <li>Look at the results of the CI pipeline.
  16362. <ul>
  16363. <li>If there is any error, fix the error.</li>
  16364. </ul>
  16365. </li>
  16366. <li>If a developer has requested changes, make these changes and let us know if it is ready for a developer to review again.
  16367. <ul>
  16368. <li>A pull request is a conversation, if you disagree with the suggestions, please respond and discuss it.</li>
  16369. </ul>
  16370. </li>
  16371. <li>Create a new commit with the changes.
  16372. <ul>
  16373. <li>Please do NOT overwrite the history. New commits make the reviewer's life easier.</li>
  16374. <li>Push this commits to your Pull Request.</li>
  16375. </ul>
  16376. </li>
  16377. <li>Back to 1.</li>
  16378. <li>Once the pull request is ready for review again please re-request review from whichever developer did your initial
  16379. review (or leave a comment in the pull request that you believe all required changes have been done).</li>
  16380. </ol>
  16381. <p>Once both the CI and the developers are happy, the patch will be merged into Synapse and released shortly!</p>
  16382. <h1 id="11-find-a-new-issue"><a class="header" href="#11-find-a-new-issue">11. Find a new issue.</a></h1>
  16383. <p>By now, you know the drill!</p>
  16384. <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>
  16385. <p>There are some notes for those with commit access to the project on how we
  16386. manage git <a href="development/git.html">here</a>.</p>
  16387. <h1 id="conclusion"><a class="header" href="#conclusion">Conclusion</a></h1>
  16388. <p>That's it! Matrix is a very open and collaborative project as you might expect
  16389. given our obsession with open communication. If we're going to successfully
  16390. matrix together all the fragmented communication technologies out there we are
  16391. reliant on contributions and collaboration from the community to do so. So
  16392. please get involved - and we hope you have as much fun hacking on Matrix as we
  16393. do!</p>
  16394. <div style="break-before: page; page-break-before: always;"></div><h1 id="code-style"><a class="header" href="#code-style">Code Style</a></h1>
  16395. <h2 id="formatting-tools"><a class="header" href="#formatting-tools">Formatting tools</a></h2>
  16396. <p>The Synapse codebase uses a number of code formatting tools in order to
  16397. quickly and automatically check for formatting (and sometimes logical)
  16398. errors in code.</p>
  16399. <p>The necessary tools are:</p>
  16400. <ul>
  16401. <li><a href="https://black.readthedocs.io/en/stable/">black</a>, a source code formatter;</li>
  16402. <li><a href="https://pycqa.github.io/isort/">isort</a>, which organises each file's imports;</li>
  16403. <li><a href="https://github.com/charliermarsh/ruff">ruff</a>, which can spot common errors; and</li>
  16404. <li><a href="https://mypy.readthedocs.io/en/stable/">mypy</a>, a type checker.</li>
  16405. </ul>
  16406. <p>See <a href="development/contributing_guide.html#run-the-linters">the contributing guide</a> for instructions
  16407. on how to install the above tools and run the linters.</p>
  16408. <p>It's worth noting that modern IDEs and text editors can run these tools
  16409. automatically on save. It may be worth looking into whether this
  16410. functionality is supported in your editor for a more convenient
  16411. development workflow. It is not, however, recommended to run <code>mypy</code>
  16412. on save as it takes a while and can be very resource intensive.</p>
  16413. <h2 id="general-rules"><a class="header" href="#general-rules">General rules</a></h2>
  16414. <ul>
  16415. <li><strong>Naming</strong>:
  16416. <ul>
  16417. <li>Use <code>CamelCase</code> for class and type names</li>
  16418. <li>Use underscores for <code>function_names</code> and <code>variable_names</code>.</li>
  16419. </ul>
  16420. </li>
  16421. <li><strong>Docstrings</strong>: should follow the <a href="https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings">google code
  16422. style</a>.
  16423. See the
  16424. <a href="http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html">examples</a>
  16425. in the sphinx documentation.</li>
  16426. <li><strong>Imports</strong>:
  16427. <ul>
  16428. <li>
  16429. <p>Imports should be sorted by <code>isort</code> as described above.</p>
  16430. </li>
  16431. <li>
  16432. <p>Prefer to import classes and functions rather than packages or
  16433. modules.</p>
  16434. <p>Example:</p>
  16435. <pre><code class="language-python">from synapse.types import UserID
  16436. ...
  16437. user_id = UserID(local, server)
  16438. </code></pre>
  16439. <p>is preferred over:</p>
  16440. <pre><code class="language-python">from synapse import types
  16441. ...
  16442. user_id = types.UserID(local, server)
  16443. </code></pre>
  16444. <p>(or any other variant).</p>
  16445. <p>This goes against the advice in the Google style guide, but it
  16446. means that errors in the name are caught early (at import time).</p>
  16447. </li>
  16448. <li>
  16449. <p>Avoid wildcard imports (<code>from synapse.types import *</code>) and
  16450. relative imports (<code>from .types import UserID</code>).</p>
  16451. </li>
  16452. </ul>
  16453. </li>
  16454. </ul>
  16455. <h2 id="configuration-code-and-documentation-format"><a class="header" href="#configuration-code-and-documentation-format">Configuration code and documentation format</a></h2>
  16456. <p>When adding a configuration option to the code, if several settings are grouped into a single dict, ensure that your code
  16457. correctly handles the top-level option being set to <code>None</code> (as it will be if no sub-options are enabled).</p>
  16458. <p>The <a href="usage/configuration/config_documentation.html">configuration manual</a> acts as a
  16459. reference to Synapse's configuration options for server administrators.
  16460. Remember that many readers will be unfamiliar with YAML and server
  16461. administration in general, so it is important that when you add
  16462. a configuration option the documentation be as easy to understand as possible, which
  16463. includes following a consistent format.</p>
  16464. <p>Some guidelines follow:</p>
  16465. <ul>
  16466. <li>
  16467. <p>Each option should be listed in the config manual with the following format:</p>
  16468. <ul>
  16469. <li>
  16470. <p>The name of the option, prefixed by <code>###</code>. </p>
  16471. </li>
  16472. <li>
  16473. <p>A comment which describes the default behaviour (i.e. what
  16474. happens if the setting is omitted), as well as what the effect
  16475. will be if the setting is changed.</p>
  16476. </li>
  16477. <li>
  16478. <p>An example setting, using backticks to define the code block</p>
  16479. <p>For boolean (on/off) options, convention is that this example
  16480. should be the <em>opposite</em> to the default. For other options, the example should give
  16481. some non-default value which is likely to be useful to the reader.</p>
  16482. </li>
  16483. </ul>
  16484. </li>
  16485. <li>
  16486. <p>There should be a horizontal rule between each option, which can be achieved by adding <code>---</code> before and
  16487. after the option.</p>
  16488. </li>
  16489. <li>
  16490. <p><code>true</code> and <code>false</code> are spelt thus (as opposed to <code>True</code>, etc.)</p>
  16491. </li>
  16492. </ul>
  16493. <p>Example:</p>
  16494. <hr />
  16495. <h3 id="modules-3"><a class="header" href="#modules-3"><code>modules</code></a></h3>
  16496. <p>Use the <code>module</code> sub-option to add a module under <code>modules</code> to extend functionality.
  16497. The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
  16498. for the <code>module</code>.</p>
  16499. <p>Defaults to none.</p>
  16500. <p>Example configuration:</p>
  16501. <pre><code class="language-yaml">modules:
  16502. - module: my_super_module.MySuperClass
  16503. config:
  16504. do_thing: true
  16505. - module: my_other_super_module.SomeClass
  16506. config: {}
  16507. </code></pre>
  16508. <hr />
  16509. <p>Note that the sample configuration is generated from the synapse code
  16510. and is maintained by a script, <code>scripts-dev/generate_sample_config.sh</code>.
  16511. Making sure that the output from this script matches the desired format
  16512. is left as an exercise for the reader!</p>
  16513. <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>
  16514. <p>The Synapse team works off a shared review queue -- any new pull requests for
  16515. Synapse (or related projects) has a review requested from the entire team. Team
  16516. members should process this queue using the following rules:</p>
  16517. <ul>
  16518. <li>Any high urgency pull requests (e.g. fixes for broken continuous integration
  16519. or fixes for release blockers);</li>
  16520. <li>Follow-up reviews for pull requests which have previously received reviews;</li>
  16521. <li>Any remaining pull requests.</li>
  16522. </ul>
  16523. <p>For the latter two categories above, older pull requests should be prioritised.</p>
  16524. <p>It is explicit that there is no priority given to pull requests from the team
  16525. (vs from the community). If a pull request requires a quick turn around, please
  16526. explicitly communicate this via <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>
  16527. or as a comment on the pull request.</p>
  16528. <p>Once an initial review has been completed and the author has made additional changes,
  16529. follow-up reviews should go back to the same reviewer. This helps build a shared
  16530. context and conversation between author and reviewer.</p>
  16531. <p>As a team we aim to keep the number of inflight pull requests to a minimum to ensure
  16532. that ongoing work is finished before starting new work.</p>
  16533. <h2 id="performing-a-review"><a class="header" href="#performing-a-review">Performing a review</a></h2>
  16534. <p>To communicate to the rest of the team the status of each pull request, team
  16535. members should do the following:</p>
  16536. <ul>
  16537. <li>Assign themselves to the pull request (they should be left assigned to the
  16538. pull request until it is merged, closed, or are no longer the reviewer);</li>
  16539. <li>Review the pull request by leaving comments, questions, and suggestions;</li>
  16540. <li>Mark the pull request appropriately (as needing changes or accepted).</li>
  16541. </ul>
  16542. <p>If you are unsure about a particular part of the pull request (or are not confident
  16543. in your understanding of part of the code) then ask questions or request review
  16544. from the team again. When requesting review from the team be sure to leave a comment
  16545. with the rationale on why you're putting it back in the queue.</p>
  16546. <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>
  16547. <p>Releases of Synapse follow a two week release cycle with new releases usually
  16548. occurring on Tuesdays:</p>
  16549. <ul>
  16550. <li>Day 0: Synapse <code>N - 1</code> is released.</li>
  16551. <li>Day 7: Synapse <code>N</code> release candidate 1 is released.</li>
  16552. <li>Days 7 - 13: Synapse <code>N</code> release candidates 2+ are released, if bugs are found.</li>
  16553. <li>Day 14: Synapse <code>N</code> is released.</li>
  16554. </ul>
  16555. <p>Note that this schedule might be modified depending on the availability of the
  16556. Synapse team, e.g. releases may be skipped to avoid holidays.</p>
  16557. <p>Release announcements can be found in the
  16558. <a href="https://matrix.org/category/releases">release category of the Matrix blog</a>.</p>
  16559. <h2 id="bugfix-releases"><a class="header" href="#bugfix-releases">Bugfix releases</a></h2>
  16560. <p>If a bug is found after release that is deemed severe enough (by a combination
  16561. of the impacted users and the impact on those users) then a bugfix release may
  16562. be issued. This may be at any point in the release cycle.</p>
  16563. <h2 id="security-releases"><a class="header" href="#security-releases">Security releases</a></h2>
  16564. <p>Security will sometimes be backported to the previous version and released
  16565. immediately before the next release candidate. An example of this might be:</p>
  16566. <ul>
  16567. <li>Day 0: Synapse N - 1 is released.</li>
  16568. <li>Day 7: Synapse (N - 1).1 is released as Synapse N - 1 + the security fix.</li>
  16569. <li>Day 7: Synapse N release candidate 1 is released (including the security fix).</li>
  16570. </ul>
  16571. <p>Depending on the impact and complexity of security fixes, multiple fixes might
  16572. be held to be released together.</p>
  16573. <p>In some cases, a pre-disclosure of a security release will be issued as a notice
  16574. to Synapse operators that there is an upcoming security release. These can be
  16575. found in the <a href="https://matrix.org/category/security">security category of the Matrix blog</a>.</p>
  16576. <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>
  16577. <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>
  16578. <p>In an ideal world, our git commit history would be a linear progression of
  16579. commits each of which contains a single change building on what came
  16580. before. Here, by way of an arbitrary example, is the top of <code>git log --graph b2dba0607</code>:</p>
  16581. <img src="development/img/git/clean.png" alt="clean git graph" width="500px">
  16582. <p>Note how the commit comment explains clearly what is changing and why. Also
  16583. note the <em>absence</em> of merge commits, as well as the absence of commits called
  16584. things like (to pick a few culprits):
  16585. <a href="https://github.com/matrix-org/synapse/commit/84691da6c">“pep8”</a>, <a href="https://github.com/matrix-org/synapse/commit/474810d9d">“fix broken
  16586. test”</a>,
  16587. <a href="https://github.com/matrix-org/synapse/commit/c9d72e457">“oops”</a>,
  16588. <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
  16589. the president?”</a>.</p>
  16590. <p>There are a number of reasons why keeping a clean commit history is a good
  16591. thing:</p>
  16592. <ul>
  16593. <li>
  16594. <p>From time to time, after a change lands, it turns out to be necessary to
  16595. revert it, or to backport it to a release branch. Those operations are
  16596. <em>much</em> easier when the change is contained in a single commit.</p>
  16597. </li>
  16598. <li>
  16599. <p>Similarly, it's much easier to answer questions like “is the fix for
  16600. <code>/publicRooms</code> on the release branch?” if that change consists of a single
  16601. commit.</p>
  16602. </li>
  16603. <li>
  16604. <p>Likewise: “what has changed on this branch in the last week?” is much
  16605. clearer without merges and “pep8” commits everywhere.</p>
  16606. </li>
  16607. <li>
  16608. <p>Sometimes we need to figure out where a bug got introduced, or some
  16609. behaviour changed. One way of doing that is with <code>git bisect</code>: pick an
  16610. arbitrary commit between the known good point and the known bad point, and
  16611. see how the code behaves. However, that strategy fails if the commit you
  16612. chose is the middle of someone's epic branch in which they broke the world
  16613. before putting it back together again.</p>
  16614. </li>
  16615. </ul>
  16616. <p>One counterargument is that it is sometimes useful to see how a PR evolved as
  16617. it went through review cycles. This is true, but that information is always
  16618. 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
  16619. namespace</a>).</p>
  16620. <p>Of course, in reality, things are more complicated than that. We have release
  16621. branches as well as <code>develop</code> and <code>master</code>, and we deliberately merge changes
  16622. between them. Bugs often slip through and have to be fixed later. That's all
  16623. fine: this not a cast-iron rule which must be obeyed, but an ideal to aim
  16624. towards.</p>
  16625. <h2 id="merges-squashes-rebases-wtf"><a class="header" href="#merges-squashes-rebases-wtf">Merges, squashes, rebases: wtf?</a></h2>
  16626. <p>Ok, so that's what we'd like to achieve. How do we achieve it?</p>
  16627. <p>The TL;DR is: when you come to merge a pull request, you <em>probably</em> want to
  16628. “squash and merge”:</p>
  16629. <p><img src="development/img/git/squash.png" alt="squash and merge" />.</p>
  16630. <p>(This applies whether you are merging your own PR, or that of another
  16631. contributor.)</p>
  16632. <p>“Squash and merge”<sup id="a1"><a href="development/git.html#f1">1</a></sup> takes all of the changes in the
  16633. PR, and bundles them into a single commit. GitHub gives you the opportunity to
  16634. edit the commit message before you confirm, and normally you should do so,
  16635. because the default will be useless (again: <code>* woops typo</code> is not a useful
  16636. thing to keep in the historical record).</p>
  16637. <p>The main problem with this approach comes when you have a series of pull
  16638. requests which build on top of one another: as soon as you squash-merge the
  16639. first PR, you'll end up with a stack of conflicts to resolve in all of the
  16640. others. In general, it's best to avoid this situation in the first place by
  16641. trying not to have multiple related PRs in flight at the same time. Still,
  16642. sometimes that's not possible and doing a regular merge is the lesser evil.</p>
  16643. <p>Another occasion in which a regular merge makes more sense is a PR where you've
  16644. deliberately created a series of commits each of which makes sense in its own
  16645. right. For example: <a href="https://github.com/matrix-org/synapse/pull/6837">a PR which gradually propagates a refactoring operation
  16646. through the codebase</a>, or <a href="https://github.com/matrix-org/synapse/pull/5987">a
  16647. PR which is the culmination of several other
  16648. PRs</a>. In this case the ability
  16649. to figure out when a particular change/bug was introduced could be very useful.</p>
  16650. <p>Ultimately: <strong>this is not a hard-and-fast-rule</strong>. If in doubt, ask yourself “do
  16651. each of the commits I am about to merge make sense in their own right”, but
  16652. remember that we're just doing our best to balance “keeping the commit history
  16653. clean” with other factors.</p>
  16654. <h2 id="git-branching-model"><a class="header" href="#git-branching-model">Git branching model</a></h2>
  16655. <p>A <a href="https://nvie.com/posts/a-successful-git-branching-model/">lot</a>
  16656. <a href="http://scottchacon.com/2011/08/31/github-flow.html">of</a>
  16657. <a href="https://www.endoflineblog.com/gitflow-considered-harmful">words</a> have been
  16658. written in the past about git branching models (no really, <a href="https://martinfowler.com/articles/branching-patterns.html">a
  16659. lot</a>). I tend to
  16660. think the whole thing is overblown. Fundamentally, it's not that
  16661. complicated. Here's how we do it.</p>
  16662. <p>Let's start with a picture:</p>
  16663. <p><img src="development/img/git/branches.jpg" alt="branching model" /></p>
  16664. <p>It looks complicated, but it's really not. There's one basic rule: <em>anyone</em> is
  16665. free to merge from <em>any</em> more-stable branch to <em>any</em> less-stable branch at
  16666. <em>any</em> time<sup id="a2"><a href="development/git.html#f2">2</a></sup>. (The principle behind this is that if a
  16667. change is good enough for the more-stable branch, then it's also good enough go
  16668. put in a less-stable branch.)</p>
  16669. <p>Meanwhile, merging (or squashing, as per the above) from a less-stable to a
  16670. more-stable branch is a deliberate action in which you want to publish a change
  16671. or a set of changes to (some subset of) the world: for example, this happens
  16672. when a PR is landed, or as part of our release process.</p>
  16673. <p>So, what counts as a more- or less-stable branch? A little reflection will show
  16674. that our active branches are ordered thus, from more-stable to less-stable:</p>
  16675. <ul>
  16676. <li><code>master</code> (tracks our last release).</li>
  16677. <li><code>release-vX.Y</code> (the branch where we prepare the next release)<sup
  16678. id="a3"><a href="development/git.html#f3">3</a></sup>.</li>
  16679. <li>PR branches which are targeting the release.</li>
  16680. <li><code>develop</code> (our &quot;mainline&quot; branch containing our bleeding-edge).</li>
  16681. <li>regular PR branches.</li>
  16682. </ul>
  16683. <p>The corollary is: if you have a bugfix that needs to land in both
  16684. <code>release-vX.Y</code> <em>and</em> <code>develop</code>, then you should base your PR on
  16685. <code>release-vX.Y</code>, get it merged there, and then merge from <code>release-vX.Y</code> to
  16686. <code>develop</code>. (If a fix lands in <code>develop</code> and we later need it in a
  16687. release-branch, we can of course cherry-pick it, but landing it in the release
  16688. branch first helps reduce the chance of annoying conflicts.)</p>
  16689. <hr />
  16690. <p><b id="f1">[1]</b>: “Squash and merge” is GitHub's term for this
  16691. operation. Given that there is no merge involved, I'm not convinced it's the
  16692. most intuitive name. <a href="development/git.html#a1">^</a></p>
  16693. <p><b id="f2">[2]</b>: Well, anyone with commit access.<a href="development/git.html#a2">^</a></p>
  16694. <p><b id="f3">[3]</b>: Very, very occasionally (I think this has happened once in
  16695. the history of Synapse), we've had two releases in flight at once. Obviously,
  16696. <code>release-v1.2</code> is more-stable than <code>release-v1.3</code>. <a href="development/git.html#a3">^</a></p>
  16697. <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>
  16698. <p><strong>DO NOT USE THESE DEMO SERVERS IN PRODUCTION</strong></p>
  16699. <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>
  16700. <p>The demo setup allows running three federation Synapse servers, with server
  16701. names <code>localhost:8480</code>, <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
  16702. <p>You can access them via any Matrix client over HTTP at <code>localhost:8080</code>,
  16703. <code>localhost:8081</code>, and <code>localhost:8082</code> or over HTTPS at <code>localhost:8480</code>,
  16704. <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
  16705. <p>To enable the servers to communicate, self-signed SSL certificates are generated
  16706. and the servers are configured in a highly insecure way, including:</p>
  16707. <ul>
  16708. <li>Not checking certificates over federation.</li>
  16709. <li>Not verifying keys.</li>
  16710. </ul>
  16711. <p>The servers are configured to store their data under <code>demo/8080</code>, <code>demo/8081</code>, and
  16712. <code>demo/8082</code>. This includes configuration, logs, SQLite databases, and media.</p>
  16713. <p>Note that when joining a public room on a different homeserver via &quot;#foo:bar.net&quot;,
  16714. then you are (in the current implementation) joining a room with room_id &quot;foo&quot;.
  16715. This means that it won't work if your homeserver already has a room with that
  16716. name.</p>
  16717. <h2 id="using-the-demo-scripts"><a class="header" href="#using-the-demo-scripts">Using the demo scripts</a></h2>
  16718. <p>There's three main scripts with straightforward purposes:</p>
  16719. <ul>
  16720. <li><code>start.sh</code> will start the Synapse servers, generating any missing configuration.
  16721. <ul>
  16722. <li>This accepts a single parameter <code>--no-rate-limit</code> to &quot;disable&quot; rate limits
  16723. (they actually still exist, but are very high).</li>
  16724. </ul>
  16725. </li>
  16726. <li><code>stop.sh</code> will stop the Synapse servers.</li>
  16727. <li><code>clean.sh</code> will delete the configuration, databases, log files, etc.</li>
  16728. </ul>
  16729. <p>To start a completely new set of servers, run:</p>
  16730. <pre><code class="language-sh">./demo/stop.sh; ./demo/clean.sh &amp;&amp; ./demo/start.sh
  16731. </code></pre>
  16732. <div style="break-before: page; page-break-before: always;"></div><h1 id="opentracing-2"><a class="header" href="#opentracing-2">OpenTracing</a></h1>
  16733. <h2 id="background"><a class="header" href="#background">Background</a></h2>
  16734. <p>OpenTracing is a semi-standard being adopted by a number of distributed
  16735. tracing platforms. It is a common api for facilitating vendor-agnostic
  16736. tracing instrumentation. That is, we can use the OpenTracing api and
  16737. select one of a number of tracer implementations to do the heavy lifting
  16738. in the background. Our current selected implementation is Jaeger.</p>
  16739. <p>OpenTracing is a tool which gives an insight into the causal
  16740. relationship of work done in and between servers. The servers each track
  16741. events and report them to a centralised server - in Synapse's case:
  16742. Jaeger. The basic unit used to represent events is the span. The span
  16743. roughly represents a single piece of work that was done and the time at
  16744. which it occurred. A span can have child spans, meaning that the work of
  16745. the child had to be completed for the parent span to complete, or it can
  16746. have follow-on spans which represent work that is undertaken as a result
  16747. of the parent but is not depended on by the parent to in order to
  16748. finish.</p>
  16749. <p>Since this is undertaken in a distributed environment a request to
  16750. another server, such as an RPC or a simple GET, can be considered a span
  16751. (a unit or work) for the local server. This causal link is what
  16752. OpenTracing aims to capture and visualise. In order to do this metadata
  16753. about the local server's span, i.e the 'span context', needs to be
  16754. included with the request to the remote.</p>
  16755. <p>It is up to the remote server to decide what it does with the spans it
  16756. creates. This is called the sampling policy and it can be configured
  16757. through Jaeger's settings.</p>
  16758. <p>For OpenTracing concepts see
  16759. <a href="https://opentracing.io/docs/overview/what-is-tracing/">https://opentracing.io/docs/overview/what-is-tracing/</a>.</p>
  16760. <p>For more information about Jaeger's implementation see
  16761. <a href="https://www.jaegertracing.io/docs/">https://www.jaegertracing.io/docs/</a></p>
  16762. <h2 id="setting-up-opentracing"><a class="header" href="#setting-up-opentracing">Setting up OpenTracing</a></h2>
  16763. <p>To receive OpenTracing spans, start up a Jaeger server. This can be done
  16764. using docker like so:</p>
  16765. <pre><code class="language-sh">docker run -d --name jaeger \
  16766. -p 6831:6831/udp \
  16767. -p 6832:6832/udp \
  16768. -p 5778:5778 \
  16769. -p 16686:16686 \
  16770. -p 14268:14268 \
  16771. jaegertracing/all-in-one:1
  16772. </code></pre>
  16773. <p>Latest documentation is probably at
  16774. https://www.jaegertracing.io/docs/latest/getting-started.</p>
  16775. <h2 id="enable-opentracing-in-synapse"><a class="header" href="#enable-opentracing-in-synapse">Enable OpenTracing in Synapse</a></h2>
  16776. <p>OpenTracing is not enabled by default. It must be enabled in the
  16777. homeserver config by adding the <code>opentracing</code> option to your config file. You can find
  16778. documentation about how to do this in the <a href="usage/configuration/config_documentation.html#opentracing">config manual under the header 'Opentracing'</a>.
  16779. See below for an example Opentracing configuration: </p>
  16780. <pre><code class="language-yaml">opentracing:
  16781. enabled: true
  16782. homeserver_whitelist:
  16783. - &quot;mytrustedhomeserver.org&quot;
  16784. - &quot;*.myotherhomeservers.com&quot;
  16785. </code></pre>
  16786. <h2 id="homeserver-whitelisting"><a class="header" href="#homeserver-whitelisting">Homeserver whitelisting</a></h2>
  16787. <p>The homeserver whitelist is configured using regular expressions. A list
  16788. of regular expressions can be given and their union will be compared
  16789. when propagating any spans contexts to another homeserver.</p>
  16790. <p>Though it's mostly safe to send and receive span contexts to and from
  16791. untrusted users since span contexts are usually opaque ids it can lead
  16792. to two problems, namely:</p>
  16793. <ul>
  16794. <li>If the span context is marked as sampled by the sending homeserver
  16795. the receiver will sample it. Therefore two homeservers with wildly
  16796. different sampling policies could incur higher sampling counts than
  16797. intended.</li>
  16798. <li>Sending servers can attach arbitrary data to spans, known as
  16799. 'baggage'. For safety this has been disabled in Synapse but that
  16800. doesn't prevent another server sending you baggage which will be
  16801. logged to OpenTracing's logs.</li>
  16802. </ul>
  16803. <h2 id="configuring-jaeger"><a class="header" href="#configuring-jaeger">Configuring Jaeger</a></h2>
  16804. <p>Sampling strategies can be set as in this document:
  16805. <a href="https://www.jaegertracing.io/docs/latest/sampling/">https://www.jaegertracing.io/docs/latest/sampling/</a>.</p>
  16806. <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>
  16807. <p>Synapse's database schema is stored in the <code>synapse.storage.schema</code> module.</p>
  16808. <h2 id="logical-databases"><a class="header" href="#logical-databases">Logical databases</a></h2>
  16809. <p>Synapse supports splitting its datastore across multiple physical databases (which can
  16810. be useful for large installations), and the schema files are therefore split according
  16811. to the logical database they apply to.</p>
  16812. <p>At the time of writing, the following &quot;logical&quot; databases are supported:</p>
  16813. <ul>
  16814. <li><code>state</code> - used to store Matrix room state (more specifically, <code>state_groups</code>,
  16815. their relationships and contents).</li>
  16816. <li><code>main</code> - stores everything else.</li>
  16817. </ul>
  16818. <p>Additionally, the <code>common</code> directory contains schema files for tables which must be
  16819. present on <em>all</em> physical databases.</p>
  16820. <h2 id="synapse-schema-versions"><a class="header" href="#synapse-schema-versions">Synapse schema versions</a></h2>
  16821. <p>Synapse manages its database schema via &quot;schema versions&quot;. These are mainly used to
  16822. help avoid confusion if the Synapse codebase is rolled back after the database is
  16823. updated. They work as follows:</p>
  16824. <ul>
  16825. <li>
  16826. <p>The Synapse codebase defines a constant <code>synapse.storage.schema.SCHEMA_VERSION</code>
  16827. which represents the expectations made about the database by that version. For
  16828. example, as of Synapse v1.36, this is <code>59</code>.</p>
  16829. </li>
  16830. <li>
  16831. <p>The database stores a &quot;compatibility version&quot; in
  16832. <code>schema_compat_version.compat_version</code> which defines the <code>SCHEMA_VERSION</code> of the
  16833. oldest version of Synapse which will work with the database. On startup, if
  16834. <code>compat_version</code> is found to be newer than <code>SCHEMA_VERSION</code>, Synapse will refuse to
  16835. start.</p>
  16836. <p>Synapse automatically updates this field from
  16837. <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code>.</p>
  16838. </li>
  16839. <li>
  16840. <p>Whenever a backwards-incompatible change is made to the database format (normally
  16841. via a <code>delta</code> file), <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code> is also updated
  16842. so that administrators can not accidentally roll back to a too-old version of Synapse.</p>
  16843. </li>
  16844. </ul>
  16845. <p>Generally, the goal is to maintain compatibility with at least one or two previous
  16846. releases of Synapse, so any substantial change tends to require multiple releases and a
  16847. bit of forward-planning to get right.</p>
  16848. <p>As a worked example: we want to remove the <code>room_stats_historical</code> table. Here is how it
  16849. might pan out.</p>
  16850. <ol>
  16851. <li>
  16852. <p>Replace any code that <em>reads</em> from <code>room_stats_historical</code> with alternative
  16853. implementations, but keep writing to it in case of rollback to an earlier version.
  16854. Also, increase <code>synapse.storage.schema.SCHEMA_VERSION</code>. In this
  16855. instance, there is no existing code which reads from <code>room_stats_historical</code>, so
  16856. our starting point is:</p>
  16857. <p>v1.36.0: <code>SCHEMA_VERSION=59</code>, <code>SCHEMA_COMPAT_VERSION=59</code></p>
  16858. </li>
  16859. <li>
  16860. <p>Next (say in Synapse v1.37.0): remove the code that <em>writes</em> to
  16861. <code>room_stats_historical</code>, but don’t yet remove the table in case of rollback to
  16862. v1.36.0. Again, we increase <code>synapse.storage.schema.SCHEMA_VERSION</code>, but
  16863. because we have not broken compatibility with v1.36, we do not yet update
  16864. <code>SCHEMA_COMPAT_VERSION</code>. We now have:</p>
  16865. <p>v1.37.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=59</code>.</p>
  16866. </li>
  16867. <li>
  16868. <p>Later (say in Synapse v1.38.0): we can remove the table altogether. This will
  16869. break compatibility with v1.36.0, so we must update <code>SCHEMA_COMPAT_VERSION</code> accordingly.
  16870. There is no need to update <code>synapse.storage.schema.SCHEMA_VERSION</code>, since there is no
  16871. change to the Synapse codebase here. So we end up with:</p>
  16872. <p>v1.38.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=60</code>.</p>
  16873. </li>
  16874. </ol>
  16875. <p>If in doubt about whether to update <code>SCHEMA_VERSION</code> or not, it is generally best to
  16876. lean towards doing so.</p>
  16877. <h2 id="full-schema-dumps"><a class="header" href="#full-schema-dumps">Full schema dumps</a></h2>
  16878. <p>In the <code>full_schemas</code> directories, only the most recently-numbered snapshot is used
  16879. (<code>54</code> at the time of writing). Older snapshots (eg, <code>16</code>) are present for historical
  16880. reference only.</p>
  16881. <h3 id="building-full-schema-dumps"><a class="header" href="#building-full-schema-dumps">Building full schema dumps</a></h3>
  16882. <p>If you want to recreate these schemas, they need to be made from a database that
  16883. has had all background updates run.</p>
  16884. <p>To do so, use <code>scripts-dev/make_full_schema.sh</code>. This will produce new
  16885. <code>full.sql.postgres</code> and <code>full.sql.sqlite</code> files.</p>
  16886. <p>Ensure postgres is installed, then run:</p>
  16887. <pre><code class="language-sh">./scripts-dev/make_full_schema.sh -p postgres_username -o output_dir/
  16888. </code></pre>
  16889. <p>NB at the time of writing, this script predates the split into separate <code>state</code>/<code>main</code>
  16890. databases so will require updates to handle that correctly.</p>
  16891. <h2 id="delta-files"><a class="header" href="#delta-files">Delta files</a></h2>
  16892. <p>Delta files define the steps required to upgrade the database from an earlier version.
  16893. They can be written as either a file containing a series of SQL statements, or a Python
  16894. module.</p>
  16895. <p>Synapse remembers which delta files it has applied to a database (they are stored in the
  16896. <code>applied_schema_deltas</code> table) and will not re-apply them (even if a given file is
  16897. subsequently updated).</p>
  16898. <p>Delta files should be placed in a directory named <code>synapse/storage/schema/&lt;database&gt;/delta/&lt;version&gt;/</code>.
  16899. They are applied in alphanumeric order, so by convention the first two characters
  16900. of the filename should be an integer such as <code>01</code>, to put the file in the right order.</p>
  16901. <h3 id="sql-delta-files"><a class="header" href="#sql-delta-files">SQL delta files</a></h3>
  16902. <p>These should be named <code>*.sql</code>, or — for changes which should only be applied for a
  16903. given database engine — <code>*.sql.posgres</code> or <code>*.sql.sqlite</code>. For example, a delta which
  16904. adds a new column to the <code>foo</code> table might be called <code>01add_bar_to_foo.sql</code>.</p>
  16905. <p>Note that our SQL parser is a bit simple - it understands comments (<code>--</code> and <code>/*...*/</code>),
  16906. 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>
  16907. <h3 id="python-delta-files"><a class="header" href="#python-delta-files">Python delta files</a></h3>
  16908. <p>For more flexibility, a delta file can take the form of a python module. These should
  16909. be named <code>*.py</code>. Note that database-engine-specific modules are not supported here –
  16910. instead you can write <code>if isinstance(database_engine, PostgresEngine)</code> or similar.</p>
  16911. <p>A Python delta module should define either or both of the following functions:</p>
  16912. <pre><code class="language-python">import synapse.config.homeserver
  16913. import synapse.storage.engines
  16914. import synapse.storage.types
  16915. def run_create(
  16916. cur: synapse.storage.types.Cursor,
  16917. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  16918. ) -&gt; None:
  16919. &quot;&quot;&quot;Called whenever an existing or new database is to be upgraded&quot;&quot;&quot;
  16920. ...
  16921. def run_upgrade(
  16922. cur: synapse.storage.types.Cursor,
  16923. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  16924. config: synapse.config.homeserver.HomeServerConfig,
  16925. ) -&gt; None:
  16926. &quot;&quot;&quot;Called whenever an existing database is to be upgraded.&quot;&quot;&quot;
  16927. ...
  16928. </code></pre>
  16929. <h2 id="background-updates-1"><a class="header" href="#background-updates-1">Background updates</a></h2>
  16930. <p>It is sometimes appropriate to perform database migrations as part of a background
  16931. process (instead of blocking Synapse until the migration is done). In particular,
  16932. this is useful for migrating data when adding new columns or tables.</p>
  16933. <p>Pending background updates stored in the <code>background_updates</code> table and are denoted
  16934. by a unique name, the current status (stored in JSON), and some dependency information:</p>
  16935. <ul>
  16936. <li>Whether the update requires a previous update to be complete.</li>
  16937. <li>A rough ordering for which to complete updates.</li>
  16938. </ul>
  16939. <p>A new background updates needs to be added to the <code>background_updates</code> table:</p>
  16940. <pre><code class="language-sql">INSERT INTO background_updates (ordering, update_name, depends_on, progress_json) VALUES
  16941. (7706, 'my_background_update', 'a_previous_background_update' '{}');
  16942. </code></pre>
  16943. <p>And then needs an associated handler in the appropriate datastore:</p>
  16944. <pre><code class="language-python">self.db_pool.updates.register_background_update_handler(
  16945. &quot;my_background_update&quot;,
  16946. update_handler=self._my_background_update,
  16947. )
  16948. </code></pre>
  16949. <p>There are a few types of updates that can be performed, see the <code>BackgroundUpdater</code>:</p>
  16950. <ul>
  16951. <li><code>register_background_update_handler</code>: A generic handler for custom SQL</li>
  16952. <li><code>register_background_index_update</code>: Create an index in the background</li>
  16953. <li><code>register_background_validate_constraint</code>: Validate a constraint in the background
  16954. (PostgreSQL-only)</li>
  16955. <li><code>register_background_validate_constraint_and_delete_rows</code>: Similar to
  16956. <code>register_background_validate_constraint</code>, but deletes rows which don't fit
  16957. the constraint.</li>
  16958. </ul>
  16959. <p>For <code>register_background_update_handler</code>, the generic handler must track progress
  16960. and then finalize the background update:</p>
  16961. <pre><code class="language-python">async def _my_background_update(self, progress: JsonDict, batch_size: int) -&gt; int:
  16962. def _do_something(txn: LoggingTransaction) -&gt; int:
  16963. ...
  16964. self.db_pool.updates._background_update_progress_txn(
  16965. txn, &quot;my_background_update&quot;, {&quot;last_processed&quot;: last_processed}
  16966. )
  16967. return last_processed - prev_last_processed
  16968. num_processed = await self.db_pool.runInteraction(&quot;_do_something&quot;, _do_something)
  16969. await self.db_pool.updates._end_background_update(&quot;my_background_update&quot;)
  16970. return num_processed
  16971. </code></pre>
  16972. <p>Synapse will attempt to rate-limit how often background updates are run via the
  16973. given batch-size and the returned number of processed entries (and how long the
  16974. function took to run). See
  16975. <a href="development/../modules/background_update_controller_callbacks.html">background update controller callbacks</a>.</p>
  16976. <h2 id="boolean-columns"><a class="header" href="#boolean-columns">Boolean columns</a></h2>
  16977. <p>Boolean columns require special treatment, since SQLite treats booleans the
  16978. same as integers.</p>
  16979. <p>Any new boolean column must be added to the <code>BOOLEAN_COLUMNS</code> list in
  16980. <code>synapse/_scripts/synapse_port_db.py</code>. This tells the port script to cast
  16981. the integer value from SQLite to a boolean before writing the value to the
  16982. postgres database.</p>
  16983. <h2 id="event_id-global-uniqueness"><a class="header" href="#event_id-global-uniqueness"><code>event_id</code> global uniqueness</a></h2>
  16984. <p><code>event_id</code>'s can be considered globally unique although there has been a lot of
  16985. debate on this topic in places like
  16986. <a href="https://github.com/matrix-org/matrix-spec-proposals/issues/2779">MSC2779</a> and
  16987. <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/2848">MSC2848</a> which
  16988. has no resolution yet (as of 2022-09-01). There are several places in Synapse
  16989. 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>
  16990. where we assume that event IDs are globally unique.</p>
  16991. <p>When scoping <code>event_id</code> in a database schema, it is often nice to accompany it
  16992. 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
  16993. makes it very easy to find and clean up everything in a room when it needs to be
  16994. purged (no need to use sub-<code>select</code> query or join from the <code>events</code> table).</p>
  16995. <p>A note on collisions: In room versions <code>1</code> and <code>2</code> it's possible to end up with
  16996. two events with the same <code>event_id</code> (in the same or different rooms). After room
  16997. version <code>3</code>, that can only happen with a hash collision, which we basically hope
  16998. will never happen (SHA256 has a massive big key space).</p>
  16999. <h2 id="worked-examples-of-gradual-migrations"><a class="header" href="#worked-examples-of-gradual-migrations">Worked examples of gradual migrations</a></h2>
  17000. <p>Some migrations need to be performed gradually. A prime example of this is anything
  17001. which would need to do a large table scan — including adding columns, indices or
  17002. <code>NOT NULL</code> constraints to non-empty tables — such a migration should be done as a
  17003. background update where possible, at least on Postgres.
  17004. We can afford to be more relaxed about SQLite databases since they are usually
  17005. used on smaller deployments and SQLite does not support the same concurrent
  17006. DDL operations as Postgres.</p>
  17007. <p>We also typically insist on having at least one Synapse version's worth of
  17008. backwards compatibility, so that administrators can roll back Synapse if an upgrade
  17009. did not go smoothly.</p>
  17010. <p>This sometimes results in having to plan a migration across multiple versions
  17011. of Synapse.</p>
  17012. <p>This section includes an example and may include more in the future.</p>
  17013. <h3 id="transforming-a-column-into-another-one-with-not-null-constraints"><a class="header" href="#transforming-a-column-into-another-one-with-not-null-constraints">Transforming a column into another one, with <code>NOT NULL</code> constraints</a></h3>
  17014. <p>This example illustrates how you would introduce a new column, write data into it
  17015. based on data from an old column and then drop the old column.</p>
  17016. <p>We are aiming for semantic equivalence to:</p>
  17017. <pre><code class="language-sql">ALTER TABLE mytable ADD COLUMN new_column INTEGER;
  17018. UPDATE mytable SET new_column = old_column * 100;
  17019. ALTER TABLE mytable ALTER COLUMN new_column ADD CONSTRAINT NOT NULL;
  17020. ALTER TABLE mytable DROP COLUMN old_column;
  17021. </code></pre>
  17022. <h4 id="synapse-version-n"><a class="header" href="#synapse-version-n">Synapse version <code>N</code></a></h4>
  17023. <pre><code class="language-python">SCHEMA_VERSION = S
  17024. SCHEMA_COMPAT_VERSION = ... # unimportant at this stage
  17025. </code></pre>
  17026. <p><strong>Invariants:</strong></p>
  17027. <ol>
  17028. <li><code>old_column</code> is read by Synapse and written to by Synapse.</li>
  17029. </ol>
  17030. <h4 id="synapse-version-n--1"><a class="header" href="#synapse-version-n--1">Synapse version <code>N + 1</code></a></h4>
  17031. <pre><code class="language-python">SCHEMA_VERSION = S + 1
  17032. SCHEMA_COMPAT_VERSION = ... # unimportant at this stage
  17033. </code></pre>
  17034. <p><strong>Changes:</strong></p>
  17035. <ol>
  17036. <li>
  17037. <pre><code class="language-sql">ALTER TABLE mytable ADD COLUMN new_column INTEGER;
  17038. </code></pre>
  17039. </li>
  17040. </ol>
  17041. <p><strong>Invariants:</strong></p>
  17042. <ol>
  17043. <li><code>old_column</code> is read by Synapse and written to by Synapse.</li>
  17044. <li><code>new_column</code> is written to by Synapse.</li>
  17045. </ol>
  17046. <p><strong>Notes:</strong></p>
  17047. <ol>
  17048. <li><code>new_column</code> can't have a <code>NOT NULL NOT VALID</code> constraint yet, because the previous Synapse version did not write to the new column (since we haven't bumped the <code>SCHEMA_COMPAT_VERSION</code> yet, we still need to be compatible with the previous version).</li>
  17049. </ol>
  17050. <h4 id="synapse-version-n--2"><a class="header" href="#synapse-version-n--2">Synapse version <code>N + 2</code></a></h4>
  17051. <pre><code class="language-python">SCHEMA_VERSION = S + 2
  17052. SCHEMA_COMPAT_VERSION = S + 1 # this signals that we can't roll back to a time before new_column existed
  17053. </code></pre>
  17054. <p><strong>Changes:</strong></p>
  17055. <ol>
  17056. <li>On Postgres, add a <code>NOT VALID</code> constraint to ensure new rows are compliant. <em>SQLite does not have such a construct, but it would be unnecessary anyway since there is no way to concurrently perform this migration on SQLite.</em>
  17057. <pre><code class="language-sql">ALTER TABLE mytable ADD CONSTRAINT CHECK new_column_not_null (new_column IS NOT NULL) NOT VALID;
  17058. </code></pre>
  17059. </li>
  17060. <li>Start a background update to perform migration: it should gradually run e.g.
  17061. <pre><code class="language-sql">UPDATE mytable SET new_column = old_column * 100 WHERE 0 &lt; mytable_id AND mytable_id &lt;= 5;
  17062. </code></pre>
  17063. This background update is technically pointless on SQLite, but you must schedule it anyway so that the <code>portdb</code> script to migrate to Postgres still works.</li>
  17064. <li>Upon completion of the background update, you should run <code>VALIDATE CONSTRAINT</code> on Postgres to turn the <code>NOT VALID</code> constraint into a valid one.
  17065. <pre><code class="language-sql">ALTER TABLE mytable VALIDATE CONSTRAINT new_column_not_null;
  17066. </code></pre>
  17067. This will take some time but does <strong>NOT</strong> hold an exclusive lock over the table.</li>
  17068. </ol>
  17069. <p><strong>Invariants:</strong></p>
  17070. <ol>
  17071. <li><code>old_column</code> is read by Synapse and written to by Synapse.</li>
  17072. <li><code>new_column</code> is written to by Synapse and new rows always have a non-<code>NULL</code> value in this field.</li>
  17073. </ol>
  17074. <p><strong>Notes:</strong></p>
  17075. <ol>
  17076. <li>If you wish, you can convert the <code>CHECK (new_column IS NOT NULL)</code> to a <code>NOT NULL</code> constraint free of charge in Postgres by adding the <code>NOT NULL</code> constraint and then dropping the <code>CHECK</code> constraint, because Postgres can statically verify that the <code>NOT NULL</code> constraint is implied by the <code>CHECK</code> constraint without performing a table scan.</li>
  17077. <li>It might be tempting to make version <code>N + 2</code> redundant by moving the background update to <code>N + 1</code> and delaying adding the <code>NOT NULL</code> constraint to <code>N + 3</code>, but that would mean the constraint would always be validated in the foreground in <code>N + 3</code>. Whereas if the <code>N + 2</code> step is kept, the migration in <code>N + 3</code> would be fast in the happy case.</li>
  17078. </ol>
  17079. <h4 id="synapse-version-n--3"><a class="header" href="#synapse-version-n--3">Synapse version <code>N + 3</code></a></h4>
  17080. <pre><code class="language-python">SCHEMA_VERSION = S + 3
  17081. SCHEMA_COMPAT_VERSION = S + 1 # we can't roll back to a time before new_column existed
  17082. </code></pre>
  17083. <p><strong>Changes:</strong></p>
  17084. <ol>
  17085. <li>(Postgres) Update the table to populate values of <code>new_column</code> in case the background update had not completed. Additionally, <code>VALIDATE CONSTRAINT</code> to make the check fully valid.
  17086. <pre><code class="language-sql">-- you ideally want an index on `new_column` or e.g. `(new_column) WHERE new_column IS NULL` first, or perhaps you can find a way to skip this if the `NOT NULL` constraint has already been validated.
  17087. UPDATE mytable SET new_column = old_column * 100 WHERE new_column IS NULL;
  17088. -- this is a no-op if it already ran as part of the background update
  17089. ALTER TABLE mytable VALIDATE CONSTRAINT new_column_not_null;
  17090. </code></pre>
  17091. </li>
  17092. <li>(SQLite) Recreate the table by precisely following <a href="https://www.sqlite.org/lang_altertable.html#otheralter">the 12-step procedure for SQLite table schema changes</a>.
  17093. During this table rewrite, you should recreate <code>new_column</code> as <code>NOT NULL</code> and populate any outstanding <code>NULL</code> values at the same time.
  17094. Unfortunately, you can't drop <code>old_column</code> yet because it must be present for compatibility with the Postgres schema, as needed by <code>portdb</code>.
  17095. (Otherwise you could do this all in one go with SQLite!)</li>
  17096. </ol>
  17097. <p><strong>Invariants:</strong></p>
  17098. <ol>
  17099. <li><code>old_column</code> is written to by Synapse (but no longer read by Synapse!).</li>
  17100. <li><code>new_column</code> is read by Synapse and written to by Synapse. Moreover, all rows have a non-<code>NULL</code> value in this field, as guaranteed by a schema constraint.</li>
  17101. </ol>
  17102. <p><strong>Notes:</strong></p>
  17103. <ol>
  17104. <li>We can't drop <code>old_column</code> yet, or even stop writing to it, because that would break a rollback to the previous version of Synapse.</li>
  17105. <li>Application code can now rely on <code>new_column</code> being populated. The remaining steps are only motivated by the wish to clean-up old columns.</li>
  17106. </ol>
  17107. <h4 id="synapse-version-n--4"><a class="header" href="#synapse-version-n--4">Synapse version <code>N + 4</code></a></h4>
  17108. <pre><code class="language-python">SCHEMA_VERSION = S + 4
  17109. SCHEMA_COMPAT_VERSION = S + 3 # we can't roll back to a time before new_column was entirely non-NULL
  17110. </code></pre>
  17111. <p><strong>Invariants:</strong></p>
  17112. <ol>
  17113. <li><code>old_column</code> exists but is not written to or read from by Synapse.</li>
  17114. <li><code>new_column</code> is read by Synapse and written to by Synapse. Moreover, all rows have a non-<code>NULL</code> value in this field, as guaranteed by a schema constraint.</li>
  17115. </ol>
  17116. <p><strong>Notes:</strong></p>
  17117. <ol>
  17118. <li>We can't drop <code>old_column</code> yet because that would break a rollback to the previous version of Synapse. <br />
  17119. <strong>TODO:</strong> It may be possible to relax this and drop the column straight away as long as the previous version of Synapse detected a rollback occurred and stopped attempting to write to the column. This could possibly be done by checking whether the database's schema compatibility version was <code>S + 3</code>.</li>
  17120. </ol>
  17121. <h4 id="synapse-version-n--5"><a class="header" href="#synapse-version-n--5">Synapse version <code>N + 5</code></a></h4>
  17122. <pre><code class="language-python">SCHEMA_VERSION = S + 5
  17123. SCHEMA_COMPAT_VERSION = S + 4 # we can't roll back to a time before old_column was no longer being touched
  17124. </code></pre>
  17125. <p><strong>Changes:</strong></p>
  17126. <ol>
  17127. <li>
  17128. <pre><code class="language-sql">ALTER TABLE mytable DROP COLUMN old_column;
  17129. </code></pre>
  17130. </li>
  17131. </ol>
  17132. <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>
  17133. <p>It can be desirable to implement &quot;experimental&quot; features which are disabled by
  17134. default and must be explicitly enabled via the Synapse configuration. This is
  17135. applicable for features which:</p>
  17136. <ul>
  17137. <li>Are unstable in the Matrix spec (e.g. those defined by an MSC that has not yet been merged).</li>
  17138. <li>Developers are not confident in their use by general Synapse administrators/users
  17139. (e.g. a feature is incomplete, buggy, performs poorly, or needs further testing).</li>
  17140. </ul>
  17141. <p>Note that this only really applies to features which are expected to be desirable
  17142. to a broad audience. The <a href="development/../modules/index.html">module infrastructure</a> should
  17143. instead be investigated for non-standard features.</p>
  17144. <p>Guarding experimental features behind configuration flags should help with some
  17145. of the following scenarios:</p>
  17146. <ul>
  17147. <li>Ensure that clients do not assume that unstable features exist (failing
  17148. gracefully if they do not).</li>
  17149. <li>Unstable features do not become de-facto standards and can be removed
  17150. aggressively (since only those who have opted-in will be affected).</li>
  17151. <li>Ease finding the implementation of unstable features in Synapse (for future
  17152. removal or stabilization).</li>
  17153. <li>Ease testing a feature (or removal of feature) due to enabling/disabling without
  17154. code changes. It also becomes possible to ask for wider testing, if desired.</li>
  17155. </ul>
  17156. <p>Experimental configuration flags should be disabled by default (requiring Synapse
  17157. administrators to explicitly opt-in), although there are situations where it makes
  17158. sense (from a product point-of-view) to enable features by default. This is
  17159. expected and not an issue.</p>
  17160. <p>It is not a requirement for experimental features to be behind a configuration flag,
  17161. but one should be used if unsure.</p>
  17162. <p>New experimental configuration flags should be added under the <code>experimental</code>
  17163. configuration key (see the <code>synapse.config.experimental</code> file) and either explain
  17164. (briefly) what is being enabled, or include the MSC number.</p>
  17165. <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>
  17166. <p>This is a quick cheat sheet for developers on how to use <a href="https://python-poetry.org/"><code>poetry</code></a>.</p>
  17167. <h1 id="installing"><a class="header" href="#installing">Installing</a></h1>
  17168. <p>See the <a href="development/contributing_guide.html#4-install-the-dependencies">contributing guide</a>.</p>
  17169. <p>Developers should use Poetry 1.3.2 or higher. If you encounter problems related
  17170. to poetry, please <a href="development/dependencies.html#check-the-version-of-poetry-with-poetry---version">double-check your poetry version</a>.</p>
  17171. <h1 id="background-1"><a class="header" href="#background-1">Background</a></h1>
  17172. <p>Synapse uses a variety of third-party Python packages to function as a homeserver.
  17173. Some of these are direct dependencies, listed in <code>pyproject.toml</code> under the
  17174. <code>[tool.poetry.dependencies]</code> section. The rest are transitive dependencies (the
  17175. things that our direct dependencies themselves depend on, and so on recursively.)</p>
  17176. <p>We maintain a locked list of all our dependencies (transitive included) so that
  17177. we can track exactly which version of each dependency appears in a given release.
  17178. See <a href="https://github.com/matrix-org/synapse/issues/11537#issue-1074469665">here</a>
  17179. for discussion of why we wanted this for Synapse. We chose to use
  17180. <a href="https://python-poetry.org/"><code>poetry</code></a> to manage this locked list; see
  17181. <a href="https://github.com/matrix-org/synapse/issues/11537#issuecomment-1015975819">this comment</a>
  17182. for the reasoning.</p>
  17183. <p>The locked dependencies get included in our &quot;self-contained&quot; releases: namely,
  17184. our docker images and our debian packages. We also use the locked dependencies
  17185. in development and our continuous integration.</p>
  17186. <p>Separately, our &quot;broad&quot; dependencies—the version ranges specified in
  17187. <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
  17188. to PyPI</a>. Installing from PyPI or from
  17189. the Synapse source tree directly will <em>not</em> use the locked dependencies; instead,
  17190. they'll pull in the latest version of each package available at install time.</p>
  17191. <h2 id="example-dependency"><a class="header" href="#example-dependency">Example dependency</a></h2>
  17192. <p>An example may help. We have a broad dependency on
  17193. <a href="https://pypi.org/project/phonenumbers/"><code>phonenumbers</code></a>, as declared in
  17194. 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>
  17195. <pre><code class="language-toml">[tool.poetry.dependencies]
  17196. # ...
  17197. phonenumbers = &quot;&gt;=8.2.0&quot;
  17198. </code></pre>
  17199. <p>In our lockfile this is
  17200. <a href="https://github.com/matrix-org/synapse/blob/dfc7646504cef3e4ff396c36089e1c6f1b1634de/poetry.lock#L679-L685">pinned</a>
  17201. to version 8.12.44, even though
  17202. <a href="https://pypi.org/project/phonenumbers/#history">newer versions are available</a>.</p>
  17203. <pre><code class="language-toml">[[package]]
  17204. name = &quot;phonenumbers&quot;
  17205. version = &quot;8.12.44&quot;
  17206. description = &quot;Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.&quot;
  17207. category = &quot;main&quot;
  17208. optional = false
  17209. python-versions = &quot;*&quot;
  17210. </code></pre>
  17211. <p>The lockfile also includes a
  17212. <a href="https://github.com/matrix-org/synapse/blob/release-v1.57/poetry.lock#L2178-L2181">cryptographic checksum</a>
  17213. of the sdists and wheels provided for this version of <code>phonenumbers</code>.</p>
  17214. <pre><code class="language-toml">[metadata.files]
  17215. # ...
  17216. phonenumbers = [
  17217. {file = &quot;phonenumbers-8.12.44-py2.py3-none-any.whl&quot;, hash = &quot;sha256:cc1299cf37b309ecab6214297663ab86cb3d64ae37fd5b88e904fe7983a874a6&quot;},
  17218. {file = &quot;phonenumbers-8.12.44.tar.gz&quot;, hash = &quot;sha256:26cfd0257d1704fe2f88caff2caabb70d16a877b1e65b6aae51f9fbbe10aa8ce&quot;},
  17219. ]
  17220. </code></pre>
  17221. <p>We can see this pinned version inside the docker image for that release:</p>
  17222. <pre><code>$ docker pull matrixdotorg/synapse:v1.57.0
  17223. ...
  17224. $ docker run --entrypoint pip matrixdotorg/synapse:v1.57.0 show phonenumbers
  17225. Name: phonenumbers
  17226. Version: 8.12.44
  17227. Summary: Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.
  17228. Home-page: https://github.com/daviddrysdale/python-phonenumbers
  17229. Author: David Drysdale
  17230. Author-email: dmd@lurklurk.org
  17231. License: Apache License 2.0
  17232. Location: /usr/local/lib/python3.9/site-packages
  17233. Requires:
  17234. Required-by: matrix-synapse
  17235. </code></pre>
  17236. <p>Whereas the wheel metadata just contains the broad dependencies:</p>
  17237. <pre><code>$ cd /tmp
  17238. $ wget https://files.pythonhosted.org/packages/ca/5e/d722d572cc5b3092402b783d6b7185901b444427633bd8a6b00ea0dd41b7/matrix_synapse-1.57.0rc1-py3-none-any.whl
  17239. ...
  17240. $ unzip -c matrix_synapse-1.57.0rc1-py3-none-any.whl matrix_synapse-1.57.0rc1.dist-info/METADATA | grep phonenumbers
  17241. Requires-Dist: phonenumbers (&gt;=8.2.0)
  17242. </code></pre>
  17243. <h1 id="tooling-recommendation-direnv"><a class="header" href="#tooling-recommendation-direnv">Tooling recommendation: direnv</a></h1>
  17244. <p><a href="https://direnv.net/"><code>direnv</code></a> is a tool for activating environments in your
  17245. shell inside a given directory. Its support for poetry is unofficial (a
  17246. community wiki recipe only), but works solidly in our experience. We thoroughly
  17247. recommend it for daily use. To use it:</p>
  17248. <ol>
  17249. <li><a href="https://direnv.net/docs/installation.html">Install <code>direnv</code></a> - it's likely
  17250. packaged for your system already.</li>
  17251. <li>Teach direnv about poetry. The <a href="https://github.com/direnv/direnv/wiki/Python#poetry">shell config here</a>
  17252. needs to be added to <code>~/.config/direnv/direnvrc</code> (or more generally <code>$XDG_CONFIG_HOME/direnv/direnvrc</code>).</li>
  17253. <li>Mark the synapse checkout as a poetry project: <code>echo layout poetry &gt; .envrc</code>.</li>
  17254. <li>Convince yourself that you trust this <code>.envrc</code> configuration and project.
  17255. Then formally confirm this to <code>direnv</code> by running <code>direnv allow</code>.</li>
  17256. </ol>
  17257. <p>Then whenever you navigate to the synapse checkout, you should be able to run
  17258. e.g. <code>mypy</code> instead of <code>poetry run mypy</code>; <code>python</code> instead of
  17259. <code>poetry run python</code>; and your shell commands will automatically run in the
  17260. context of poetry's venv, without having to run <code>poetry shell</code> beforehand.</p>
  17261. <h1 id="how-do-i"><a class="header" href="#how-do-i">How do I...</a></h1>
  17262. <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>
  17263. <pre><code class="language-shell">poetry install --all-extras --sync
  17264. </code></pre>
  17265. <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>
  17266. <pre><code class="language-shell"># Stop the current virtualenv if active
  17267. $ deactivate
  17268. # Remove all of the files from the current environment.
  17269. # Don't worry, even though it says &quot;all&quot;, this will only
  17270. # remove the Poetry virtualenvs for the current project.
  17271. $ poetry env remove --all
  17272. # Reactivate Poetry shell to create the virtualenv again
  17273. $ poetry shell
  17274. # Install everything again
  17275. $ poetry install --extras all
  17276. </code></pre>
  17277. <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>
  17278. <p>Use <code>poetry run cmd args</code> when you need the python virtualenv context.
  17279. To avoid typing <code>poetry run</code> all the time, you can run <code>poetry shell</code>
  17280. to start a new shell in the poetry virtualenv context. Within <code>poetry shell</code>,
  17281. <code>python</code>, <code>pip</code>, <code>mypy</code>, <code>trial</code>, etc. are all run inside the project virtualenv
  17282. and isolated from the rest o the system.</p>
  17283. <p>Roughly speaking, the translation from a traditional virtualenv is:</p>
  17284. <ul>
  17285. <li><code>env/bin/activate</code> -&gt; <code>poetry shell</code>, and</li>
  17286. <li><code>deactivate</code> -&gt; close the terminal (Ctrl-D, <code>exit</code>, etc.)</li>
  17287. </ul>
  17288. <p>See also the direnv recommendation above, which makes <code>poetry run</code> and
  17289. <code>poetry shell</code> unnecessary.</p>
  17290. <h2 id="inspect-the-poetry-virtualenv"><a class="header" href="#inspect-the-poetry-virtualenv">...inspect the <code>poetry</code> virtualenv?</a></h2>
  17291. <p>Some suggestions:</p>
  17292. <pre><code class="language-shell"># Current env only
  17293. poetry env info
  17294. # All envs: this allows you to have e.g. a poetry managed venv for Python 3.7,
  17295. # and another for Python 3.10.
  17296. poetry env list --full-path
  17297. poetry run pip list
  17298. </code></pre>
  17299. <p>Note that <code>poetry show</code> describes the abstract <em>lock file</em> rather than your
  17300. on-disk environment. With that said, <code>poetry show --tree</code> can sometimes be
  17301. useful.</p>
  17302. <h2 id="add-a-new-dependency"><a class="header" href="#add-a-new-dependency">...add a new dependency?</a></h2>
  17303. <p>Either:</p>
  17304. <ul>
  17305. <li>manually update <code>pyproject.toml</code>; then <code>poetry lock --no-update</code>; or else</li>
  17306. <li><code>poetry add packagename</code>. See <code>poetry add --help</code>; note the <code>--dev</code>,
  17307. <code>--extras</code> and <code>--optional</code> flags in particular.</li>
  17308. </ul>
  17309. <p>Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> files in your commit.</p>
  17310. <h2 id="remove-a-dependency"><a class="header" href="#remove-a-dependency">...remove a dependency?</a></h2>
  17311. <p>This is not done often and is untested, but</p>
  17312. <pre><code class="language-shell">poetry remove packagename
  17313. </code></pre>
  17314. <p>ought to do the trick. Alternatively, manually update <code>pyproject.toml</code> and
  17315. <code>poetry lock --no-update</code>. Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code>
  17316. files in your commit.</p>
  17317. <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>
  17318. <p>Best done by manually editing <code>pyproject.toml</code>, then <code>poetry lock --no-update</code>.
  17319. Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> in your commit.</p>
  17320. <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>
  17321. <p>Use</p>
  17322. <pre><code class="language-shell">poetry update packagename
  17323. </code></pre>
  17324. <p>to use the latest version of <code>packagename</code> in the locked environment, without
  17325. affecting the broad dependencies listed in the wheel.</p>
  17326. <p>There doesn't seem to be a way to do this whilst locking a <em>specific</em> version of
  17327. <code>packagename</code>. We can workaround this (crudely) as follows:</p>
  17328. <pre><code class="language-shell">poetry add packagename==1.2.3
  17329. # This should update pyproject.lock.
  17330. # Now undo the changes to pyproject.toml. For example
  17331. # git restore pyproject.toml
  17332. # Get poetry to recompute the content-hash of pyproject.toml without changing
  17333. # the locked package versions.
  17334. poetry lock --no-update
  17335. </code></pre>
  17336. <p>Either way, include the updated <code>poetry.lock</code> file in your commit.</p>
  17337. <h2 id="export-a-requirementstxt-file"><a class="header" href="#export-a-requirementstxt-file">...export a <code>requirements.txt</code> file?</a></h2>
  17338. <pre><code class="language-shell">poetry export --extras all
  17339. </code></pre>
  17340. <p>Be wary of bugs in <code>poetry export</code> and <code>pip install -r requirements.txt</code>.</p>
  17341. <h2 id="build-a-test-wheel"><a class="header" href="#build-a-test-wheel">...build a test wheel?</a></h2>
  17342. <p>I usually use</p>
  17343. <pre><code class="language-shell">poetry run pip install build &amp;&amp; poetry run python -m build
  17344. </code></pre>
  17345. <p>because <a href="https://github.com/pypa/build"><code>build</code></a> is a standardish tool which
  17346. doesn't require poetry. (It's what we use in CI too). However, you could try
  17347. <code>poetry build</code> too.</p>
  17348. <h2 id="handle-a-dependabot-pull-request"><a class="header" href="#handle-a-dependabot-pull-request">...handle a Dependabot pull request?</a></h2>
  17349. <p>Synapse uses Dependabot to keep the <code>poetry.lock</code> and <code>Cargo.lock</code> file
  17350. up-to-date with the latest releases of our dependencies. The changelog check is
  17351. omitted for Dependabot PRs; the release script will include them in the
  17352. changelog.</p>
  17353. <p>When reviewing a dependabot PR, ensure that:</p>
  17354. <ul>
  17355. <li>the lockfile changes look reasonable;</li>
  17356. <li>the upstream changelog file (linked in the description) doesn't include any
  17357. breaking changes;</li>
  17358. <li>continuous integration passes.</li>
  17359. </ul>
  17360. <p>In particular, any updates to the type hints (usually packages which start with <code>types-</code>)
  17361. should be safe to merge if linting passes.</p>
  17362. <h1 id="troubleshooting-4"><a class="header" href="#troubleshooting-4">Troubleshooting</a></h1>
  17363. <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>
  17364. <p>The minimum version of poetry supported by Synapse is 1.3.2.</p>
  17365. <p>It can also be useful to check the version of <code>poetry-core</code> in use. If you've
  17366. installed <code>poetry</code> with <code>pipx</code>, try <code>pipx runpip poetry list | grep poetry-core</code>.</p>
  17367. <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>
  17368. <p>Poetry caches a bunch of information about packages that isn't readily available
  17369. from PyPI. (This is what makes poetry seem slow when doing the first
  17370. <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>
  17371. <h2 id="remove-outdated-egg-info"><a class="header" href="#remove-outdated-egg-info">Remove outdated egg-info</a></h2>
  17372. <p>Delete the <code>matrix_synapse.egg-info/</code> directory from the root of your Synapse
  17373. install.</p>
  17374. <p>This stores some cached information about dependencies and often conflicts with
  17375. letting Poetry do the right thing.</p>
  17376. <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>
  17377. <p>Sometimes useful to see what poetry's internal logic is.</p>
  17378. <div style="break-before: page; page-break-before: always;"></div><h1 id="cancellation"><a class="header" href="#cancellation">Cancellation</a></h1>
  17379. <p>Sometimes, requests take a long time to service and clients disconnect
  17380. before Synapse produces a response. To avoid wasting resources, Synapse
  17381. can cancel request processing for select endpoints marked with the
  17382. <code>@cancellable</code> decorator.</p>
  17383. <p>Synapse makes use of Twisted's <code>Deferred.cancel()</code> feature to make
  17384. cancellation work. The <code>@cancellable</code> decorator does nothing by itself
  17385. and merely acts as a flag, signalling to developers and other code alike
  17386. that a method can be cancelled.</p>
  17387. <h2 id="enabling-cancellation-for-an-endpoint"><a class="header" href="#enabling-cancellation-for-an-endpoint">Enabling cancellation for an endpoint</a></h2>
  17388. <ol>
  17389. <li>Check that the endpoint method, and any <code>async</code> functions in its call
  17390. tree handle cancellation correctly. See
  17391. <a href="development/synapse_architecture/cancellation.html#handling-cancellation-correctly">Handling cancellation correctly</a>
  17392. for a list of things to look out for.</li>
  17393. <li>Add the <code>@cancellable</code> decorator to the <code>on_GET/POST/PUT/DELETE</code>
  17394. method. It's not recommended to make non-<code>GET</code> methods cancellable,
  17395. since cancellation midway through some database updates is less
  17396. likely to be handled correctly.</li>
  17397. </ol>
  17398. <h2 id="mechanics"><a class="header" href="#mechanics">Mechanics</a></h2>
  17399. <p>There are two stages to cancellation: downward propagation of a
  17400. <code>cancel()</code> call, followed by upwards propagation of a <code>CancelledError</code>
  17401. out of a blocked <code>await</code>.
  17402. Both Twisted and asyncio have a cancellation mechanism.</p>
  17403. <table><thead><tr><th></th><th>Method</th><th>Exception</th><th>Exception inherits from</th></tr></thead><tbody>
  17404. <tr><td>Twisted</td><td><code>Deferred.cancel()</code></td><td><code>twisted.internet.defer.CancelledError</code></td><td><code>Exception</code> (!)</td></tr>
  17405. <tr><td>asyncio</td><td><code>Task.cancel()</code></td><td><code>asyncio.CancelledError</code></td><td><code>BaseException</code></td></tr>
  17406. </tbody></table>
  17407. <h3 id="deferredcancel"><a class="header" href="#deferredcancel">Deferred.cancel()</a></h3>
  17408. <p>When Synapse starts handling a request, it runs the async method
  17409. responsible for handling it using <code>defer.ensureDeferred</code>, which returns
  17410. a <code>Deferred</code>. For example:</p>
  17411. <pre><code class="language-python">def do_something() -&gt; Deferred[None]:
  17412. ...
  17413. @cancellable
  17414. async def on_GET() -&gt; Tuple[int, JsonDict]:
  17415. d = make_deferred_yieldable(do_something())
  17416. await d
  17417. return 200, {}
  17418. request = defer.ensureDeferred(on_GET())
  17419. </code></pre>
  17420. <p>When a client disconnects early, Synapse checks for the presence of the
  17421. <code>@cancellable</code> decorator on <code>on_GET</code>. Since <code>on_GET</code> is cancellable,
  17422. <code>Deferred.cancel()</code> is called on the <code>Deferred</code> from
  17423. <code>defer.ensureDeferred</code>, ie. <code>request</code>. Twisted knows which <code>Deferred</code>
  17424. <code>request</code> is waiting on and passes the <code>cancel()</code> call on to <code>d</code>.</p>
  17425. <p>The <code>Deferred</code> being waited on, <code>d</code>, may have its own handling for
  17426. <code>cancel()</code> and pass the call on to other <code>Deferred</code>s.</p>
  17427. <p>Eventually, a <code>Deferred</code> handles the <code>cancel()</code> call by resolving itself
  17428. with a <code>CancelledError</code>.</p>
  17429. <h3 id="cancellederror"><a class="header" href="#cancellederror">CancelledError</a></h3>
  17430. <p>The <code>CancelledError</code> gets raised out of the <code>await</code> and bubbles up, as
  17431. per normal Python exception handling.</p>
  17432. <h2 id="handling-cancellation-correctly"><a class="header" href="#handling-cancellation-correctly">Handling cancellation correctly</a></h2>
  17433. <p>In general, when writing code that might be subject to cancellation, two
  17434. things must be considered:</p>
  17435. <ul>
  17436. <li>The effect of <code>CancelledError</code>s raised out of <code>await</code>s.</li>
  17437. <li>The effect of <code>Deferred</code>s being <code>cancel()</code>ed.</li>
  17438. </ul>
  17439. <p>Examples of code that handles cancellation incorrectly include:</p>
  17440. <ul>
  17441. <li><code>try-except</code> blocks which swallow <code>CancelledError</code>s.</li>
  17442. <li>Code that shares the same <code>Deferred</code>, which may be cancelled, between
  17443. multiple requests.</li>
  17444. <li>Code that starts some processing that's exempt from cancellation, but
  17445. uses a logging context from cancellable code. The logging context
  17446. will be finished upon cancellation, while the uncancelled processing
  17447. is still using it.</li>
  17448. </ul>
  17449. <p>Some common patterns are listed below in more detail.</p>
  17450. <h3 id="async-function-calls"><a class="header" href="#async-function-calls"><code>async</code> function calls</a></h3>
  17451. <p>Most functions in Synapse are relatively straightforward from a
  17452. cancellation standpoint: they don't do anything with <code>Deferred</code>s and
  17453. purely call and <code>await</code> other <code>async</code> functions.</p>
  17454. <p>An <code>async</code> function handles cancellation correctly if its own code
  17455. handles cancellation correctly and all the async function it calls
  17456. handle cancellation correctly. For example:</p>
  17457. <pre><code class="language-python">async def do_two_things() -&gt; None:
  17458. check_something()
  17459. await do_something()
  17460. await do_something_else()
  17461. </code></pre>
  17462. <p><code>do_two_things</code> handles cancellation correctly if <code>do_something</code> and
  17463. <code>do_something_else</code> handle cancellation correctly.</p>
  17464. <p>That is, when checking whether a function handles cancellation
  17465. correctly, its implementation and all its <code>async</code> function calls need to
  17466. be checked, recursively.</p>
  17467. <p>As <code>check_something</code> is not <code>async</code>, it does not need to be checked.</p>
  17468. <h3 id="cancellederrors"><a class="header" href="#cancellederrors">CancelledErrors</a></h3>
  17469. <p>Because Twisted's <code>CancelledError</code>s are <code>Exception</code>s, it's easy to
  17470. accidentally catch and suppress them. Care must be taken to ensure that
  17471. <code>CancelledError</code>s are allowed to propagate upwards.</p>
  17472. <table width="100%">
  17473. <tr>
  17474. <td width="50%" valign="top">
  17475. <p><strong>Bad</strong>:</p>
  17476. <pre><code class="language-python">try:
  17477. await do_something()
  17478. except Exception:
  17479. # `CancelledError` gets swallowed here.
  17480. logger.info(...)
  17481. </code></pre>
  17482. </td>
  17483. <td width="50%" valign="top">
  17484. <p><strong>Good</strong>:</p>
  17485. <pre><code class="language-python">try:
  17486. await do_something()
  17487. except CancelledError:
  17488. raise
  17489. except Exception:
  17490. logger.info(...)
  17491. </code></pre>
  17492. </td>
  17493. </tr>
  17494. <tr>
  17495. <td width="50%" valign="top">
  17496. <p><strong>OK</strong>:</p>
  17497. <pre><code class="language-python">try:
  17498. check_something()
  17499. # A `CancelledError` won't ever be raised here.
  17500. except Exception:
  17501. logger.info(...)
  17502. </code></pre>
  17503. </td>
  17504. <td width="50%" valign="top">
  17505. <p><strong>Good</strong>:</p>
  17506. <pre><code class="language-python">try:
  17507. await do_something()
  17508. except ValueError:
  17509. logger.info(...)
  17510. </code></pre>
  17511. </td>
  17512. </tr>
  17513. </table>
  17514. <h4 id="defergatherresults"><a class="header" href="#defergatherresults">defer.gatherResults</a></h4>
  17515. <p><code>defer.gatherResults</code> produces a <code>Deferred</code> which:</p>
  17516. <ul>
  17517. <li>broadcasts <code>cancel()</code> calls to every <code>Deferred</code> being waited on.</li>
  17518. <li>wraps the first exception it sees in a <code>FirstError</code>.</li>
  17519. </ul>
  17520. <p>Together, this means that <code>CancelledError</code>s will be wrapped in
  17521. a <code>FirstError</code> unless unwrapped. Such <code>FirstError</code>s are liable to be
  17522. swallowed, so they must be unwrapped.</p>
  17523. <table width="100%">
  17524. <tr>
  17525. <td width="50%" valign="top">
  17526. <p><strong>Bad</strong>:</p>
  17527. <pre><code class="language-python">async def do_something() -&gt; None:
  17528. await make_deferred_yieldable(
  17529. defer.gatherResults([...], consumeErrors=True)
  17530. )
  17531. try:
  17532. await do_something()
  17533. except CancelledError:
  17534. raise
  17535. except Exception:
  17536. # `FirstError(CancelledError)` gets swallowed here.
  17537. logger.info(...)
  17538. </code></pre>
  17539. </td>
  17540. <td width="50%" valign="top">
  17541. <p><strong>Good</strong>:</p>
  17542. <pre><code class="language-python">async def do_something() -&gt; None:
  17543. await make_deferred_yieldable(
  17544. defer.gatherResults([...], consumeErrors=True)
  17545. ).addErrback(unwrapFirstError)
  17546. try:
  17547. await do_something()
  17548. except CancelledError:
  17549. raise
  17550. except Exception:
  17551. logger.info(...)
  17552. </code></pre>
  17553. </td>
  17554. </tr>
  17555. </table>
  17556. <h3 id="creation-of-deferreds"><a class="header" href="#creation-of-deferreds">Creation of <code>Deferred</code>s</a></h3>
  17557. <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>
  17558. <table width="100%">
  17559. <tr>
  17560. <td width="50%" valign="top">
  17561. <p><strong>Bad</strong>:</p>
  17562. <pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}
  17563. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  17564. deferred = cache.get(room_id)
  17565. if deferred is None:
  17566. deferred = Deferred()
  17567. cache[room_id] = deferred
  17568. # `deferred` can have multiple waiters.
  17569. # All of them will observe a `CancelledError`
  17570. # if any one of them is cancelled.
  17571. return make_deferred_yieldable(deferred)
  17572. # Request 1
  17573. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17574. # Request 2
  17575. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17576. </code></pre>
  17577. </td>
  17578. <td width="50%" valign="top">
  17579. <p><strong>Good</strong>:</p>
  17580. <pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}
  17581. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  17582. deferred = cache.get(room_id)
  17583. if deferred is None:
  17584. deferred = Deferred()
  17585. cache[room_id] = deferred
  17586. # `deferred` will never be cancelled now.
  17587. # A `CancelledError` will still come out of
  17588. # the `await`.
  17589. # `delay_cancellation` may also be used.
  17590. return make_deferred_yieldable(stop_cancellation(deferred))
  17591. # Request 1
  17592. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17593. # Request 2
  17594. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17595. </code></pre>
  17596. </td>
  17597. </tr>
  17598. <tr>
  17599. <td width="50%" valign="top">
  17600. </td>
  17601. <td width="50%" valign="top">
  17602. <p><strong>Good</strong>:</p>
  17603. <pre><code class="language-python">cache: Dict[str, List[Deferred[None]]] = {}
  17604. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  17605. if room_id not in cache:
  17606. cache[room_id] = []
  17607. # Each request gets its own `Deferred` to wait on.
  17608. deferred = Deferred()
  17609. cache[room_id]].append(deferred)
  17610. return make_deferred_yieldable(deferred)
  17611. # Request 1
  17612. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17613. # Request 2
  17614. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  17615. </code></pre>
  17616. </td>
  17617. </table>
  17618. <h3 id="uncancelled-processing"><a class="header" href="#uncancelled-processing">Uncancelled processing</a></h3>
  17619. <p>Some <code>async</code> functions may kick off some <code>async</code> processing which is
  17620. intentionally protected from cancellation, by <code>stop_cancellation</code> or
  17621. other means. If the <code>async</code> processing inherits the logcontext of the
  17622. request which initiated it, care must be taken to ensure that the
  17623. logcontext is not finished before the <code>async</code> processing completes.</p>
  17624. <table width="100%">
  17625. <tr>
  17626. <td width="50%" valign="top">
  17627. <p><strong>Bad</strong>:</p>
  17628. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  17629. async def do_something_else(
  17630. to_resolve: Deferred[None]
  17631. ) -&gt; None:
  17632. await ...
  17633. logger.info(&quot;done!&quot;)
  17634. to_resolve.callback(None)
  17635. async def do_something() -&gt; None:
  17636. if not cache:
  17637. to_resolve = Deferred()
  17638. cache = ObservableDeferred(to_resolve)
  17639. # `do_something_else` will never be cancelled and
  17640. # can outlive the `request-1` logging context.
  17641. run_in_background(do_something_else, to_resolve)
  17642. await make_deferred_yieldable(cache.observe())
  17643. with LoggingContext(&quot;request-1&quot;):
  17644. await do_something()
  17645. </code></pre>
  17646. </td>
  17647. <td width="50%" valign="top">
  17648. <p><strong>Good</strong>:</p>
  17649. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  17650. async def do_something_else(
  17651. to_resolve: Deferred[None]
  17652. ) -&gt; None:
  17653. await ...
  17654. logger.info(&quot;done!&quot;)
  17655. to_resolve.callback(None)
  17656. async def do_something() -&gt; None:
  17657. if not cache:
  17658. to_resolve = Deferred()
  17659. cache = ObservableDeferred(to_resolve)
  17660. run_in_background(do_something_else, to_resolve)
  17661. # We'll wait until `do_something_else` is
  17662. # done before raising a `CancelledError`.
  17663. await make_deferred_yieldable(
  17664. delay_cancellation(cache.observe())
  17665. )
  17666. else:
  17667. await make_deferred_yieldable(cache.observe())
  17668. with LoggingContext(&quot;request-1&quot;):
  17669. await do_something()
  17670. </code></pre>
  17671. </td>
  17672. </tr>
  17673. <tr>
  17674. <td width="50%">
  17675. <p><strong>OK</strong>:</p>
  17676. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  17677. async def do_something_else(
  17678. to_resolve: Deferred[None]
  17679. ) -&gt; None:
  17680. await ...
  17681. logger.info(&quot;done!&quot;)
  17682. to_resolve.callback(None)
  17683. async def do_something() -&gt; None:
  17684. if not cache:
  17685. to_resolve = Deferred()
  17686. cache = ObservableDeferred(to_resolve)
  17687. # `do_something_else` will get its own independent
  17688. # logging context. `request-1` will not count any
  17689. # metrics from `do_something_else`.
  17690. run_as_background_process(
  17691. &quot;do_something_else&quot;,
  17692. do_something_else,
  17693. to_resolve,
  17694. )
  17695. await make_deferred_yieldable(cache.observe())
  17696. with LoggingContext(&quot;request-1&quot;):
  17697. await do_something()
  17698. </code></pre>
  17699. </td>
  17700. <td width="50%">
  17701. </td>
  17702. </tr>
  17703. </table>
  17704. <div style="break-before: page; page-break-before: always;"></div><h1 id="log-contexts"><a class="header" href="#log-contexts">Log Contexts</a></h1>
  17705. <p>To help track the processing of individual requests, synapse uses a
  17706. '<code>log context</code>' to track which request it is handling at any given
  17707. moment. This is done via a thread-local variable; a <code>logging.Filter</code> is
  17708. then used to fish the information back out of the thread-local variable
  17709. and add it to each log record.</p>
  17710. <p>Logcontexts are also used for CPU and database accounting, so that we
  17711. can track which requests were responsible for high CPU use or database
  17712. activity.</p>
  17713. <p>The <code>synapse.logging.context</code> module provides facilities for managing
  17714. the current log context (as well as providing the <code>LoggingContextFilter</code>
  17715. class).</p>
  17716. <p>Asynchronous functions make the whole thing complicated, so this document describes
  17717. how it all works, and how to write code which follows the rules.</p>
  17718. <p>In this document, &quot;awaitable&quot; refers to any object which can be <code>await</code>ed. In the context of
  17719. Synapse, that normally means either a coroutine or a Twisted
  17720. <a href="https://twistedmatrix.com/documents/current/api/twisted.internet.defer.Deferred.html"><code>Deferred</code></a>.</p>
  17721. <h2 id="logcontexts-without-asynchronous-code"><a class="header" href="#logcontexts-without-asynchronous-code">Logcontexts without asynchronous code</a></h2>
  17722. <p>In the absence of any asynchronous voodoo, things are simple enough. As with
  17723. any code of this nature, the rule is that our function should leave
  17724. things as it found them:</p>
  17725. <pre><code class="language-python">from synapse.logging import context # omitted from future snippets
  17726. def handle_request(request_id):
  17727. request_context = context.LoggingContext()
  17728. calling_context = context.set_current_context(request_context)
  17729. try:
  17730. request_context.request = request_id
  17731. do_request_handling()
  17732. logger.debug(&quot;finished&quot;)
  17733. finally:
  17734. context.set_current_context(calling_context)
  17735. def do_request_handling():
  17736. logger.debug(&quot;phew&quot;) # this will be logged against request_id
  17737. </code></pre>
  17738. <p>LoggingContext implements the context management methods, so the above
  17739. can be written much more succinctly as:</p>
  17740. <pre><code class="language-python">def handle_request(request_id):
  17741. with context.LoggingContext() as request_context:
  17742. request_context.request = request_id
  17743. do_request_handling()
  17744. logger.debug(&quot;finished&quot;)
  17745. def do_request_handling():
  17746. logger.debug(&quot;phew&quot;)
  17747. </code></pre>
  17748. <h2 id="using-logcontexts-with-awaitables"><a class="header" href="#using-logcontexts-with-awaitables">Using logcontexts with awaitables</a></h2>
  17749. <p>Awaitables break the linear flow of code so that there is no longer a single entry point
  17750. where we should set the logcontext and a single exit point where we should remove it.</p>
  17751. <p>Consider the example above, where <code>do_request_handling</code> needs to do some
  17752. blocking operation, and returns an awaitable:</p>
  17753. <pre><code class="language-python">async def handle_request(request_id):
  17754. with context.LoggingContext() as request_context:
  17755. request_context.request = request_id
  17756. await do_request_handling()
  17757. logger.debug(&quot;finished&quot;)
  17758. </code></pre>
  17759. <p>In the above flow:</p>
  17760. <ul>
  17761. <li>The logcontext is set</li>
  17762. <li><code>do_request_handling</code> is called, and returns an awaitable</li>
  17763. <li><code>handle_request</code> awaits the awaitable</li>
  17764. <li>Execution of <code>handle_request</code> is suspended</li>
  17765. </ul>
  17766. <p>So we have stopped processing the request (and will probably go on to
  17767. start processing the next), without clearing the logcontext.</p>
  17768. <p>To circumvent this problem, synapse code assumes that, wherever you have
  17769. an awaitable, you will want to <code>await</code> it. To that end, wherever
  17770. functions return awaitables, we adopt the following conventions:</p>
  17771. <p><strong>Rules for functions returning awaitables:</strong></p>
  17772. <blockquote>
  17773. <ul>
  17774. <li>If the awaitable is already complete, the function returns with the
  17775. same logcontext it started with.</li>
  17776. <li>If the awaitable is incomplete, the function clears the logcontext
  17777. before returning; when the awaitable completes, it restores the
  17778. logcontext before running any callbacks.</li>
  17779. </ul>
  17780. </blockquote>
  17781. <p>That sounds complicated, but actually it means a lot of code (including
  17782. the example above) &quot;just works&quot;. There are two cases:</p>
  17783. <ul>
  17784. <li>
  17785. <p>If <code>do_request_handling</code> returns a completed awaitable, then the
  17786. logcontext will still be in place. In this case, execution will
  17787. continue immediately after the <code>await</code>; the &quot;finished&quot; line will
  17788. be logged against the right context, and the <code>with</code> block restores
  17789. the original context before we return to the caller.</p>
  17790. </li>
  17791. <li>
  17792. <p>If the returned awaitable is incomplete, <code>do_request_handling</code> clears
  17793. the logcontext before returning. The logcontext is therefore clear
  17794. when <code>handle_request</code> <code>await</code>s the awaitable.</p>
  17795. <p>Once <code>do_request_handling</code>'s awaitable completes, it will reinstate
  17796. the logcontext, before running the second half of <code>handle_request</code>,
  17797. so again the &quot;finished&quot; line will be logged against the right context,
  17798. and the <code>with</code> block restores the original context.</p>
  17799. </li>
  17800. </ul>
  17801. <p>As an aside, it's worth noting that <code>handle_request</code> follows our rules</p>
  17802. <ul>
  17803. <li>though that only matters if the caller has its own logcontext which it
  17804. cares about.</li>
  17805. </ul>
  17806. <p>The following sections describe pitfalls and helpful patterns when
  17807. implementing these rules.</p>
  17808. <h2 id="always-await-your-awaitables"><a class="header" href="#always-await-your-awaitables">Always await your awaitables</a></h2>
  17809. <p>Whenever you get an awaitable back from a function, you should <code>await</code> on
  17810. it as soon as possible. Do not pass go; do not do any logging; do not
  17811. call any other functions.</p>
  17812. <pre><code class="language-python">async def fun():
  17813. logger.debug(&quot;starting&quot;)
  17814. await do_some_stuff() # just like this
  17815. coro = more_stuff()
  17816. result = await coro # also fine, of course
  17817. return result
  17818. </code></pre>
  17819. <p>Provided this pattern is followed all the way back up to the callchain
  17820. to where the logcontext was set, this will make things work out ok:
  17821. provided <code>do_some_stuff</code> and <code>more_stuff</code> follow the rules above, then
  17822. so will <code>fun</code>.</p>
  17823. <p>It's all too easy to forget to <code>await</code>: for instance if we forgot that
  17824. <code>do_some_stuff</code> returned an awaitable, we might plough on regardless. This
  17825. leads to a mess; it will probably work itself out eventually, but not
  17826. before a load of stuff has been logged against the wrong context.
  17827. (Normally, other things will break, more obviously, if you forget to
  17828. <code>await</code>, so this tends not to be a major problem in practice.)</p>
  17829. <p>Of course sometimes you need to do something a bit fancier with your
  17830. awaitable - not all code follows the linear A-then-B-then-C pattern.
  17831. Notes on implementing more complex patterns are in later sections.</p>
  17832. <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>
  17833. <p>Most of the time, an awaitable comes from another synapse function.
  17834. Sometimes, though, we need to make up a new awaitable, or we get an awaitable
  17835. back from external code. We need to make it follow our rules.</p>
  17836. <p>The easy way to do it is by using <code>context.make_deferred_yieldable</code>. Suppose we want to implement
  17837. <code>sleep</code>, which returns a deferred which will run its callbacks after a
  17838. given number of seconds. That might look like:</p>
  17839. <pre><code class="language-python"># not a logcontext-rules-compliant function
  17840. def get_sleep_deferred(seconds):
  17841. d = defer.Deferred()
  17842. reactor.callLater(seconds, d.callback, None)
  17843. return d
  17844. </code></pre>
  17845. <p>That doesn't follow the rules, but we can fix it by calling it through
  17846. <code>context.make_deferred_yieldable</code>:</p>
  17847. <pre><code class="language-python">async def sleep(seconds):
  17848. return await context.make_deferred_yieldable(get_sleep_deferred(seconds))
  17849. </code></pre>
  17850. <h2 id="fire-and-forget"><a class="header" href="#fire-and-forget">Fire-and-forget</a></h2>
  17851. <p>Sometimes you want to fire off a chain of execution, but not wait for
  17852. its result. That might look a bit like this:</p>
  17853. <pre><code class="language-python">async def do_request_handling():
  17854. await foreground_operation()
  17855. # *don't* do this
  17856. background_operation()
  17857. logger.debug(&quot;Request handling complete&quot;)
  17858. async def background_operation():
  17859. await first_background_step()
  17860. logger.debug(&quot;Completed first step&quot;)
  17861. await second_background_step()
  17862. logger.debug(&quot;Completed second step&quot;)
  17863. </code></pre>
  17864. <p>The above code does a couple of steps in the background after
  17865. <code>do_request_handling</code> has finished. The log lines are still logged
  17866. against the <code>request_context</code> logcontext, which may or may not be
  17867. desirable. There are two big problems with the above, however. The first
  17868. problem is that, if <code>background_operation</code> returns an incomplete
  17869. awaitable, it will expect its caller to <code>await</code> immediately, so will have
  17870. cleared the logcontext. In this example, that means that 'Request
  17871. handling complete' will be logged without any context.</p>
  17872. <p>The second problem, which is potentially even worse, is that when the
  17873. awaitable returned by <code>background_operation</code> completes, it will restore
  17874. the original logcontext. There is nothing waiting on that awaitable, so
  17875. the logcontext will leak into the reactor and possibly get attached to
  17876. some arbitrary future operation.</p>
  17877. <p>There are two potential solutions to this.</p>
  17878. <p>One option is to surround the call to <code>background_operation</code> with a
  17879. <code>PreserveLoggingContext</code> call. That will reset the logcontext before
  17880. starting <code>background_operation</code> (so the context restored when the
  17881. deferred completes will be the empty logcontext), and will restore the
  17882. current logcontext before continuing the foreground process:</p>
  17883. <pre><code class="language-python">async def do_request_handling():
  17884. await foreground_operation()
  17885. # start background_operation off in the empty logcontext, to
  17886. # avoid leaking the current context into the reactor.
  17887. with PreserveLoggingContext():
  17888. background_operation()
  17889. # this will now be logged against the request context
  17890. logger.debug(&quot;Request handling complete&quot;)
  17891. </code></pre>
  17892. <p>Obviously that option means that the operations done in
  17893. <code>background_operation</code> would be not be logged against a logcontext
  17894. (though that might be fixed by setting a different logcontext via a
  17895. <code>with LoggingContext(...)</code> in <code>background_operation</code>).</p>
  17896. <p>The second option is to use <code>context.run_in_background</code>, which wraps a
  17897. function so that it doesn't reset the logcontext even when it returns
  17898. an incomplete awaitable, and adds a callback to the returned awaitable to
  17899. reset the logcontext. In other words, it turns a function that follows
  17900. the Synapse rules about logcontexts and awaitables into one which behaves
  17901. more like an external function --- the opposite operation to that
  17902. described in the previous section. It can be used like this:</p>
  17903. <pre><code class="language-python">async def do_request_handling():
  17904. await foreground_operation()
  17905. context.run_in_background(background_operation)
  17906. # this will now be logged against the request context
  17907. logger.debug(&quot;Request handling complete&quot;)
  17908. </code></pre>
  17909. <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>
  17910. <p>A typical example of this is where we want to collect together two or
  17911. more awaitables via <code>defer.gatherResults</code>:</p>
  17912. <pre><code class="language-python">a1 = operation1()
  17913. a2 = operation2()
  17914. a3 = defer.gatherResults([a1, a2])
  17915. </code></pre>
  17916. <p>This is really a variation of the fire-and-forget problem above, in that
  17917. we are firing off <code>a1</code> and <code>a2</code> without awaiting on them. The difference
  17918. is that we now have third-party code attached to their callbacks. Anyway
  17919. either technique given in the <a href="log_contexts.html#fire-and-forget">Fire-and-forget</a>
  17920. section will work.</p>
  17921. <p>Of course, the new awaitable returned by <code>gather</code> needs to be
  17922. wrapped in order to make it follow the logcontext rules before we can
  17923. 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
  17924. follow the
  17925. rules</a>.</p>
  17926. <p>So, option one: reset the logcontext before starting the operations to
  17927. be gathered:</p>
  17928. <pre><code class="language-python">async def do_request_handling():
  17929. with PreserveLoggingContext():
  17930. a1 = operation1()
  17931. a2 = operation2()
  17932. result = await defer.gatherResults([a1, a2])
  17933. </code></pre>
  17934. <p>In this case particularly, though, option two, of using
  17935. <code>context.run_in_background</code> almost certainly makes more sense, so that
  17936. <code>operation1</code> and <code>operation2</code> are both logged against the original
  17937. logcontext. This looks like:</p>
  17938. <pre><code class="language-python">async def do_request_handling():
  17939. a1 = context.run_in_background(operation1)
  17940. a2 = context.run_in_background(operation2)
  17941. result = await make_deferred_yieldable(defer.gatherResults([a1, a2]))
  17942. </code></pre>
  17943. <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>
  17944. <p>It turns out that our logcontext rules do not play nicely with awaitable
  17945. chains which get orphaned and garbage-collected.</p>
  17946. <p>Imagine we have some code that looks like this:</p>
  17947. <pre><code class="language-python">listener_queue = []
  17948. def on_something_interesting():
  17949. for d in listener_queue:
  17950. d.callback(&quot;foo&quot;)
  17951. async def await_something_interesting():
  17952. new_awaitable = defer.Deferred()
  17953. listener_queue.append(new_awaitable)
  17954. with PreserveLoggingContext():
  17955. await new_awaitable
  17956. </code></pre>
  17957. <p>Obviously, the idea here is that we have a bunch of things which are
  17958. waiting for an event. (It's just an example of the problem here, but a
  17959. relatively common one.)</p>
  17960. <p>Now let's imagine two further things happen. First of all, whatever was
  17961. waiting for the interesting thing goes away. (Perhaps the request times
  17962. out, or something <em>even more</em> interesting happens.)</p>
  17963. <p>Secondly, let's suppose that we decide that the interesting thing is
  17964. never going to happen, and we reset the listener queue:</p>
  17965. <pre><code class="language-python">def reset_listener_queue():
  17966. listener_queue.clear()
  17967. </code></pre>
  17968. <p>So, both ends of the awaitable chain have now dropped their references,
  17969. and the awaitable chain is now orphaned, and will be garbage-collected at
  17970. some point. Note that <code>await_something_interesting</code> is a coroutine,
  17971. which Python implements as a generator function. When Python
  17972. garbage-collects generator functions, it gives them a chance to
  17973. clean up by making the <code>await</code> (or <code>yield</code>) raise a <code>GeneratorExit</code>
  17974. exception. In our case, that means that the <code>__exit__</code> handler of
  17975. <code>PreserveLoggingContext</code> will carefully restore the request context, but
  17976. there is now nothing waiting for its return, so the request context is
  17977. never cleared.</p>
  17978. <p>To reiterate, this problem only arises when <em>both</em> ends of a awaitable
  17979. chain are dropped. Dropping the the reference to an awaitable you're
  17980. supposed to be awaiting is bad practice, so this doesn't
  17981. actually happen too much. Unfortunately, when it does happen, it will
  17982. lead to leaked logcontexts which are incredibly hard to track down.</p>
  17983. <div style="break-before: page; page-break-before: always;"></div><h1 id="replication-architecture"><a class="header" href="#replication-architecture">Replication Architecture</a></h1>
  17984. <h2 id="motivation"><a class="header" href="#motivation">Motivation</a></h2>
  17985. <p>We'd like to be able to split some of the work that synapse does into
  17986. multiple python processes. In theory multiple synapse processes could
  17987. share a single postgresql database and we'd scale up by running more
  17988. synapse processes. However much of synapse assumes that only one process
  17989. is interacting with the database, both for assigning unique identifiers
  17990. when inserting into tables, notifying components about new updates, and
  17991. for invalidating its caches.</p>
  17992. <p>So running multiple copies of the current code isn't an option. One way
  17993. to run multiple processes would be to have a single writer process and
  17994. multiple reader processes connected to the same database. In order to do
  17995. this we'd need a way for the reader process to invalidate its in-memory
  17996. caches when an update happens on the writer. One way to do this is for
  17997. the writer to present an append-only log of updates which the readers
  17998. can consume to invalidate their caches and to push updates to listening
  17999. clients or pushers.</p>
  18000. <p>Synapse already stores much of its data as an append-only log so that it
  18001. can correctly respond to <code>/sync</code> requests so the amount of code changes
  18002. needed to expose the append-only log to the readers should be fairly
  18003. minimal.</p>
  18004. <h2 id="architecture"><a class="header" href="#architecture">Architecture</a></h2>
  18005. <h3 id="the-replication-protocol"><a class="header" href="#the-replication-protocol">The Replication Protocol</a></h3>
  18006. <p>See <a href="tcp_replication.html">the TCP replication documentation</a>.</p>
  18007. <h3 id="the-tcp-replication-module"><a class="header" href="#the-tcp-replication-module">The TCP Replication Module</a></h3>
  18008. <p>Information about how the tcp replication module is structured, including how
  18009. the classes interact, can be found in
  18010. <code>synapse/replication/tcp/__init__.py</code></p>
  18011. <div style="break-before: page; page-break-before: always;"></div><h2 id="streams"><a class="header" href="#streams">Streams</a></h2>
  18012. <p>Synapse has a concept of &quot;streams&quot;, which are roughly described in <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/storage/util/id_generators.py"><code>id_generators.py</code></a>.
  18013. Generally speaking, streams are a series of notifications that something in Synapse's database has changed that the application might need to respond to.
  18014. For example:</p>
  18015. <ul>
  18016. <li>The events stream reports new events (PDUs) that Synapse creates, or that Synapse accepts from another homeserver.</li>
  18017. <li>The account data stream reports changes to users' <a href="https://spec.matrix.org/v1.7/client-server-api/#client-config">account data</a>.</li>
  18018. <li>The to-device stream reports when a device has a new <a href="https://spec.matrix.org/v1.7/client-server-api/#send-to-device-messaging">to-device message</a>.</li>
  18019. </ul>
  18020. <p>See <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/replication/tcp/streams/__init__.py"><code>synapse.replication.tcp.streams</code></a> for the full list of streams.</p>
  18021. <p>It is very helpful to understand the streams mechanism when working on any part of Synapse that needs to respond to changes—especially if those changes are made by different workers.
  18022. To that end, let's describe streams formally, paraphrasing from the docstring of <a href="https://github.com/matrix-org/synapse/blob/a719b703d9bd0dade2565ddcad0e2f3a7a9d4c37/synapse/storage/util/id_generators.py#L96"><code>AbstractStreamIdGenerator</code></a>.</p>
  18023. <h3 id="definition"><a class="header" href="#definition">Definition</a></h3>
  18024. <p>A stream is an append-only log <code>T1, T2, ..., Tn, ...</code> of facts<sup class="footnote-reference"><a href="#1">1</a></sup> which grows over time.
  18025. Only &quot;writers&quot; can add facts to a stream, and there may be multiple writers.</p>
  18026. <p>Each fact has an ID, called its &quot;stream ID&quot;.
  18027. Readers should only process facts in ascending stream ID order.</p>
  18028. <p>Roughly speaking, each stream is backed by a database table.
  18029. It should have a <code>stream_id</code> (or similar) bigint column holding stream IDs, plus additional columns as necessary to describe the fact.
  18030. Typically, a fact is expressed with a single row in its backing table.<sup class="footnote-reference"><a href="#2">2</a></sup>
  18031. Within a stream, no two facts may have the same stream_id.</p>
  18032. <blockquote>
  18033. <p><em>Aside</em>. Some additional notes on streams' backing tables.</p>
  18034. <ol>
  18035. <li>Rich would like to <a href="https://github.com/matrix-org/synapse/issues/13456">ditch the backing tables</a>.</li>
  18036. <li>The backing tables may have other uses.
  18037. &gt; For example, the events table serves backs the events stream, and is read when processing new events.
  18038. &gt; But old rows are read from the table all the time, whenever Synapse needs to lookup some facts about an event.</li>
  18039. <li>Rich suspects that sometimes the stream is backed by multiple tables, so the stream proper is the union of those tables.</li>
  18040. </ol>
  18041. </blockquote>
  18042. <p>Stream writers can &quot;reserve&quot; a stream ID, and then later mark it as having being completed.
  18043. Stream writers need to track the completion of each stream fact.
  18044. In the happy case, completion means a fact has been written to the stream table.
  18045. But unhappy cases (e.g. transaction rollback due to an error) also count as completion.
  18046. Once completed, the rows written with that stream ID are fixed, and no new rows
  18047. will be inserted with that ID.</p>
  18048. <h3 id="current-stream-id"><a class="header" href="#current-stream-id">Current stream ID</a></h3>
  18049. <p>For any given stream reader (including writers themselves), we may define a per-writer current stream ID:</p>
  18050. <blockquote>
  18051. <p>The current stream ID <em>for a writer W</em> is the largest stream ID such that
  18052. all transactions added by W with equal or smaller ID have completed.</p>
  18053. </blockquote>
  18054. <p>Similarly, there is a &quot;linear&quot; notion of current stream ID:</p>
  18055. <blockquote>
  18056. <p>The &quot;linear&quot; current stream ID is the largest stream ID such that
  18057. all facts (added by any writer) with equal or smaller ID have completed.</p>
  18058. </blockquote>
  18059. <p>Because different stream readers A and B learn about new facts at different times, A and B may disagree about current stream IDs.
  18060. Put differently: we should think of stream readers as being independent of each other, proceeding through a stream of facts at different rates.</p>
  18061. <p><strong>NB.</strong> For both senses of &quot;current&quot;, that if a writer opens a transaction that never completes, the current stream ID will never advance beyond that writer's last written stream ID.</p>
  18062. <p>For single-writer streams, the per-writer current ID and the linear current ID are the same.
  18063. Both senses of current ID are monotonic, but they may &quot;skip&quot; or jump over IDs because facts complete out of order.</p>
  18064. <p><em>Example</em>.
  18065. Consider a single-writer stream which is initially at ID 1.</p>
  18066. <table><thead><tr><th>Action</th><th>Current stream ID</th><th>Notes</th></tr></thead><tbody>
  18067. <tr><td></td><td>1</td><td></td></tr>
  18068. <tr><td>Reserve 2</td><td>1</td><td></td></tr>
  18069. <tr><td>Reserve 3</td><td>1</td><td></td></tr>
  18070. <tr><td>Complete 3</td><td>1</td><td>current ID unchanged, waiting for 2 to complete</td></tr>
  18071. <tr><td>Complete 2</td><td>3</td><td>current ID jumps from 1 -&gt; 3</td></tr>
  18072. <tr><td>Reserve 4</td><td>3</td><td></td></tr>
  18073. <tr><td>Reserve 5</td><td>3</td><td></td></tr>
  18074. <tr><td>Reserve 6</td><td>3</td><td></td></tr>
  18075. <tr><td>Complete 5</td><td>3</td><td></td></tr>
  18076. <tr><td>Complete 4</td><td>5</td><td>current ID jumps 3-&gt;5, even though 6 is pending</td></tr>
  18077. <tr><td>Complete 6</td><td>6</td><td></td></tr>
  18078. </tbody></table>
  18079. <h3 id="multi-writer-streams"><a class="header" href="#multi-writer-streams">Multi-writer streams</a></h3>
  18080. <p>There are two ways to view a multi-writer stream.</p>
  18081. <ol>
  18082. <li>Treat it as a collection of distinct single-writer streams, one
  18083. for each writer.</li>
  18084. <li>Treat it as a single stream.</li>
  18085. </ol>
  18086. <p>The single stream (option 2) is conceptually simpler, and easier to represent (a single stream id).
  18087. However, it requires each reader to know about the entire set of writers, to ensures that readers don't erroneously advance their current stream position too early and miss a fact from an unknown writer.
  18088. In contrast, multiple parallel streams (option 1) are more complex, requiring more state to represent (map from writer to stream id).
  18089. The payoff for doing so is that readers can &quot;peek&quot; ahead to facts that completed on one writer no matter the state of the others, reducing latency.</p>
  18090. <p>Note that a multi-writer stream can be viewed in both ways.
  18091. For example, the events stream is treated as multiple single-writer streams (option 1) by the sync handler, so that events are sent to clients as soon as possible.
  18092. But the background process that works through events treats them as a single linear stream.</p>
  18093. <p>Another useful example is the cache invalidation stream.
  18094. The facts this stream holds are instructions to &quot;you should now invalidate these cache entries&quot;.
  18095. We only ever treat this as a multiple single-writer streams as there is no important ordering between cache invalidations.
  18096. (Invalidations are self-contained facts; and the invalidations commute/are idempotent).</p>
  18097. <h3 id="writing-to-streams"><a class="header" href="#writing-to-streams">Writing to streams</a></h3>
  18098. <p>Writers need to track:</p>
  18099. <ul>
  18100. <li>track their current position (i.e. its own per-writer stream ID).</li>
  18101. <li>their facts currently awaiting completion.</li>
  18102. </ul>
  18103. <p>At startup, </p>
  18104. <ul>
  18105. <li>the current position of that writer can be found by querying the database (which suggests that facts need to be written to the database atomically, in a transaction); and</li>
  18106. <li>there are no facts awaiting completion.</li>
  18107. </ul>
  18108. <p>To reserve a stream ID, call <a href="https://www.postgresql.org/docs/current/functions-sequence.html"><code>nextval</code></a> on the appropriate postgres sequence.</p>
  18109. <p>To write a fact to the stream: insert the appropriate rows to the appropriate backing table.</p>
  18110. <p>To complete a fact, first remove it from your map of facts currently awaiting completion.
  18111. Then, if no earlier fact is awaiting completion, the writer can advance its current position in that stream.
  18112. Upon doing so it should emit an <code>RDATA</code> message<sup class="footnote-reference"><a href="#3">3</a></sup>, once for every fact between the old and the new stream ID.</p>
  18113. <h3 id="subscribing-to-streams"><a class="header" href="#subscribing-to-streams">Subscribing to streams</a></h3>
  18114. <p>Readers need to track the current position of every writer.</p>
  18115. <p>At startup, they can find this by contacting each writer with a <code>REPLICATE</code> message,
  18116. requesting that all writers reply describing their current position in their streams.
  18117. Writers reply with a <code>POSITION</code> message.</p>
  18118. <p>To learn about new facts, readers should listen for <code>RDATA</code> messages and process them to respond to the new fact.
  18119. The <code>RDATA</code> itself is not a self-contained representation of the fact;
  18120. readers will have to query the stream tables for the full details.
  18121. Readers must also advance their record of the writer's current position for that stream.</p>
  18122. <h1 id="summary"><a class="header" href="#summary">Summary</a></h1>
  18123. <p>In a nutshell: we have an append-only log with a &quot;buffer/scratchpad&quot; at the end where we have to wait for the sequence to be linear and contiguous.</p>
  18124. <hr />
  18125. <div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
  18126. <p>we use the word <em>fact</em> here for two reasons.
  18127. Firstly, the word &quot;event&quot; is already heavily overloaded (PDUs, EDUs, account data, ...) and we don't need to make that worse.
  18128. Secondly, &quot;fact&quot; emphasises that the things we append to a stream cannot change after the fact.</p>
  18129. </div>
  18130. <div class="footnote-definition" id="2"><sup class="footnote-definition-label">2</sup>
  18131. <p>A fact might be expressed with 0 rows, e.g. if we opened a transaction to persist an event, but failed and rolled the transaction back before marking the fact as completed.
  18132. In principle a fact might be expressed with 2 or more rows; if so, each of those rows should share the fact's stream ID.</p>
  18133. </div>
  18134. <div class="footnote-definition" id="3"><sup class="footnote-definition-label">3</sup>
  18135. <p>This communication used to happen directly with the writers <a href="development/synapse_architecture/../../tcp_replication.html">over TCP</a>;
  18136. nowadays it's done via Redis's Pubsub.</p>
  18137. </div>
  18138. <div style="break-before: page; page-break-before: always;"></div><h1 id="tcp-replication"><a class="header" href="#tcp-replication">TCP Replication</a></h1>
  18139. <h2 id="motivation-1"><a class="header" href="#motivation-1">Motivation</a></h2>
  18140. <p>Previously the workers used an HTTP long poll mechanism to get updates
  18141. from the master, which had the problem of causing a lot of duplicate
  18142. work on the server. This TCP protocol replaces those APIs with the aim
  18143. of increased efficiency.</p>
  18144. <h2 id="overview-3"><a class="header" href="#overview-3">Overview</a></h2>
  18145. <p>The protocol is based on fire and forget, line based commands. An
  18146. example flow would be (where '&gt;' indicates master to worker and
  18147. '&lt;' worker to master flows):</p>
  18148. <pre><code>&gt; SERVER example.com
  18149. &lt; REPLICATE
  18150. &gt; POSITION events master 53 53
  18151. &gt; RDATA events master 54 [&quot;$foo1:bar.com&quot;, ...]
  18152. &gt; RDATA events master 55 [&quot;$foo4:bar.com&quot;, ...]
  18153. </code></pre>
  18154. <p>The example shows the server accepting a new connection and sending its identity
  18155. with the <code>SERVER</code> command, followed by the client server to respond with the
  18156. position of all streams. The server then periodically sends <code>RDATA</code> commands
  18157. which have the format <code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row&gt;</code>, where
  18158. the format of <code>&lt;row&gt;</code> is defined by the individual streams. The
  18159. <code>&lt;instance_name&gt;</code> is the name of the Synapse process that generated the data
  18160. (usually &quot;master&quot;). We expect an RDATA for every row in the DB.</p>
  18161. <p>Error reporting happens by either the client or server sending an ERROR
  18162. command, and usually the connection will be closed.</p>
  18163. <p>Since the protocol is a simple line based, its possible to manually
  18164. connect to the server using a tool like netcat. A few things should be
  18165. noted when manually using the protocol:</p>
  18166. <ul>
  18167. <li>The federation stream is only available if federation sending has
  18168. been disabled on the main process.</li>
  18169. <li>The server will only time connections out that have sent a <code>PING</code>
  18170. command. If a ping is sent then the connection will be closed if no
  18171. further commands are received within 15s. Both the client and
  18172. server protocol implementations will send an initial PING on
  18173. connection and ensure at least one command every 5s is sent (not
  18174. necessarily <code>PING</code>).</li>
  18175. <li><code>RDATA</code> commands <em>usually</em> include a numeric token, however if the
  18176. stream has multiple rows to replicate per token the server will send
  18177. multiple <code>RDATA</code> commands, with all but the last having a token of
  18178. <code>batch</code>. See the documentation on <code>commands.RdataCommand</code> for
  18179. further details.</li>
  18180. </ul>
  18181. <h2 id="architecture-1"><a class="header" href="#architecture-1">Architecture</a></h2>
  18182. <p>The basic structure of the protocol is line based, where the initial
  18183. word of each line specifies the command. The rest of the line is parsed
  18184. based on the command. For example, the RDATA command is defined as:</p>
  18185. <pre><code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row_json&gt;
  18186. </code></pre>
  18187. <p>(Note that &lt;row_json&gt; may contains spaces, but cannot contain
  18188. newlines.)</p>
  18189. <p>Blank lines are ignored.</p>
  18190. <h3 id="keep-alives"><a class="header" href="#keep-alives">Keep alives</a></h3>
  18191. <p>Both sides are expected to send at least one command every 5s or so, and
  18192. should send a <code>PING</code> command if necessary. If either side do not receive
  18193. a command within e.g. 15s then the connection should be closed.</p>
  18194. <p>Because the server may be connected to manually using e.g. netcat, the
  18195. timeouts aren't enabled until an initial <code>PING</code> command is seen. Both
  18196. the client and server implementations below send a <code>PING</code> command
  18197. immediately on connection to ensure the timeouts are enabled.</p>
  18198. <p>This ensures that both sides can quickly realize if the tcp connection
  18199. has gone and handle the situation appropriately.</p>
  18200. <h3 id="start-up"><a class="header" href="#start-up">Start up</a></h3>
  18201. <p>When a new connection is made, the server:</p>
  18202. <ul>
  18203. <li>Sends a <code>SERVER</code> command, which includes the identity of the server,
  18204. allowing the client to detect if its connected to the expected
  18205. server</li>
  18206. <li>Sends a <code>PING</code> command as above, to enable the client to time out
  18207. connections promptly.</li>
  18208. </ul>
  18209. <p>The client:</p>
  18210. <ul>
  18211. <li>Sends a <code>NAME</code> command, allowing the server to associate a human
  18212. friendly name with the connection. This is optional.</li>
  18213. <li>Sends a <code>PING</code> as above</li>
  18214. <li>Sends a <code>REPLICATE</code> to get the current position of all streams.</li>
  18215. <li>On receipt of a <code>SERVER</code> command, checks that the server name
  18216. matches the expected server name.</li>
  18217. </ul>
  18218. <h3 id="error-handling"><a class="header" href="#error-handling">Error handling</a></h3>
  18219. <p>If either side detects an error it can send an <code>ERROR</code> command and close
  18220. the connection.</p>
  18221. <p>If the client side loses the connection to the server it should
  18222. reconnect, following the steps above.</p>
  18223. <h3 id="congestion"><a class="header" href="#congestion">Congestion</a></h3>
  18224. <p>If the server sends messages faster than the client can consume them the
  18225. server will first buffer a (fairly large) number of commands and then
  18226. disconnect the client. This ensures that we don't queue up an unbounded
  18227. number of commands in memory and gives us a potential opportunity to
  18228. squawk loudly. When/if the client recovers it can reconnect to the
  18229. server and ask for missed messages.</p>
  18230. <h3 id="reliability"><a class="header" href="#reliability">Reliability</a></h3>
  18231. <p>In general the replication stream should be considered an unreliable
  18232. transport since e.g. commands are not resent if the connection
  18233. disappears.</p>
  18234. <p>The exception to that are the replication streams, i.e. RDATA commands,
  18235. since these include tokens which can be used to restart the stream on
  18236. connection errors.</p>
  18237. <p>The client should keep track of the token in the last RDATA command
  18238. received for each stream so that on reconnection it can start streaming
  18239. from the correct place. Note: not all RDATA have valid tokens due to
  18240. batching. See <code>RdataCommand</code> for more details.</p>
  18241. <h3 id="example-5"><a class="header" href="#example-5">Example</a></h3>
  18242. <p>An example interaction is shown below. Each line is prefixed with '&gt;'
  18243. or '&lt;' to indicate which side is sending, these are <em>not</em> included on
  18244. the wire:</p>
  18245. <pre><code>* connection established *
  18246. &gt; SERVER localhost:8823
  18247. &gt; PING 1490197665618
  18248. &lt; NAME synapse.app.appservice
  18249. &lt; PING 1490197665618
  18250. &lt; REPLICATE
  18251. &gt; POSITION events master 1 1
  18252. &gt; POSITION backfill master 1 1
  18253. &gt; POSITION caches master 1 1
  18254. &gt; RDATA caches master 2 [&quot;get_user_by_id&quot;,[&quot;@01register-user:localhost:8823&quot;],1490197670513]
  18255. &gt; RDATA events master 14 [&quot;$149019767112vOHxz:localhost:8823&quot;,
  18256. &quot;!AFDCvgApUmpdfVjIXm:localhost:8823&quot;,&quot;m.room.guest_access&quot;,&quot;&quot;,null]
  18257. &lt; PING 1490197675618
  18258. &gt; ERROR server stopping
  18259. * connection closed by server *
  18260. </code></pre>
  18261. <p>The <code>POSITION</code> command sent by the server is used to set the clients
  18262. position without needing to send data with the <code>RDATA</code> command.</p>
  18263. <p>An example of a batched set of <code>RDATA</code> is:</p>
  18264. <pre><code>&gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test:localhost:8823&quot;],1490197670513]
  18265. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test2:localhost:8823&quot;],1490197670513]
  18266. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test3:localhost:8823&quot;],1490197670513]
  18267. &gt; RDATA caches master 54 [&quot;get_user_by_id&quot;,[&quot;@test4:localhost:8823&quot;],1490197670513]
  18268. </code></pre>
  18269. <p>In this case the client shouldn't advance their caches token until it
  18270. sees the the last <code>RDATA</code>.</p>
  18271. <h3 id="list-of-commands"><a class="header" href="#list-of-commands">List of commands</a></h3>
  18272. <p>The list of valid commands, with which side can send it: server (S) or
  18273. client (C):</p>
  18274. <h4 id="server-s"><a class="header" href="#server-s">SERVER (S)</a></h4>
  18275. <p>Sent at the start to identify which server the client is talking to</p>
  18276. <h4 id="rdata-s"><a class="header" href="#rdata-s">RDATA (S)</a></h4>
  18277. <p>A single update in a stream</p>
  18278. <h4 id="position-s"><a class="header" href="#position-s">POSITION (S)</a></h4>
  18279. <p>On receipt of a POSITION command clients should check if they have missed any
  18280. updates, and if so then fetch them out of band. Sent in response to a
  18281. REPLICATE command (but can happen at any time).</p>
  18282. <p>The POSITION command includes the source of the stream. Currently all streams
  18283. are written by a single process (usually &quot;master&quot;). If fetching missing
  18284. updates via HTTP API, rather than via the DB, then processes should make the
  18285. request to the appropriate process.</p>
  18286. <p>Two positions are included, the &quot;new&quot; position and the last position sent respectively.
  18287. This allows servers to tell instances that the positions have advanced but no
  18288. data has been written, without clients needlessly checking to see if they
  18289. have missed any updates. Instances will only fetch stuff if there is a gap between
  18290. their current position and the given last position.</p>
  18291. <h4 id="error-s-c"><a class="header" href="#error-s-c">ERROR (S, C)</a></h4>
  18292. <p>There was an error</p>
  18293. <h4 id="ping-s-c"><a class="header" href="#ping-s-c">PING (S, C)</a></h4>
  18294. <p>Sent periodically to ensure the connection is still alive</p>
  18295. <h4 id="name-c"><a class="header" href="#name-c">NAME (C)</a></h4>
  18296. <p>Sent at the start by client to inform the server who they are</p>
  18297. <h4 id="replicate-c"><a class="header" href="#replicate-c">REPLICATE (C)</a></h4>
  18298. <p>Asks the server for the current position of all streams.</p>
  18299. <h4 id="user_sync-c"><a class="header" href="#user_sync-c">USER_SYNC (C)</a></h4>
  18300. <p>A user has started or stopped syncing on this process.</p>
  18301. <h4 id="clear_user_sync-c"><a class="header" href="#clear_user_sync-c">CLEAR_USER_SYNC (C)</a></h4>
  18302. <p>The server should clear all associated user sync data from the worker.</p>
  18303. <p>This is used when a worker is shutting down.</p>
  18304. <h4 id="federation_ack-c"><a class="header" href="#federation_ack-c">FEDERATION_ACK (C)</a></h4>
  18305. <p>Acknowledge receipt of some federation data</p>
  18306. <h3 id="remote_server_up-s-c"><a class="header" href="#remote_server_up-s-c">REMOTE_SERVER_UP (S, C)</a></h3>
  18307. <p>Inform other processes that a remote server may have come back online.</p>
  18308. <p>See <code>synapse/replication/tcp/commands.py</code> for a detailed description and
  18309. the format of each command.</p>
  18310. <h3 id="cache-invalidation-stream"><a class="header" href="#cache-invalidation-stream">Cache Invalidation Stream</a></h3>
  18311. <p>The cache invalidation stream is used to inform workers when they need
  18312. to invalidate any of their caches in the data store. This is done by
  18313. streaming all cache invalidations done on master down to the workers,
  18314. assuming that any caches on the workers also exist on the master.</p>
  18315. <p>Each individual cache invalidation results in a row being sent down
  18316. replication, which includes the cache name (the name of the function)
  18317. and they key to invalidate. For example:</p>
  18318. <pre><code>&gt; RDATA caches master 550953771 [&quot;get_user_by_id&quot;, [&quot;@bob:example.com&quot;], 1550574873251]
  18319. </code></pre>
  18320. <p>Alternatively, an entire cache can be invalidated by sending down a <code>null</code>
  18321. instead of the key. For example:</p>
  18322. <pre><code>&gt; RDATA caches master 550953772 [&quot;get_user_by_id&quot;, null, 1550574873252]
  18323. </code></pre>
  18324. <p>However, there are times when a number of caches need to be invalidated
  18325. at the same time with the same key. To reduce traffic we batch those
  18326. invalidations into a single poke by defining a special cache name that
  18327. workers understand to mean to expand to invalidate the correct caches.</p>
  18328. <p>Currently the special cache names are declared in
  18329. <code>synapse/storage/_base.py</code> and are:</p>
  18330. <ol>
  18331. <li><code>cs_cache_fake</code> ─ invalidates caches that depend on the current
  18332. state</li>
  18333. </ol>
  18334. <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>
  18335. <p>This is a work-in-progress set of notes with two goals:</p>
  18336. <ul>
  18337. <li>act as a reference, explaining how Synapse implements faster joins; and</li>
  18338. <li>record the rationale behind our choices.</li>
  18339. </ul>
  18340. <p>See also <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/3902">MSC3902</a>.</p>
  18341. <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
  18342. request a lightweight response to the federation <code>/send_join</code> endpoint.
  18343. This is called a <strong>faster join</strong>, also known as a <strong>partial join</strong>. In these
  18344. notes we'll usually use the word &quot;partial&quot; as it matches the database schema.</p>
  18345. <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>
  18346. <p>The response to a partial join consists of</p>
  18347. <ul>
  18348. <li>the requested join event <code>J</code>,</li>
  18349. <li>a list of the servers in the room (according to the state before <code>J</code>),</li>
  18350. <li>a subset of the state of the room before <code>J</code>,</li>
  18351. <li>the full auth chain of that state subset.</li>
  18352. </ul>
  18353. <p>Synapse marks the room as partially joined by adding a row to the database table
  18354. <code>partial_state_rooms</code>. It also marks the join event <code>J</code> as &quot;partially stated&quot;,
  18355. meaning that we have neither received nor computed the full state before/after
  18356. <code>J</code>. This is done by adding a row to <code>partial_state_events</code>.</p>
  18357. <details><summary>DB schema</summary>
  18358. <pre><code>matrix=&gt; \d partial_state_events
  18359. Table &quot;matrix.partial_state_events&quot;
  18360. Column │ Type │ Collation │ Nullable │ Default
  18361. ══════════╪══════╪═══════════╪══════════╪═════════
  18362. room_id │ text │ │ not null │
  18363. event_id │ text │ │ not null │
  18364. matrix=&gt; \d partial_state_rooms
  18365. Table &quot;matrix.partial_state_rooms&quot;
  18366. Column │ Type │ Collation │ Nullable │ Default
  18367. ════════════════════════╪════════╪═══════════╪══════════╪═════════
  18368. room_id │ text │ │ not null │
  18369. device_lists_stream_id │ bigint │ │ not null │ 0
  18370. join_event_id │ text │ │ │
  18371. joined_via │ text │ │ │
  18372. matrix=&gt; \d partial_state_rooms_servers
  18373. Table &quot;matrix.partial_state_rooms_servers&quot;
  18374. Column │ Type │ Collation │ Nullable │ Default
  18375. ═════════════╪══════╪═══════════╪══════════╪═════════
  18376. room_id │ text │ │ not null │
  18377. server_name │ text │ │ not null │
  18378. </code></pre>
  18379. <p>Indices, foreign-keys and check constraints are omitted for brevity.</p>
  18380. </details>
  18381. <p>While partially joined to a room, Synapse receives events <code>E</code> from remote
  18382. homeservers as normal, and can create events at the request of its local users.
  18383. 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>
  18384. <blockquote>
  18385. <ol>
  18386. <li>Is a valid event, otherwise it is dropped. For an event to be valid, it
  18387. must contain a room_id, and it must comply with the event format of that
  18388. room version.</li>
  18389. <li>Passes signature checks, otherwise it is dropped.</li>
  18390. <li>Passes hash checks, otherwise it is redacted before being processed further.</li>
  18391. <li>Passes authorization rules based on the event’s auth events, otherwise it
  18392. is rejected.</li>
  18393. <li><strong>Passes authorization rules based on the state before the event, otherwise
  18394. it is rejected.</strong></li>
  18395. <li><strong>Passes authorization rules based on the current state of the room,
  18396. otherwise it is “soft failed”.</strong></li>
  18397. </ol>
  18398. </blockquote>
  18399. <p>We can enforce checks 1--4 without any problems.
  18400. But we cannot enforce checks 5 or 6 with complete certainty, since Synapse does
  18401. not know the full state before <code>E</code>, nor that of the room.</p>
  18402. <h3 id="partial-state"><a class="header" href="#partial-state">Partial state</a></h3>
  18403. <p>Instead, we make a best-effort approximation.
  18404. While the room is considered partially joined, Synapse tracks the &quot;partial
  18405. state&quot; before events.
  18406. This works in a similar way as regular state:</p>
  18407. <ul>
  18408. <li>The partial state before <code>J</code> is that given to us by the partial join response.</li>
  18409. <li>The partial state before an event <code>E</code> is the resolution of the partial states
  18410. after each of <code>E</code>'s <code>prev_event</code>s.</li>
  18411. <li>If <code>E</code> is rejected or a message event, the partial state after <code>E</code> is the
  18412. partial state before <code>E</code>.</li>
  18413. <li>Otherwise, the partial state after <code>E</code> is the partial state before <code>E</code>, plus
  18414. <code>E</code> itself.</li>
  18415. </ul>
  18416. <p>More concisely, partial state propagates just like full state; the only
  18417. difference is that we &quot;seed&quot; it with an incomplete initial state.
  18418. Synapse records that we have only calculated partial state for this event with
  18419. a row in <code>partial_state_events</code>.</p>
  18420. <p>While the room remains partially stated, check 5 on incoming events to that
  18421. room becomes:</p>
  18422. <blockquote>
  18423. <ol start="5">
  18424. <li>Passes authorization rules based on <strong>the resolution between the partial
  18425. state before <code>E</code> and <code>E</code>'s auth events.</strong> If the event fails to pass
  18426. authorization rules, it is rejected.</li>
  18427. </ol>
  18428. </blockquote>
  18429. <p>Additionally, check 6 is deleted: no soft-failures are enforced.</p>
  18430. <p>While partially joined, the current partial state of the room is defined as the
  18431. resolution across the partial states after all forward extremities in the room.</p>
  18432. <p><em>Remark.</em> Events with partial state are <em>not</em> considered
  18433. <a href="development/synapse_architecture/../room-dag-concepts.html#outliers">outliers</a>.</p>
  18434. <h3 id="approximation-error"><a class="header" href="#approximation-error">Approximation error</a></h3>
  18435. <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>
  18436. <div class="footnote-definition" id="2"><sup class="footnote-definition-label">1</sup>
  18437. <p>Is this exhaustive?</p>
  18438. </div>
  18439. <ul>
  18440. <li>We may erroneously accept an incoming event in check 5 based on partial state
  18441. when it would have been rejected based on full state, or vice versa.</li>
  18442. <li>This means that an event could erroneously be added to the current partial
  18443. state of the room when it would not be present in the full state of the room,
  18444. or vice versa.</li>
  18445. <li>Additionally, we may have skipped soft-failing an event that would have been
  18446. soft-failed based on full state.</li>
  18447. </ul>
  18448. <p>(Note that the discrepancies described in the last two bullets are user-visible.)</p>
  18449. <p>This means that we have to be very careful when we want to lookup pieces of room
  18450. state in a partially-joined room. Our approximation of the state may be
  18451. incorrect or missing. But we can make some educated guesses. If</p>
  18452. <ul>
  18453. <li>our partial state is likely to be correct, or</li>
  18454. <li>the consequences of our partial state being incorrect are minor,</li>
  18455. </ul>
  18456. <p>then we proceed as normal, and let the resync process fix up any mistakes (see
  18457. below).</p>
  18458. <p>When is our partial state likely to be correct?</p>
  18459. <ul>
  18460. <li>It's more accurate the closer we are to the partial join event. (So we should
  18461. ideally complete the resync as soon as possible.)</li>
  18462. <li>Non-member events: we will have received them as part of the partial join
  18463. response, if they were part of the room state at that point. We may
  18464. incorrectly accept or reject updates to that state (at first because we lack
  18465. remote membership information; later because of compounding errors), so these
  18466. can become incorrect over time.</li>
  18467. <li>Local members' memberships: we are the only ones who can create join and
  18468. knock events for our users. We can't be completely confident in the
  18469. correctness of bans, invites and kicks from other homeservers, but the resync
  18470. process should correct any mistakes.</li>
  18471. <li>Remote members' memberships: we did not receive these in the /send_join
  18472. response, so we have essentially no idea if these are correct or not.</li>
  18473. </ul>
  18474. <p>In short, we deem it acceptable to trust the partial state for non-membership
  18475. and local membership events. For remote membership events, we wait for the
  18476. resync to complete, at which point we have the full state of the room and can
  18477. proceed as normal.</p>
  18478. <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>
  18479. <p>The partial-state approximation is only a temporary affair. In the background,
  18480. synapse beings a &quot;resync&quot; process. This is a continuous loop, starting at the
  18481. partial join event and proceeding downwards through the event graph. For each
  18482. <code>E</code> seen in the room since partial join, Synapse will fetch </p>
  18483. <ul>
  18484. <li>the event ids in the state of the room before <code>E</code>, via
  18485. <a href="https://spec.matrix.org/v1.5/server-server-api/#get_matrixfederationv1state_idsroomid"><code>/state_ids</code></a>;</li>
  18486. <li>the event ids in the full auth chain of <code>E</code>, included in the <code>/state_ids</code>
  18487. response; and</li>
  18488. <li>any events from the previous two bullets that Synapse hasn't persisted, via
  18489. <a href="https://spec.matrix.org/v1.5/server-server-api/#get_matrixfederationv1stateroomid">`/state</a>.</li>
  18490. </ul>
  18491. <p>This means Synapse has (or can compute) the full state before <code>E</code>, which allows
  18492. Synapse to properly authorise or reject <code>E</code>. At this point ,the event
  18493. is considered to have &quot;full state&quot; rather than &quot;partial state&quot;. We record this
  18494. by removing <code>E</code> from the <code>partial_state_events</code> table.</p>
  18495. <p>[<strong>TODO:</strong> Does Synapse persist a new state group for the full state
  18496. before <code>E</code>, or do we alter the (partial-)state group in-place? Are state groups
  18497. ever marked as partially-stated? ]</p>
  18498. <p>This scheme means it is possible for us to have accepted and sent an event to
  18499. clients, only to reject it during the resync. From a client's perspective, the
  18500. effect is similar to a retroactive
  18501. state change due to state resolution---i.e. a &quot;state reset&quot;.<sup class="footnote-reference"><a href="#3">2</a></sup></p>
  18502. <div class="footnote-definition" id="3"><sup class="footnote-definition-label">2</sup>
  18503. <p>Clients should refresh caches to detect such a change. Rumour has it that
  18504. sliding sync will fix this.</p>
  18505. </div>
  18506. <p>When all events since the join <code>J</code> have been fully-stated, the room resync
  18507. process is complete. We record this by removing the room from
  18508. <code>partial_state_rooms</code>.</p>
  18509. <h2 id="faster-joins-on-workers"><a class="header" href="#faster-joins-on-workers">Faster joins on workers</a></h2>
  18510. <p>For the time being, the resync process happens on the master worker.
  18511. A new replication stream <code>un_partial_stated_room</code> is added. Whenever a resync
  18512. completes and a partial-state room becomes fully stated, a new message is sent
  18513. into that stream containing the room ID.</p>
  18514. <h2 id="notes-on-specific-cases"><a class="header" href="#notes-on-specific-cases">Notes on specific cases</a></h2>
  18515. <blockquote>
  18516. <p><strong>NB.</strong> The notes below are rough. Some of them are hidden under <code>&lt;details&gt;</code>
  18517. disclosures because they have yet to be implemented in mainline Synapse.</p>
  18518. </blockquote>
  18519. <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>
  18520. <p>When sending out messages during a partial join, we assume our partial state is
  18521. accurate and proceed as normal. For this to have any hope of succeeding at all,
  18522. our partial state must contain an entry for each of the (type, state key) pairs
  18523. <a href="https://spec.matrix.org/v1.3/rooms/v10/#authorization-rules">specified by the auth rules</a>:</p>
  18524. <ul>
  18525. <li><code>m.room.create</code></li>
  18526. <li><code>m.room.join_rules</code></li>
  18527. <li><code>m.room.power_levels</code></li>
  18528. <li><code>m.room.third_party_invite</code></li>
  18529. <li><code>m.room.member</code></li>
  18530. </ul>
  18531. <p>The first four of these should be present in the state before <code>J</code> that is given
  18532. to us in the partial join response; only membership events are omitted. In order
  18533. for us to consider the user joined, we must have their membership event. That
  18534. means the only possible omission is the target's membership in an invite, kick
  18535. or ban.</p>
  18536. <p>The worst possibility is that we locally invite someone who is banned according to
  18537. the full state, because we lack their ban in our current partial state. The rest
  18538. of the federation---at least, those who are fully joined---should correctly
  18539. 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
  18540. homeservers and resolved by the resync for partially-joined homeservers.</p>
  18541. <p>In more generality, there are two problems we're worrying about here:</p>
  18542. <ul>
  18543. <li>We might create an event that is valid under our partial state, only to later
  18544. find out that is actually invalid according to the full state.</li>
  18545. <li>Or: we might refuse to create an event that is invalid under our partial
  18546. state, even though it would be perfectly valid under the full state.</li>
  18547. </ul>
  18548. <p>However we expect such problems to be unlikely in practise, because</p>
  18549. <ul>
  18550. <li>We trust that the room has sensible power levels, e.g. that bad actors with
  18551. high power levels are demoted before their ban.</li>
  18552. <li>We trust that the resident server provides us up-to-date power levels, join
  18553. rules, etc.</li>
  18554. <li>State changes in rooms are relatively infrequent, and the resync period is
  18555. relatively quick.</li>
  18556. </ul>
  18557. <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>
  18558. <p><strong>TODO:</strong> needs prose fleshing out.</p>
  18559. <p>Normally: send out in a fed txn to all HSes in the room.
  18560. We only know that some HSes were in the room at some point. Wat do.
  18561. Send it out to the list of servers from the first join.
  18562. <strong>TODO</strong> what do we do here if we have full state?
  18563. 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...)
  18564. But don't want to send out sensitive data in other HS's events in this way.</p>
  18565. <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.
  18566. What about if we didn't send them an event but shouldn't've?
  18567. E.g. what if someone joined from a new HS shortly after you did? We wouldn't talk to them.
  18568. Could imagine sending out the &quot;Missed&quot; events after the resync but... painful to work out what they should have seen if they joined/left.
  18569. Instead, just send them the latest event (if they're still in the room after resync) and let them backfill.(?)</p>
  18570. <ul>
  18571. <li>Don't do this currently.</li>
  18572. <li>If anyone who has received our messages sends a message to a HS we missed, they can backfill our messages</li>
  18573. <li>Gap: rooms which are infrequently used and take a long time to resync.</li>
  18574. </ul>
  18575. <h3 id="joining-after-a-partial-join"><a class="header" href="#joining-after-a-partial-join">Joining after a partial join</a></h3>
  18576. <p><strong>NB.</strong> Not yet implemented.</p>
  18577. <details>
  18578. <p><strong>TODO:</strong> needs prose fleshing out. Liase with Matthieu. Explain why /send_join
  18579. (Rich was surprised we didn't just create it locally. Answer: to try and avoid
  18580. a join which then gets rejected after resync.)</p>
  18581. <p>We don't know for sure that any join we create would be accepted.
  18582. 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.
  18583. Instead, do another partial make-join/send-join handshake to confirm that the join works.</p>
  18584. <ul>
  18585. <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>
  18586. <li>What if the second send_join response includes a different list of reisdent HSes? Could ignore it.
  18587. <ul>
  18588. <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>
  18589. </ul>
  18590. </li>
  18591. <li>SQ: wrt device lists it's a lot safer to ignore it!!!!!</li>
  18592. <li>What if the state at the second join is inconsistent with what we have? Ignore it?</li>
  18593. </ul>
  18594. </details>
  18595. <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>
  18596. <p><strong>NB.</strong> Not yet implemented.</p>
  18597. <details>
  18598. <p>When you're fully joined to a room, to have <code>U</code> leave a room their homeserver
  18599. needs to</p>
  18600. <ul>
  18601. <li>create a new leave event for <code>U</code> which will be accepted by other homeservers,
  18602. and</li>
  18603. <li>send that event <code>U</code> out to the homeservers in the federation.</li>
  18604. </ul>
  18605. <p>When is a leave event accepted? See
  18606. <a href="https://spec.matrix.org/v1.5/rooms/v10/#authorization-rules">v10 auth rules</a>:</p>
  18607. <blockquote>
  18608. <ol start="4">
  18609. <li>If type is m.room.member: [...]
  18610. &gt;
  18611. &gt; 5. If membership is leave:
  18612. &gt;
  18613. &gt; 1. If the sender matches state_key, allow if and only if that user’s current membership state is invite, join, or knock.
  18614. 2. [...]</li>
  18615. </ol>
  18616. </blockquote>
  18617. <p>I think this means that (well-formed!) self-leaves are governed entirely by
  18618. 4.5.1. This means that if we correctly calculate state which says that <code>U</code> is
  18619. invited, joined or knocked and include it in the leave's auth events, our event
  18620. is accepted by checks 4 and 5 on incoming events.</p>
  18621. <blockquote>
  18622. <ol start="4">
  18623. <li>Passes authorization rules based on the event’s auth events, otherwise
  18624. &gt; it is rejected.</li>
  18625. <li>Passes authorization rules based on the state before the event, otherwise
  18626. &gt; it is rejected.</li>
  18627. </ol>
  18628. </blockquote>
  18629. <p>The only way to fail check 6 is if the receiving server's current state of the
  18630. room says that <code>U</code> is banned, has left, or has no membership event. But this is
  18631. fine: the receiving server already thinks that <code>U</code> isn't in the room.</p>
  18632. <blockquote>
  18633. <ol start="6">
  18634. <li>Passes authorization rules based on the current state of the room,
  18635. &gt; otherwise it is “soft failed”.</li>
  18636. </ol>
  18637. </blockquote>
  18638. <p>For the second point (publishing the leave event), the best thing we can do is
  18639. to is publish to all HSes we know to be currently in the room. If they miss that
  18640. event, they might send us traffic in the room that we don't care about. This is
  18641. a problem with leaving after a &quot;full&quot; join; we don't seek to fix this with
  18642. partial joins.</p>
  18643. <p>(With that said: there's nothing machine-readable in the /send response. I don't
  18644. think we can deduce &quot;destination has left the room&quot; from a failure to /send an
  18645. event into that room?)</p>
  18646. <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>
  18647. <p>We can create leave events and can choose what gets included in our auth events,
  18648. so we can be sure that we pass check 4 on incoming events. For check 5, we might
  18649. have an incorrect view of the state before an event.
  18650. The only way we might erroneously think a leave is valid is if</p>
  18651. <ul>
  18652. <li>the partial state before the leave has <code>U</code> joined, invited or knocked, but</li>
  18653. <li>the full state before the leave has <code>U</code> banned, left or not present,</li>
  18654. </ul>
  18655. <p>in which case the leave doesn't make anything worse: other HSes already consider
  18656. us as not in the room, and will continue to do so after seeing the leave.</p>
  18657. <p>The remaining obstacle is then: can we safely broadcast the leave event? We may
  18658. miss servers or incorrectly think that a server is in the room. Or the
  18659. destination server may be offline and miss the transaction containing our leave
  18660. event.This should self-heal when they see an event whose <code>prev_events</code> descends
  18661. from our leave.</p>
  18662. <p>Another option we considered was to use federation <code>/send_leave</code> to ask a
  18663. fully-joined server to send out the event on our behalf. But that introduces
  18664. complexity without much benefit. Besides, as Rich put it,</p>
  18665. <blockquote>
  18666. <p>sending out leaves is pretty best-effort currently</p>
  18667. </blockquote>
  18668. <p>so this is probably good enough as-is.</p>
  18669. <h4 id="cleanup-after-the-last-leave"><a class="header" href="#cleanup-after-the-last-leave">Cleanup after the last leave</a></h4>
  18670. <p><strong>TODO</strong>: what cleanup is necessary? Is it all just nice-to-have to save unused
  18671. work?</p>
  18672. </details>
  18673. <div style="break-before: page; page-break-before: always;"></div><h1 id="internal-documentation"><a class="header" href="#internal-documentation">Internal Documentation</a></h1>
  18674. <p>This section covers implementation documentation for various parts of Synapse.</p>
  18675. <p>If a developer is planning to make a change to a feature of Synapse, it can be useful for
  18676. general documentation of how that feature is implemented to be available. This saves the
  18677. developer time in place of needing to understand how the feature works by reading the
  18678. code.</p>
  18679. <p>Documentation that would be more useful for the perspective of a system administrator,
  18680. rather than a developer who's intending to change to code, should instead be placed
  18681. under the Usage section of the documentation.</p>
  18682. <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>
  18683. <p>https://fujifish.github.io/samling/samling.html (https://github.com/fujifish/samling) is a great resource for being able to tinker with the
  18684. SAML options within Synapse without needing to deploy and configure a complicated software stack.</p>
  18685. <p>To make Synapse (and therefore Element) use it:</p>
  18686. <ol>
  18687. <li>Use the samling.html URL above or deploy your own and visit the IdP Metadata tab.</li>
  18688. <li>Copy the XML to your clipboard.</li>
  18689. <li>On your Synapse server, create a new file <code>samling.xml</code> next to your <code>homeserver.yaml</code> with
  18690. the XML from step 2 as the contents.</li>
  18691. <li>Edit your <code>homeserver.yaml</code> to include:
  18692. <pre><code class="language-yaml">saml2_config:
  18693. sp_config:
  18694. allow_unknown_attributes: true # Works around a bug with AVA Hashes: https://github.com/IdentityPython/pysaml2/issues/388
  18695. metadata:
  18696. local: [&quot;samling.xml&quot;]
  18697. </code></pre>
  18698. </li>
  18699. <li>Ensure that your <code>homeserver.yaml</code> has a setting for <code>public_baseurl</code>:
  18700. <pre><code class="language-yaml">public_baseurl: http://localhost:8080/
  18701. </code></pre>
  18702. </li>
  18703. <li>Run <code>apt-get install xmlsec1</code> and <code>pip install --upgrade --force 'pysaml2&gt;=4.5.0'</code> to ensure
  18704. the dependencies are installed and ready to go.</li>
  18705. <li>Restart Synapse.</li>
  18706. </ol>
  18707. <p>Then in Element:</p>
  18708. <ol>
  18709. <li>Visit the login page and point Element towards your homeserver using the <code>public_baseurl</code> above.</li>
  18710. <li>Click the Single Sign-On button.</li>
  18711. <li>On the samling page, enter a Name Identifier and add a SAML Attribute for <code>uid=your_localpart</code>.
  18712. The response must also be signed.</li>
  18713. <li>Click &quot;Next&quot;.</li>
  18714. <li>Click &quot;Post Response&quot; (change nothing).</li>
  18715. <li>You should be logged in.</li>
  18716. </ol>
  18717. <p>If you try and repeat this process, you may be automatically logged in using the information you
  18718. gave previously. To fix this, open your developer console (<code>F12</code> or <code>Ctrl+Shift+I</code>) while on the
  18719. samling page and clear the site data. In Chrome, this will be a button on the Application tab.</p>
  18720. <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>
  18721. <p>The <a href="https://github.com/jbittel/django-mama-cas">django-mama-cas</a> project is an
  18722. easy to run CAS implementation built on top of Django.</p>
  18723. <h2 id="prerequisites"><a class="header" href="#prerequisites">Prerequisites</a></h2>
  18724. <ol>
  18725. <li>Create a new virtualenv: <code>python3 -m venv &lt;your virtualenv&gt;</code></li>
  18726. <li>Activate your virtualenv: <code>source /path/to/your/virtualenv/bin/activate</code></li>
  18727. <li>Install Django and django-mama-cas:
  18728. <pre><code class="language-sh">python -m pip install &quot;django&lt;3&quot; &quot;django-mama-cas==2.4.0&quot;
  18729. </code></pre>
  18730. </li>
  18731. <li>Create a Django project in the current directory:
  18732. <pre><code class="language-sh">django-admin startproject cas_test .
  18733. </code></pre>
  18734. </li>
  18735. <li>Follow the <a href="https://django-mama-cas.readthedocs.io/en/latest/installation.html#configuring">install directions</a> for django-mama-cas</li>
  18736. <li>Setup the SQLite database: <code>python manage.py migrate</code></li>
  18737. <li>Create a user:
  18738. <pre><code class="language-sh">python manage.py createsuperuser
  18739. </code></pre>
  18740. <ol>
  18741. <li>Use whatever you want as the username and password.</li>
  18742. <li>Leave the other fields blank.</li>
  18743. </ol>
  18744. </li>
  18745. <li>Use the built-in Django test server to serve the CAS endpoints on port 8000:
  18746. <pre><code class="language-sh">python manage.py runserver
  18747. </code></pre>
  18748. </li>
  18749. </ol>
  18750. <p>You should now have a Django project configured to serve CAS authentication with
  18751. a single user created.</p>
  18752. <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>
  18753. <ol>
  18754. <li>Modify your <code>homeserver.yaml</code> to enable CAS and point it to your locally
  18755. running Django test server:
  18756. <pre><code class="language-yaml">cas_config:
  18757. enabled: true
  18758. server_url: &quot;http://localhost:8000&quot;
  18759. service_url: &quot;http://localhost:8081&quot;
  18760. #displayname_attribute: name
  18761. #required_attributes:
  18762. # name: value
  18763. </code></pre>
  18764. </li>
  18765. <li>Restart Synapse.</li>
  18766. </ol>
  18767. <p>Note that the above configuration assumes the homeserver is running on port 8081
  18768. and that the CAS server is on port 8000, both on localhost.</p>
  18769. <h2 id="testing-the-configuration"><a class="header" href="#testing-the-configuration">Testing the configuration</a></h2>
  18770. <p>Then in Element:</p>
  18771. <ol>
  18772. <li>Visit the login page with a Element pointing at your homeserver.</li>
  18773. <li>Click the Single Sign-On button.</li>
  18774. <li>Login using the credentials created with <code>createsuperuser</code>.</li>
  18775. <li>You should be logged in.</li>
  18776. </ol>
  18777. <p>If you want to repeat this process you'll need to manually logout first:</p>
  18778. <ol>
  18779. <li>http://localhost:8000/admin/</li>
  18780. <li>Click &quot;logout&quot; in the top right.</li>
  18781. </ol>
  18782. <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>
  18783. <h2 id="edges"><a class="header" href="#edges">Edges</a></h2>
  18784. <p>The word &quot;edge&quot; comes from graph theory lingo. An edge is just a connection
  18785. between two events. In Synapse, we connect events by specifying their
  18786. <code>prev_events</code>. A subsequent event points back at a previous event.</p>
  18787. <pre><code>A (oldest) &lt;---- B &lt;---- C (most recent)
  18788. </code></pre>
  18789. <h2 id="depth-and-stream-ordering"><a class="header" href="#depth-and-stream-ordering">Depth and stream ordering</a></h2>
  18790. <p>Events are normally sorted by <code>(topological_ordering, stream_ordering)</code> where
  18791. <code>topological_ordering</code> is just <code>depth</code>. In other words, we first sort by <code>depth</code>
  18792. and then tie-break based on <code>stream_ordering</code>. <code>depth</code> is incremented as new
  18793. messages are added to the DAG. Normally, <code>stream_ordering</code> is an auto
  18794. incrementing integer, but backfilled events start with <code>stream_ordering=-1</code> and decrement.</p>
  18795. <hr />
  18796. <ul>
  18797. <li><code>/sync</code> returns things in the order they arrive at the server (<code>stream_ordering</code>).</li>
  18798. <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>
  18799. </ul>
  18800. <p>The general idea is that, if you're following a room in real-time (i.e.
  18801. <code>/sync</code>), you probably want to see the messages as they arrive at your server,
  18802. rather than skipping any that arrived late; whereas if you're looking at a
  18803. historical section of timeline (i.e. <code>/messages</code>), you want to see the best
  18804. representation of the state of the room as others were seeing it at the time.</p>
  18805. <h2 id="outliers"><a class="header" href="#outliers">Outliers</a></h2>
  18806. <p>We mark an event as an <code>outlier</code> when we haven't figured out the state for the
  18807. room at that point in the DAG yet. They are &quot;floating&quot; events that we haven't
  18808. yet correlated to the DAG.</p>
  18809. <p>Outliers typically arise when we fetch the auth chain or state for a given
  18810. event. When that happens, we just grab the events in the state/auth chain,
  18811. without calculating the state at those events, or backfilling their
  18812. <code>prev_events</code>. Since we don't have the state at any events fetched in that
  18813. way, we mark them as outliers.</p>
  18814. <p>So, typically, we won't have the <code>prev_events</code> of an <code>outlier</code> in the database,
  18815. (though it's entirely possible that we <em>might</em> have them for some other
  18816. reason). Other things that make outliers different from regular events:</p>
  18817. <ul>
  18818. <li>
  18819. <p>We don't have state for them, so there should be no entry in
  18820. <code>event_to_state_groups</code> for an outlier. (In practice this isn't always
  18821. the case, though I'm not sure why: see https://github.com/matrix-org/synapse/issues/12201).</p>
  18822. </li>
  18823. <li>
  18824. <p>We don't record entries for them in the <code>event_edges</code>,
  18825. <code>event_forward_extremeties</code> or <code>event_backward_extremities</code> tables.</p>
  18826. </li>
  18827. </ul>
  18828. <p>Since outliers are not tied into the DAG, they do not normally form part of the
  18829. timeline sent down to clients via <code>/sync</code> or <code>/messages</code>; however there is an
  18830. exception:</p>
  18831. <h3 id="out-of-band-membership-events"><a class="header" href="#out-of-band-membership-events">Out-of-band membership events</a></h3>
  18832. <p>A special case of outlier events are some membership events for federated rooms
  18833. that we aren't full members of. For example:</p>
  18834. <ul>
  18835. <li>invites received over federation, before we join the room</li>
  18836. <li><em>rejections</em> for said invites</li>
  18837. <li>knock events for rooms that we would like to join but have not yet joined.</li>
  18838. </ul>
  18839. <p>In all the above cases, we don't have the state for the room, which is why they
  18840. are treated as outliers. They are a bit special though, in that they are
  18841. proactively sent to clients via <code>/sync</code>.</p>
  18842. <h2 id="forward-extremity"><a class="header" href="#forward-extremity">Forward extremity</a></h2>
  18843. <p>Most-recent-in-time events in the DAG which are not referenced by any other
  18844. events' <code>prev_events</code> yet. (In this definition, outliers, rejected events, and
  18845. soft-failed events don't count.)</p>
  18846. <p>The forward extremities of a room (or at least, a subset of them, if there are
  18847. more than ten) are used as the <code>prev_events</code> when the next event is sent.</p>
  18848. <p>The &quot;current state&quot; of a room (ie: the state which would be used if we
  18849. generated a new event) is, therefore, the resolution of the room states
  18850. at each of the forward extremities.</p>
  18851. <h2 id="backward-extremity"><a class="header" href="#backward-extremity">Backward extremity</a></h2>
  18852. <p>The current marker of where we have backfilled up to and will generally be the
  18853. <code>prev_events</code> of the oldest-in-time events we have in the DAG. This gives a starting point when
  18854. backfilling history.</p>
  18855. <p>Note that, unlike forward extremities, we typically don't have any backward
  18856. extremity events themselves in the database - or, if we do, they will be &quot;outliers&quot; (see
  18857. above). Either way, we don't expect to have the room state at a backward extremity.</p>
  18858. <p>When we persist a non-outlier event, if it was previously a backward extremity,
  18859. we clear it as a backward extremity and set all of its <code>prev_events</code> as the new
  18860. backward extremities if they aren't already persisted as non-outliers. This
  18861. therefore keeps the backward extremities up-to-date.</p>
  18862. <h2 id="state-groups"><a class="header" href="#state-groups">State groups</a></h2>
  18863. <p>For every non-outlier event we need to know the state at that event. Instead of
  18864. storing the full state for each event in the DB (i.e. a <code>event_id -&gt; state</code>
  18865. mapping), which is <em>very</em> space inefficient when state doesn't change, we
  18866. instead assign each different set of state a &quot;state group&quot; and then have
  18867. mappings of <code>event_id -&gt; state_group</code> and <code>state_group -&gt; state</code>.</p>
  18868. <h3 id="stage-group-edges"><a class="header" href="#stage-group-edges">Stage group edges</a></h3>
  18869. <p>TODO: <code>state_group_edges</code> is a further optimization...
  18870. notes from @Azrenbeth, https://pastebin.com/seUGVGeT</p>
  18871. <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>
  18872. <p>The auth chain difference algorithm is used by V2 state resolution, where a
  18873. naive implementation can be a significant source of CPU and DB usage.</p>
  18874. <h3 id="definitions"><a class="header" href="#definitions">Definitions</a></h3>
  18875. <p>A <em>state set</em> is a set of state events; e.g. the input of a state resolution
  18876. algorithm is a collection of state sets.</p>
  18877. <p>The <em>auth chain</em> of a set of events are all the events' auth events and <em>their</em>
  18878. auth events, recursively (i.e. the events reachable by walking the graph induced
  18879. by an event's auth events links).</p>
  18880. <p>The <em>auth chain difference</em> of a collection of state sets is the union minus the
  18881. intersection of the sets of auth chains corresponding to the state sets, i.e an
  18882. event is in the auth chain difference if it is reachable by walking the auth
  18883. event graph from at least one of the state sets but not from <em>all</em> of the state
  18884. sets.</p>
  18885. <h2 id="breadth-first-walk-algorithm"><a class="header" href="#breadth-first-walk-algorithm">Breadth First Walk Algorithm</a></h2>
  18886. <p>A way of calculating the auth chain difference without calculating the full auth
  18887. chains for each state set is to do a parallel breadth first walk (ordered by
  18888. depth) of each state set's auth chain. By tracking which events are reachable
  18889. from each state set we can finish early if every pending event is reachable from
  18890. every state set.</p>
  18891. <p>This can work well for state sets that have a small auth chain difference, but
  18892. can be very inefficient for larger differences. However, this algorithm is still
  18893. used if we don't have a chain cover index for the room (e.g. because we're in
  18894. the process of indexing it).</p>
  18895. <h2 id="chain-cover-index"><a class="header" href="#chain-cover-index">Chain Cover Index</a></h2>
  18896. <p>Synapse computes auth chain differences by pre-computing a &quot;chain cover&quot; index
  18897. for the auth chain in a room, allowing us to efficiently make reachability queries
  18898. like &quot;is event <code>A</code> in the auth chain of event <code>B</code>?&quot;. We could do this with an index
  18899. that tracks all pairs <code>(A, B)</code> such that <code>A</code> is in the auth chain of <code>B</code>. However, this
  18900. would be prohibitively large, scaling poorly as the room accumulates more state
  18901. events.</p>
  18902. <p>Instead, we break down the graph into <em>chains</em>. A chain is a subset of a DAG
  18903. with the following property: for any pair of events <code>E</code> and <code>F</code> in the chain,
  18904. the chain contains a path <code>E -&gt; F</code> or a path <code>F -&gt; E</code>. This forces a chain to be
  18905. linear (without forks), e.g. <code>E -&gt; F -&gt; G -&gt; ... -&gt; H</code>. Each event in the chain
  18906. is given a <em>sequence number</em> local to that chain. The oldest event <code>E</code> in the
  18907. chain has sequence number 1. If <code>E</code> has a child <code>F</code> in the chain, then <code>F</code> has
  18908. sequence number 2. If <code>E</code> has a grandchild <code>G</code> in the chain, then <code>G</code> has
  18909. sequence number 3; and so on.</p>
  18910. <p>Synapse ensures that each persisted event belongs to exactly one chain, and
  18911. tracks how the chains are connected to one another. This allows us to
  18912. efficiently answer reachability queries. Doing so uses less storage than
  18913. tracking reachability on an event-by-event basis, particularly when we have
  18914. fewer and longer chains. See</p>
  18915. <blockquote>
  18916. <p>Jagadish, H. (1990). <a href="https://doi.org/10.1145/99935.99944">A compression technique to materialize transitive closure</a>.
  18917. <em>ACM Transactions on Database Systems (TODS)</em>, 15*(4)*, 558-598.</p>
  18918. </blockquote>
  18919. <p>for the original idea or</p>
  18920. <blockquote>
  18921. <p>Y. Chen, Y. Chen, <a href="https://doi.org/10.1109/ICDE.2008.4497498">An efficient algorithm for answering graph
  18922. reachability queries</a>,
  18923. in: 2008 IEEE 24th International Conference on Data Engineering, April 2008,
  18924. 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>
  18925. </blockquote>
  18926. <p>for a more modern take.</p>
  18927. <p>In practical terms, the chain cover assigns every event a
  18928. <em>chain ID</em> and <em>sequence number</em> (e.g. <code>(5,3)</code>), and maintains a map of <em>links</em>
  18929. between events in chains (e.g. <code>(5,3) -&gt; (2,4)</code>) such that <code>A</code> is reachable by <code>B</code>
  18930. (i.e. <code>A</code> is in the auth chain of <code>B</code>) if and only if either:</p>
  18931. <ol>
  18932. <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
  18933. sequence number; or</li>
  18934. <li>there is a link <code>L</code> between <code>B</code>'s chain ID and <code>A</code>'s chain ID such that
  18935. <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>
  18936. </ol>
  18937. <p>There are actually two potential implementations, one where we store links from
  18938. each chain to every other reachable chain (the transitive closure of the links
  18939. graph), and one where we remove redundant links (the transitive reduction of the
  18940. links graph) e.g. if we have chains <code>C3 -&gt; C2 -&gt; C1</code> then the link <code>C3 -&gt; C1</code>
  18941. would not be stored. Synapse uses the former implementation so that it doesn't
  18942. need to recurse to test reachability between chains. This trades-off extra storage
  18943. in order to save CPU cycles and DB queries.</p>
  18944. <h3 id="example-6"><a class="header" href="#example-6">Example</a></h3>
  18945. <p>An example auth graph would look like the following, where chains have been
  18946. formed based on type/state_key and are denoted by colour and are labelled with
  18947. <code>(chain ID, sequence number)</code>. Links are denoted by the arrows (links in grey
  18948. are those that would be remove in the second implementation described above).</p>
  18949. <p><img src="auth_chain_diff.dot.png" alt="Example" /></p>
  18950. <p>Note that we don't include all links between events and their auth events, as
  18951. most of those links would be redundant. For example, all events point to the
  18952. create event, but each chain only needs the one link from it's base to the
  18953. create event.</p>
  18954. <h2 id="using-the-index"><a class="header" href="#using-the-index">Using the Index</a></h2>
  18955. <p>This index can be used to calculate the auth chain difference of the state sets
  18956. by looking at the chain ID and sequence numbers reachable from each state set:</p>
  18957. <ol>
  18958. <li>For every state set lookup the chain ID/sequence numbers of each state event</li>
  18959. <li>Use the index to find all chains and the maximum sequence number reachable
  18960. from each state set.</li>
  18961. <li>The auth chain difference is then all events in each chain that have sequence
  18962. numbers between the maximum sequence number reachable from <em>any</em> state set and
  18963. the minimum reachable by <em>all</em> state sets (if any).</li>
  18964. </ol>
  18965. <p>Note that steps 2 is effectively calculating the auth chain for each state set
  18966. (in terms of chain IDs and sequence numbers), and step 3 is calculating the
  18967. difference between the union and intersection of the auth chains.</p>
  18968. <h3 id="worked-example"><a class="header" href="#worked-example">Worked Example</a></h3>
  18969. <p>For example, given the above graph, we can calculate the difference between
  18970. state sets consisting of:</p>
  18971. <ol>
  18972. <li><code>S1</code>: Alice's invite <code>(4,1)</code> and Bob's second join <code>(2,2)</code>; and</li>
  18973. <li><code>S2</code>: Alice's second join <code>(4,3)</code> and Bob's first join <code>(2,1)</code>.</li>
  18974. </ol>
  18975. <p>Using the index we see that the following auth chains are reachable from each
  18976. state set:</p>
  18977. <ol>
  18978. <li><code>S1</code>: <code>(1,1)</code>, <code>(2,2)</code>, <code>(3,1)</code> &amp; <code>(4,1)</code></li>
  18979. <li><code>S2</code>: <code>(1,1)</code>, <code>(2,1)</code>, <code>(3,2)</code> &amp; <code>(4,3)</code></li>
  18980. </ol>
  18981. <p>And so, for each the ranges that are in the auth chain difference:</p>
  18982. <ol>
  18983. <li>Chain 1: None, (since everything can reach the create event).</li>
  18984. <li>Chain 2: The range <code>(1, 2]</code> (i.e. just <code>2</code>), as <code>1</code> is reachable by all state
  18985. sets and the maximum reachable is <code>2</code> (corresponding to Bob's second join).</li>
  18986. <li>Chain 3: Similarly the range <code>(1, 2]</code> (corresponding to the second power
  18987. level).</li>
  18988. <li>Chain 4: The range <code>(1, 3]</code> (corresponding to both of Alice's joins).</li>
  18989. </ol>
  18990. <p>So the final result is: Bob's second join <code>(2,2)</code>, the second power level
  18991. <code>(3,2)</code> and both of Alice's joins <code>(4,2)</code> &amp; <code>(4,3)</code>.</p>
  18992. <div style="break-before: page; page-break-before: always;"></div><h1 id="media-repository"><a class="header" href="#media-repository">Media Repository</a></h1>
  18993. <p><em>Synapse implementation-specific details for the media repository</em></p>
  18994. <p>The media repository</p>
  18995. <ul>
  18996. <li>stores avatars, attachments and their thumbnails for media uploaded by local
  18997. users.</li>
  18998. <li>caches avatars, attachments and their thumbnails for media uploaded by remote
  18999. users.</li>
  19000. <li>caches resources and thumbnails used for URL previews.</li>
  19001. </ul>
  19002. <p>All media in Matrix can be identified by a unique
  19003. <a href="https://spec.matrix.org/latest/client-server-api/#matrix-content-mxc-uris">MXC URI</a>,
  19004. consisting of a server name and media ID:</p>
  19005. <pre><code>mxc://&lt;server-name&gt;/&lt;media-id&gt;
  19006. </code></pre>
  19007. <h2 id="local-media"><a class="header" href="#local-media">Local Media</a></h2>
  19008. <p>Synapse generates 24 character media IDs for content uploaded by local users.
  19009. These media IDs consist of upper and lowercase letters and are case-sensitive.
  19010. Other homeserver implementations may generate media IDs differently.</p>
  19011. <p>Local media is recorded in the <code>local_media_repository</code> table, which includes
  19012. metadata such as MIME types, upload times and file sizes.
  19013. Note that this table is shared by the URL cache, which has a different media ID
  19014. scheme.</p>
  19015. <h3 id="paths"><a class="header" href="#paths">Paths</a></h3>
  19016. <p>A file with media ID <code>aabbcccccccccccccccccccc</code> and its <code>128x96</code> <code>image/jpeg</code>
  19017. thumbnail, created by scaling, would be stored at:</p>
  19018. <pre><code>local_content/aa/bb/cccccccccccccccccccc
  19019. local_thumbnails/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  19020. </code></pre>
  19021. <h2 id="remote-media"><a class="header" href="#remote-media">Remote Media</a></h2>
  19022. <p>When media from a remote homeserver is requested from Synapse, it is assigned
  19023. a local <code>filesystem_id</code>, with the same format as locally-generated media IDs,
  19024. as described above.</p>
  19025. <p>A record of remote media is stored in the <code>remote_media_cache</code> table, which
  19026. can be used to map remote MXC URIs (server names and media IDs) to local
  19027. <code>filesystem_id</code>s.</p>
  19028. <h3 id="paths-1"><a class="header" href="#paths-1">Paths</a></h3>
  19029. <p>A file from <code>matrix.org</code> with <code>filesystem_id</code> <code>aabbcccccccccccccccccccc</code> and its
  19030. <code>128x96</code> <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  19031. <pre><code>remote_content/matrix.org/aa/bb/cccccccccccccccccccc
  19032. remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  19033. </code></pre>
  19034. <p>Older thumbnails may omit the thumbnailing method:</p>
  19035. <pre><code>remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg
  19036. </code></pre>
  19037. <p>Note that <code>remote_thumbnail/</code> does not have an <code>s</code>.</p>
  19038. <h2 id="url-previews-1"><a class="header" href="#url-previews-1">URL Previews</a></h2>
  19039. <p>When generating previews for URLs, Synapse may download and cache various
  19040. resources, including images. These resources are assigned temporary media IDs
  19041. of the form <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code>, where <code>yyyy-mm-dd</code> is the current
  19042. date and <code>aaaaaaaaaaaaaaaa</code> is a random sequence of 16 case-sensitive letters.</p>
  19043. <p>The metadata for these cached resources is stored in the
  19044. <code>local_media_repository</code> and <code>local_media_repository_url_cache</code> tables.</p>
  19045. <p>Resources for URL previews are deleted after a few days.</p>
  19046. <h3 id="paths-2"><a class="header" href="#paths-2">Paths</a></h3>
  19047. <p>The file with media ID <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code> and its <code>128x96</code>
  19048. <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  19049. <pre><code>url_cache/yyyy-mm-dd/aaaaaaaaaaaaaaaa
  19050. url_cache_thumbnails/yyyy-mm-dd/aaaaaaaaaaaaaaaa/128-96-image-jpeg-scale
  19051. </code></pre>
  19052. <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>
  19053. <p>Synapse maintains room and user statistics in various tables. These can be used
  19054. for administrative purposes but are also used when generating the public room
  19055. directory.</p>
  19056. <h1 id="synapse-developer-documentation"><a class="header" href="#synapse-developer-documentation">Synapse Developer Documentation</a></h1>
  19057. <h2 id="high-level-concepts"><a class="header" href="#high-level-concepts">High-Level Concepts</a></h2>
  19058. <h3 id="definitions-1"><a class="header" href="#definitions-1">Definitions</a></h3>
  19059. <ul>
  19060. <li><strong>subject</strong>: Something we are tracking stats about – currently a room or user.</li>
  19061. <li><strong>current row</strong>: An entry for a subject in the appropriate current statistics
  19062. table. Each subject can have only one.</li>
  19063. </ul>
  19064. <h3 id="overview-4"><a class="header" href="#overview-4">Overview</a></h3>
  19065. <p>Stats correspond to the present values. Current rows contain the most up-to-date
  19066. statistics for a room. Each subject can only have one entry.</p>
  19067. <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>
  19068. <p>Synapse has a number of platform dependencies, including Python, Rust,
  19069. PostgreSQL and SQLite. This document outlines the policy towards which versions
  19070. we support, and when we drop support for versions in the future.</p>
  19071. <h2 id="policy"><a class="header" href="#policy">Policy</a></h2>
  19072. <p>Synapse follows the upstream support life cycles for Python and PostgreSQL,
  19073. i.e. when a version reaches End of Life Synapse will withdraw support for that
  19074. version in future releases.</p>
  19075. <p>Details on the upstream support life cycles for Python and PostgreSQL are
  19076. documented at <a href="https://endoflife.date/python">https://endoflife.date/python</a> and
  19077. <a href="https://endoflife.date/postgresql">https://endoflife.date/postgresql</a>.</p>
  19078. <p>A Rust compiler is required to build Synapse from source. For any given release
  19079. the minimum required version may be bumped up to a recent Rust version, and so
  19080. people building from source should ensure they can fetch recent versions of Rust
  19081. (e.g. by using <a href="https://rustup.rs/">rustup</a>).</p>
  19082. <p>The oldest supported version of SQLite is the version
  19083. <a href="https://packages.debian.org/bullseye/libsqlite3-0">provided</a> by
  19084. <a href="https://wiki.debian.org/DebianOldStable">Debian oldstable</a>.</p>
  19085. <h2 id="context"><a class="header" href="#context">Context</a></h2>
  19086. <p>It is important for system admins to have a clear understanding of the platform
  19087. requirements of Synapse and its deprecation policies so that they can
  19088. effectively plan upgrading their infrastructure ahead of time. This is
  19089. especially important in contexts where upgrading the infrastructure requires
  19090. auditing and approval from a security team, or where otherwise upgrading is a
  19091. long process.</p>
  19092. <p>By following the upstream support life cycles Synapse can ensure that its
  19093. dependencies continue to get security patches, while not requiring system admins
  19094. to constantly update their platform dependencies to the latest versions.</p>
  19095. <p>For Rust, the situation is a bit different given that a) the Rust foundation
  19096. does not generally support older Rust versions, and b) the library ecosystem
  19097. generally bump their minimum support Rust versions frequently. In general, the
  19098. Synapse team will try to avoid updating the dependency on Rust to the absolute
  19099. latest version, but introducing a formal policy is hard given the constraints of
  19100. the ecosystem.</p>
  19101. <p>On a similar note, SQLite does not generally have a concept of &quot;supported
  19102. release&quot;; bugfixes are published for the latest minor release only. We chose to
  19103. track Debian's oldstable as this is relatively conservative, predictably updated
  19104. and is consistent with the <code>.deb</code> packages released by Matrix.org.</p>
  19105. <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>
  19106. <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>
  19107. <ul>
  19108. <li><strong>Platform</strong>: 2x1GHz armhf 2GiB ram <a href="https://wiki.debian.org/CheapServerBoxHardware">Single-board computers</a>, SSD, postgres.</li>
  19109. </ul>
  19110. <h3 id="presence-1"><a class="header" href="#presence-1">Presence</a></h3>
  19111. <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>
  19112. <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>
  19113. <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>
  19114. <h3 id="joining"><a class="header" href="#joining">Joining</a></h3>
  19115. <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>
  19116. <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>
  19117. <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>
  19118. <h3 id="sessions"><a class="header" href="#sessions">Sessions</a></h3>
  19119. <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>
  19120. <h3 id="recommended-configuration"><a class="header" href="#recommended-configuration">Recommended configuration</a></h3>
  19121. <p>Put the below in a new file at /etc/matrix-synapse/conf.d/sbc.yaml to override the defaults in homeserver.yaml.</p>
  19122. <pre><code># Disable presence tracking, which is currently fairly resource intensive
  19123. # More info: https://github.com/matrix-org/synapse/issues/9478
  19124. use_presence: false
  19125. # Set a small complexity limit, preventing users from joining large rooms
  19126. # which may be resource-intensive to remain a part of.
  19127. #
  19128. # Note that this will not prevent users from joining smaller rooms that
  19129. # eventually become complex.
  19130. limit_remote_rooms:
  19131. enabled: true
  19132. complexity: 3.0
  19133. # Database configuration
  19134. database:
  19135. # Use postgres for the best performance
  19136. name: psycopg2
  19137. args:
  19138. user: matrix-synapse
  19139. # Generate a long, secure password using a password manager
  19140. password: hunter2
  19141. database: matrix-synapse
  19142. host: localhost
  19143. </code></pre>
  19144. <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>
  19145. <pre><code>admin@homeserver:~$ zgrep '/client/r0/join/' /var/log/matrix-synapse/homeserver.log* | awk '{print $18, $25}' | sort --human-numeric-sort
  19146. 29.922sec/-0.002sec /_matrix/client/r0/join/%23debian-fasttrack%3Apoddery.com
  19147. 182.088sec/0.003sec /_matrix/client/r0/join/%23decentralizedweb-general%3Amatrix.org
  19148. 911.625sec/-570.847sec /_matrix/client/r0/join/%23synapse%3Amatrix.org
  19149. 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'
  19150. canonical_alias | joined_members | current_state_events
  19151. -------------------------------+----------------+----------------------
  19152. #_oftc_#debian:matrix.org | 871 | 52355
  19153. #matrix:matrix.org | 6379 | 10684
  19154. #irc:matrix.org | 461 | 3751
  19155. #decentralizedweb-general:matrix.org | 997 | 1509
  19156. #whatsapp:maunium.net | 554 | 854
  19157. </code></pre>
  19158. </main>
  19159. <nav class="nav-wrapper" aria-label="Page navigation">
  19160. <!-- Mobile navigation buttons -->
  19161. <div style="clear: both"></div>
  19162. </nav>
  19163. </div>
  19164. </div>
  19165. <nav class="nav-wide-wrapper" aria-label="Page navigation">
  19166. </nav>
  19167. </div>
  19168. <script type="text/javascript">
  19169. window.playground_copyable = true;
  19170. </script>
  19171. <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
  19172. <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
  19173. <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
  19174. <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
  19175. <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
  19176. <script src="book.js" type="text/javascript" charset="utf-8"></script>
  19177. <!-- Custom JS scripts -->
  19178. <script type="text/javascript" src="docs/website_files/table-of-contents.js"></script>
  19179. <script type="text/javascript" src="docs/website_files/version-picker.js"></script>
  19180. <script type="text/javascript" src="docs/website_files/version.js"></script>
  19181. <script type="text/javascript">
  19182. window.addEventListener('load', function() {
  19183. window.setTimeout(window.print, 100);
  19184. });
  19185. </script>
  19186. </body>
  19187. </html>