print.html 989 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105
  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. </head>
  31. <body>
  32. <!-- Provide site root to javascript -->
  33. <script type="text/javascript">
  34. var path_to_root = "";
  35. var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
  36. </script>
  37. <!-- Work around some values being stored in localStorage wrapped in quotes -->
  38. <script type="text/javascript">
  39. try {
  40. var theme = localStorage.getItem('mdbook-theme');
  41. var sidebar = localStorage.getItem('mdbook-sidebar');
  42. if (theme.startsWith('"') && theme.endsWith('"')) {
  43. localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
  44. }
  45. if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
  46. localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
  47. }
  48. } catch (e) { }
  49. </script>
  50. <!-- Set the theme before any content is loaded, prevents flash -->
  51. <script type="text/javascript">
  52. var theme;
  53. try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
  54. if (theme === null || theme === undefined) { theme = default_theme; }
  55. var html = document.querySelector('html');
  56. html.classList.remove('no-js')
  57. html.classList.remove('light')
  58. html.classList.add(theme);
  59. html.classList.add('js');
  60. </script>
  61. <!-- Hide / unhide sidebar before it is displayed -->
  62. <script type="text/javascript">
  63. var html = document.querySelector('html');
  64. var sidebar = 'hidden';
  65. if (document.body.clientWidth >= 1080) {
  66. try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
  67. sidebar = sidebar || 'visible';
  68. }
  69. html.classList.remove('sidebar-visible');
  70. html.classList.add("sidebar-" + sidebar);
  71. </script>
  72. <nav id="sidebar" class="sidebar" aria-label="Table of contents">
  73. <div class="sidebar-scrollbox">
  74. <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 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/media_admin_api.html">Media</a></li><li class="chapter-item expanded "><a href="admin_api/purge_history_api.html">Purge History</a></li><li class="chapter-item expanded "><a href="admin_api/register_api.html">Register Users</a></li><li class="chapter-item expanded "><a href="usage/administration/admin_api/registration_tokens.html">Registration Tokens</a></li><li class="chapter-item expanded "><a href="admin_api/room_membership.html">Manipulate Room Membership</a></li><li class="chapter-item expanded "><a href="admin_api/rooms.html">Rooms</a></li><li class="chapter-item expanded "><a href="admin_api/server_notices.html">Server Notices</a></li><li class="chapter-item expanded "><a href="admin_api/statistics.html">Statistics</a></li><li class="chapter-item expanded "><a href="admin_api/user_admin_api.html">Users</a></li><li class="chapter-item expanded "><a href="admin_api/version_api.html">Server Version</a></li><li class="chapter-item expanded "><a href="usage/administration/admin_api/federation.html">Federation</a></li></ol></li><li class="chapter-item expanded "><a href="manhole.html">Manhole</a></li><li class="chapter-item expanded "><a href="metrics-howto.html">Monitoring</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="usage/administration/monitoring/reporting_homeserver_usage_statistics.html">Reporting Homeserver Usage Statistics</a></li></ol></li><li class="chapter-item expanded "><a href="usage/administration/monthly_active_users.html">Monthly Active Users</a></li><li class="chapter-item expanded "><a href="usage/administration/understanding_synapse_through_grafana_graphs.html">Understanding Synapse Through Grafana Graphs</a></li><li class="chapter-item expanded "><a href="usage/administration/useful_sql_for_admins.html">Useful SQL for Admins</a></li><li class="chapter-item expanded "><a href="usage/administration/database_maintenance_tools.html">Database Maintenance Tools</a></li><li class="chapter-item expanded "><a href="usage/administration/state_groups.html">State Groups</a></li><li class="chapter-item expanded "><a href="usage/administration/request_log.html">Request log format</a></li><li class="chapter-item expanded "><a href="usage/administration/admin_faq.html">Admin FAQ</a></li><li class="chapter-item expanded "><div>Scripts</div></li></ol></li><li class="chapter-item expanded "><li class="part-title">Development</li><li class="chapter-item expanded "><a href="development/contributing_guide.html">Contributing Guide</a></li><li class="chapter-item expanded "><a href="code_style.html">Code Style</a></li><li class="chapter-item expanded "><a href="development/reviews.html">Reviewing Code</a></li><li class="chapter-item expanded "><a href="development/releases.html">Release Cycle</a></li><li class="chapter-item expanded "><a href="development/git.html">Git Usage</a></li><li class="chapter-item expanded "><div>Testing</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="development/demo.html">Demo scripts</a></li></ol></li><li class="chapter-item expanded "><a href="opentracing.html">OpenTracing</a></li><li class="chapter-item expanded "><a href="development/database_schema.html">Database Schemas</a></li><li class="chapter-item expanded "><a href="development/experimental_features.html">Experimental features</a></li><li class="chapter-item expanded "><a href="development/dependencies.html">Dependency management</a></li><li class="chapter-item expanded "><div>Synapse Architecture</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="development/synapse_architecture/cancellation.html">Cancellation</a></li><li class="chapter-item expanded "><a href="log_contexts.html">Log Contexts</a></li><li class="chapter-item expanded "><a href="replication.html">Replication</a></li><li class="chapter-item expanded "><a href="tcp_replication.html">TCP Replication</a></li></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>
  75. </div>
  76. <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
  77. </nav>
  78. <div id="page-wrapper" class="page-wrapper">
  79. <div class="page">
  80. <div id="menu-bar-hover-placeholder"></div>
  81. <div id="menu-bar" class="menu-bar sticky bordered">
  82. <div class="left-buttons">
  83. <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
  84. <i class="fa fa-bars"></i>
  85. </button>
  86. <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">
  87. <i class="fa fa-paint-brush"></i>
  88. </button>
  89. <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
  90. <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
  91. <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
  92. <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
  93. <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
  94. <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
  95. </ul>
  96. <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">
  97. <i class="fa fa-search"></i>
  98. </button>
  99. </div>
  100. <h1 class="menu-title">Synapse</h1>
  101. <div class="right-buttons">
  102. <a href="print.html" title="Print this book" aria-label="Print this book">
  103. <i id="print-button" class="fa fa-print"></i>
  104. </a>
  105. <a href="https://github.com/matrix-org/synapse" title="Git repository" aria-label="Git repository">
  106. <i id="git-repository-button" class="fa fa-github"></i>
  107. </a>
  108. </div>
  109. </div>
  110. <div id="search-wrapper" class="hidden">
  111. <form id="searchbar-outer" class="searchbar-outer">
  112. <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
  113. </form>
  114. <div id="searchresults-outer" class="searchresults-outer hidden">
  115. <div id="searchresults-header" class="searchresults-header"></div>
  116. <ul id="searchresults">
  117. </ul>
  118. </div>
  119. </div>
  120. <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
  121. <script type="text/javascript">
  122. document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
  123. document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
  124. Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
  125. link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
  126. });
  127. </script>
  128. <div id="content" class="content">
  129. <main>
  130. <!-- Page table of contents -->
  131. <div class="sidetoc">
  132. <nav class="pagetoc"></nav>
  133. </div>
  134. <div style="break-before: page; page-break-before: always;"></div><h1 id="introduction"><a class="header" href="#introduction">Introduction</a></h1>
  135. <p>Welcome to the documentation repository for Synapse, a
  136. <a href="https://matrix.org">Matrix</a> homeserver implementation developed by the matrix.org core
  137. team.</p>
  138. <h2 id="installing-and-using-synapse"><a class="header" href="#installing-and-using-synapse">Installing and using Synapse</a></h2>
  139. <p>This documentation covers topics for <strong>installation</strong>, <strong>configuration</strong> and
  140. <strong>maintenance</strong> of your Synapse process:</p>
  141. <ul>
  142. <li>
  143. <p>Learn how to <a href="setup/installation.html">install</a> and
  144. <a href="usage/configuration/config_documentation.html">configure</a> your own instance, perhaps with <a href="usage/configuration/user_authentication/index.html">Single
  145. Sign-On</a>.</p>
  146. </li>
  147. <li>
  148. <p>See how to <a href="upgrade.html">upgrade</a> between Synapse versions.</p>
  149. </li>
  150. <li>
  151. <p>Administer your instance using the <a href="usage/administration/admin_api/index.html">Admin
  152. API</a>, installing <a href="modules/index.html">pluggable
  153. modules</a>, or by accessing the <a href="manhole.html">manhole</a>.</p>
  154. </li>
  155. <li>
  156. <p>Learn how to <a href="usage/administration/request_log.html">read log lines</a>, configure
  157. <a href="usage/configuration/logging_sample_config.html">logging</a> or set up <a href="structured_logging.html">structured
  158. logging</a>.</p>
  159. </li>
  160. <li>
  161. <p>Scale Synapse through additional <a href="workers.html">worker processes</a>.</p>
  162. </li>
  163. <li>
  164. <p>Set up <a href="metrics-howto.html">monitoring and metrics</a> to keep an eye on your
  165. Synapse instance's performance.</p>
  166. </li>
  167. </ul>
  168. <h2 id="developing-on-synapse"><a class="header" href="#developing-on-synapse">Developing on Synapse</a></h2>
  169. <p>Contributions are welcome! Synapse is primarily written in
  170. <a href="https://python.org">Python</a>. As a developer, you may be interested in the
  171. following documentation:</p>
  172. <ul>
  173. <li>
  174. <p>Read the <a href="development/contributing_guide.html">Contributing Guide</a>. It is meant
  175. to walk new contributors through the process of developing and submitting a
  176. change to the Synapse codebase (which is <a href="https://github.com/matrix-org/synapse">hosted on
  177. GitHub</a>).</p>
  178. </li>
  179. <li>
  180. <p>Set up your <a href="development/contributing_guide.html#2-what-do-i-need">development
  181. environment</a>, then learn
  182. how to <a href="development/contributing_guide.html#run-the-linters">lint</a> and
  183. <a href="development/contributing_guide.html#8-test-test-test">test</a> your code.</p>
  184. </li>
  185. <li>
  186. <p>Look at <a href="https://github.com/matrix-org/synapse/issues">the issue tracker</a> for
  187. bugs to fix or features to add. If you're new, it may be best to start with
  188. those labeled <a href="https://github.com/matrix-org/synapse/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22">good first
  189. issue</a>.</p>
  190. </li>
  191. <li>
  192. <p>Understand <a href="development/internal_documentation/index.html">how Synapse is
  193. built</a>, how to <a href="development/database_schema.html">migrate
  194. database schemas</a>, learn about
  195. <a href="federate.html">federation</a> and how to <a href="federate.html#running-a-demo-federation-of-synapses">set up a local
  196. federation</a> for development.</p>
  197. </li>
  198. <li>
  199. <p>We like to keep our <code>git</code> history clean. <a href="development/git.html">Learn</a> how to
  200. do so!</p>
  201. </li>
  202. <li>
  203. <p>And finally, contribute to this documentation! The source for which is
  204. <a href="https://github.com/matrix-org/synapse/tree/develop/docs">located here</a>.</p>
  205. </li>
  206. </ul>
  207. <h2 id="donating-to-synapse-development"><a class="header" href="#donating-to-synapse-development">Donating to Synapse development</a></h2>
  208. <p>Want to help keep Synapse going but don't know how to code? Synapse is a
  209. <a href="https://matrix.org">Matrix.org Foundation</a> project. Consider becoming a
  210. supporter on <a href="https://liberapay.com/matrixdotorg">Liberapay</a>,
  211. <a href="https://patreon.com/matrixdotorg">Patreon</a> or through
  212. <a href="https://paypal.me/matrixdotorg">PayPal</a> via a one-time donation.</p>
  213. <p>If you are an organisation or enterprise and would like to sponsor development,
  214. reach out to us over email at: support (at) matrix.org</p>
  215. <h2 id="reporting-a-security-vulnerability"><a class="header" href="#reporting-a-security-vulnerability">Reporting a security vulnerability</a></h2>
  216. <p>If you've found a security issue in Synapse or any other Matrix.org Foundation
  217. project, please report it to us in accordance with our <a href="https://www.matrix.org/security-disclosure-policy/">Security Disclosure
  218. Policy</a>. Thank you!</p>
  219. <div style="break-before: page; page-break-before: always;"></div><h1 id="installation-instructions"><a class="header" href="#installation-instructions">Installation Instructions</a></h1>
  220. <h2 id="choosing-your-server-name"><a class="header" href="#choosing-your-server-name">Choosing your server name</a></h2>
  221. <p>It is important to choose the name for your server before you install Synapse,
  222. because it cannot be changed later.</p>
  223. <p>The server name determines the &quot;domain&quot; part of user-ids for users on your
  224. server: these will all be of the format <code>@user:my.domain.name</code>. It also
  225. determines how other matrix servers will reach yours for federation.</p>
  226. <p>For a test configuration, set this to the hostname of your server. For a more
  227. production-ready setup, you will probably want to specify your domain
  228. (<code>example.com</code>) rather than a matrix-specific hostname here (in the same way
  229. that your email address is probably <code>user@example.com</code> rather than
  230. <code>user@email.example.com</code>) - but doing so may require more advanced setup: see
  231. <a href="setup/../federate.html">Setting up Federation</a>.</p>
  232. <h2 id="installing-synapse"><a class="header" href="#installing-synapse">Installing Synapse</a></h2>
  233. <h3 id="prebuilt-packages"><a class="header" href="#prebuilt-packages">Prebuilt packages</a></h3>
  234. <p>Prebuilt packages are available for a number of platforms. These are recommended
  235. for most users.</p>
  236. <h4 id="docker-images-and-ansible-playbooks"><a class="header" href="#docker-images-and-ansible-playbooks">Docker images and Ansible playbooks</a></h4>
  237. <p>There is an official synapse image available at
  238. <a href="https://hub.docker.com/r/matrixdotorg/synapse">https://hub.docker.com/r/matrixdotorg/synapse</a> which can be used with
  239. the docker-compose file available at
  240. <a href="https://github.com/matrix-org/synapse/tree/develop/contrib/docker">contrib/docker</a>.
  241. Further information on this including configuration options is available in the README
  242. on hub.docker.com.</p>
  243. <p>Alternatively, Andreas Peters (previously Silvio Fricke) has contributed a
  244. Dockerfile to automate a synapse server in a single Docker image, at
  245. <a href="https://hub.docker.com/r/avhost/docker-matrix/tags/">https://hub.docker.com/r/avhost/docker-matrix/tags/</a></p>
  246. <p>Slavi Pantaleev has created an Ansible playbook,
  247. which installs the offical Docker image of Matrix Synapse
  248. along with many other Matrix-related services (Postgres database, Element, coturn,
  249. ma1sd, SSL support, etc.).
  250. For more details, see
  251. <a href="https://github.com/spantaleev/matrix-docker-ansible-deploy">https://github.com/spantaleev/matrix-docker-ansible-deploy</a></p>
  252. <h4 id="debianubuntu"><a class="header" href="#debianubuntu">Debian/Ubuntu</a></h4>
  253. <h5 id="matrixorg-packages"><a class="header" href="#matrixorg-packages">Matrix.org packages</a></h5>
  254. <p>Matrix.org provides Debian/Ubuntu packages of Synapse, for the amd64
  255. architecture via <a href="https://packages.matrix.org/debian/">https://packages.matrix.org/debian/</a>.</p>
  256. <p>To install the latest release:</p>
  257. <pre><code class="language-sh">sudo apt install -y lsb-release wget apt-transport-https
  258. sudo wget -O /usr/share/keyrings/matrix-org-archive-keyring.gpg https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg
  259. echo &quot;deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main&quot; |
  260. sudo tee /etc/apt/sources.list.d/matrix-org.list
  261. sudo apt update
  262. sudo apt install matrix-synapse-py3
  263. </code></pre>
  264. <p>Packages are also published for release candidates. To enable the prerelease
  265. channel, add <code>prerelease</code> to the <code>sources.list</code> line. For example:</p>
  266. <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
  267. echo &quot;deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main prerelease&quot; |
  268. sudo tee /etc/apt/sources.list.d/matrix-org.list
  269. sudo apt update
  270. sudo apt install matrix-synapse-py3
  271. </code></pre>
  272. <p>The fingerprint of the repository signing key (as shown by <code>gpg /usr/share/keyrings/matrix-org-archive-keyring.gpg</code>) is
  273. <code>AAF9AE843A7584B5A3E4CD2BCF45A512DE2DA058</code>.</p>
  274. <p>When installing with Debian packages, you might prefer to place files in
  275. <code>/etc/matrix-synapse/conf.d/</code> to override your configuration without editing
  276. the main configuration file at <code>/etc/matrix-synapse/homeserver.yaml</code>.
  277. By doing that, you won't be asked if you want to replace your configuration
  278. file when you upgrade the Debian package to a later version.</p>
  279. <h5 id="downstream-debian-packages"><a class="header" href="#downstream-debian-packages">Downstream Debian packages</a></h5>
  280. <p>Andrej Shadura maintains a <code>matrix-synapse</code> package in the Debian repositories.
  281. For <code>bookworm</code> and <code>sid</code>, it can be installed simply with:</p>
  282. <pre><code class="language-sh">sudo apt install matrix-synapse
  283. </code></pre>
  284. <p>Synapse is also avaliable in <code>bullseye-backports</code>. Please
  285. see the <a href="https://backports.debian.org/Instructions/">Debian documentation</a>
  286. for information on how to use backports.</p>
  287. <p><code>matrix-synapse</code> is no longer maintained for <code>buster</code> and older.</p>
  288. <h5 id="downstream-ubuntu-packages"><a class="header" href="#downstream-ubuntu-packages">Downstream Ubuntu packages</a></h5>
  289. <p>We do not recommend using the packages in the default Ubuntu repository
  290. at this time, as they are old and suffer from known security vulnerabilities.
  291. The latest version of Synapse can be installed from <a href="setup/installation.html#matrixorg-packages">our repository</a>.</p>
  292. <h4 id="fedora"><a class="header" href="#fedora">Fedora</a></h4>
  293. <p>Synapse is in the Fedora repositories as <code>matrix-synapse</code>:</p>
  294. <pre><code class="language-sh">sudo dnf install matrix-synapse
  295. </code></pre>
  296. <p>Oleg Girko provides Fedora RPMs at
  297. <a href="https://obs.infoserver.lv/project/monitor/matrix-synapse">https://obs.infoserver.lv/project/monitor/matrix-synapse</a></p>
  298. <h4 id="opensuse"><a class="header" href="#opensuse">OpenSUSE</a></h4>
  299. <p>Synapse is in the OpenSUSE repositories as <code>matrix-synapse</code>:</p>
  300. <pre><code class="language-sh">sudo zypper install matrix-synapse
  301. </code></pre>
  302. <h4 id="suse-linux-enterprise-server"><a class="header" href="#suse-linux-enterprise-server">SUSE Linux Enterprise Server</a></h4>
  303. <p>Unofficial package are built for SLES 15 in the openSUSE:Backports:SLE-15 repository at
  304. <a href="https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/">https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/</a></p>
  305. <h4 id="archlinux"><a class="header" href="#archlinux">ArchLinux</a></h4>
  306. <p>The quickest way to get up and running with ArchLinux is probably with the community package
  307. <a href="https://www.archlinux.org/packages/community/any/matrix-synapse/">https://www.archlinux.org/packages/community/any/matrix-synapse/</a>, which should pull in most of
  308. the necessary dependencies.</p>
  309. <p>pip may be outdated (6.0.7-1 and needs to be upgraded to 6.0.8-1 ):</p>
  310. <pre><code class="language-sh">sudo pip install --upgrade pip
  311. </code></pre>
  312. <p>If you encounter an error with lib bcrypt causing an Wrong ELF Class:
  313. ELFCLASS32 (x64 Systems), you may need to reinstall py-bcrypt to correctly
  314. compile it under the right architecture. (This should not be needed if
  315. installing under virtualenv):</p>
  316. <pre><code class="language-sh">sudo pip uninstall py-bcrypt
  317. sudo pip install py-bcrypt
  318. </code></pre>
  319. <h4 id="void-linux"><a class="header" href="#void-linux">Void Linux</a></h4>
  320. <p>Synapse can be found in the void repositories as 'synapse':</p>
  321. <pre><code class="language-sh">xbps-install -Su
  322. xbps-install -S synapse
  323. </code></pre>
  324. <h4 id="freebsd"><a class="header" href="#freebsd">FreeBSD</a></h4>
  325. <p>Synapse can be installed via FreeBSD Ports or Packages contributed by Brendan Molloy from:</p>
  326. <ul>
  327. <li>Ports: <code>cd /usr/ports/net-im/py-matrix-synapse &amp;&amp; make install clean</code></li>
  328. <li>Packages: <code>pkg install py38-matrix-synapse</code></li>
  329. </ul>
  330. <h4 id="openbsd"><a class="header" href="#openbsd">OpenBSD</a></h4>
  331. <p>As of OpenBSD 6.7 Synapse is available as a pre-compiled binary. The filesystem
  332. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  333. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  334. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  335. <p>Installing Synapse:</p>
  336. <pre><code class="language-sh">doas pkg_add synapse
  337. </code></pre>
  338. <h4 id="nixos"><a class="header" href="#nixos">NixOS</a></h4>
  339. <p>Robin Lambertz has packaged Synapse for NixOS at:
  340. <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>
  341. <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>
  342. <p>It's also possible to install Synapse as a Python module from PyPI.</p>
  343. <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>
  344. <p>System requirements:</p>
  345. <ul>
  346. <li>POSIX-compliant system (tested on Linux &amp; OS X)</li>
  347. <li>Python 3.7 or later, up to Python 3.10.</li>
  348. <li>At least 1GB of free RAM if you want to join large public rooms like #matrix:matrix.org</li>
  349. </ul>
  350. <p>If building on an uncommon architecture for which pre-built wheels are
  351. unavailable, you will need to have a recent Rust compiler installed. The easiest
  352. way of installing the latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
  353. <p>To install the Synapse homeserver run:</p>
  354. <pre><code class="language-sh">mkdir -p ~/synapse
  355. virtualenv -p python3 ~/synapse/env
  356. source ~/synapse/env/bin/activate
  357. pip install --upgrade pip
  358. pip install --upgrade setuptools
  359. pip install matrix-synapse
  360. </code></pre>
  361. <p>This will download Synapse from <a href="https://pypi.org/project/matrix-synapse">PyPI</a>
  362. and install it, along with the python libraries it uses, into a virtual environment
  363. under <code>~/synapse/env</code>. Feel free to pick a different directory if you
  364. prefer.</p>
  365. <p>This Synapse installation can then be later upgraded by using pip again with the
  366. update flag:</p>
  367. <pre><code class="language-sh">source ~/synapse/env/bin/activate
  368. pip install -U matrix-synapse
  369. </code></pre>
  370. <p>Before you can start Synapse, you will need to generate a configuration
  371. file. To do this, run (in your virtualenv, as before):</p>
  372. <pre><code class="language-sh">cd ~/synapse
  373. python -m synapse.app.homeserver \
  374. --server-name my.domain.name \
  375. --config-path homeserver.yaml \
  376. --generate-config \
  377. --report-stats=[yes|no]
  378. </code></pre>
  379. <p>... substituting an appropriate value for <code>--server-name</code> and choosing whether
  380. or not to report usage statistics (hostname, Synapse version, uptime, total
  381. users, etc.) to the developers via the <code>--report-stats</code> argument.</p>
  382. <p>This command will generate you a config file that you can then customise, but it will
  383. also generate a set of keys for you. These keys will allow your homeserver to
  384. identify itself to other homeserver, so don't lose or delete them. It would be
  385. wise to back them up somewhere safe. (If, for whatever reason, you do need to
  386. change your homeserver's keys, you may find that other homeserver have the
  387. old key cached. If you update the signing key, you should change the name of the
  388. key in the <code>&lt;server name&gt;.signing.key</code> file (the second word) to something
  389. 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>
  390. <p>To actually run your new homeserver, pick a working directory for Synapse to
  391. run (e.g. <code>~/synapse</code>), and:</p>
  392. <pre><code class="language-sh">cd ~/synapse
  393. source env/bin/activate
  394. synctl start
  395. </code></pre>
  396. <h4 id="platform-specific-prerequisites"><a class="header" href="#platform-specific-prerequisites">Platform-specific prerequisites</a></h4>
  397. <p>Synapse is written in Python but some of the libraries it uses are written in
  398. C. So before we can install Synapse itself we need a working C compiler and the
  399. header files for Python C extensions.</p>
  400. <h5 id="debianubunturaspbian"><a class="header" href="#debianubunturaspbian">Debian/Ubuntu/Raspbian</a></h5>
  401. <p>Installing prerequisites on Ubuntu or Debian:</p>
  402. <pre><code class="language-sh">sudo apt install build-essential python3-dev libffi-dev \
  403. python3-pip python3-setuptools sqlite3 \
  404. libssl-dev virtualenv libjpeg-dev libxslt1-dev
  405. </code></pre>
  406. <h5 id="archlinux-1"><a class="header" href="#archlinux-1">ArchLinux</a></h5>
  407. <p>Installing prerequisites on ArchLinux:</p>
  408. <pre><code class="language-sh">sudo pacman -S base-devel python python-pip \
  409. python-setuptools python-virtualenv sqlite3
  410. </code></pre>
  411. <h5 id="centosfedora"><a class="header" href="#centosfedora">CentOS/Fedora</a></h5>
  412. <p>Installing prerequisites on CentOS or Fedora Linux:</p>
  413. <pre><code class="language-sh">sudo dnf install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
  414. libwebp-devel libxml2-devel libxslt-devel libpq-devel \
  415. python3-virtualenv libffi-devel openssl-devel python3-devel
  416. sudo dnf groupinstall &quot;Development Tools&quot;
  417. </code></pre>
  418. <h5 id="macos"><a class="header" href="#macos">macOS</a></h5>
  419. <p>Installing prerequisites on macOS:</p>
  420. <p>You may need to install the latest Xcode developer tools:</p>
  421. <pre><code class="language-sh">xcode-select --install
  422. </code></pre>
  423. <p>On ARM-based Macs you may need to install libjpeg and libpq.
  424. You can use Homebrew (https://brew.sh):</p>
  425. <pre><code class="language-sh"> brew install jpeg libpq
  426. </code></pre>
  427. <p>On macOS Catalina (10.15) you may need to explicitly install OpenSSL
  428. via brew and inform <code>pip</code> about it so that <code>psycopg2</code> builds:</p>
  429. <pre><code class="language-sh">brew install openssl@1.1
  430. export LDFLAGS=&quot;-L/usr/local/opt/openssl/lib&quot;
  431. export CPPFLAGS=&quot;-I/usr/local/opt/openssl/include&quot;
  432. </code></pre>
  433. <h5 id="opensuse-1"><a class="header" href="#opensuse-1">OpenSUSE</a></h5>
  434. <p>Installing prerequisites on openSUSE:</p>
  435. <pre><code class="language-sh">sudo zypper in -t pattern devel_basis
  436. sudo zypper in python-pip python-setuptools sqlite3 python-virtualenv \
  437. python-devel libffi-devel libopenssl-devel libjpeg62-devel
  438. </code></pre>
  439. <h5 id="openbsd-1"><a class="header" href="#openbsd-1">OpenBSD</a></h5>
  440. <p>A port of Synapse is available under <code>net/synapse</code>. The filesystem
  441. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  442. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  443. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  444. <p>To be able to build Synapse's dependency on python the <code>WRKOBJDIR</code>
  445. (cf. <code>bsd.port.mk(5)</code>) for building python, too, needs to be on a filesystem
  446. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>).</p>
  447. <p>Creating a <code>WRKOBJDIR</code> for building python under <code>/usr/local</code> (which on a
  448. default OpenBSD installation is mounted with <code>wxallowed</code>):</p>
  449. <pre><code class="language-sh">doas mkdir /usr/local/pobj_wxallowed
  450. </code></pre>
  451. <p>Assuming <code>PORTS_PRIVSEP=Yes</code> (cf. <code>bsd.port.mk(5)</code>) and <code>SUDO=doas</code> are
  452. configured in <code>/etc/mk.conf</code>:</p>
  453. <pre><code class="language-sh">doas chown _pbuild:_pbuild /usr/local/pobj_wxallowed
  454. </code></pre>
  455. <p>Setting the <code>WRKOBJDIR</code> for building python:</p>
  456. <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
  457. </code></pre>
  458. <p>Building Synapse:</p>
  459. <pre><code class="language-sh">cd /usr/ports/net/synapse
  460. make install
  461. </code></pre>
  462. <h5 id="windows"><a class="header" href="#windows">Windows</a></h5>
  463. <p>Running Synapse natively on Windows is not officially supported.</p>
  464. <p>If you wish to run or develop Synapse on Windows, the Windows Subsystem for
  465. Linux provides a Linux environment which is capable of using the Debian, Fedora,
  466. or source installation methods. More information about WSL can be found at
  467. <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
  468. <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
  469. Windows Server.</p>
  470. <h2 id="setting-up-synapse"><a class="header" href="#setting-up-synapse">Setting up Synapse</a></h2>
  471. <p>Once you have installed synapse as above, you will need to configure it.</p>
  472. <h3 id="using-postgresql"><a class="header" href="#using-postgresql">Using PostgreSQL</a></h3>
  473. <p>By default Synapse uses an <a href="https://sqlite.org/">SQLite</a> database and in doing so trades
  474. performance for convenience. Almost all installations should opt to use <a href="https://www.postgresql.org">PostgreSQL</a>
  475. instead. Advantages include:</p>
  476. <ul>
  477. <li>significant performance improvements due to the superior threading and
  478. caching model, smarter query optimiser</li>
  479. <li>allowing the DB to be run on separate hardware</li>
  480. </ul>
  481. <p>For information on how to install and use PostgreSQL in Synapse, please see
  482. <a href="setup/../postgres.html">Using Postgres</a></p>
  483. <p>SQLite is only acceptable for testing purposes. SQLite should not be used in
  484. a production server. Synapse will perform poorly when using
  485. SQLite, especially when participating in large rooms.</p>
  486. <h3 id="tls-certificates"><a class="header" href="#tls-certificates">TLS certificates</a></h3>
  487. <p>The default configuration exposes a single HTTP port on the local
  488. interface: <code>http://localhost:8008</code>. It is suitable for local testing,
  489. but for any practical use, you will need Synapse's APIs to be served
  490. over HTTPS.</p>
  491. <p>The recommended way to do so is to set up a reverse proxy on port
  492. <code>8448</code>. You can find documentation on doing so in
  493. <a href="setup/../reverse_proxy.html">the reverse proxy documentation</a>.</p>
  494. <p>Alternatively, you can configure Synapse to expose an HTTPS port. To do
  495. so, you will need to edit <code>homeserver.yaml</code>, as follows:</p>
  496. <ul>
  497. <li>First, under the <code>listeners</code> option, add the configuration for the
  498. TLS-enabled listener like so:</li>
  499. </ul>
  500. <pre><code class="language-yaml">listeners:
  501. - port: 8448
  502. type: http
  503. tls: true
  504. resources:
  505. - names: [client, federation]
  506. </code></pre>
  507. <ul>
  508. <li>
  509. <p>You will also need to add the options <code>tls_certificate_path</code> and
  510. <code>tls_private_key_path</code>. to your configuration file. You will need to manage provisioning of
  511. these certificates yourself.</p>
  512. </li>
  513. <li>
  514. <p>You can find more information about these options as well as how to configure synapse in the
  515. <a href="setup/../usage/configuration/config_documentation.html">configuration manual</a>.</p>
  516. <p>If you are using your own certificate, be sure to use a <code>.pem</code> file that
  517. includes the full certificate chain including any intermediate certificates
  518. (for instance, if using certbot, use <code>fullchain.pem</code> as your certificate, not
  519. <code>cert.pem</code>).</p>
  520. </li>
  521. </ul>
  522. <p>For a more detailed guide to configuring your server for federation, see
  523. <a href="setup/../federate.html">Federation</a>.</p>
  524. <h3 id="client-well-known-uri"><a class="header" href="#client-well-known-uri">Client Well-Known URI</a></h3>
  525. <p>Setting up the client Well-Known URI is optional but if you set it up, it will
  526. allow users to enter their full username (e.g. <code>@user:&lt;server_name&gt;</code>) into clients
  527. which support well-known lookup to automatically configure the homeserver and
  528. identity server URLs. This is useful so that users don't have to memorize or think
  529. about the actual homeserver URL you are using.</p>
  530. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/client</code> should return JSON in
  531. the following format.</p>
  532. <pre><code class="language-json">{
  533. &quot;m.homeserver&quot;: {
  534. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  535. }
  536. }
  537. </code></pre>
  538. <p>It can optionally contain identity server information as well.</p>
  539. <pre><code class="language-json">{
  540. &quot;m.homeserver&quot;: {
  541. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  542. },
  543. &quot;m.identity_server&quot;: {
  544. &quot;base_url&quot;: &quot;https://&lt;identity.example.com&gt;&quot;
  545. }
  546. }
  547. </code></pre>
  548. <p>To work in browser based clients, the file must be served with the appropriate
  549. Cross-Origin Resource Sharing (CORS) headers. A recommended value would be
  550. <code>Access-Control-Allow-Origin: *</code> which would allow all browser based clients to
  551. view it.</p>
  552. <p>In nginx this would be something like:</p>
  553. <pre><code class="language-nginx">location /.well-known/matrix/client {
  554. return 200 '{&quot;m.homeserver&quot;: {&quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;}}';
  555. default_type application/json;
  556. add_header Access-Control-Allow-Origin *;
  557. }
  558. </code></pre>
  559. <p>You should also ensure the <code>public_baseurl</code> option in <code>homeserver.yaml</code> is set
  560. correctly. <code>public_baseurl</code> should be set to the URL that clients will use to
  561. connect to your server. This is the same URL you put for the <code>m.homeserver</code>
  562. <code>base_url</code> above.</p>
  563. <pre><code class="language-yaml">public_baseurl: &quot;https://&lt;matrix.example.com&gt;&quot;
  564. </code></pre>
  565. <h3 id="email"><a class="header" href="#email">Email</a></h3>
  566. <p>It is desirable for Synapse to have the capability to send email. This allows
  567. Synapse to send password reset emails, send verifications when an email address
  568. is added to a user's account, and send email notifications to users when they
  569. receive new messages.</p>
  570. <p>To configure an SMTP server for Synapse, modify the configuration section
  571. headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>, <code>smtp_port</code>
  572. and <code>notif_from</code> fields filled out. You may also need to set <code>smtp_user</code>,
  573. <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  574. <p>If email is not configured, password reset, registration and notifications via
  575. email will be disabled.</p>
  576. <h3 id="registering-a-user"><a class="header" href="#registering-a-user">Registering a user</a></h3>
  577. <p>One way to create a new user is to do so from a client like
  578. <a href="https://element.io/">Element</a>. This requires registration to be enabled via
  579. the
  580. <a href="setup/../usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a>
  581. setting.</p>
  582. <p>Alternatively, you can create new users from the command line. This can be done as follows:</p>
  583. <ol>
  584. <li>If synapse was installed via pip, activate the virtualenv as follows (if Synapse was
  585. installed via a prebuilt package, <code>register_new_matrix_user</code> should already be
  586. on the search path):
  587. <pre><code class="language-sh">cd ~/synapse
  588. source env/bin/activate
  589. synctl start # if not already running
  590. </code></pre>
  591. </li>
  592. <li>Run the following command:
  593. <pre><code class="language-sh">register_new_matrix_user -c homeserver.yaml
  594. </code></pre>
  595. </li>
  596. </ol>
  597. <p>This will prompt you to add details for the new user, and will then connect to
  598. the running Synapse to create the new user. For example:</p>
  599. <pre><code>New user localpart: erikj
  600. Password:
  601. Confirm password:
  602. Make admin [no]:
  603. Success!
  604. </code></pre>
  605. <p>This process uses a setting
  606. <a href="setup/../usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>,
  607. which is shared between Synapse itself and the <code>register_new_matrix_user</code>
  608. script. It doesn't matter what it is (a random value is generated by
  609. <code>--generate-config</code>), but it should be kept secret, as anyone with knowledge of
  610. it can register users, including admin accounts, on your server even if
  611. <code>enable_registration</code> is <code>false</code>.</p>
  612. <h3 id="setting-up-a-turn-server"><a class="header" href="#setting-up-a-turn-server">Setting up a TURN server</a></h3>
  613. <p>For reliable VoIP calls to be routed via this homeserver, you MUST configure
  614. a TURN server. See <a href="setup/../turn-howto.html">TURN setup</a> for details.</p>
  615. <h3 id="url-previews"><a class="header" href="#url-previews">URL previews</a></h3>
  616. <p>Synapse includes support for previewing URLs, which is disabled by default. To
  617. turn it on you must enable the <code>url_preview_enabled: True</code> config parameter
  618. and explicitly specify the IP ranges that Synapse is not allowed to spider for
  619. previewing in the <code>url_preview_ip_range_blacklist</code> configuration parameter.
  620. This is critical from a security perspective to stop arbitrary Matrix users
  621. spidering 'internal' URLs on your network. At the very least we recommend that
  622. your loopback and RFC1918 IP addresses are blacklisted.</p>
  623. <p>This also requires the optional <code>lxml</code> python dependency to be installed. This
  624. in turn requires the <code>libxml2</code> library to be available - on Debian/Ubuntu this
  625. means <code>apt-get install libxml2-dev</code>, or equivalent for your OS.</p>
  626. <h3 id="troubleshooting-installation"><a class="header" href="#troubleshooting-installation">Troubleshooting Installation</a></h3>
  627. <p><code>pip</code> seems to leak <em>lots</em> of memory during installation. For instance, a Linux
  628. host with 512MB of RAM may run out of memory whilst installing Twisted. If this
  629. happens, you will have to individually install the dependencies which are
  630. failing, e.g.:</p>
  631. <pre><code class="language-sh">pip install twisted
  632. </code></pre>
  633. <p>If you have any other problems, feel free to ask in
  634. <a href="https://matrix.to/#/#synapse:matrix.org">#synapse:matrix.org</a>.</p>
  635. <div style="break-before: page; page-break-before: always;"></div><h1 id="using-postgres"><a class="header" href="#using-postgres">Using Postgres</a></h1>
  636. <p>Synapse supports PostgreSQL versions 10 or later.</p>
  637. <h2 id="install-postgres-client-libraries"><a class="header" href="#install-postgres-client-libraries">Install postgres client libraries</a></h2>
  638. <p>Synapse will require the python postgres client library in order to
  639. connect to a postgres database.</p>
  640. <ul>
  641. <li>
  642. <p>If you are using the <a href="setup/installation.html#matrixorg-packages">matrix.org debian/ubuntu
  643. packages</a>, the necessary python
  644. library will already be installed, but you will need to ensure the
  645. low-level postgres library is installed, which you can do with
  646. <code>apt install libpq5</code>.</p>
  647. </li>
  648. <li>
  649. <p>For other pre-built packages, please consult the documentation from
  650. the relevant package.</p>
  651. </li>
  652. <li>
  653. <p>If you installed synapse <a href="setup/installation.html#installing-from-source">in a
  654. virtualenv</a>, you can install
  655. the library with:</p>
  656. <pre><code>~/synapse/env/bin/pip install &quot;matrix-synapse[postgres]&quot;
  657. </code></pre>
  658. <p>(substituting the path to your virtualenv for <code>~/synapse/env</code>, if
  659. you used a different path). You will require the postgres
  660. development files. These are in the <code>libpq-dev</code> package on
  661. Debian-derived distributions.</p>
  662. </li>
  663. </ul>
  664. <h2 id="set-up-database"><a class="header" href="#set-up-database">Set up database</a></h2>
  665. <p>Assuming your PostgreSQL database user is called <code>postgres</code>, first authenticate as the database user with:</p>
  666. <pre><code class="language-sh">su - postgres
  667. # Or, if your system uses sudo to get administrative rights
  668. sudo -u postgres bash
  669. </code></pre>
  670. <p>Then, create a postgres user and a database with:</p>
  671. <pre><code class="language-sh"># this will prompt for a password for the new user
  672. createuser --pwprompt synapse_user
  673. createdb --encoding=UTF8 --locale=C --template=template0 --owner=synapse_user synapse
  674. </code></pre>
  675. <p>The above will create a user called <code>synapse_user</code>, and a database called
  676. <code>synapse</code>.</p>
  677. <p>Note that the PostgreSQL database <em>must</em> have the correct encoding set
  678. (as shown above), otherwise it will not be able to store UTF8 strings.</p>
  679. <p>You may need to enable password authentication so <code>synapse_user</code> can
  680. connect to the database. See
  681. <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>
  682. <h2 id="synapse-config"><a class="header" href="#synapse-config">Synapse config</a></h2>
  683. <p>When you are ready to start using PostgreSQL, edit the <code>database</code>
  684. section in your config file to match the following lines:</p>
  685. <pre><code class="language-yaml">database:
  686. name: psycopg2
  687. args:
  688. user: &lt;user&gt;
  689. password: &lt;pass&gt;
  690. database: &lt;db&gt;
  691. host: &lt;host&gt;
  692. cp_min: 5
  693. cp_max: 10
  694. </code></pre>
  695. <p>All key, values in <code>args</code> are passed to the <code>psycopg2.connect(..)</code>
  696. function, except keys beginning with <code>cp_</code>, which are consumed by the
  697. twisted adbapi connection pool. See the <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">libpq
  698. documentation</a>
  699. for a list of options which can be passed.</p>
  700. <p>You should consider tuning the <code>args.keepalives_*</code> options if there is any danger of
  701. the connection between your homeserver and database dropping, otherwise Synapse
  702. may block for an extended period while it waits for a response from the
  703. database server. Example values might be:</p>
  704. <pre><code class="language-yaml">database:
  705. args:
  706. # ... as above
  707. # seconds of inactivity after which TCP should send a keepalive message to the server
  708. keepalives_idle: 10
  709. # the number of seconds after which a TCP keepalive message that is not
  710. # acknowledged by the server should be retransmitted
  711. keepalives_interval: 10
  712. # the number of TCP keepalives that can be lost before the client's connection
  713. # to the server is considered dead
  714. keepalives_count: 3
  715. </code></pre>
  716. <h2 id="tuning-postgres"><a class="header" href="#tuning-postgres">Tuning Postgres</a></h2>
  717. <p>The default settings should be fine for most deployments. For larger
  718. scale deployments tuning some of the settings is recommended, details of
  719. which can be found at
  720. <a href="https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server">https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server</a>.</p>
  721. <p>In particular, we've found tuning the following values helpful for
  722. performance:</p>
  723. <ul>
  724. <li><code>shared_buffers</code></li>
  725. <li><code>effective_cache_size</code></li>
  726. <li><code>work_mem</code></li>
  727. <li><code>maintenance_work_mem</code></li>
  728. <li><code>autovacuum_work_mem</code></li>
  729. </ul>
  730. <p>Note that the appropriate values for those fields depend on the amount
  731. of free memory the database host has available.</p>
  732. <p>Additionally, admins of large deployments might want to consider using huge pages
  733. to help manage memory, especially when using large values of <code>shared_buffers</code>. You
  734. can read more about that <a href="https://www.postgresql.org/docs/10/kernel-resources.html#LINUX-HUGE-PAGES">here</a>.</p>
  735. <h2 id="porting-from-sqlite"><a class="header" href="#porting-from-sqlite">Porting from SQLite</a></h2>
  736. <h3 id="overview"><a class="header" href="#overview">Overview</a></h3>
  737. <p>The script <code>synapse_port_db</code> allows porting an existing synapse server
  738. backed by SQLite to using PostgreSQL. This is done in as a two phase
  739. process:</p>
  740. <ol>
  741. <li>Copy the existing SQLite database to a separate location and run
  742. the port script against that offline database.</li>
  743. <li>Shut down the server. Rerun the port script to port any data that
  744. has come in since taking the first snapshot. Restart server against
  745. the PostgreSQL database.</li>
  746. </ol>
  747. <p>The port script is designed to be run repeatedly against newer snapshots
  748. of the SQLite database file. This makes it safe to repeat step 1 if
  749. there was a delay between taking the previous snapshot and being ready
  750. to do step 2.</p>
  751. <p>It is safe to at any time kill the port script and restart it.</p>
  752. <p>However, under no circumstances should the SQLite database be <code>VACUUM</code>ed between
  753. multiple runs of the script. Doing so can lead to an inconsistent copy of your database
  754. into Postgres.
  755. To avoid accidental error, the script will check that SQLite's <code>auto_vacuum</code> mechanism
  756. is disabled, but the script is not able to protect against a manual <code>VACUUM</code> operation
  757. performed either by the administrator or by any automated task that the administrator
  758. may have configured.</p>
  759. <p>Note that the database may take up significantly more (25% - 100% more)
  760. space on disk after porting to Postgres.</p>
  761. <h3 id="using-the-port-script"><a class="header" href="#using-the-port-script">Using the port script</a></h3>
  762. <p>Firstly, shut down the currently running synapse server and copy its
  763. database file (typically <code>homeserver.db</code>) to another location. Once the
  764. copy is complete, restart synapse. For instance:</p>
  765. <pre><code class="language-sh">synctl stop
  766. cp homeserver.db homeserver.db.snapshot
  767. synctl start
  768. </code></pre>
  769. <p>Copy the old config file into a new config file:</p>
  770. <pre><code class="language-sh">cp homeserver.yaml homeserver-postgres.yaml
  771. </code></pre>
  772. <p>Edit the database section as described in the section <em>Synapse config</em>
  773. above and with the SQLite snapshot located at <code>homeserver.db.snapshot</code>
  774. simply run:</p>
  775. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db.snapshot \
  776. --postgres-config homeserver-postgres.yaml
  777. </code></pre>
  778. <p>The flag <code>--curses</code> displays a coloured curses progress UI.</p>
  779. <p>If the script took a long time to complete, or time has otherwise passed
  780. since the original snapshot was taken, repeat the previous steps with a
  781. newer snapshot.</p>
  782. <p>To complete the conversion shut down the synapse server and run the port
  783. script one last time, e.g. if the SQLite database is at <code>homeserver.db</code>
  784. run:</p>
  785. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db \
  786. --postgres-config homeserver-postgres.yaml
  787. </code></pre>
  788. <p>Once that has completed, change the synapse config to point at the
  789. PostgreSQL database configuration file <code>homeserver-postgres.yaml</code>:</p>
  790. <pre><code class="language-sh">synctl stop
  791. mv homeserver.yaml homeserver-old-sqlite.yaml
  792. mv homeserver-postgres.yaml homeserver.yaml
  793. synctl start
  794. </code></pre>
  795. <p>Synapse should now be running against PostgreSQL.</p>
  796. <h2 id="troubleshooting"><a class="header" href="#troubleshooting">Troubleshooting</a></h2>
  797. <h3 id="alternative-auth-methods"><a class="header" href="#alternative-auth-methods">Alternative auth methods</a></h3>
  798. <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
  799. <code>ident</code>:</p>
  800. <ul>
  801. <li>
  802. <p>If the <code>synapse_user</code> user has a password, add the password to the <code>database:</code>
  803. section of <code>homeserver.yaml</code>. Then add the following to <code>pg_hba.conf</code>:</p>
  804. <pre><code>host synapse synapse_user ::1/128 md5 # or `scram-sha-256` instead of `md5` if you use that
  805. </code></pre>
  806. </li>
  807. <li>
  808. <p>If the <code>synapse_user</code> user does not have a password, then a password doesn't
  809. have to be added to <code>homeserver.yaml</code>. But the following does need to be added
  810. to <code>pg_hba.conf</code>:</p>
  811. <pre><code>host synapse synapse_user ::1/128 trust
  812. </code></pre>
  813. </li>
  814. </ul>
  815. <p>Note that line order matters in <code>pg_hba.conf</code>, so make sure that if you do add a
  816. new line, it is inserted before:</p>
  817. <pre><code>host all all ::1/128 ident
  818. </code></pre>
  819. <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>
  820. <p>Synapse will refuse to set up a new database if it has the wrong values of
  821. <code>COLLATE</code> and <code>CTYPE</code> set. Synapse will also refuse to start an existing database with incorrect values
  822. of <code>COLLATE</code> and <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the
  823. <code>database</code> section of the config, is set to true. Using different locales can cause issues if the locale library is updated from
  824. underneath the database, or if a different version of the locale is used on any
  825. replicas.</p>
  826. <p>If you have a databse with an unsafe locale, the safest way to fix the issue is to dump the database and recreate it with
  827. the correct locale parameter (as shown above). It is also possible to change the
  828. parameters on a live database and run a <code>REINDEX</code> on the entire database,
  829. however extreme care must be taken to avoid database corruption.</p>
  830. <p>Note that the above may fail with an error about duplicate rows if corruption
  831. has already occurred, and such duplicate rows will need to be manually removed.</p>
  832. <h3 id="fixing-inconsistent-sequences-error"><a class="header" href="#fixing-inconsistent-sequences-error">Fixing inconsistent sequences error</a></h3>
  833. <p>Synapse uses Postgres sequences to generate IDs for various tables. A sequence
  834. and associated table can get out of sync if, for example, Synapse has been
  835. downgraded and then upgraded again.</p>
  836. <p>To fix the issue shut down Synapse (including any and all workers) and run the
  837. SQL command included in the error message. Once done Synapse should start
  838. successfully.</p>
  839. <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>
  840. <p>It is recommended to put a reverse proxy such as
  841. <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">nginx</a>,
  842. <a href="https://httpd.apache.org/docs/current/mod/mod_proxy_http.html">Apache</a>,
  843. <a href="https://caddyserver.com/docs/quick-starts/reverse-proxy">Caddy</a>,
  844. <a href="https://www.haproxy.org/">HAProxy</a> or
  845. <a href="https://man.openbsd.org/relayd.8">relayd</a> in front of Synapse. One advantage
  846. of doing so is that it means that you can expose the default https port
  847. (443) to Matrix clients without needing to run Synapse with root
  848. privileges.</p>
  849. <p>You should configure your reverse proxy to forward requests to <code>/_matrix</code> or
  850. <code>/_synapse/client</code> to Synapse, and have it set the <code>X-Forwarded-For</code> and
  851. <code>X-Forwarded-Proto</code> request headers.</p>
  852. <p>You should remember that Matrix clients and other Matrix servers do not
  853. necessarily need to connect to your server via the same server name or
  854. port. Indeed, clients will use port 443 by default, whereas servers default to
  855. port 8448. Where these are different, we refer to the 'client port' and the
  856. 'federation port'. See <a href="https://matrix.org/docs/spec/server_server/latest#resolving-server-names">the Matrix
  857. specification</a>
  858. for more details of the algorithm used for federation connections, and
  859. <a href="delegate.html">Delegation</a> for instructions on setting up delegation.</p>
  860. <p><strong>NOTE</strong>: Your reverse proxy must not <code>canonicalise</code> or <code>normalise</code>
  861. the requested URI in any way (for example, by decoding <code>%xx</code> escapes).
  862. Beware that Apache <em>will</em> canonicalise URIs unless you specify
  863. <code>nocanon</code>.</p>
  864. <p>Let's assume that we expect clients to connect to our server at
  865. <code>https://matrix.example.com</code>, and other servers to connect at
  866. <code>https://example.com:8448</code>. The following sections detail the configuration of
  867. the reverse proxy and the homeserver.</p>
  868. <h2 id="homeserver-configuration"><a class="header" href="#homeserver-configuration">Homeserver Configuration</a></h2>
  869. <p>The HTTP configuration will need to be updated for Synapse to correctly record
  870. client IP addresses and generate redirect URLs while behind a reverse proxy. </p>
  871. <p>In <code>homeserver.yaml</code> set <code>x_forwarded: true</code> in the port 8008 section and
  872. consider setting <code>bind_addresses: ['127.0.0.1']</code> so that the server only
  873. listens to traffic on localhost. (Do not change <code>bind_addresses</code> to <code>127.0.0.1</code>
  874. when using a containerized Synapse, as that will prevent it from responding
  875. to proxied traffic.)</p>
  876. <p>Optionally, you can also set
  877. <a href="../usage/configuration/config_documentation.html#listeners"><code>request_id_header</code></a>
  878. so that the server extracts and re-uses the same request ID format that the
  879. reverse proxy is using.</p>
  880. <h2 id="reverse-proxy-configuration-examples"><a class="header" href="#reverse-proxy-configuration-examples">Reverse-proxy configuration examples</a></h2>
  881. <p><strong>NOTE</strong>: You only need one of these.</p>
  882. <h3 id="nginx"><a class="header" href="#nginx">nginx</a></h3>
  883. <pre><code class="language-nginx">server {
  884. listen 443 ssl http2;
  885. listen [::]:443 ssl http2;
  886. # For the federation port
  887. listen 8448 ssl http2 default_server;
  888. listen [::]:8448 ssl http2 default_server;
  889. server_name matrix.example.com;
  890. location ~ ^(/_matrix|/_synapse/client) {
  891. # note: do not add a path (even a single /) after the port in `proxy_pass`,
  892. # otherwise nginx will canonicalise the URI and cause signature verification
  893. # errors.
  894. proxy_pass http://localhost:8008;
  895. proxy_set_header X-Forwarded-For $remote_addr;
  896. proxy_set_header X-Forwarded-Proto $scheme;
  897. proxy_set_header Host $host;
  898. # Nginx by default only allows file uploads up to 1M in size
  899. # Increase client_max_body_size to match max_upload_size defined in homeserver.yaml
  900. client_max_body_size 50M;
  901. }
  902. }
  903. </code></pre>
  904. <h3 id="caddy-v2"><a class="header" href="#caddy-v2">Caddy v2</a></h3>
  905. <pre><code>matrix.example.com {
  906. reverse_proxy /_matrix/* localhost:8008
  907. reverse_proxy /_synapse/client/* localhost:8008
  908. }
  909. example.com:8448 {
  910. reverse_proxy localhost:8008
  911. }
  912. </code></pre>
  913. <p><a href="delegate.html">Delegation</a> example:</p>
  914. <pre><code>example.com {
  915. header /.well-known/matrix/* Content-Type application/json
  916. header /.well-known/matrix/* Access-Control-Allow-Origin *
  917. respond /.well-known/matrix/server `{&quot;m.server&quot;: &quot;matrix.example.com:443&quot;}`
  918. 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;}}`
  919. }
  920. matrix.example.com {
  921. reverse_proxy /_matrix/* localhost:8008
  922. reverse_proxy /_synapse/client/* localhost:8008
  923. }
  924. </code></pre>
  925. <h3 id="apache"><a class="header" href="#apache">Apache</a></h3>
  926. <pre><code class="language-apache">&lt;VirtualHost *:443&gt;
  927. SSLEngine on
  928. ServerName matrix.example.com
  929. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  930. AllowEncodedSlashes NoDecode
  931. ProxyPreserveHost on
  932. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  933. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  934. ProxyPass /_synapse/client http://127.0.0.1:8008/_synapse/client nocanon
  935. ProxyPassReverse /_synapse/client http://127.0.0.1:8008/_synapse/client
  936. &lt;/VirtualHost&gt;
  937. &lt;VirtualHost *:8448&gt;
  938. SSLEngine on
  939. ServerName example.com
  940. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  941. AllowEncodedSlashes NoDecode
  942. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  943. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  944. &lt;/VirtualHost&gt;
  945. </code></pre>
  946. <p><strong>NOTE</strong>: ensure the <code>nocanon</code> options are included.</p>
  947. <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>
  948. <pre><code class="language-apache">&lt;IfModule security2_module&gt;
  949. SecRuleEngine off
  950. &lt;/IfModule&gt;
  951. </code></pre>
  952. <p><strong>NOTE 3</strong>: Missing <code>ProxyPreserveHost on</code> can lead to a redirect loop.</p>
  953. <h3 id="haproxy"><a class="header" href="#haproxy">HAProxy</a></h3>
  954. <pre><code>frontend https
  955. bind *:443,[::]:443 ssl crt /etc/ssl/haproxy/ strict-sni alpn h2,http/1.1
  956. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  957. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  958. http-request set-header X-Forwarded-For %[src]
  959. # Matrix client traffic
  960. acl matrix-host hdr(host) -i matrix.example.com matrix.example.com:443
  961. acl matrix-path path_beg /_matrix
  962. acl matrix-path path_beg /_synapse/client
  963. use_backend matrix if matrix-host matrix-path
  964. frontend matrix-federation
  965. bind *:8448,[::]:8448 ssl crt /etc/ssl/haproxy/synapse.pem alpn h2,http/1.1
  966. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  967. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  968. http-request set-header X-Forwarded-For %[src]
  969. default_backend matrix
  970. backend matrix
  971. server matrix 127.0.0.1:8008
  972. </code></pre>
  973. <p><a href="delegate.html">Delegation</a> example:</p>
  974. <pre><code>frontend https
  975. acl matrix-well-known-client-path path /.well-known/matrix/client
  976. acl matrix-well-known-server-path path /.well-known/matrix/server
  977. use_backend matrix-well-known-client if matrix-well-known-client-path
  978. use_backend matrix-well-known-server if matrix-well-known-server-path
  979. backend matrix-well-known-client
  980. http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  981. http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  982. http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  983. 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;}}'
  984. backend matrix-well-known-server
  985. http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  986. http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  987. http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  988. http-request return status 200 content-type application/json string '{&quot;m.server&quot;:&quot;matrix.example.com:443&quot;}'
  989. </code></pre>
  990. <h3 id="relayd"><a class="header" href="#relayd">Relayd</a></h3>
  991. <pre><code>table &lt;webserver&gt; { 127.0.0.1 }
  992. table &lt;matrixserver&gt; { 127.0.0.1 }
  993. http protocol &quot;https&quot; {
  994. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  995. tls keypair &quot;example.com&quot;
  996. match header set &quot;X-Forwarded-For&quot; value &quot;$REMOTE_ADDR&quot;
  997. match header set &quot;X-Forwarded-Proto&quot; value &quot;https&quot;
  998. # set CORS header for .well-known/matrix/server, .well-known/matrix/client
  999. # httpd does not support setting headers, so do it here
  1000. match request path &quot;/.well-known/matrix/*&quot; tag &quot;matrix-cors&quot;
  1001. match response tagged &quot;matrix-cors&quot; header set &quot;Access-Control-Allow-Origin&quot; value &quot;*&quot;
  1002. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1003. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1004. # pass on non-matrix traffic to webserver
  1005. pass forward to &lt;webserver&gt;
  1006. }
  1007. relay &quot;https_traffic&quot; {
  1008. listen on egress port 443 tls
  1009. protocol &quot;https&quot;
  1010. forward to &lt;matrixserver&gt; port 8008 check tcp
  1011. forward to &lt;webserver&gt; port 8080 check tcp
  1012. }
  1013. http protocol &quot;matrix&quot; {
  1014. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  1015. tls keypair &quot;example.com&quot;
  1016. block
  1017. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1018. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1019. }
  1020. relay &quot;matrix_federation&quot; {
  1021. listen on egress port 8448 tls
  1022. protocol &quot;matrix&quot;
  1023. forward to &lt;matrixserver&gt; port 8008 check tcp
  1024. }
  1025. </code></pre>
  1026. <h2 id="health-check-endpoint"><a class="header" href="#health-check-endpoint">Health check endpoint</a></h2>
  1027. <p>Synapse exposes a health check endpoint for use by reverse proxies.
  1028. Each configured HTTP listener has a <code>/health</code> endpoint which always returns
  1029. 200 OK (and doesn't get logged).</p>
  1030. <h2 id="synapse-administration-endpoints"><a class="header" href="#synapse-administration-endpoints">Synapse administration endpoints</a></h2>
  1031. <p>Endpoints for administering your Synapse instance are placed under
  1032. <code>/_synapse/admin</code>. These require authentication through an access token of an
  1033. admin user. However as access to these endpoints grants the caller a lot of power,
  1034. we do not recommend exposing them to the public internet without good reason.</p>
  1035. <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>
  1036. <p>You can use Synapse with a forward or outbound proxy. An example of when
  1037. this is necessary is in corporate environments behind a DMZ (demilitarized zone).
  1038. Synapse supports routing outbound HTTP(S) requests via a proxy. Only HTTP(S)
  1039. proxy is supported, not SOCKS proxy or anything else.</p>
  1040. <h2 id="configure"><a class="header" href="#configure">Configure</a></h2>
  1041. <p>The <code>http_proxy</code>, <code>https_proxy</code>, <code>no_proxy</code> environment variables are used to
  1042. specify proxy settings. The environment variable is not case sensitive.</p>
  1043. <ul>
  1044. <li><code>http_proxy</code>: Proxy server to use for HTTP requests.</li>
  1045. <li><code>https_proxy</code>: Proxy server to use for HTTPS requests.</li>
  1046. <li><code>no_proxy</code>: Comma-separated list of hosts, IP addresses, or IP ranges in CIDR
  1047. format which should not use the proxy. Synapse will directly connect to these hosts.</li>
  1048. </ul>
  1049. <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>
  1050. <ul>
  1051. <li>
  1052. <p>Supported schemes are <code>http://</code> and <code>https://</code>. The default scheme is <code>http://</code>
  1053. for compatibility reasons; it is recommended to set a scheme. If scheme is set
  1054. to <code>https://</code> the connection uses TLS between Synapse and the proxy.</p>
  1055. <p><strong>NOTE</strong>: Synapse validates the certificates. If the certificate is not
  1056. valid, then the connection is dropped.</p>
  1057. </li>
  1058. <li>
  1059. <p>Default port if not given is <code>1080</code>.</p>
  1060. </li>
  1061. <li>
  1062. <p>Username and password are optional and will be used to authenticate against
  1063. the proxy.</p>
  1064. </li>
  1065. </ul>
  1066. <p><strong>Examples</strong></p>
  1067. <ul>
  1068. <li>HTTP_PROXY=http://USERNAME:PASSWORD@10.0.1.1:8080/</li>
  1069. <li>HTTPS_PROXY=http://USERNAME:PASSWORD@proxy.example.com:8080/</li>
  1070. <li>NO_PROXY=master.hostname.example.com,10.1.0.0/16,172.30.0.0/16</li>
  1071. </ul>
  1072. <p><strong>NOTE</strong>:
  1073. Synapse does not apply the IP blacklist to connections through the proxy (since
  1074. the DNS resolution is done by the proxy). It is expected that the proxy or firewall
  1075. will apply blacklisting of IP addresses.</p>
  1076. <h2 id="connection-types"><a class="header" href="#connection-types">Connection types</a></h2>
  1077. <p>The proxy will be <strong>used</strong> for:</p>
  1078. <ul>
  1079. <li>push</li>
  1080. <li>url previews</li>
  1081. <li>phone-home stats</li>
  1082. <li>recaptcha validation</li>
  1083. <li>CAS auth validation</li>
  1084. <li>OpenID Connect</li>
  1085. <li>Outbound federation</li>
  1086. <li>Federation (checking public key revocation)</li>
  1087. <li>Fetching public keys of other servers</li>
  1088. <li>Downloading remote media</li>
  1089. </ul>
  1090. <p>It will <strong>not be used</strong> for:</p>
  1091. <ul>
  1092. <li>Application Services</li>
  1093. <li>Identity servers</li>
  1094. <li>In worker configurations
  1095. <ul>
  1096. <li>connections between workers</li>
  1097. <li>connections from workers to Redis</li>
  1098. </ul>
  1099. </li>
  1100. </ul>
  1101. <h2 id="troubleshooting-1"><a class="header" href="#troubleshooting-1">Troubleshooting</a></h2>
  1102. <p>If a proxy server is used with TLS (HTTPS) and no connections are established,
  1103. it is most likely due to the proxy's certificates. To test this, the validation
  1104. in Synapse can be deactivated.</p>
  1105. <p><strong>NOTE</strong>: This has an impact on security and is for testing purposes only!</p>
  1106. <p>To deactivate the certificate validation, the following setting must be added to
  1107. your <a href="setup/../usage/configuration/homeserver_sample_config.html">homserver.yaml</a>.</p>
  1108. <pre><code class="language-yaml">use_insecure_ssl_client_just_for_testing_do_not_use: true
  1109. </code></pre>
  1110. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-1"><a class="header" href="#overview-1">Overview</a></h1>
  1111. <p>This document explains how to enable VoIP relaying on your homeserver with
  1112. TURN.</p>
  1113. <p>The synapse Matrix homeserver supports integration with TURN server via the
  1114. <a href="https://tools.ietf.org/html/draft-uberti-behave-turn-rest-00">TURN server REST API</a>. This
  1115. allows the homeserver to generate credentials that are valid for use on the
  1116. TURN server through the use of a secret shared between the homeserver and the
  1117. TURN server.</p>
  1118. <p>The following sections describe how to install <a href="https://github.com/coturn/coturn">coturn</a> (which implements the TURN REST API) and integrate it with synapse.</p>
  1119. <h2 id="requirements"><a class="header" href="#requirements">Requirements</a></h2>
  1120. <p>For TURN relaying with <code>coturn</code> to work, it must be hosted on a server/endpoint with a public IP.</p>
  1121. <p>Hosting TURN behind NAT requires port forwaring and for the NAT gateway to have a public IP.
  1122. However, even with appropriate configuration, NAT is known to cause issues and to often not work.</p>
  1123. <h2 id="coturn-setup"><a class="header" href="#coturn-setup"><code>coturn</code> setup</a></h2>
  1124. <h3 id="initial-installation"><a class="header" href="#initial-installation">Initial installation</a></h3>
  1125. <p>The TURN daemon <code>coturn</code> is available from a variety of sources such as native package managers, or installation from source.</p>
  1126. <h4 id="debian-installation"><a class="header" href="#debian-installation">Debian installation</a></h4>
  1127. <p>Just install the debian package:</p>
  1128. <pre><code class="language-sh">apt install coturn
  1129. </code></pre>
  1130. <p>This will install and start a systemd service called <code>coturn</code>.</p>
  1131. <h4 id="source-installation"><a class="header" href="#source-installation">Source installation</a></h4>
  1132. <ol>
  1133. <li>
  1134. <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>
  1135. </li>
  1136. <li>
  1137. <p>Configure it:</p>
  1138. <pre><code class="language-sh">./configure
  1139. </code></pre>
  1140. <p>You may need to install <code>libevent2</code>: if so, you should do so in
  1141. the way recommended by your operating system. You can ignore
  1142. warnings about lack of database support: a database is unnecessary
  1143. for this purpose.</p>
  1144. </li>
  1145. <li>
  1146. <p>Build and install it:</p>
  1147. <pre><code class="language-sh">make
  1148. make install
  1149. </code></pre>
  1150. </li>
  1151. </ol>
  1152. <h3 id="configuration"><a class="header" href="#configuration">Configuration</a></h3>
  1153. <ol>
  1154. <li>
  1155. <p>Create or edit the config file in <code>/etc/turnserver.conf</code>. The relevant
  1156. lines, with example values, are:</p>
  1157. <pre><code>use-auth-secret
  1158. static-auth-secret=[your secret key here]
  1159. realm=turn.myserver.org
  1160. </code></pre>
  1161. <p>See <code>turnserver.conf</code> for explanations of the options. One way to generate
  1162. the <code>static-auth-secret</code> is with <code>pwgen</code>:</p>
  1163. <pre><code class="language-sh">pwgen -s 64 1
  1164. </code></pre>
  1165. <p>A <code>realm</code> must be specified, but its value is somewhat arbitrary. (It is
  1166. sent to clients as part of the authentication flow.) It is conventional to
  1167. set it to be your server name.</p>
  1168. </li>
  1169. <li>
  1170. <p>You will most likely want to configure coturn to write logs somewhere. The
  1171. easiest way is normally to send them to the syslog:</p>
  1172. <pre><code class="language-sh">syslog
  1173. </code></pre>
  1174. <p>(in which case, the logs will be available via <code>journalctl -u coturn</code> on a
  1175. systemd system). Alternatively, coturn can be configured to write to a
  1176. logfile - check the example config file supplied with coturn.</p>
  1177. </li>
  1178. <li>
  1179. <p>Consider your security settings. TURN lets users request a relay which will
  1180. connect to arbitrary IP addresses and ports. The following configuration is
  1181. suggested as a minimum starting point:</p>
  1182. <pre><code># VoIP traffic is all UDP. There is no reason to let users connect to arbitrary TCP endpoints via the relay.
  1183. no-tcp-relay
  1184. # don't let the relay ever try to connect to private IP address ranges within your network (if any)
  1185. # given the turn server is likely behind your firewall, remember to include any privileged public IPs too.
  1186. denied-peer-ip=10.0.0.0-10.255.255.255
  1187. denied-peer-ip=192.168.0.0-192.168.255.255
  1188. denied-peer-ip=172.16.0.0-172.31.255.255
  1189. # recommended additional local peers to block, to mitigate external access to internal services.
  1190. # https://www.rtcsec.com/article/slack-webrtc-turn-compromise-and-bug-bounty/#how-to-fix-an-open-turn-relay-to-address-this-vulnerability
  1191. no-multicast-peers
  1192. denied-peer-ip=0.0.0.0-0.255.255.255
  1193. denied-peer-ip=100.64.0.0-100.127.255.255
  1194. denied-peer-ip=127.0.0.0-127.255.255.255
  1195. denied-peer-ip=169.254.0.0-169.254.255.255
  1196. denied-peer-ip=192.0.0.0-192.0.0.255
  1197. denied-peer-ip=192.0.2.0-192.0.2.255
  1198. denied-peer-ip=192.88.99.0-192.88.99.255
  1199. denied-peer-ip=198.18.0.0-198.19.255.255
  1200. denied-peer-ip=198.51.100.0-198.51.100.255
  1201. denied-peer-ip=203.0.113.0-203.0.113.255
  1202. denied-peer-ip=240.0.0.0-255.255.255.255
  1203. # special case the turn server itself so that client-&gt;TURN-&gt;TURN-&gt;client flows work
  1204. # this should be one of the turn server's listening IPs
  1205. allowed-peer-ip=10.0.0.1
  1206. # consider whether you want to limit the quota of relayed streams per user (or total) to avoid risk of DoS.
  1207. user-quota=12 # 4 streams per video call, so 12 streams = 3 simultaneous relayed calls per user.
  1208. total-quota=1200
  1209. </code></pre>
  1210. </li>
  1211. <li>
  1212. <p>Also consider supporting TLS/DTLS. To do this, add the following settings
  1213. to <code>turnserver.conf</code>:</p>
  1214. <pre><code># TLS certificates, including intermediate certs.
  1215. # For Let's Encrypt certificates, use `fullchain.pem` here.
  1216. cert=/path/to/fullchain.pem
  1217. # TLS private key file
  1218. pkey=/path/to/privkey.pem
  1219. # Ensure the configuration lines that disable TLS/DTLS are commented-out or removed
  1220. #no-tls
  1221. #no-dtls
  1222. </code></pre>
  1223. <p>In this case, replace the <code>turn:</code> schemes in the <code>turn_uris</code> settings below
  1224. with <code>turns:</code>.</p>
  1225. <p>We recommend that you only try to set up TLS/DTLS once you have set up a
  1226. basic installation and got it working.</p>
  1227. <p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
  1228. not work with any Matrix client that uses Chromium's WebRTC library. This
  1229. currently includes Element Android &amp; iOS; for more details, see their
  1230. <a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
  1231. <a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
  1232. <a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
  1233. Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
  1234. </li>
  1235. <li>
  1236. <p>Ensure your firewall allows traffic into the TURN server on the ports
  1237. you've configured it to listen on (By default: 3478 and 5349 for TURN
  1238. traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
  1239. for the UDP relay.)</p>
  1240. </li>
  1241. <li>
  1242. <p>If your TURN server is behind NAT, the NAT gateway must have an external,
  1243. publicly-reachable IP address. You must configure coturn to advertise that
  1244. address to connecting clients:</p>
  1245. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1246. </code></pre>
  1247. <p>You may optionally limit the TURN server to listen only on the local
  1248. address that is mapped by NAT to the external address:</p>
  1249. <pre><code>listening-ip=INTERNAL_TURNSERVER_IPv4_ADDRESS
  1250. </code></pre>
  1251. <p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
  1252. configure coturn to advertise each available address:</p>
  1253. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1254. external-ip=EXTERNAL_NAT_IPv6_ADDRESS
  1255. </code></pre>
  1256. <p>When advertising an external IPv6 address, ensure that the firewall and
  1257. network settings of the system running your TURN server are configured to
  1258. accept IPv6 traffic, and that the TURN server is listening on the local
  1259. IPv6 address that is mapped by NAT to the external IPv6 address.</p>
  1260. </li>
  1261. <li>
  1262. <p>(Re)start the turn server:</p>
  1263. <ul>
  1264. <li>
  1265. <p>If you used the Debian package (or have set up a systemd unit yourself):</p>
  1266. <pre><code class="language-sh">systemctl restart coturn
  1267. </code></pre>
  1268. </li>
  1269. <li>
  1270. <p>If you installed from source:</p>
  1271. <pre><code class="language-sh">bin/turnserver -o
  1272. </code></pre>
  1273. </li>
  1274. </ul>
  1275. </li>
  1276. </ol>
  1277. <h2 id="synapse-setup"><a class="header" href="#synapse-setup">Synapse setup</a></h2>
  1278. <p>Your homeserver configuration file needs the following extra keys:</p>
  1279. <ol>
  1280. <li>&quot;<code>turn_uris</code>&quot;: This needs to be a yaml list of public-facing URIs
  1281. for your TURN server to be given out to your clients. Add separate
  1282. entries for each transport your TURN server supports.</li>
  1283. <li>&quot;<code>turn_shared_secret</code>&quot;: This is the secret shared between your
  1284. homeserver and your TURN server, so you should set it to the same
  1285. string you used in turnserver.conf.</li>
  1286. <li>&quot;<code>turn_user_lifetime</code>&quot;: This is the amount of time credentials
  1287. generated by your homeserver are valid for (in milliseconds).
  1288. Shorter times offer less potential for abuse at the expense of
  1289. increased traffic between web clients and your homeserver to
  1290. refresh credentials. The TURN REST API specification recommends
  1291. one day (86400000).</li>
  1292. <li>&quot;<code>turn_allow_guests</code>&quot;: Whether to allow guest users to use the
  1293. TURN server. This is enabled by default, as otherwise VoIP will
  1294. not work reliably for guests. However, it does introduce a
  1295. security risk as it lets guests connect to arbitrary endpoints
  1296. without having gone through a CAPTCHA or similar to register a
  1297. real account.</li>
  1298. </ol>
  1299. <p>As an example, here is the relevant section of the config file for <code>matrix.org</code>. The
  1300. <code>turn_uris</code> are appropriate for TURN servers listening on the default ports, with no TLS.</p>
  1301. <pre><code>turn_uris: [ &quot;turn:turn.matrix.org?transport=udp&quot;, &quot;turn:turn.matrix.org?transport=tcp&quot; ]
  1302. turn_shared_secret: &quot;n0t4ctuAllymatr1Xd0TorgSshar3d5ecret4obvIousreAsons&quot;
  1303. turn_user_lifetime: 86400000
  1304. turn_allow_guests: True
  1305. </code></pre>
  1306. <p>After updating the homeserver configuration, you must restart synapse:</p>
  1307. <ul>
  1308. <li>If you use synctl:
  1309. <pre><code class="language-sh"># Depending on how Synapse is installed, synctl may already be on
  1310. # your PATH. If not, you may need to activate a virtual environment.
  1311. synctl restart
  1312. </code></pre>
  1313. </li>
  1314. <li>If you use systemd:
  1315. <pre><code class="language-sh">systemctl restart matrix-synapse.service
  1316. </code></pre>
  1317. </li>
  1318. </ul>
  1319. <p>... and then reload any clients (or wait an hour for them to refresh their
  1320. settings).</p>
  1321. <h2 id="troubleshooting-2"><a class="header" href="#troubleshooting-2">Troubleshooting</a></h2>
  1322. <p>The normal symptoms of a misconfigured TURN server are that calls between
  1323. devices on different networks ring, but get stuck at &quot;call
  1324. connecting&quot;. Unfortunately, troubleshooting this can be tricky.</p>
  1325. <p>Here are a few things to try:</p>
  1326. <ul>
  1327. <li>
  1328. <p>Check that you have opened your firewall to allow TCP and UDP traffic to the
  1329. TURN ports (normally 3478 and 5349).</p>
  1330. </li>
  1331. <li>
  1332. <p>Check that you have opened your firewall to allow UDP traffic to the UDP
  1333. relay ports (49152-65535 by default).</p>
  1334. </li>
  1335. <li>
  1336. <p>Try disabling <code>coturn</code>'s TLS/DTLS listeners and enable only its (unencrypted)
  1337. TCP/UDP listeners. (This will only leave signaling traffic unencrypted;
  1338. voice &amp; video WebRTC traffic is always encrypted.)</p>
  1339. </li>
  1340. <li>
  1341. <p>Some WebRTC implementations (notably, that of Google Chrome) appear to get
  1342. confused by TURN servers which are reachable over IPv6 (this appears to be
  1343. an unexpected side-effect of its handling of multiple IP addresses as
  1344. defined by
  1345. <a href="https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12"><code>draft-ietf-rtcweb-ip-handling</code></a>).</p>
  1346. <p>Try removing any AAAA records for your TURN server, so that it is only
  1347. reachable over IPv4.</p>
  1348. </li>
  1349. <li>
  1350. <p>If your TURN server is behind NAT:</p>
  1351. <ul>
  1352. <li>
  1353. <p>double-check that your NAT gateway is correctly forwarding all TURN
  1354. ports (normally 3478 &amp; 5349 for TCP &amp; UDP TURN traffic, and 49152-65535 for the UDP
  1355. relay) to the NAT-internal address of your TURN server. If advertising
  1356. both IPv4 and IPv6 external addresses via the <code>external-ip</code> option, ensure
  1357. that the NAT is forwarding both IPv4 and IPv6 traffic to the IPv4 and IPv6
  1358. internal addresses of your TURN server. When in doubt, remove AAAA records
  1359. for your TURN server and specify only an IPv4 address as your <code>external-ip</code>.</p>
  1360. </li>
  1361. <li>
  1362. <p>ensure that your TURN server uses the NAT gateway as its default route.</p>
  1363. </li>
  1364. </ul>
  1365. </li>
  1366. <li>
  1367. <p>Enable more verbose logging in coturn via the <code>verbose</code> setting:</p>
  1368. <pre><code>verbose
  1369. </code></pre>
  1370. <p>... and then see if there are any clues in its logs.</p>
  1371. </li>
  1372. <li>
  1373. <p>If you are using a browser-based client under Chrome, check
  1374. <code>chrome://webrtc-internals/</code> for insights into the internals of the
  1375. negotiation. On Firefox, check the &quot;Connection Log&quot; on <code>about:webrtc</code>.</p>
  1376. <p>(Understanding the output is beyond the scope of this document!)</p>
  1377. </li>
  1378. <li>
  1379. <p>You can test your Matrix homeserver TURN setup with <a href="https://test.voip.librepush.net/">https://test.voip.librepush.net/</a>.
  1380. Note that this test is not fully reliable yet, so don't be discouraged if
  1381. the test fails.
  1382. <a href="https://github.com/matrix-org/voip-tester">Here</a> is the github repo of the
  1383. source of the tester, where you can file bug reports.</p>
  1384. </li>
  1385. <li>
  1386. <p>There is a WebRTC test tool at
  1387. <a href="https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/">https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/</a>. To
  1388. use it, you will need a username/password for your TURN server. You can
  1389. either:</p>
  1390. <ul>
  1391. <li>
  1392. <p>look for the <code>GET /_matrix/client/r0/voip/turnServer</code> request made by a
  1393. matrix client to your homeserver in your browser's network inspector. In
  1394. the response you should see <code>username</code> and <code>password</code>. Or:</p>
  1395. </li>
  1396. <li>
  1397. <p>Use the following shell commands:</p>
  1398. <pre><code class="language-sh">secret=staticAuthSecretHere
  1399. u=$((`date +%s` + 3600)):test
  1400. p=$(echo -n $u | openssl dgst -hmac $secret -sha1 -binary | base64)
  1401. echo -e &quot;username: $u\npassword: $p&quot;
  1402. </code></pre>
  1403. <p>Or:</p>
  1404. </li>
  1405. <li>
  1406. <p>Temporarily configure coturn to accept a static username/password. To do
  1407. this, comment out <code>use-auth-secret</code> and <code>static-auth-secret</code> and add the
  1408. following:</p>
  1409. <pre><code>lt-cred-mech
  1410. user=username:password
  1411. </code></pre>
  1412. <p><strong>Note</strong>: these settings will not take effect unless <code>use-auth-secret</code>
  1413. and <code>static-auth-secret</code> are disabled.</p>
  1414. <p>Restart coturn after changing the configuration file.</p>
  1415. <p>Remember to restore the original settings to go back to testing with
  1416. Matrix clients!</p>
  1417. </li>
  1418. </ul>
  1419. <p>If the TURN server is working correctly, you should see at least one <code>relay</code>
  1420. entry in the results.</p>
  1421. </li>
  1422. </ul>
  1423. <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>
  1424. <p>In the following documentation, we use the term <code>server_name</code> to refer to that setting
  1425. in your homeserver configuration file. It appears at the ends of user ids, and tells
  1426. other homeservers where they can find your server.</p>
  1427. <p>By default, other homeservers will expect to be able to reach yours via
  1428. your <code>server_name</code>, on port 8448. For example, if you set your <code>server_name</code>
  1429. to <code>example.com</code> (so that your user names look like <code>@user:example.com</code>),
  1430. other servers will try to connect to yours at <code>https://example.com:8448/</code>.</p>
  1431. <p>Delegation is a Matrix feature allowing a homeserver admin to retain a
  1432. <code>server_name</code> of <code>example.com</code> so that user IDs, room aliases, etc continue
  1433. to look like <code>*:example.com</code>, whilst having federation traffic routed
  1434. to a different server and/or port (e.g. <code>synapse.example.com:443</code>).</p>
  1435. <h2 id="well-known-delegation"><a class="header" href="#well-known-delegation">.well-known delegation</a></h2>
  1436. <p>To use this method, you need to be able to configure the server at
  1437. <code>https://&lt;server_name&gt;</code> to serve a file at
  1438. <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>. There are two ways to do this, shown below.</p>
  1439. <p>Note that the <code>.well-known</code> file is hosted on the default port for <code>https</code> (port 443).</p>
  1440. <h3 id="external-server"><a class="header" href="#external-server">External server</a></h3>
  1441. <p>For maximum flexibility, you need to configure an external server such as nginx, Apache
  1442. or HAProxy to serve the <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> file. Setting
  1443. up such a server is out of the scope of this documentation, but note that it is often
  1444. possible to configure your <a href="reverse_proxy.html">reverse proxy</a> for this.</p>
  1445. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> should be configured
  1446. return a JSON structure containing the key <code>m.server</code> like this:</p>
  1447. <pre><code class="language-json">{
  1448. &quot;m.server&quot;: &quot;&lt;synapse.server.name&gt;[:&lt;yourport&gt;]&quot;
  1449. }
  1450. </code></pre>
  1451. <p>In our example (where we want federation traffic to be routed to
  1452. <code>https://synapse.example.com</code>, on port 443), this would mean that
  1453. <code>https://example.com/.well-known/matrix/server</code> should return:</p>
  1454. <pre><code class="language-json">{
  1455. &quot;m.server&quot;: &quot;synapse.example.com:443&quot;
  1456. }
  1457. </code></pre>
  1458. <p>Note, specifying a port is optional. If no port is specified, then it defaults
  1459. to 8448.</p>
  1460. <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>
  1461. <p>If you are able to set up your domain so that <code>https://&lt;server_name&gt;</code> is routed to
  1462. Synapse (i.e., the only change needed is to direct federation traffic to port 443
  1463. instead of port 8448), then it is possible to configure Synapse to serve a suitable
  1464. <code>.well-known/matrix/server</code> file. To do so, add the following to your <code>homeserver.yaml</code>
  1465. file:</p>
  1466. <pre><code class="language-yaml">serve_server_wellknown: true
  1467. </code></pre>
  1468. <p><strong>Note</strong>: this <em>only</em> works if <code>https://&lt;server_name&gt;</code> is routed to Synapse, so is
  1469. generally not suitable if Synapse is hosted at a subdomain such as
  1470. <code>https://synapse.example.com</code>.</p>
  1471. <h2 id="srv-dns-record-delegation"><a class="header" href="#srv-dns-record-delegation">SRV DNS record delegation</a></h2>
  1472. <p>It is also possible to do delegation using a SRV DNS record. However, that is generally
  1473. not recommended, as it can be difficult to configure the TLS certificates correctly in
  1474. this case, and it offers little advantage over <code>.well-known</code> delegation.</p>
  1475. <p>However, if you really need it, you can find some documentation on what such a
  1476. 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
  1477. specification</a>.</p>
  1478. <h2 id="delegation-faq"><a class="header" href="#delegation-faq">Delegation FAQ</a></h2>
  1479. <h3 id="when-do-i-need-delegation"><a class="header" href="#when-do-i-need-delegation">When do I need delegation?</a></h3>
  1480. <p>If your homeserver's APIs are accessible on the default federation port (8448)
  1481. and the domain your <code>server_name</code> points to, you do not need any delegation.</p>
  1482. <p>For instance, if you registered <code>example.com</code> and pointed its DNS A record at a
  1483. fresh server, you could install Synapse on that host, giving it a <code>server_name</code>
  1484. of <code>example.com</code>, and once a reverse proxy has been set up to proxy all requests
  1485. sent to the port <code>8448</code> and serve TLS certificates for <code>example.com</code>, you
  1486. wouldn't need any delegation set up.</p>
  1487. <p><strong>However</strong>, if your homeserver's APIs aren't accessible on port 8448 and on the
  1488. domain <code>server_name</code> points to, you will need to let other servers know how to
  1489. find it using delegation.</p>
  1490. <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>
  1491. <p>Generally, using a reverse proxy for both the federation and client traffic is a good
  1492. idea, since it saves handling TLS traffic in Synapse. See
  1493. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a
  1494. reverse proxy.</p>
  1495. <div style="break-before: page; page-break-before: always;"></div><h1 id="upgrading-synapse"><a class="header" href="#upgrading-synapse">Upgrading Synapse</a></h1>
  1496. <p>Before upgrading check if any special steps are required to upgrade from
  1497. the version you currently have installed to the current version of
  1498. Synapse. The extra instructions that may be required are listed later in
  1499. this document.</p>
  1500. <ul>
  1501. <li>
  1502. <p>Check that your versions of Python and PostgreSQL are still
  1503. supported.</p>
  1504. <p>Synapse follows upstream lifecycles for <a href="https://endoflife.date/python">Python</a> and
  1505. <a href="https://endoflife.date/postgresql">PostgreSQL</a>, and removes support for versions
  1506. which are no longer maintained.</p>
  1507. <p>The website <a href="https://endoflife.date">https://endoflife.date</a> also offers convenient
  1508. summaries.</p>
  1509. </li>
  1510. <li>
  1511. <p>If Synapse was installed using <a href="setup/installation.html#prebuilt-packages">prebuilt packages</a>,
  1512. you will need to follow the normal process for upgrading those packages.</p>
  1513. </li>
  1514. <li>
  1515. <p>If Synapse was installed using pip then upgrade to the latest
  1516. version by running:</p>
  1517. <pre><code class="language-bash">pip install --upgrade matrix-synapse
  1518. </code></pre>
  1519. </li>
  1520. <li>
  1521. <p>If Synapse was installed from source, then:</p>
  1522. <ol>
  1523. <li>
  1524. <p>Obtain the latest version of the source code. Git users can run
  1525. <code>git pull</code> to do this.</p>
  1526. </li>
  1527. <li>
  1528. <p>If you're running Synapse in a virtualenv, make sure to activate it before
  1529. upgrading. For example, if Synapse is installed in a virtualenv in <code>~/synapse/env</code> then
  1530. run:</p>
  1531. <pre><code class="language-bash">source ~/synapse/env/bin/activate
  1532. pip install --upgrade .
  1533. </code></pre>
  1534. <p>Include any relevant extras between square brackets, e.g. <code>pip install --upgrade &quot;.[postgres,oidc]&quot;</code>.</p>
  1535. </li>
  1536. <li>
  1537. <p>If you're using <code>poetry</code> to manage a Synapse installation, run:</p>
  1538. <pre><code class="language-bash">poetry install
  1539. </code></pre>
  1540. <p>Include any relevant extras with <code>--extras</code>, e.g. <code>poetry install --extras postgres --extras oidc</code>.
  1541. It's probably easiest to run <code>poetry install --extras all</code>.</p>
  1542. </li>
  1543. <li>
  1544. <p>Restart Synapse:</p>
  1545. <pre><code class="language-bash">synctl restart
  1546. </code></pre>
  1547. </li>
  1548. </ol>
  1549. </li>
  1550. </ul>
  1551. <p>To check whether your update was successful, you can check the running
  1552. server version with:</p>
  1553. <pre><code class="language-bash"># you may need to replace 'localhost:8008' if synapse is not configured
  1554. # to listen on port 8008.
  1555. curl http://localhost:8008/_synapse/admin/v1/server_version
  1556. </code></pre>
  1557. <h2 id="rolling-back-to-older-versions"><a class="header" href="#rolling-back-to-older-versions">Rolling back to older versions</a></h2>
  1558. <p>Rolling back to previous releases can be difficult, due to database
  1559. schema changes between releases. Where we have been able to test the
  1560. rollback process, this will be noted below.</p>
  1561. <p>In general, you will need to undo any changes made during the upgrade
  1562. process, for example:</p>
  1563. <ul>
  1564. <li>
  1565. <p>pip:</p>
  1566. <pre><code class="language-bash">source env/bin/activate
  1567. # replace `1.3.0` accordingly:
  1568. pip install matrix-synapse==1.3.0
  1569. </code></pre>
  1570. </li>
  1571. <li>
  1572. <p>Debian:</p>
  1573. <pre><code class="language-bash"># replace `1.3.0` and `stretch` accordingly:
  1574. wget https://packages.matrix.org/debian/pool/main/m/matrix-synapse-py3/matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1575. dpkg -i matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1576. </code></pre>
  1577. </li>
  1578. </ul>
  1579. <h1 id="upgrading-to-v1690"><a class="header" href="#upgrading-to-v1690">Upgrading to v1.69.0</a></h1>
  1580. <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>
  1581. <p>Synapse now includes information indicating if a receipt applies to a thread when
  1582. replicating it to other workers. This is a forwards- and backwards-incompatible
  1583. change: v1.68 and workers cannot process receipts replicated by v1.69 workers, and
  1584. vice versa.</p>
  1585. <p>Once all workers are upgraded to v1.69 (or downgraded to v1.68), receipts
  1586. replication will resume as normal.</p>
  1587. <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>
  1588. <p>In current versions of Synapse, some Prometheus metrics are emitted under two different names,
  1589. with one of the names being older but non-compliant with OpenMetrics and Prometheus conventions
  1590. and one of the names being newer but compliant.</p>
  1591. <p>Synapse v1.71.0 will turn the old metric names off <em>by default</em>.
  1592. For administrators that still rely on them and have not had chance to update their
  1593. uses of the metrics, it's possible to specify <code>enable_legacy_metrics: true</code> in
  1594. the configuration to re-enable them temporarily.</p>
  1595. <p>Synapse v1.73.0 will <strong>remove legacy metric names altogether</strong> and it will no longer
  1596. be possible to re-enable them.</p>
  1597. <p>The Grafana dashboard, Prometheus recording rules and Prometheus Consoles included
  1598. in the <code>contrib</code> directory in the Synapse repository have been updated to no longer
  1599. rely on the legacy names. These can be used on a current version of Synapse
  1600. because current versions of Synapse emit both old and new names.</p>
  1601. <p>You may need to update your alerting rules or any other rules that depend on
  1602. the names of Prometheus metrics.
  1603. If you want to test your changes before legacy names are disabled by default,
  1604. you may specify <code>enable_legacy_metrics: false</code> in your homeserver configuration.</p>
  1605. <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>
  1606. <h1 id="upgrading-to-v1680"><a class="header" href="#upgrading-to-v1680">Upgrading to v1.68.0</a></h1>
  1607. <p>Two changes announced in the upgrade notes for v1.67.0 have now landed in v1.68.0.</p>
  1608. <h2 id="sqlite-version-requirement"><a class="header" href="#sqlite-version-requirement">SQLite version requirement</a></h2>
  1609. <p>Synapse now requires a SQLite version of 3.27.0 or higher if SQLite is configured as
  1610. Synapse's database.</p>
  1611. <p>Installations using</p>
  1612. <ul>
  1613. <li>Docker images <a href="https://hub.docker.com/r/matrixdotorg/synapse">from <code>matrixdotorg</code></a>,</li>
  1614. <li>Debian packages <a href="https://packages.matrix.org/">from Matrix.org</a>, or</li>
  1615. <li>a PostgreSQL database</li>
  1616. </ul>
  1617. <p>are not affected.</p>
  1618. <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>
  1619. <p>Building from a source checkout of Synapse now requires a recent Rust compiler
  1620. (currently Rust 1.58.1, but see also the
  1621. <a href="https://matrix-org.github.io/synapse/latest/deprecation_policy.html">Platform Dependency Policy</a>).</p>
  1622. <p>Installations using</p>
  1623. <ul>
  1624. <li>Docker images <a href="https://hub.docker.com/r/matrixdotorg/synapse">from <code>matrixdotorg</code></a>,</li>
  1625. <li>Debian packages <a href="https://packages.matrix.org/">from Matrix.org</a>, or</li>
  1626. <li>PyPI wheels via <code>pip install matrix-synapse</code> (on supported platforms and architectures)</li>
  1627. </ul>
  1628. <p>will not be affected.</p>
  1629. <h1 id="upgrading-to-v1670"><a class="header" href="#upgrading-to-v1670">Upgrading to v1.67.0</a></h1>
  1630. <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>
  1631. <p>Redis support was added in v1.13.0 with it becoming the recommended method in
  1632. v1.18.0. It replaced the old direct TCP connections (which was deprecated as of
  1633. v1.18.0) to the main process. With Redis, rather than all the workers connecting
  1634. to the main process, all the workers and the main process connect to Redis,
  1635. which relays replication commands between processes. This can give a significant
  1636. CPU saving on the main process and is a prerequisite for upcoming
  1637. performance improvements.</p>
  1638. <p>To migrate to Redis add the <a href="./workers.html#shared-configuration"><code>redis</code> config</a>,
  1639. and remove the TCP <code>replication</code> listener from config of the master and
  1640. <code>worker_replication_port</code> from worker config. Note that a HTTP listener with a
  1641. <code>replication</code> resource is still required.</p>
  1642. <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>
  1643. <p>The minimum supported version of poetry is now 1.2. This should only affect
  1644. those installing from a source checkout.</p>
  1645. <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>
  1646. <p>From the next major release (v1.68.0) installing Synapse from a source checkout
  1647. will require a recent Rust compiler. Those using packages or
  1648. <code>pip install matrix-synapse</code> will not be affected.</p>
  1649. <p>The simplest way of installing Rust is via <a href="https://rustup.rs/">rustup.rs</a></p>
  1650. <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>
  1651. <p>From the next major release (v1.68.0) Synapse will require SQLite 3.27.0 or
  1652. higher. Synapse v1.67.0 will be the last major release supporting SQLite
  1653. versions 3.22 to 3.26.</p>
  1654. <p>Those using Docker images or Debian packages from Matrix.org will not be
  1655. affected. If you have installed from source, you should check the version of
  1656. SQLite used by Python with:</p>
  1657. <pre><code class="language-shell">python -c &quot;import sqlite3; print(sqlite3.sqlite_version)&quot;
  1658. </code></pre>
  1659. <p>If this is too old, refer to your distribution for advice on upgrading.</p>
  1660. <h1 id="upgrading-to-v1660"><a class="header" href="#upgrading-to-v1660">Upgrading to v1.66.0</a></h1>
  1661. <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>
  1662. <p>As of this version, Synapse no longer allows the tasks of verifying email address
  1663. ownership, and password reset confirmation, to be delegated to an identity server.
  1664. This removal was previously planned for Synapse 1.64.0, but was
  1665. <a href="https://github.com/matrix-org/synapse/issues/13421">delayed</a> until now to give
  1666. homeserver administrators more notice of the change.</p>
  1667. <p>To continue to allow users to add email addresses to their homeserver accounts,
  1668. and perform password resets, make sure that Synapse is configured with a working
  1669. email server in the <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#email"><code>email</code> configuration
  1670. section</a>
  1671. (including, at a minimum, a <code>notif_from</code> setting.)</p>
  1672. <p>Specifying an <code>email</code> setting under <code>account_threepid_delegates</code> will now cause
  1673. an error at startup.</p>
  1674. <h1 id="upgrading-to-v1640"><a class="header" href="#upgrading-to-v1640">Upgrading to v1.64.0</a></h1>
  1675. <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>
  1676. <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>
  1677. <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.
  1678. <a href="https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#email">Consult the configuration documentation for more information.</a></p>
  1679. <p>The option that will be removed is <code>account_threepid_delegates.email</code>.</p>
  1680. <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>
  1681. <p>Synapse now includes a flag indicating if an event is an outlier when
  1682. replicating it to other workers. This is a forwards- and backwards-incompatible
  1683. change: v1.63 and workers cannot process events replicated by v1.64 workers, and
  1684. vice versa.</p>
  1685. <p>Once all workers are upgraded to v1.64 (or downgraded to v1.63), event
  1686. replication will resume as normal.</p>
  1687. <h2 id="frozendict-release"><a class="header" href="#frozendict-release">frozendict release</a></h2>
  1688. <p><a href="https://github.com/Marco-Sulla/python-frozendict/releases/tag/v2.3.3">frozendict 2.3.3</a>
  1689. has recently been released, which fixes a memory leak that occurs during <code>/sync</code>
  1690. requests. We advise server administrators who installed Synapse via pip to upgrade
  1691. frozendict with <code>pip install --upgrade frozendict</code>. The Docker image
  1692. <code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> already
  1693. include the updated library.</p>
  1694. <h1 id="upgrading-to-v1620"><a class="header" href="#upgrading-to-v1620">Upgrading to v1.62.0</a></h1>
  1695. <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>
  1696. <p>As a followup to changes in v1.60.0, the following spam-checker callbacks have changed signature:</p>
  1697. <ul>
  1698. <li><code>user_may_join_room</code></li>
  1699. <li><code>user_may_invite</code></li>
  1700. <li><code>user_may_send_3pid_invite</code></li>
  1701. <li><code>user_may_create_room</code></li>
  1702. <li><code>user_may_create_room_alias</code></li>
  1703. <li><code>user_may_publish_room</code></li>
  1704. <li><code>check_media_file_for_spam</code></li>
  1705. </ul>
  1706. <p>For each of these methods, the previous callback signature has been deprecated.</p>
  1707. <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>
  1708. <p>For instance, if your module implements <code>user_may_join_room</code> as follows:</p>
  1709. <pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
  1710. if ...:
  1711. # Request is spam
  1712. return False
  1713. # Request is not spam
  1714. return True
  1715. </code></pre>
  1716. <p>you should rewrite it as follows:</p>
  1717. <pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
  1718. if ...:
  1719. # Request is spam, mark it as forbidden (you may use some more precise error
  1720. # code if it is useful).
  1721. return synapse.module_api.errors.Codes.FORBIDDEN
  1722. # Request is not spam, mark it as such.
  1723. return synapse.module_api.NOT_SPAM
  1724. </code></pre>
  1725. <h1 id="upgrading-to-v1610"><a class="header" href="#upgrading-to-v1610">Upgrading to v1.61.0</a></h1>
  1726. <h2 id="removal-of-deprecated-communitygroups"><a class="header" href="#removal-of-deprecated-communitygroups">Removal of deprecated community/groups</a></h2>
  1727. <p>This release of Synapse will remove deprecated community/groups from codebase.</p>
  1728. <h3 id="worker-endpoints"><a class="header" href="#worker-endpoints">Worker endpoints</a></h3>
  1729. <p>For those who have deployed workers, following worker endpoints will no longer
  1730. exist and they can be removed from the reverse proxy configuration:</p>
  1731. <ul>
  1732. <li><code>^/_matrix/federation/v1/get_groups_publicised$</code></li>
  1733. <li><code>^/_matrix/client/(r0|v3|unstable)/joined_groups$</code></li>
  1734. <li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups$</code></li>
  1735. <li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups/</code></li>
  1736. <li><code>^/_matrix/federation/v1/groups/</code></li>
  1737. <li><code>^/_matrix/client/(r0|v3|unstable)/groups/</code></li>
  1738. </ul>
  1739. <h1 id="upgrading-to-v1600"><a class="header" href="#upgrading-to-v1600">Upgrading to v1.60.0</a></h1>
  1740. <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>
  1741. <p>This release of Synapse will add a unique index to the <code>state_group_edges</code> table, in order
  1742. to prevent accidentally introducing duplicate information (for example, because a database
  1743. backup was restored multiple times).</p>
  1744. <p>Duplicate rows being present in this table could cause drastic performance problems; see
  1745. <a href="https://github.com/matrix-org/synapse/issues/11779">issue 11779</a> for more details.</p>
  1746. <p>If your Synapse database already has had duplicate rows introduced into this table,
  1747. this could fail, with either of these errors:</p>
  1748. <p><strong>On Postgres:</strong></p>
  1749. <pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
  1750. synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
  1751. ...
  1752. psycopg2.errors.UniqueViolation: could not create unique index &quot;state_group_edges_unique_idx&quot;
  1753. DETAIL: Key (state_group, prev_state_group)=(2, 1) is duplicated.
  1754. </code></pre>
  1755. <p>(The numbers may be different.)</p>
  1756. <p><strong>On SQLite:</strong></p>
  1757. <pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
  1758. synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
  1759. ...
  1760. sqlite3.IntegrityError: UNIQUE constraint failed: state_group_edges.state_group, state_group_edges.prev_state_group
  1761. </code></pre>
  1762. <details>
  1763. <summary><b>Expand this section for steps to resolve this problem</b></summary>
  1764. <h3 id="on-postgres"><a class="header" href="#on-postgres">On Postgres</a></h3>
  1765. <p>Connect to your database with <code>psql</code>.</p>
  1766. <pre><code class="language-sql">BEGIN;
  1767. DELETE FROM state_group_edges WHERE (ctid, state_group, prev_state_group) IN (
  1768. SELECT row_id, state_group, prev_state_group
  1769. FROM (
  1770. SELECT
  1771. ctid AS row_id,
  1772. MIN(ctid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
  1773. state_group,
  1774. prev_state_group
  1775. FROM state_group_edges
  1776. ) AS t1
  1777. WHERE row_id &lt;&gt; min_row_id
  1778. );
  1779. COMMIT;
  1780. </code></pre>
  1781. <h3 id="on-sqlite"><a class="header" href="#on-sqlite">On SQLite</a></h3>
  1782. <p>At the command-line, use <code>sqlite3 path/to/your-homeserver-database.db</code>:</p>
  1783. <pre><code class="language-sql">BEGIN;
  1784. DELETE FROM state_group_edges WHERE (rowid, state_group, prev_state_group) IN (
  1785. SELECT row_id, state_group, prev_state_group
  1786. FROM (
  1787. SELECT
  1788. rowid AS row_id,
  1789. MIN(rowid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
  1790. state_group,
  1791. prev_state_group
  1792. FROM state_group_edges
  1793. )
  1794. WHERE row_id &lt;&gt; min_row_id
  1795. );
  1796. COMMIT;
  1797. </code></pre>
  1798. <h3 id="for-more-details"><a class="header" href="#for-more-details">For more details</a></h3>
  1799. <p><a href="https://github.com/matrix-org/synapse/issues/11779#issuecomment-1131545970">This comment on issue 11779</a>
  1800. has queries that can be used to check a database for this problem in advance.</p>
  1801. </details>
  1802. <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>
  1803. <p>The previous signature has been deprecated.</p>
  1804. <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>
  1805. <p>This is part of an ongoing refactoring of the SpamChecker API to make it less ambiguous and more powerful.</p>
  1806. <p>If your module implements <code>check_event_for_spam</code> as follows:</p>
  1807. <pre><code class="language-python">async def check_event_for_spam(event):
  1808. if ...:
  1809. # Event is spam
  1810. return True
  1811. # Event is not spam
  1812. return False
  1813. </code></pre>
  1814. <p>you should rewrite it as follows:</p>
  1815. <pre><code class="language-python">async def check_event_for_spam(event):
  1816. if ...:
  1817. # Event is spam, mark it as forbidden (you may use some more precise error
  1818. # code if it is useful).
  1819. return synapse.module_api.errors.Codes.FORBIDDEN
  1820. # Event is not spam, mark it as such.
  1821. return synapse.module_api.NOT_SPAM
  1822. </code></pre>
  1823. <h1 id="upgrading-to-v1590"><a class="header" href="#upgrading-to-v1590">Upgrading to v1.59.0</a></h1>
  1824. <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>
  1825. <p>The names of user devices are no longer visible to users on other homeservers by default.
  1826. Device IDs are unaffected, as these are necessary to facilitate end-to-end encryption.</p>
  1827. <p>To re-enable this functionality, set the
  1828. <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>
  1829. homeserver config option to <code>true</code>.</p>
  1830. <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>
  1831. <p>The <code>synapse.app.appservice</code> worker application type allowed you to configure a
  1832. single worker to use to notify application services of new events, as long
  1833. as this functionality was disabled on the main process with <code>notify_appservices: False</code>.
  1834. Further, the <code>synapse.app.user_dir</code> worker application type allowed you to configure
  1835. a single worker to be responsible for updating the user directory, as long as this
  1836. was disabled on the main process with <code>update_user_directory: False</code>.</p>
  1837. <p>To unify Synapse's worker types, the <code>synapse.app.appservice</code> worker application
  1838. type and the <code>notify_appservices</code> configuration option have been deprecated.
  1839. The <code>synapse.app.user_dir</code> worker application type and <code>update_user_directory</code>
  1840. configuration option have also been deprecated.</p>
  1841. <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>
  1842. worker application type is used and that the <code>notify_appservices_from_worker</code> and/or
  1843. <code>update_user_directory_from_worker</code> options are set to the name of a worker.</p>
  1844. <p>For the time being, the old options can be used alongside the new options to make
  1845. it easier to transition between the two configurations, however please note that:</p>
  1846. <ul>
  1847. <li>the options must not contradict each other (otherwise Synapse won't start); and</li>
  1848. <li>the <code>notify_appservices</code> and <code>update_user_directory</code> options will be removed in a future release of Synapse.</li>
  1849. </ul>
  1850. <p>Please see the <a href="workers.html#notifying-application-services"><em>Notifying Application Services</em></a> and
  1851. <a href="workers.html#updating-the-user-directory"><em>Updating the User Directory</em></a> sections of the worker
  1852. documentation for more information.</p>
  1853. <h1 id="upgrading-to-v1580"><a class="header" href="#upgrading-to-v1580">Upgrading to v1.58.0</a></h1>
  1854. <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>
  1855. <p>The non-standard groups/communities feature in Synapse has been disabled by default
  1856. and will be removed in Synapse v1.61.0.</p>
  1857. <h1 id="upgrading-to-v1570"><a class="header" href="#upgrading-to-v1570">Upgrading to v1.57.0</a></h1>
  1858. <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>
  1859. <p>Synapse v1.57.0 includes a <a href="https://github.com/matrix-org/synapse/pull/12209">change</a> to the
  1860. way transaction IDs are managed for application services. If your deployment uses a dedicated
  1861. worker for application service traffic, <strong>it must be stopped</strong> when the database is upgraded
  1862. (which normally happens when the main process is upgraded), to ensure the change is made safely
  1863. without any risk of reusing transaction IDs.</p>
  1864. <p>Deployments which do not use separate worker processes can be upgraded as normal. Similarly,
  1865. deployments where no application services are in use can be upgraded as normal.</p>
  1866. <details>
  1867. <summary><b>Recovering from an incorrect upgrade</b></summary>
  1868. <p>If the database schema is upgraded <em>without</em> stopping the worker responsible
  1869. for AS traffic, then the following error may be given when attempting to start
  1870. a Synapse worker or master process:</p>
  1871. <pre><code>**********************************************************************************
  1872. Error during initialisation:
  1873. Postgres sequence 'application_services_txn_id_seq' is inconsistent with associated
  1874. table 'application_services_txns'. This can happen if Synapse has been downgraded and
  1875. then upgraded again, or due to a bad migration.
  1876. To fix this error, shut down Synapse (including any and all workers)
  1877. and run the following SQL:
  1878. SELECT setval('application_services_txn_id_seq', (
  1879. SELECT GREATEST(MAX(txn_id), 0) FROM application_services_txns
  1880. ));
  1881. See docs/postgres.md for more information.
  1882. There may be more information in the logs.
  1883. **********************************************************************************
  1884. </code></pre>
  1885. <p>This error may also be seen if Synapse is <em>downgraded</em> to an earlier version,
  1886. and then upgraded again to v1.57.0 or later.</p>
  1887. <p>In either case:</p>
  1888. <ol>
  1889. <li>Ensure that the worker responsible for AS traffic is stopped.</li>
  1890. <li>Run the SQL command given in the error message via <code>psql</code>.</li>
  1891. </ol>
  1892. <p>Synapse should then start correctly.</p>
  1893. </details>
  1894. <h1 id="upgrading-to-v1560"><a class="header" href="#upgrading-to-v1560">Upgrading to v1.56.0</a></h1>
  1895. <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>
  1896. <p>Synapse will refuse to start if registration is enabled without email, captcha, or token-based verification unless the new config
  1897. flag <code>enable_registration_without_verification</code> is set to &quot;true&quot;.</p>
  1898. <h2 id="groupscommunities-feature-has-been-deprecated"><a class="header" href="#groupscommunities-feature-has-been-deprecated">Groups/communities feature has been deprecated</a></h2>
  1899. <p>The non-standard groups/communities feature in Synapse has been deprecated and will
  1900. be disabled by default in Synapse v1.58.0.</p>
  1901. <p>You can test disabling it by adding the following to your homeserver configuration:</p>
  1902. <pre><code class="language-yaml">experimental_features:
  1903. groups_enabled: false
  1904. </code></pre>
  1905. <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>
  1906. <p>Synapse now refuses to start when using PostgreSQL with non-<code>C</code> values for <code>COLLATE</code> and
  1907. <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the database section of
  1908. 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>
  1909. for more information and instructions on how to fix a database with incorrect values.</p>
  1910. <h1 id="upgrading-to-v1550"><a class="header" href="#upgrading-to-v1550">Upgrading to v1.55.0</a></h1>
  1911. <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>
  1912. <p>The <code>synctl</code> script
  1913. <a href="https://github.com/matrix-org/synapse/pull/12140">has been made</a> an
  1914. <a href="https://packaging.python.org/en/latest/specifications/entry-points/">entry point</a>
  1915. and no longer exists at the root of Synapse's source tree. If you wish to use
  1916. <code>synctl</code> to manage your homeserver, you should invoke <code>synctl</code> directly, e.g.
  1917. <code>synctl start</code> instead of <code>./synctl start</code> or <code>/path/to/synctl start</code>.</p>
  1918. <p>You will need to ensure <code>synctl</code> is on your <code>PATH</code>.</p>
  1919. <ul>
  1920. <li>This is automatically the case when using
  1921. <a href="https://packages.matrix.org/debian/">Debian packages</a> or
  1922. <a href="https://hub.docker.com/r/matrixdotorg/synapse">docker images</a>
  1923. provided by Matrix.org.</li>
  1924. <li>When installing from a wheel, sdist, or PyPI, a <code>synctl</code> executable is added
  1925. to your Python installation's <code>bin</code>. This should be on your <code>PATH</code>
  1926. automatically, though you might need to activate a virtual environment
  1927. depending on how you installed Synapse.</li>
  1928. </ul>
  1929. <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>
  1930. <p>Synapse v1.55.0 drops support for Mjolnir 1.3.1 and earlier.
  1931. If you use the Mjolnir module to moderate your homeserver,
  1932. please upgrade Mjolnir to version 1.3.2 or later before upgrading Synapse.</p>
  1933. <h1 id="upgrading-to-v1540"><a class="header" href="#upgrading-to-v1540">Upgrading to v1.54.0</a></h1>
  1934. <h2 id="legacy-structured-logging-configuration-removal"><a class="header" href="#legacy-structured-logging-configuration-removal">Legacy structured logging configuration removal</a></h2>
  1935. <p>This release removes support for the <code>structured: true</code> logging configuration
  1936. which was deprecated in Synapse v1.23.0. If your logging configuration contains
  1937. <code>structured: true</code> then it should be modified based on the
  1938. <a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
  1939. <h1 id="upgrading-to-v1530"><a class="header" href="#upgrading-to-v1530">Upgrading to v1.53.0</a></h1>
  1940. <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>
  1941. <p>Per the deprecation notice in Synapse v1.51.0, listeners of type <code>webclient</code>
  1942. are no longer supported and configuring them is a now a configuration error.</p>
  1943. <p>Configuring a non-HTTP(S) <code>web_client_location</code> configuration is is now a
  1944. configuration error. Since the <code>webclient</code> listener is no longer supported, this
  1945. setting only applies to the root path <code>/</code> of Synapse's web server and no longer
  1946. the <code>/_matrix/client/</code> path.</p>
  1947. <h2 id="stablisation-of-msc3231"><a class="header" href="#stablisation-of-msc3231">Stablisation of MSC3231</a></h2>
  1948. <p>The unstable validity-check endpoint for the
  1949. <a href="https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv1registermloginregistration_tokenvalidity">Registration Tokens</a>
  1950. feature has been stabilised and moved from:</p>
  1951. <p><code>/_matrix/client/unstable/org.matrix.msc3231/register/org.matrix.msc3231.login.registration_token/validity</code></p>
  1952. <p>to:</p>
  1953. <p><code>/_matrix/client/v1/register/m.login.registration_token/validity</code></p>
  1954. <p>Please update any relevant reverse proxy or firewall configurations appropriately.</p>
  1955. <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>
  1956. <p>Formerly, entries in the cache were not evicted regardless of whether they were accessed after storing.
  1957. This behavior has now changed. By default entries in the cache are now evicted after 30m of not being accessed.
  1958. To change the default behavior, go to the <code>caches</code> section of the config and change the <code>expire_caches</code> and
  1959. <code>cache_entry_ttl</code> flags as necessary. Please note that these flags replace the <code>expiry_time</code> flag in the config.
  1960. The <code>expiry_time</code> flag will still continue to work, but it has been deprecated and will be removed in the future.</p>
  1961. <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>
  1962. <p>The <code>capabilities</code> of MSC3283 from the REST API <code>/_matrix/client/r0/capabilities</code>
  1963. becomes stable.</p>
  1964. <p>The old <code>capabilities</code></p>
  1965. <ul>
  1966. <li><code>org.matrix.msc3283.set_displayname</code>,</li>
  1967. <li><code>org.matrix.msc3283.set_avatar_url</code> and</li>
  1968. <li><code>org.matrix.msc3283.3pid_changes</code></li>
  1969. </ul>
  1970. <p>are deprecated and scheduled to be removed in Synapse v1.54.0.</p>
  1971. <p>The new <code>capabilities</code></p>
  1972. <ul>
  1973. <li><code>m.set_displayname</code>,</li>
  1974. <li><code>m.set_avatar_url</code> and</li>
  1975. <li><code>m.3pid_changes</code></li>
  1976. </ul>
  1977. <p>are now active by default.</p>
  1978. <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>
  1979. <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>,
  1980. the deprecated <code>user_may_create_room_with_invites</code> module callback has been removed.</p>
  1981. <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>
  1982. 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>
  1983. 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>
  1984. 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>
  1985. <h1 id="upgrading-to-v1520"><a class="header" href="#upgrading-to-v1520">Upgrading to v1.52.0</a></h1>
  1986. <h2 id="twisted-security-release"><a class="header" href="#twisted-security-release">Twisted security release</a></h2>
  1987. <p>Note that <a href="https://github.com/twisted/twisted/releases/tag/twisted-22.1.0">Twisted 22.1.0</a>
  1988. has recently been released, which fixes a <a href="https://github.com/twisted/twisted/security/advisories/GHSA-92x2-jw7w-xvvx">security issue</a>
  1989. within the Twisted library. We do not believe Synapse is affected by this vulnerability,
  1990. though we advise server administrators who installed Synapse via pip to upgrade Twisted
  1991. with <code>pip install --upgrade Twisted treq</code> as a matter of good practice. The Docker image
  1992. <code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> are using the
  1993. updated library.</p>
  1994. <h1 id="upgrading-to-v1510"><a class="header" href="#upgrading-to-v1510">Upgrading to v1.51.0</a></h1>
  1995. <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>
  1996. <p>Listeners of type <code>webclient</code> are deprecated and scheduled to be removed in
  1997. Synapse v1.53.0.</p>
  1998. <p>Similarly, a non-HTTP(S) <code>web_client_location</code> configuration is deprecated and
  1999. will become a configuration error in Synapse v1.53.0.</p>
  2000. <h1 id="upgrading-to-v1500"><a class="header" href="#upgrading-to-v1500">Upgrading to v1.50.0</a></h1>
  2001. <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>
  2002. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  2003. we've dropped support for Python 3.6 and PostgreSQL 9.6, as they are no
  2004. longer supported upstream.</p>
  2005. <p>This release of Synapse requires Python 3.7+ and PostgreSQL 10+.</p>
  2006. <h1 id="upgrading-to-v1470"><a class="header" href="#upgrading-to-v1470">Upgrading to v1.47.0</a></h1>
  2007. <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>
  2008. <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>
  2009. (released on 2021-05-17) and have now been removed:</p>
  2010. <ul>
  2011. <li><code>POST /_synapse/admin/v1/&lt;room_id&gt;/delete</code></li>
  2012. </ul>
  2013. <p>Any scripts still using the above APIs should be converted to use the
  2014. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  2015. <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>
  2016. <p>The <code>user_may_create_room_with_invites</code> is deprecated and will be removed in a future
  2017. version of Synapse. Modules implementing this callback can instead implement
  2018. <a href="https://matrix-org.github.io/synapse/latest/modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a>
  2019. 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>
  2020. module API method to infer whether the invite is happening in the context of creating a
  2021. room.</p>
  2022. <p>We plan to remove this callback in January 2022.</p>
  2023. <h1 id="upgrading-to-v1450"><a class="header" href="#upgrading-to-v1450">Upgrading to v1.45.0</a></h1>
  2024. <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>
  2025. <p>Media storage provider modules that read from the Synapse configuration object (i.e. that
  2026. read the value of <code>hs.config.[...]</code>) now need to specify the configuration section they're
  2027. reading from. This means that if a module reads the value of e.g. <code>hs.config.media_store_path</code>,
  2028. it needs to replace it with <code>hs.config.media.media_store_path</code>.</p>
  2029. <h1 id="upgrading-to-v1440"><a class="header" href="#upgrading-to-v1440">Upgrading to v1.44.0</a></h1>
  2030. <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>
  2031. <p>The <code>url_cache/</code> and <code>url_cache_thumbnails/</code> directories in the media store are
  2032. no longer mirrored to storage providers. These two directories can be safely
  2033. deleted from any configured storage providers to reclaim space.</p>
  2034. <h1 id="upgrading-to-v1430"><a class="header" href="#upgrading-to-v1430">Upgrading to v1.43.0</a></h1>
  2035. <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>
  2036. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#available-worker-applications">available worker applications documentation</a>
  2037. has been updated to reflect that calls to the <code>/spaces</code>, <code>/hierarchy</code>, and
  2038. <code>/summary</code> endpoints can now be routed to workers for both client API and
  2039. federation requests.</p>
  2040. <h1 id="upgrading-to-v1420"><a class="header" href="#upgrading-to-v1420">Upgrading to v1.42.0</a></h1>
  2041. <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>
  2042. <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>
  2043. (released on 2021-01-13) and have now been removed:</p>
  2044. <ul>
  2045. <li><code>POST /_synapse/admin/v1/purge_room</code></li>
  2046. <li><code>POST /_synapse/admin/v1/shutdown_room/&lt;room_id&gt;</code></li>
  2047. </ul>
  2048. <p>Any scripts still using the above APIs should be converted to use the
  2049. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  2050. <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>
  2051. <p>This may affect you if you make use of custom HTML templates for the
  2052. <a href="../synapse/res/templates/recaptcha.html">reCAPTCHA</a> or
  2053. <a href="../synapse/res/templates/terms.html">terms</a> fallback pages.</p>
  2054. <p>The template is now provided an <code>error</code> variable if the authentication
  2055. process failed. See the default templates linked above for an example.</p>
  2056. <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>
  2057. <p>Users will stop receiving message updates via email for addresses that were
  2058. once, but not still, linked to their account.</p>
  2059. <h1 id="upgrading-to-v1410"><a class="header" href="#upgrading-to-v1410">Upgrading to v1.41.0</a></h1>
  2060. <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>
  2061. <p>Since Synapse 1.6.0 (2019-11-26) you can set a proxy for outbound HTTP requests via
  2062. http_proxy/https_proxy environment variables. This proxy was set for:</p>
  2063. <ul>
  2064. <li>push</li>
  2065. <li>url previews</li>
  2066. <li>phone-home stats</li>
  2067. <li>recaptcha validation</li>
  2068. <li>CAS auth validation</li>
  2069. <li>OpenID Connect</li>
  2070. <li>Federation (checking public key revocation)</li>
  2071. </ul>
  2072. <p>In this version we have added support for outbound requests for:</p>
  2073. <ul>
  2074. <li>Outbound federation</li>
  2075. <li>Downloading remote media</li>
  2076. <li>Fetching public keys of other servers</li>
  2077. </ul>
  2078. <p>These requests use the same proxy configuration. If you have a proxy configuration we
  2079. recommend to verify the configuration. It may be necessary to adjust the <code>no_proxy</code>
  2080. environment variable.</p>
  2081. <p>See <a href="setup/forward_proxy.html">using a forward proxy with Synapse documentation</a> for
  2082. details.</p>
  2083. <h2 id="deprecation-of-template_dir"><a class="header" href="#deprecation-of-template_dir">Deprecation of <code>template_dir</code></a></h2>
  2084. <p>The <code>template_dir</code> settings in the <code>sso</code>, <code>account_validity</code> and <code>email</code> sections of the
  2085. configuration file are now deprecated. Server admins should use the new
  2086. <code>templates.custom_template_directory</code> setting in the configuration file and use one single
  2087. custom template directory for all aforementioned features. Template file names remain
  2088. unchanged. See <a href="https://matrix-org.github.io/synapse/latest/templates.html">the related documentation</a>
  2089. for more information and examples.</p>
  2090. <p>We plan to remove support for these settings in October 2021.</p>
  2091. <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>
  2092. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#synapseappmedia_repository">media repository worker documentation</a>
  2093. has been updated to reflect that calls to <code>/_synapse/admin/v1/users/{userId}/media</code>
  2094. must now be handled by media repository workers. This is due to the new <code>DELETE</code> method
  2095. of this endpoint modifying the media store.</p>
  2096. <h1 id="upgrading-to-v1390"><a class="header" href="#upgrading-to-v1390">Upgrading to v1.39.0</a></h1>
  2097. <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>
  2098. <p>The current third-party rules module interface is deprecated in favour of the new generic
  2099. modules system introduced in Synapse v1.37.0. Authors of third-party rules modules can refer
  2100. to <a href="modules/porting_legacy_module.html">this documentation</a>
  2101. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this documentation</a>
  2102. to update their configuration once the modules they are using have been updated.</p>
  2103. <p>We plan to remove support for the current third-party rules interface in September 2021.</p>
  2104. <h1 id="upgrading-to-v1380"><a class="header" href="#upgrading-to-v1380">Upgrading to v1.38.0</a></h1>
  2105. <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>
  2106. <p>This release includes a database schema update which requires re-indexing one of
  2107. the larger tables in the database, <code>events</code>. This could result in increased
  2108. disk I/O for several hours or days after upgrading while the migration
  2109. completes. Furthermore, because we have to keep the old indexes until the new
  2110. indexes are ready, it could result in a significant, temporary, increase in
  2111. disk space.</p>
  2112. <p>To get a rough idea of the disk space required, check the current size of one
  2113. of the indexes. For example, from a <code>psql</code> shell, run the following sql:</p>
  2114. <pre><code class="language-sql">SELECT pg_size_pretty(pg_relation_size('events_order_room'));
  2115. </code></pre>
  2116. <p>We need to rebuild <strong>four</strong> indexes, so you will need to multiply this result
  2117. by four to give an estimate of the disk space required. For example, on one
  2118. particular server:</p>
  2119. <pre><code>synapse=# select pg_size_pretty(pg_relation_size('events_order_room'));
  2120. pg_size_pretty
  2121. ----------------
  2122. 288 MB
  2123. (1 row)
  2124. </code></pre>
  2125. <p>On this server, it would be wise to ensure that at least 1152MB are free.</p>
  2126. <p>The additional disk space will be freed once the migration completes.</p>
  2127. <p>SQLite databases are unaffected by this change.</p>
  2128. <h1 id="upgrading-to-v1370"><a class="header" href="#upgrading-to-v1370">Upgrading to v1.37.0</a></h1>
  2129. <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>
  2130. <p>The current spam checker interface is deprecated in favour of a new generic modules system.
  2131. Authors of spam checker modules can refer to [this
  2132. documentation](modules/porting_legacy_module.md
  2133. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this
  2134. documentation</a>
  2135. to update their configuration once the modules they are using have been updated.</p>
  2136. <p>We plan to remove support for the current spam checker interface in August 2021.</p>
  2137. <p>More module interfaces will be ported over to this new generic system in future versions
  2138. of Synapse.</p>
  2139. <h1 id="upgrading-to-v1340"><a class="header" href="#upgrading-to-v1340">Upgrading to v1.34.0</a></h1>
  2140. <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>
  2141. <p>The <code>room_invite_state_types</code> configuration setting has been deprecated
  2142. 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
  2143. file</a>.</p>
  2144. <p>If you have set <code>room_invite_state_types</code> to the default value you
  2145. should simply remove it from your configuration file. The default value
  2146. used to be:</p>
  2147. <pre><code class="language-yaml">room_invite_state_types:
  2148. - &quot;m.room.join_rules&quot;
  2149. - &quot;m.room.canonical_alias&quot;
  2150. - &quot;m.room.avatar&quot;
  2151. - &quot;m.room.encryption&quot;
  2152. - &quot;m.room.name&quot;
  2153. </code></pre>
  2154. <p>If you have customised this value, you should remove
  2155. <code>room_invite_state_types</code> and configure <code>room_prejoin_state</code> instead.</p>
  2156. <h1 id="upgrading-to-v1330"><a class="header" href="#upgrading-to-v1330">Upgrading to v1.33.0</a></h1>
  2157. <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>
  2158. <p>This may affect you if you have enabled the account validity feature,
  2159. and have made use of a custom HTML template specified by the
  2160. <code>account_validity.template_dir</code> or
  2161. <code>account_validity.account_renewed_html_path</code> Synapse config options.</p>
  2162. <p>The template can now accept an <code>expiration_ts</code> variable, which
  2163. represents the unix timestamp in milliseconds for the future date of
  2164. 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
  2165. template</a>
  2166. for an example of usage.</p>
  2167. <p>ALso note that a new HTML template, <code>account_previously_renewed.html</code>,
  2168. has been added. This is is shown to users when they attempt to renew
  2169. their account with a valid renewal token that has already been used
  2170. before. The default template contents can been found
  2171. <a href="https://github.com/matrix-org/synapse/blob/release-v1.33.0/synapse/res/templates/account_previously_renewed.html">here</a>,
  2172. and can also accept an <code>expiration_ts</code> variable. This template replaces
  2173. the error message users would previously see upon attempting to use a
  2174. valid renewal token more than once.</p>
  2175. <h1 id="upgrading-to-v1320"><a class="header" href="#upgrading-to-v1320">Upgrading to v1.32.0</a></h1>
  2176. <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>
  2177. <p>This release introduces <a href="https://github.com/matrix-org/synapse/issues/9853">a
  2178. regression</a> that can
  2179. overwhelm connected Prometheus instances. This issue is not present in
  2180. Synapse v1.32.0rc1.</p>
  2181. <p>If you have been affected, please downgrade to 1.31.0. You then may need
  2182. to remove excess writeahead logs in order for Prometheus to recover.
  2183. Instructions for doing so are provided
  2184. <a href="https://github.com/matrix-org/synapse/pull/9854#issuecomment-823472183">here</a>.</p>
  2185. <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>
  2186. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  2187. we've dropped support for Python 3.5 and PostgreSQL 9.5, as they are no
  2188. longer supported upstream.</p>
  2189. <p>This release of Synapse requires Python 3.6+ and PostgresSQL 9.6+ or
  2190. SQLite 3.22+.</p>
  2191. <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>
  2192. <p>The deprecated v1 &quot;list accounts&quot; admin API
  2193. (<code>GET /_synapse/admin/v1/users/&lt;user_id&gt;</code>) has been removed in this
  2194. version.</p>
  2195. <p>The <a href="admin_api/user_admin_api.html#list-accounts">v2 list accounts API</a>
  2196. has been available since Synapse 1.7.0 (2019-12-13), and is accessible
  2197. under <code>GET /_synapse/admin/v2/users</code>.</p>
  2198. <p>The deprecation of the old endpoint was announced with Synapse 1.28.0
  2199. (released on 2021-02-25).</p>
  2200. <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>
  2201. <p>In compliance with the <a href="https://matrix.org/docs/spec/application_service/r0.1.2#server-admin-style-permissions">Application Service
  2202. spec</a>,
  2203. Application Services are now required to use the
  2204. <code>m.login.application_service</code> type when registering users via the
  2205. <code>/_matrix/client/r0/register</code> endpoint. This behaviour was deprecated in
  2206. Synapse v1.30.0.</p>
  2207. <p>Please ensure your Application Services are up to date.</p>
  2208. <h1 id="upgrading-to-v1290"><a class="header" href="#upgrading-to-v1290">Upgrading to v1.29.0</a></h1>
  2209. <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>
  2210. <p>When using Synapse with a reverse proxy (in particular, when using the
  2211. <code>x_forwarded</code> option on an HTTP listener), Synapse now
  2212. expects to receive an <code>X-Forwarded-Proto</code> header on incoming
  2213. HTTP requests. If it is not set, Synapse will log a warning on each
  2214. received request.</p>
  2215. <p>To avoid the warning, administrators using a reverse proxy should ensure
  2216. that the reverse proxy sets <code>X-Forwarded-Proto</code> header to
  2217. <code>https</code> or <code>http</code> to indicate the protocol used
  2218. by the client.</p>
  2219. <p>Synapse also requires the <code>Host</code> header to be preserved.</p>
  2220. <p>See the <a href="reverse_proxy.html">reverse proxy documentation</a>, where the
  2221. example configurations have been updated to show how to set these
  2222. headers.</p>
  2223. <p>(Users of <a href="https://caddyserver.com/">Caddy</a> are unaffected, since we
  2224. believe it sets <code>X-Forwarded-Proto</code> by default.)</p>
  2225. <h1 id="upgrading-to-v1270"><a class="header" href="#upgrading-to-v1270">Upgrading to v1.27.0</a></h1>
  2226. <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>
  2227. <p>This version changes the URI used for callbacks from OAuth2 and SAML2
  2228. identity providers:</p>
  2229. <ul>
  2230. <li>
  2231. <p>If your server is configured for single sign-on via an OpenID
  2232. Connect or OAuth2 identity provider, you will need to add
  2233. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> to the list
  2234. of permitted &quot;redirect URIs&quot; at the identity provider.</p>
  2235. <p>See the <a href="openid.html">OpenID docs</a> for more information on setting
  2236. up OpenID Connect.</p>
  2237. </li>
  2238. <li>
  2239. <p>If your server is configured for single sign-on via a SAML2 identity
  2240. provider, you will need to add
  2241. <code>[synapse public baseurl]/_synapse/client/saml2/authn_response</code> as a
  2242. permitted &quot;ACS location&quot; (also known as &quot;allowed callback URLs&quot;)
  2243. at the identity provider.</p>
  2244. <p>The &quot;Issuer&quot; in the &quot;AuthnRequest&quot; to the SAML2 identity
  2245. provider is also updated to
  2246. <code>[synapse public baseurl]/_synapse/client/saml2/metadata.xml</code>. If
  2247. your SAML2 identity provider uses this property to validate or
  2248. otherwise identify Synapse, its configuration will need to be
  2249. updated to use the new URL. Alternatively you could create a new,
  2250. separate &quot;EntityDescriptor&quot; in your SAML2 identity provider with
  2251. the new URLs and leave the URLs in the existing &quot;EntityDescriptor&quot;
  2252. as they were.</p>
  2253. </li>
  2254. </ul>
  2255. <h2 id="changes-to-html-templates"><a class="header" href="#changes-to-html-templates">Changes to HTML templates</a></h2>
  2256. <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
  2257. autoescape</a>
  2258. enabled for files ending in <code>.html</code>, <code>.htm</code>, and <code>.xml</code>. If you have
  2259. customised these templates and see issues when viewing them you might
  2260. need to update them. It is expected that most configurations will need
  2261. no changes.</p>
  2262. <p>If you have customised the templates <em>names</em> for these templates, it is
  2263. recommended to verify they end in <code>.html</code> to ensure autoescape is
  2264. enabled.</p>
  2265. <p>The above applies to the following templates:</p>
  2266. <ul>
  2267. <li><code>add_threepid.html</code></li>
  2268. <li><code>add_threepid_failure.html</code></li>
  2269. <li><code>add_threepid_success.html</code></li>
  2270. <li><code>notice_expiry.html</code></li>
  2271. <li><code>notice_expiry.html</code></li>
  2272. <li><code>notif_mail.html</code> (which, by default, includes <code>room.html</code> and
  2273. <code>notif.html</code>)</li>
  2274. <li><code>password_reset.html</code></li>
  2275. <li><code>password_reset_confirmation.html</code></li>
  2276. <li><code>password_reset_failure.html</code></li>
  2277. <li><code>password_reset_success.html</code></li>
  2278. <li><code>registration.html</code></li>
  2279. <li><code>registration_failure.html</code></li>
  2280. <li><code>registration_success.html</code></li>
  2281. <li><code>sso_account_deactivated.html</code></li>
  2282. <li><code>sso_auth_bad_user.html</code></li>
  2283. <li><code>sso_auth_confirm.html</code></li>
  2284. <li><code>sso_auth_success.html</code></li>
  2285. <li><code>sso_error.html</code></li>
  2286. <li><code>sso_login_idp_picker.html</code></li>
  2287. <li><code>sso_redirect_confirm.html</code></li>
  2288. </ul>
  2289. <h1 id="upgrading-to-v1260"><a class="header" href="#upgrading-to-v1260">Upgrading to v1.26.0</a></h1>
  2290. <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>
  2291. <p>v1.26.0 includes a lot of large changes. If something problematic
  2292. occurs, you may want to roll-back to a previous version of Synapse.
  2293. Because v1.26.0 also includes a new database schema version, reverting
  2294. that version is also required alongside the generic rollback
  2295. instructions mentioned above. In short, to roll back to v1.25.0 you need
  2296. to:</p>
  2297. <ol>
  2298. <li>
  2299. <p>Stop the server</p>
  2300. </li>
  2301. <li>
  2302. <p>Decrease the schema version in the database:</p>
  2303. <pre><code class="language-sql">UPDATE schema_version SET version = 58;
  2304. </code></pre>
  2305. </li>
  2306. <li>
  2307. <p>Delete the ignored users &amp; chain cover data:</p>
  2308. <pre><code class="language-sql">DROP TABLE IF EXISTS ignored_users;
  2309. UPDATE rooms SET has_auth_chain_index = false;
  2310. </code></pre>
  2311. <p>For PostgreSQL run:</p>
  2312. <pre><code class="language-sql">TRUNCATE event_auth_chain_links;
  2313. TRUNCATE event_auth_chains;
  2314. </code></pre>
  2315. <p>For SQLite run:</p>
  2316. <pre><code class="language-sql">DELETE FROM event_auth_chain_links;
  2317. DELETE FROM event_auth_chains;
  2318. </code></pre>
  2319. </li>
  2320. <li>
  2321. <p>Mark the deltas as not run (so they will re-run on upgrade).</p>
  2322. <pre><code class="language-sql">DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/01ignored_user.py&quot;;
  2323. DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/06chain_cover_index.sql&quot;;
  2324. </code></pre>
  2325. </li>
  2326. <li>
  2327. <p>Downgrade Synapse by following the instructions for your
  2328. installation method in the &quot;Rolling back to older versions&quot;
  2329. section above.</p>
  2330. </li>
  2331. </ol>
  2332. <h1 id="upgrading-to-v1250"><a class="header" href="#upgrading-to-v1250">Upgrading to v1.25.0</a></h1>
  2333. <h2 id="last-release-supporting-python-35"><a class="header" href="#last-release-supporting-python-35">Last release supporting Python 3.5</a></h2>
  2334. <p>This is the last release of Synapse which guarantees support with Python
  2335. 3.5, which passed its upstream End of Life date several months ago.</p>
  2336. <p>We will attempt to maintain support through March 2021, but without
  2337. guarantees.</p>
  2338. <p>In the future, Synapse will follow upstream schedules for ending support
  2339. of older versions of Python and PostgreSQL. Please upgrade to at least
  2340. Python 3.6 and PostgreSQL 9.6 as soon as possible.</p>
  2341. <h2 id="blacklisting-ip-ranges"><a class="header" href="#blacklisting-ip-ranges">Blacklisting IP ranges</a></h2>
  2342. <p>Synapse v1.25.0 includes new settings, <code>ip_range_blacklist</code> and
  2343. <code>ip_range_whitelist</code>, for controlling outgoing requests from Synapse for
  2344. federation, identity servers, push, and for checking key validity for
  2345. third-party invite events. The previous setting,
  2346. <code>federation_ip_range_blacklist</code>, is deprecated. The new
  2347. <code>ip_range_blacklist</code> defaults to private IP ranges if it is not defined.</p>
  2348. <p>If you have never customised <code>federation_ip_range_blacklist</code> it is
  2349. recommended that you remove that setting.</p>
  2350. <p>If you have customised <code>federation_ip_range_blacklist</code> you should update
  2351. the setting name to <code>ip_range_blacklist</code>.</p>
  2352. <p>If you have a custom push server that is reached via private IP space
  2353. you may need to customise <code>ip_range_blacklist</code> or <code>ip_range_whitelist</code>.</p>
  2354. <h1 id="upgrading-to-v1240"><a class="header" href="#upgrading-to-v1240">Upgrading to v1.24.0</a></h1>
  2355. <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>
  2356. <p>This release allows the OpenID Connect mapping provider to perform
  2357. normalisation of the localpart of the Matrix ID. This allows for the
  2358. mapping provider to specify different algorithms, instead of the
  2359. <a href="https://matrix.org/docs/spec/appendices#mapping-from-other-character-sets">default
  2360. way</a>.</p>
  2361. <p>If your Synapse configuration uses a custom mapping provider
  2362. (<code>oidc_config.user_mapping_provider.module</code> is specified and
  2363. not equal to
  2364. <code>synapse.handlers.oidc_handler.JinjaOidcMappingProvider</code>)
  2365. then you <em>must</em> ensure that <code>map_user_attributes</code> of the
  2366. mapping provider performs some normalisation of the
  2367. <code>localpart</code> returned. To match previous behaviour you can
  2368. use the <code>map_username_to_mxid_localpart</code> function provided
  2369. by Synapse. An example is shown below:</p>
  2370. <pre><code class="language-python">from synapse.types import map_username_to_mxid_localpart
  2371. class MyMappingProvider:
  2372. def map_user_attributes(self, userinfo, token):
  2373. # ... your custom logic ...
  2374. sso_user_id = ...
  2375. localpart = map_username_to_mxid_localpart(sso_user_id)
  2376. return {&quot;localpart&quot;: localpart}
  2377. </code></pre>
  2378. <h2 id="removal-historical-synapse-admin-api"><a class="header" href="#removal-historical-synapse-admin-api">Removal historical Synapse Admin API</a></h2>
  2379. <p>Historically, the Synapse Admin API has been accessible under:</p>
  2380. <ul>
  2381. <li><code>/_matrix/client/api/v1/admin</code></li>
  2382. <li><code>/_matrix/client/unstable/admin</code></li>
  2383. <li><code>/_matrix/client/r0/admin</code></li>
  2384. <li><code>/_synapse/admin/v1</code></li>
  2385. </ul>
  2386. <p>The endpoints with <code>/_matrix/client/*</code> prefixes have been removed as of
  2387. v1.24.0. The Admin API is now only accessible under:</p>
  2388. <ul>
  2389. <li><code>/_synapse/admin/v1</code></li>
  2390. </ul>
  2391. <p>The only exception is the <code>/admin/whois</code> endpoint, which is
  2392. <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
  2393. API</a>.</p>
  2394. <p>The deprecation of the old endpoints was announced with Synapse 1.20.0
  2395. (released on 2020-09-22) and makes it easier for homeserver admins to
  2396. lock down external access to the Admin API endpoints.</p>
  2397. <h1 id="upgrading-to-v1230"><a class="header" href="#upgrading-to-v1230">Upgrading to v1.23.0</a></h1>
  2398. <h2 id="structured-logging-configuration-breaking-changes"><a class="header" href="#structured-logging-configuration-breaking-changes">Structured logging configuration breaking changes</a></h2>
  2399. <p>This release deprecates use of the <code>structured: true</code> logging
  2400. configuration for structured logging. If your logging configuration
  2401. contains <code>structured: true</code> then it should be modified based on the
  2402. <a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
  2403. <p>The <code>structured</code> and <code>drains</code> logging options are now deprecated and
  2404. should be replaced by standard logging configuration of <code>handlers</code> and
  2405. <code>formatters</code>.</p>
  2406. <p>A future will release of Synapse will make using <code>structured: true</code> an
  2407. error.</p>
  2408. <h1 id="upgrading-to-v1220"><a class="header" href="#upgrading-to-v1220">Upgrading to v1.22.0</a></h1>
  2409. <h2 id="thirdpartyeventrules-breaking-changes"><a class="header" href="#thirdpartyeventrules-breaking-changes">ThirdPartyEventRules breaking changes</a></h2>
  2410. <p>This release introduces a backwards-incompatible change to modules
  2411. making use of <code>ThirdPartyEventRules</code> in Synapse. If you make use of a
  2412. module defined under the <code>third_party_event_rules</code> config option, please
  2413. make sure it is updated to handle the below change:</p>
  2414. <p>The <code>http_client</code> argument is no longer passed to modules as they are
  2415. initialised. Instead, modules are expected to make use of the
  2416. <code>http_client</code> property on the <code>ModuleApi</code> class. Modules are now passed
  2417. a <code>module_api</code> argument during initialisation, which is an instance of
  2418. <code>ModuleApi</code>. <code>ModuleApi</code> instances have a <code>http_client</code> property which
  2419. acts the same as the <code>http_client</code> argument previously passed to
  2420. <code>ThirdPartyEventRules</code> modules.</p>
  2421. <h1 id="upgrading-to-v1210"><a class="header" href="#upgrading-to-v1210">Upgrading to v1.21.0</a></h1>
  2422. <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>
  2423. <p>The <a href="reverse_proxy.html">reverse proxy documentation</a>
  2424. has been updated to include reverse proxy directives for
  2425. <code>/_synapse/client/*</code> endpoints. As the user password reset flow now uses
  2426. endpoints under this prefix, <strong>you must update your reverse proxy
  2427. configurations for user password reset to work</strong>.</p>
  2428. <p>Additionally, note that the <a href="workers.html">Synapse worker documentation</a> has been updated to</p>
  2429. <p>: state that the <code>/_synapse/client/password_reset/email/submit_token</code>
  2430. endpoint can be handled</p>
  2431. <p>by all workers. If you make use of Synapse's worker feature, please
  2432. update your reverse proxy configuration to reflect this change.</p>
  2433. <h2 id="new-html-templates"><a class="header" href="#new-html-templates">New HTML templates</a></h2>
  2434. <p>A new HTML template,
  2435. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/res/templates/password_reset_confirmation.html">password_reset_confirmation.html</a>,
  2436. has been added to the <code>synapse/res/templates</code> directory. If you are
  2437. using a custom template directory, you may want to copy the template
  2438. over and modify it.</p>
  2439. <p>Note that as of v1.20.0, templates do not need to be included in custom
  2440. template directories for Synapse to start. The default templates will be
  2441. used if a custom template cannot be found.</p>
  2442. <p>This page will appear to the user after clicking a password reset link
  2443. that has been emailed to them.</p>
  2444. <p>To complete password reset, the page must include a way to make a
  2445. <code>POST</code> request to
  2446. <code>/_synapse/client/password_reset/{medium}/submit_token</code> with the query
  2447. parameters from the original link, presented as a URL-encoded form. See
  2448. the file itself for more details.</p>
  2449. <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>
  2450. <p>The <code>saml_error.html</code> template was removed from Synapse and replaced
  2451. with the <code>sso_error.html</code> template. If your Synapse is configured to use
  2452. SAML and a custom <code>sso_redirect_confirm_template_dir</code> configuration then
  2453. any customisations of the <code>saml_error.html</code> template will need to be
  2454. merged into the <code>sso_error.html</code> template. These templates are similar,
  2455. but the parameters are slightly different:</p>
  2456. <ul>
  2457. <li>The <code>msg</code> parameter should be renamed to <code>error_description</code>.</li>
  2458. <li>There is no longer a <code>code</code> parameter for the response code.</li>
  2459. <li>A string <code>error</code> parameter is available that includes a short hint
  2460. of why a user is seeing the error page.</li>
  2461. </ul>
  2462. <h1 id="upgrading-to-v1180"><a class="header" href="#upgrading-to-v1180">Upgrading to v1.18.0</a></h1>
  2463. <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>
  2464. <p>From 10th August 2020, we will no longer publish Docker images with the
  2465. <code>-py3</code> tag suffix. The images tagged with the
  2466. <code>-py3</code> suffix have been identical to the non-suffixed tags
  2467. since release 0.99.0, and the suffix is obsolete.</p>
  2468. <p>On 10th August, we will remove the <code>latest-py3</code> tag.
  2469. Existing per-release tags (such as <code>v1.18.0-py3</code> will not
  2470. be removed, but no new <code>-py3</code> tags will be added.</p>
  2471. <p>Scripts relying on the <code>-py3</code> suffix will need to be
  2472. updated.</p>
  2473. <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>
  2474. <p>When setting up worker processes, we now recommend the use of a Redis
  2475. server for replication. <strong>The old direct TCP connection method is
  2476. deprecated and will be removed in a future release.</strong> See
  2477. the <a href="https://matrix-org.github.io/synapse/v1.66/workers.html">worker documentation</a> for more details.</p>
  2478. <h1 id="upgrading-to-v1140"><a class="header" href="#upgrading-to-v1140">Upgrading to v1.14.0</a></h1>
  2479. <p>This version includes a database update which is run as part of the
  2480. upgrade, and which may take a couple of minutes in the case of a large
  2481. server. Synapse will not respond to HTTP requests while this update is
  2482. taking place.</p>
  2483. <h1 id="upgrading-to-v1130"><a class="header" href="#upgrading-to-v1130">Upgrading to v1.13.0</a></h1>
  2484. <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>
  2485. <p>A bug was introduced in Synapse 1.4.0 which could cause the room
  2486. directory to be incomplete or empty if Synapse was upgraded directly
  2487. from v1.2.1 or earlier, to versions between v1.4.0 and v1.12.x.</p>
  2488. <p>This will <em>not</em> be a problem for Synapse installations which were:</p>
  2489. <p>: - created at v1.4.0 or later,
  2490. - upgraded via v1.3.x, or
  2491. - upgraded straight from v1.2.1 or earlier to v1.13.0 or later.</p>
  2492. <p>If completeness of the room directory is a concern, installations which
  2493. are affected can be repaired as follows:</p>
  2494. <ol>
  2495. <li>
  2496. <p>Run the following sql from a <code>psql</code> or
  2497. <code>sqlite3</code> console:</p>
  2498. <pre><code class="language-sql">INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2499. ('populate_stats_process_rooms', '{}', 'current_state_events_membership');
  2500. INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2501. ('populate_stats_process_users', '{}', 'populate_stats_process_rooms');
  2502. </code></pre>
  2503. </li>
  2504. <li>
  2505. <p>Restart synapse.</p>
  2506. </li>
  2507. </ol>
  2508. <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>
  2509. <p>New templates (<code>sso_auth_confirm.html</code>, <code>sso_auth_success.html</code>, and
  2510. <code>sso_account_deactivated.html</code>) were added to Synapse. If your Synapse
  2511. is configured to use SSO and a custom
  2512. <code>sso_redirect_confirm_template_dir</code> configuration then these templates
  2513. will need to be copied from
  2514. <a href="synapse/res/templates">synapse/res/templates</a> into that directory.</p>
  2515. <h2 id="synapse-sso-plugins-method-deprecation"><a class="header" href="#synapse-sso-plugins-method-deprecation">Synapse SSO Plugins Method Deprecation</a></h2>
  2516. <p>Plugins using the <code>complete_sso_login</code> method of
  2517. <code>synapse.module_api.ModuleApi</code> should update to using the async/await
  2518. version <code>complete_sso_login_async</code> which includes additional checks. The
  2519. non-async version is considered deprecated.</p>
  2520. <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>
  2521. <p>v1.13.0 includes a lot of large changes. If something problematic
  2522. occurs, you may want to roll-back to a previous version of Synapse.
  2523. Because v1.13.0 also includes a new database schema version, reverting
  2524. that version is also required alongside the generic rollback
  2525. instructions mentioned above. In short, to roll back to v1.12.4 you need
  2526. to:</p>
  2527. <ol>
  2528. <li>
  2529. <p>Stop the server</p>
  2530. </li>
  2531. <li>
  2532. <p>Decrease the schema version in the database:</p>
  2533. <pre><code class="language-sql">UPDATE schema_version SET version = 57;
  2534. </code></pre>
  2535. </li>
  2536. <li>
  2537. <p>Downgrade Synapse by following the instructions for your
  2538. installation method in the &quot;Rolling back to older versions&quot;
  2539. section above.</p>
  2540. </li>
  2541. </ol>
  2542. <h1 id="upgrading-to-v1120"><a class="header" href="#upgrading-to-v1120">Upgrading to v1.12.0</a></h1>
  2543. <p>This version includes a database update which is run as part of the
  2544. upgrade, and which may take some time (several hours in the case of a
  2545. large server). Synapse will not respond to HTTP requests while this
  2546. update is taking place.</p>
  2547. <p>This is only likely to be a problem in the case of a server which is
  2548. participating in many rooms.</p>
  2549. <ol start="0">
  2550. <li>
  2551. <p>As with all upgrades, it is recommended that you have a recent
  2552. backup of your database which can be used for recovery in the event
  2553. of any problems.</p>
  2554. </li>
  2555. <li>
  2556. <p>As an initial check to see if you will be affected, you can try
  2557. running the following query from the <code>psql</code> or
  2558. <code>sqlite3</code> console. It is safe to run it while Synapse is
  2559. still running.</p>
  2560. <pre><code class="language-sql">SELECT MAX(q.v) FROM (
  2561. SELECT (
  2562. SELECT ej.json AS v
  2563. FROM state_events se INNER JOIN event_json ej USING (event_id)
  2564. WHERE se.room_id=rooms.room_id AND se.type='m.room.create' AND se.state_key=''
  2565. LIMIT 1
  2566. ) FROM rooms WHERE rooms.room_version IS NULL
  2567. ) q;
  2568. </code></pre>
  2569. <p>This query will take about the same amount of time as the upgrade
  2570. process: ie, if it takes 5 minutes, then it is likely that Synapse
  2571. will be unresponsive for 5 minutes during the upgrade.</p>
  2572. <p>If you consider an outage of this duration to be acceptable, no
  2573. further action is necessary and you can simply start Synapse 1.12.0.</p>
  2574. <p>If you would prefer to reduce the downtime, continue with the steps
  2575. below.</p>
  2576. </li>
  2577. <li>
  2578. <p>The easiest workaround for this issue is to manually create a new
  2579. index before upgrading. On PostgreSQL, his can be done as follows:</p>
  2580. <pre><code class="language-sql">CREATE INDEX CONCURRENTLY tmp_upgrade_1_12_0_index
  2581. ON state_events(room_id) WHERE type = 'm.room.create';
  2582. </code></pre>
  2583. <p>The above query may take some time, but is also safe to run while
  2584. Synapse is running.</p>
  2585. <p>We assume that no SQLite users have databases large enough to be
  2586. affected. If you <em>are</em> affected, you can run a similar query,
  2587. omitting the <code>CONCURRENTLY</code> keyword. Note however that this
  2588. operation may in itself cause Synapse to stop running for some time.
  2589. Synapse admins are reminded that <a href="postgres.html">SQLite is not recommended for use
  2590. outside a test environment</a>.</p>
  2591. </li>
  2592. <li>
  2593. <p>Once the index has been created, the <code>SELECT</code> query in step 1 above
  2594. should complete quickly. It is therefore safe to upgrade to Synapse
  2595. 1.12.0.</p>
  2596. </li>
  2597. <li>
  2598. <p>Once Synapse 1.12.0 has successfully started and is responding to
  2599. HTTP requests, the temporary index can be removed:</p>
  2600. <pre><code class="language-sql">DROP INDEX tmp_upgrade_1_12_0_index;
  2601. </code></pre>
  2602. </li>
  2603. </ol>
  2604. <h1 id="upgrading-to-v1100"><a class="header" href="#upgrading-to-v1100">Upgrading to v1.10.0</a></h1>
  2605. <p>Synapse will now log a warning on start up if used with a PostgreSQL
  2606. database that has a non-recommended locale set.</p>
  2607. <p>See <a href="postgres.html">Postgres</a> for details.</p>
  2608. <h1 id="upgrading-to-v180"><a class="header" href="#upgrading-to-v180">Upgrading to v1.8.0</a></h1>
  2609. <p>Specifying a <code>log_file</code> config option will now cause Synapse to refuse
  2610. to start, and should be replaced by with the <code>log_config</code> option.
  2611. Support for the <code>log_file</code> option was removed in v1.3.0 and has since
  2612. had no effect.</p>
  2613. <h1 id="upgrading-to-v170"><a class="header" href="#upgrading-to-v170">Upgrading to v1.7.0</a></h1>
  2614. <p>In an attempt to configure Synapse in a privacy preserving way, the
  2615. default behaviours of <code>allow_public_rooms_without_auth</code> and
  2616. <code>allow_public_rooms_over_federation</code> have been inverted. This means that
  2617. by default, only authenticated users querying the Client/Server API will
  2618. be able to query the room directory, and relatedly that the server will
  2619. not share room directory information with other servers over federation.</p>
  2620. <p>If your installation does not explicitly set these settings one way or
  2621. the other and you want either setting to be <code>true</code> then it will
  2622. necessary to update your homeserver configuration file accordingly.</p>
  2623. <p>For more details on the surrounding context see our
  2624. <a href="https://matrix.org/blog/2019/11/09/avoiding-unwelcome-visitors-on-private-matrix-servers">explainer</a>.</p>
  2625. <h1 id="upgrading-to-v150"><a class="header" href="#upgrading-to-v150">Upgrading to v1.5.0</a></h1>
  2626. <p>This release includes a database migration which may take several
  2627. minutes to complete if there are a large number (more than a million or
  2628. so) of entries in the <code>devices</code> table. This is only likely to a be a
  2629. problem on very large installations.</p>
  2630. <h1 id="upgrading-to-v140"><a class="header" href="#upgrading-to-v140">Upgrading to v1.4.0</a></h1>
  2631. <h2 id="new-custom-templates"><a class="header" href="#new-custom-templates">New custom templates</a></h2>
  2632. <p>If you have configured a custom template directory with the
  2633. <code>email.template_dir</code> option, be aware that there are new templates
  2634. regarding registration and threepid management (see below) that must be
  2635. included.</p>
  2636. <ul>
  2637. <li><code>registration.html</code> and <code>registration.txt</code></li>
  2638. <li><code>registration_success.html</code> and <code>registration_failure.html</code></li>
  2639. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code></li>
  2640. <li><code>add_threepid_failure.html</code> and <code>add_threepid_success.html</code></li>
  2641. </ul>
  2642. <p>Synapse will expect these files to exist inside the configured template
  2643. directory, and <strong>will fail to start</strong> if they are absent. To view the
  2644. default templates, see
  2645. <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">synapse/res/templates</a>.</p>
  2646. <h2 id="3pid-verification-changes"><a class="header" href="#3pid-verification-changes">3pid verification changes</a></h2>
  2647. <p><strong>Note: As of this release, users will be unable to add phone numbers or
  2648. email addresses to their accounts, without changes to the Synapse
  2649. configuration. This includes adding an email address during
  2650. registration.</strong></p>
  2651. <p>It is possible for a user to associate an email address or phone number
  2652. with their account, for a number of reasons:</p>
  2653. <ul>
  2654. <li>for use when logging in, as an alternative to the user id.</li>
  2655. <li>in the case of email, as an alternative contact to help with account
  2656. recovery.</li>
  2657. <li>in the case of email, to receive notifications of missed messages.</li>
  2658. </ul>
  2659. <p>Before an email address or phone number can be added to a user's
  2660. account, or before such an address is used to carry out a
  2661. password-reset, Synapse must confirm the operation with the owner of the
  2662. email address or phone number. It does this by sending an email or text
  2663. giving the user a link or token to confirm receipt. This process is
  2664. known as '3pid verification'. ('3pid', or 'threepid', stands for
  2665. third-party identifier, and we use it to refer to external identifiers
  2666. such as email addresses and phone numbers.)</p>
  2667. <p>Previous versions of Synapse delegated the task of 3pid verification to
  2668. an identity server by default. In most cases this server is <code>vector.im</code>
  2669. or <code>matrix.org</code>.</p>
  2670. <p>In Synapse 1.4.0, for security and privacy reasons, the homeserver will
  2671. no longer delegate this task to an identity server by default. Instead,
  2672. the server administrator will need to explicitly decide how they would
  2673. like the verification messages to be sent.</p>
  2674. <p>In the medium term, the <code>vector.im</code> and <code>matrix.org</code> identity servers
  2675. will disable support for delegated 3pid verification entirely. However,
  2676. in order to ease the transition, they will retain the capability for a
  2677. limited period. Delegated email verification will be disabled on Monday
  2678. 2nd December 2019 (giving roughly 2 months notice). Disabling delegated
  2679. SMS verification will follow some time after that once SMS verification
  2680. support lands in Synapse.</p>
  2681. <p>Once delegated 3pid verification support has been disabled in the
  2682. <code>vector.im</code> and <code>matrix.org</code> identity servers, all Synapse versions that
  2683. depend on those instances will be unable to verify email and phone
  2684. numbers through them. There are no imminent plans to remove delegated
  2685. 3pid verification from Sydent generally. (Sydent is the identity server
  2686. project that backs the <code>vector.im</code> and <code>matrix.org</code> instances).</p>
  2687. <h3 id="email-1"><a class="header" href="#email-1">Email</a></h3>
  2688. <p>Following upgrade, to continue verifying email (e.g. as part of the
  2689. registration process), admins can either:-</p>
  2690. <ul>
  2691. <li>Configure Synapse to use an email server.</li>
  2692. <li>Run or choose an identity server which allows delegated email
  2693. verification and delegate to it.</li>
  2694. </ul>
  2695. <h4 id="configure-smtp-in-synapse"><a class="header" href="#configure-smtp-in-synapse">Configure SMTP in Synapse</a></h4>
  2696. <p>To configure an SMTP server for Synapse, modify the configuration
  2697. section headed <code>email</code>, and be sure to have at least the
  2698. <code>smtp_host, smtp_port</code> and <code>notif_from</code> fields filled out.</p>
  2699. <p>You may also need to set <code>smtp_user</code>, <code>smtp_pass</code>, and
  2700. <code>require_transport_security</code>.</p>
  2701. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2702. for more details on these settings.</p>
  2703. <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>
  2704. <p>Some admins will wish to continue using email verification as part of
  2705. the registration process, but will not immediately have an appropriate
  2706. SMTP server at hand.</p>
  2707. <p>To this end, we will continue to support email verification delegation
  2708. via the <code>vector.im</code> and <code>matrix.org</code> identity servers for two months.
  2709. Support for delegated email verification will be disabled on Monday 2nd
  2710. December.</p>
  2711. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  2712. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  2713. server</a>) to handle
  2714. sending confirmation messages via email and SMS.</p>
  2715. <p>So to delegate email verification, in <code>homeserver.yaml</code>, set
  2716. <code>account_threepid_delegates.email</code> to the base URL of an identity
  2717. server. For example:</p>
  2718. <pre><code class="language-yaml">account_threepid_delegates:
  2719. email: https://example.com # Delegate email sending to example.com
  2720. </code></pre>
  2721. <p>Note that <code>account_threepid_delegates.email</code> replaces the deprecated
  2722. <code>email.trust_identity_server_for_password_resets</code>: if
  2723. <code>email.trust_identity_server_for_password_resets</code> is set to <code>true</code>, and
  2724. <code>account_threepid_delegates.email</code> is not set, then the first entry in
  2725. <code>trusted_third_party_id_servers</code> will be used as the
  2726. <code>account_threepid_delegate</code> for email. This is to ensure compatibility
  2727. with existing Synapse installs that set up external server handling for
  2728. these tasks before v1.4.0. If
  2729. <code>email.trust_identity_server_for_password_resets</code> is <code>true</code> and no
  2730. trusted identity server domains are configured, Synapse will report an
  2731. error and refuse to start.</p>
  2732. <p>If <code>email.trust_identity_server_for_password_resets</code> is <code>false</code> or
  2733. absent and no <code>email</code> delegate is configured in
  2734. <code>account_threepid_delegates</code>, then Synapse will send email verification
  2735. messages itself, using the configured SMTP server (see above). that
  2736. type.</p>
  2737. <h3 id="phone-numbers"><a class="header" href="#phone-numbers">Phone numbers</a></h3>
  2738. <p>Synapse does not support phone-number verification itself, so the only
  2739. way to maintain the ability for users to add phone numbers to their
  2740. accounts will be by continuing to delegate phone number verification to
  2741. the <code>matrix.org</code> and <code>vector.im</code> identity servers (or another identity
  2742. server that supports SMS sending).</p>
  2743. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  2744. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  2745. server</a>) to handle
  2746. sending confirmation messages via email and SMS.</p>
  2747. <p>So to delegate phone number verification, in <code>homeserver.yaml</code>, set
  2748. <code>account_threepid_delegates.msisdn</code> to the base URL of an identity
  2749. server. For example:</p>
  2750. <pre><code class="language-yaml">account_threepid_delegates:
  2751. msisdn: https://example.com # Delegate sms sending to example.com
  2752. </code></pre>
  2753. <p>The <code>matrix.org</code> and <code>vector.im</code> identity servers will continue to
  2754. support delegated phone number verification via SMS until such time as
  2755. it is possible for admins to configure their servers to perform phone
  2756. number verification directly. More details will follow in a future
  2757. release.</p>
  2758. <h2 id="rolling-back-to-v131"><a class="header" href="#rolling-back-to-v131">Rolling back to v1.3.1</a></h2>
  2759. <p>If you encounter problems with v1.4.0, it should be possible to roll
  2760. back to v1.3.1, subject to the following:</p>
  2761. <ul>
  2762. <li>
  2763. <p>The 'room statistics' engine was heavily reworked in this release
  2764. (see <a href="https://github.com/matrix-org/synapse/pull/5971">#5971</a>),
  2765. including significant changes to the database schema, which are not
  2766. easily reverted. This will cause the room statistics engine to stop
  2767. updating when you downgrade.</p>
  2768. <p>The room statistics are essentially unused in v1.3.1 (in future
  2769. versions of Synapse, they will be used to populate the room
  2770. directory), so there should be no loss of functionality. However,
  2771. the statistics engine will write errors to the logs, which can be
  2772. avoided by setting the following in <code>homeserver.yaml</code>:</p>
  2773. <pre><code class="language-yaml">stats:
  2774. enabled: false
  2775. </code></pre>
  2776. <p>Don't forget to re-enable it when you upgrade again, in preparation
  2777. for its use in the room directory!</p>
  2778. </li>
  2779. </ul>
  2780. <h1 id="upgrading-to-v120"><a class="header" href="#upgrading-to-v120">Upgrading to v1.2.0</a></h1>
  2781. <p>Some counter metrics have been renamed, with the old names deprecated.
  2782. See <a href="metrics-howto.html#renaming-of-metrics--deprecation-of-old-names-in-12">the metrics
  2783. documentation</a>
  2784. for details.</p>
  2785. <h1 id="upgrading-to-v110"><a class="header" href="#upgrading-to-v110">Upgrading to v1.1.0</a></h1>
  2786. <p>Synapse v1.1.0 removes support for older Python and PostgreSQL versions,
  2787. as outlined in <a href="https://matrix.org/blog/2019/04/08/synapse-deprecating-postgres-9-4-and-python-2-x">our deprecation
  2788. notice</a>.</p>
  2789. <h2 id="minimum-python-version"><a class="header" href="#minimum-python-version">Minimum Python Version</a></h2>
  2790. <p>Synapse v1.1.0 has a minimum Python requirement of Python 3.5. Python
  2791. 3.6 or Python 3.7 are recommended as they have improved internal string
  2792. handling, significantly reducing memory usage.</p>
  2793. <p>If you use current versions of the Matrix.org-distributed Debian
  2794. packages or Docker images, action is not required.</p>
  2795. <p>If you install Synapse in a Python virtual environment, please see
  2796. &quot;Upgrading to v0.34.0&quot; for notes on setting up a new virtualenv under
  2797. Python 3.</p>
  2798. <h2 id="minimum-postgresql-version"><a class="header" href="#minimum-postgresql-version">Minimum PostgreSQL Version</a></h2>
  2799. <p>If using PostgreSQL under Synapse, you will need to use PostgreSQL 9.5
  2800. or above. Please see the <a href="https://www.postgresql.org/docs/11/upgrading.html">PostgreSQL
  2801. documentation</a> for
  2802. more details on upgrading your database.</p>
  2803. <h1 id="upgrading-to-v10"><a class="header" href="#upgrading-to-v10">Upgrading to v1.0</a></h1>
  2804. <h2 id="validation-of-tls-certificates"><a class="header" href="#validation-of-tls-certificates">Validation of TLS certificates</a></h2>
  2805. <p>Synapse v1.0 is the first release to enforce validation of TLS
  2806. certificates for the federation API. It is therefore essential that your
  2807. certificates are correctly configured.</p>
  2808. <p>Note, v1.0 installations will also no longer be able to federate with
  2809. servers that have not correctly configured their certificates.</p>
  2810. <p>In rare cases, it may be desirable to disable certificate checking: for
  2811. example, it might be essential to be able to federate with a given
  2812. legacy server in a closed federation. This can be done in one of two
  2813. ways:-</p>
  2814. <ul>
  2815. <li>Configure the global switch <code>federation_verify_certificates</code> to
  2816. <code>false</code>.</li>
  2817. <li>Configure a whitelist of server domains to trust via
  2818. <code>federation_certificate_verification_whitelist</code>.</li>
  2819. </ul>
  2820. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2821. for more details on these settings.</p>
  2822. <h2 id="email-2"><a class="header" href="#email-2">Email</a></h2>
  2823. <p>When a user requests a password reset, Synapse will send an email to the
  2824. user to confirm the request.</p>
  2825. <p>Previous versions of Synapse delegated the job of sending this email to
  2826. an identity server. If the identity server was somehow malicious or
  2827. became compromised, it would be theoretically possible to hijack an
  2828. account through this means.</p>
  2829. <p>Therefore, by default, Synapse v1.0 will send the confirmation email
  2830. itself. If Synapse is not configured with an SMTP server, password reset
  2831. via email will be disabled.</p>
  2832. <p>To configure an SMTP server for Synapse, modify the configuration
  2833. section headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>,
  2834. <code>smtp_port</code> and <code>notif_from</code> fields filled out. You may also need to set
  2835. <code>smtp_user</code>, <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  2836. <p>If you are absolutely certain that you wish to continue using an
  2837. identity server for password resets, set
  2838. <code>trust_identity_server_for_password_resets</code> to <code>true</code>.</p>
  2839. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2840. for more details on these settings.</p>
  2841. <h2 id="new-email-templates"><a class="header" href="#new-email-templates">New email templates</a></h2>
  2842. <p>Some new templates have been added to the default template directory for the purpose of
  2843. the homeserver sending its own password reset emails. If you have configured a
  2844. custom <code>template_dir</code> in your Synapse config, these files will need to be added.</p>
  2845. <p><code>password_reset.html</code> and <code>password_reset.txt</code> are HTML and plain text
  2846. templates respectively that contain the contents of what will be emailed
  2847. to the user upon attempting to reset their password via email.
  2848. <code>password_reset_success.html</code> and <code>password_reset_failure.html</code> are HTML
  2849. files that the content of which (assuming no redirect URL is set) will
  2850. be shown to the user after they attempt to click the link in the email
  2851. sent to them.</p>
  2852. <h1 id="upgrading-to-v0990"><a class="header" href="#upgrading-to-v0990">Upgrading to v0.99.0</a></h1>
  2853. <p>Please be aware that, before Synapse v1.0 is released around March 2019,
  2854. you will need to replace any self-signed certificates with those
  2855. verified by a root CA. Information on how to do so can be found at the
  2856. ACME docs.</p>
  2857. <h1 id="upgrading-to-v0340"><a class="header" href="#upgrading-to-v0340">Upgrading to v0.34.0</a></h1>
  2858. <ol>
  2859. <li>
  2860. <p>This release is the first to fully support Python 3. Synapse will
  2861. now run on Python versions 3.5, or 3.6 (as well as 2.7). We
  2862. recommend switching to Python 3, as it has been shown to give
  2863. performance improvements.</p>
  2864. <p>For users who have installed Synapse into a virtualenv, we recommend
  2865. doing this by creating a new virtualenv. For example:</p>
  2866. <pre><code class="language-sh">virtualenv -p python3 ~/synapse/env3
  2867. source ~/synapse/env3/bin/activate
  2868. pip install matrix-synapse
  2869. </code></pre>
  2870. <p>You can then start synapse as normal, having activated the new
  2871. virtualenv:</p>
  2872. <pre><code class="language-sh">cd ~/synapse
  2873. source env3/bin/activate
  2874. synctl start
  2875. </code></pre>
  2876. <p>Users who have installed from distribution packages should see the
  2877. relevant package documentation. See below for notes on Debian
  2878. packages.</p>
  2879. <ul>
  2880. <li>
  2881. <p>When upgrading to Python 3, you <strong>must</strong> make sure that your log
  2882. files are configured as UTF-8, by adding <code>encoding: utf8</code> to the
  2883. <code>RotatingFileHandler</code> configuration (if you have one) in your
  2884. <code>&lt;server&gt;.log.config</code> file. For example, if your <code>log.config</code>
  2885. file contains:</p>
  2886. <pre><code class="language-yaml">handlers:
  2887. file:
  2888. class: logging.handlers.RotatingFileHandler
  2889. formatter: precise
  2890. filename: homeserver.log
  2891. maxBytes: 104857600
  2892. backupCount: 10
  2893. filters: [context]
  2894. console:
  2895. class: logging.StreamHandler
  2896. formatter: precise
  2897. filters: [context]
  2898. </code></pre>
  2899. <p>Then you should update this to be:</p>
  2900. <pre><code class="language-yaml">handlers:
  2901. file:
  2902. class: logging.handlers.RotatingFileHandler
  2903. formatter: precise
  2904. filename: homeserver.log
  2905. maxBytes: 104857600
  2906. backupCount: 10
  2907. filters: [context]
  2908. encoding: utf8
  2909. console:
  2910. class: logging.StreamHandler
  2911. formatter: precise
  2912. filters: [context]
  2913. </code></pre>
  2914. <p>There is no need to revert this change if downgrading to
  2915. Python 2.</p>
  2916. </li>
  2917. </ul>
  2918. <p>We are also making available Debian packages which will run Synapse
  2919. on Python 3. You can switch to these packages with
  2920. <code>apt-get install matrix-synapse-py3</code>, however, please read
  2921. <a href="https://github.com/matrix-org/synapse/blob/release-v0.34.0/debian/NEWS">debian/NEWS</a>
  2922. before doing so. The existing <code>matrix-synapse</code> packages will
  2923. continue to use Python 2 for the time being.</p>
  2924. </li>
  2925. <li>
  2926. <p>This release removes the <code>riot.im</code> from the default list of trusted
  2927. identity servers.</p>
  2928. <p>If <code>riot.im</code> is in your homeserver's list of
  2929. <code>trusted_third_party_id_servers</code>, you should remove it. It was added
  2930. in case a hypothetical future identity server was put there. If you
  2931. don't remove it, users may be unable to deactivate their accounts.</p>
  2932. </li>
  2933. <li>
  2934. <p>This release no longer installs the (unmaintained) Matrix Console
  2935. web client as part of the default installation. It is possible to
  2936. re-enable it by installing it separately and setting the
  2937. <code>web_client_location</code> config option, but please consider switching
  2938. to another client.</p>
  2939. </li>
  2940. </ol>
  2941. <h1 id="upgrading-to-v0337"><a class="header" href="#upgrading-to-v0337">Upgrading to v0.33.7</a></h1>
  2942. <p>This release removes the example email notification templates from
  2943. <code>res/templates</code> (they are now internal to the python package). This
  2944. should only affect you if you (a) deploy your Synapse instance from a
  2945. git checkout or a github snapshot URL, and (b) have email notifications
  2946. enabled.</p>
  2947. <p>If you have email notifications enabled, you should ensure that
  2948. <code>email.template_dir</code> is either configured to point at a directory where
  2949. you have installed customised templates, or leave it unset to use the
  2950. default templates.</p>
  2951. <h1 id="upgrading-to-v0273"><a class="header" href="#upgrading-to-v0273">Upgrading to v0.27.3</a></h1>
  2952. <p>This release expands the anonymous usage stats sent if the opt-in
  2953. <code>report_stats</code> configuration is set to <code>true</code>. We now capture RSS memory
  2954. and cpu use at a very coarse level. This requires administrators to
  2955. install the optional <code>psutil</code> python module.</p>
  2956. <p>We would appreciate it if you could assist by ensuring this module is
  2957. available and <code>report_stats</code> is enabled. This will let us see if
  2958. performance changes to synapse are having an impact to the general
  2959. community.</p>
  2960. <h1 id="upgrading-to-v0150"><a class="header" href="#upgrading-to-v0150">Upgrading to v0.15.0</a></h1>
  2961. <p>If you want to use the new URL previewing API
  2962. (<code>/_matrix/media/r0/preview_url</code>) then you have to explicitly enable it
  2963. in the config and update your dependencies dependencies. See README.rst
  2964. for details.</p>
  2965. <h1 id="upgrading-to-v0110"><a class="header" href="#upgrading-to-v0110">Upgrading to v0.11.0</a></h1>
  2966. <p>This release includes the option to send anonymous usage stats to
  2967. matrix.org, and requires that administrators explictly opt in or out by
  2968. setting the <code>report_stats</code> option to either <code>true</code> or <code>false</code>.</p>
  2969. <p>We would really appreciate it if you could help our project out by
  2970. reporting anonymized usage statistics from your homeserver. Only very
  2971. basic aggregate data (e.g. number of users) will be reported, but it
  2972. helps us to track the growth of the Matrix community, and helps us to
  2973. make Matrix a success, as well as to convince other networks that they
  2974. should peer with us.</p>
  2975. <h1 id="upgrading-to-v090"><a class="header" href="#upgrading-to-v090">Upgrading to v0.9.0</a></h1>
  2976. <p>Application services have had a breaking API change in this version.</p>
  2977. <p>They can no longer register themselves with a home server using the AS
  2978. HTTP API. This decision was made because a compromised application
  2979. service with free reign to register any regex in effect grants full
  2980. read/write access to the home server if a regex of <code>.*</code> is used. An
  2981. attack where a compromised AS re-registers itself with <code>.*</code> was deemed
  2982. too big of a security risk to ignore, and so the ability to register
  2983. with the HS remotely has been removed.</p>
  2984. <p>It has been replaced by specifying a list of application service
  2985. registrations in <code>homeserver.yaml</code>:</p>
  2986. <pre><code class="language-yaml">app_service_config_files: [&quot;registration-01.yaml&quot;, &quot;registration-02.yaml&quot;]
  2987. </code></pre>
  2988. <p>Where <code>registration-01.yaml</code> looks like:</p>
  2989. <pre><code class="language-yaml">url: &lt;String&gt; # e.g. &quot;https://my.application.service.com&quot;
  2990. as_token: &lt;String&gt;
  2991. hs_token: &lt;String&gt;
  2992. sender_localpart: &lt;String&gt; # This is a new field which denotes the user_id localpart when using the AS token
  2993. namespaces:
  2994. users:
  2995. - exclusive: &lt;Boolean&gt;
  2996. regex: &lt;String&gt; # e.g. &quot;@prefix_.*&quot;
  2997. aliases:
  2998. - exclusive: &lt;Boolean&gt;
  2999. regex: &lt;String&gt;
  3000. rooms:
  3001. - exclusive: &lt;Boolean&gt;
  3002. regex: &lt;String&gt;
  3003. </code></pre>
  3004. <h1 id="upgrading-to-v080"><a class="header" href="#upgrading-to-v080">Upgrading to v0.8.0</a></h1>
  3005. <p>Servers which use captchas will need to add their public key to:</p>
  3006. <pre><code>static/client/register/register_config.js
  3007. window.matrixRegistrationConfig = {
  3008. recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  3009. };
  3010. </code></pre>
  3011. <p>This is required in order to support registration fallback (typically
  3012. used on mobile devices).</p>
  3013. <h1 id="upgrading-to-v070"><a class="header" href="#upgrading-to-v070">Upgrading to v0.7.0</a></h1>
  3014. <p>New dependencies are:</p>
  3015. <ul>
  3016. <li>pydenticon</li>
  3017. <li>simplejson</li>
  3018. <li>syutil</li>
  3019. <li>matrix-angular-sdk</li>
  3020. </ul>
  3021. <p>To pull in these dependencies in a virtual env, run:</p>
  3022. <pre><code>python synapse/python_dependencies.py | xargs -n 1 pip install
  3023. </code></pre>
  3024. <h1 id="upgrading-to-v060"><a class="header" href="#upgrading-to-v060">Upgrading to v0.6.0</a></h1>
  3025. <p>To pull in new dependencies, run:</p>
  3026. <pre><code>python setup.py develop --user
  3027. </code></pre>
  3028. <p>This update includes a change to the database schema. To upgrade you
  3029. first need to upgrade the database by running:</p>
  3030. <pre><code>python scripts/upgrade_db_to_v0.6.0.py &lt;db&gt; &lt;server_name&gt; &lt;signing_key&gt;
  3031. </code></pre>
  3032. <p>Where <code>&lt;db&gt;</code> is the location of the database,
  3033. <code>&lt;server_name&gt;</code> is the server name as specified in the
  3034. synapse configuration, and <code>&lt;signing_key&gt;</code> is the location
  3035. of the signing key as specified in the synapse configuration.</p>
  3036. <p>This may take some time to complete. Failures of signatures and content
  3037. hashes can safely be ignored.</p>
  3038. <h1 id="upgrading-to-v051"><a class="header" href="#upgrading-to-v051">Upgrading to v0.5.1</a></h1>
  3039. <p>Depending on precisely when you installed v0.5.0 you may have ended up
  3040. with a stale release of the reference matrix webclient installed as a
  3041. python module. To uninstall it and ensure you are depending on the
  3042. latest module, please run:</p>
  3043. <pre><code>$ pip uninstall syweb
  3044. </code></pre>
  3045. <h1 id="upgrading-to-v050"><a class="header" href="#upgrading-to-v050">Upgrading to v0.5.0</a></h1>
  3046. <p>The webclient has been split out into a seperate repository/pacakage in
  3047. this release. Before you restart your homeserver you will need to pull
  3048. in the webclient package by running:</p>
  3049. <pre><code>python setup.py develop --user
  3050. </code></pre>
  3051. <p>This release completely changes the database schema and so requires
  3052. upgrading it before starting the new version of the homeserver.</p>
  3053. <p>The script &quot;database-prepare-for-0.5.0.sh&quot; should be used to upgrade
  3054. the database. This will save all user information, such as logins and
  3055. profiles, but will otherwise purge the database. This includes messages,
  3056. which rooms the home server was a member of and room alias mappings.</p>
  3057. <p>If you would like to keep your history, please take a copy of your
  3058. database file and ask for help in #matrix:matrix.org. The upgrade
  3059. process is, unfortunately, non trivial and requires human intervention
  3060. to resolve any resulting conflicts during the upgrade process.</p>
  3061. <p>Before running the command the homeserver should be first completely
  3062. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  3063. <blockquote>
  3064. <p>./scripts/database-prepare-for-0.5.0.sh &quot;homeserver.db&quot;</p>
  3065. </blockquote>
  3066. <p>Once this has successfully completed it will be safe to restart the
  3067. homeserver. You may notice that the homeserver takes a few seconds
  3068. longer to restart than usual as it reinitializes the database.</p>
  3069. <p>On startup of the new version, users can either rejoin remote rooms
  3070. using room aliases or by being reinvited. Alternatively, if any other
  3071. homeserver sends a message to a room that the homeserver was previously
  3072. in the local HS will automatically rejoin the room.</p>
  3073. <h1 id="upgrading-to-v040"><a class="header" href="#upgrading-to-v040">Upgrading to v0.4.0</a></h1>
  3074. <p>This release needs an updated syutil version. Run:</p>
  3075. <pre><code>python setup.py develop
  3076. </code></pre>
  3077. <p>You will also need to upgrade your configuration as the signing key
  3078. format has changed. Run:</p>
  3079. <pre><code>python -m synapse.app.homeserver --config-path &lt;CONFIG&gt; --generate-config
  3080. </code></pre>
  3081. <h1 id="upgrading-to-v030"><a class="header" href="#upgrading-to-v030">Upgrading to v0.3.0</a></h1>
  3082. <p>This registration API now closely matches the login API. This introduces
  3083. a bit more backwards and forwards between the HS and the client, but
  3084. this improves the overall flexibility of the API. You can now GET on
  3085. /register to retrieve a list of valid registration flows. Upon choosing
  3086. one, they are submitted in the same way as login, e.g:</p>
  3087. <pre><code>{
  3088. type: m.login.password,
  3089. user: foo,
  3090. password: bar
  3091. }
  3092. </code></pre>
  3093. <p>The default HS supports 2 flows, with and without Identity Server email
  3094. authentication. Enabling captcha on the HS will add in an extra step to
  3095. all flows: <code>m.login.recaptcha</code> which must be completed before you can
  3096. transition to the next stage. There is a new login type:
  3097. <code>m.login.email.identity</code> which contains the <code>threepidCreds</code> key which
  3098. were previously sent in the original register request. For more
  3099. information on this, see the specification.</p>
  3100. <h2 id="web-client"><a class="header" href="#web-client">Web Client</a></h2>
  3101. <p>The VoIP specification has changed between v0.2.0 and v0.3.0. Users
  3102. should refresh any browser tabs to get the latest web client code. Users
  3103. on v0.2.0 of the web client will not be able to call those on v0.3.0 and
  3104. vice versa.</p>
  3105. <h1 id="upgrading-to-v020"><a class="header" href="#upgrading-to-v020">Upgrading to v0.2.0</a></h1>
  3106. <p>The home server now requires setting up of SSL config before it can run.
  3107. To automatically generate default config use:</p>
  3108. <pre><code>$ python synapse/app/homeserver.py \
  3109. --server-name machine.my.domain.name \
  3110. --bind-port 8448 \
  3111. --config-path homeserver.config \
  3112. --generate-config
  3113. </code></pre>
  3114. <p>This config can be edited if desired, for example to specify a different
  3115. SSL certificate to use. Once done you can run the home server using:</p>
  3116. <pre><code>$ python synapse/app/homeserver.py --config-path homeserver.config
  3117. </code></pre>
  3118. <p>See the README.rst for more information.</p>
  3119. <p>Also note that some config options have been renamed, including:</p>
  3120. <ul>
  3121. <li>&quot;host&quot; to &quot;server-name&quot;</li>
  3122. <li>&quot;database&quot; to &quot;database-path&quot;</li>
  3123. <li>&quot;port&quot; to &quot;bind-port&quot; and &quot;unsecure-port&quot;</li>
  3124. </ul>
  3125. <h1 id="upgrading-to-v001"><a class="header" href="#upgrading-to-v001">Upgrading to v0.0.1</a></h1>
  3126. <p>This release completely changes the database schema and so requires
  3127. upgrading it before starting the new version of the homeserver.</p>
  3128. <p>The script &quot;database-prepare-for-0.0.1.sh&quot; should be used to upgrade
  3129. the database. This will save all user information, such as logins and
  3130. profiles, but will otherwise purge the database. This includes messages,
  3131. which rooms the home server was a member of and room alias mappings.</p>
  3132. <p>Before running the command the homeserver should be first completely
  3133. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  3134. <blockquote>
  3135. <p>./scripts/database-prepare-for-0.0.1.sh &quot;homeserver.db&quot;</p>
  3136. </blockquote>
  3137. <p>Once this has successfully completed it will be safe to restart the
  3138. homeserver. You may notice that the homeserver takes a few seconds
  3139. longer to restart than usual as it reinitializes the database.</p>
  3140. <p>On startup of the new version, users can either rejoin remote rooms
  3141. using room aliases or by being reinvited. Alternatively, if any other
  3142. homeserver sends a message to a room that the homeserver was previously
  3143. in the local HS will automatically rejoin the room.</p>
  3144. <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>
  3145. <p>Federation is the process by which users on different servers can participate
  3146. in the same room. For this to work, those other servers must be able to contact
  3147. yours to send messages.</p>
  3148. <p>The <code>server_name</code> configured in the Synapse configuration file (often
  3149. <code>homeserver.yaml</code>) defines how resources (users, rooms, etc.) will be
  3150. identified (eg: <code>@user:example.com</code>, <code>#room:example.com</code>). By default,
  3151. it is also the domain that other servers will use to try to reach your
  3152. server (via port 8448). This is easy to set up and will work provided
  3153. you set the <code>server_name</code> to match your machine's public DNS hostname.</p>
  3154. <p>For this default configuration to work, you will need to listen for TLS
  3155. connections on port 8448. The preferred way to do that is by using a
  3156. reverse proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions
  3157. on how to correctly set one up.</p>
  3158. <p>In some cases you might not want to run Synapse on the machine that has
  3159. the <code>server_name</code> as its public DNS hostname, or you might want federation
  3160. traffic to use a different port than 8448. For example, you might want to
  3161. have your user names look like <code>@user:example.com</code>, but you want to run
  3162. Synapse on <code>synapse.example.com</code> on port 443. This can be done using
  3163. delegation, which allows an admin to control where federation traffic should
  3164. be sent. See <a href="delegate.html">the delegation documentation</a> for instructions on how to set this up.</p>
  3165. <p>Once federation has been configured, you should be able to join a room over
  3166. federation. A good place to start is <code>#synapse:matrix.org</code> - a room for
  3167. Synapse admins.</p>
  3168. <h2 id="troubleshooting-3"><a class="header" href="#troubleshooting-3">Troubleshooting</a></h2>
  3169. <p>You can use the <a href="https://matrix.org/federationtester">federation tester</a>
  3170. to check if your homeserver is configured correctly. Alternatively try the
  3171. <a href="https://matrix.org/federationtester/api/report?server_name=DOMAIN">JSON API used by the federation tester</a>.
  3172. Note that you'll have to modify this URL to replace <code>DOMAIN</code> with your
  3173. <code>server_name</code>. Hitting the API directly provides extra detail.</p>
  3174. <p>The typical failure mode for federation is that when the server tries to join
  3175. a room, it is rejected with &quot;401: Unauthorized&quot;. Generally this means that other
  3176. servers in the room could not access yours. (Joining a room over federation is
  3177. a complicated dance which requires connections in both directions).</p>
  3178. <p>Another common problem is that people on other servers can't join rooms that
  3179. you invite them to. This can be caused by an incorrectly-configured reverse
  3180. proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions on how
  3181. to correctly configure a reverse proxy.</p>
  3182. <h3 id="known-issues"><a class="header" href="#known-issues">Known issues</a></h3>
  3183. <p><strong>HTTP <code>308 Permanent Redirect</code> redirects are not followed</strong>: Due to missing features
  3184. in the HTTP library used by Synapse, 308 redirects are currently not followed by
  3185. federating servers, which can cause <code>M_UNKNOWN</code> or <code>401 Unauthorized</code> errors. This
  3186. may affect users who are redirecting apex-to-www (e.g. <code>example.com</code> -&gt; <code>www.example.com</code>),
  3187. and especially users of the Kubernetes <em>Nginx Ingress</em> module, which uses 308 redirect
  3188. codes by default. For those Kubernetes users, <a href="https://stackoverflow.com/a/52617528/5096871">this Stackoverflow post</a>
  3189. might be helpful. For other users, switching to a <code>301 Moved Permanently</code> code may be
  3190. an option. 308 redirect codes will be supported properly in a future
  3191. release of Synapse.</p>
  3192. <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>
  3193. <p>If you want to get up and running quickly with a trio of homeservers in a
  3194. private federation, there is a script in the <code>demo</code> directory. This is mainly
  3195. useful just for development purposes. See
  3196. <a href="https://matrix-org.github.io/synapse/develop/development/demo.html">demo scripts</a>.</p>
  3197. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuration-1"><a class="header" href="#configuration-1">Configuration</a></h1>
  3198. <p>This section contains information on tweaking Synapse via the various options in the configuration file. A configuration
  3199. file should have been generated when you <a href="usage/configuration/../../setup/installation.html">installed Synapse</a>.</p>
  3200. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuring-synapse"><a class="header" href="#configuring-synapse">Configuring Synapse</a></h1>
  3201. <p>This is intended as a guide to the Synapse configuration. The behavior of a Synapse instance can be modified
  3202. through the many configuration settings documented here — each config option is explained,
  3203. including what the default is, how to change the default and what sort of behaviour the setting governs.
  3204. Also included is an example configuration for each setting. If you don't want to spend a lot of time
  3205. thinking about options, the config as generated sets sensible defaults for all values. Do note however that the
  3206. database defaults to SQLite, which is not recommended for production usage. You can read more on this subject
  3207. <a href="usage/configuration/../../setup/installation.html#using-postgresql">here</a>.</p>
  3208. <h2 id="config-conventions"><a class="header" href="#config-conventions">Config Conventions</a></h2>
  3209. <p>Configuration options that take a time period can be set using a number
  3210. followed by a letter. Letters have the following meanings:</p>
  3211. <ul>
  3212. <li><code>s</code> = second</li>
  3213. <li><code>m</code> = minute</li>
  3214. <li><code>h</code> = hour</li>
  3215. <li><code>d</code> = day</li>
  3216. <li><code>w</code> = week</li>
  3217. <li><code>y</code> = year</li>
  3218. </ul>
  3219. <p>For example, setting <code>redaction_retention_period: 5m</code> would remove redacted
  3220. messages from the database after 5 minutes, rather than 5 months.</p>
  3221. <p>In addition, configuration options referring to size use the following suffixes:</p>
  3222. <ul>
  3223. <li><code>M</code> = MiB, or 1,048,576 bytes</li>
  3224. <li><code>K</code> = KiB, or 1024 bytes</li>
  3225. </ul>
  3226. <p>For example, setting <code>max_avatar_size: 10M</code> means that Synapse will not accept files larger than 10,485,760 bytes
  3227. for a user avatar.</p>
  3228. <h3 id="yaml"><a class="header" href="#yaml">YAML</a></h3>
  3229. <p>The configuration file is a <a href="https://yaml.org/">YAML</a> file, which means that certain syntax rules
  3230. apply if you want your config file to be read properly. A few helpful things to know:</p>
  3231. <ul>
  3232. <li>
  3233. <p><code>#</code> before any option in the config will comment out that setting and either a default (if available) will
  3234. be applied or Synapse will ignore the setting. Thus, in example #1 below, the setting will be read and
  3235. applied, but in example #2 the setting will not be read and a default will be applied.</p>
  3236. <p>Example #1:</p>
  3237. <pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
  3238. </code></pre>
  3239. <p>Example #2:</p>
  3240. <pre><code class="language-yaml">#pid_file: DATADIR/homeserver.pid
  3241. </code></pre>
  3242. </li>
  3243. <li>
  3244. <p>Indentation matters! The indentation before a setting
  3245. will determine whether a given setting is read as part of another
  3246. setting, or considered on its own. Thus, in example #1, the <code>enabled</code> setting
  3247. is read as a sub-option of the <code>presence</code> setting, and will be properly applied.</p>
  3248. <p>However, the lack of indentation before the <code>enabled</code> setting in example #2 means
  3249. that when reading the config, Synapse will consider both <code>presence</code> and <code>enabled</code> as
  3250. different settings. In this case, <code>presence</code> has no value, and thus a default applied, and <code>enabled</code>
  3251. is an option that Synapse doesn't recognize and thus ignores.</p>
  3252. <p>Example #1:</p>
  3253. <pre><code class="language-yaml">presence:
  3254. enabled: false
  3255. </code></pre>
  3256. <p>Example #2:</p>
  3257. <pre><code class="language-yaml">presence:
  3258. enabled: false
  3259. </code></pre>
  3260. <p>In this manual, all top-level settings (ones with no indentation) are identified
  3261. at the beginning of their section (i.e. &quot;### <code>example_setting</code>&quot;) and
  3262. the sub-options, if any, are identified and listed in the body of the section.
  3263. In addition, each setting has an example of its usage, with the proper indentation
  3264. shown.</p>
  3265. </li>
  3266. </ul>
  3267. <h2 id="modules"><a class="header" href="#modules">Modules</a></h2>
  3268. <p>Server admins can expand Synapse's functionality with external modules.</p>
  3269. <p>See <a href="usage/configuration/../../modules/index.html">here</a> for more
  3270. documentation on how to configure or create custom modules for Synapse.</p>
  3271. <hr />
  3272. <h3 id="modules-1"><a class="header" href="#modules-1"><code>modules</code></a></h3>
  3273. <p>Use the <code>module</code> sub-option to add modules under this option to extend functionality.
  3274. The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
  3275. for the <code>module</code>.</p>
  3276. <p>Defaults to none.</p>
  3277. <p>Example configuration:</p>
  3278. <pre><code class="language-yaml">modules:
  3279. - module: my_super_module.MySuperClass
  3280. config:
  3281. do_thing: true
  3282. - module: my_other_super_module.SomeClass
  3283. config: {}
  3284. </code></pre>
  3285. <hr />
  3286. <h2 id="server"><a class="header" href="#server">Server</a></h2>
  3287. <p>Define your homeserver name and other base options.</p>
  3288. <hr />
  3289. <h3 id="server_name"><a class="header" href="#server_name"><code>server_name</code></a></h3>
  3290. <p>This sets the public-facing domain of the server.</p>
  3291. <p>The <code>server_name</code> name will appear at the end of usernames and room addresses
  3292. created on your server. For example if the <code>server_name</code> was example.com,
  3293. usernames on your server would be in the format <code>@user:example.com</code></p>
  3294. <p>In most cases you should avoid using a matrix specific subdomain such as
  3295. matrix.example.com or synapse.example.com as the <code>server_name</code> for the same
  3296. reasons you wouldn't use user@email.example.com as your email address.
  3297. See <a href="usage/configuration/../../delegate.html">here</a>
  3298. for information on how to host Synapse on a subdomain while preserving
  3299. a clean <code>server_name</code>.</p>
  3300. <p>The <code>server_name</code> cannot be changed later so it is important to
  3301. configure this correctly before you start Synapse. It should be all
  3302. lowercase and may contain an explicit port.</p>
  3303. <p>There is no default for this option.</p>
  3304. <p>Example configuration #1:</p>
  3305. <pre><code class="language-yaml">server_name: matrix.org
  3306. </code></pre>
  3307. <p>Example configuration #2:</p>
  3308. <pre><code class="language-yaml">server_name: localhost:8080
  3309. </code></pre>
  3310. <hr />
  3311. <h3 id="pid_file"><a class="header" href="#pid_file"><code>pid_file</code></a></h3>
  3312. <p>When running Synapse as a daemon, the file to store the pid in. Defaults to none.</p>
  3313. <p>Example configuration:</p>
  3314. <pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
  3315. </code></pre>
  3316. <hr />
  3317. <h3 id="web_client_location"><a class="header" href="#web_client_location"><code>web_client_location</code></a></h3>
  3318. <p>The absolute URL to the web client which <code>/</code> will redirect to. Defaults to none.</p>
  3319. <p>Example configuration:</p>
  3320. <pre><code class="language-yaml">web_client_location: https://riot.example.com/
  3321. </code></pre>
  3322. <hr />
  3323. <h3 id="public_baseurl"><a class="header" href="#public_baseurl"><code>public_baseurl</code></a></h3>
  3324. <p>The public-facing base URL that clients use to access this Homeserver (not
  3325. including _matrix/...). This is the same URL a user might enter into the
  3326. 'Custom Homeserver URL' field on their client. If you use Synapse with a
  3327. reverse proxy, this should be the URL to reach Synapse via the proxy.
  3328. Otherwise, it should be the URL to reach Synapse's client HTTP listener (see
  3329. 'listeners' below).</p>
  3330. <p>Defaults to <code>https://&lt;server_name&gt;/</code>.</p>
  3331. <p>Example configuration:</p>
  3332. <pre><code class="language-yaml">public_baseurl: https://example.com/
  3333. </code></pre>
  3334. <hr />
  3335. <h3 id="serve_server_wellknown"><a class="header" href="#serve_server_wellknown"><code>serve_server_wellknown</code></a></h3>
  3336. <p>By default, other servers will try to reach our server on port 8448, which can
  3337. be inconvenient in some environments.</p>
  3338. <p>Provided <code>https://&lt;server_name&gt;/</code> on port 443 is routed to Synapse, this
  3339. option configures Synapse to serve a file at <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>.
  3340. This will tell other servers to send traffic to port 443 instead.</p>
  3341. <p>This option currently defaults to false.</p>
  3342. <p>See <a href="usage/configuration/../../delegate.html">Delegation of incoming federation traffic</a> for more
  3343. information.</p>
  3344. <p>Example configuration:</p>
  3345. <pre><code class="language-yaml">serve_server_wellknown: true
  3346. </code></pre>
  3347. <hr />
  3348. <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>
  3349. <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>.
  3350. 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>
  3351. <p>If this option is provided, it parses the given yaml to json and
  3352. serves it on <code>/.well-known/matrix/client</code> endpoint
  3353. alongside the standard properties.</p>
  3354. <p><em>Added in Synapse 1.62.0.</em></p>
  3355. <p>Example configuration:</p>
  3356. <pre><code class="language-yaml">extra_well_known_client_content :
  3357. option1: value1
  3358. option2: value2
  3359. </code></pre>
  3360. <hr />
  3361. <h3 id="soft_file_limit"><a class="header" href="#soft_file_limit"><code>soft_file_limit</code></a></h3>
  3362. <p>Set the soft limit on the number of file descriptors synapse can use.
  3363. Zero is used to indicate synapse should set the soft limit to the hard limit.
  3364. Defaults to 0.</p>
  3365. <p>Example configuration:</p>
  3366. <pre><code class="language-yaml">soft_file_limit: 3
  3367. </code></pre>
  3368. <hr />
  3369. <h3 id="presence"><a class="header" href="#presence"><code>presence</code></a></h3>
  3370. <p>Presence tracking allows users to see the state (e.g online/offline)
  3371. of other local and remote users. Set the <code>enabled</code> sub-option to false to
  3372. disable presence tracking on this homeserver. Defaults to true.
  3373. This option replaces the previous top-level 'use_presence' option.</p>
  3374. <p>Example configuration:</p>
  3375. <pre><code class="language-yaml">presence:
  3376. enabled: false
  3377. </code></pre>
  3378. <hr />
  3379. <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>
  3380. <p>Whether to require authentication to retrieve profile data (avatars, display names) of other
  3381. users through the client API. Defaults to false. Note that profile data is also available
  3382. via the federation API, unless <code>allow_profile_lookup_over_federation</code> is set to false.</p>
  3383. <p>Example configuration:</p>
  3384. <pre><code class="language-yaml">require_auth_for_profile_requests: true
  3385. </code></pre>
  3386. <hr />
  3387. <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>
  3388. <p>Use this option to require a user to share a room with another user in order
  3389. to retrieve their profile information. Only checked on Client-Server
  3390. requests. Profile requests from other servers should be checked by the
  3391. requesting server. Defaults to false.</p>
  3392. <p>Example configuration:</p>
  3393. <pre><code class="language-yaml">limit_profile_requests_to_users_who_share_rooms: true
  3394. </code></pre>
  3395. <hr />
  3396. <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>
  3397. <p>Use this option to prevent a user's profile data from being retrieved and
  3398. displayed in a room until they have joined it. By default, a user's
  3399. profile data is included in an invite event, regardless of the values
  3400. of the above two settings, and whether or not the users share a server.
  3401. Defaults to true.</p>
  3402. <p>Example configuration:</p>
  3403. <pre><code class="language-yaml">include_profile_data_on_invite: false
  3404. </code></pre>
  3405. <hr />
  3406. <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>
  3407. <p>If set to true, removes the need for authentication to access the server's
  3408. public rooms directory through the client API, meaning that anyone can
  3409. query the room directory. Defaults to false.</p>
  3410. <p>Example configuration:</p>
  3411. <pre><code class="language-yaml">allow_public_rooms_without_auth: true
  3412. </code></pre>
  3413. <hr />
  3414. <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>
  3415. <p>If set to true, allows any other homeserver to fetch the server's public
  3416. rooms directory via federation. Defaults to false.</p>
  3417. <p>Example configuration:</p>
  3418. <pre><code class="language-yaml">allow_public_rooms_over_federation: true
  3419. </code></pre>
  3420. <hr />
  3421. <h3 id="default_room_version"><a class="header" href="#default_room_version"><code>default_room_version</code></a></h3>
  3422. <p>The default room version for newly created rooms on this server.</p>
  3423. <p>Known room versions are listed <a href="https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions">here</a></p>
  3424. <p>For example, for room version 1, <code>default_room_version</code> should be set
  3425. to &quot;1&quot;.</p>
  3426. <p>Currently defaults to &quot;9&quot;.</p>
  3427. <p>Example configuration:</p>
  3428. <pre><code class="language-yaml">default_room_version: &quot;8&quot;
  3429. </code></pre>
  3430. <hr />
  3431. <h3 id="gc_thresholds"><a class="header" href="#gc_thresholds"><code>gc_thresholds</code></a></h3>
  3432. <p>The garbage collection threshold parameters to pass to <code>gc.set_threshold</code>, if defined.
  3433. Defaults to none.</p>
  3434. <p>Example configuration:</p>
  3435. <pre><code class="language-yaml">gc_thresholds: [700, 10, 10]
  3436. </code></pre>
  3437. <hr />
  3438. <h3 id="gc_min_interval"><a class="header" href="#gc_min_interval"><code>gc_min_interval</code></a></h3>
  3439. <p>The minimum time in seconds between each GC for a generation, regardless of
  3440. the GC thresholds. This ensures that we don't do GC too frequently. A value of <code>[1s, 10s, 30s]</code>
  3441. indicates that a second must pass between consecutive generation 0 GCs, etc.</p>
  3442. <p>Defaults to <code>[1s, 10s, 30s]</code>.</p>
  3443. <p>Example configuration:</p>
  3444. <pre><code class="language-yaml">gc_min_interval: [0.5s, 30s, 1m]
  3445. </code></pre>
  3446. <hr />
  3447. <h3 id="filter_timeline_limit"><a class="header" href="#filter_timeline_limit"><code>filter_timeline_limit</code></a></h3>
  3448. <p>Set the limit on the returned events in the timeline in the get
  3449. and sync operations. Defaults to 100. A value of -1 means no upper limit.</p>
  3450. <p>Example configuration:</p>
  3451. <pre><code class="language-yaml">filter_timeline_limit: 5000
  3452. </code></pre>
  3453. <hr />
  3454. <h3 id="block_non_admin_invites"><a class="header" href="#block_non_admin_invites"><code>block_non_admin_invites</code></a></h3>
  3455. <p>Whether room invites to users on this server should be blocked
  3456. (except those sent by local server admins). Defaults to false.</p>
  3457. <p>Example configuration:</p>
  3458. <pre><code class="language-yaml">block_non_admin_invites: true
  3459. </code></pre>
  3460. <hr />
  3461. <h3 id="enable_search"><a class="header" href="#enable_search"><code>enable_search</code></a></h3>
  3462. <p>If set to false, new messages will not be indexed for searching and users
  3463. will receive errors when searching for messages. Defaults to true.</p>
  3464. <p>Example configuration:</p>
  3465. <pre><code class="language-yaml">enable_search: false
  3466. </code></pre>
  3467. <hr />
  3468. <h3 id="ip_range_blacklist"><a class="header" href="#ip_range_blacklist"><code>ip_range_blacklist</code></a></h3>
  3469. <p>This option prevents outgoing requests from being sent to the specified blacklisted IP address
  3470. CIDR ranges. If this option is not specified then it defaults to private IP
  3471. address ranges (see the example below).</p>
  3472. <p>The blacklist applies to the outbound requests for federation, identity servers,
  3473. push servers, and for checking key validity for third-party invite events.</p>
  3474. <p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  3475. listed here, since they correspond to unroutable addresses.)</p>
  3476. <p>This option replaces <code>federation_ip_range_blacklist</code> in Synapse v1.25.0.</p>
  3477. <p>Note: The value is ignored when an HTTP proxy is in use.</p>
  3478. <p>Example configuration:</p>
  3479. <pre><code class="language-yaml">ip_range_blacklist:
  3480. - '127.0.0.0/8'
  3481. - '10.0.0.0/8'
  3482. - '172.16.0.0/12'
  3483. - '192.168.0.0/16'
  3484. - '100.64.0.0/10'
  3485. - '192.0.0.0/24'
  3486. - '169.254.0.0/16'
  3487. - '192.88.99.0/24'
  3488. - '198.18.0.0/15'
  3489. - '192.0.2.0/24'
  3490. - '198.51.100.0/24'
  3491. - '203.0.113.0/24'
  3492. - '224.0.0.0/4'
  3493. - '::1/128'
  3494. - 'fe80::/10'
  3495. - 'fc00::/7'
  3496. - '2001:db8::/32'
  3497. - 'ff00::/8'
  3498. - 'fec0::/10'
  3499. </code></pre>
  3500. <hr />
  3501. <h3 id="ip_range_whitelist"><a class="header" href="#ip_range_whitelist"><code>ip_range_whitelist</code></a></h3>
  3502. <p>List of IP address CIDR ranges that should be allowed for federation,
  3503. identity servers, push servers, and for checking key validity for
  3504. third-party invite events. This is useful for specifying exceptions to
  3505. wide-ranging blacklisted target IP ranges - e.g. for communication with
  3506. a push server only visible in your network.</p>
  3507. <p>This whitelist overrides <code>ip_range_blacklist</code> and defaults to an empty
  3508. list.</p>
  3509. <p>Example configuration:</p>
  3510. <pre><code class="language-yaml">ip_range_whitelist:
  3511. - '192.168.1.1'
  3512. </code></pre>
  3513. <hr />
  3514. <h3 id="listeners"><a class="header" href="#listeners"><code>listeners</code></a></h3>
  3515. <p>List of ports that Synapse should listen on, their purpose and their
  3516. configuration.</p>
  3517. <p>Sub-options for each listener include:</p>
  3518. <ul>
  3519. <li>
  3520. <p><code>port</code>: the TCP port to bind to.</p>
  3521. </li>
  3522. <li>
  3523. <p><code>bind_addresses</code>: a list of local addresses to listen on. The default is
  3524. 'all local interfaces'.</p>
  3525. </li>
  3526. <li>
  3527. <p><code>type</code>: the type of listener. Normally <code>http</code>, but other valid options are:</p>
  3528. <ul>
  3529. <li>
  3530. <p><code>manhole</code>: (see the docs <a href="usage/configuration/../../manhole.html">here</a>),</p>
  3531. </li>
  3532. <li>
  3533. <p><code>metrics</code>: (see the docs <a href="usage/configuration/../../metrics-howto.html">here</a>),</p>
  3534. </li>
  3535. </ul>
  3536. </li>
  3537. <li>
  3538. <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>
  3539. </li>
  3540. <li>
  3541. <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
  3542. behind a <a href="usage/configuration/../../reverse_proxy.html">reverse-proxy</a>.</p>
  3543. </li>
  3544. <li>
  3545. <p><code>request_id_header</code>: The header extracted from each incoming request that is
  3546. used as the basis for the request ID. The request ID is used in
  3547. <a href="usage/configuration/../administration/request_log.html#request-log-format">logs</a> and tracing to
  3548. correlate and match up requests. When unset, Synapse will automatically
  3549. generate sequential request IDs. This option is useful when Synapse is behind
  3550. a <a href="usage/configuration/../../reverse_proxy.html">reverse-proxy</a>.</p>
  3551. <p><em>Added in Synapse 1.68.0.</em></p>
  3552. </li>
  3553. <li>
  3554. <p><code>resources</code>: Only valid for an 'http' listener. A list of resources to host
  3555. on this port. Sub-options for each resource are:</p>
  3556. <ul>
  3557. <li>
  3558. <p><code>names</code>: a list of names of HTTP resources. See below for a list of valid resource names.</p>
  3559. </li>
  3560. <li>
  3561. <p><code>compress</code>: set to true to enable gzip compression on HTTP bodies for this resource. This is currently only supported with the
  3562. <code>client</code>, <code>consent</code>, <code>metrics</code> and <code>federation</code> resources.</p>
  3563. </li>
  3564. </ul>
  3565. </li>
  3566. <li>
  3567. <p><code>additional_resources</code>: Only valid for an 'http' listener. A map of
  3568. additional endpoints which should be loaded via dynamic modules.</p>
  3569. </li>
  3570. </ul>
  3571. <p>Valid resource names are:</p>
  3572. <ul>
  3573. <li>
  3574. <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>
  3575. </li>
  3576. <li>
  3577. <p><code>consent</code>: user consent forms (/_matrix/consent). See <a href="usage/configuration/../../consent_tracking.html">here</a> for more.</p>
  3578. </li>
  3579. <li>
  3580. <p><code>federation</code>: the server-server API (/_matrix/federation). Also implies <code>media</code>, <code>keys</code>, <code>openid</code></p>
  3581. </li>
  3582. <li>
  3583. <p><code>keys</code>: the key discovery API (/_matrix/key).</p>
  3584. </li>
  3585. <li>
  3586. <p><code>media</code>: the media API (/_matrix/media).</p>
  3587. </li>
  3588. <li>
  3589. <p><code>metrics</code>: the metrics interface. See <a href="usage/configuration/../../metrics-howto.html">here</a>.</p>
  3590. </li>
  3591. <li>
  3592. <p><code>openid</code>: OpenID authentication. See <a href="usage/configuration/../../openid.html">here</a>.</p>
  3593. </li>
  3594. <li>
  3595. <p><code>replication</code>: the HTTP replication API (/_synapse/replication). See <a href="usage/configuration/../../workers.html">here</a>.</p>
  3596. </li>
  3597. <li>
  3598. <p><code>static</code>: static resources under synapse/static (/_matrix/static). (Mostly useful for 'fallback authentication'.)</p>
  3599. </li>
  3600. </ul>
  3601. <p>Example configuration #1:</p>
  3602. <pre><code class="language-yaml">listeners:
  3603. # TLS-enabled listener: for when matrix traffic is sent directly to synapse.
  3604. #
  3605. # (Note that you will also need to give Synapse a TLS key and certificate: see the TLS section
  3606. # below.)
  3607. #
  3608. - port: 8448
  3609. type: http
  3610. tls: true
  3611. resources:
  3612. - names: [client, federation]
  3613. </code></pre>
  3614. <p>Example configuration #2:</p>
  3615. <pre><code class="language-yaml">listeners:
  3616. # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy
  3617. # that unwraps TLS.
  3618. #
  3619. # If you plan to use a reverse proxy, please see
  3620. # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  3621. #
  3622. - port: 8008
  3623. tls: false
  3624. type: http
  3625. x_forwarded: true
  3626. bind_addresses: ['::1', '127.0.0.1']
  3627. resources:
  3628. - names: [client, federation]
  3629. compress: false
  3630. # example additional_resources:
  3631. additional_resources:
  3632. &quot;/_matrix/my/custom/endpoint&quot;:
  3633. module: my_module.CustomRequestHandler
  3634. config: {}
  3635. # Turn on the twisted ssh manhole service on localhost on the given
  3636. # port.
  3637. - port: 9000
  3638. bind_addresses: ['::1', '127.0.0.1']
  3639. type: manhole
  3640. </code></pre>
  3641. <hr />
  3642. <h3 id="manhole_settings"><a class="header" href="#manhole_settings"><code>manhole_settings</code></a></h3>
  3643. <p>Connection settings for the manhole. You can find more information
  3644. on the manhole <a href="usage/configuration/../../manhole.html">here</a>. Manhole sub-options include:</p>
  3645. <ul>
  3646. <li><code>username</code> : the username for the manhole. This defaults to 'matrix'.</li>
  3647. <li><code>password</code>: The password for the manhole. This defaults to 'rabbithole'.</li>
  3648. <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.
  3649. If these are left unset, then hardcoded and non-secret keys are used,
  3650. which could allow traffic to be intercepted if sent over a public network.</li>
  3651. </ul>
  3652. <p>Example configuration:</p>
  3653. <pre><code class="language-yaml">manhole_settings:
  3654. username: manhole
  3655. password: mypassword
  3656. ssh_priv_key_path: CONFDIR/id_rsa
  3657. ssh_pub_key_path: CONFDIR/id_rsa.pub
  3658. </code></pre>
  3659. <hr />
  3660. <h3 id="dummy_events_threshold"><a class="header" href="#dummy_events_threshold"><code>dummy_events_threshold</code></a></h3>
  3661. <p>Forward extremities can build up in a room due to networking delays between
  3662. homeservers. Once this happens in a large room, calculation of the state of
  3663. that room can become quite expensive. To mitigate this, once the number of
  3664. forward extremities reaches a given threshold, Synapse will send an
  3665. <code>org.matrix.dummy_event</code> event, which will reduce the forward extremities
  3666. in the room.</p>
  3667. <p>This setting defines the threshold (i.e. number of forward extremities in the room) at which dummy events are sent.
  3668. The default value is 10.</p>
  3669. <p>Example configuration:</p>
  3670. <pre><code class="language-yaml">dummy_events_threshold: 5
  3671. </code></pre>
  3672. <hr />
  3673. <h3 id="delete_stale_devices_after"><a class="header" href="#delete_stale_devices_after"><code>delete_stale_devices_after</code></a></h3>
  3674. <p>An optional duration. If set, Synapse will run a daily background task to log out and
  3675. delete any device that hasn't been accessed for more than the specified amount of time.</p>
  3676. <p>Defaults to no duration, which means devices are never pruned.</p>
  3677. <p>Example configuration:</p>
  3678. <pre><code class="language-yaml">delete_stale_devices_after: 1y
  3679. </code></pre>
  3680. <h2 id="homeserver-blocking"><a class="header" href="#homeserver-blocking">Homeserver blocking</a></h2>
  3681. <p>Useful options for Synapse admins.</p>
  3682. <hr />
  3683. <h3 id="admin_contact"><a class="header" href="#admin_contact"><code>admin_contact</code></a></h3>
  3684. <p>How to reach the server admin, used in <code>ResourceLimitError</code>. Defaults to none.</p>
  3685. <p>Example configuration:</p>
  3686. <pre><code class="language-yaml">admin_contact: 'mailto:admin@server.com'
  3687. </code></pre>
  3688. <hr />
  3689. <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>
  3690. <p>Blocks users from connecting to the homeserver and provides a human-readable reason
  3691. why the connection was blocked. Defaults to false.</p>
  3692. <p>Example configuration:</p>
  3693. <pre><code class="language-yaml">hs_disabled: true
  3694. hs_disabled_message: 'Reason for why the HS is blocked'
  3695. </code></pre>
  3696. <hr />
  3697. <h3 id="limit_usage_by_mau"><a class="header" href="#limit_usage_by_mau"><code>limit_usage_by_mau</code></a></h3>
  3698. <p>This option disables/enables monthly active user blocking. Used in cases where the admin or
  3699. server owner wants to limit to the number of monthly active users. When enabled and a limit is
  3700. reached the server returns a <code>ResourceLimitError</code> with error type <code>Codes.RESOURCE_LIMIT_EXCEEDED</code>.
  3701. Defaults to false. If this is enabled, a value for <code>max_mau_value</code> must also be set.</p>
  3702. <p>See <a href="usage/configuration/../administration/monthly_active_users.html">Monthly Active Users</a> for details on how to configure MAU.</p>
  3703. <p>Example configuration:</p>
  3704. <pre><code class="language-yaml">limit_usage_by_mau: true
  3705. </code></pre>
  3706. <hr />
  3707. <h3 id="max_mau_value"><a class="header" href="#max_mau_value"><code>max_mau_value</code></a></h3>
  3708. <p>This option sets the hard limit of monthly active users above which the server will start
  3709. blocking user actions if <code>limit_usage_by_mau</code> is enabled. Defaults to 0.</p>
  3710. <p>Example configuration:</p>
  3711. <pre><code class="language-yaml">max_mau_value: 50
  3712. </code></pre>
  3713. <hr />
  3714. <h3 id="mau_trial_days"><a class="header" href="#mau_trial_days"><code>mau_trial_days</code></a></h3>
  3715. <p>The option <code>mau_trial_days</code> is a means to add a grace period for active users. It
  3716. means that users must be active for the specified number of days before they
  3717. can be considered active and guards against the case where lots of users
  3718. sign up in a short space of time never to return after their initial
  3719. session. Defaults to 0.</p>
  3720. <p>Example configuration:</p>
  3721. <pre><code class="language-yaml">mau_trial_days: 5
  3722. </code></pre>
  3723. <hr />
  3724. <h3 id="mau_appservice_trial_days"><a class="header" href="#mau_appservice_trial_days"><code>mau_appservice_trial_days</code></a></h3>
  3725. <p>The option <code>mau_appservice_trial_days</code> is similar to <code>mau_trial_days</code>, but applies a different
  3726. trial number if the user was registered by an appservice. A value
  3727. of 0 means no trial days are applied. Appservices not listed in this dictionary
  3728. use the value of <code>mau_trial_days</code> instead.</p>
  3729. <p>Example configuration:</p>
  3730. <pre><code class="language-yaml">mau_appservice_trial_days:
  3731. my_appservice_id: 3
  3732. another_appservice_id: 6
  3733. </code></pre>
  3734. <hr />
  3735. <h3 id="mau_limit_alerting"><a class="header" href="#mau_limit_alerting"><code>mau_limit_alerting</code></a></h3>
  3736. <p>The option <code>mau_limit_alerting</code> is a means of limiting client-side alerting
  3737. should the mau limit be reached. This is useful for small instances
  3738. where the admin has 5 mau seats (say) for 5 specific people and no
  3739. interest increasing the mau limit further. Defaults to true, which
  3740. means that alerting is enabled.</p>
  3741. <p>Example configuration:</p>
  3742. <pre><code class="language-yaml">mau_limit_alerting: false
  3743. </code></pre>
  3744. <hr />
  3745. <h3 id="mau_stats_only"><a class="header" href="#mau_stats_only"><code>mau_stats_only</code></a></h3>
  3746. <p>If enabled, the metrics for the number of monthly active users will
  3747. be populated, however no one will be limited based on these numbers. If <code>limit_usage_by_mau</code>
  3748. is true, this is implied to be true. Defaults to false.</p>
  3749. <p>Example configuration:</p>
  3750. <pre><code class="language-yaml">mau_stats_only: true
  3751. </code></pre>
  3752. <hr />
  3753. <h3 id="mau_limit_reserved_threepids"><a class="header" href="#mau_limit_reserved_threepids"><code>mau_limit_reserved_threepids</code></a></h3>
  3754. <p>Sometimes the server admin will want to ensure certain accounts are
  3755. never blocked by mau checking. These accounts are specified by this option.
  3756. Defaults to none. Add accounts by specifying the <code>medium</code> and <code>address</code> of the
  3757. reserved threepid (3rd party identifier).</p>
  3758. <p>Example configuration:</p>
  3759. <pre><code class="language-yaml">mau_limit_reserved_threepids:
  3760. - medium: 'email'
  3761. address: 'reserved_user@example.com'
  3762. </code></pre>
  3763. <hr />
  3764. <h3 id="server_context"><a class="header" href="#server_context"><code>server_context</code></a></h3>
  3765. <p>This option is used by phonehome stats to group together related servers.
  3766. Defaults to none.</p>
  3767. <p>Example configuration:</p>
  3768. <pre><code class="language-yaml">server_context: context
  3769. </code></pre>
  3770. <hr />
  3771. <h3 id="limit_remote_rooms"><a class="header" href="#limit_remote_rooms"><code>limit_remote_rooms</code></a></h3>
  3772. <p>When this option is enabled, the room &quot;complexity&quot; will be checked before a user
  3773. joins a new remote room. If it is above the complexity limit, the server will
  3774. disallow joining, or will instantly leave. This is useful for homeservers that are
  3775. resource-constrained. Options for this setting include:</p>
  3776. <ul>
  3777. <li><code>enabled</code>: whether this check is enabled. Defaults to false.</li>
  3778. <li><code>complexity</code>: the limit above which rooms cannot be joined. The default is 1.0.</li>
  3779. <li><code>complexity_error</code>: override the error which is returned when the room is too complex with a
  3780. custom message.</li>
  3781. <li><code>admins_can_join</code>: allow server admins to join complex rooms. Default is false.</li>
  3782. </ul>
  3783. <p>Room complexity is an arbitrary measure based on factors such as the number of
  3784. users in the room.</p>
  3785. <p>Example configuration:</p>
  3786. <pre><code class="language-yaml">limit_remote_rooms:
  3787. enabled: true
  3788. complexity: 0.5
  3789. complexity_error: &quot;I can't let you do that, Dave.&quot;
  3790. admins_can_join: true
  3791. </code></pre>
  3792. <hr />
  3793. <h3 id="require_membership_for_aliases"><a class="header" href="#require_membership_for_aliases"><code>require_membership_for_aliases</code></a></h3>
  3794. <p>Whether to require a user to be in the room to add an alias to it.
  3795. Defaults to true.</p>
  3796. <p>Example configuration:</p>
  3797. <pre><code class="language-yaml">require_membership_for_aliases: false
  3798. </code></pre>
  3799. <hr />
  3800. <h3 id="allow_per_room_profiles"><a class="header" href="#allow_per_room_profiles"><code>allow_per_room_profiles</code></a></h3>
  3801. <p>Whether to allow per-room membership profiles through the sending of membership
  3802. events with profile information that differs from the target's global profile.
  3803. Defaults to true.</p>
  3804. <p>Example configuration:</p>
  3805. <pre><code class="language-yaml">allow_per_room_profiles: false
  3806. </code></pre>
  3807. <hr />
  3808. <h3 id="max_avatar_size"><a class="header" href="#max_avatar_size"><code>max_avatar_size</code></a></h3>
  3809. <p>The largest permissible file size in bytes for a user avatar. Defaults to no restriction.
  3810. Use M for MB and K for KB.</p>
  3811. <p>Note that user avatar changes will not work if this is set without using Synapse's media repository.</p>
  3812. <p>Example configuration:</p>
  3813. <pre><code class="language-yaml">max_avatar_size: 10M
  3814. </code></pre>
  3815. <hr />
  3816. <h3 id="allowed_avatar_mimetypes"><a class="header" href="#allowed_avatar_mimetypes"><code>allowed_avatar_mimetypes</code></a></h3>
  3817. <p>The MIME types allowed for user avatars. Defaults to no restriction.</p>
  3818. <p>Note that user avatar changes will not work if this is set without
  3819. using Synapse's media repository.</p>
  3820. <p>Example configuration:</p>
  3821. <pre><code class="language-yaml">allowed_avatar_mimetypes: [&quot;image/png&quot;, &quot;image/jpeg&quot;, &quot;image/gif&quot;]
  3822. </code></pre>
  3823. <hr />
  3824. <h3 id="redaction_retention_period"><a class="header" href="#redaction_retention_period"><code>redaction_retention_period</code></a></h3>
  3825. <p>How long to keep redacted events in unredacted form in the database. After
  3826. this period redacted events get replaced with their redacted form in the DB.</p>
  3827. <p>Synapse will check whether the rentention period has concluded for redacted
  3828. events every 5 minutes. Thus, even if this option is set to <code>0</code>, Synapse may
  3829. still take up to 5 minutes to purge redacted events from the database.</p>
  3830. <p>Defaults to <code>7d</code>. Set to <code>null</code> to disable.</p>
  3831. <p>Example configuration:</p>
  3832. <pre><code class="language-yaml">redaction_retention_period: 28d
  3833. </code></pre>
  3834. <hr />
  3835. <h3 id="user_ips_max_age"><a class="header" href="#user_ips_max_age"><code>user_ips_max_age</code></a></h3>
  3836. <p>How long to track users' last seen time and IPs in the database.</p>
  3837. <p>Defaults to <code>28d</code>. Set to <code>null</code> to disable clearing out of old rows.</p>
  3838. <p>Example configuration:</p>
  3839. <pre><code class="language-yaml">user_ips_max_age: 14d
  3840. </code></pre>
  3841. <hr />
  3842. <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>
  3843. <p>Inhibits the <code>/requestToken</code> endpoints from returning an error that might leak
  3844. information about whether an e-mail address is in use or not on this
  3845. homeserver. Defaults to false.
  3846. Note that for some endpoints the error situation is the e-mail already being
  3847. used, and for others the error is entering the e-mail being unused.
  3848. If this option is enabled, instead of returning an error, these endpoints will
  3849. act as if no error happened and return a fake session ID ('sid') to clients.</p>
  3850. <p>Example configuration:</p>
  3851. <pre><code class="language-yaml">request_token_inhibit_3pid_errors: true
  3852. </code></pre>
  3853. <hr />
  3854. <h3 id="next_link_domain_whitelist"><a class="header" href="#next_link_domain_whitelist"><code>next_link_domain_whitelist</code></a></h3>
  3855. <p>A list of domains that the domain portion of <code>next_link</code> parameters
  3856. must match.</p>
  3857. <p>This parameter is optionally provided by clients while requesting
  3858. validation of an email or phone number, and maps to a link that
  3859. users will be automatically redirected to after validation
  3860. succeeds. Clients can make use this parameter to aid the validation
  3861. process.</p>
  3862. <p>The whitelist is applied whether the homeserver or an identity server is handling validation.</p>
  3863. <p>The default value is no whitelist functionality; all domains are
  3864. allowed. Setting this value to an empty list will instead disallow
  3865. all domains.</p>
  3866. <p>Example configuration:</p>
  3867. <pre><code class="language-yaml">next_link_domain_whitelist: [&quot;matrix.org&quot;]
  3868. </code></pre>
  3869. <hr />
  3870. <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>
  3871. <p>These options define templates to use when generating email or HTML page contents.
  3872. The <code>custom_template_directory</code> determines which directory Synapse will try to
  3873. find template files in to use to generate email or HTML page contents.
  3874. If not set, or a file is not found within the template directory, a default
  3875. template from within the Synapse package will be used.</p>
  3876. <p>See <a href="usage/configuration/../../templates.html">here</a> for more
  3877. information about using custom templates.</p>
  3878. <p>Example configuration:</p>
  3879. <pre><code class="language-yaml">templates:
  3880. custom_template_directory: /path/to/custom/templates/
  3881. </code></pre>
  3882. <hr />
  3883. <h3 id="retention"><a class="header" href="#retention"><code>retention</code></a></h3>
  3884. <p>This option and the associated options determine message retention policy at the
  3885. server level.</p>
  3886. <p>Room admins and mods can define a retention period for their rooms using the
  3887. <code>m.room.retention</code> state event, and server admins can cap this period by setting
  3888. the <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> config options.</p>
  3889. <p>If this feature is enabled, Synapse will regularly look for and purge events
  3890. which are older than the room's maximum retention period. Synapse will also
  3891. filter events received over federation so that events that should have been
  3892. purged are ignored and not stored again.</p>
  3893. <p>The message retention policies feature is disabled by default. Please be advised
  3894. that enabling this feature carries some risk. There are known bugs with the implementation
  3895. which can cause database corruption. Setting retention to delete older history
  3896. is less risky than deleting newer history but in general caution is advised when enabling this
  3897. experimental feature. You can read more about this feature <a href="usage/configuration/../../message_retention_policies.html">here</a>.</p>
  3898. <p>This setting has the following sub-options:</p>
  3899. <ul>
  3900. <li>
  3901. <p><code>default_policy</code>: Default retention policy. If set, Synapse will apply it to rooms that lack the
  3902. 'm.room.retention' state event. This option is further specified by the
  3903. <code>min_lifetime</code> and <code>max_lifetime</code> sub-options associated with it. Note that the
  3904. value of <code>min_lifetime</code> doesn't matter much because Synapse doesn't take it into account yet.</p>
  3905. </li>
  3906. <li>
  3907. <p><code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code>: Retention policy limits. If
  3908. set, and the state of a room contains a <code>m.room.retention</code> event in its state
  3909. which contains a <code>min_lifetime</code> or a <code>max_lifetime</code> that's out of these bounds,
  3910. Synapse will cap the room's policy to these limits when running purge jobs.</p>
  3911. </li>
  3912. <li>
  3913. <p><code>purge_jobs</code> and the associated <code>shortest_max_lifetime</code> and <code>longest_max_lifetime</code> sub-options:
  3914. Server admins can define the settings of the background jobs purging the
  3915. events whose lifetime has expired under the <code>purge_jobs</code> section.</p>
  3916. <p>If no configuration is provided for this option, a single job will be set up to delete
  3917. expired events in every room daily.</p>
  3918. <p>Each job's configuration defines which range of message lifetimes the job
  3919. takes care of. For example, if <code>shortest_max_lifetime</code> is '2d' and
  3920. <code>longest_max_lifetime</code> is '3d', the job will handle purging expired events in
  3921. rooms whose state defines a <code>max_lifetime</code> that's both higher than 2 days, and
  3922. lower than or equal to 3 days. Both the minimum and the maximum value of a
  3923. range are optional, e.g. a job with no <code>shortest_max_lifetime</code> and a
  3924. <code>longest_max_lifetime</code> of '3d' will handle every room with a retention policy
  3925. whose <code>max_lifetime</code> is lower than or equal to three days.</p>
  3926. <p>The rationale for this per-job configuration is that some rooms might have a
  3927. retention policy with a low <code>max_lifetime</code>, where history needs to be purged
  3928. of outdated messages on a more frequent basis than for the rest of the rooms
  3929. (e.g. every 12h), but not want that purge to be performed by a job that's
  3930. iterating over every room it knows, which could be heavy on the server.</p>
  3931. <p>If any purge job is configured, it is strongly recommended to have at least
  3932. a single job with neither <code>shortest_max_lifetime</code> nor <code>longest_max_lifetime</code>
  3933. set, or one job without <code>shortest_max_lifetime</code> and one job without
  3934. <code>longest_max_lifetime</code> set. Otherwise some rooms might be ignored, even if
  3935. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> are set, because capping a
  3936. room's policy to these values is done after the policies are retrieved from
  3937. Synapse's database (which is done using the range specified in a purge job's
  3938. configuration).</p>
  3939. </li>
  3940. </ul>
  3941. <p>Example configuration:</p>
  3942. <pre><code class="language-yaml">retention:
  3943. enabled: true
  3944. default_policy:
  3945. min_lifetime: 1d
  3946. max_lifetime: 1y
  3947. allowed_lifetime_min: 1d
  3948. allowed_lifetime_max: 1y
  3949. purge_jobs:
  3950. - longest_max_lifetime: 3d
  3951. interval: 12h
  3952. - shortest_max_lifetime: 3d
  3953. interval: 1d
  3954. </code></pre>
  3955. <hr />
  3956. <h2 id="tls"><a class="header" href="#tls">TLS</a></h2>
  3957. <p>Options related to TLS.</p>
  3958. <hr />
  3959. <h3 id="tls_certificate_path"><a class="header" href="#tls_certificate_path"><code>tls_certificate_path</code></a></h3>
  3960. <p>This option specifies a PEM-encoded X509 certificate for TLS.
  3961. This certificate, as of Synapse 1.0, will need to be a valid and verifiable
  3962. certificate, signed by a recognised Certificate Authority. Defaults to none.</p>
  3963. <p>Be sure to use a <code>.pem</code> file that includes the full certificate chain including
  3964. any intermediate certificates (for instance, if using certbot, use
  3965. <code>fullchain.pem</code> as your certificate, not <code>cert.pem</code>).</p>
  3966. <p>Example configuration:</p>
  3967. <pre><code class="language-yaml">tls_certificate_path: &quot;CONFDIR/SERVERNAME.tls.crt&quot;
  3968. </code></pre>
  3969. <hr />
  3970. <h3 id="tls_private_key_path"><a class="header" href="#tls_private_key_path"><code>tls_private_key_path</code></a></h3>
  3971. <p>PEM-encoded private key for TLS. Defaults to none.</p>
  3972. <p>Example configuration:</p>
  3973. <pre><code class="language-yaml">tls_private_key_path: &quot;CONFDIR/SERVERNAME.tls.key&quot;
  3974. </code></pre>
  3975. <hr />
  3976. <h3 id="federation_verify_certificates"><a class="header" href="#federation_verify_certificates"><code>federation_verify_certificates</code></a></h3>
  3977. <p>Whether to verify TLS server certificates for outbound federation requests.</p>
  3978. <p>Defaults to true. To disable certificate verification, set the option to false.</p>
  3979. <p>Example configuration:</p>
  3980. <pre><code class="language-yaml">federation_verify_certificates: false
  3981. </code></pre>
  3982. <hr />
  3983. <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>
  3984. <p>The minimum TLS version that will be used for outbound federation requests.</p>
  3985. <p>Defaults to <code>1</code>. Configurable to <code>1</code>, <code>1.1</code>, <code>1.2</code>, or <code>1.3</code>. Note
  3986. that setting this value higher than <code>1.2</code> will prevent federation to most
  3987. of the public Matrix network: only configure it to <code>1.3</code> if you have an
  3988. entirely private federation setup and you can ensure TLS 1.3 support.</p>
  3989. <p>Example configuration:</p>
  3990. <pre><code class="language-yaml">federation_client_minimum_tls_version: 1.2
  3991. </code></pre>
  3992. <hr />
  3993. <h3 id="federation_certificate_verification_whitelist"><a class="header" href="#federation_certificate_verification_whitelist"><code>federation_certificate_verification_whitelist</code></a></h3>
  3994. <p>Skip federation certificate verification on a given whitelist
  3995. of domains.</p>
  3996. <p>This setting should only be used in very specific cases, such as
  3997. federation over Tor hidden services and similar. For private networks
  3998. of homeservers, you likely want to use a private CA instead.</p>
  3999. <p>Only effective if <code>federation_verify_certicates</code> is <code>true</code>.</p>
  4000. <p>Example configuration:</p>
  4001. <pre><code class="language-yaml">federation_certificate_verification_whitelist:
  4002. - lon.example.com
  4003. - &quot;*.domain.com&quot;
  4004. - &quot;*.onion&quot;
  4005. </code></pre>
  4006. <hr />
  4007. <h3 id="federation_custom_ca_list"><a class="header" href="#federation_custom_ca_list"><code>federation_custom_ca_list</code></a></h3>
  4008. <p>List of custom certificate authorities for federation traffic.</p>
  4009. <p>This setting should only normally be used within a private network of
  4010. homeservers.</p>
  4011. <p>Note that this list will replace those that are provided by your
  4012. operating environment. Certificates must be in PEM format.</p>
  4013. <p>Example configuration:</p>
  4014. <pre><code class="language-yaml">federation_custom_ca_list:
  4015. - myCA1.pem
  4016. - myCA2.pem
  4017. - myCA3.pem
  4018. </code></pre>
  4019. <hr />
  4020. <h2 id="federation"><a class="header" href="#federation">Federation</a></h2>
  4021. <p>Options related to federation.</p>
  4022. <hr />
  4023. <h3 id="federation_domain_whitelist"><a class="header" href="#federation_domain_whitelist"><code>federation_domain_whitelist</code></a></h3>
  4024. <p>Restrict federation to the given whitelist of domains.
  4025. N.B. we recommend also firewalling your federation listener to limit
  4026. inbound federation traffic as early as possible, rather than relying
  4027. purely on this application-layer restriction. If not specified, the
  4028. default is to whitelist everything.</p>
  4029. <p>Example configuration:</p>
  4030. <pre><code class="language-yaml">federation_domain_whitelist:
  4031. - lon.example.com
  4032. - nyc.example.com
  4033. - syd.example.com
  4034. </code></pre>
  4035. <hr />
  4036. <h3 id="federation_metrics_domains"><a class="header" href="#federation_metrics_domains"><code>federation_metrics_domains</code></a></h3>
  4037. <p>Report prometheus metrics on the age of PDUs being sent to and received from
  4038. the given domains. This can be used to give an idea of &quot;delay&quot; on inbound
  4039. and outbound federation, though be aware that any delay can be due to problems
  4040. at either end or with the intermediate network.</p>
  4041. <p>By default, no domains are monitored in this way.</p>
  4042. <p>Example configuration:</p>
  4043. <pre><code class="language-yaml">federation_metrics_domains:
  4044. - matrix.org
  4045. - example.com
  4046. </code></pre>
  4047. <hr />
  4048. <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>
  4049. <p>Set to false to disable profile lookup over federation. By default, the
  4050. Federation API allows other homeservers to obtain profile data of any user
  4051. on this homeserver.</p>
  4052. <p>Example configuration:</p>
  4053. <pre><code class="language-yaml">allow_profile_lookup_over_federation: false
  4054. </code></pre>
  4055. <hr />
  4056. <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>
  4057. <p>Set this option to true to allow device display name lookup over federation. By default, the
  4058. Federation API prevents other homeservers from obtaining the display names of any user devices
  4059. on this homeserver.</p>
  4060. <p>Example configuration:</p>
  4061. <pre><code class="language-yaml">allow_device_name_lookup_over_federation: true
  4062. </code></pre>
  4063. <hr />
  4064. <h2 id="caching"><a class="header" href="#caching">Caching</a></h2>
  4065. <p>Options related to caching.</p>
  4066. <hr />
  4067. <h3 id="event_cache_size"><a class="header" href="#event_cache_size"><code>event_cache_size</code></a></h3>
  4068. <p>The number of events to cache in memory. Defaults to 10K. Like other caches,
  4069. this is affected by <code>caches.global_factor</code> (see below).</p>
  4070. <p>Note that this option is not part of the <code>caches</code> section.</p>
  4071. <p>Example configuration:</p>
  4072. <pre><code class="language-yaml">event_cache_size: 15K
  4073. </code></pre>
  4074. <hr />
  4075. <h3 id="caches-and-associated-values"><a class="header" href="#caches-and-associated-values"><code>caches</code> and associated values</a></h3>
  4076. <p>A cache 'factor' is a multiplier that can be applied to each of
  4077. Synapse's caches in order to increase or decrease the maximum
  4078. number of entries that can be stored.</p>
  4079. <p><code>caches</code> can be configured through the following sub-options:</p>
  4080. <ul>
  4081. <li>
  4082. <p><code>global_factor</code>: Controls the global cache factor, which is the default cache factor
  4083. for all caches if a specific factor for that cache is not otherwise
  4084. set.</p>
  4085. <p>This can also be set by the <code>SYNAPSE_CACHE_FACTOR</code> environment
  4086. variable. Setting by environment variable takes priority over
  4087. setting through the config file.</p>
  4088. <p>Defaults to 0.5, which will halve the size of all caches.</p>
  4089. </li>
  4090. <li>
  4091. <p><code>per_cache_factors</code>: A dictionary of cache name to cache factor for that individual
  4092. cache. Overrides the global cache factor for a given cache.</p>
  4093. <p>These can also be set through environment variables comprised
  4094. of <code>SYNAPSE_CACHE_FACTOR_</code> + the name of the cache in capital
  4095. letters and underscores. Setting by environment variable
  4096. takes priority over setting through the config file.
  4097. Ex. <code>SYNAPSE_CACHE_FACTOR_GET_USERS_WHO_SHARE_ROOM_WITH_USER=2.0</code></p>
  4098. <p>Some caches have '*' and other characters that are not
  4099. alphanumeric or underscores. These caches can be named with or
  4100. without the special characters stripped. For example, to specify
  4101. the cache factor for <code>*stateGroupCache*</code> via an environment
  4102. variable would be <code>SYNAPSE_CACHE_FACTOR_STATEGROUPCACHE=2.0</code>.</p>
  4103. </li>
  4104. <li>
  4105. <p><code>expire_caches</code>: Controls whether cache entries are evicted after a specified time
  4106. period. Defaults to true. Set to false to disable this feature. Note that never expiring
  4107. caches may result in excessive memory usage.</p>
  4108. </li>
  4109. <li>
  4110. <p><code>cache_entry_ttl</code>: If <code>expire_caches</code> is enabled, this flag controls how long an entry can
  4111. be in a cache without having been accessed before being evicted.
  4112. Defaults to 30m.</p>
  4113. </li>
  4114. <li>
  4115. <p><code>sync_response_cache_duration</code>: Controls how long the results of a /sync request are
  4116. cached for after a successful response is returned. A higher duration can help clients
  4117. with intermittent connections, at the cost of higher memory usage.
  4118. A value of zero means that sync responses are not cached.
  4119. Defaults to 2m.</p>
  4120. <p><em>Changed in Synapse 1.62.0</em>: The default was changed from 0 to 2m.</p>
  4121. </li>
  4122. <li>
  4123. <p><code>cache_autotuning</code> and its sub-options <code>max_cache_memory_usage</code>, <code>target_cache_memory_usage</code>, and
  4124. <code>min_cache_ttl</code> work in conjunction with each other to maintain a balance between cache memory
  4125. usage and cache entry availability. You must be using <a href="https://github.com/matrix-org/synapse#help-synapse-is-slow-and-eats-all-my-ramcpu">jemalloc</a>
  4126. to utilize this option, and all three of the options must be specified for this feature to work. This option
  4127. defaults to off, enable it by providing values for the sub-options listed below. Please note that the feature will not work
  4128. and may cause unstable behavior (such as excessive emptying of caches or exceptions) if all of the values are not provided.
  4129. 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
  4130. durations.</p>
  4131. <ul>
  4132. <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.
  4133. They will continue to be evicted until the memory usage drops below the <code>target_memory_usage</code>, set in
  4134. the setting below, or until the <code>min_cache_ttl</code> is hit. There is no default value for this option.</li>
  4135. <li><code>target_memory_usage</code> sets a rough target for the desired memory usage of the caches. There is no default value
  4136. for this option.</li>
  4137. <li><code>min_cache_ttl</code> sets a limit under which newer cache entries are not evicted and is only applied when
  4138. caches are actively being evicted/<code>max_cache_memory_usage</code> has been exceeded. This is to protect hot caches
  4139. from being emptied while Synapse is evicting due to memory. There is no default value for this option.</li>
  4140. </ul>
  4141. </li>
  4142. </ul>
  4143. <p>Example configuration:</p>
  4144. <pre><code class="language-yaml">event_cache_size: 15K
  4145. caches:
  4146. global_factor: 1.0
  4147. per_cache_factors:
  4148. get_users_who_share_room_with_user: 2.0
  4149. sync_response_cache_duration: 2m
  4150. cache_autotuning:
  4151. max_cache_memory_usage: 1024M
  4152. target_cache_memory_usage: 758M
  4153. min_cache_ttl: 5m
  4154. </code></pre>
  4155. <h3 id="reloading-cache-factors"><a class="header" href="#reloading-cache-factors">Reloading cache factors</a></h3>
  4156. <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
  4157. <a href="https://en.wikipedia.org/wiki/SIGHUP"><code>SIGHUP</code></a> signal to Synapse using e.g.</p>
  4158. <pre><code class="language-commandline">kill -HUP [PID_OF_SYNAPSE_PROCESS]
  4159. </code></pre>
  4160. <p>If you are running multiple workers, you must individually update the worker
  4161. config file and send this signal to each worker process.</p>
  4162. <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>
  4163. file in Synapse's <code>contrib</code> directory, you can send a <code>SIGHUP</code> signal by using
  4164. <code>systemctl reload matrix-synapse</code>.</p>
  4165. <hr />
  4166. <h2 id="database"><a class="header" href="#database">Database</a></h2>
  4167. <p>Config options related to database settings.</p>
  4168. <hr />
  4169. <h3 id="database-1"><a class="header" href="#database-1"><code>database</code></a></h3>
  4170. <p>The <code>database</code> setting defines the database that synapse uses to store all of
  4171. its data.</p>
  4172. <p>Associated sub-options:</p>
  4173. <ul>
  4174. <li>
  4175. <p><code>name</code>: this option specifies the database engine to use: either <code>sqlite3</code> (for SQLite)
  4176. or <code>psycopg2</code> (for PostgreSQL). If no name is specified Synapse will default to SQLite.</p>
  4177. </li>
  4178. <li>
  4179. <p><code>txn_limit</code> gives the maximum number of transactions to run per connection
  4180. before reconnecting. Defaults to 0, which means no limit.</p>
  4181. </li>
  4182. <li>
  4183. <p><code>allow_unsafe_locale</code> is an option specific to Postgres. Under the default behavior, Synapse will refuse to
  4184. start if the postgres db is set to a non-C locale. You can override this behavior (which is <em>not</em> recommended)
  4185. by setting <code>allow_unsafe_locale</code> to true. Note that doing so may corrupt your database. You can find more information
  4186. <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>
  4187. </li>
  4188. <li>
  4189. <p><code>args</code> gives options which are passed through to the database engine,
  4190. except for options starting with <code>cp_</code>, which are used to configure the Twisted
  4191. connection pool. For a reference to valid arguments, see:</p>
  4192. <ul>
  4193. <li>for <a href="https://docs.python.org/3/library/sqlite3.html#sqlite3.connect">sqlite</a></li>
  4194. <li>for <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">postgres</a></li>
  4195. <li>for <a href="https://twistedmatrix.com/documents/current/api/twisted.enterprise.adbapi.ConnectionPool.html#__init__">the connection pool</a></li>
  4196. </ul>
  4197. </li>
  4198. </ul>
  4199. <p>For more information on using Synapse with Postgres,
  4200. see <a href="usage/configuration/../../postgres.html">here</a>.</p>
  4201. <p>Example SQLite configuration:</p>
  4202. <pre><code class="language-yaml">database:
  4203. name: sqlite3
  4204. args:
  4205. database: /path/to/homeserver.db
  4206. </code></pre>
  4207. <p>Example Postgres configuration:</p>
  4208. <pre><code class="language-yaml">database:
  4209. name: psycopg2
  4210. txn_limit: 10000
  4211. args:
  4212. user: synapse_user
  4213. password: secretpassword
  4214. database: synapse
  4215. host: localhost
  4216. port: 5432
  4217. cp_min: 5
  4218. cp_max: 10
  4219. </code></pre>
  4220. <hr />
  4221. <h3 id="databases"><a class="header" href="#databases"><code>databases</code></a></h3>
  4222. <p>The <code>databases</code> option allows specifying a mapping between certain database tables and
  4223. database host details, spreading the load of a single Synapse instance across multiple
  4224. database backends. This is often referred to as &quot;database sharding&quot;. This option is only
  4225. supported for PostgreSQL database backends.</p>
  4226. <p><strong>Important note:</strong> This is a supported option, but is not currently used in production by the
  4227. Matrix.org Foundation. Proceed with caution and always make backups.</p>
  4228. <p><code>databases</code> is a dictionary of arbitrarily-named database entries. Each entry is equivalent
  4229. to the value of the <code>database</code> homeserver config option (see above), with the addition of
  4230. a <code>data_stores</code> key. <code>data_stores</code> is an array of strings that specifies the data store(s)
  4231. (a defined label for a set of tables) that should be stored on the associated database
  4232. backend entry.</p>
  4233. <p>The currently defined values for <code>data_stores</code> are:</p>
  4234. <ul>
  4235. <li>
  4236. <p><code>&quot;state&quot;</code>: Database that relates to state groups will be stored in this database.</p>
  4237. <p>Specifically, that means the following tables:</p>
  4238. <ul>
  4239. <li><code>state_groups</code></li>
  4240. <li><code>state_group_edges</code></li>
  4241. <li><code>state_groups_state</code></li>
  4242. </ul>
  4243. <p>And the following sequences:</p>
  4244. <ul>
  4245. <li><code>state_groups_seq_id</code></li>
  4246. </ul>
  4247. </li>
  4248. <li>
  4249. <p><code>&quot;main&quot;</code>: All other database tables and sequences.</p>
  4250. </li>
  4251. </ul>
  4252. <p>All databases will end up with additional tables used for tracking database schema migrations
  4253. and any pending background updates. Synapse will create these automatically on startup when checking for
  4254. and/or performing database schema migrations.</p>
  4255. <p>To migrate an existing database configuration (e.g. all tables on a single database) to a different
  4256. configuration (e.g. the &quot;main&quot; data store on one database, and &quot;state&quot; on another), do the following:</p>
  4257. <ol>
  4258. <li>
  4259. <p>Take a backup of your existing database. Things can and do go wrong and database corruption is no joke!</p>
  4260. </li>
  4261. <li>
  4262. <p>Ensure all pending database migrations have been applied and background updates have run. The simplest
  4263. way to do this is to use the <code>update_synapse_database</code> script supplied with your Synapse installation.</p>
  4264. <pre><code class="language-sh">update_synapse_database --database-config homeserver.yaml --run-background-updates
  4265. </code></pre>
  4266. </li>
  4267. <li>
  4268. <p>Copy over the necessary tables and sequences from one database to the other. Tables relating to database
  4269. migrations, schemas, schema versions and background updates should <strong>not</strong> be copied.</p>
  4270. <p>As an example, say that you'd like to split out the &quot;state&quot; data store from an existing database which
  4271. currently contains all data stores.</p>
  4272. <p>Simply copy the tables and sequences defined above for the &quot;state&quot; datastore from the existing database
  4273. to the secondary database. As noted above, additional tables will be created in the secondary database
  4274. when Synapse is started.</p>
  4275. </li>
  4276. <li>
  4277. <p>Modify/create the <code>databases</code> option in your <code>homeserver.yaml</code> to match the desired database configuration.</p>
  4278. </li>
  4279. <li>
  4280. <p>Start Synapse. Check that it starts up successfully and that things generally seem to be working.</p>
  4281. </li>
  4282. <li>
  4283. <p>Drop the old tables that were copied in step 3.</p>
  4284. </li>
  4285. </ol>
  4286. <p>Only one of the options <code>database</code> or <code>databases</code> may be specified in your config, but not both.</p>
  4287. <p>Example configuration:</p>
  4288. <pre><code class="language-yaml">databases:
  4289. basement_box:
  4290. name: psycopg2
  4291. txn_limit: 10000
  4292. data_stores: [&quot;main&quot;]
  4293. args:
  4294. user: synapse_user
  4295. password: secretpassword
  4296. database: synapse_main
  4297. host: localhost
  4298. port: 5432
  4299. cp_min: 5
  4300. cp_max: 10
  4301. my_other_database:
  4302. name: psycopg2
  4303. txn_limit: 10000
  4304. data_stores: [&quot;state&quot;]
  4305. args:
  4306. user: synapse_user
  4307. password: secretpassword
  4308. database: synapse_state
  4309. host: localhost
  4310. port: 5432
  4311. cp_min: 5
  4312. cp_max: 10
  4313. </code></pre>
  4314. <hr />
  4315. <h2 id="logging"><a class="header" href="#logging">Logging</a></h2>
  4316. <p>Config options related to logging.</p>
  4317. <hr />
  4318. <h3 id="log_config"><a class="header" href="#log_config"><code>log_config</code></a></h3>
  4319. <p>This option specifies a yaml python logging config file as described <a href="https://docs.python.org/3.7/library/logging.config.html#configuration-dictionary-schema">here</a>.</p>
  4320. <p>Example configuration:</p>
  4321. <pre><code class="language-yaml">log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  4322. </code></pre>
  4323. <hr />
  4324. <h2 id="ratelimiting"><a class="header" href="#ratelimiting">Ratelimiting</a></h2>
  4325. <p>Options related to ratelimiting in Synapse.</p>
  4326. <p>Each ratelimiting configuration is made of two parameters:</p>
  4327. <ul>
  4328. <li><code>per_second</code>: number of requests a client can send per second.</li>
  4329. <li><code>burst_count</code>: number of requests a client can send before being throttled.</li>
  4330. </ul>
  4331. <hr />
  4332. <h3 id="rc_message"><a class="header" href="#rc_message"><code>rc_message</code></a></h3>
  4333. <p>Ratelimiting settings for client messaging.</p>
  4334. <p>This is a ratelimiting option for messages that ratelimits sending based on the account the client
  4335. is using. It defaults to: <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
  4336. <p>Example configuration:</p>
  4337. <pre><code class="language-yaml">rc_message:
  4338. per_second: 0.5
  4339. burst_count: 15
  4340. </code></pre>
  4341. <hr />
  4342. <h3 id="rc_registration"><a class="header" href="#rc_registration"><code>rc_registration</code></a></h3>
  4343. <p>This option ratelimits registration requests based on the client's IP address.
  4344. It defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  4345. <p>Example configuration:</p>
  4346. <pre><code class="language-yaml">rc_registration:
  4347. per_second: 0.15
  4348. burst_count: 2
  4349. </code></pre>
  4350. <hr />
  4351. <h3 id="rc_registration_token_validity"><a class="header" href="#rc_registration_token_validity"><code>rc_registration_token_validity</code></a></h3>
  4352. <p>This option checks the validity of registration tokens that ratelimits requests based on
  4353. the client's IP address.
  4354. Defaults to <code>per_second: 0.1</code>, <code>burst_count: 5</code>.</p>
  4355. <p>Example configuration:</p>
  4356. <pre><code class="language-yaml">rc_registration_token_validity:
  4357. per_second: 0.3
  4358. burst_count: 6
  4359. </code></pre>
  4360. <hr />
  4361. <h3 id="rc_login"><a class="header" href="#rc_login"><code>rc_login</code></a></h3>
  4362. <p>This option specifies several limits for login:</p>
  4363. <ul>
  4364. <li>
  4365. <p><code>address</code> ratelimits login requests based on the client's IP
  4366. address. Defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  4367. </li>
  4368. <li>
  4369. <p><code>account</code> ratelimits login requests based on the account the
  4370. client is attempting to log into. Defaults to <code>per_second: 0.17</code>,
  4371. <code>burst_count: 3</code>.</p>
  4372. </li>
  4373. <li>
  4374. <p><code>failed_attempts</code> ratelimits login requests based on the account the
  4375. client is attempting to log into, based on the amount of failed login
  4376. attempts for this account. Defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  4377. </li>
  4378. </ul>
  4379. <p>Example configuration:</p>
  4380. <pre><code class="language-yaml">rc_login:
  4381. address:
  4382. per_second: 0.15
  4383. burst_count: 5
  4384. account:
  4385. per_second: 0.18
  4386. burst_count: 4
  4387. failed_attempts:
  4388. per_second: 0.19
  4389. burst_count: 7
  4390. </code></pre>
  4391. <hr />
  4392. <h3 id="rc_admin_redaction"><a class="header" href="#rc_admin_redaction"><code>rc_admin_redaction</code></a></h3>
  4393. <p>This option sets ratelimiting redactions by room admins. If this is not explicitly
  4394. set then it uses the same ratelimiting as per <code>rc_message</code>. This is useful
  4395. to allow room admins to deal with abuse quickly.</p>
  4396. <p>Example configuration:</p>
  4397. <pre><code class="language-yaml">rc_admin_redaction:
  4398. per_second: 1
  4399. burst_count: 50
  4400. </code></pre>
  4401. <hr />
  4402. <h3 id="rc_joins"><a class="header" href="#rc_joins"><code>rc_joins</code></a></h3>
  4403. <p>This option allows for ratelimiting number of rooms a user can join. This setting has the following sub-options:</p>
  4404. <ul>
  4405. <li>
  4406. <p><code>local</code>: ratelimits when users are joining rooms the server is already in.
  4407. Defaults to <code>per_second: 0.1</code>, <code>burst_count: 10</code>.</p>
  4408. </li>
  4409. <li>
  4410. <p><code>remote</code>: ratelimits when users are trying to join rooms not on the server (which
  4411. can be more computationally expensive than restricting locally). Defaults to
  4412. <code>per_second: 0.01</code>, <code>burst_count: 10</code></p>
  4413. </li>
  4414. </ul>
  4415. <p>Example configuration:</p>
  4416. <pre><code class="language-yaml">rc_joins:
  4417. local:
  4418. per_second: 0.2
  4419. burst_count: 15
  4420. remote:
  4421. per_second: 0.03
  4422. burst_count: 12
  4423. </code></pre>
  4424. <hr />
  4425. <h3 id="rc_joins_per_room"><a class="header" href="#rc_joins_per_room"><code>rc_joins_per_room</code></a></h3>
  4426. <p>This option allows admins to ratelimit joins to a room based on the number of recent
  4427. joins (local or remote) to that room. It is intended to mitigate mass-join spam
  4428. waves which target multiple homeservers.</p>
  4429. <p>By default, one join is permitted to a room every second, with an accumulating
  4430. buffer of up to ten instantaneous joins.</p>
  4431. <p>Example configuration (default values):</p>
  4432. <pre><code class="language-yaml">rc_joins_per_room:
  4433. per_second: 1
  4434. burst_count: 10
  4435. </code></pre>
  4436. <p><em>Added in Synapse 1.64.0.</em></p>
  4437. <hr />
  4438. <h3 id="rc_3pid_validation"><a class="header" href="#rc_3pid_validation"><code>rc_3pid_validation</code></a></h3>
  4439. <p>This option ratelimits how often a user or IP can attempt to validate a 3PID.
  4440. Defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  4441. <p>Example configuration:</p>
  4442. <pre><code class="language-yaml">rc_3pid_validation:
  4443. per_second: 0.003
  4444. burst_count: 5
  4445. </code></pre>
  4446. <hr />
  4447. <h3 id="rc_invites"><a class="header" href="#rc_invites"><code>rc_invites</code></a></h3>
  4448. <p>This option sets ratelimiting how often invites can be sent in a room or to a
  4449. specific user. <code>per_room</code> defaults to <code>per_second: 0.3</code>, <code>burst_count: 10</code> and
  4450. <code>per_user</code> defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  4451. <p>Client requests that invite user(s) when <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3createroom">creating a
  4452. room</a>
  4453. will count against the <code>rc_invites.per_room</code> limit, whereas
  4454. client requests to <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidinvite">invite a single user to a
  4455. room</a>
  4456. will count against both the <code>rc_invites.per_user</code> and <code>rc_invites.per_room</code> limits.</p>
  4457. <p>Federation requests to invite a user will count against the <code>rc_invites.per_user</code>
  4458. limit only, as Synapse presumes ratelimiting by room will be done by the sending server.</p>
  4459. <p>The <code>rc_invites.per_user</code> limit applies to the <em>receiver</em> of the invite, rather than the
  4460. sender, meaning that a <code>rc_invite.per_user.burst_count</code> of 5 mandates that a single user
  4461. cannot <em>receive</em> more than a burst of 5 invites at a time.</p>
  4462. <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>
  4463. <p><em>Changed in version 1.63:</em> added the <code>per_issuer</code> limit.</p>
  4464. <p>Example configuration:</p>
  4465. <pre><code class="language-yaml">rc_invites:
  4466. per_room:
  4467. per_second: 0.5
  4468. burst_count: 5
  4469. per_user:
  4470. per_second: 0.004
  4471. burst_count: 3
  4472. per_issuer:
  4473. per_second: 0.5
  4474. burst_count: 5
  4475. </code></pre>
  4476. <hr />
  4477. <h3 id="rc_third_party_invite"><a class="header" href="#rc_third_party_invite"><code>rc_third_party_invite</code></a></h3>
  4478. <p>This option ratelimits 3PID invites (i.e. invites sent to a third-party ID
  4479. such as an email address or a phone number) based on the account that's
  4480. sending the invite. Defaults to <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
  4481. <p>Example configuration:</p>
  4482. <pre><code class="language-yaml">rc_third_party_invite:
  4483. per_second: 0.2
  4484. burst_count: 10
  4485. </code></pre>
  4486. <hr />
  4487. <h3 id="rc_federation"><a class="header" href="#rc_federation"><code>rc_federation</code></a></h3>
  4488. <p>Defines limits on federation requests.</p>
  4489. <p>The <code>rc_federation</code> configuration has the following sub-options:</p>
  4490. <ul>
  4491. <li><code>window_size</code>: window size in milliseconds. Defaults to 1000.</li>
  4492. <li><code>sleep_limit</code>: number of federation requests from a single server in
  4493. a window before the server will delay processing the request. Defaults to 10.</li>
  4494. <li><code>sleep_delay</code>: duration in milliseconds to delay processing events
  4495. from remote servers by if they go over the sleep limit. Defaults to 500.</li>
  4496. <li><code>reject_limit</code>: maximum number of concurrent federation requests
  4497. allowed from a single server. Defaults to 50.</li>
  4498. <li><code>concurrent</code>: number of federation requests to concurrently process
  4499. from a single server. Defaults to 3.</li>
  4500. </ul>
  4501. <p>Example configuration:</p>
  4502. <pre><code class="language-yaml">rc_federation:
  4503. window_size: 750
  4504. sleep_limit: 15
  4505. sleep_delay: 400
  4506. reject_limit: 40
  4507. concurrent: 5
  4508. </code></pre>
  4509. <hr />
  4510. <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>
  4511. <p>Sets outgoing federation transaction frequency for sending read-receipts,
  4512. per-room.</p>
  4513. <p>If we end up trying to send out more read-receipts, they will get buffered up
  4514. into fewer transactions. Defaults to 50.</p>
  4515. <p>Example configuration:</p>
  4516. <pre><code class="language-yaml">federation_rr_transactions_per_room_per_second: 40
  4517. </code></pre>
  4518. <hr />
  4519. <h2 id="media-store"><a class="header" href="#media-store">Media Store</a></h2>
  4520. <p>Config options related to Synapse's media store.</p>
  4521. <hr />
  4522. <h3 id="enable_media_repo"><a class="header" href="#enable_media_repo"><code>enable_media_repo</code></a></h3>
  4523. <p>Enable the media store service in the Synapse master. Defaults to true.
  4524. Set to false if you are using a separate media store worker.</p>
  4525. <p>Example configuration:</p>
  4526. <pre><code class="language-yaml">enable_media_repo: false
  4527. </code></pre>
  4528. <hr />
  4529. <h3 id="media_store_path"><a class="header" href="#media_store_path"><code>media_store_path</code></a></h3>
  4530. <p>Directory where uploaded images and attachments are stored.</p>
  4531. <p>Example configuration:</p>
  4532. <pre><code class="language-yaml">media_store_path: &quot;DATADIR/media_store&quot;
  4533. </code></pre>
  4534. <hr />
  4535. <h3 id="media_storage_providers"><a class="header" href="#media_storage_providers"><code>media_storage_providers</code></a></h3>
  4536. <p>Media storage providers allow media to be stored in different
  4537. locations. Defaults to none. Associated sub-options are:</p>
  4538. <ul>
  4539. <li><code>module</code>: type of resource, e.g. <code>file_system</code>.</li>
  4540. <li><code>store_local</code>: whether to store newly uploaded local files</li>
  4541. <li><code>store_remote</code>: whether to store newly downloaded local files</li>
  4542. <li><code>store_synchronous</code>: whether to wait for successful storage for local uploads</li>
  4543. <li><code>config</code>: sets a path to the resource through the <code>directory</code> option</li>
  4544. </ul>
  4545. <p>Example configuration:</p>
  4546. <pre><code class="language-yaml">media_storage_providers:
  4547. - module: file_system
  4548. store_local: false
  4549. store_remote: false
  4550. store_synchronous: false
  4551. config:
  4552. directory: /mnt/some/other/directory
  4553. </code></pre>
  4554. <hr />
  4555. <h3 id="max_upload_size"><a class="header" href="#max_upload_size"><code>max_upload_size</code></a></h3>
  4556. <p>The largest allowed upload size in bytes.</p>
  4557. <p>If you are using a reverse proxy you may also need to set this value in
  4558. your reverse proxy's config. Defaults to 50M. Notably Nginx has a small max body size by default.
  4559. See <a href="usage/configuration/../../reverse_proxy.html">here</a> for more on using a reverse proxy with Synapse.</p>
  4560. <p>Example configuration:</p>
  4561. <pre><code class="language-yaml">max_upload_size: 60M
  4562. </code></pre>
  4563. <hr />
  4564. <h3 id="max_image_pixels"><a class="header" href="#max_image_pixels"><code>max_image_pixels</code></a></h3>
  4565. <p>Maximum number of pixels that will be thumbnailed. Defaults to 32M.</p>
  4566. <p>Example configuration:</p>
  4567. <pre><code class="language-yaml">max_image_pixels: 35M
  4568. </code></pre>
  4569. <hr />
  4570. <h3 id="dynamic_thumbnails"><a class="header" href="#dynamic_thumbnails"><code>dynamic_thumbnails</code></a></h3>
  4571. <p>Whether to generate new thumbnails on the fly to precisely match
  4572. the resolution requested by the client. If true then whenever
  4573. a new resolution is requested by the client the server will
  4574. generate a new thumbnail. If false the server will pick a thumbnail
  4575. from a precalculated list. Defaults to false.</p>
  4576. <p>Example configuration:</p>
  4577. <pre><code class="language-yaml">dynamic_thumbnails: true
  4578. </code></pre>
  4579. <hr />
  4580. <h3 id="thumbnail_sizes"><a class="header" href="#thumbnail_sizes"><code>thumbnail_sizes</code></a></h3>
  4581. <p>List of thumbnails to precalculate when an image is uploaded. Associated sub-options are:</p>
  4582. <ul>
  4583. <li><code>width</code></li>
  4584. <li><code>height</code></li>
  4585. <li><code>method</code>: i.e. <code>crop</code>, <code>scale</code>, etc.</li>
  4586. </ul>
  4587. <p>Example configuration:</p>
  4588. <pre><code class="language-yaml">thumbnail_sizes:
  4589. - width: 32
  4590. height: 32
  4591. method: crop
  4592. - width: 96
  4593. height: 96
  4594. method: crop
  4595. - width: 320
  4596. height: 240
  4597. method: scale
  4598. - width: 640
  4599. height: 480
  4600. method: scale
  4601. - width: 800
  4602. height: 600
  4603. method: scale
  4604. </code></pre>
  4605. <hr />
  4606. <h3 id="media_retention"><a class="header" href="#media_retention"><code>media_retention</code></a></h3>
  4607. <p>Controls whether local media and entries in the remote media cache
  4608. (media that is downloaded from other homeservers) should be removed
  4609. under certain conditions, typically for the purpose of saving space.</p>
  4610. <p>Purging media files will be the carried out by the media worker
  4611. (that is, the worker that has the <code>enable_media_repo</code> homeserver config
  4612. option set to 'true'). This may be the main process.</p>
  4613. <p>The <code>media_retention.local_media_lifetime</code> and
  4614. <code>media_retention.remote_media_lifetime</code> config options control whether
  4615. media will be purged if it has not been accessed in a given amount of
  4616. time. Note that media is 'accessed' when loaded in a room in a client, or
  4617. otherwise downloaded by a local or remote user. If the media has never
  4618. been accessed, the media's creation time is used instead. Both thumbnails
  4619. and the original media will be removed. If either of these options are unset,
  4620. then media of that type will not be purged.</p>
  4621. <p>Local or cached remote media that has been
  4622. <a href="usage/configuration/../../admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantined</a>
  4623. will not be deleted. Similarly, local media that has been marked as
  4624. <a href="usage/configuration/../../admin_api/media_admin_api.html#protecting-media-from-being-quarantined">protected from quarantine</a>
  4625. will not be deleted.</p>
  4626. <p>Example configuration:</p>
  4627. <pre><code class="language-yaml">media_retention:
  4628. local_media_lifetime: 90d
  4629. remote_media_lifetime: 14d
  4630. </code></pre>
  4631. <hr />
  4632. <h3 id="url_preview_enabled"><a class="header" href="#url_preview_enabled"><code>url_preview_enabled</code></a></h3>
  4633. <p>This setting determines whether the preview URL API is enabled.
  4634. It is disabled by default. Set to true to enable. If enabled you must specify a
  4635. <code>url_preview_ip_range_blacklist</code> blacklist.</p>
  4636. <p>Example configuration:</p>
  4637. <pre><code class="language-yaml">url_preview_enabled: true
  4638. </code></pre>
  4639. <hr />
  4640. <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>
  4641. <p>List of IP address CIDR ranges that the URL preview spider is denied
  4642. from accessing. There are no defaults: you must explicitly
  4643. specify a list for URL previewing to work. You should specify any
  4644. internal services in your network that you do not want synapse to try
  4645. to connect to, otherwise anyone in any Matrix room could cause your
  4646. synapse to issue arbitrary GET requests to your internal services,
  4647. causing serious security issues.</p>
  4648. <p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  4649. listed here, since they correspond to unroutable addresses.)</p>
  4650. <p>This must be specified if <code>url_preview_enabled</code> is set. It is recommended that
  4651. you use the following example list as a starting point.</p>
  4652. <p>Note: The value is ignored when an HTTP proxy is in use.</p>
  4653. <p>Example configuration:</p>
  4654. <pre><code class="language-yaml">url_preview_ip_range_blacklist:
  4655. - '127.0.0.0/8'
  4656. - '10.0.0.0/8'
  4657. - '172.16.0.0/12'
  4658. - '192.168.0.0/16'
  4659. - '100.64.0.0/10'
  4660. - '192.0.0.0/24'
  4661. - '169.254.0.0/16'
  4662. - '192.88.99.0/24'
  4663. - '198.18.0.0/15'
  4664. - '192.0.2.0/24'
  4665. - '198.51.100.0/24'
  4666. - '203.0.113.0/24'
  4667. - '224.0.0.0/4'
  4668. - '::1/128'
  4669. - 'fe80::/10'
  4670. - 'fc00::/7'
  4671. - '2001:db8::/32'
  4672. - 'ff00::/8'
  4673. - 'fec0::/10'
  4674. </code></pre>
  4675. <hr />
  4676. <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>
  4677. <p>This option sets a list of IP address CIDR ranges that the URL preview spider is allowed
  4678. to access even if they are specified in <code>url_preview_ip_range_blacklist</code>.
  4679. This is useful for specifying exceptions to wide-ranging blacklisted
  4680. target IP ranges - e.g. for enabling URL previews for a specific private
  4681. website only visible in your network. Defaults to none.</p>
  4682. <p>Example configuration:</p>
  4683. <pre><code class="language-yaml">url_preview_ip_range_whitelist:
  4684. - '192.168.1.1'
  4685. </code></pre>
  4686. <hr />
  4687. <h3 id="url_preview_url_blacklist"><a class="header" href="#url_preview_url_blacklist"><code>url_preview_url_blacklist</code></a></h3>
  4688. <p>Optional list of URL matches that the URL preview spider is
  4689. denied from accessing. You should use <code>url_preview_ip_range_blacklist</code>
  4690. in preference to this, otherwise someone could define a public DNS
  4691. entry that points to a private IP address and circumvent the blacklist.
  4692. This is more useful if you know there is an entire shape of URL that
  4693. you know that will never want synapse to try to spider.</p>
  4694. <p>Each list entry is a dictionary of url component attributes as returned
  4695. by urlparse.urlsplit as applied to the absolute form of the URL. See
  4696. <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit">here</a> for more
  4697. information. Some examples are:</p>
  4698. <ul>
  4699. <li><code>username</code></li>
  4700. <li><code>netloc</code></li>
  4701. <li><code>scheme</code></li>
  4702. <li><code>path</code></li>
  4703. </ul>
  4704. <p>The values of the dictionary are treated as a filename match pattern
  4705. applied to that component of URLs, unless they start with a ^ in which
  4706. case they are treated as a regular expression match. If all the
  4707. specified component matches for a given list item succeed, the URL is
  4708. blacklisted.</p>
  4709. <p>Example configuration:</p>
  4710. <pre><code class="language-yaml">url_preview_url_blacklist:
  4711. # blacklist any URL with a username in its URI
  4712. - username: '*'
  4713. # blacklist all *.google.com URLs
  4714. - netloc: 'google.com'
  4715. - netloc: '*.google.com'
  4716. # blacklist all plain HTTP URLs
  4717. - scheme: 'http'
  4718. # blacklist http(s)://www.acme.com/foo
  4719. - netloc: 'www.acme.com'
  4720. path: '/foo'
  4721. # blacklist any URL with a literal IPv4 address
  4722. - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
  4723. </code></pre>
  4724. <hr />
  4725. <h3 id="max_spider_size"><a class="header" href="#max_spider_size"><code>max_spider_size</code></a></h3>
  4726. <p>The largest allowed URL preview spidering size in bytes. Defaults to 10M.</p>
  4727. <p>Example configuration:</p>
  4728. <pre><code class="language-yaml">max_spider_size: 8M
  4729. </code></pre>
  4730. <hr />
  4731. <h3 id="url_preview_accept_language"><a class="header" href="#url_preview_accept_language"><code>url_preview_accept_language</code></a></h3>
  4732. <p>A list of values for the Accept-Language HTTP header used when
  4733. downloading webpages during URL preview generation. This allows
  4734. Synapse to specify the preferred languages that URL previews should
  4735. be in when communicating with remote servers.</p>
  4736. <p>Each value is a IETF language tag; a 2-3 letter identifier for a
  4737. language, optionally followed by subtags separated by '-', specifying
  4738. a country or region variant.</p>
  4739. <p>Multiple values can be provided, and a weight can be added to each by
  4740. using quality value syntax (;q=). '*' translates to any language.</p>
  4741. <p>Defaults to &quot;en&quot;.</p>
  4742. <p>Example configuration:</p>
  4743. <pre><code class="language-yaml"> url_preview_accept_language:
  4744. - 'en-UK'
  4745. - 'en-US;q=0.9'
  4746. - 'fr;q=0.8'
  4747. - '*;q=0.7'
  4748. </code></pre>
  4749. <hr />
  4750. <h3 id="oembed"><a class="header" href="#oembed"><code>oembed</code></a></h3>
  4751. <p>oEmbed allows for easier embedding content from a website. It can be
  4752. used for generating URLs previews of services which support it. A default list of oEmbed providers
  4753. is included with Synapse. Set <code>disable_default_providers</code> to true to disable using
  4754. these default oEmbed URLs. Use <code>additional_providers</code> to specify additional files with oEmbed configuration (each
  4755. should be in the form of providers.json). By default this list is empty.</p>
  4756. <p>Example configuration:</p>
  4757. <pre><code class="language-yaml">oembed:
  4758. disable_default_providers: true
  4759. additional_providers:
  4760. - oembed/my_providers.json
  4761. </code></pre>
  4762. <hr />
  4763. <h2 id="captcha"><a class="header" href="#captcha">Captcha</a></h2>
  4764. <p>See <a href="usage/configuration/../../CAPTCHA_SETUP.html">here</a> for full details on setting up captcha.</p>
  4765. <hr />
  4766. <h3 id="recaptcha_public_key"><a class="header" href="#recaptcha_public_key"><code>recaptcha_public_key</code></a></h3>
  4767. <p>This homeserver's ReCAPTCHA public key. Must be specified if
  4768. <a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a> is enabled.</p>
  4769. <p>Example configuration:</p>
  4770. <pre><code class="language-yaml">recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  4771. </code></pre>
  4772. <hr />
  4773. <h3 id="recaptcha_private_key"><a class="header" href="#recaptcha_private_key"><code>recaptcha_private_key</code></a></h3>
  4774. <p>This homeserver's ReCAPTCHA private key. Must be specified if
  4775. <a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a> is
  4776. enabled.</p>
  4777. <p>Example configuration:</p>
  4778. <pre><code class="language-yaml">recaptcha_private_key: &quot;YOUR_PRIVATE_KEY&quot;
  4779. </code></pre>
  4780. <hr />
  4781. <h3 id="enable_registration_captcha"><a class="header" href="#enable_registration_captcha"><code>enable_registration_captcha</code></a></h3>
  4782. <p>Set to <code>true</code> to require users to complete a CAPTCHA test when registering an account.
  4783. Requires a valid ReCaptcha public/private key.
  4784. Defaults to <code>false</code>.</p>
  4785. <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>
  4786. <p>Example configuration:</p>
  4787. <pre><code class="language-yaml">enable_registration_captcha: true
  4788. </code></pre>
  4789. <hr />
  4790. <h3 id="recaptcha_siteverify_api"><a class="header" href="#recaptcha_siteverify_api"><code>recaptcha_siteverify_api</code></a></h3>
  4791. <p>The API endpoint to use for verifying <code>m.login.recaptcha</code> responses.
  4792. Defaults to <code>https://www.recaptcha.net/recaptcha/api/siteverify</code>.</p>
  4793. <p>Example configuration:</p>
  4794. <pre><code class="language-yaml">recaptcha_siteverify_api: &quot;https://my.recaptcha.site&quot;
  4795. </code></pre>
  4796. <hr />
  4797. <h2 id="turn"><a class="header" href="#turn">TURN</a></h2>
  4798. <p>Options related to adding a TURN server to Synapse.</p>
  4799. <hr />
  4800. <h3 id="turn_uris"><a class="header" href="#turn_uris"><code>turn_uris</code></a></h3>
  4801. <p>The public URIs of the TURN server to give to clients.</p>
  4802. <p>Example configuration:</p>
  4803. <pre><code class="language-yaml">turn_uris: [turn:example.org]
  4804. </code></pre>
  4805. <hr />
  4806. <h3 id="turn_shared_secret"><a class="header" href="#turn_shared_secret"><code>turn_shared_secret</code></a></h3>
  4807. <p>The shared secret used to compute passwords for the TURN server.</p>
  4808. <p>Example configuration:</p>
  4809. <pre><code class="language-yaml">turn_shared_secret: &quot;YOUR_SHARED_SECRET&quot;
  4810. </code></pre>
  4811. <hr />
  4812. <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>
  4813. <p>The Username and password if the TURN server needs them and does not use a token.</p>
  4814. <p>Example configuration:</p>
  4815. <pre><code class="language-yaml">turn_username: &quot;TURNSERVER_USERNAME&quot;
  4816. turn_password: &quot;TURNSERVER_PASSWORD&quot;
  4817. </code></pre>
  4818. <hr />
  4819. <h3 id="turn_user_lifetime"><a class="header" href="#turn_user_lifetime"><code>turn_user_lifetime</code></a></h3>
  4820. <p>How long generated TURN credentials last. Defaults to 1h.</p>
  4821. <p>Example configuration:</p>
  4822. <pre><code class="language-yaml">turn_user_lifetime: 2h
  4823. </code></pre>
  4824. <hr />
  4825. <h3 id="turn_allow_guests"><a class="header" href="#turn_allow_guests"><code>turn_allow_guests</code></a></h3>
  4826. <p>Whether guests should be allowed to use the TURN server. This defaults to true, otherwise
  4827. VoIP will be unreliable for guests. However, it does introduce a slight security risk as
  4828. it allows users to connect to arbitrary endpoints without having first signed up for a valid account (e.g. by passing a CAPTCHA).</p>
  4829. <p>Example configuration:</p>
  4830. <pre><code class="language-yaml">turn_allow_guests: false
  4831. </code></pre>
  4832. <hr />
  4833. <h2 id="registration"><a class="header" href="#registration">Registration</a></h2>
  4834. <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>
  4835. <hr />
  4836. <h3 id="enable_registration"><a class="header" href="#enable_registration"><code>enable_registration</code></a></h3>
  4837. <p>Enable registration for new users. Defaults to <code>false</code>.</p>
  4838. <p>It is highly recommended that if you enable registration, you set one or more
  4839. or the following options, to avoid abuse of your server by &quot;bots&quot;:</p>
  4840. <ul>
  4841. <li><a href="usage/configuration/config_documentation.html#enable_registration_captcha"><code>enable_registration_captcha</code></a></li>
  4842. <li><a href="usage/configuration/config_documentation.html#registrations_require_3pid"><code>registrations_require_3pid</code></a></li>
  4843. <li><a href="usage/configuration/config_documentation.html#registration_requires_token"><code>registration_requires_token</code></a></li>
  4844. </ul>
  4845. <p>(In order to enable registration without any verification, you must also set
  4846. <a href="usage/configuration/config_documentation.html#enable_registration_without_verification"><code>enable_registration_without_verification</code></a>.)</p>
  4847. <p>Note that even if this setting is disabled, new accounts can still be created
  4848. via the admin API if
  4849. <a href="usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a> is set.</p>
  4850. <p>Example configuration:</p>
  4851. <pre><code class="language-yaml">enable_registration: true
  4852. </code></pre>
  4853. <hr />
  4854. <h3 id="enable_registration_without_verification"><a class="header" href="#enable_registration_without_verification"><code>enable_registration_without_verification</code></a></h3>
  4855. <p>Enable registration without email or captcha verification. Note: this option is <em>not</em> recommended,
  4856. as registration without verification is a known vector for spam and abuse. Defaults to <code>false</code>. Has no effect
  4857. unless <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> is also enabled.</p>
  4858. <p>Example configuration:</p>
  4859. <pre><code class="language-yaml">enable_registration_without_verification: true
  4860. </code></pre>
  4861. <hr />
  4862. <h3 id="registrations_require_3pid"><a class="header" href="#registrations_require_3pid"><code>registrations_require_3pid</code></a></h3>
  4863. <p>If this is set, users must provide all of the specified types of 3PID when registering an account.</p>
  4864. <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>
  4865. <p>Example configuration:</p>
  4866. <pre><code class="language-yaml">registrations_require_3pid:
  4867. - email
  4868. - msisdn
  4869. </code></pre>
  4870. <hr />
  4871. <h3 id="disable_msisdn_registration"><a class="header" href="#disable_msisdn_registration"><code>disable_msisdn_registration</code></a></h3>
  4872. <p>Explicitly disable asking for MSISDNs from the registration
  4873. flow (overrides <code>registrations_require_3pid</code> if MSISDNs are set as required).</p>
  4874. <p>Example configuration:</p>
  4875. <pre><code class="language-yaml">disable_msisdn_registration: true
  4876. </code></pre>
  4877. <hr />
  4878. <h3 id="allowed_local_3pids"><a class="header" href="#allowed_local_3pids"><code>allowed_local_3pids</code></a></h3>
  4879. <p>Mandate that users are only allowed to associate certain formats of
  4880. 3PIDs with accounts on this server, as specified by the <code>medium</code> and <code>pattern</code> sub-options.</p>
  4881. <p>Example configuration:</p>
  4882. <pre><code class="language-yaml">allowed_local_3pids:
  4883. - medium: email
  4884. pattern: '^[^@]+@matrix\.org$'
  4885. - medium: email
  4886. pattern: '^[^@]+@vector\.im$'
  4887. - medium: msisdn
  4888. pattern: '\+44'
  4889. </code></pre>
  4890. <hr />
  4891. <h3 id="enable_3pid_lookup"><a class="header" href="#enable_3pid_lookup"><code>enable_3pid_lookup</code></a></h3>
  4892. <p>Enable 3PIDs lookup requests to identity servers from this server. Defaults to true.</p>
  4893. <p>Example configuration:</p>
  4894. <pre><code class="language-yaml">enable_3pid_lookup: false
  4895. </code></pre>
  4896. <hr />
  4897. <h3 id="registration_requires_token"><a class="header" href="#registration_requires_token"><code>registration_requires_token</code></a></h3>
  4898. <p>Require users to submit a token during registration.
  4899. Tokens can be managed using the admin <a href="usage/configuration/../administration/admin_api/registration_tokens.html">API</a>.
  4900. Disabling this option will not delete any tokens previously generated.
  4901. Defaults to <code>false</code>. Set to <code>true</code> to enable.</p>
  4902. <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>
  4903. <p>Example configuration:</p>
  4904. <pre><code class="language-yaml">registration_requires_token: true
  4905. </code></pre>
  4906. <hr />
  4907. <h3 id="registration_shared_secret"><a class="header" href="#registration_shared_secret"><code>registration_shared_secret</code></a></h3>
  4908. <p>If set, allows registration of standard or admin accounts by anyone who has the
  4909. shared secret, even if <a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a> is not
  4910. set.</p>
  4911. <p>This is primarily intended for use with the <code>register_new_matrix_user</code> script
  4912. (see <a href="usage/configuration/../../setup/installation.html#registering-a-user">Registering a user</a>);
  4913. however, the interface is <a href="usage/configuration/../admin_api/register_api.html">documented</a>.</p>
  4914. <p>See also <a href="usage/configuration/config_documentation.html#registration_shared_secret_path"><code>registration_shared_secret_path</code></a>.</p>
  4915. <p>Example configuration:</p>
  4916. <pre><code class="language-yaml">registration_shared_secret: &lt;PRIVATE STRING&gt;
  4917. </code></pre>
  4918. <hr />
  4919. <h3 id="registration_shared_secret_path"><a class="header" href="#registration_shared_secret_path"><code>registration_shared_secret_path</code></a></h3>
  4920. <p>An alternative to <a href="usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>:
  4921. allows the shared secret to be specified in an external file.</p>
  4922. <p>The file should be a plain text file, containing only the shared secret.</p>
  4923. <p>If this file does not exist, Synapse will create a new signing
  4924. key on startup and store it in this file.</p>
  4925. <p>Example configuration:</p>
  4926. <pre><code class="language-yaml">registration_shared_secret_file: /path/to/secrets/file
  4927. </code></pre>
  4928. <p><em>Added in Synapse 1.67.0.</em></p>
  4929. <hr />
  4930. <h3 id="bcrypt_rounds"><a class="header" href="#bcrypt_rounds"><code>bcrypt_rounds</code></a></h3>
  4931. <p>Set the number of bcrypt rounds used to generate password hash.
  4932. Larger numbers increase the work factor needed to generate the hash.
  4933. The default number is 12 (which equates to 2^12 rounds).
  4934. N.B. that increasing this will exponentially increase the time required
  4935. to register or login - e.g. 24 =&gt; 2^24 rounds which will take &gt;20 mins.
  4936. Example configuration:</p>
  4937. <pre><code class="language-yaml">bcrypt_rounds: 14
  4938. </code></pre>
  4939. <hr />
  4940. <h3 id="allow_guest_access"><a class="header" href="#allow_guest_access"><code>allow_guest_access</code></a></h3>
  4941. <p>Allows users to register as guests without a password/email/etc, and
  4942. participate in rooms hosted on this server which have been made
  4943. accessible to anonymous users. Defaults to false.</p>
  4944. <p>Example configuration:</p>
  4945. <pre><code class="language-yaml">allow_guest_access: true
  4946. </code></pre>
  4947. <hr />
  4948. <h3 id="default_identity_server"><a class="header" href="#default_identity_server"><code>default_identity_server</code></a></h3>
  4949. <p>The identity server which we suggest that clients should use when users log
  4950. in on this server.</p>
  4951. <p>(By default, no suggestion is made, so it is left up to the client.
  4952. This setting is ignored unless <code>public_baseurl</code> is also explicitly set.)</p>
  4953. <p>Example configuration:</p>
  4954. <pre><code class="language-yaml">default_identity_server: https://matrix.org
  4955. </code></pre>
  4956. <hr />
  4957. <h3 id="account_threepid_delegates"><a class="header" href="#account_threepid_delegates"><code>account_threepid_delegates</code></a></h3>
  4958. <p>Delegate verification of phone numbers to an identity server.</p>
  4959. <p>When a user wishes to add a phone number to their account, we need to verify that they
  4960. actually own that phone number, which requires sending them a text message (SMS).
  4961. Currently Synapse does not support sending those texts itself and instead delegates the
  4962. task to an identity server. The base URI for the identity server to be used is
  4963. specified by the <code>account_threepid_delegates.msisdn</code> option.</p>
  4964. <p>If this is left unspecified, Synapse will not allow users to add phone numbers to
  4965. their account.</p>
  4966. <p>(Servers handling the these requests must answer the <code>/requestToken</code> endpoints defined
  4967. by the Matrix Identity Service API
  4968. <a href="https://matrix.org/docs/spec/identity_service/latest">specification</a>.)</p>
  4969. <p><em>Deprecated in Synapse 1.64.0</em>: The <code>email</code> option is deprecated.</p>
  4970. <p><em>Removed in Synapse 1.66.0</em>: The <code>email</code> option has been removed.
  4971. If present, Synapse will report a configuration error on startup.</p>
  4972. <p>Example configuration:</p>
  4973. <pre><code class="language-yaml">account_threepid_delegates:
  4974. msisdn: http://localhost:8090 # Delegate SMS sending to this local process
  4975. </code></pre>
  4976. <hr />
  4977. <h3 id="enable_set_displayname"><a class="header" href="#enable_set_displayname"><code>enable_set_displayname</code></a></h3>
  4978. <p>Whether users are allowed to change their displayname after it has
  4979. been initially set. Useful when provisioning users based on the
  4980. contents of a third-party directory.</p>
  4981. <p>Does not apply to server administrators. Defaults to true.</p>
  4982. <p>Example configuration:</p>
  4983. <pre><code class="language-yaml">enable_set_displayname: false
  4984. </code></pre>
  4985. <hr />
  4986. <h3 id="enable_set_avatar_url"><a class="header" href="#enable_set_avatar_url"><code>enable_set_avatar_url</code></a></h3>
  4987. <p>Whether users are allowed to change their avatar after it has been
  4988. initially set. Useful when provisioning users based on the contents
  4989. of a third-party directory.</p>
  4990. <p>Does not apply to server administrators. Defaults to true.</p>
  4991. <p>Example configuration:</p>
  4992. <pre><code class="language-yaml">enable_set_avatar_url: false
  4993. </code></pre>
  4994. <hr />
  4995. <h3 id="enable_3pid_changes"><a class="header" href="#enable_3pid_changes"><code>enable_3pid_changes</code></a></h3>
  4996. <p>Whether users can change the third-party IDs associated with their accounts
  4997. (email address and msisdn).</p>
  4998. <p>Defaults to true.</p>
  4999. <p>Example configuration:</p>
  5000. <pre><code class="language-yaml">enable_3pid_changes: false
  5001. </code></pre>
  5002. <hr />
  5003. <h3 id="auto_join_rooms"><a class="header" href="#auto_join_rooms"><code>auto_join_rooms</code></a></h3>
  5004. <p>Users who register on this homeserver will automatically be joined
  5005. to the rooms listed under this option.</p>
  5006. <p>By default, any room aliases included in this list will be created
  5007. as a publicly joinable room when the first user registers for the
  5008. homeserver. If the room already exists, make certain it is a publicly joinable
  5009. room, i.e. the join rule of the room must be set to 'public'. You can find more options
  5010. relating to auto-joining rooms below.</p>
  5011. <p>As Spaces are just rooms under the hood, Space aliases may also be
  5012. used.</p>
  5013. <p>Example configuration:</p>
  5014. <pre><code class="language-yaml">auto_join_rooms:
  5015. - &quot;#exampleroom:example.com&quot;
  5016. - &quot;#anotherexampleroom:example.com&quot;
  5017. </code></pre>
  5018. <hr />
  5019. <h3 id="autocreate_auto_join_rooms"><a class="header" href="#autocreate_auto_join_rooms"><code>autocreate_auto_join_rooms</code></a></h3>
  5020. <p>Where <code>auto_join_rooms</code> are specified, setting this flag ensures that
  5021. the rooms exist by creating them when the first user on the
  5022. homeserver registers. This option will not create Spaces.</p>
  5023. <p>By default the auto-created rooms are publicly joinable from any federated
  5024. server. Use the <code>autocreate_auto_join_rooms_federated</code> and
  5025. <code>autocreate_auto_join_room_preset</code> settings to customise this behaviour.</p>
  5026. <p>Setting to false means that if the rooms are not manually created,
  5027. users cannot be auto-joined since they do not exist.</p>
  5028. <p>Defaults to true.</p>
  5029. <p>Example configuration:</p>
  5030. <pre><code class="language-yaml">autocreate_auto_join_rooms: false
  5031. </code></pre>
  5032. <hr />
  5033. <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>
  5034. <p>Whether the rooms listed in <code>auto_join_rooms</code> that are auto-created are available
  5035. via federation. Only has an effect if <code>autocreate_auto_join_rooms</code> is true.</p>
  5036. <p>Note that whether a room is federated cannot be modified after
  5037. creation.</p>
  5038. <p>Defaults to true: the room will be joinable from other servers.
  5039. Set to false to prevent users from other homeservers from
  5040. joining these rooms.</p>
  5041. <p>Example configuration:</p>
  5042. <pre><code class="language-yaml">autocreate_auto_join_rooms_federated: false
  5043. </code></pre>
  5044. <hr />
  5045. <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>
  5046. <p>The room preset to use when auto-creating one of <code>auto_join_rooms</code>. Only has an
  5047. effect if <code>autocreate_auto_join_rooms</code> is true.</p>
  5048. <p>Possible values for this option are:</p>
  5049. <ul>
  5050. <li>&quot;public_chat&quot;: the room is joinable by anyone, including
  5051. federated servers if <code>autocreate_auto_join_rooms_federated</code> is true (the default).</li>
  5052. <li>&quot;private_chat&quot;: an invitation is required to join these rooms.</li>
  5053. <li>&quot;trusted_private_chat&quot;: an invitation is required to join this room and the invitee is
  5054. assigned a power level of 100 upon joining the room.</li>
  5055. </ul>
  5056. <p>If a value of &quot;private_chat&quot; or &quot;trusted_private_chat&quot; is used then
  5057. <code>auto_join_mxid_localpart</code> must also be configured.</p>
  5058. <p>Defaults to &quot;public_chat&quot;.</p>
  5059. <p>Example configuration:</p>
  5060. <pre><code class="language-yaml">autocreate_auto_join_room_preset: private_chat
  5061. </code></pre>
  5062. <hr />
  5063. <h3 id="auto_join_mxid_localpart"><a class="header" href="#auto_join_mxid_localpart"><code>auto_join_mxid_localpart</code></a></h3>
  5064. <p>The local part of the user id which is used to create <code>auto_join_rooms</code> if
  5065. <code>autocreate_auto_join_rooms</code> is true. If this is not provided then the
  5066. initial user account that registers will be used to create the rooms.</p>
  5067. <p>The user id is also used to invite new users to any auto-join rooms which
  5068. are set to invite-only.</p>
  5069. <p>It <em>must</em> be configured if <code>autocreate_auto_join_room_preset</code> is set to
  5070. &quot;private_chat&quot; or &quot;trusted_private_chat&quot;.</p>
  5071. <p>Note that this must be specified in order for new users to be correctly
  5072. invited to any auto-join rooms which have been set to invite-only (either
  5073. at the time of creation or subsequently).</p>
  5074. <p>Note that, if the room already exists, this user must be joined and
  5075. have the appropriate permissions to invite new members.</p>
  5076. <p>Example configuration:</p>
  5077. <pre><code class="language-yaml">auto_join_mxid_localpart: system
  5078. </code></pre>
  5079. <hr />
  5080. <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>
  5081. <p>When <code>auto_join_rooms</code> is specified, setting this flag to false prevents
  5082. guest accounts from being automatically joined to the rooms.</p>
  5083. <p>Defaults to true.</p>
  5084. <p>Example configuration:</p>
  5085. <pre><code class="language-yaml">auto_join_rooms_for_guests: false
  5086. </code></pre>
  5087. <hr />
  5088. <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>
  5089. <p>Whether to inhibit errors raised when registering a new account if the user ID
  5090. already exists. If turned on, requests to <code>/register/available</code> will always
  5091. show a user ID as available, and Synapse won't raise an error when starting
  5092. a registration with a user ID that already exists. However, Synapse will still
  5093. raise an error if the registration completes and the username conflicts.</p>
  5094. <p>Defaults to false.</p>
  5095. <p>Example configuration:</p>
  5096. <pre><code class="language-yaml">inhibit_user_in_use_error: true
  5097. </code></pre>
  5098. <hr />
  5099. <h2 id="user-session-management"><a class="header" href="#user-session-management">User session management</a></h2>
  5100. <hr />
  5101. <h3 id="session_lifetime"><a class="header" href="#session_lifetime"><code>session_lifetime</code></a></h3>
  5102. <p>Time that a user's session remains valid for, after they log in.</p>
  5103. <p>Note that this is not currently compatible with guest logins.</p>
  5104. <p>Note also that this is calculated at login time: changes are not applied retrospectively to users who have already
  5105. logged in.</p>
  5106. <p>By default, this is infinite.</p>
  5107. <p>Example configuration:</p>
  5108. <pre><code class="language-yaml">session_lifetime: 24h
  5109. </code></pre>
  5110. <hr />
  5111. <h3 id="refresh_access_token_lifetime"><a class="header" href="#refresh_access_token_lifetime"><code>refresh_access_token_lifetime</code></a></h3>
  5112. <p>Time that an access token remains valid for, if the session is using refresh tokens.</p>
  5113. <p>For more information about refresh tokens, please see the <a href="usage/configuration/user_authentication/refresh_tokens.html">manual</a>.</p>
  5114. <p>Note that this only applies to clients which advertise support for refresh tokens.</p>
  5115. <p>Note also that this is calculated at login time and refresh time: changes are not applied to
  5116. existing sessions until they are refreshed.</p>
  5117. <p>By default, this is 5 minutes.</p>
  5118. <p>Example configuration:</p>
  5119. <pre><code class="language-yaml">refreshable_access_token_lifetime: 10m
  5120. </code></pre>
  5121. <hr />
  5122. <h3 id="refresh_token_lifetime-24h"><a class="header" href="#refresh_token_lifetime-24h"><code>refresh_token_lifetime: 24h</code></a></h3>
  5123. <p>Time that a refresh token remains valid for (provided that it is not
  5124. exchanged for another one first).
  5125. This option can be used to automatically log-out inactive sessions.
  5126. Please see the manual for more information.</p>
  5127. <p>Note also that this is calculated at login time and refresh time:
  5128. changes are not applied to existing sessions until they are refreshed.</p>
  5129. <p>By default, this is infinite.</p>
  5130. <p>Example configuration:</p>
  5131. <pre><code class="language-yaml">refresh_token_lifetime: 24h
  5132. </code></pre>
  5133. <hr />
  5134. <h3 id="nonrefreshable_access_token_lifetime"><a class="header" href="#nonrefreshable_access_token_lifetime"><code>nonrefreshable_access_token_lifetime</code></a></h3>
  5135. <p>Time that an access token remains valid for, if the session is NOT
  5136. using refresh tokens.</p>
  5137. <p>Please note that not all clients support refresh tokens, so setting
  5138. this to a short value may be inconvenient for some users who will
  5139. then be logged out frequently.</p>
  5140. <p>Note also that this is calculated at login time: changes are not applied
  5141. retrospectively to existing sessions for users that have already logged in.</p>
  5142. <p>By default, this is infinite.</p>
  5143. <p>Example configuration:</p>
  5144. <pre><code class="language-yaml">nonrefreshable_access_token_lifetime: 24h
  5145. </code></pre>
  5146. <hr />
  5147. <h2 id="metrics"><a class="header" href="#metrics">Metrics</a></h2>
  5148. <p>Config options related to metrics.</p>
  5149. <hr />
  5150. <h3 id="enable_metrics"><a class="header" href="#enable_metrics"><code>enable_metrics</code></a></h3>
  5151. <p>Set to true to enable collection and rendering of performance metrics.
  5152. Defaults to false.</p>
  5153. <p>Example configuration:</p>
  5154. <pre><code class="language-yaml">enable_metrics: true
  5155. </code></pre>
  5156. <hr />
  5157. <h3 id="enable_legacy_metrics"><a class="header" href="#enable_legacy_metrics"><code>enable_legacy_metrics</code></a></h3>
  5158. <p>Set to <code>true</code> to publish both legacy and non-legacy Prometheus metric names,
  5159. or to <code>false</code> to only publish non-legacy Prometheus metric names.
  5160. Defaults to <code>true</code>. Has no effect if <code>enable_metrics</code> is <code>false</code>.
  5161. <strong>In Synapse v1.71.0, this will default to <code>false</code> before being removed in Synapse v1.73.0.</strong></p>
  5162. <p>Legacy metric names include:</p>
  5163. <ul>
  5164. <li>metrics containing colons in the name, such as <code>synapse_util_caches_response_cache:hits</code>, because colons are supposed to be reserved for user-defined recording rules;</li>
  5165. <li>counters that don't end with the <code>_total</code> suffix, such as <code>synapse_federation_client_sent_edus</code>, therefore not adhering to the OpenMetrics standard.</li>
  5166. </ul>
  5167. <p>These legacy metric names are unconventional and not compliant with OpenMetrics standards.
  5168. They are included for backwards compatibility.</p>
  5169. <p>Example configuration:</p>
  5170. <pre><code class="language-yaml">enable_legacy_metrics: false
  5171. </code></pre>
  5172. <p>See https://github.com/matrix-org/synapse/issues/11106 for context.</p>
  5173. <p><em>Since v1.67.0.</em></p>
  5174. <h2 id="will-be-removed-in-v1730"><a class="header" href="#will-be-removed-in-v1730"><strong>Will be removed in v1.73.0.</strong></a></h2>
  5175. <h3 id="sentry"><a class="header" href="#sentry"><code>sentry</code></a></h3>
  5176. <p>Use this option to enable sentry integration. Provide the DSN assigned to you by sentry
  5177. with the <code>dsn</code> setting.</p>
  5178. <p>NOTE: While attempts are made to ensure that the logs don't contain
  5179. any sensitive information, this cannot be guaranteed. By enabling
  5180. this option the sentry server may therefore receive sensitive
  5181. information, and it in turn may then disseminate sensitive information
  5182. through insecure notification channels if so configured.</p>
  5183. <p>Example configuration:</p>
  5184. <pre><code class="language-yaml">sentry:
  5185. dsn: &quot;...&quot;
  5186. </code></pre>
  5187. <hr />
  5188. <h3 id="metrics_flags"><a class="header" href="#metrics_flags"><code>metrics_flags</code></a></h3>
  5189. <p>Flags to enable Prometheus metrics which are not suitable to be
  5190. enabled by default, either for performance reasons or limited use.
  5191. Currently the only option is <code>known_servers</code>, which publishes
  5192. <code>synapse_federation_known_servers</code>, a gauge of the number of
  5193. servers this homeserver knows about, including itself. May cause
  5194. performance problems on large homeservers.</p>
  5195. <p>Example configuration:</p>
  5196. <pre><code class="language-yaml">metrics_flags:
  5197. known_servers: true
  5198. </code></pre>
  5199. <hr />
  5200. <h3 id="report_stats"><a class="header" href="#report_stats"><code>report_stats</code></a></h3>
  5201. <p>Whether or not to report homeserver usage statistics. This is originally
  5202. set when generating the config. Set this option to true or false to change the current
  5203. behavior. See
  5204. <a href="usage/configuration/../administration/monitoring/reporting_homeserver_usage_statistics.html">Reporting Homeserver Usage Statistics</a>
  5205. for information on what data is reported.</p>
  5206. <p>Statistics will be reported 5 minutes after Synapse starts, and then every 3 hours
  5207. after that.</p>
  5208. <p>Example configuration:</p>
  5209. <pre><code class="language-yaml">report_stats: true
  5210. </code></pre>
  5211. <hr />
  5212. <h3 id="report_stats_endpoint"><a class="header" href="#report_stats_endpoint"><code>report_stats_endpoint</code></a></h3>
  5213. <p>The endpoint to report homeserver usage statistics to.
  5214. Defaults to https://matrix.org/report-usage-stats/push</p>
  5215. <p>Example configuration:</p>
  5216. <pre><code class="language-yaml">report_stats_endpoint: https://example.com/report-usage-stats/push
  5217. </code></pre>
  5218. <hr />
  5219. <h2 id="api-configuration"><a class="header" href="#api-configuration">API Configuration</a></h2>
  5220. <p>Config settings related to the client/server API</p>
  5221. <hr />
  5222. <h3 id="room_prejoin_state"><a class="header" href="#room_prejoin_state"><code>room_prejoin_state</code></a></h3>
  5223. <p>Controls for the state that is shared with users who receive an invite
  5224. to a room. By default, the following state event types are shared with users who
  5225. receive invites to the room:</p>
  5226. <ul>
  5227. <li>m.room.join_rules</li>
  5228. <li>m.room.canonical_alias</li>
  5229. <li>m.room.avatar</li>
  5230. <li>m.room.encryption</li>
  5231. <li>m.room.name</li>
  5232. <li>m.room.create</li>
  5233. <li>m.room.topic</li>
  5234. </ul>
  5235. <p>To change the default behavior, use the following sub-options:</p>
  5236. <ul>
  5237. <li><code>disable_default_event_types</code>: set to true to disable the above defaults. If this
  5238. is enabled, only the event types listed in <code>additional_event_types</code> are shared.
  5239. Defaults to false.</li>
  5240. <li><code>additional_event_types</code>: Additional state event types to share with users when they are invited
  5241. to a room. By default, this list is empty (so only the default event types are shared).</li>
  5242. </ul>
  5243. <p>Example configuration:</p>
  5244. <pre><code class="language-yaml">room_prejoin_state:
  5245. disable_default_event_types: true
  5246. additional_event_types:
  5247. - org.example.custom.event.type
  5248. - m.room.join_rules
  5249. </code></pre>
  5250. <hr />
  5251. <h3 id="track_puppeted_user_ips"><a class="header" href="#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a></h3>
  5252. <p>We record the IP address of clients used to access the API for various
  5253. reasons, including displaying it to the user in the &quot;Where you're signed in&quot;
  5254. dialog.</p>
  5255. <p>By default, when puppeting another user via the admin API, the client IP
  5256. address is recorded against the user who created the access token (ie, the
  5257. admin user), and <em>not</em> the puppeted user.</p>
  5258. <p>Set this option to true to also record the IP address against the puppeted
  5259. user. (This also means that the puppeted user will count as an &quot;active&quot; user
  5260. for the purpose of monthly active user tracking - see <code>limit_usage_by_mau</code> etc
  5261. above.)</p>
  5262. <p>Example configuration:</p>
  5263. <pre><code class="language-yaml">track_puppeted_user_ips: true
  5264. </code></pre>
  5265. <hr />
  5266. <h3 id="app_service_config_files"><a class="header" href="#app_service_config_files"><code>app_service_config_files</code></a></h3>
  5267. <p>A list of application service config files to use.</p>
  5268. <p>Example configuration:</p>
  5269. <pre><code class="language-yaml">app_service_config_files:
  5270. - app_service_1.yaml
  5271. - app_service_2.yaml
  5272. </code></pre>
  5273. <hr />
  5274. <h3 id="track_appservice_user_ips"><a class="header" href="#track_appservice_user_ips"><code>track_appservice_user_ips</code></a></h3>
  5275. <p>Defaults to false. Set to true to enable tracking of application service IP addresses.
  5276. Implicitly enables MAU tracking for application service users.</p>
  5277. <p>Example configuration:</p>
  5278. <pre><code class="language-yaml">track_appservice_user_ips: true
  5279. </code></pre>
  5280. <hr />
  5281. <h3 id="macaroon_secret_key"><a class="header" href="#macaroon_secret_key"><code>macaroon_secret_key</code></a></h3>
  5282. <p>A secret which is used to sign</p>
  5283. <ul>
  5284. <li>access token for guest users,</li>
  5285. <li>short-term login token used during SSO logins (OIDC or SAML2) and</li>
  5286. <li>token used for unsubscribing from email notifications.</li>
  5287. </ul>
  5288. <p>If none is specified, the <code>registration_shared_secret</code> is used, if one is given;
  5289. otherwise, a secret key is derived from the signing key.</p>
  5290. <p>Example configuration:</p>
  5291. <pre><code class="language-yaml">macaroon_secret_key: &lt;PRIVATE STRING&gt;
  5292. </code></pre>
  5293. <hr />
  5294. <h3 id="form_secret"><a class="header" href="#form_secret"><code>form_secret</code></a></h3>
  5295. <p>A secret which is used to calculate HMACs for form values, to stop
  5296. falsification of values. Must be specified for the User Consent
  5297. forms to work.</p>
  5298. <p>Example configuration:</p>
  5299. <pre><code class="language-yaml">form_secret: &lt;PRIVATE STRING&gt;
  5300. </code></pre>
  5301. <hr />
  5302. <h2 id="signing-keys"><a class="header" href="#signing-keys">Signing Keys</a></h2>
  5303. <p>Config options relating to signing keys</p>
  5304. <hr />
  5305. <h3 id="signing_key_path"><a class="header" href="#signing_key_path"><code>signing_key_path</code></a></h3>
  5306. <p>Path to the signing key to sign events and federation requests with.</p>
  5307. <p><em>New in Synapse 1.67</em>: If this file does not exist, Synapse will create a new signing
  5308. key on startup and store it in this file.</p>
  5309. <p>Example configuration:</p>
  5310. <pre><code class="language-yaml">signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  5311. </code></pre>
  5312. <hr />
  5313. <h3 id="old_signing_keys"><a class="header" href="#old_signing_keys"><code>old_signing_keys</code></a></h3>
  5314. <p>The keys that the server used to sign messages with but won't use
  5315. to sign new messages. For each key, <code>key</code> should be the base64-encoded public key, and
  5316. <code>expired_ts</code>should be the time (in milliseconds since the unix epoch) that
  5317. it was last used.</p>
  5318. <p>It is possible to build an entry from an old <code>signing.key</code> file using the
  5319. <code>export_signing_key</code> script which is provided with synapse.</p>
  5320. <p>Example configuration:</p>
  5321. <pre><code class="language-yaml">old_signing_keys:
  5322. &quot;ed25519:id&quot;: { key: &quot;base64string&quot;, expired_ts: 123456789123 }
  5323. </code></pre>
  5324. <hr />
  5325. <h3 id="key_refresh_interval"><a class="header" href="#key_refresh_interval"><code>key_refresh_interval</code></a></h3>
  5326. <p>How long key response published by this server is valid for.
  5327. Used to set the <code>valid_until_ts</code> in <code>/key/v2</code> APIs.
  5328. Determines how quickly servers will query to check which keys
  5329. are still valid. Defaults to 1d.</p>
  5330. <p>Example configuration:</p>
  5331. <pre><code class="language-yaml">key_refresh_interval: 2d
  5332. </code></pre>
  5333. <hr />
  5334. <h3 id="trusted_key_servers"><a class="header" href="#trusted_key_servers"><code>trusted_key_servers</code></a></h3>
  5335. <p>The trusted servers to download signing keys from.</p>
  5336. <p>When we need to fetch a signing key, each server is tried in parallel.</p>
  5337. <p>Normally, the connection to the key server is validated via TLS certificates.
  5338. Additional security can be provided by configuring a <code>verify key</code>, which
  5339. will make synapse check that the response is signed by that key.</p>
  5340. <p>This setting supercedes an older setting named <code>perspectives</code>. The old format
  5341. is still supported for backwards-compatibility, but it is deprecated.</p>
  5342. <p><code>trusted_key_servers</code> defaults to matrix.org, but using it will generate a
  5343. warning on start-up. To suppress this warning, set
  5344. <code>suppress_key_server_warning</code> to true.</p>
  5345. <p>Options for each entry in the list include:</p>
  5346. <ul>
  5347. <li><code>server_name</code>: the name of the server. Required.</li>
  5348. <li><code>verify_keys</code>: an optional map from key id to base64-encoded public key.
  5349. If specified, we will check that the response is signed by at least
  5350. one of the given keys.</li>
  5351. <li><code>accept_keys_insecurely</code>: a boolean. Normally, if <code>verify_keys</code> is unset,
  5352. and <code>federation_verify_certificates</code> is not <code>true</code>, synapse will refuse
  5353. to start, because this would allow anyone who can spoof DNS responses
  5354. to masquerade as the trusted key server. If you know what you are doing
  5355. and are sure that your network environment provides a secure connection
  5356. to the key server, you can set this to <code>true</code> to override this behaviour.</li>
  5357. </ul>
  5358. <p>Example configuration #1:</p>
  5359. <pre><code class="language-yaml">trusted_key_servers:
  5360. - server_name: &quot;my_trusted_server.example.com&quot;
  5361. verify_keys:
  5362. &quot;ed25519:auto&quot;: &quot;abcdefghijklmnopqrstuvwxyzabcdefghijklmopqr&quot;
  5363. - server_name: &quot;my_other_trusted_server.example.com&quot;
  5364. </code></pre>
  5365. <p>Example configuration #2:</p>
  5366. <pre><code class="language-yaml">trusted_key_servers:
  5367. - server_name: &quot;matrix.org&quot;
  5368. </code></pre>
  5369. <hr />
  5370. <h3 id="suppress_key_server_warning"><a class="header" href="#suppress_key_server_warning"><code>suppress_key_server_warning</code></a></h3>
  5371. <p>Set the following to true to disable the warning that is emitted when the
  5372. <code>trusted_key_servers</code> include 'matrix.org'. See above.</p>
  5373. <p>Example configuration:</p>
  5374. <pre><code class="language-yaml">suppress_key_server_warning: true
  5375. </code></pre>
  5376. <hr />
  5377. <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>
  5378. <p>The signing keys to use when acting as a trusted key server. If not specified
  5379. defaults to the server signing key.</p>
  5380. <p>Can contain multiple keys, one per line.</p>
  5381. <p>Example configuration:</p>
  5382. <pre><code class="language-yaml">key_server_signing_keys_path: &quot;key_server_signing_keys.key&quot;
  5383. </code></pre>
  5384. <hr />
  5385. <h2 id="single-sign-on-integration"><a class="header" href="#single-sign-on-integration">Single sign-on integration</a></h2>
  5386. <p>The following settings can be used to make Synapse use a single sign-on
  5387. provider for authentication, instead of its internal password database.</p>
  5388. <p>You will probably also want to set the following options to <code>false</code> to
  5389. disable the regular login/registration flows:</p>
  5390. <ul>
  5391. <li><a href="usage/configuration/config_documentation.html#enable_registration"><code>enable_registration</code></a></li>
  5392. <li><a href="usage/configuration/config_documentation.html#password_config"><code>password_config.enabled</code></a></li>
  5393. </ul>
  5394. <hr />
  5395. <h3 id="saml2_config"><a class="header" href="#saml2_config"><code>saml2_config</code></a></h3>
  5396. <p>Enable SAML2 for registration and login. Uses pysaml2. To learn more about pysaml and
  5397. to find a full list options for configuring pysaml, read the docs <a href="https://pysaml2.readthedocs.io/en/latest/">here</a>.</p>
  5398. <p>At least one of <code>sp_config</code> or <code>config_path</code> must be set in this section to
  5399. enable SAML login. You can either put your entire pysaml config inline using the <code>sp_config</code>
  5400. option, or you can specify a path to a psyaml config file with the sub-option <code>config_path</code>.
  5401. This setting has the following sub-options:</p>
  5402. <ul>
  5403. <li><code>sp_config</code>: the configuration for the pysaml2 Service Provider. See pysaml2 docs for format of config.
  5404. Default values will be used for the <code>entityid</code> and <code>service</code> settings,
  5405. so it is not normally necessary to specify them unless you need to
  5406. override them. Here are a few useful sub-options for configuring pysaml:
  5407. <ul>
  5408. <li><code>metadata</code>: Point this to the IdP's metadata. You must provide either a local
  5409. file via the <code>local</code> attribute or (preferably) a URL via the
  5410. <code>remote</code> attribute.</li>
  5411. <li><code>accepted_time_diff: 3</code>: Allowed clock difference in seconds between the homeserver and IdP.
  5412. Defaults to 0.</li>
  5413. <li><code>service</code>: By default, the user has to go to our login page first. If you'd like
  5414. to allow IdP-initiated login, set <code>allow_unsolicited</code> to true under <code>sp</code> in the <code>service</code>
  5415. section.</li>
  5416. </ul>
  5417. </li>
  5418. <li><code>config_path</code>: specify a separate pysaml2 configuration file thusly:
  5419. <code>config_path: &quot;CONFDIR/sp_conf.py&quot;</code></li>
  5420. <li><code>saml_session_lifetime</code>: The lifetime of a SAML session. This defines how long a user has to
  5421. complete the authentication process, if <code>allow_unsolicited</code> is unset. The default is 15 minutes.</li>
  5422. <li><code>user_mapping_provider</code>: Using this option, an external module can be provided as a
  5423. custom solution to mapping attributes returned from a saml provider onto a matrix user. The
  5424. <code>user_mapping_provider</code> has the following attributes:
  5425. <ul>
  5426. <li><code>module</code>: The custom module's class.</li>
  5427. <li><code>config</code>: Custom configuration values for the module. Use the values provided in the
  5428. example if you are using the built-in user_mapping_provider, or provide your own
  5429. config values for a custom class if you are using one. This section will be passed as a Python
  5430. dictionary to the module's <code>parse_config</code> method. The built-in provider takes the following two
  5431. options:
  5432. <ul>
  5433. <li><code>mxid_source_attribute</code>: The SAML attribute (after mapping via the attribute maps) to use
  5434. to derive the Matrix ID from. It is 'uid' by default. Note: This used to be configured by the
  5435. <code>saml2_config.mxid_source_attribute option</code>. If that is still defined, its value will be used instead.</li>
  5436. <li><code>mxid_mapping</code>: The mapping system to use for mapping the saml attribute onto a
  5437. matrix ID. Options include: <code>hexencode</code> (which maps unpermitted characters to '=xx')
  5438. and <code>dotreplace</code> (which replaces unpermitted characters with '.').
  5439. The default is <code>hexencode</code>. Note: This used to be configured by the
  5440. <code>saml2_config.mxid_mapping option</code>. If that is still defined, its value will be used instead.</li>
  5441. </ul>
  5442. </li>
  5443. </ul>
  5444. </li>
  5445. <li><code>grandfathered_mxid_source_attribute</code>: In previous versions of synapse, the mapping from SAML attribute to
  5446. MXID was always calculated dynamically rather than stored in a table. For backwards- compatibility, we will look for <code>user_ids</code>
  5447. matching such a pattern before creating a new account. This setting controls the SAML attribute which will be used for this
  5448. backwards-compatibility lookup. Typically it should be 'uid', but if the attribute maps are changed, it may be necessary to change it.
  5449. The default is 'uid'.</li>
  5450. <li><code>attribute_requirements</code>: It is possible to configure Synapse to only allow logins if SAML attributes
  5451. match particular values. The requirements can be listed under
  5452. <code>attribute_requirements</code> as shown in the example. All of the listed attributes must
  5453. match for the login to be permitted.</li>
  5454. <li><code>idp_entityid</code>: If the metadata XML contains multiple IdP entities then the <code>idp_entityid</code>
  5455. option must be set to the entity to redirect users to.
  5456. Most deployments only have a single IdP entity and so should omit this option.</li>
  5457. </ul>
  5458. <p>Once SAML support is enabled, a metadata file will be exposed at
  5459. <code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/metadata.xml</code>, which you may be able to
  5460. use to configure your SAML IdP with. Alternatively, you can manually configure
  5461. the IdP to use an ACS location of
  5462. <code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/authn_response</code>.</p>
  5463. <p>Example configuration:</p>
  5464. <pre><code class="language-yaml">saml2_config:
  5465. sp_config:
  5466. metadata:
  5467. local: [&quot;saml2/idp.xml&quot;]
  5468. remote:
  5469. - url: https://our_idp/metadata.xml
  5470. accepted_time_diff: 3
  5471. service:
  5472. sp:
  5473. allow_unsolicited: true
  5474. # The examples below are just used to generate our metadata xml, and you
  5475. # may well not need them, depending on your setup. Alternatively you
  5476. # may need a whole lot more detail - see the pysaml2 docs!
  5477. description: [&quot;My awesome SP&quot;, &quot;en&quot;]
  5478. name: [&quot;Test SP&quot;, &quot;en&quot;]
  5479. ui_info:
  5480. display_name:
  5481. - lang: en
  5482. text: &quot;Display Name is the descriptive name of your service.&quot;
  5483. description:
  5484. - lang: en
  5485. text: &quot;Description should be a short paragraph explaining the purpose of the service.&quot;
  5486. information_url:
  5487. - lang: en
  5488. text: &quot;https://example.com/terms-of-service&quot;
  5489. privacy_statement_url:
  5490. - lang: en
  5491. text: &quot;https://example.com/privacy-policy&quot;
  5492. keywords:
  5493. - lang: en
  5494. text: [&quot;Matrix&quot;, &quot;Element&quot;]
  5495. logo:
  5496. - lang: en
  5497. text: &quot;https://example.com/logo.svg&quot;
  5498. width: &quot;200&quot;
  5499. height: &quot;80&quot;
  5500. organization:
  5501. name: Example com
  5502. display_name:
  5503. - [&quot;Example co&quot;, &quot;en&quot;]
  5504. url: &quot;http://example.com&quot;
  5505. contact_person:
  5506. - given_name: Bob
  5507. sur_name: &quot;the Sysadmin&quot;
  5508. email_address&quot;: [&quot;admin@example.com&quot;]
  5509. contact_type&quot;: technical
  5510. saml_session_lifetime: 5m
  5511. user_mapping_provider:
  5512. # Below options are intended for the built-in provider, they should be
  5513. # changed if using a custom module.
  5514. config:
  5515. mxid_source_attribute: displayName
  5516. mxid_mapping: dotreplace
  5517. grandfathered_mxid_source_attribute: upn
  5518. attribute_requirements:
  5519. - attribute: userGroup
  5520. value: &quot;staff&quot;
  5521. - attribute: department
  5522. value: &quot;sales&quot;
  5523. idp_entityid: 'https://our_idp/entityid'
  5524. </code></pre>
  5525. <hr />
  5526. <h3 id="oidc_providers"><a class="header" href="#oidc_providers"><code>oidc_providers</code></a></h3>
  5527. <p>List of OpenID Connect (OIDC) / OAuth 2.0 identity providers, for registration
  5528. and login. See <a href="usage/configuration/../../openid.html">here</a>
  5529. for information on how to configure these options.</p>
  5530. <p>For backwards compatibility, it is also possible to configure a single OIDC
  5531. provider via an <code>oidc_config</code> setting. This is now deprecated and admins are
  5532. advised to migrate to the <code>oidc_providers</code> format. (When doing that migration,
  5533. use <code>oidc</code> for the <code>idp_id</code> to ensure that existing users continue to be
  5534. recognised.)</p>
  5535. <p>Options for each entry include:</p>
  5536. <ul>
  5537. <li>
  5538. <p><code>idp_id</code>: a unique identifier for this identity provider. Used internally
  5539. by Synapse; should be a single word such as 'github'.
  5540. Note that, if this is changed, users authenticating via that provider
  5541. will no longer be recognised as the same user!
  5542. (Use &quot;oidc&quot; here if you are migrating from an old <code>oidc_config</code> configuration.)</p>
  5543. </li>
  5544. <li>
  5545. <p><code>idp_name</code>: A user-facing name for this identity provider, which is used to
  5546. offer the user a choice of login mechanisms.</p>
  5547. </li>
  5548. <li>
  5549. <p><code>idp_icon</code>: An optional icon for this identity provider, which is presented
  5550. by clients and Synapse's own IdP picker page. If given, must be an
  5551. MXC URI of the format mxc://<server-name>/<media-id>. (An easy way to
  5552. obtain such an MXC URI is to upload an image to an (unencrypted) room
  5553. and then copy the &quot;url&quot; from the source of the event.)</p>
  5554. </li>
  5555. <li>
  5556. <p><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
  5557. to style the login flow according to the identity provider in question.
  5558. See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</p>
  5559. </li>
  5560. <li>
  5561. <p><code>discover</code>: set to false to disable the use of the OIDC discovery mechanism
  5562. to discover endpoints. Defaults to true.</p>
  5563. </li>
  5564. <li>
  5565. <p><code>issuer</code>: Required. The OIDC issuer. Used to validate tokens and (if discovery
  5566. is enabled) to discover the provider's endpoints.</p>
  5567. </li>
  5568. <li>
  5569. <p><code>client_id</code>: Required. oauth2 client id to use.</p>
  5570. </li>
  5571. <li>
  5572. <p><code>client_secret</code>: oauth2 client secret to use. May be omitted if
  5573. <code>client_secret_jwt_key</code> is given, or if <code>client_auth_method</code> is 'none'.</p>
  5574. </li>
  5575. <li>
  5576. <p><code>client_secret_jwt_key</code>: Alternative to client_secret: details of a key used
  5577. to create a JSON Web Token to be used as an OAuth2 client secret. If
  5578. given, must be a dictionary with the following properties:</p>
  5579. <ul>
  5580. <li>
  5581. <p><code>key</code>: a pem-encoded signing key. Must be a suitable key for the
  5582. algorithm specified. Required unless <code>key_file</code> is given.</p>
  5583. </li>
  5584. <li>
  5585. <p><code>key_file</code>: the path to file containing a pem-encoded signing key file.
  5586. Required unless <code>key</code> is given.</p>
  5587. </li>
  5588. <li>
  5589. <p><code>jwt_header</code>: a dictionary giving properties to include in the JWT
  5590. header. Must include the key <code>alg</code>, giving the algorithm used to
  5591. sign the JWT, such as &quot;ES256&quot;, using the JWA identifiers in
  5592. RFC7518.</p>
  5593. </li>
  5594. <li>
  5595. <p><code>jwt_payload</code>: an optional dictionary giving properties to include in
  5596. the JWT payload. Normally this should include an <code>iss</code> key.</p>
  5597. </li>
  5598. </ul>
  5599. </li>
  5600. <li>
  5601. <p><code>client_auth_method</code>: auth method to use when exchanging the token. Valid
  5602. values are <code>client_secret_basic</code> (default), <code>client_secret_post</code> and
  5603. <code>none</code>.</p>
  5604. </li>
  5605. <li>
  5606. <p><code>scopes</code>: list of scopes to request. This should normally include the &quot;openid&quot;
  5607. scope. Defaults to [&quot;openid&quot;].</p>
  5608. </li>
  5609. <li>
  5610. <p><code>authorization_endpoint</code>: the oauth2 authorization endpoint. Required if
  5611. provider discovery is disabled.</p>
  5612. </li>
  5613. <li>
  5614. <p><code>token_endpoint</code>: the oauth2 token endpoint. Required if provider discovery is
  5615. disabled.</p>
  5616. </li>
  5617. <li>
  5618. <p><code>userinfo_endpoint</code>: the OIDC userinfo endpoint. Required if discovery is
  5619. disabled and the 'openid' scope is not requested.</p>
  5620. </li>
  5621. <li>
  5622. <p><code>jwks_uri</code>: URI where to fetch the JWKS. Required if discovery is disabled and
  5623. the 'openid' scope is used.</p>
  5624. </li>
  5625. <li>
  5626. <p><code>skip_verification</code>: set to 'true' to skip metadata verification. Use this if
  5627. you are connecting to a provider that is not OpenID Connect compliant.
  5628. Defaults to false. Avoid this in production.</p>
  5629. </li>
  5630. <li>
  5631. <p><code>user_profile_method</code>: Whether to fetch the user profile from the userinfo
  5632. endpoint, or to rely on the data returned in the id_token from the <code>token_endpoint</code>.
  5633. Valid values are: <code>auto</code> or <code>userinfo_endpoint</code>.
  5634. Defaults to <code>auto</code>, which uses the userinfo endpoint if <code>openid</code> is
  5635. not included in <code>scopes</code>. Set to <code>userinfo_endpoint</code> to always use the
  5636. userinfo endpoint.</p>
  5637. </li>
  5638. <li>
  5639. <p><code>allow_existing_users</code>: set to true to allow a user logging in via OIDC to
  5640. match a pre-existing account instead of failing. This could be used if
  5641. switching from password logins to OIDC. Defaults to false.</p>
  5642. </li>
  5643. <li>
  5644. <p><code>user_mapping_provider</code>: Configuration for how attributes returned from a OIDC
  5645. provider are mapped onto a matrix user. This setting has the following
  5646. sub-properties:</p>
  5647. <ul>
  5648. <li>
  5649. <p><code>module</code>: The class name of a custom mapping module. Default is
  5650. <code>synapse.handlers.oidc.JinjaOidcMappingProvider</code>.
  5651. See <a href="usage/configuration/../../sso_mapping_providers.html#openid-mapping-providers">OpenID Mapping Providers</a>
  5652. for information on implementing a custom mapping provider.</p>
  5653. </li>
  5654. <li>
  5655. <p><code>config</code>: Configuration for the mapping provider module. This section will
  5656. be passed as a Python dictionary to the user mapping provider
  5657. module's <code>parse_config</code> method.</p>
  5658. <p>For the default provider, the following settings are available:</p>
  5659. <ul>
  5660. <li>
  5661. <p>subject_claim: name of the claim containing a unique identifier
  5662. for the user. Defaults to 'sub', which OpenID Connect
  5663. compliant providers should provide.</p>
  5664. </li>
  5665. <li>
  5666. <p><code>localpart_template</code>: Jinja2 template for the localpart of the MXID.
  5667. If this is not set, the user will be prompted to choose their
  5668. own username (see the documentation for the <code>sso_auth_account_details.html</code>
  5669. template). This template can use the <code>localpart_from_email</code> filter.</p>
  5670. </li>
  5671. <li>
  5672. <p><code>confirm_localpart</code>: Whether to prompt the user to validate (or
  5673. change) the generated localpart (see the documentation for the
  5674. 'sso_auth_account_details.html' template), instead of
  5675. registering the account right away.</p>
  5676. </li>
  5677. <li>
  5678. <p><code>display_name_template</code>: Jinja2 template for the display name to set
  5679. on first login. If unset, no displayname will be set.</p>
  5680. </li>
  5681. <li>
  5682. <p><code>email_template</code>: Jinja2 template for the email address of the user.
  5683. If unset, no email address will be added to the account.</p>
  5684. </li>
  5685. <li>
  5686. <p><code>extra_attributes</code>: a map of Jinja2 templates for extra attributes
  5687. to send back to the client during login. Note that these are non-standard and clients will ignore them
  5688. without modifications.</p>
  5689. </li>
  5690. </ul>
  5691. </li>
  5692. </ul>
  5693. <p>When rendering, the Jinja2 templates are given a 'user' variable,
  5694. which is set to the claims returned by the UserInfo Endpoint and/or
  5695. in the ID Token.</p>
  5696. </li>
  5697. </ul>
  5698. <p>It is possible to configure Synapse to only allow logins if certain attributes
  5699. match particular values in the OIDC userinfo. The requirements can be listed under
  5700. <code>attribute_requirements</code> as shown here:</p>
  5701. <pre><code class="language-yaml">attribute_requirements:
  5702. - attribute: family_name
  5703. value: &quot;Stephensson&quot;
  5704. - attribute: groups
  5705. value: &quot;admin&quot;
  5706. </code></pre>
  5707. <p>All of the listed attributes must match for the login to be permitted. Additional attributes can be added to
  5708. userinfo by expanding the <code>scopes</code> section of the OIDC config to retrieve
  5709. additional information from the OIDC provider.</p>
  5710. <p>If the OIDC claim is a list, then the attribute must match any value in the list.
  5711. Otherwise, it must exactly match the value of the claim. Using the example
  5712. above, the <code>family_name</code> claim MUST be &quot;Stephensson&quot;, but the <code>groups</code>
  5713. claim MUST contain &quot;admin&quot;.</p>
  5714. <p>Example configuration:</p>
  5715. <pre><code class="language-yaml">oidc_providers:
  5716. # Generic example
  5717. #
  5718. - idp_id: my_idp
  5719. idp_name: &quot;My OpenID provider&quot;
  5720. idp_icon: &quot;mxc://example.com/mediaid&quot;
  5721. discover: false
  5722. issuer: &quot;https://accounts.example.com/&quot;
  5723. client_id: &quot;provided-by-your-issuer&quot;
  5724. client_secret: &quot;provided-by-your-issuer&quot;
  5725. client_auth_method: client_secret_post
  5726. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  5727. authorization_endpoint: &quot;https://accounts.example.com/oauth2/auth&quot;
  5728. token_endpoint: &quot;https://accounts.example.com/oauth2/token&quot;
  5729. userinfo_endpoint: &quot;https://accounts.example.com/userinfo&quot;
  5730. jwks_uri: &quot;https://accounts.example.com/.well-known/jwks.json&quot;
  5731. skip_verification: true
  5732. user_mapping_provider:
  5733. config:
  5734. subject_claim: &quot;id&quot;
  5735. localpart_template: &quot;{{ user.login }}&quot;
  5736. display_name_template: &quot;{{ user.name }}&quot;
  5737. email_template: &quot;{{ user.email }}&quot;
  5738. attribute_requirements:
  5739. - attribute: userGroup
  5740. value: &quot;synapseUsers&quot;
  5741. </code></pre>
  5742. <hr />
  5743. <h3 id="cas_config"><a class="header" href="#cas_config"><code>cas_config</code></a></h3>
  5744. <p>Enable Central Authentication Service (CAS) for registration and login.
  5745. Has the following sub-options:</p>
  5746. <ul>
  5747. <li><code>enabled</code>: Set this to true to enable authorization against a CAS server.
  5748. Defaults to false.</li>
  5749. <li><code>server_url</code>: The URL of the CAS authorization endpoint.</li>
  5750. <li><code>displayname_attribute</code>: The attribute of the CAS response to use as the display name.
  5751. If no name is given here, no displayname will be set.</li>
  5752. <li><code>required_attributes</code>: It is possible to configure Synapse to only allow logins if CAS attributes
  5753. match particular values. All of the keys given below must exist
  5754. and the values must match the given value. Alternately if the given value
  5755. is <code>None</code> then any value is allowed (the attribute just must exist).
  5756. All of the listed attributes must match for the login to be permitted.</li>
  5757. </ul>
  5758. <p>Example configuration:</p>
  5759. <pre><code class="language-yaml">cas_config:
  5760. enabled: true
  5761. server_url: &quot;https://cas-server.com&quot;
  5762. displayname_attribute: name
  5763. required_attributes:
  5764. userGroup: &quot;staff&quot;
  5765. department: None
  5766. </code></pre>
  5767. <hr />
  5768. <h3 id="sso"><a class="header" href="#sso"><code>sso</code></a></h3>
  5769. <p>Additional settings to use with single-sign on systems such as OpenID Connect,
  5770. SAML2 and CAS.</p>
  5771. <p>Server admins can configure custom templates for pages related to SSO. See
  5772. <a href="usage/configuration/../../templates.html">here</a> for more information.</p>
  5773. <p>Options include:</p>
  5774. <ul>
  5775. <li><code>client_whitelist</code>: A list of client URLs which are whitelisted so that the user does not
  5776. have to confirm giving access to their account to the URL. Any client
  5777. whose URL starts with an entry in the following list will not be subject
  5778. to an additional confirmation step after the SSO login is completed.
  5779. WARNING: An entry such as &quot;https://my.client&quot; is insecure, because it
  5780. will also match &quot;https://my.client.evil.site&quot;, exposing your users to
  5781. phishing attacks from evil.site. To avoid this, include a slash after the
  5782. hostname: &quot;https://my.client/&quot;.
  5783. The login fallback page (used by clients that don't natively support the
  5784. required login flows) is whitelisted in addition to any URLs in this list.
  5785. By default, this list contains only the login fallback page.</li>
  5786. <li><code>update_profile_information</code>: Use this setting to keep a user's profile fields in sync with information from
  5787. the identity provider. Currently only syncing the displayname is supported. Fields
  5788. are checked on every SSO login, and are updated if necessary.
  5789. Note that enabling this option will override user profile information,
  5790. regardless of whether users have opted-out of syncing that
  5791. information when first signing in. Defaults to false.</li>
  5792. </ul>
  5793. <p>Example configuration:</p>
  5794. <pre><code class="language-yaml">sso:
  5795. client_whitelist:
  5796. - https://riot.im/develop
  5797. - https://my.custom.client/
  5798. update_profile_information: true
  5799. </code></pre>
  5800. <hr />
  5801. <h3 id="jwt_config"><a class="header" href="#jwt_config"><code>jwt_config</code></a></h3>
  5802. <p>JSON web token integration. The following settings can be used to make
  5803. Synapse JSON web tokens for authentication, instead of its internal
  5804. password database.</p>
  5805. <p>Each JSON Web Token needs to contain a &quot;sub&quot; (subject) claim, which is
  5806. used as the localpart of the mxid.</p>
  5807. <p>Additionally, the expiration time (&quot;exp&quot;), not before time (&quot;nbf&quot;),
  5808. and issued at (&quot;iat&quot;) claims are validated if present.</p>
  5809. <p>Note that this is a non-standard login type and client support is
  5810. expected to be non-existent.</p>
  5811. <p>See <a href="usage/configuration/../../jwt.html">here</a> for more.</p>
  5812. <p>Additional sub-options for this setting include:</p>
  5813. <ul>
  5814. <li><code>enabled</code>: Set to true to enable authorization using JSON web
  5815. tokens. Defaults to false.</li>
  5816. <li><code>secret</code>: This is either the private shared secret or the public key used to
  5817. decode the contents of the JSON web token. Required if <code>enabled</code> is set to true.</li>
  5818. <li><code>algorithm</code>: The algorithm used to sign (or HMAC) the JSON web token.
  5819. Supported algorithms are listed
  5820. <a href="https://docs.authlib.org/en/latest/specs/rfc7518.html">here (section JWS)</a>.
  5821. Required if <code>enabled</code> is set to true.</li>
  5822. <li><code>subject_claim</code>: Name of the claim containing a unique identifier for the user.
  5823. Optional, defaults to <code>sub</code>.</li>
  5824. <li><code>issuer</code>: The issuer to validate the &quot;iss&quot; claim against. Optional. If provided the
  5825. &quot;iss&quot; claim will be required and validated for all JSON web tokens.</li>
  5826. <li><code>audiences</code>: A list of audiences to validate the &quot;aud&quot; claim against. Optional.
  5827. If provided the &quot;aud&quot; claim will be required and validated for all JSON web tokens.
  5828. Note that if the &quot;aud&quot; claim is included in a JSON web token then
  5829. validation will fail without configuring audiences.</li>
  5830. </ul>
  5831. <p>Example configuration:</p>
  5832. <pre><code class="language-yaml">jwt_config:
  5833. enabled: true
  5834. secret: &quot;provided-by-your-issuer&quot;
  5835. algorithm: &quot;provided-by-your-issuer&quot;
  5836. subject_claim: &quot;name_of_claim&quot;
  5837. issuer: &quot;provided-by-your-issuer&quot;
  5838. audiences:
  5839. - &quot;provided-by-your-issuer&quot;
  5840. </code></pre>
  5841. <hr />
  5842. <h3 id="password_config"><a class="header" href="#password_config"><code>password_config</code></a></h3>
  5843. <p>Use this setting to enable password-based logins.</p>
  5844. <p>This setting has the following sub-options:</p>
  5845. <ul>
  5846. <li><code>enabled</code>: Defaults to true.
  5847. Set to false to disable password authentication.
  5848. Set to <code>only_for_reauth</code> to allow users with existing passwords to use them
  5849. to log in and reauthenticate, whilst preventing new users from setting passwords.</li>
  5850. <li><code>localdb_enabled</code>: Set to false to disable authentication against the local password
  5851. database. This is ignored if <code>enabled</code> is false, and is only useful
  5852. if you have other <code>password_providers</code>. Defaults to true.</li>
  5853. <li><code>pepper</code>: Set the value here to a secret random string for extra security.
  5854. DO NOT CHANGE THIS AFTER INITIAL SETUP!</li>
  5855. <li><code>policy</code>: Define and enforce a password policy, such as minimum lengths for passwords, etc.
  5856. Each parameter is optional. This is an implementation of MSC2000. Parameters are as follows:
  5857. <ul>
  5858. <li><code>enabled</code>: Defaults to false. Set to true to enable.</li>
  5859. <li><code>minimum_length</code>: Minimum accepted length for a password. Defaults to 0.</li>
  5860. <li><code>require_digit</code>: Whether a password must contain at least one digit.
  5861. Defaults to false.</li>
  5862. <li><code>require_symbol</code>: Whether a password must contain at least one symbol.
  5863. A symbol is any character that's not a number or a letter. Defaults to false.</li>
  5864. <li><code>require_lowercase</code>: Whether a password must contain at least one lowercase letter.
  5865. Defaults to false.</li>
  5866. <li><code>require_uppercase</code>: Whether a password must contain at least one uppercase letter.
  5867. Defaults to false.</li>
  5868. </ul>
  5869. </li>
  5870. </ul>
  5871. <p>Example configuration:</p>
  5872. <pre><code class="language-yaml">password_config:
  5873. enabled: false
  5874. localdb_enabled: false
  5875. pepper: &quot;EVEN_MORE_SECRET&quot;
  5876. policy:
  5877. enabled: true
  5878. minimum_length: 15
  5879. require_digit: true
  5880. require_symbol: true
  5881. require_lowercase: true
  5882. require_uppercase: true
  5883. </code></pre>
  5884. <hr />
  5885. <h3 id="ui_auth"><a class="header" href="#ui_auth"><code>ui_auth</code></a></h3>
  5886. <p>The amount of time to allow a user-interactive authentication session to be active.</p>
  5887. <p>This defaults to 0, meaning the user is queried for their credentials
  5888. before every action, but this can be overridden to allow a single
  5889. validation to be re-used. This weakens the protections afforded by
  5890. the user-interactive authentication process, by allowing for multiple
  5891. (and potentially different) operations to use the same validation session.</p>
  5892. <p>This is ignored for potentially &quot;dangerous&quot; operations (including
  5893. deactivating an account, modifying an account password, and
  5894. adding a 3PID).</p>
  5895. <p>Use the <code>session_timeout</code> sub-option here to change the time allowed for credential validation.</p>
  5896. <p>Example configuration:</p>
  5897. <pre><code class="language-yaml">ui_auth:
  5898. session_timeout: &quot;15s&quot;
  5899. </code></pre>
  5900. <hr />
  5901. <h3 id="email-3"><a class="header" href="#email-3"><code>email</code></a></h3>
  5902. <p>Configuration for sending emails from Synapse.</p>
  5903. <p>Server admins can configure custom templates for email content. See
  5904. <a href="usage/configuration/../../templates.html">here</a> for more information.</p>
  5905. <p>This setting has the following sub-options:</p>
  5906. <ul>
  5907. <li>
  5908. <p><code>smtp_host</code>: The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.</p>
  5909. </li>
  5910. <li>
  5911. <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>
  5912. <p><em>Changed in Synapse 1.64.0:</em> the default port is now aware of <code>force_tls</code>.</p>
  5913. </li>
  5914. <li>
  5915. <p><code>smtp_user</code> and <code>smtp_pass</code>: Username/password for authentication to the SMTP server. By default, no
  5916. authentication is attempted.</p>
  5917. </li>
  5918. <li>
  5919. <p><code>force_tls</code>: By default, Synapse connects over plain text and then optionally upgrades
  5920. to TLS via STARTTLS. If this option is set to true, TLS is used from the start (Implicit TLS),
  5921. and the option <code>require_transport_security</code> is ignored.
  5922. It is recommended to enable this if supported by your mail server.</p>
  5923. <p><em>New in Synapse 1.64.0.</em></p>
  5924. </li>
  5925. <li>
  5926. <p><code>require_transport_security</code>: Set to true to require TLS transport security for SMTP.
  5927. By default, Synapse will connect over plain text, and will then switch to
  5928. TLS via STARTTLS <em>if the SMTP server supports it</em>. If this option is set,
  5929. Synapse will refuse to connect unless the server supports STARTTLS.</p>
  5930. </li>
  5931. <li>
  5932. <p><code>enable_tls</code>: By default, if the server supports TLS, it will be used, and the server
  5933. must present a certificate that is valid for 'smtp_host'. If this option
  5934. is set to false, TLS will not be used.</p>
  5935. </li>
  5936. <li>
  5937. <p><code>notif_from</code>: defines the &quot;From&quot; address to use when sending emails.
  5938. It must be set if email sending is enabled. The placeholder '%(app)s' will be replaced by the application name,
  5939. which is normally set in <code>app_name</code>, but may be overridden by the
  5940. Matrix client application. Note that the placeholder must be written '%(app)s', including the
  5941. trailing 's'.</p>
  5942. </li>
  5943. <li>
  5944. <p><code>app_name</code>: <code>app_name</code> defines the default value for '%(app)s' in <code>notif_from</code> and email
  5945. subjects. It defaults to 'Matrix'.</p>
  5946. </li>
  5947. <li>
  5948. <p><code>enable_notifs</code>: Set to true to enable sending emails for messages that the user
  5949. has missed. Disabled by default.</p>
  5950. </li>
  5951. <li>
  5952. <p><code>notif_for_new_users</code>: Set to false to disable automatic subscription to email
  5953. notifications for new users. Enabled by default.</p>
  5954. </li>
  5955. <li>
  5956. <p><code>client_base_url</code>: Custom URL for client links within the email notifications. By default
  5957. links will be based on &quot;https://matrix.to&quot;. (This setting used to be called <code>riot_base_url</code>;
  5958. the old name is still supported for backwards-compatibility but is now deprecated.)</p>
  5959. </li>
  5960. <li>
  5961. <p><code>validation_token_lifetime</code>: Configures the time that a validation email will expire after sending.
  5962. Defaults to 1h.</p>
  5963. </li>
  5964. <li>
  5965. <p><code>invite_client_location</code>: The web client location to direct users to during an invite. This is passed
  5966. to the identity server as the <code>org.matrix.web_client_location</code> key. Defaults
  5967. to unset, giving no guidance to the identity server.</p>
  5968. </li>
  5969. <li>
  5970. <p><code>subjects</code>: Subjects to use when sending emails from Synapse. The placeholder '%(app)s' will
  5971. be replaced with the value of the <code>app_name</code> setting, or by a value dictated by the Matrix client application.
  5972. In addition, each subject can use the following placeholders: '%(person)s', which will be replaced by the displayname
  5973. 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
  5974. message(s) have been sent to, e.g. &quot;My super room&quot;. In addition, emails related to account administration will
  5975. can use the '%(server_name)s' placeholder, which will be replaced by the value of the
  5976. <code>server_name</code> setting in your Synapse configuration.</p>
  5977. <p>Here is a list of subjects for notification emails that can be set:</p>
  5978. <ul>
  5979. <li><code>message_from_person_in_room</code>: Subject to use to notify about one message from one or more user(s) in a
  5980. 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>
  5981. <li><code>message_from_person</code>: Subject to use to notify about one message from one or more user(s) in a
  5982. room which doesn't have a name. Defaults to &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;</li>
  5983. <li><code>messages_from_person</code>: Subject to use to notify about multiple messages from one or more users in
  5984. a room which doesn't have a name. Defaults to &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;</li>
  5985. <li><code>messages_in_room</code>: Subject to use to notify about multiple messages in a room which has a
  5986. name. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;</li>
  5987. <li><code>messages_in_room_and_others</code>: Subject to use to notify about multiple messages in multiple rooms.
  5988. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;</li>
  5989. <li><code>messages_from_person_and_others</code>: Subject to use to notify about multiple messages from multiple persons in
  5990. multiple rooms. This is similar to the setting above except it's used when
  5991. the room in which the notification was triggered has no name. Defaults to
  5992. &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;</li>
  5993. <li><code>invite_from_person_to_room</code>: Subject to use to notify about an invite to a room which has a name.
  5994. Defaults to &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;</li>
  5995. <li><code>invite_from_person</code>: Subject to use to notify about an invite to a room which doesn't have a
  5996. name. Defaults to &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;</li>
  5997. <li><code>password_reset</code>: Subject to use when sending a password reset email. Defaults to &quot;[%(server_name)s] Password reset&quot;</li>
  5998. <li><code>email_validation</code>: Subject to use when sending a verification email to assert an address's
  5999. ownership. Defaults to &quot;[%(server_name)s] Validate your email&quot;</li>
  6000. </ul>
  6001. </li>
  6002. </ul>
  6003. <p>Example configuration:</p>
  6004. <pre><code class="language-yaml">email:
  6005. smtp_host: mail.server
  6006. smtp_port: 587
  6007. smtp_user: &quot;exampleusername&quot;
  6008. smtp_pass: &quot;examplepassword&quot;
  6009. force_tls: true
  6010. require_transport_security: true
  6011. enable_tls: false
  6012. notif_from: &quot;Your Friendly %(app)s homeserver &lt;noreply@example.com&gt;&quot;
  6013. app_name: my_branded_matrix_server
  6014. enable_notifs: true
  6015. notif_for_new_users: false
  6016. client_base_url: &quot;http://localhost/riot&quot;
  6017. validation_token_lifetime: 15m
  6018. invite_client_location: https://app.element.io
  6019. subjects:
  6020. message_from_person_in_room: &quot;[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...&quot;
  6021. message_from_person: &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;
  6022. messages_from_person: &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;
  6023. messages_in_room: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;
  6024. messages_in_room_and_others: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;
  6025. messages_from_person_and_others: &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;
  6026. invite_from_person_to_room: &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;
  6027. invite_from_person: &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;
  6028. password_reset: &quot;[%(server_name)s] Password reset&quot;
  6029. email_validation: &quot;[%(server_name)s] Validate your email&quot;
  6030. </code></pre>
  6031. <hr />
  6032. <h2 id="push"><a class="header" href="#push">Push</a></h2>
  6033. <p>Configuration settings related to push notifications</p>
  6034. <hr />
  6035. <h3 id="push-1"><a class="header" href="#push-1"><code>push</code></a></h3>
  6036. <p>This setting defines options for push notifications.</p>
  6037. <p>This option has a number of sub-options. They are as follows:</p>
  6038. <ul>
  6039. <li><code>include_content</code>: Clients requesting push notifications can either have the body of
  6040. the message sent in the notification poke along with other details
  6041. like the sender, or just the event ID and room ID (<code>event_id_only</code>).
  6042. If clients choose the to have the body sent, this option controls whether the
  6043. notification request includes the content of the event (other details
  6044. like the sender are still included). If <code>event_id_only</code> is enabled, it
  6045. has no effect.
  6046. For modern android devices the notification content will still appear
  6047. because it is loaded by the app. iPhone, however will send a
  6048. notification saying only that a message arrived and who it came from.
  6049. Defaults to true. Set to false to only include the event ID and room ID in push notification payloads.</li>
  6050. <li><code>group_unread_count_by_room: false</code>: When a push notification is received, an unread count is also sent.
  6051. This number can either be calculated as the number of unread messages for the user, or the number of <em>rooms</em> the
  6052. user has unread messages in. Defaults to true, meaning push clients will see the number of
  6053. rooms with unread messages in them. Set to false to instead send the number
  6054. of unread messages.</li>
  6055. </ul>
  6056. <p>Example configuration:</p>
  6057. <pre><code class="language-yaml">push:
  6058. include_content: false
  6059. group_unread_count_by_room: false
  6060. </code></pre>
  6061. <hr />
  6062. <h2 id="rooms"><a class="header" href="#rooms">Rooms</a></h2>
  6063. <p>Config options relating to rooms.</p>
  6064. <hr />
  6065. <h3 id="encryption_enabled_by_default"><a class="header" href="#encryption_enabled_by_default"><code>encryption_enabled_by_default</code></a></h3>
  6066. <p>Controls whether locally-created rooms should be end-to-end encrypted by
  6067. default.</p>
  6068. <p>Possible options are &quot;all&quot;, &quot;invite&quot;, and &quot;off&quot;. They are defined as:</p>
  6069. <ul>
  6070. <li>&quot;all&quot;: any locally-created room</li>
  6071. <li>&quot;invite&quot;: any room created with the <code>private_chat</code> or <code>trusted_private_chat</code>
  6072. room creation presets</li>
  6073. <li>&quot;off&quot;: this option will take no effect</li>
  6074. </ul>
  6075. <p>The default value is &quot;off&quot;.</p>
  6076. <p>Note that this option will only affect rooms created after it is set. It
  6077. will also not affect rooms created by other servers.</p>
  6078. <p>Example configuration:</p>
  6079. <pre><code class="language-yaml">encryption_enabled_by_default_for_room_type: invite
  6080. </code></pre>
  6081. <hr />
  6082. <h3 id="user_directory"><a class="header" href="#user_directory"><code>user_directory</code></a></h3>
  6083. <p>This setting defines options related to the user directory.</p>
  6084. <p>This option has the following sub-options:</p>
  6085. <ul>
  6086. <li>
  6087. <p><code>enabled</code>: Defines whether users can search the user directory. If false then
  6088. empty responses are returned to all queries. Defaults to true.</p>
  6089. </li>
  6090. <li>
  6091. <p><code>search_all_users</code>: Defines whether to search all users visible to your HS when searching
  6092. the user directory. If false, search results will only contain users
  6093. visible in public rooms and users sharing a room with the requester.
  6094. Defaults to false.</p>
  6095. <p>NB. If you set this to true, and the last time the user_directory search
  6096. indexes were (re)built was before Synapse 1.44, you'll have to
  6097. rebuild the indexes in order to search through all known users.</p>
  6098. <p>These indexes are built the first time Synapse starts; admins can
  6099. manually trigger a rebuild via the API following the instructions
  6100. <a href="usage/configuration/../administration/admin_api/background_updates.html#run">for running background updates</a>,
  6101. set to true to return search results containing all known users, even if that
  6102. user does not share a room with the requester.</p>
  6103. </li>
  6104. <li>
  6105. <p><code>prefer_local_users</code>: Defines whether to prefer local users in search query results.
  6106. If set to true, local users are more likely to appear above remote users when searching the
  6107. user directory. Defaults to false.</p>
  6108. </li>
  6109. </ul>
  6110. <p>Example configuration:</p>
  6111. <pre><code class="language-yaml">user_directory:
  6112. enabled: false
  6113. search_all_users: true
  6114. prefer_local_users: true
  6115. </code></pre>
  6116. <hr />
  6117. <h3 id="user_consent"><a class="header" href="#user_consent"><code>user_consent</code></a></h3>
  6118. <p>For detailed instructions on user consent configuration, see <a href="usage/configuration/../../consent_tracking.html">here</a>.</p>
  6119. <p>Parts of this section are required if enabling the <code>consent</code> resource under
  6120. <a href="usage/configuration/config_documentation.html#listeners"><code>listeners</code></a>, in particular <code>template_dir</code> and <code>version</code>.</p>
  6121. <ul>
  6122. <li>
  6123. <p><code>template_dir</code>: gives the location of the templates for the HTML forms.
  6124. This directory should contain one subdirectory per language (eg, <code>en</code>, <code>fr</code>),
  6125. and each language directory should contain the policy document (named as
  6126. <version>.html) and a success page (success.html).</p>
  6127. </li>
  6128. <li>
  6129. <p><code>version</code>: specifies the 'current' version of the policy document. It defines
  6130. the version to be served by the consent resource if there is no 'v'
  6131. parameter.</p>
  6132. </li>
  6133. <li>
  6134. <p><code>server_notice_content</code>: if enabled, will send a user a &quot;Server Notice&quot;
  6135. asking them to consent to the privacy policy. The <a href="usage/configuration/config_documentation.html#server_notices"><code>server_notices</code> section</a>
  6136. must also be configured for this to work. Notices will <em>not</em> be sent to
  6137. guest users unless <code>send_server_notice_to_guests</code> is set to true.</p>
  6138. </li>
  6139. <li>
  6140. <p><code>block_events_error</code>, if set, will block any attempts to send events
  6141. until the user consents to the privacy policy. The value of the setting is
  6142. used as the text of the error.</p>
  6143. </li>
  6144. <li>
  6145. <p><code>require_at_registration</code>, if enabled, will add a step to the registration
  6146. process, similar to how captcha works. Users will be required to accept the
  6147. policy before their account is created.</p>
  6148. </li>
  6149. <li>
  6150. <p><code>policy_name</code> is the display name of the policy users will see when registering
  6151. for an account. Has no effect unless <code>require_at_registration</code> is enabled.
  6152. Defaults to &quot;Privacy Policy&quot;.</p>
  6153. </li>
  6154. </ul>
  6155. <p>Example configuration:</p>
  6156. <pre><code class="language-yaml">user_consent:
  6157. template_dir: res/templates/privacy
  6158. version: 1.0
  6159. server_notice_content:
  6160. msgtype: m.text
  6161. body: &gt;-
  6162. To continue using this homeserver you must review and agree to the
  6163. terms and conditions at %(consent_uri)s
  6164. send_server_notice_to_guests: true
  6165. block_events_error: &gt;-
  6166. To continue using this homeserver you must review and agree to the
  6167. terms and conditions at %(consent_uri)s
  6168. require_at_registration: false
  6169. policy_name: Privacy Policy
  6170. </code></pre>
  6171. <hr />
  6172. <h3 id="stats"><a class="header" href="#stats"><code>stats</code></a></h3>
  6173. <p>Settings for local room and user statistics collection. See <a href="usage/configuration/../../room_and_user_statistics.html">here</a>
  6174. for more.</p>
  6175. <ul>
  6176. <li><code>enabled</code>: Set to false to disable room and user statistics. Note that doing
  6177. so may cause certain features (such as the room directory) not to work
  6178. correctly. Defaults to true.</li>
  6179. </ul>
  6180. <p>Example configuration:</p>
  6181. <pre><code class="language-yaml">stats:
  6182. enabled: false
  6183. </code></pre>
  6184. <hr />
  6185. <h3 id="server_notices"><a class="header" href="#server_notices"><code>server_notices</code></a></h3>
  6186. <p>Use this setting to enable a room which can be used to send notices
  6187. from the server to users. It is a special room which users cannot leave; notices
  6188. in the room come from a special &quot;notices&quot; user id.</p>
  6189. <p>If you use this setting, you <em>must</em> define the <code>system_mxid_localpart</code>
  6190. sub-setting, which defines the id of the user which will be used to send the
  6191. notices.</p>
  6192. <p>Sub-options for this setting include:</p>
  6193. <ul>
  6194. <li><code>system_mxid_display_name</code>: set the display name of the &quot;notices&quot; user</li>
  6195. <li><code>system_mxid_avatar_url</code>: set the avatar for the &quot;notices&quot; user</li>
  6196. <li><code>room_name</code>: set the room name of the server notices room</li>
  6197. </ul>
  6198. <p>Example configuration:</p>
  6199. <pre><code class="language-yaml">server_notices:
  6200. system_mxid_localpart: notices
  6201. system_mxid_display_name: &quot;Server Notices&quot;
  6202. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  6203. room_name: &quot;Server Notices&quot;
  6204. </code></pre>
  6205. <hr />
  6206. <h3 id="enable_room_list_search"><a class="header" href="#enable_room_list_search"><code>enable_room_list_search</code></a></h3>
  6207. <p>Set to false to disable searching the public room list. When disabled
  6208. blocks searching local and remote room lists for local and remote
  6209. users by always returning an empty list for all queries. Defaults to true.</p>
  6210. <p>Example configuration:</p>
  6211. <pre><code class="language-yaml">enable_room_list_search: false
  6212. </code></pre>
  6213. <hr />
  6214. <h3 id="alias_creation"><a class="header" href="#alias_creation"><code>alias_creation</code></a></h3>
  6215. <p>The <code>alias_creation</code> option controls who is allowed to create aliases
  6216. on this server.</p>
  6217. <p>The format of this option is a list of rules that contain globs that
  6218. match against user_id, room_id and the new alias (fully qualified with
  6219. server name). The action in the first rule that matches is taken,
  6220. which can currently either be &quot;allow&quot; or &quot;deny&quot;.</p>
  6221. <p>Missing user_id/room_id/alias fields default to &quot;*&quot;.</p>
  6222. <p>If no rules match the request is denied. An empty list means no one
  6223. can create aliases.</p>
  6224. <p>Options for the rules include:</p>
  6225. <ul>
  6226. <li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
  6227. <li><code>alias</code>: Matches against the alias being created. Defaults to &quot;*&quot;.</li>
  6228. <li><code>room_id</code>: Matches against the room ID the alias is being pointed at. Defaults to &quot;*&quot;</li>
  6229. <li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow.</li>
  6230. </ul>
  6231. <p>Example configuration:</p>
  6232. <pre><code class="language-yaml">alias_creation_rules:
  6233. - user_id: &quot;bad_user&quot;
  6234. alias: &quot;spammy_alias&quot;
  6235. room_id: &quot;*&quot;
  6236. action: deny
  6237. </code></pre>
  6238. <hr />
  6239. <h3 id="room_list_publication_rules"><a class="header" href="#room_list_publication_rules"><code>room_list_publication_rules</code></a></h3>
  6240. <p>The <code>room_list_publication_rules</code> option controls who can publish and
  6241. which rooms can be published in the public room list.</p>
  6242. <p>The format of this option is the same as that for
  6243. <code>alias_creation_rules</code>.</p>
  6244. <p>If the room has one or more aliases associated with it, only one of
  6245. the aliases needs to match the alias rule. If there are no aliases
  6246. then only rules with <code>alias: *</code> match.</p>
  6247. <p>If no rules match the request is denied. An empty list means no one
  6248. can publish rooms.</p>
  6249. <p>Options for the rules include:</p>
  6250. <ul>
  6251. <li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
  6252. <li><code>alias</code>: Matches against any current local or canonical aliases associated with the room. Defaults to &quot;*&quot;.</li>
  6253. <li><code>room_id</code>: Matches against the room ID being published. Defaults to &quot;*&quot;.</li>
  6254. <li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow.</li>
  6255. </ul>
  6256. <p>Example configuration:</p>
  6257. <pre><code class="language-yaml">room_list_publication_rules:
  6258. - user_id: &quot;*&quot;
  6259. alias: &quot;*&quot;
  6260. room_id: &quot;*&quot;
  6261. action: allow
  6262. </code></pre>
  6263. <hr />
  6264. <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>
  6265. <p>The <code>default_power_level_content_override</code> option controls the default power
  6266. levels for rooms.</p>
  6267. <p>Useful if you know that your users need special permissions in rooms
  6268. that they create (e.g. to send particular types of state events without
  6269. needing an elevated power level). This takes the same shape as the
  6270. <code>power_level_content_override</code> parameter in the /createRoom API, but
  6271. is applied before that parameter.</p>
  6272. <p>Note that each key provided inside a preset (for example <code>events</code> in the example
  6273. below) will overwrite all existing defaults inside that key. So in the example
  6274. below, newly-created private_chat rooms will have no rules for any event types
  6275. except <code>com.example.foo</code>.</p>
  6276. <p>Example configuration:</p>
  6277. <pre><code class="language-yaml">default_power_level_content_override:
  6278. private_chat: { &quot;events&quot;: { &quot;com.example.foo&quot; : 0 } }
  6279. trusted_private_chat: null
  6280. public_chat: null
  6281. </code></pre>
  6282. <hr />
  6283. <h2 id="opentracing"><a class="header" href="#opentracing">Opentracing</a></h2>
  6284. <p>Configuration options related to Opentracing support.</p>
  6285. <hr />
  6286. <h3 id="opentracing-1"><a class="header" href="#opentracing-1"><code>opentracing</code></a></h3>
  6287. <p>These settings enable and configure opentracing, which implements distributed tracing.
  6288. This allows you to observe the causal chains of events across servers
  6289. including requests, key lookups etc., across any server running
  6290. synapse or any other services which support opentracing
  6291. (specifically those implemented with Jaeger).</p>
  6292. <p>Sub-options include:</p>
  6293. <ul>
  6294. <li><code>enabled</code>: whether tracing is enabled. Set to true to enable. Disabled by default.</li>
  6295. <li><code>homeserver_whitelist</code>: The list of homeservers we wish to send and receive span contexts and span baggage.
  6296. See <a href="usage/configuration/../../opentracing.html">here</a> for more.
  6297. This is a list of regexes which are matched against the <code>server_name</code> of the homeserver.
  6298. By default, it is empty, so no servers are matched.</li>
  6299. <li><code>force_tracing_for_users</code>: # A list of the matrix IDs of users whose requests will always be traced,
  6300. even if the tracing system would otherwise drop the traces due to probabilistic sampling.
  6301. By default, the list is empty.</li>
  6302. <li><code>jaeger_config</code>: Jaeger can be configured to sample traces at different rates.
  6303. All configuration options provided by Jaeger can be set here. Jaeger's configuration is
  6304. mostly related to trace sampling which is documented <a href="https://www.jaegertracing.io/docs/latest/sampling/">here</a>.</li>
  6305. </ul>
  6306. <p>Example configuration:</p>
  6307. <pre><code class="language-yaml">opentracing:
  6308. enabled: true
  6309. homeserver_whitelist:
  6310. - &quot;.*&quot;
  6311. force_tracing_for_users:
  6312. - &quot;@user1:server_name&quot;
  6313. - &quot;@user2:server_name&quot;
  6314. jaeger_config:
  6315. sampler:
  6316. type: const
  6317. param: 1
  6318. logging:
  6319. false
  6320. </code></pre>
  6321. <hr />
  6322. <h2 id="workers"><a class="header" href="#workers">Workers</a></h2>
  6323. <p>Configuration options related to workers.</p>
  6324. <hr />
  6325. <h3 id="send_federation"><a class="header" href="#send_federation"><code>send_federation</code></a></h3>
  6326. <p>Controls sending of outbound federation transactions on the main process.
  6327. Set to false if using a federation sender worker. Defaults to true.</p>
  6328. <p>Example configuration:</p>
  6329. <pre><code class="language-yaml">send_federation: false
  6330. </code></pre>
  6331. <hr />
  6332. <h3 id="federation_sender_instances"><a class="header" href="#federation_sender_instances"><code>federation_sender_instances</code></a></h3>
  6333. <p>It is possible to run multiple federation sender workers, in which case the
  6334. work is balanced across them. Use this setting to list the senders.</p>
  6335. <p>This configuration setting must be shared between all federation sender workers, and if
  6336. changed all federation sender workers must be stopped at the same time and then
  6337. started, to ensure that all instances are running with the same config (otherwise
  6338. events may be dropped).</p>
  6339. <p>Example configuration:</p>
  6340. <pre><code class="language-yaml">federation_sender_instances:
  6341. - federation_sender1
  6342. </code></pre>
  6343. <hr />
  6344. <h3 id="instance_map"><a class="header" href="#instance_map"><code>instance_map</code></a></h3>
  6345. <p>When using workers this should be a map from worker name to the
  6346. HTTP replication listener of the worker, if configured.</p>
  6347. <p>Example configuration:</p>
  6348. <pre><code class="language-yaml">instance_map:
  6349. worker1:
  6350. host: localhost
  6351. port: 8034
  6352. </code></pre>
  6353. <hr />
  6354. <h3 id="stream_writers"><a class="header" href="#stream_writers"><code>stream_writers</code></a></h3>
  6355. <p>Experimental: When using workers you can define which workers should
  6356. handle event persistence and typing notifications. Any worker
  6357. specified here must also be in the <code>instance_map</code>.</p>
  6358. <p>Example configuration:</p>
  6359. <pre><code class="language-yaml">stream_writers:
  6360. events: worker1
  6361. typing: worker1
  6362. </code></pre>
  6363. <hr />
  6364. <h3 id="run_background_tasks_on"><a class="header" href="#run_background_tasks_on"><code>run_background_tasks_on</code></a></h3>
  6365. <p>The worker that is used to run background tasks (e.g. cleaning up expired
  6366. data). If not provided this defaults to the main process.</p>
  6367. <p>Example configuration:</p>
  6368. <pre><code class="language-yaml">run_background_tasks_on: worker1
  6369. </code></pre>
  6370. <hr />
  6371. <h3 id="worker_replication_secret"><a class="header" href="#worker_replication_secret"><code>worker_replication_secret</code></a></h3>
  6372. <p>A shared secret used by the replication APIs to authenticate HTTP requests
  6373. from workers.</p>
  6374. <p>By default this is unused and traffic is not authenticated.</p>
  6375. <p>Example configuration:</p>
  6376. <pre><code class="language-yaml">worker_replication_secret: &quot;secret_secret&quot;
  6377. </code></pre>
  6378. <h3 id="redis"><a class="header" href="#redis"><code>redis</code></a></h3>
  6379. <p>Configuration for Redis when using workers. This <em>must</em> be enabled when
  6380. using workers (unless using old style direct TCP configuration).
  6381. This setting has the following sub-options:</p>
  6382. <ul>
  6383. <li><code>enabled</code>: whether to use Redis support. Defaults to false.</li>
  6384. <li><code>host</code> and <code>port</code>: Optional host and port to use to connect to redis. Defaults to
  6385. localhost and 6379</li>
  6386. <li><code>password</code>: Optional password if configured on the Redis instance.</li>
  6387. </ul>
  6388. <p>Example configuration:</p>
  6389. <pre><code class="language-yaml">redis:
  6390. enabled: true
  6391. host: localhost
  6392. port: 6379
  6393. password: &lt;secret_password&gt;
  6394. </code></pre>
  6395. <h2 id="background-updates"><a class="header" href="#background-updates">Background Updates</a></h2>
  6396. <p>Configuration settings related to background updates.</p>
  6397. <hr />
  6398. <h3 id="background_updates"><a class="header" href="#background_updates"><code>background_updates</code></a></h3>
  6399. <p>Background updates are database updates that are run in the background in batches.
  6400. The duration, minimum batch size, default batch size, whether to sleep between batches and if so, how long to
  6401. sleep can all be configured. This is helpful to speed up or slow down the updates.
  6402. This setting has the following sub-options:</p>
  6403. <ul>
  6404. <li><code>background_update_duration_ms</code>: How long in milliseconds to run a batch of background updates for. Defaults to 100.
  6405. Set a different time to change the default.</li>
  6406. <li><code>sleep_enabled</code>: Whether to sleep between updates. Defaults to true. Set to false to change the default.</li>
  6407. <li><code>sleep_duration_ms</code>: If sleeping between updates, how long in milliseconds to sleep for. Defaults to 1000.
  6408. Set a duration to change the default.</li>
  6409. <li><code>min_batch_size</code>: Minimum size a batch of background updates can be. Must be greater than 0. Defaults to 1.
  6410. Set a size to change the default.</li>
  6411. <li><code>default_batch_size</code>: The batch size to use for the first iteration of a new background update. The default is 100.
  6412. Set a size to change the default.</li>
  6413. </ul>
  6414. <p>Example configuration:</p>
  6415. <pre><code class="language-yaml">background_updates:
  6416. background_update_duration_ms: 500
  6417. sleep_enabled: false
  6418. sleep_duration_ms: 300
  6419. min_batch_size: 10
  6420. default_batch_size: 50
  6421. </code></pre>
  6422. <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>
  6423. <p>Below is a sample homeserver configuration file. The homeserver configuration file
  6424. can be tweaked to change the behaviour of your homeserver. A restart of the server is
  6425. generally required to apply any changes made to this file.</p>
  6426. <p>Note that the contents below are <em>not</em> intended to be copied and used as the basis for
  6427. a real homeserver.yaml. Instead, if you are starting from scratch, please generate
  6428. a fresh config using Synapse by following the instructions in
  6429. <a href="usage/configuration/../../setup/installation.html">Installation</a>.</p>
  6430. <p>Documentation for all configuration options can be found in the
  6431. <a href="usage/configuration/./config_documentation.html">Configuration Manual</a>.</p>
  6432. <pre><code class="language-yaml"># This file is maintained as an up-to-date snapshot of the default
  6433. # homeserver.yaml configuration generated by Synapse. You can find a
  6434. # complete accounting of possible configuration options at
  6435. # https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
  6436. #
  6437. # It is *not* intended to be copied and used as the basis for a real
  6438. # homeserver.yaml. Instead, if you are starting from scratch, please generate
  6439. # a fresh config using Synapse by following the instructions in
  6440. # https://matrix-org.github.io/synapse/latest/setup/installation.html.
  6441. #
  6442. ################################################################################
  6443. # Configuration file for Synapse.
  6444. #
  6445. # This is a YAML file: see [1] for a quick introduction. Note in particular
  6446. # that *indentation is important*: all the elements of a list or dictionary
  6447. # should have the same indentation.
  6448. #
  6449. # [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
  6450. #
  6451. # For more information on how to configure Synapse, including a complete accounting of
  6452. # each option, go to docs/usage/configuration/config_documentation.md or
  6453. # https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
  6454. server_name: &quot;SERVERNAME&quot;
  6455. pid_file: DATADIR/homeserver.pid
  6456. listeners:
  6457. - port: 8008
  6458. tls: false
  6459. type: http
  6460. x_forwarded: true
  6461. bind_addresses: ['::1', '127.0.0.1']
  6462. resources:
  6463. - names: [client, federation]
  6464. compress: false
  6465. database:
  6466. name: sqlite3
  6467. args:
  6468. database: DATADIR/homeserver.db
  6469. log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  6470. media_store_path: DATADIR/media_store
  6471. signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  6472. trusted_key_servers:
  6473. - server_name: &quot;matrix.org&quot;
  6474. </code></pre>
  6475. <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>
  6476. <p>Below is a sample logging configuration file. This file can be tweaked to control how your
  6477. homeserver will output logs. A restart of the server is generally required to apply any
  6478. changes made to this file. The value of the <code>log_config</code> option in your homeserver
  6479. config should be the path to this file.</p>
  6480. <p>Note that a default logging configuration (shown below) is created automatically alongside
  6481. the homeserver config when following the <a href="usage/configuration/../../setup/installation.html">installation instructions</a>.
  6482. It should be named <code>&lt;SERVERNAME&gt;.log.config</code> by default.</p>
  6483. <pre><code class="language-yaml"># Log configuration for Synapse.
  6484. #
  6485. # This is a YAML file containing a standard Python logging configuration
  6486. # dictionary. See [1] for details on the valid settings.
  6487. #
  6488. # Synapse also supports structured logging for machine readable logs which can
  6489. # be ingested by ELK stacks. See [2] for details.
  6490. #
  6491. # [1]: https://docs.python.org/3.7/library/logging.config.html#configuration-dictionary-schema
  6492. # [2]: https://matrix-org.github.io/synapse/latest/structured_logging.html
  6493. version: 1
  6494. formatters:
  6495. precise:
  6496. format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s'
  6497. handlers:
  6498. file:
  6499. class: logging.handlers.TimedRotatingFileHandler
  6500. formatter: precise
  6501. filename: /var/log/matrix-synapse/homeserver.log
  6502. when: midnight
  6503. backupCount: 3 # Does not include the current log file.
  6504. encoding: utf8
  6505. # Default to buffering writes to log file for efficiency.
  6506. # WARNING/ERROR logs will still be flushed immediately, but there will be a
  6507. # delay (of up to `period` seconds, or until the buffer is full with
  6508. # `capacity` messages) before INFO/DEBUG logs get written.
  6509. buffer:
  6510. class: synapse.logging.handlers.PeriodicallyFlushingMemoryHandler
  6511. target: file
  6512. # The capacity is the maximum number of log lines that are buffered
  6513. # before being written to disk. Increasing this will lead to better
  6514. # performance, at the expensive of it taking longer for log lines to
  6515. # be written to disk.
  6516. # This parameter is required.
  6517. capacity: 10
  6518. # Logs with a level at or above the flush level will cause the buffer to
  6519. # be flushed immediately.
  6520. # Default value: 40 (ERROR)
  6521. # Other values: 50 (CRITICAL), 30 (WARNING), 20 (INFO), 10 (DEBUG)
  6522. flushLevel: 30 # Flush immediately for WARNING logs and higher
  6523. # The period of time, in seconds, between forced flushes.
  6524. # Messages will not be delayed for longer than this time.
  6525. # Default value: 5 seconds
  6526. period: 5
  6527. # A handler that writes logs to stderr. Unused by default, but can be used
  6528. # instead of &quot;buffer&quot; and &quot;file&quot; in the logger handlers.
  6529. console:
  6530. class: logging.StreamHandler
  6531. formatter: precise
  6532. loggers:
  6533. synapse.storage.SQL:
  6534. # beware: increasing this to DEBUG will make synapse log sensitive
  6535. # information such as access tokens.
  6536. level: INFO
  6537. root:
  6538. level: INFO
  6539. # Write logs to the `buffer` handler, which will buffer them together in memory,
  6540. # then write them to a file.
  6541. #
  6542. # Replace &quot;buffer&quot; with &quot;console&quot; to log to stderr instead. (Note that you'll
  6543. # also need to update the configuration for the `twisted` logger above, in
  6544. # this case.)
  6545. #
  6546. handlers: [buffer]
  6547. disable_existing_loggers: false
  6548. </code></pre>
  6549. <div style="break-before: page; page-break-before: always;"></div><h1 id="structured-logging"><a class="header" href="#structured-logging">Structured Logging</a></h1>
  6550. <p>A structured logging system can be useful when your logs are destined for a
  6551. machine to parse and process. By maintaining its machine-readable characteristics,
  6552. it enables more efficient searching and aggregations when consumed by software
  6553. such as the &quot;ELK stack&quot;.</p>
  6554. <p>Synapse's structured logging system is configured via the file that Synapse's
  6555. <code>log_config</code> config option points to. The file should include a formatter which
  6556. uses the <code>synapse.logging.TerseJsonFormatter</code> class included with Synapse and a
  6557. handler which uses the above formatter.</p>
  6558. <p>There is also a <code>synapse.logging.JsonFormatter</code> option which does not include
  6559. a timestamp in the resulting JSON. This is useful if the log ingester adds its
  6560. own timestamp.</p>
  6561. <p>A structured logging configuration looks similar to the following:</p>
  6562. <pre><code class="language-yaml">version: 1
  6563. formatters:
  6564. structured:
  6565. class: synapse.logging.TerseJsonFormatter
  6566. handlers:
  6567. file:
  6568. class: logging.handlers.TimedRotatingFileHandler
  6569. formatter: structured
  6570. filename: /path/to/my/logs/homeserver.log
  6571. when: midnight
  6572. backupCount: 3 # Does not include the current log file.
  6573. encoding: utf8
  6574. loggers:
  6575. synapse:
  6576. level: INFO
  6577. handlers: [remote]
  6578. synapse.storage.SQL:
  6579. level: WARNING
  6580. </code></pre>
  6581. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  6582. with the SQL layer at 'WARNING', and will log to a file, stored as JSON.</p>
  6583. <p>It is also possible to configure Synapse to log to a remote endpoint by using the
  6584. <code>synapse.logging.RemoteHandler</code> class included with Synapse. It takes the
  6585. following arguments:</p>
  6586. <ul>
  6587. <li><code>host</code>: Hostname or IP address of the log aggregator.</li>
  6588. <li><code>port</code>: Numerical port to contact on the host.</li>
  6589. <li><code>maximum_buffer</code>: (Optional, defaults to 1000) The maximum buffer size to allow.</li>
  6590. </ul>
  6591. <p>A remote structured logging configuration looks similar to the following:</p>
  6592. <pre><code class="language-yaml">version: 1
  6593. formatters:
  6594. structured:
  6595. class: synapse.logging.TerseJsonFormatter
  6596. handlers:
  6597. remote:
  6598. class: synapse.logging.RemoteHandler
  6599. formatter: structured
  6600. host: 10.1.2.3
  6601. port: 9999
  6602. loggers:
  6603. synapse:
  6604. level: INFO
  6605. handlers: [remote]
  6606. synapse.storage.SQL:
  6607. level: WARNING
  6608. </code></pre>
  6609. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  6610. with the SQL layer at 'WARNING', and will log JSON formatted messages to a
  6611. remote endpoint at 10.1.2.3:9999.</p>
  6612. <div style="break-before: page; page-break-before: always;"></div><h1 id="templates"><a class="header" href="#templates">Templates</a></h1>
  6613. <p>Synapse uses parametrised templates to generate the content of emails it sends and
  6614. webpages it shows to users.</p>
  6615. <p>By default, Synapse will use the templates listed <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">here</a>.
  6616. Server admins can configure an additional directory for Synapse to look for templates
  6617. in, allowing them to specify custom templates:</p>
  6618. <pre><code class="language-yaml">templates:
  6619. custom_template_directory: /path/to/custom/templates/
  6620. </code></pre>
  6621. <p>If this setting is not set, or the files named below are not found within the directory,
  6622. default templates from within the Synapse package will be used.</p>
  6623. <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>.
  6624. Templates rendered by Jinja 2 can also access two functions on top of the functions
  6625. already available as part of Jinja 2:</p>
  6626. <pre><code class="language-python">format_ts(value: int, format: str) -&gt; str
  6627. </code></pre>
  6628. <p>Formats a timestamp in milliseconds.</p>
  6629. <p>Example: <code>reason.last_sent_ts|format_ts(&quot;%c&quot;)</code></p>
  6630. <pre><code class="language-python">mxc_to_http(value: str, width: int, height: int, resize_method: str = &quot;crop&quot;) -&gt; str
  6631. </code></pre>
  6632. <p>Turns a <code>mxc://</code> URL for media content into an HTTP(S) one using the homeserver's
  6633. <code>public_baseurl</code> configuration setting as the URL's base.</p>
  6634. <p>Example: <code>message.sender_avatar_url|mxc_to_http(32,32)</code></p>
  6635. <pre><code class="language-python">localpart_from_email(address: str) -&gt; str
  6636. </code></pre>
  6637. <p>Returns the local part of an email address (e.g. <code>alice</code> in <code>alice@example.com</code>).</p>
  6638. <p>Example: <code>user.email_address|localpart_from_email</code></p>
  6639. <h2 id="email-templates"><a class="header" href="#email-templates">Email templates</a></h2>
  6640. <p>Below are the templates Synapse will look for when generating the content of an email:</p>
  6641. <ul>
  6642. <li><code>notif_mail.html</code> and <code>notif_mail.txt</code>: The contents of email notifications of missed
  6643. events.
  6644. When rendering, this template is given the following variables:
  6645. <ul>
  6646. <li><code>user_display_name</code>: the display name for the user receiving the notification</li>
  6647. <li><code>unsubscribe_link</code>: the link users can click to unsubscribe from email notifications</li>
  6648. <li><code>summary_text</code>: a summary of the notification(s). The text used can be customised
  6649. by configuring the various settings in the <code>email.subjects</code> section of the
  6650. configuration file.</li>
  6651. <li><code>rooms</code>: a list of rooms containing events to include in the email. Each element is
  6652. an object with the following attributes:
  6653. <ul>
  6654. <li><code>title</code>: a human-readable name for the room</li>
  6655. <li><code>hash</code>: a hash of the ID of the room</li>
  6656. <li><code>invite</code>: a boolean, which is <code>True</code> if the room is an invite the user hasn't
  6657. accepted yet, <code>False</code> otherwise</li>
  6658. <li><code>notifs</code>: a list of events, or an empty list if <code>invite</code> is <code>True</code>. Each element
  6659. is an object with the following attributes:
  6660. <ul>
  6661. <li><code>link</code>: a <code>matrix.to</code> link to the event</li>
  6662. <li><code>ts</code>: the time in milliseconds at which the event was received</li>
  6663. <li><code>messages</code>: a list of messages containing one message before the event, the
  6664. message in the event, and one message after the event. Each element is an
  6665. object with the following attributes:
  6666. <ul>
  6667. <li><code>event_type</code>: the type of the event</li>
  6668. <li><code>is_historical</code>: a boolean, which is <code>False</code> if the message is the one
  6669. that triggered the notification, <code>True</code> otherwise</li>
  6670. <li><code>id</code>: the ID of the event</li>
  6671. <li><code>ts</code>: the time in milliseconds at which the event was sent</li>
  6672. <li><code>sender_name</code>: the display name for the event's sender</li>
  6673. <li><code>sender_avatar_url</code>: the avatar URL (as a <code>mxc://</code> URL) for the event's
  6674. sender</li>
  6675. <li><code>sender_hash</code>: a hash of the user ID of the sender</li>
  6676. <li><code>msgtype</code>: the type of the message</li>
  6677. <li><code>body_text_html</code>: html representation of the message</li>
  6678. <li><code>body_text_plain</code>: plaintext representation of the message</li>
  6679. <li><code>image_url</code>: mxc url of an image, when &quot;msgtype&quot; is &quot;m.image&quot;</li>
  6680. </ul>
  6681. </li>
  6682. </ul>
  6683. </li>
  6684. <li><code>link</code>: a <code>matrix.to</code> link to the room</li>
  6685. <li><code>avator_url</code>: url to the room's avator</li>
  6686. </ul>
  6687. </li>
  6688. <li><code>reason</code>: information on the event that triggered the email to be sent. It's an
  6689. object with the following attributes:
  6690. <ul>
  6691. <li><code>room_id</code>: the ID of the room the event was sent in</li>
  6692. <li><code>room_name</code>: a human-readable name for the room the event was sent in</li>
  6693. <li><code>now</code>: the current time in milliseconds</li>
  6694. <li><code>received_at</code>: the time in milliseconds at which the event was received</li>
  6695. <li><code>delay_before_mail_ms</code>: the amount of time in milliseconds Synapse always waits
  6696. before ever emailing about a notification (to give the user a chance to respond
  6697. to other push or notice the window)</li>
  6698. <li><code>last_sent_ts</code>: the time in milliseconds at which a notification was last sent
  6699. for an event in this room</li>
  6700. <li><code>throttle_ms</code>: the minimum amount of time in milliseconds between two
  6701. notifications can be sent for this room</li>
  6702. </ul>
  6703. </li>
  6704. </ul>
  6705. </li>
  6706. <li><code>password_reset.html</code> and <code>password_reset.txt</code>: The contents of password reset emails
  6707. sent by the homeserver.
  6708. When rendering, these templates are given a <code>link</code> variable which contains the link the
  6709. user must click in order to reset their password.</li>
  6710. <li><code>registration.html</code> and <code>registration.txt</code>: The contents of address verification emails
  6711. sent during registration.
  6712. When rendering, these templates are given a <code>link</code> variable which contains the link the
  6713. user must click in order to validate their email address.</li>
  6714. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code>: The contents of address verification emails
  6715. sent when an address is added to a Matrix account.
  6716. When rendering, these templates are given a <code>link</code> variable which contains the link the
  6717. user must click in order to validate their email address.</li>
  6718. </ul>
  6719. <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>
  6720. <p>Below are the templates Synapse will look for when generating pages related to
  6721. registration and password reset:</p>
  6722. <ul>
  6723. <li><code>password_reset_confirmation.html</code>: An HTML page that a user will see when they follow
  6724. the link in the password reset email. The user will be asked to confirm the action
  6725. before their password is reset.
  6726. When rendering, this template is given the following variables:
  6727. <ul>
  6728. <li><code>sid</code>: the session ID for the password reset</li>
  6729. <li><code>token</code>: the token for the password reset</li>
  6730. <li><code>client_secret</code>: the client secret for the password reset</li>
  6731. </ul>
  6732. </li>
  6733. <li><code>password_reset_success.html</code> and <code>password_reset_failure.html</code>: HTML pages for success
  6734. and failure that a user will see when they confirm the password reset flow using the
  6735. page above.
  6736. When rendering, <code>password_reset_success.html</code> is given no variable, and
  6737. <code>password_reset_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  6738. for the password reset failure. </li>
  6739. <li><code>registration_success.html</code> and <code>registration_failure.html</code>: HTML pages for success and
  6740. failure that a user will see when they follow the link in an address verification email
  6741. sent during registration.
  6742. When rendering, <code>registration_success.html</code> is given no variable, and
  6743. <code>registration_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  6744. for the registration failure.</li>
  6745. <li><code>add_threepid_success.html</code> and <code>add_threepid_failure.html</code>: HTML pages for success and
  6746. failure that a user will see when they follow the link in an address verification email
  6747. sent when an address is added to a Matrix account.
  6748. When rendering, <code>add_threepid_success.html</code> is given no variable, and
  6749. <code>add_threepid_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  6750. for the registration failure.</li>
  6751. </ul>
  6752. <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>
  6753. <p>Below are the templates Synapse will look for when generating pages related to SSO:</p>
  6754. <ul>
  6755. <li><code>sso_login_idp_picker.html</code>: HTML page to prompt the user to choose an
  6756. Identity Provider during login.
  6757. This is only used if multiple SSO Identity Providers are configured.
  6758. When rendering, this template is given the following variables:
  6759. <ul>
  6760. <li><code>redirect_url</code>: the URL that the user will be redirected to after
  6761. login.</li>
  6762. <li><code>server_name</code>: the homeserver's name.</li>
  6763. <li><code>providers</code>: a list of available Identity Providers. Each element is
  6764. an object with the following attributes:
  6765. <ul>
  6766. <li><code>idp_id</code>: unique identifier for the IdP</li>
  6767. <li><code>idp_name</code>: user-facing name for the IdP</li>
  6768. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  6769. for the IdP</li>
  6770. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  6771. for the brand of the IdP
  6772. The rendered HTML page should contain a form which submits its results
  6773. back as a GET request, with the following query parameters:</li>
  6774. </ul>
  6775. </li>
  6776. <li><code>redirectUrl</code>: the client redirect URI (ie, the <code>redirect_url</code> passed
  6777. to the template)</li>
  6778. <li><code>idp</code>: the 'idp_id' of the chosen IDP.</li>
  6779. </ul>
  6780. </li>
  6781. <li><code>sso_auth_account_details.html</code>: HTML page to prompt new users to enter a
  6782. userid and confirm other details. This is only shown if the
  6783. SSO implementation (with any <code>user_mapping_provider</code>) does not return
  6784. a localpart.
  6785. When rendering, this template is given the following variables:
  6786. <ul>
  6787. <li><code>server_name</code>: the homeserver's name.</li>
  6788. <li><code>idp</code>: details of the SSO Identity Provider that the user logged in
  6789. with: an object with the following attributes:
  6790. <ul>
  6791. <li><code>idp_id</code>: unique identifier for the IdP</li>
  6792. <li><code>idp_name</code>: user-facing name for the IdP</li>
  6793. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  6794. for the IdP</li>
  6795. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  6796. for the brand of the IdP</li>
  6797. </ul>
  6798. </li>
  6799. <li><code>user_attributes</code>: an object containing details about the user that
  6800. we received from the IdP. May have the following attributes:
  6801. <ul>
  6802. <li><code>display_name</code>: the user's display name</li>
  6803. <li><code>emails</code>: a list of email addresses</li>
  6804. <li><code>localpart</code>: the local part of the Matrix user ID to register,
  6805. if <code>localpart_template</code> is set in the mapping provider configuration (empty
  6806. string if not)
  6807. The template should render a form which submits the following fields:</li>
  6808. </ul>
  6809. </li>
  6810. <li><code>username</code>: the localpart of the user's chosen user id</li>
  6811. </ul>
  6812. </li>
  6813. <li><code>sso_new_user_consent.html</code>: HTML page allowing the user to consent to the
  6814. server's terms and conditions. This is only shown for new users, and only if
  6815. <code>user_consent.require_at_registration</code> is set.
  6816. When rendering, this template is given the following variables:
  6817. <ul>
  6818. <li><code>server_name</code>: the homeserver's name.</li>
  6819. <li><code>user_id</code>: the user's matrix proposed ID.</li>
  6820. <li><code>user_profile.display_name</code>: the user's proposed display name, if any.</li>
  6821. <li>consent_version: the version of the terms that the user will be
  6822. shown</li>
  6823. <li><code>terms_url</code>: a link to the page showing the terms.
  6824. The template should render a form which submits the following fields:</li>
  6825. <li><code>accepted_version</code>: the version of the terms accepted by the user
  6826. (ie, 'consent_version' from the input variables).</li>
  6827. </ul>
  6828. </li>
  6829. <li><code>sso_redirect_confirm.html</code>: HTML page for a confirmation step before redirecting back
  6830. to the client with the login token.
  6831. When rendering, this template is given the following variables:
  6832. <ul>
  6833. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  6834. <li><code>display_url</code>: the same as <code>redirect_url</code>, but with the query
  6835. parameters stripped. The intention is to have a
  6836. human-readable URL to show to users, not to use it as
  6837. the final address to redirect to.</li>
  6838. <li><code>server_name</code>: the homeserver's name.</li>
  6839. <li><code>new_user</code>: a boolean indicating whether this is the user's first time
  6840. logging in.</li>
  6841. <li><code>user_id</code>: the user's matrix ID.</li>
  6842. <li><code>user_profile.avatar_url</code>: an MXC URI for the user's avatar, if any.
  6843. <code>None</code> if the user has not set an avatar.</li>
  6844. <li><code>user_profile.display_name</code>: the user's display name. <code>None</code> if the user
  6845. has not set a display name.</li>
  6846. </ul>
  6847. </li>
  6848. <li><code>sso_auth_confirm.html</code>: HTML page which notifies the user that they are authenticating
  6849. to confirm an operation on their account during the user interactive authentication
  6850. process.
  6851. When rendering, this template is given the following variables:
  6852. <ul>
  6853. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  6854. <li><code>description</code>: the operation which the user is being asked to confirm</li>
  6855. <li><code>idp</code>: details of the Identity Provider that we will use to confirm
  6856. the user's identity: an object with the following attributes:
  6857. <ul>
  6858. <li><code>idp_id</code>: unique identifier for the IdP</li>
  6859. <li><code>idp_name</code>: user-facing name for the IdP</li>
  6860. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  6861. for the IdP</li>
  6862. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  6863. for the brand of the IdP</li>
  6864. </ul>
  6865. </li>
  6866. </ul>
  6867. </li>
  6868. <li><code>sso_auth_success.html</code>: HTML page shown after a successful user interactive
  6869. authentication session.
  6870. Note that this page must include the JavaScript which notifies of a successful
  6871. authentication (see https://matrix.org/docs/spec/client_server/r0.6.0#fallback).
  6872. This template has no additional variables.</li>
  6873. <li><code>sso_auth_bad_user.html</code>: HTML page shown after a user-interactive authentication
  6874. session which does not map correctly onto the expected user.
  6875. When rendering, this template is given the following variables:
  6876. <ul>
  6877. <li><code>server_name</code>: the homeserver's name.</li>
  6878. <li><code>user_id_to_verify</code>: the MXID of the user that we are trying to
  6879. validate.</li>
  6880. </ul>
  6881. </li>
  6882. <li><code>sso_account_deactivated.html</code>: HTML page shown during single sign-on if a deactivated
  6883. user (according to Synapse's database) attempts to login.
  6884. This template has no additional variables.</li>
  6885. <li><code>sso_error.html</code>: HTML page to display to users if something goes wrong during the
  6886. OpenID Connect authentication process.
  6887. When rendering, this template is given two variables:
  6888. <ul>
  6889. <li><code>error</code>: the technical name of the error</li>
  6890. <li><code>error_description</code>: a human-readable message for the error</li>
  6891. </ul>
  6892. </li>
  6893. </ul>
  6894. <div style="break-before: page; page-break-before: always;"></div><h1 id="user-authentication"><a class="header" href="#user-authentication">User Authentication</a></h1>
  6895. <p>Synapse supports multiple methods of authenticating users, either out-of-the-box or through custom pluggable
  6896. authentication modules.</p>
  6897. <p>Included in Synapse is support for authenticating users via:</p>
  6898. <ul>
  6899. <li>A username and password.</li>
  6900. <li>An email address and password.</li>
  6901. <li>Single Sign-On through the SAML, Open ID Connect or CAS protocols.</li>
  6902. <li>JSON Web Tokens.</li>
  6903. <li>An administrator's shared secret.</li>
  6904. </ul>
  6905. <p>Synapse can additionally be extended to support custom authentication schemes through optional &quot;password auth provider&quot;
  6906. modules.</p>
  6907. <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>
  6908. <p>Synapse supports single sign-on through the SAML, Open ID Connect or CAS protocols.
  6909. LDAP and other login methods are supported through first and third-party password
  6910. auth provider modules.</p>
  6911. <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>
  6912. <p>Synapse can be configured to use an OpenID Connect Provider (OP) for
  6913. authentication, instead of its own local password database.</p>
  6914. <p>Any OP should work with Synapse, as long as it supports the authorization code
  6915. flow. There are a few options for that:</p>
  6916. <ul>
  6917. <li>
  6918. <p>start a local OP. Synapse has been tested with <a href="https://www.ory.sh/docs/hydra/">Hydra</a> and
  6919. <a href="https://github.com/dexidp/dex">Dex</a>. Note that for an OP to work, it should be served under a
  6920. secure (HTTPS) origin. A certificate signed with a self-signed, locally
  6921. trusted CA should work. In that case, start Synapse with a <code>SSL_CERT_FILE</code>
  6922. environment variable set to the path of the CA.</p>
  6923. </li>
  6924. <li>
  6925. <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
  6926. <a href="https://www.okta.com/">Okta</a>. Synapse has been tested with Auth0 and Google.</p>
  6927. </li>
  6928. </ul>
  6929. <p>It may also be possible to use other OAuth2 providers which provide the
  6930. <a href="https://tools.ietf.org/html/rfc6749#section-4.1">authorization code grant type</a>,
  6931. such as <a href="https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps">Github</a>.</p>
  6932. <h2 id="preparing-synapse"><a class="header" href="#preparing-synapse">Preparing Synapse</a></h2>
  6933. <p>The OpenID integration in Synapse uses the
  6934. <a href="https://pypi.org/project/Authlib/"><code>authlib</code></a> library, which must be installed
  6935. as follows:</p>
  6936. <ul>
  6937. <li>
  6938. <p>The relevant libraries are included in the Docker images and Debian packages
  6939. provided by <code>matrix.org</code> so no further action is needed.</p>
  6940. </li>
  6941. <li>
  6942. <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>
  6943. </li>
  6944. <li>
  6945. <p>For other installation mechanisms, see the documentation provided by the
  6946. maintainer.</p>
  6947. </li>
  6948. </ul>
  6949. <p>To enable the OpenID integration, you should then add a section to the <code>oidc_providers</code>
  6950. setting in your configuration file.
  6951. See the <a href="usage/configuration/config_documentation.html#oidc_providers">configuration manual</a> for some sample settings, as well as
  6952. the text below for example configurations for specific providers.</p>
  6953. <h2 id="sample-configs"><a class="header" href="#sample-configs">Sample configs</a></h2>
  6954. <p>Here are a few configs for providers that should work with Synapse.</p>
  6955. <h3 id="microsoft-azure-active-directory"><a class="header" href="#microsoft-azure-active-directory">Microsoft Azure Active Directory</a></h3>
  6956. <p>Azure AD can act as an OpenID Connect Provider. Register a new application under
  6957. <em>App registrations</em> in the Azure AD management console. The RedirectURI for your
  6958. application should point to your matrix server:
  6959. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  6960. <p>Go to <em>Certificates &amp; secrets</em> and register a new client secret. Make note of your
  6961. Directory (tenant) ID as it will be used in the Azure links.
  6962. Edit your Synapse config file and change the <code>oidc_config</code> section:</p>
  6963. <pre><code class="language-yaml">oidc_providers:
  6964. - idp_id: microsoft
  6965. idp_name: Microsoft
  6966. issuer: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/v2.0&quot;
  6967. client_id: &quot;&lt;client id&gt;&quot;
  6968. client_secret: &quot;&lt;client secret&gt;&quot;
  6969. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6970. authorization_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/authorize&quot;
  6971. token_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/token&quot;
  6972. userinfo_endpoint: &quot;https://graph.microsoft.com/oidc/userinfo&quot;
  6973. user_mapping_provider:
  6974. config:
  6975. localpart_template: &quot;{{ user.preferred_username.split('@')[0] }}&quot;
  6976. display_name_template: &quot;{{ user.name }}&quot;
  6977. </code></pre>
  6978. <h3 id="dex"><a class="header" href="#dex">Dex</a></h3>
  6979. <p><a href="https://github.com/dexidp/dex">Dex</a> is a simple, open-source OpenID Connect Provider.
  6980. Although it is designed to help building a full-blown provider with an
  6981. external database, it can be configured with static passwords in a config file.</p>
  6982. <p>Follow the <a href="https://dexidp.io/docs/getting-started/">Getting Started guide</a>
  6983. to install Dex.</p>
  6984. <p>Edit <code>examples/config-dev.yaml</code> config file from the Dex repo to add a client:</p>
  6985. <pre><code class="language-yaml">staticClients:
  6986. - id: synapse
  6987. secret: secret
  6988. redirectURIs:
  6989. - '[synapse public baseurl]/_synapse/client/oidc/callback'
  6990. name: 'Synapse'
  6991. </code></pre>
  6992. <p>Run with <code>dex serve examples/config-dev.yaml</code>.</p>
  6993. <p>Synapse config:</p>
  6994. <pre><code class="language-yaml">oidc_providers:
  6995. - idp_id: dex
  6996. idp_name: &quot;My Dex server&quot;
  6997. skip_verification: true # This is needed as Dex is served on an insecure endpoint
  6998. issuer: &quot;http://127.0.0.1:5556/dex&quot;
  6999. client_id: &quot;synapse&quot;
  7000. client_secret: &quot;secret&quot;
  7001. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7002. user_mapping_provider:
  7003. config:
  7004. localpart_template: &quot;{{ user.name }}&quot;
  7005. display_name_template: &quot;{{ user.name|capitalize }}&quot;
  7006. </code></pre>
  7007. <h3 id="keycloak"><a class="header" href="#keycloak">Keycloak</a></h3>
  7008. <p><a href="https://www.keycloak.org/docs/latest/server_admin/#sso-protocols">Keycloak</a> is an opensource IdP maintained by Red Hat.</p>
  7009. <p>Follow the <a href="https://www.keycloak.org/getting-started">Getting Started Guide</a> to install Keycloak and set up a realm.</p>
  7010. <ol>
  7011. <li>
  7012. <p>Click <code>Clients</code> in the sidebar and click <code>Create</code></p>
  7013. </li>
  7014. <li>
  7015. <p>Fill in the fields as below:</p>
  7016. </li>
  7017. </ol>
  7018. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  7019. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  7020. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  7021. </tbody></table>
  7022. <ol start="3">
  7023. <li>Click <code>Save</code></li>
  7024. <li>Fill in the fields as below:</li>
  7025. </ol>
  7026. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  7027. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  7028. <tr><td>Enabled</td><td><code>On</code></td></tr>
  7029. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  7030. <tr><td>Access Type</td><td><code>confidential</code></td></tr>
  7031. <tr><td>Valid Redirect URIs</td><td><code>[synapse public baseurl]/_synapse/client/oidc/callback</code></td></tr>
  7032. </tbody></table>
  7033. <ol start="5">
  7034. <li>Click <code>Save</code></li>
  7035. <li>On the Credentials tab, update the fields:</li>
  7036. </ol>
  7037. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  7038. <tr><td>Client Authenticator</td><td><code>Client ID and Secret</code></td></tr>
  7039. </tbody></table>
  7040. <ol start="7">
  7041. <li>Click <code>Regenerate Secret</code></li>
  7042. <li>Copy Secret</li>
  7043. </ol>
  7044. <pre><code class="language-yaml">oidc_providers:
  7045. - idp_id: keycloak
  7046. idp_name: &quot;My KeyCloak server&quot;
  7047. issuer: &quot;https://127.0.0.1:8443/realms/{realm_name}&quot;
  7048. client_id: &quot;synapse&quot;
  7049. client_secret: &quot;copy secret generated from above&quot;
  7050. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7051. user_mapping_provider:
  7052. config:
  7053. localpart_template: &quot;{{ user.preferred_username }}&quot;
  7054. display_name_template: &quot;{{ user.name }}&quot;
  7055. </code></pre>
  7056. <h3 id="auth0"><a class="header" href="#auth0">Auth0</a></h3>
  7057. <p><a href="https://auth0.com/">Auth0</a> is a hosted SaaS IdP solution.</p>
  7058. <ol>
  7059. <li>
  7060. <p>Create a regular web application for Synapse</p>
  7061. </li>
  7062. <li>
  7063. <p>Set the Allowed Callback URLs to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  7064. </li>
  7065. <li>
  7066. <p>Add a rule with any name to add the <code>preferred_username</code> claim.
  7067. (See https://auth0.com/docs/customize/rules/create-rules for more information on how to create rules.)</p>
  7068. <details>
  7069. <summary>Code sample</summary>
  7070. <pre><code class="language-js">function addPersistenceAttribute(user, context, callback) {
  7071. user.user_metadata = user.user_metadata || {};
  7072. user.user_metadata.preferred_username = user.user_metadata.preferred_username || user.user_id;
  7073. context.idToken.preferred_username = user.user_metadata.preferred_username;
  7074. auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
  7075. .then(function(){
  7076. callback(null, user, context);
  7077. })
  7078. .catch(function(err){
  7079. callback(err);
  7080. });
  7081. }
  7082. </code></pre>
  7083. </li>
  7084. </ol>
  7085. </details>
  7086. <p>Synapse config:</p>
  7087. <pre><code class="language-yaml">oidc_providers:
  7088. - idp_id: auth0
  7089. idp_name: Auth0
  7090. issuer: &quot;https://your-tier.eu.auth0.com/&quot; # TO BE FILLED
  7091. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7092. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7093. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7094. user_mapping_provider:
  7095. config:
  7096. localpart_template: &quot;{{ user.preferred_username }}&quot;
  7097. display_name_template: &quot;{{ user.name }}&quot;
  7098. </code></pre>
  7099. <h3 id="authentik"><a class="header" href="#authentik">Authentik</a></h3>
  7100. <p><a href="https://goauthentik.io/">Authentik</a> is an open-source IdP solution.</p>
  7101. <ol>
  7102. <li>Create a provider in Authentik, with type OAuth2/OpenID.</li>
  7103. <li>The parameters are:</li>
  7104. </ol>
  7105. <ul>
  7106. <li>Client Type: Confidential</li>
  7107. <li>JWT Algorithm: RS256</li>
  7108. <li>Scopes: OpenID, Email and Profile</li>
  7109. <li>RSA Key: Select any available key</li>
  7110. <li>Redirect URIs: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  7111. </ul>
  7112. <ol start="3">
  7113. <li>Create an application for synapse in Authentik and link it to the provider.</li>
  7114. <li>Note the slug of your application, Client ID and Client Secret.</li>
  7115. </ol>
  7116. <p>Note: RSA keys must be used for signing for Authentik, ECC keys do not work.</p>
  7117. <p>Synapse config:</p>
  7118. <pre><code class="language-yaml">oidc_providers:
  7119. - idp_id: authentik
  7120. idp_name: authentik
  7121. discover: true
  7122. issuer: &quot;https://your.authentik.example.org/application/o/your-app-slug/&quot; # TO BE FILLED: domain and slug
  7123. client_id: &quot;your client id&quot; # TO BE FILLED
  7124. client_secret: &quot;your client secret&quot; # TO BE FILLED
  7125. scopes:
  7126. - &quot;openid&quot;
  7127. - &quot;profile&quot;
  7128. - &quot;email&quot;
  7129. user_mapping_provider:
  7130. config:
  7131. localpart_template: &quot;{{ user.preferred_username }}&quot;
  7132. 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.
  7133. </code></pre>
  7134. <h3 id="lemonldap"><a class="header" href="#lemonldap">LemonLDAP</a></h3>
  7135. <p><a href="https://lemonldap-ng.org/">LemonLDAP::NG</a> is an open-source IdP solution.</p>
  7136. <ol>
  7137. <li>Create an OpenID Connect Relying Parties in LemonLDAP::NG</li>
  7138. <li>The parameters are:</li>
  7139. </ol>
  7140. <ul>
  7141. <li>Client ID under the basic menu of the new Relying Parties (<code>Options &gt; Basic &gt; Client ID</code>)</li>
  7142. <li>Client secret (<code>Options &gt; Basic &gt; Client secret</code>)</li>
  7143. <li>JWT Algorithm: RS256 within the security menu of the new Relying Parties
  7144. (<code>Options &gt; Security &gt; ID Token signature algorithm</code> and <code>Options &gt; Security &gt; Access Token signature algorithm</code>)</li>
  7145. <li>Scopes: OpenID, Email and Profile</li>
  7146. <li>Allowed redirection addresses for login (<code>Options &gt; Basic &gt; Allowed redirection addresses for login</code> ) :
  7147. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  7148. </ul>
  7149. <p>Synapse config:</p>
  7150. <pre><code class="language-yaml">oidc_providers:
  7151. - idp_id: lemonldap
  7152. idp_name: lemonldap
  7153. discover: true
  7154. issuer: &quot;https://auth.example.org/&quot; # TO BE FILLED: replace with your domain
  7155. client_id: &quot;your client id&quot; # TO BE FILLED
  7156. client_secret: &quot;your client secret&quot; # TO BE FILLED
  7157. scopes:
  7158. - &quot;openid&quot;
  7159. - &quot;profile&quot;
  7160. - &quot;email&quot;
  7161. user_mapping_provider:
  7162. config:
  7163. localpart_template: &quot;{{ user.preferred_username }}}&quot;
  7164. # 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.
  7165. display_name_template: &quot;{{ user.preferred_username|capitalize }}&quot;
  7166. </code></pre>
  7167. <h3 id="github"><a class="header" href="#github">GitHub</a></h3>
  7168. <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
  7169. just a regular OAuth2 provider.</p>
  7170. <p>The <a href="https://developer.github.com/v3/users/#get-the-authenticated-user"><code>/user</code> API endpoint</a>
  7171. can be used to retrieve information on the authenticated user. As the Synapse
  7172. login mechanism needs an attribute to uniquely identify users, and that endpoint
  7173. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  7174. <ol>
  7175. <li>Create a new OAuth application: <a href="https://github.com/settings/applications/new">https://github.com/settings/applications/new</a>.</li>
  7176. <li>Set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  7177. </ol>
  7178. <p>Synapse config:</p>
  7179. <pre><code class="language-yaml">oidc_providers:
  7180. - idp_id: github
  7181. idp_name: Github
  7182. idp_brand: &quot;github&quot; # optional: styling hint for clients
  7183. discover: false
  7184. issuer: &quot;https://github.com/&quot;
  7185. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7186. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7187. authorization_endpoint: &quot;https://github.com/login/oauth/authorize&quot;
  7188. token_endpoint: &quot;https://github.com/login/oauth/access_token&quot;
  7189. userinfo_endpoint: &quot;https://api.github.com/user&quot;
  7190. scopes: [&quot;read:user&quot;]
  7191. user_mapping_provider:
  7192. config:
  7193. subject_claim: &quot;id&quot;
  7194. localpart_template: &quot;{{ user.login }}&quot;
  7195. display_name_template: &quot;{{ user.name }}&quot;
  7196. </code></pre>
  7197. <h3 id="google"><a class="header" href="#google">Google</a></h3>
  7198. <p><a href="https://developers.google.com/identity/protocols/oauth2/openid-connect">Google</a> is an OpenID certified authentication and authorisation provider.</p>
  7199. <ol>
  7200. <li>Set up a project in the Google API Console (see
  7201. <a href="https://developers.google.com/identity/protocols/oauth2/openid-connect#appsetup">documentation</a>).</li>
  7202. <li>Add an &quot;OAuth Client ID&quot; for a Web Application under &quot;Credentials&quot;.</li>
  7203. <li>Copy the Client ID and Client Secret, and add the following to your synapse config:
  7204. <pre><code class="language-yaml">oidc_providers:
  7205. - idp_id: google
  7206. idp_name: Google
  7207. idp_brand: &quot;google&quot; # optional: styling hint for clients
  7208. issuer: &quot;https://accounts.google.com/&quot;
  7209. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7210. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7211. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7212. user_mapping_provider:
  7213. config:
  7214. localpart_template: &quot;{{ user.given_name|lower }}&quot;
  7215. display_name_template: &quot;{{ user.name }}&quot;
  7216. </code></pre>
  7217. </li>
  7218. <li>Back in the Google console, add this Authorized redirect URI: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  7219. </ol>
  7220. <h3 id="twitch"><a class="header" href="#twitch">Twitch</a></h3>
  7221. <ol>
  7222. <li>Setup a developer account on <a href="https://dev.twitch.tv/">Twitch</a></li>
  7223. <li>Obtain the OAuth 2.0 credentials by <a href="https://dev.twitch.tv/console/apps/">creating an app</a></li>
  7224. <li>Add this OAuth Redirect URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  7225. </ol>
  7226. <p>Synapse config:</p>
  7227. <pre><code class="language-yaml">oidc_providers:
  7228. - idp_id: twitch
  7229. idp_name: Twitch
  7230. issuer: &quot;https://id.twitch.tv/oauth2/&quot;
  7231. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7232. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7233. client_auth_method: &quot;client_secret_post&quot;
  7234. user_mapping_provider:
  7235. config:
  7236. localpart_template: &quot;{{ user.preferred_username }}&quot;
  7237. display_name_template: &quot;{{ user.name }}&quot;
  7238. </code></pre>
  7239. <h3 id="gitlab"><a class="header" href="#gitlab">GitLab</a></h3>
  7240. <ol>
  7241. <li>Create a <a href="https://gitlab.com/profile/applications">new application</a>.</li>
  7242. <li>Add the <code>read_user</code> and <code>openid</code> scopes.</li>
  7243. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  7244. </ol>
  7245. <p>Synapse config:</p>
  7246. <pre><code class="language-yaml">oidc_providers:
  7247. - idp_id: gitlab
  7248. idp_name: Gitlab
  7249. idp_brand: &quot;gitlab&quot; # optional: styling hint for clients
  7250. issuer: &quot;https://gitlab.com/&quot;
  7251. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7252. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7253. client_auth_method: &quot;client_secret_post&quot;
  7254. scopes: [&quot;openid&quot;, &quot;read_user&quot;]
  7255. user_profile_method: &quot;userinfo_endpoint&quot;
  7256. user_mapping_provider:
  7257. config:
  7258. localpart_template: '{{ user.nickname }}'
  7259. display_name_template: '{{ user.name }}'
  7260. </code></pre>
  7261. <h3 id="facebook"><a class="header" href="#facebook">Facebook</a></h3>
  7262. <ol start="0">
  7263. <li>You will need a Facebook developer account. You can register for one
  7264. <a href="https://developers.facebook.com/async/registration/">here</a>.</li>
  7265. <li>On the <a href="https://developers.facebook.com/apps/">apps</a> page of the developer
  7266. console, &quot;Create App&quot;, and choose &quot;Build Connected Experiences&quot;.</li>
  7267. <li>Once the app is created, add &quot;Facebook Login&quot; and choose &quot;Web&quot;. You don't
  7268. need to go through the whole form here.</li>
  7269. <li>In the left-hand menu, open &quot;Products&quot;/&quot;Facebook Login&quot;/&quot;Settings&quot;.
  7270. <ul>
  7271. <li>Add <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> as an OAuth Redirect
  7272. URL.</li>
  7273. </ul>
  7274. </li>
  7275. <li>In the left-hand menu, open &quot;Settings/Basic&quot;. Here you can copy the &quot;App ID&quot;
  7276. and &quot;App Secret&quot; for use below.</li>
  7277. </ol>
  7278. <p>Synapse config:</p>
  7279. <pre><code class="language-yaml"> - idp_id: facebook
  7280. idp_name: Facebook
  7281. idp_brand: &quot;facebook&quot; # optional: styling hint for clients
  7282. discover: false
  7283. issuer: &quot;https://www.facebook.com&quot;
  7284. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7285. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7286. scopes: [&quot;openid&quot;, &quot;email&quot;]
  7287. authorization_endpoint: &quot;https://facebook.com/dialog/oauth&quot;
  7288. token_endpoint: &quot;https://graph.facebook.com/v9.0/oauth/access_token&quot;
  7289. jwks_uri: &quot;https://www.facebook.com/.well-known/oauth/openid/jwks/&quot;
  7290. user_mapping_provider:
  7291. config:
  7292. display_name_template: &quot;{{ user.name }}&quot;
  7293. email_template: &quot;{{ user.email }}&quot;
  7294. </code></pre>
  7295. <p>Relevant documents:</p>
  7296. <ul>
  7297. <li><a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow">Manually Build a Login Flow</a></li>
  7298. <li><a href="https://developers.facebook.com/docs/graph-api/using-graph-api/">Using Facebook's Graph API</a></li>
  7299. <li><a href="https://developers.facebook.com/docs/graph-api/reference/user">Reference to the User endpoint</a></li>
  7300. </ul>
  7301. <p>Facebook do have an <a href="https://www.facebook.com/.well-known/openid-configuration">OIDC discovery endpoint</a>,
  7302. but it has a <code>response_types_supported</code> which excludes &quot;code&quot; (which we rely on, and
  7303. is even mentioned in their <a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#login">documentation</a>),
  7304. so we have to disable discovery and configure the URIs manually.</p>
  7305. <h3 id="gitea"><a class="header" href="#gitea">Gitea</a></h3>
  7306. <p>Gitea is, like Github, not an OpenID provider, but just an OAuth2 provider.</p>
  7307. <p>The <a href="https://try.gitea.io/api/swagger#/user/userGetCurrent"><code>/user</code> API endpoint</a>
  7308. can be used to retrieve information on the authenticated user. As the Synapse
  7309. login mechanism needs an attribute to uniquely identify users, and that endpoint
  7310. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  7311. <ol>
  7312. <li>Create a new application.</li>
  7313. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  7314. </ol>
  7315. <p>Synapse config:</p>
  7316. <pre><code class="language-yaml">oidc_providers:
  7317. - idp_id: gitea
  7318. idp_name: Gitea
  7319. discover: false
  7320. issuer: &quot;https://your-gitea.com/&quot;
  7321. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7322. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7323. client_auth_method: client_secret_post
  7324. scopes: [] # Gitea doesn't support Scopes
  7325. authorization_endpoint: &quot;https://your-gitea.com/login/oauth/authorize&quot;
  7326. token_endpoint: &quot;https://your-gitea.com/login/oauth/access_token&quot;
  7327. userinfo_endpoint: &quot;https://your-gitea.com/api/v1/user&quot;
  7328. user_mapping_provider:
  7329. config:
  7330. subject_claim: &quot;id&quot;
  7331. localpart_template: &quot;{{ user.login }}&quot;
  7332. display_name_template: &quot;{{ user.full_name }}&quot;
  7333. </code></pre>
  7334. <h3 id="xwiki"><a class="header" href="#xwiki">XWiki</a></h3>
  7335. <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>
  7336. <p>Synapse config:</p>
  7337. <pre><code class="language-yaml">oidc_providers:
  7338. - idp_id: xwiki
  7339. idp_name: &quot;XWiki&quot;
  7340. issuer: &quot;https://myxwikihost/xwiki/oidc/&quot;
  7341. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7342. client_auth_method: none
  7343. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7344. user_profile_method: &quot;userinfo_endpoint&quot;
  7345. user_mapping_provider:
  7346. config:
  7347. localpart_template: &quot;{{ user.preferred_username }}&quot;
  7348. display_name_template: &quot;{{ user.name }}&quot;
  7349. </code></pre>
  7350. <h3 id="apple"><a class="header" href="#apple">Apple</a></h3>
  7351. <p>Configuring &quot;Sign in with Apple&quot; (SiWA) requires an Apple Developer account.</p>
  7352. <p>You will need to create a new &quot;Services ID&quot; for SiWA, and create and download a
  7353. private key with &quot;SiWA&quot; enabled.</p>
  7354. <p>As well as the private key file, you will need:</p>
  7355. <ul>
  7356. <li>Client ID: the &quot;identifier&quot; you gave the &quot;Services ID&quot;</li>
  7357. <li>Team ID: a 10-character ID associated with your developer account.</li>
  7358. <li>Key ID: the 10-character identifier for the key.</li>
  7359. </ul>
  7360. <p><a href="https://help.apple.com/developer-account/?lang=en#/dev77c875b7e">Apple's developer documentation</a>
  7361. has more information on setting up SiWA.</p>
  7362. <p>The synapse config will look like this:</p>
  7363. <pre><code class="language-yaml"> - idp_id: apple
  7364. idp_name: Apple
  7365. issuer: &quot;https://appleid.apple.com&quot;
  7366. client_id: &quot;your-client-id&quot; # Set to the &quot;identifier&quot; for your &quot;ServicesID&quot;
  7367. client_auth_method: &quot;client_secret_post&quot;
  7368. client_secret_jwt_key:
  7369. key_file: &quot;/path/to/AuthKey_KEYIDCODE.p8&quot; # point to your key file
  7370. jwt_header:
  7371. alg: ES256
  7372. kid: &quot;KEYIDCODE&quot; # Set to the 10-char Key ID
  7373. jwt_payload:
  7374. iss: TEAMIDCODE # Set to the 10-char Team ID
  7375. scopes: [&quot;name&quot;, &quot;email&quot;, &quot;openid&quot;]
  7376. authorization_endpoint: https://appleid.apple.com/auth/authorize?response_mode=form_post
  7377. user_mapping_provider:
  7378. config:
  7379. email_template: &quot;{{ user.email }}&quot;
  7380. </code></pre>
  7381. <h3 id="django-oauth-toolkit"><a class="header" href="#django-oauth-toolkit">Django OAuth Toolkit</a></h3>
  7382. <p><a href="https://github.com/jazzband/django-oauth-toolkit">django-oauth-toolkit</a> is a
  7383. Django application providing out of the box all the endpoints, data and logic
  7384. needed to add OAuth2 capabilities to your Django projects. It supports
  7385. <a href="https://django-oauth-toolkit.readthedocs.io/en/latest/oidc.html">OpenID Connect too</a>.</p>
  7386. <p>Configuration on Django's side:</p>
  7387. <ol>
  7388. <li>Add an application: <code>https://example.com/admin/oauth2_provider/application/add/</code> and choose parameters like this:</li>
  7389. </ol>
  7390. <ul>
  7391. <li><code>Redirect uris</code>: <code>https://synapse.example.com/_synapse/client/oidc/callback</code></li>
  7392. <li><code>Client type</code>: <code>Confidential</code></li>
  7393. <li><code>Authorization grant type</code>: <code>Authorization code</code></li>
  7394. <li><code>Algorithm</code>: <code>HMAC with SHA-2 256</code></li>
  7395. </ul>
  7396. <ol start="2">
  7397. <li>
  7398. <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>
  7399. <details>
  7400. <summary>Code sample</summary>
  7401. <pre><code class="language-python">class CustomOAuth2Validator(OAuth2Validator):
  7402. def get_additional_claims(self, request):
  7403. return {
  7404. &quot;sub&quot;: request.user.email,
  7405. &quot;email&quot;: request.user.email,
  7406. &quot;first_name&quot;: request.user.first_name,
  7407. &quot;last_name&quot;: request.user.last_name,
  7408. }
  7409. </code></pre>
  7410. </details>
  7411. </li>
  7412. </ol>
  7413. <p>Your synapse config is then:</p>
  7414. <pre><code class="language-yaml">oidc_providers:
  7415. - idp_id: django_example
  7416. idp_name: &quot;Django Example&quot;
  7417. issuer: &quot;https://example.com/o/&quot;
  7418. client_id: &quot;your-client-id&quot; # CHANGE ME
  7419. client_secret: &quot;your-client-secret&quot; # CHANGE ME
  7420. scopes: [&quot;openid&quot;]
  7421. user_profile_method: &quot;userinfo_endpoint&quot; # needed because oauth-toolkit does not include user information in the authorization response
  7422. user_mapping_provider:
  7423. config:
  7424. localpart_template: &quot;{{ user.email.split('@')[0] }}&quot;
  7425. display_name_template: &quot;{{ user.first_name }} {{ user.last_name }}&quot;
  7426. email_template: &quot;{{ user.email }}&quot;
  7427. </code></pre>
  7428. <div style="break-before: page; page-break-before: always;"></div><h1 id="saml"><a class="header" href="#saml">SAML</a></h1>
  7429. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language">Security Assertion
  7430. Markup Language</a>
  7431. (SAML) protocol natively.</p>
  7432. <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
  7433. file</a> for more details.</p>
  7434. <div style="break-before: page; page-break-before: always;"></div><h1 id="cas"><a class="header" href="#cas">CAS</a></h1>
  7435. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Central_Authentication_Service">Central Authentication
  7436. Service protocol</a>
  7437. (CAS) natively.</p>
  7438. <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>
  7439. sections of the configuration manual for more details.</p>
  7440. <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>
  7441. <p>A mapping provider is a Python class (loaded via a Python module) that
  7442. works out how to map attributes of a SSO response to Matrix-specific
  7443. user attributes. Details such as user ID localpart, displayname, and even avatar
  7444. URLs are all things that can be mapped from talking to a SSO service.</p>
  7445. <p>As an example, a SSO service may return the email address
  7446. &quot;john.smith@example.com&quot; for a user, whereas Synapse will need to figure out how
  7447. to turn that into a displayname when creating a Matrix user for this individual.
  7448. It may choose <code>John Smith</code>, or <code>Smith, John [Example.com]</code> or any number of
  7449. variations. As each Synapse configuration may want something different, this is
  7450. where SAML mapping providers come into play.</p>
  7451. <p>SSO mapping providers are currently supported for OpenID and SAML SSO
  7452. configurations. Please see the details below for how to implement your own.</p>
  7453. <p>It is up to the mapping provider whether the user should be assigned a predefined
  7454. Matrix ID based on the SSO attributes, or if the user should be allowed to
  7455. choose their own username.</p>
  7456. <p>In the first case - where users are automatically allocated a Matrix ID - it is
  7457. the responsibility of the mapping provider to normalise the SSO attributes and
  7458. map them to a valid Matrix ID. The <a href="https://spec.matrix.org/latest/appendices/#user-identifiers">specification for Matrix
  7459. IDs</a> has some
  7460. information about what is considered valid.</p>
  7461. <p>If the mapping provider does not assign a Matrix ID, then Synapse will
  7462. automatically serve an HTML page allowing the user to pick their own username.</p>
  7463. <p>External mapping providers are provided to Synapse in the form of an external
  7464. Python module. You can retrieve this module from <a href="https://pypi.org">PyPI</a> or elsewhere,
  7465. but it must be importable via Synapse (e.g. it must be in the same virtualenv
  7466. as Synapse). The Synapse config is then modified to point to the mapping provider
  7467. (and optionally provide additional configuration for it).</p>
  7468. <h2 id="openid-mapping-providers"><a class="header" href="#openid-mapping-providers">OpenID Mapping Providers</a></h2>
  7469. <p>The OpenID mapping provider can be customized by editing the
  7470. <a href="usage/configuration/config_documentation.html#oidc_providers"><code>oidc_providers.user_mapping_provider.module</code></a>
  7471. config option.</p>
  7472. <p><code>oidc_providers.user_mapping_provider.config</code> allows you to provide custom
  7473. configuration options to the module. Check with the module's documentation for
  7474. what options it provides (if any). The options listed by default are for the
  7475. user mapping provider built in to Synapse. If using a custom module, you should
  7476. comment these options out and use those specified by the module instead.</p>
  7477. <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>
  7478. <p>A custom mapping provider must specify the following methods:</p>
  7479. <ul>
  7480. <li><code>def __init__(self, parsed_config)</code>
  7481. <ul>
  7482. <li>Arguments:
  7483. <ul>
  7484. <li><code>parsed_config</code> - A configuration object that is the return value of the
  7485. <code>parse_config</code> method. You should set any configuration options needed by
  7486. the module here.</li>
  7487. </ul>
  7488. </li>
  7489. </ul>
  7490. </li>
  7491. <li><code>def parse_config(config)</code>
  7492. <ul>
  7493. <li>This method should have the <code>@staticmethod</code> decoration.</li>
  7494. <li>Arguments:
  7495. <ul>
  7496. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  7497. <code>oidc_providers.user_mapping_provider.config</code> homeserver config option.
  7498. Runs on homeserver startup. Providers should extract and validate
  7499. any option values they need here.</li>
  7500. </ul>
  7501. </li>
  7502. <li>Whatever is returned will be passed back to the user mapping provider module's
  7503. <code>__init__</code> method during construction.</li>
  7504. </ul>
  7505. </li>
  7506. <li><code>def get_remote_user_id(self, userinfo)</code>
  7507. <ul>
  7508. <li>Arguments:
  7509. <ul>
  7510. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  7511. information from.</li>
  7512. </ul>
  7513. </li>
  7514. <li>This method must return a string, which is the unique, immutable identifier
  7515. for the user. Commonly the <code>sub</code> claim of the response.</li>
  7516. </ul>
  7517. </li>
  7518. <li><code>async def map_user_attributes(self, userinfo, token, failures)</code>
  7519. <ul>
  7520. <li>This method must be async.</li>
  7521. <li>Arguments:
  7522. <ul>
  7523. <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>
  7524. object to extract user information from.</li>
  7525. <li><code>token</code> - A dictionary which includes information necessary to make
  7526. further requests to the OpenID provider.</li>
  7527. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  7528. mxid localpart mapping has failed. This should be used
  7529. to create a deduplicated mxid localpart which should be
  7530. returned instead. For example, if this method returns
  7531. <code>john.doe</code> as the value of <code>localpart</code> in the returned
  7532. dict, and that is already taken on the homeserver, this
  7533. method will be called again with the same parameters but
  7534. with failures=1. The method should then return a different
  7535. <code>localpart</code> value, such as <code>john.doe1</code>.</li>
  7536. </ul>
  7537. </li>
  7538. <li>Returns a dictionary with two keys:
  7539. <ul>
  7540. <li><code>localpart</code>: A string, used to generate the Matrix ID. If this is
  7541. <code>None</code>, the user is prompted to pick their own username. This is only used
  7542. during a user's first login. Once a localpart has been associated with a
  7543. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  7544. <li><code>confirm_localpart</code>: A boolean. If set to <code>True</code>, when a <code>localpart</code>
  7545. string is returned from this method, Synapse will prompt the user to
  7546. either accept this localpart or pick their own username. Otherwise this
  7547. option has no effect. If omitted, defaults to <code>False</code>.</li>
  7548. <li><code>display_name</code>: An optional string, the display name for the user.</li>
  7549. <li><code>emails</code>: A list of strings, the email address(es) to associate with
  7550. this user. If omitted, defaults to an empty list.</li>
  7551. </ul>
  7552. </li>
  7553. </ul>
  7554. </li>
  7555. <li><code>async def get_extra_attributes(self, userinfo, token)</code>
  7556. <ul>
  7557. <li>
  7558. <p>This method must be async.</p>
  7559. </li>
  7560. <li>
  7561. <p>Arguments:</p>
  7562. <ul>
  7563. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  7564. information from.</li>
  7565. <li><code>token</code> - A dictionary which includes information necessary to make
  7566. further requests to the OpenID provider.</li>
  7567. </ul>
  7568. </li>
  7569. <li>
  7570. <p>Returns a dictionary that is suitable to be serialized to JSON. This
  7571. will be returned as part of the response during a successful login.</p>
  7572. <p>Note that care should be taken to not overwrite any of the parameters
  7573. usually returned as part of the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3login">login response</a>.</p>
  7574. </li>
  7575. </ul>
  7576. </li>
  7577. </ul>
  7578. <h3 id="default-openid-mapping-provider"><a class="header" href="#default-openid-mapping-provider">Default OpenID Mapping Provider</a></h3>
  7579. <p>Synapse has a built-in OpenID mapping provider if a custom provider isn't
  7580. specified in the config. It is located at
  7581. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/oidc.py"><code>synapse.handlers.oidc.JinjaOidcMappingProvider</code></a>.</p>
  7582. <h2 id="saml-mapping-providers"><a class="header" href="#saml-mapping-providers">SAML Mapping Providers</a></h2>
  7583. <p>The SAML mapping provider can be customized by editing the
  7584. <a href="docs/usage/configuration/config_documentation.html#saml2_config"><code>saml2_config.user_mapping_provider.module</code></a>
  7585. config option.</p>
  7586. <p><code>saml2_config.user_mapping_provider.config</code> allows you to provide custom
  7587. configuration options to the module. Check with the module's documentation for
  7588. what options it provides (if any). The options listed by default are for the
  7589. user mapping provider built in to Synapse. If using a custom module, you should
  7590. comment these options out and use those specified by the module instead.</p>
  7591. <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>
  7592. <p>A custom mapping provider must specify the following methods:</p>
  7593. <ul>
  7594. <li><code>def __init__(self, parsed_config, module_api)</code>
  7595. <ul>
  7596. <li>Arguments:
  7597. <ul>
  7598. <li><code>parsed_config</code> - A configuration object that is the return value of the
  7599. <code>parse_config</code> method. You should set any configuration options needed by
  7600. the module here.</li>
  7601. <li><code>module_api</code> - a <code>synapse.module_api.ModuleApi</code> object which provides the
  7602. stable API available for extension modules.</li>
  7603. </ul>
  7604. </li>
  7605. </ul>
  7606. </li>
  7607. <li><code>def parse_config(config)</code>
  7608. <ul>
  7609. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  7610. <li>Arguments:
  7611. <ul>
  7612. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  7613. <code>saml_config.user_mapping_provider.config</code> homeserver config option.
  7614. Runs on homeserver startup. Providers should extract and validate
  7615. any option values they need here.</li>
  7616. </ul>
  7617. </li>
  7618. <li>Whatever is returned will be passed back to the user mapping provider module's
  7619. <code>__init__</code> method during construction.</li>
  7620. </ul>
  7621. </li>
  7622. <li><code>def get_saml_attributes(config)</code>
  7623. <ul>
  7624. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  7625. <li>Arguments:
  7626. <ul>
  7627. <li><code>config</code> - A object resulting from a call to <code>parse_config</code>.</li>
  7628. </ul>
  7629. </li>
  7630. <li>Returns a tuple of two sets. The first set equates to the SAML auth
  7631. response attributes that are required for the module to function, whereas
  7632. the second set consists of those attributes which can be used if available,
  7633. but are not necessary.</li>
  7634. </ul>
  7635. </li>
  7636. <li><code>def get_remote_user_id(self, saml_response, client_redirect_url)</code>
  7637. <ul>
  7638. <li>Arguments:
  7639. <ul>
  7640. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  7641. information from.</li>
  7642. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  7643. redirected to.</li>
  7644. </ul>
  7645. </li>
  7646. <li>This method must return a string, which is the unique, immutable identifier
  7647. for the user. Commonly the <code>uid</code> claim of the response.</li>
  7648. </ul>
  7649. </li>
  7650. <li><code>def saml_response_to_user_attributes(self, saml_response, failures, client_redirect_url)</code>
  7651. <ul>
  7652. <li>
  7653. <p>Arguments:</p>
  7654. <ul>
  7655. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  7656. information from.</li>
  7657. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  7658. mxid localpart mapping has failed. This should be used
  7659. to create a deduplicated mxid localpart which should be
  7660. returned instead. For example, if this method returns
  7661. <code>john.doe</code> as the value of <code>mxid_localpart</code> in the returned
  7662. dict, and that is already taken on the homeserver, this
  7663. method will be called again with the same parameters but
  7664. with failures=1. The method should then return a different
  7665. <code>mxid_localpart</code> value, such as <code>john.doe1</code>.</li>
  7666. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  7667. redirected to.</li>
  7668. </ul>
  7669. </li>
  7670. <li>
  7671. <p>This method must return a dictionary, which will then be used by Synapse
  7672. to build a new user. The following keys are allowed:</p>
  7673. <ul>
  7674. <li><code>mxid_localpart</code> - A string, the mxid localpart of the new user. If this is
  7675. <code>None</code>, the user is prompted to pick their own username. This is only used
  7676. during a user's first login. Once a localpart has been associated with a
  7677. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  7678. <li><code>displayname</code> - The displayname of the new user. If not provided, will default to
  7679. the value of <code>mxid_localpart</code>.</li>
  7680. <li><code>emails</code> - A list of emails for the new user. If not provided, will
  7681. default to an empty list.</li>
  7682. </ul>
  7683. <p>Alternatively it can raise a <code>synapse.api.errors.RedirectException</code> to
  7684. redirect the user to another page. This is useful to prompt the user for
  7685. additional information, e.g. if you want them to provide their own username.
  7686. It is the responsibility of the mapping provider to either redirect back
  7687. to <code>client_redirect_url</code> (including any additional information) or to
  7688. complete registration using methods from the <code>ModuleApi</code>.</p>
  7689. </li>
  7690. </ul>
  7691. </li>
  7692. </ul>
  7693. <h3 id="default-saml-mapping-provider"><a class="header" href="#default-saml-mapping-provider">Default SAML Mapping Provider</a></h3>
  7694. <p>Synapse has a built-in SAML mapping provider if a custom provider isn't
  7695. specified in the config. It is located at
  7696. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/saml.py"><code>synapse.handlers.saml.DefaultSamlMappingProvider</code></a>.</p>
  7697. <div style="break-before: page; page-break-before: always;"></div><h2 style="color:red">
  7698. This page of the Synapse documentation is now deprecated. For up to date
  7699. documentation on setting up or writing a password auth provider module, please see
  7700. <a href="modules/index.html">this page</a>.
  7701. </h2>
  7702. <h1 id="password-auth-provider-modules"><a class="header" href="#password-auth-provider-modules">Password auth provider modules</a></h1>
  7703. <p>Password auth providers offer a way for server administrators to
  7704. integrate their Synapse installation with an existing authentication
  7705. system.</p>
  7706. <p>A password auth provider is a Python class which is dynamically loaded
  7707. into Synapse, and provides a number of methods by which it can integrate
  7708. with the authentication system.</p>
  7709. <p>This document serves as a reference for those looking to implement their
  7710. own password auth providers. Additionally, here is a list of known
  7711. password auth provider module implementations:</p>
  7712. <ul>
  7713. <li><a href="https://github.com/matrix-org/matrix-synapse-ldap3/">matrix-synapse-ldap3</a></li>
  7714. <li><a href="https://github.com/devture/matrix-synapse-shared-secret-auth">matrix-synapse-shared-secret-auth</a></li>
  7715. <li><a href="https://github.com/ma1uta/matrix-synapse-rest-password-provider">matrix-synapse-rest-password-provider</a></li>
  7716. </ul>
  7717. <h2 id="required-methods"><a class="header" href="#required-methods">Required methods</a></h2>
  7718. <p>Password auth provider classes must provide the following methods:</p>
  7719. <ul>
  7720. <li>
  7721. <p><code>parse_config(config)</code>
  7722. This method is passed the <code>config</code> object for this module from the
  7723. homeserver configuration file.</p>
  7724. <p>It should perform any appropriate sanity checks on the provided
  7725. configuration, and return an object which is then passed into
  7726. <code>__init__</code>.</p>
  7727. <p>This method should have the <code>@staticmethod</code> decoration.</p>
  7728. </li>
  7729. <li>
  7730. <p><code>__init__(self, config, account_handler)</code></p>
  7731. <p>The constructor is passed the config object returned by
  7732. <code>parse_config</code>, and a <code>synapse.module_api.ModuleApi</code> object which
  7733. allows the password provider to check if accounts exist and/or create
  7734. new ones.</p>
  7735. </li>
  7736. </ul>
  7737. <h2 id="optional-methods"><a class="header" href="#optional-methods">Optional methods</a></h2>
  7738. <p>Password auth provider classes may optionally provide the following methods:</p>
  7739. <ul>
  7740. <li>
  7741. <p><code>get_db_schema_files(self)</code></p>
  7742. <p>This method, if implemented, should return an Iterable of
  7743. <code>(name, stream)</code> pairs of database schema files. Each file is applied
  7744. in turn at initialisation, and a record is then made in the database
  7745. so that it is not re-applied on the next start.</p>
  7746. </li>
  7747. <li>
  7748. <p><code>get_supported_login_types(self)</code></p>
  7749. <p>This method, if implemented, should return a <code>dict</code> mapping from a
  7750. login type identifier (such as <code>m.login.password</code>) to an iterable
  7751. giving the fields which must be provided by the user in the submission
  7752. to <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-login">the <code>/login</code> API</a>.
  7753. These fields are passed in the <code>login_dict</code> dictionary to <code>check_auth</code>.</p>
  7754. <p>For example, if a password auth provider wants to implement a custom
  7755. login type of <code>com.example.custom_login</code>, where the client is expected
  7756. to pass the fields <code>secret1</code> and <code>secret2</code>, the provider should
  7757. implement this method and return the following dict:</p>
  7758. <pre><code class="language-python">{&quot;com.example.custom_login&quot;: (&quot;secret1&quot;, &quot;secret2&quot;)}
  7759. </code></pre>
  7760. </li>
  7761. <li>
  7762. <p><code>check_auth(self, username, login_type, login_dict)</code></p>
  7763. <p>This method does the real work. If implemented, it
  7764. will be called for each login attempt where the login type matches one
  7765. of the keys returned by <code>get_supported_login_types</code>.</p>
  7766. <p>It is passed the (possibly unqualified) <code>user</code> field provided by the client,
  7767. the login type, and a dictionary of login secrets passed by the
  7768. client.</p>
  7769. <p>The method should return an <code>Awaitable</code> object, which resolves
  7770. to the canonical <code>@localpart:domain</code> user ID if authentication is
  7771. successful, and <code>None</code> if not.</p>
  7772. <p>Alternatively, the <code>Awaitable</code> can resolve to a <code>(str, func)</code> tuple, in
  7773. which case the second field is a callback which will be called with
  7774. the result from the <code>/login</code> call (including <code>access_token</code>,
  7775. <code>device_id</code>, etc.)</p>
  7776. </li>
  7777. <li>
  7778. <p><code>check_3pid_auth(self, medium, address, password)</code></p>
  7779. <p>This method, if implemented, is called when a user attempts to
  7780. register or log in with a third party identifier, such as email. It is
  7781. passed the medium (ex. &quot;email&quot;), an address (ex.
  7782. &quot;<a href="mailto:jdoe@example.com">jdoe@example.com</a>&quot;) and the user's password.</p>
  7783. <p>The method should return an <code>Awaitable</code> object, which resolves
  7784. to a <code>str</code> containing the user's (canonical) User id if
  7785. authentication was successful, and <code>None</code> if not.</p>
  7786. <p>As with <code>check_auth</code>, the <code>Awaitable</code> may alternatively resolve to a
  7787. <code>(user_id, callback)</code> tuple.</p>
  7788. </li>
  7789. <li>
  7790. <p><code>check_password(self, user_id, password)</code></p>
  7791. <p>This method provides a simpler interface than
  7792. <code>get_supported_login_types</code> and <code>check_auth</code> for password auth
  7793. providers that just want to provide a mechanism for validating
  7794. <code>m.login.password</code> logins.</p>
  7795. <p>If implemented, it will be called to check logins with an
  7796. <code>m.login.password</code> login type. It is passed a qualified
  7797. <code>@localpart:domain</code> user id, and the password provided by the user.</p>
  7798. <p>The method should return an <code>Awaitable</code> object, which resolves
  7799. to <code>True</code> if authentication is successful, and <code>False</code> if not.</p>
  7800. </li>
  7801. <li>
  7802. <p><code>on_logged_out(self, user_id, device_id, access_token)</code></p>
  7803. <p>This method, if implemented, is called when a user logs out. It is
  7804. passed the qualified user ID, the ID of the deactivated device (if
  7805. any: access tokens are occasionally created without an associated
  7806. device ID), and the (now deactivated) access token.</p>
  7807. <p>It may return an <code>Awaitable</code> object; the logout request will
  7808. wait for the <code>Awaitable</code> to complete, but the result is ignored.</p>
  7809. </li>
  7810. </ul>
  7811. <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>
  7812. <p>Synapse comes with a non-standard login type to support
  7813. <a href="https://en.wikipedia.org/wiki/JSON_Web_Token">JSON Web Tokens</a>. In general the
  7814. documentation for
  7815. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#login">the login endpoint</a>
  7816. is still valid (and the mechanism works similarly to the
  7817. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#token-based">token based login</a>).</p>
  7818. <p>To log in using a JSON Web Token, clients should submit a <code>/login</code> request as
  7819. follows:</p>
  7820. <pre><code class="language-json">{
  7821. &quot;type&quot;: &quot;org.matrix.login.jwt&quot;,
  7822. &quot;token&quot;: &quot;&lt;jwt&gt;&quot;
  7823. }
  7824. </code></pre>
  7825. <p>The <code>token</code> field should include the JSON web token with the following claims:</p>
  7826. <ul>
  7827. <li>A claim that encodes the local part of the user ID is required. By default,
  7828. the <code>sub</code> (subject) claim is used, or a custom claim can be set in the
  7829. configuration file.</li>
  7830. <li>The expiration time (<code>exp</code>), not before time (<code>nbf</code>), and issued at (<code>iat</code>)
  7831. claims are optional, but validated if present.</li>
  7832. <li>The issuer (<code>iss</code>) claim is optional, but required and validated if configured.</li>
  7833. <li>The audience (<code>aud</code>) claim is optional, but required and validated if configured.
  7834. Providing the audience claim when not configured will cause validation to fail.</li>
  7835. </ul>
  7836. <p>In the case that the token is not valid, the homeserver must respond with
  7837. <code>403 Forbidden</code> and an error code of <code>M_FORBIDDEN</code>.</p>
  7838. <p>As with other login types, there are additional fields (e.g. <code>device_id</code> and
  7839. <code>initial_device_display_name</code>) which can be included in the above request.</p>
  7840. <h2 id="preparing-synapse-1"><a class="header" href="#preparing-synapse-1">Preparing Synapse</a></h2>
  7841. <p>The JSON Web Token integration in Synapse uses the
  7842. <a href="https://docs.authlib.org/en/latest/index.html"><code>Authlib</code></a> library, which must be installed
  7843. as follows:</p>
  7844. <ul>
  7845. <li>
  7846. <p>The relevant libraries are included in the Docker images and Debian packages
  7847. provided by <code>matrix.org</code> so no further action is needed.</p>
  7848. </li>
  7849. <li>
  7850. <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>
  7851. </li>
  7852. <li>
  7853. <p>For other installation mechanisms, see the documentation provided by the
  7854. maintainer.</p>
  7855. </li>
  7856. </ul>
  7857. <p>To enable the JSON web token integration, you should then add a <code>jwt_config</code> option
  7858. to your configuration file. See the <a href="usage/configuration/config_documentation.html#jwt_config">configuration manual</a> for some
  7859. sample settings.</p>
  7860. <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>
  7861. <p>Although JSON Web Tokens are typically generated from an external server, the
  7862. example below uses a locally generated JWT.</p>
  7863. <ol>
  7864. <li>
  7865. <p>Configure Synapse with JWT logins, note that this example uses a pre-shared
  7866. secret and an algorithm of HS256:</p>
  7867. <pre><code class="language-yaml">jwt_config:
  7868. enabled: true
  7869. secret: &quot;my-secret-token&quot;
  7870. algorithm: &quot;HS256&quot;
  7871. </code></pre>
  7872. </li>
  7873. <li>
  7874. <p>Generate a JSON web token:</p>
  7875. <p>You can use the following short Python snippet to generate a JWT
  7876. protected by an HMAC.
  7877. Take care that the <code>secret</code> and the algorithm given in the <code>header</code> match
  7878. the entries from <code>jwt_config</code> above.</p>
  7879. <pre><code class="language-python">from authlib.jose import jwt
  7880. header = {&quot;alg&quot;: &quot;HS256&quot;}
  7881. payload = {&quot;sub&quot;: &quot;user1&quot;, &quot;aud&quot;: [&quot;audience&quot;]}
  7882. secret = &quot;my-secret-token&quot;
  7883. result = jwt.encode(header, payload, secret)
  7884. print(result.decode(&quot;ascii&quot;))
  7885. </code></pre>
  7886. </li>
  7887. <li>
  7888. <p>Query for the login types and ensure <code>org.matrix.login.jwt</code> is there:</p>
  7889. <pre><code class="language-bash">curl http://localhost:8080/_matrix/client/r0/login
  7890. </code></pre>
  7891. </li>
  7892. <li>
  7893. <p>Login used the generated JSON web token from above:</p>
  7894. <pre><code class="language-bash">$ curl http://localhost:8082/_matrix/client/r0/login -X POST \
  7895. --data '{&quot;type&quot;:&quot;org.matrix.login.jwt&quot;,&quot;token&quot;:&quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.Ag71GT8v01UO3w80aqRPTeuVPBIBZkYhNTJJ-_-zQIc&quot;}'
  7896. {
  7897. &quot;access_token&quot;: &quot;&lt;access token&gt;&quot;,
  7898. &quot;device_id&quot;: &quot;ACBDEFGHI&quot;,
  7899. &quot;home_server&quot;: &quot;localhost:8080&quot;,
  7900. &quot;user_id&quot;: &quot;@test-user:localhost:8480&quot;
  7901. }
  7902. </code></pre>
  7903. </li>
  7904. </ol>
  7905. <p>You should now be able to use the returned access token to query the client API.</p>
  7906. <div style="break-before: page; page-break-before: always;"></div><h1 id="refresh-tokens"><a class="header" href="#refresh-tokens">Refresh Tokens</a></h1>
  7907. <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>
  7908. <h2 id="background-and-motivation"><a class="header" href="#background-and-motivation">Background and motivation</a></h2>
  7909. <p>Synapse users' sessions are identified by <strong>access tokens</strong>; access tokens are
  7910. issued to users on login. Each session gets a unique access token which identifies
  7911. it; the access token must be kept secret as it grants access to the user's account.</p>
  7912. <p>Traditionally, these access tokens were eternally valid (at least until the user
  7913. explicitly chose to log out).</p>
  7914. <p>In some cases, it may be desirable for these access tokens to expire so that the
  7915. potential damage caused by leaking an access token is reduced.
  7916. On the other hand, forcing a user to re-authenticate (log in again) often might
  7917. be too much of an inconvenience.</p>
  7918. <p><strong>Refresh tokens</strong> are a mechanism to avoid some of this inconvenience whilst
  7919. still getting most of the benefits of short access token lifetimes.
  7920. Refresh tokens are also a concept present in OAuth 2 — further reading is available
  7921. <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.5">here</a>.</p>
  7922. <p>When refresh tokens are in use, both an access token and a refresh token will be
  7923. issued to users on login. The access token will expire after a predetermined amount
  7924. of time, but otherwise works in the same way as before. When the access token is
  7925. close to expiring (or has expired), the user's client should present the homeserver
  7926. (Synapse) with the refresh token.</p>
  7927. <p>The homeserver will then generate a new access token and refresh token for the user
  7928. and return them. The old refresh token is invalidated and can not be used again*.</p>
  7929. <p>Finally, refresh tokens also make it possible for sessions to be logged out if they
  7930. are inactive for too long, before the session naturally ends; see the configuration
  7931. guide below.</p>
  7932. <p>*To prevent issues if clients lose connection half-way through refreshing a token,
  7933. the refresh token is only invalidated once the new access token has been used at
  7934. least once. For all intents and purposes, the above simplification is sufficient.</p>
  7935. <h2 id="caveats"><a class="header" href="#caveats">Caveats</a></h2>
  7936. <p>There are some caveats:</p>
  7937. <ul>
  7938. <li>If a third party gets both your access token and refresh token, they will be able to
  7939. continue to enjoy access to your session.
  7940. <ul>
  7941. <li>This is still an improvement because you (the user) will notice when <em>your</em>
  7942. session expires and you're not able to use your refresh token.
  7943. That would be a giveaway that someone else has compromised your session.
  7944. You would be able to log in again and terminate that session.
  7945. Previously (with long-lived access tokens), a third party that has your access
  7946. token could go undetected for a very long time.</li>
  7947. </ul>
  7948. </li>
  7949. <li>Clients need to implement support for refresh tokens in order for them to be a
  7950. useful mechanism.
  7951. <ul>
  7952. <li>It is up to homeserver administrators if they want to issue long-lived access
  7953. tokens to clients not implementing refresh tokens.
  7954. <ul>
  7955. <li>For compatibility, it is likely that they should, at least until client support
  7956. is widespread.
  7957. <ul>
  7958. <li>Users with clients that support refresh tokens will still benefit from the
  7959. added security; it's not possible to downgrade a session to using long-lived
  7960. access tokens so this effectively gives users the choice.</li>
  7961. </ul>
  7962. </li>
  7963. <li>In a closed environment where all users use known clients, this may not be
  7964. an issue as the homeserver administrator can know if the clients have refresh
  7965. token support. In that case, the non-refreshable access token lifetime
  7966. may be set to a short duration so that a similar level of security is provided.</li>
  7967. </ul>
  7968. </li>
  7969. </ul>
  7970. </li>
  7971. </ul>
  7972. <h2 id="configuration-guide"><a class="header" href="#configuration-guide">Configuration Guide</a></h2>
  7973. <p>The following configuration options, in the <code>registration</code> section, are related:</p>
  7974. <ul>
  7975. <li><code>session_lifetime</code>: maximum length of a session, even if it's refreshed.
  7976. In other words, the client must log in again after this time period.
  7977. In most cases, this can be unset (infinite) or set to a long time (years or months).</li>
  7978. <li><code>refreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  7979. by clients supporting refresh tokens.
  7980. This should be short; a good value might be 5 minutes (<code>5m</code>).</li>
  7981. <li><code>nonrefreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  7982. by clients which don't support refresh tokens.
  7983. Make this short if you want to effectively force use of refresh tokens.
  7984. Make this long if you don't want to inconvenience users of clients which don't
  7985. support refresh tokens (by forcing them to frequently re-authenticate using
  7986. login credentials).</li>
  7987. <li><code>refresh_token_lifetime</code>: lifetime of refresh tokens.
  7988. In other words, the client must refresh within this time period to maintain its session.
  7989. Unless you want to log inactive sessions out, it is often fine to use a long
  7990. value here or even leave it unset (infinite).
  7991. Beware that making it too short will inconvenience clients that do not connect
  7992. very often, including mobile clients and clients of infrequent users (by making
  7993. it more difficult for them to refresh in time, which may force them to need to
  7994. re-authenticate using login credentials).</li>
  7995. </ul>
  7996. <p><strong>Note:</strong> All four options above only apply when tokens are created (by logging in or refreshing).
  7997. Changes to these settings do not apply retroactively.</p>
  7998. <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>
  7999. <p>If you'd like to force sessions to be logged out upon inactivity, you can enable
  8000. refreshable access token expiry and refresh token expiry.</p>
  8001. <p>This works because a client must refresh at least once within a period of
  8002. <code>refresh_token_lifetime</code> in order to maintain valid credentials to access the
  8003. account.</p>
  8004. <p>(It's suggested that <code>refresh_token_lifetime</code> should be longer than
  8005. <code>refreshable_access_token_lifetime</code> and this section assumes that to be the case
  8006. for simplicity.)</p>
  8007. <p>Note: this will only affect sessions using refresh tokens. You may wish to
  8008. set a short <code>nonrefreshable_access_token_lifetime</code> to prevent this being bypassed
  8009. by clients that do not support refresh tokens.</p>
  8010. <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>
  8011. <p>It may be desirable to permit some short periods of inactivity, for example to
  8012. accommodate brief outages in client connectivity.</p>
  8013. <p>The following model aims to provide guidance for choosing <code>refresh_token_lifetime</code>
  8014. and <code>refreshable_access_token_lifetime</code> to satisfy requirements of the form:</p>
  8015. <ol>
  8016. <li>inactivity longer than <code>L</code> <strong>MUST</strong> cause the session to be logged out; and</li>
  8017. <li>inactivity shorter than <code>S</code> <strong>MUST NOT</strong> cause the session to be logged out.</li>
  8018. </ol>
  8019. <p>This model makes the weakest assumption that all active clients will refresh as
  8020. needed to maintain an active access token, but no sooner.
  8021. <em>In reality, clients may refresh more often than this model assumes, but the
  8022. above requirements will still hold.</em></p>
  8023. <p>To satisfy the above model,</p>
  8024. <ul>
  8025. <li><code>refresh_token_lifetime</code> should be set to <code>L</code>; and</li>
  8026. <li><code>refreshable_access_token_lifetime</code> should be set to <code>L - S</code>.</li>
  8027. </ul>
  8028. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-2"><a class="header" href="#overview-2">Overview</a></h1>
  8029. <p>A captcha can be enabled on your homeserver to help prevent bots from registering
  8030. accounts. Synapse currently uses Google's reCAPTCHA service which requires API keys
  8031. from Google.</p>
  8032. <h2 id="getting-api-keys"><a class="header" href="#getting-api-keys">Getting API keys</a></h2>
  8033. <ol>
  8034. <li>Create a new site at <a href="https://www.google.com/recaptcha/admin/create">https://www.google.com/recaptcha/admin/create</a></li>
  8035. <li>Set the label to anything you want</li>
  8036. <li>Set the type to reCAPTCHA v2 using the &quot;I'm not a robot&quot; Checkbox option.
  8037. This is the only type of captcha that works with Synapse.</li>
  8038. <li>Add the public hostname for your server, as set in <code>public_baseurl</code>
  8039. in <code>homeserver.yaml</code>, to the list of authorized domains. If you have not set
  8040. <code>public_baseurl</code>, use <code>server_name</code>.</li>
  8041. <li>Agree to the terms of service and submit.</li>
  8042. <li>Copy your site key and secret key and add them to your <code>homeserver.yaml</code>
  8043. configuration file
  8044. <pre><code class="language-yaml">recaptcha_public_key: YOUR_SITE_KEY
  8045. recaptcha_private_key: YOUR_SECRET_KEY
  8046. </code></pre>
  8047. </li>
  8048. <li>Enable the CAPTCHA for new registrations
  8049. <pre><code class="language-yaml">enable_registration_captcha: true
  8050. </code></pre>
  8051. </li>
  8052. <li>Go to the settings page for the CAPTCHA you just created</li>
  8053. <li>Uncheck the &quot;Verify the origin of reCAPTCHA solutions&quot; checkbox so that the
  8054. captcha can be displayed in any client. If you do not disable this option then you
  8055. must specify the domains of every client that is allowed to display the CAPTCHA.</li>
  8056. </ol>
  8057. <h2 id="configuring-ip-used-for-auth"><a class="header" href="#configuring-ip-used-for-auth">Configuring IP used for auth</a></h2>
  8058. <p>The reCAPTCHA API requires that the IP address of the user who solved the
  8059. CAPTCHA is sent. If the client is connecting through a proxy or load balancer,
  8060. it may be required to use the <code>X-Forwarded-For</code> (XFF) header instead of the origin
  8061. IP address. This can be configured using the <code>x_forwarded</code> directive in the
  8062. listeners section of the <code>homeserver.yaml</code> configuration file.</p>
  8063. <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>
  8064. <p>The registration of new application services depends on the homeserver used.
  8065. In synapse, you need to create a new configuration file for your AS and add it
  8066. to the list specified under the <code>app_service_config_files</code> config
  8067. option in your synapse config.</p>
  8068. <p>For example:</p>
  8069. <pre><code class="language-yaml">app_service_config_files:
  8070. - /home/matrix/.synapse/&lt;your-AS&gt;.yaml
  8071. </code></pre>
  8072. <p>The format of the AS configuration file is as follows:</p>
  8073. <pre><code class="language-yaml">url: &lt;base url of AS&gt;
  8074. as_token: &lt;token AS will add to requests to HS&gt;
  8075. hs_token: &lt;token HS will add to requests to AS&gt;
  8076. sender_localpart: &lt;localpart of AS user&gt;
  8077. namespaces:
  8078. users: # List of users we're interested in
  8079. - exclusive: &lt;bool&gt;
  8080. regex: &lt;regex&gt;
  8081. group_id: &lt;group&gt;
  8082. - ...
  8083. aliases: [] # List of aliases we're interested in
  8084. rooms: [] # List of room ids we're interested in
  8085. </code></pre>
  8086. <p><code>exclusive</code>: If enabled, only this application service is allowed to register users in its namespace(s).
  8087. <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>
  8088. <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>
  8089. <div style="break-before: page; page-break-before: always;"></div><h1 id="server-notices"><a class="header" href="#server-notices">Server Notices</a></h1>
  8090. <p>'Server Notices' are a new feature introduced in Synapse 0.30. They provide a
  8091. channel whereby server administrators can send messages to users on the server.</p>
  8092. <p>They are used as part of communication of the server polices (see
  8093. <a href="consent_tracking.html">Consent Tracking</a>), however the intention is that
  8094. they may also find a use for features such as &quot;Message of the day&quot;.</p>
  8095. <p>This is a feature specific to Synapse, but it uses standard Matrix
  8096. communication mechanisms, so should work with any Matrix client.</p>
  8097. <h2 id="user-experience"><a class="header" href="#user-experience">User experience</a></h2>
  8098. <p>When the user is first sent a server notice, they will get an invitation to a
  8099. room (typically called 'Server Notices', though this is configurable in
  8100. <code>homeserver.yaml</code>). They will be <strong>unable to reject</strong> this invitation -
  8101. attempts to do so will receive an error.</p>
  8102. <p>Once they accept the invitation, they will see the notice message in the room
  8103. history; it will appear to have come from the 'server notices user' (see
  8104. below).</p>
  8105. <p>The user is prevented from sending any messages in this room by the power
  8106. levels.</p>
  8107. <p>Having joined the room, the user can leave the room if they want. Subsequent
  8108. server notices will then cause a new room to be created.</p>
  8109. <h2 id="synapse-configuration"><a class="header" href="#synapse-configuration">Synapse configuration</a></h2>
  8110. <p>Server notices come from a specific user id on the server. Server
  8111. administrators are free to choose the user id - something like <code>server</code> is
  8112. suggested, meaning the notices will come from
  8113. <code>@server:&lt;your_server_name&gt;</code>. Once the Server Notices user is configured, that
  8114. user id becomes a special, privileged user, so administrators should ensure
  8115. that <strong>it is not already allocated</strong>.</p>
  8116. <p>In order to support server notices, it is necessary to add some configuration
  8117. to the <code>homeserver.yaml</code> file. In particular, you should add a <code>server_notices</code>
  8118. section, which should look like this:</p>
  8119. <pre><code class="language-yaml">server_notices:
  8120. system_mxid_localpart: server
  8121. system_mxid_display_name: &quot;Server Notices&quot;
  8122. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  8123. room_name: &quot;Server Notices&quot;
  8124. </code></pre>
  8125. <p>The only compulsory setting is <code>system_mxid_localpart</code>, which defines the user
  8126. id of the Server Notices user, as above. <code>room_name</code> defines the name of the
  8127. room which will be created.</p>
  8128. <p><code>system_mxid_display_name</code> and <code>system_mxid_avatar_url</code> can be used to set the
  8129. displayname and avatar of the Server Notices user.</p>
  8130. <h2 id="sending-notices"><a class="header" href="#sending-notices">Sending notices</a></h2>
  8131. <p>To send server notices to users you can use the
  8132. <a href="admin_api/server_notices.html">admin_api</a>.</p>
  8133. <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>
  8134. <p>Synapse 0.30 introduces support for tracking whether users have agreed to the
  8135. terms and conditions set by the administrator of a server - and blocking access
  8136. to the server until they have.</p>
  8137. <p>There are several parts to this functionality; each requires some specific
  8138. configuration in <code>homeserver.yaml</code> to be enabled.</p>
  8139. <p>Note that various parts of the configuation and this document refer to the
  8140. &quot;privacy policy&quot;: agreement with a privacy policy is one particular use of this
  8141. feature, but of course adminstrators can specify other terms and conditions
  8142. unrelated to &quot;privacy&quot; per se.</p>
  8143. <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>
  8144. <p>Synapse can be configured to serve the user a simple policy form with an
  8145. &quot;accept&quot; button. Clicking &quot;Accept&quot; records the user's acceptance in the
  8146. database and shows a success page.</p>
  8147. <p>To enable this, first create templates for the policy and success pages.
  8148. These should be stored on the local filesystem.</p>
  8149. <p>These templates use the <a href="http://jinja.pocoo.org">Jinja2</a> templating language,
  8150. and <a href="https://github.com/matrix-org/synapse/tree/develop/docs/privacy_policy_templates/">docs/privacy_policy_templates</a>
  8151. gives examples of the sort of thing that can be done.</p>
  8152. <p>Note that the templates must be stored under a name giving the language of the
  8153. template - currently this must always be <code>en</code> (for &quot;English&quot;);
  8154. internationalisation support is intended for the future.</p>
  8155. <p>The template for the policy itself should be versioned and named according to
  8156. the version: for example <code>1.0.html</code>. The version of the policy which the user
  8157. has agreed to is stored in the database.</p>
  8158. <p>Once the templates are in place, make the following changes to <code>homeserver.yaml</code>:</p>
  8159. <ol>
  8160. <li>
  8161. <p>Add a <code>user_consent</code> section, which should look like:</p>
  8162. <pre><code class="language-yaml">user_consent:
  8163. template_dir: privacy_policy_templates
  8164. version: 1.0
  8165. </code></pre>
  8166. <p><code>template_dir</code> points to the directory containing the policy
  8167. templates. <code>version</code> defines the version of the policy which will be served
  8168. to the user. In the example above, Synapse will serve
  8169. <code>privacy_policy_templates/en/1.0.html</code>.</p>
  8170. </li>
  8171. <li>
  8172. <p>Add a <code>form_secret</code> setting at the top level:</p>
  8173. <pre><code class="language-yaml">form_secret: &quot;&lt;unique secret&gt;&quot;
  8174. </code></pre>
  8175. <p>This should be set to an arbitrary secret string (try <code>pwgen -y 30</code> to
  8176. generate suitable secrets).</p>
  8177. <p>More on what this is used for below.</p>
  8178. </li>
  8179. <li>
  8180. <p>Add <code>consent</code> wherever the <code>client</code> resource is currently enabled in the
  8181. <code>listeners</code> configuration. For example:</p>
  8182. <pre><code class="language-yaml">listeners:
  8183. - port: 8008
  8184. resources:
  8185. - names:
  8186. - client
  8187. - consent
  8188. </code></pre>
  8189. </li>
  8190. </ol>
  8191. <p>Finally, ensure that <code>jinja2</code> is installed. If you are using a virtualenv, this
  8192. should be a matter of <code>pip install Jinja2</code>. On debian, try <code>apt-get install python-jinja2</code>.</p>
  8193. <p>Once this is complete, and the server has been restarted, try visiting
  8194. <code>https://&lt;server&gt;/_matrix/consent</code>. If correctly configured, this should give
  8195. an error &quot;Missing string query parameter 'u'&quot;. It is now possible to manually
  8196. construct URIs where users can give their consent.</p>
  8197. <h3 id="enabling-consent-tracking-at-registration"><a class="header" href="#enabling-consent-tracking-at-registration">Enabling consent tracking at registration</a></h3>
  8198. <ol>
  8199. <li>
  8200. <p>Add the following to your configuration:</p>
  8201. <pre><code class="language-yaml">user_consent:
  8202. require_at_registration: true
  8203. policy_name: &quot;Privacy Policy&quot; # or whatever you'd like to call the policy
  8204. </code></pre>
  8205. </li>
  8206. <li>
  8207. <p>In your consent templates, make use of the <code>public_version</code> variable to
  8208. see if an unauthenticated user is viewing the page. This is typically
  8209. wrapped around the form that would be used to actually agree to the document:</p>
  8210. <pre><code class="language-html">{% if not public_version %}
  8211. &lt;!-- The variables used here are only provided when the 'u' param is given to the homeserver --&gt;
  8212. &lt;form method=&quot;post&quot; action=&quot;consent&quot;&gt;
  8213. &lt;input type=&quot;hidden&quot; name=&quot;v&quot; value=&quot;{{version}}&quot;/&gt;
  8214. &lt;input type=&quot;hidden&quot; name=&quot;u&quot; value=&quot;{{user}}&quot;/&gt;
  8215. &lt;input type=&quot;hidden&quot; name=&quot;h&quot; value=&quot;{{userhmac}}&quot;/&gt;
  8216. &lt;input type=&quot;submit&quot; value=&quot;Sure thing!&quot;/&gt;
  8217. &lt;/form&gt;
  8218. {% endif %}
  8219. </code></pre>
  8220. </li>
  8221. <li>
  8222. <p>Restart Synapse to apply the changes.</p>
  8223. </li>
  8224. </ol>
  8225. <p>Visiting <code>https://&lt;server&gt;/_matrix/consent</code> should now give you a view of the privacy
  8226. document. This is what users will be able to see when registering for accounts.</p>
  8227. <h3 id="constructing-the-consent-uri"><a class="header" href="#constructing-the-consent-uri">Constructing the consent URI</a></h3>
  8228. <p>It may be useful to manually construct the &quot;consent URI&quot; for a given user - for
  8229. instance, in order to send them an email asking them to consent. To do this,
  8230. take the base <code>https://&lt;server&gt;/_matrix/consent</code> URL and add the following
  8231. query parameters:</p>
  8232. <ul>
  8233. <li>
  8234. <p><code>u</code>: the user id of the user. This can either be a full MXID
  8235. (<code>@user:server.com</code>) or just the localpart (<code>user</code>).</p>
  8236. </li>
  8237. <li>
  8238. <p><code>h</code>: hex-encoded HMAC-SHA256 of <code>u</code> using the <code>form_secret</code> as a key. It is
  8239. possible to calculate this on the commandline with something like:</p>
  8240. <pre><code class="language-bash">echo -n '&lt;user&gt;' | openssl sha256 -hmac '&lt;form_secret&gt;'
  8241. </code></pre>
  8242. <p>This should result in a URI which looks something like:
  8243. <code>https://&lt;server&gt;/_matrix/consent?u=&lt;user&gt;&amp;h=68a152465a4d...</code>.</p>
  8244. </li>
  8245. </ul>
  8246. <p>Note that not providing a <code>u</code> parameter will be interpreted as wanting to view
  8247. the document from an unauthenticated perspective, such as prior to registration.
  8248. Therefore, the <code>h</code> parameter is not required in this scenario. To enable this
  8249. behaviour, set <code>require_at_registration</code> to <code>true</code> in your <code>user_consent</code> config.</p>
  8250. <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>
  8251. <p>It is possible to configure Synapse to send a <a href="server_notices.html">server
  8252. notice</a> to anybody who has not yet agreed to the current
  8253. version of the policy. To do so:</p>
  8254. <ul>
  8255. <li>
  8256. <p>ensure that the consent resource is configured, as in the previous section</p>
  8257. </li>
  8258. <li>
  8259. <p>ensure that server notices are configured, as in <a href="server_notices.html">the server notice documentation</a>.</p>
  8260. </li>
  8261. <li>
  8262. <p>Add <code>server_notice_content</code> under <code>user_consent</code> in <code>homeserver.yaml</code>. For
  8263. example:</p>
  8264. <pre><code class="language-yaml">user_consent:
  8265. server_notice_content:
  8266. msgtype: m.text
  8267. body: &gt;-
  8268. Please give your consent to the privacy policy at %(consent_uri)s.
  8269. </code></pre>
  8270. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  8271. consent uri for that user.</p>
  8272. </li>
  8273. <li>
  8274. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  8275. URI that clients use to connect to the server. (It is used to construct
  8276. <code>consent_uri</code> in the server notice.)</p>
  8277. </li>
  8278. </ul>
  8279. <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>
  8280. <p>Synapse can be configured to block any attempts to join rooms or send messages
  8281. until the user has given their agreement to the policy. (Joining the server
  8282. notices room is exempted from this).</p>
  8283. <p>To enable this, add <code>block_events_error</code> under <code>user_consent</code>. For example:</p>
  8284. <pre><code class="language-yaml">user_consent:
  8285. block_events_error: &gt;-
  8286. You can't send any messages until you consent to the privacy policy at
  8287. %(consent_uri)s.
  8288. </code></pre>
  8289. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  8290. consent uri for that user.</p>
  8291. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  8292. URI that clients use to connect to the server. (It is used to construct
  8293. <code>consent_uri</code> in the error.)</p>
  8294. <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>
  8295. <p>The user directory is currently maintained based on the 'visible' users
  8296. on this particular server - i.e. ones which your account shares a room with, or
  8297. who are present in a publicly viewable room present on the server.</p>
  8298. <p>The directory info is stored in various tables, which can (typically after
  8299. DB corruption) get stale or out of sync. If this happens, for now the
  8300. solution to fix it is to use the <a href="usage/administration/admin_api/background_updates.html#run">admin API</a>
  8301. and execute the job <code>regenerate_directory</code>. This should then start a background task to
  8302. flush the current tables and regenerate the directory.</p>
  8303. <h2 id="data-model"><a class="header" href="#data-model">Data model</a></h2>
  8304. <p>There are five relevant tables that collectively form the &quot;user directory&quot;.
  8305. Three of them track a master list of all the users we could search for.
  8306. The last two (collectively called the &quot;search tables&quot;) track who can
  8307. see who.</p>
  8308. <p>From all of these tables we exclude three types of local user:</p>
  8309. <ul>
  8310. <li>support users</li>
  8311. <li>appservice users</li>
  8312. <li>deactivated users</li>
  8313. </ul>
  8314. <ul>
  8315. <li>
  8316. <p><code>user_directory</code>. This contains the user_id, display name and avatar we'll
  8317. return when you search the directory.</p>
  8318. <ul>
  8319. <li>Because there's only one directory entry per user, it's important that we only
  8320. ever put publicly visible names here. Otherwise we might leak a private
  8321. nickname or avatar used in a private room.</li>
  8322. <li>Indexed on rooms. Indexed on users.</li>
  8323. </ul>
  8324. </li>
  8325. <li>
  8326. <p><code>user_directory_search</code>. To be joined to <code>user_directory</code>. It contains an extra
  8327. column that enables full text search based on user ids and display names.
  8328. Different schemas for SQLite and Postgres with different code paths to match.</p>
  8329. <ul>
  8330. <li>Indexed on the full text search data. Indexed on users.</li>
  8331. </ul>
  8332. </li>
  8333. <li>
  8334. <p><code>user_directory_stream_pos</code>. When the initial background update to populate
  8335. the directory is complete, we record a stream position here. This indicates
  8336. that synapse should now listen for room changes and incrementally update
  8337. the directory where necessary.</p>
  8338. </li>
  8339. <li>
  8340. <p><code>users_in_public_rooms</code>. Contains associations between users and the public rooms they're in.
  8341. Used to determine which users are in public rooms and should be publicly visible in the directory.</p>
  8342. </li>
  8343. <li>
  8344. <p><code>users_who_share_private_rooms</code>. Rows are triples <code>(L, M, room id)</code> where <code>L</code>
  8345. is a local user and <code>M</code> is a local or remote user. <code>L</code> and <code>M</code> should be
  8346. different, but this isn't enforced by a constraint.</p>
  8347. </li>
  8348. </ul>
  8349. <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>
  8350. <p>Synapse admins can enable support for message retention policies on
  8351. their homeserver. Message retention policies exist at a room level,
  8352. follow the semantics described in
  8353. <a href="https://github.com/matrix-org/matrix-doc/blob/matthew/msc1763/proposals/1763-configurable-retention-periods.md">MSC1763</a>,
  8354. and allow server and room admins to configure how long messages should
  8355. be kept in a homeserver's database before being purged from it.
  8356. <strong>Please note that, as this feature isn't part of the Matrix
  8357. specification yet, this implementation is to be considered as
  8358. experimental. There are known bugs which may cause database corruption.
  8359. Proceed with caution.</strong> </p>
  8360. <p>A message retention policy is mainly defined by its <code>max_lifetime</code>
  8361. parameter, which defines how long a message can be kept around after
  8362. it was sent to the room. If a room doesn't have a message retention
  8363. policy, and there's no default one for a given server, then no message
  8364. sent in that room is ever purged on that server.</p>
  8365. <p>MSC1763 also specifies semantics for a <code>min_lifetime</code> parameter which
  8366. defines the amount of time after which an event <em>can</em> get purged (after
  8367. it was sent to the room), but Synapse doesn't currently support it
  8368. beyond registering it.</p>
  8369. <p>Both <code>max_lifetime</code> and <code>min_lifetime</code> are optional parameters.</p>
  8370. <p>Note that message retention policies don't apply to state events.</p>
  8371. <p>Once an event reaches its expiry date (defined as the time it was sent
  8372. plus the value for <code>max_lifetime</code> in the room), two things happen:</p>
  8373. <ul>
  8374. <li>Synapse stops serving the event to clients via any endpoint.</li>
  8375. <li>The message gets picked up by the next purge job (see the &quot;Purge jobs&quot;
  8376. section) and is removed from Synapse's database.</li>
  8377. </ul>
  8378. <p>Since purge jobs don't run continuously, this means that an event might
  8379. stay in a server's database for longer than the value for <code>max_lifetime</code>
  8380. in the room would allow, though hidden from clients.</p>
  8381. <p>Similarly, if a server (with support for message retention policies
  8382. enabled) receives from another server an event that should have been
  8383. purged according to its room's policy, then the receiving server will
  8384. process and store that event until it's picked up by the next purge job,
  8385. though it will always hide it from clients.</p>
  8386. <p>Synapse requires at least one message in each room, so it will never
  8387. delete the last message in a room. It will, however, hide it from
  8388. clients.</p>
  8389. <h2 id="server-configuration"><a class="header" href="#server-configuration">Server configuration</a></h2>
  8390. <p>Support for this feature can be enabled and configured by adding a the
  8391. <code>retention</code> in the Synapse configuration file (see
  8392. <a href="usage/configuration/config_documentation.html#retention">configuration manual</a>).</p>
  8393. <p>To enable support for message retention policies, set the setting
  8394. <code>enabled</code> in this section to <code>true</code>.</p>
  8395. <h3 id="default-policy"><a class="header" href="#default-policy">Default policy</a></h3>
  8396. <p>A default message retention policy is a policy defined in Synapse's
  8397. configuration that is used by Synapse for every room that doesn't have a
  8398. message retention policy configured in its state. This allows server
  8399. admins to ensure that messages are never kept indefinitely in a server's
  8400. database. </p>
  8401. <p>A default policy can be defined as such, by adding the <code>retention</code> option in
  8402. the configuration file and adding these sub-options:</p>
  8403. <pre><code class="language-yaml">default_policy:
  8404. min_lifetime: 1d
  8405. max_lifetime: 1y
  8406. </code></pre>
  8407. <p>Here, <code>min_lifetime</code> and <code>max_lifetime</code> have the same meaning and level
  8408. of support as previously described. They can be expressed either as a
  8409. duration (using the units <code>s</code> (seconds), <code>m</code> (minutes), <code>h</code> (hours),
  8410. <code>d</code> (days), <code>w</code> (weeks) and <code>y</code> (years)) or as a number of milliseconds.</p>
  8411. <h3 id="purge-jobs"><a class="header" href="#purge-jobs">Purge jobs</a></h3>
  8412. <p>Purge jobs are the jobs that Synapse runs in the background to purge
  8413. expired events from the database. They are only run if support for
  8414. message retention policies is enabled in the server's configuration. If
  8415. no configuration for purge jobs is configured by the server admin,
  8416. Synapse will use a default configuration, which is described here in the
  8417. <a href="usage/configuration/config_documentation.html#retention">configuration manual</a>.</p>
  8418. <p>Some server admins might want a finer control on when events are removed
  8419. depending on an event's room's policy. This can be done by setting the
  8420. <code>purge_jobs</code> sub-section in the <code>retention</code> section of the configuration
  8421. file. An example of such configuration could be:</p>
  8422. <pre><code class="language-yaml">purge_jobs:
  8423. - longest_max_lifetime: 3d
  8424. interval: 12h
  8425. - shortest_max_lifetime: 3d
  8426. longest_max_lifetime: 1w
  8427. interval: 1d
  8428. - shortest_max_lifetime: 1w
  8429. interval: 2d
  8430. </code></pre>
  8431. <p>In this example, we define three jobs:</p>
  8432. <ul>
  8433. <li>one that runs twice a day (every 12 hours) and purges events in rooms
  8434. which policy's <code>max_lifetime</code> is lower or equal to 3 days.</li>
  8435. <li>one that runs once a day and purges events in rooms which policy's
  8436. <code>max_lifetime</code> is between 3 days and a week.</li>
  8437. <li>one that runs once every 2 days and purges events in rooms which
  8438. policy's <code>max_lifetime</code> is greater than a week.</li>
  8439. </ul>
  8440. <p>Note that this example is tailored to show different configurations and
  8441. features slightly more jobs than it's probably necessary (in practice, a
  8442. server admin would probably consider it better to replace the two last
  8443. jobs with one that runs once a day and handles rooms which
  8444. policy's <code>max_lifetime</code> is greater than 3 days).</p>
  8445. <p>Keep in mind, when configuring these jobs, that a purge job can become
  8446. quite heavy on the server if it targets many rooms, therefore prefer
  8447. having jobs with a low interval that target a limited set of rooms. Also
  8448. make sure to include a job with no minimum and one with no maximum to
  8449. make sure your configuration handles every policy.</p>
  8450. <p>As previously mentioned in this documentation, while a purge job that
  8451. runs e.g. every day means that an expired event might stay in the
  8452. database for up to a day after its expiry, Synapse hides expired events
  8453. from clients as soon as they expire, so the event is not visible to
  8454. local users between its expiry date and the moment it gets purged from
  8455. the server's database.</p>
  8456. <h3 id="lifetime-limits"><a class="header" href="#lifetime-limits">Lifetime limits</a></h3>
  8457. <p>Server admins can set limits on the values of <code>max_lifetime</code> to use when
  8458. purging old events in a room. These limits can be defined under the
  8459. <code>retention</code> option in the configuration file:</p>
  8460. <pre><code class="language-yaml">allowed_lifetime_min: 1d
  8461. allowed_lifetime_max: 1y
  8462. </code></pre>
  8463. <p>The limits are considered when running purge jobs. If necessary, the
  8464. effective value of <code>max_lifetime</code> will be brought between
  8465. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> (inclusive).
  8466. This means that, if the value of <code>max_lifetime</code> defined in the room's state
  8467. is lower than <code>allowed_lifetime_min</code>, the value of <code>allowed_lifetime_min</code>
  8468. will be used instead. Likewise, if the value of <code>max_lifetime</code> is higher
  8469. than <code>allowed_lifetime_max</code>, the value of <code>allowed_lifetime_max</code> will be
  8470. used instead.</p>
  8471. <p>In the example above, we ensure Synapse never deletes events that are less
  8472. than one day old, and that it always deletes events that are over a year
  8473. old.</p>
  8474. <p>If a default policy is set, and its <code>max_lifetime</code> value is lower than
  8475. <code>allowed_lifetime_min</code> or higher than <code>allowed_lifetime_max</code>, the same
  8476. process applies.</p>
  8477. <p>Both parameters are optional; if one is omitted Synapse won't use it to
  8478. adjust the effective value of <code>max_lifetime</code>.</p>
  8479. <p>Like other settings in this section, these parameters can be expressed
  8480. either as a duration or as a number of milliseconds.</p>
  8481. <h2 id="room-configuration"><a class="header" href="#room-configuration">Room configuration</a></h2>
  8482. <p>To configure a room's message retention policy, a room's admin or
  8483. moderator needs to send a state event in that room with the type
  8484. <code>m.room.retention</code> and the following content:</p>
  8485. <pre><code class="language-json">{
  8486. &quot;max_lifetime&quot;: ...
  8487. }
  8488. </code></pre>
  8489. <p>In this event's content, the <code>max_lifetime</code> parameter has the same
  8490. meaning as previously described, and needs to be expressed in
  8491. milliseconds. The event's content can also include a <code>min_lifetime</code>
  8492. parameter, which has the same meaning and limited support as previously
  8493. described.</p>
  8494. <p>Note that over every server in the room, only the ones with support for
  8495. message retention policies will actually remove expired events. This
  8496. support is currently not enabled by default in Synapse.</p>
  8497. <h2 id="note-on-reclaiming-disk-space"><a class="header" href="#note-on-reclaiming-disk-space">Note on reclaiming disk space</a></h2>
  8498. <p>While purge jobs actually delete data from the database, the disk space
  8499. used by the database might not decrease immediately on the database's
  8500. host. However, even though the database engine won't free up the disk
  8501. space, it will start writing new data into where the purged data was.</p>
  8502. <p>If you want to reclaim the freed disk space anyway and return it to the
  8503. operating system, the server admin needs to run <code>VACUUM FULL;</code> (or
  8504. <code>VACUUM;</code> for SQLite databases) on Synapse's database (see the related
  8505. <a href="https://www.postgresql.org/docs/current/sql-vacuum.html">PostgreSQL documentation</a>).</p>
  8506. <div style="break-before: page; page-break-before: always;"></div><h1 id="modules-2"><a class="header" href="#modules-2">Modules</a></h1>
  8507. <p>Synapse supports extending its functionality by configuring external modules.</p>
  8508. <p><strong>Note</strong>: When using third-party modules, you effectively allow someone else to run
  8509. custom code on your Synapse homeserver. Server admins are encouraged to verify the
  8510. provenance of the modules they use on their homeserver and make sure the modules aren't
  8511. running malicious code on their instance.</p>
  8512. <h2 id="using-modules"><a class="header" href="#using-modules">Using modules</a></h2>
  8513. <p>To use a module on Synapse, add it to the <code>modules</code> section of the configuration file:</p>
  8514. <pre><code class="language-yaml">modules:
  8515. - module: my_super_module.MySuperClass
  8516. config:
  8517. do_thing: true
  8518. - module: my_other_super_module.SomeClass
  8519. config: {}
  8520. </code></pre>
  8521. <p>Each module is defined by a path to a Python class as well as a configuration. This
  8522. information for a given module should be available in the module's own documentation.</p>
  8523. <h2 id="using-multiple-modules"><a class="header" href="#using-multiple-modules">Using multiple modules</a></h2>
  8524. <p>The order in which modules are listed in this section is important. When processing an
  8525. action that can be handled by several modules, Synapse will always prioritise the module
  8526. that appears first (i.e. is the highest in the list). This means:</p>
  8527. <ul>
  8528. <li>If several modules register the same callback, the callback registered by the module
  8529. that appears first is used.</li>
  8530. <li>If several modules try to register a handler for the same HTTP path, only the handler
  8531. registered by the module that appears first is used. Handlers registered by the other
  8532. module(s) are ignored and Synapse will log a warning message about them.</li>
  8533. </ul>
  8534. <p>Note that Synapse doesn't allow multiple modules implementing authentication checkers via
  8535. the password auth provider feature for the same login type with different fields. If this
  8536. happens, Synapse will refuse to start.</p>
  8537. <h2 id="current-status"><a class="header" href="#current-status">Current status</a></h2>
  8538. <p>We are currently in the process of migrating module interfaces to this system. While some
  8539. interfaces might be compatible with it, others still require configuring modules in
  8540. another part of Synapse's configuration file.</p>
  8541. <p>Currently, only the following pre-existing interfaces are compatible with this new system:</p>
  8542. <ul>
  8543. <li>spam checker</li>
  8544. <li>third-party rules</li>
  8545. <li>presence router</li>
  8546. <li>password auth providers</li>
  8547. </ul>
  8548. <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>
  8549. <p>A module is a Python class that uses Synapse's module API to interact with the
  8550. homeserver. It can register callbacks that Synapse will call on specific operations, as
  8551. well as web resources to attach to Synapse's web server.</p>
  8552. <p>When instantiated, a module is given its parsed configuration as well as an instance of
  8553. the <code>synapse.module_api.ModuleApi</code> class. The configuration is a dictionary, and is
  8554. either the output of the module's <code>parse_config</code> static method (see below), or the
  8555. configuration associated with the module in Synapse's configuration file.</p>
  8556. <p>See the documentation for the <code>ModuleApi</code> class
  8557. <a href="https://github.com/matrix-org/synapse/blob/master/synapse/module_api/__init__.py">here</a>.</p>
  8558. <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>
  8559. <p>If Synapse is running with other modules configured, the order each module appears in
  8560. within the <code>modules</code> section of the Synapse configuration file might restrict what it can
  8561. or cannot register. See <a href="modules/index.html#using-multiple-modules">this section</a> for more
  8562. information.</p>
  8563. <p>On top of the rules listed in the link above, if a callback returns a value that should
  8564. cause the current operation to fail (e.g. if a callback checking an event returns with a
  8565. value that should cause the event to be denied), Synapse will fail the operation and
  8566. ignore any subsequent callbacks that should have been run after this one.</p>
  8567. <p>The documentation for each callback mentions how Synapse behaves when
  8568. multiple modules implement it.</p>
  8569. <h2 id="handling-the-modules-configuration"><a class="header" href="#handling-the-modules-configuration">Handling the module's configuration</a></h2>
  8570. <p>A module can implement the following static method:</p>
  8571. <pre><code class="language-python">@staticmethod
  8572. def parse_config(config: dict) -&gt; Any
  8573. </code></pre>
  8574. <p>This method is given a dictionary resulting from parsing the YAML configuration for the
  8575. module. It may modify it (for example by parsing durations expressed as strings (e.g.
  8576. &quot;5d&quot;) into milliseconds, etc.), and return the modified dictionary. It may also verify
  8577. that the configuration is correct, and raise an instance of
  8578. <code>synapse.module_api.errors.ConfigError</code> if not.</p>
  8579. <h2 id="registering-a-web-resource"><a class="header" href="#registering-a-web-resource">Registering a web resource</a></h2>
  8580. <p>Modules can register web resources onto Synapse's web server using the following module
  8581. API method:</p>
  8582. <pre><code class="language-python">def ModuleApi.register_web_resource(path: str, resource: IResource) -&gt; None
  8583. </code></pre>
  8584. <p>The path is the full absolute path to register the resource at. For example, if you
  8585. register a resource for the path <code>/_synapse/client/my_super_module/say_hello</code>, Synapse
  8586. will serve it at <code>http(s)://[HS_URL]/_synapse/client/my_super_module/say_hello</code>. Note
  8587. that Synapse does not allow registering resources for several sub-paths in the <code>/_matrix</code>
  8588. namespace (such as anything under <code>/_matrix/client</code> for example). It is strongly
  8589. recommended that modules register their web resources under the <code>/_synapse/client</code>
  8590. namespace.</p>
  8591. <p>The provided resource is a Python class that implements Twisted's <a href="https://twistedmatrix.com/documents/current/api/twisted.web.resource.IResource.html">IResource</a>
  8592. interface (such as <a href="https://twistedmatrix.com/documents/current/api/twisted.web.resource.Resource.html">Resource</a>).</p>
  8593. <p>Only one resource can be registered for a given path. If several modules attempt to
  8594. register a resource for the same path, the module that appears first in Synapse's
  8595. configuration file takes priority.</p>
  8596. <p>Modules <strong>must</strong> register their web resources in their <code>__init__</code> method.</p>
  8597. <h2 id="registering-a-callback"><a class="header" href="#registering-a-callback">Registering a callback</a></h2>
  8598. <p>Modules can use Synapse's module API to register callbacks. Callbacks are functions that
  8599. Synapse will call when performing specific actions. Callbacks must be asynchronous (unless
  8600. specified otherwise), and are split in categories. A single module may implement callbacks
  8601. from multiple categories, and is under no obligation to implement all callbacks from the
  8602. categories it registers callbacks for.</p>
  8603. <p>Modules can register callbacks using one of the module API's <code>register_[...]_callbacks</code>
  8604. methods. The callback functions are passed to these methods as keyword arguments, with
  8605. the callback name as the argument name and the function as its value. A
  8606. <code>register_[...]_callbacks</code> method exists for each category.</p>
  8607. <p>Callbacks for each category can be found on their respective page of the
  8608. <a href="https://matrix-org.github.io/synapse">Synapse documentation website</a>.</p>
  8609. <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>
  8610. <p>Spam checker callbacks allow module developers to implement spam mitigation actions for
  8611. Synapse instances. Spam checker callbacks can be registered using the module API's
  8612. <code>register_spam_checker_callbacks</code> method.</p>
  8613. <h2 id="callbacks"><a class="header" href="#callbacks">Callbacks</a></h2>
  8614. <p>The available spam checker callbacks are:</p>
  8615. <h3 id="check_event_for_spam"><a class="header" href="#check_event_for_spam"><code>check_event_for_spam</code></a></h3>
  8616. <p><em>First introduced in Synapse v1.37.0</em></p>
  8617. <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>
  8618. <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]
  8619. </code></pre>
  8620. <p>Called when receiving an event from a client or via federation. The callback must return one of:</p>
  8621. <ul>
  8622. <li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8623. decide to reject it.</li>
  8624. <li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8625. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
  8626. <li>(deprecated) a non-<code>Codes</code> <code>str</code> to reject the operation and specify an error message. Note that clients
  8627. typically will not localize the error message to the user's preferred locale.</li>
  8628. <li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
  8629. <li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
  8630. </ul>
  8631. <p>If multiple modules implement this callback, they will be considered in order. If a
  8632. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8633. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8634. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8635. this callback.</p>
  8636. <h3 id="user_may_join_room"><a class="header" href="#user_may_join_room"><code>user_may_join_room</code></a></h3>
  8637. <p><em>First introduced in Synapse v1.37.0</em></p>
  8638. <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>
  8639. <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]
  8640. </code></pre>
  8641. <p>Called when a user is trying to join a room. The user is represented by their Matrix user ID (e.g.
  8642. <code>@alice:example.com</code>) and the room is represented by its Matrix ID (e.g.
  8643. <code>!room:example.com</code>). The module is also given a boolean to indicate whether the user
  8644. currently has a pending invite in the room.</p>
  8645. <p>This callback isn't called if the join is performed by a server administrator, or in the
  8646. context of a room creation.</p>
  8647. <p>The callback must return one of:</p>
  8648. <ul>
  8649. <li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8650. decide to reject it.</li>
  8651. <li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8652. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
  8653. <li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
  8654. <li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
  8655. </ul>
  8656. <p>If multiple modules implement this callback, they will be considered in order. If a
  8657. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8658. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8659. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8660. this callback.</p>
  8661. <h3 id="user_may_invite"><a class="header" href="#user_may_invite"><code>user_may_invite</code></a></h3>
  8662. <p><em>First introduced in Synapse v1.37.0</em></p>
  8663. <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>
  8664. <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]
  8665. </code></pre>
  8666. <p>Called when processing an invitation. Both inviter and invitee are
  8667. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  8668. <p>The callback must return one of:</p>
  8669. <ul>
  8670. <li>
  8671. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8672. decide to reject it.</p>
  8673. </li>
  8674. <li>
  8675. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8676. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8677. </li>
  8678. <li>
  8679. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8680. </li>
  8681. <li>
  8682. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8683. </li>
  8684. </ul>
  8685. <p>If multiple modules implement this callback, they will be considered in order. If a
  8686. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8687. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8688. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8689. this callback.</p>
  8690. <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>
  8691. <p><em>First introduced in Synapse v1.45.0</em></p>
  8692. <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>
  8693. <pre><code class="language-python">async def user_may_send_3pid_invite(
  8694. inviter: str,
  8695. medium: str,
  8696. address: str,
  8697. room_id: str,
  8698. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
  8699. </code></pre>
  8700. <p>Called when processing an invitation using a third-party identifier (also called a 3PID,
  8701. e.g. an email address or a phone number). </p>
  8702. <p>The inviter is represented by their Matrix user ID (e.g. <code>@alice:example.com</code>), and the
  8703. invitee is represented by its medium (e.g. &quot;email&quot;) and its address
  8704. (e.g. <code>alice@example.com</code>). See <a href="https://matrix.org/docs/spec/appendices#pid-types">the Matrix specification</a>
  8705. for more information regarding third-party identifiers.</p>
  8706. <p>For example, a call to this callback to send an invitation to the email address
  8707. <code>alice@example.com</code> would look like this:</p>
  8708. <pre><code class="language-python">await user_may_send_3pid_invite(
  8709. &quot;@bob:example.com&quot;, # The inviter's user ID
  8710. &quot;email&quot;, # The medium of the 3PID to invite
  8711. &quot;alice@example.com&quot;, # The address of the 3PID to invite
  8712. &quot;!some_room:example.com&quot;, # The ID of the room to send the invite into
  8713. )
  8714. </code></pre>
  8715. <p><strong>Note</strong>: If the third-party identifier is already associated with a matrix user ID,
  8716. <a href="modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a> will be used instead.</p>
  8717. <p>The callback must return one of:</p>
  8718. <ul>
  8719. <li>
  8720. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8721. decide to reject it.</p>
  8722. </li>
  8723. <li>
  8724. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8725. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8726. </li>
  8727. <li>
  8728. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8729. </li>
  8730. <li>
  8731. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8732. </li>
  8733. </ul>
  8734. <p>If multiple modules implement this callback, they will be considered in order. If a
  8735. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8736. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8737. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8738. this callback.</p>
  8739. <h3 id="user_may_create_room"><a class="header" href="#user_may_create_room"><code>user_may_create_room</code></a></h3>
  8740. <p><em>First introduced in Synapse v1.37.0</em></p>
  8741. <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>
  8742. <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]
  8743. </code></pre>
  8744. <p>Called when processing a room creation request.</p>
  8745. <p>The callback must return one of:</p>
  8746. <ul>
  8747. <li>
  8748. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8749. decide to reject it.</p>
  8750. </li>
  8751. <li>
  8752. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8753. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8754. </li>
  8755. <li>
  8756. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8757. </li>
  8758. <li>
  8759. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8760. </li>
  8761. </ul>
  8762. <p>If multiple modules implement this callback, they will be considered in order. If a
  8763. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8764. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8765. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8766. this callback.</p>
  8767. <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>
  8768. <p><em>First introduced in Synapse v1.37.0</em></p>
  8769. <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>
  8770. <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]
  8771. </code></pre>
  8772. <p>Called when trying to associate an alias with an existing room.</p>
  8773. <p>The callback must return one of:</p>
  8774. <ul>
  8775. <li>
  8776. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8777. decide to reject it.</p>
  8778. </li>
  8779. <li>
  8780. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8781. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8782. </li>
  8783. <li>
  8784. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8785. </li>
  8786. <li>
  8787. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8788. </li>
  8789. </ul>
  8790. <p>If multiple modules implement this callback, they will be considered in order. If a
  8791. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8792. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8793. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8794. this callback.</p>
  8795. <h3 id="user_may_publish_room"><a class="header" href="#user_may_publish_room"><code>user_may_publish_room</code></a></h3>
  8796. <p><em>First introduced in Synapse v1.37.0</em></p>
  8797. <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>
  8798. <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]
  8799. </code></pre>
  8800. <p>Called when trying to publish a room to the homeserver's public rooms directory.</p>
  8801. <p>The callback must return one of:</p>
  8802. <ul>
  8803. <li>
  8804. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8805. decide to reject it.</p>
  8806. </li>
  8807. <li>
  8808. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8809. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8810. </li>
  8811. <li>
  8812. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8813. </li>
  8814. <li>
  8815. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8816. </li>
  8817. </ul>
  8818. <p>If multiple modules implement this callback, they will be considered in order. If a
  8819. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8820. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8821. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8822. this callback.</p>
  8823. <h3 id="check_username_for_spam"><a class="header" href="#check_username_for_spam"><code>check_username_for_spam</code></a></h3>
  8824. <p><em>First introduced in Synapse v1.37.0</em></p>
  8825. <pre><code class="language-python">async def check_username_for_spam(user_profile: synapse.module_api.UserProfile) -&gt; bool
  8826. </code></pre>
  8827. <p>Called when computing search results in the user directory. The module must return a
  8828. <code>bool</code> indicating whether the given user should be excluded from user directory
  8829. searches. Return <code>True</code> to indicate that the user is spammy and exclude them from
  8830. search results; otherwise return <code>False</code>.</p>
  8831. <p>The profile is represented as a dictionary with the following keys:</p>
  8832. <ul>
  8833. <li><code>user_id: str</code>. The Matrix ID for this user.</li>
  8834. <li><code>display_name: Optional[str]</code>. The user's display name, or <code>None</code> if this user
  8835. has not set a display name.</li>
  8836. <li><code>avatar_url: Optional[str]</code>. The <code>mxc://</code> URL to the user's avatar, or <code>None</code>
  8837. if this user has not set an avatar.</li>
  8838. </ul>
  8839. <p>The module is given a copy of the original dictionary, so modifying it from within the
  8840. module cannot modify a user's profile when included in user directory search results.</p>
  8841. <p>If multiple modules implement this callback, they will be considered in order. If a
  8842. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  8843. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  8844. any of the subsequent implementations of this callback.</p>
  8845. <h3 id="check_registration_for_spam"><a class="header" href="#check_registration_for_spam"><code>check_registration_for_spam</code></a></h3>
  8846. <p><em>First introduced in Synapse v1.37.0</em></p>
  8847. <pre><code class="language-python">async def check_registration_for_spam(
  8848. email_threepid: Optional[dict],
  8849. username: Optional[str],
  8850. request_info: Collection[Tuple[str, str]],
  8851. auth_provider_id: Optional[str] = None,
  8852. ) -&gt; &quot;synapse.spam_checker_api.RegistrationBehaviour&quot;
  8853. </code></pre>
  8854. <p>Called when registering a new user. The module must return a <code>RegistrationBehaviour</code>
  8855. indicating whether the registration can go through or must be denied, or whether the user
  8856. may be allowed to register but will be shadow banned.</p>
  8857. <p>The arguments passed to this callback are:</p>
  8858. <ul>
  8859. <li><code>email_threepid</code>: The email address used for registering, if any.</li>
  8860. <li><code>username</code>: The username the user would like to register. Can be <code>None</code>, meaning that
  8861. Synapse will generate one later.</li>
  8862. <li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
  8863. second item is an IP address. These user agents and IP addresses are the ones that were
  8864. used during the registration process.</li>
  8865. <li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
  8866. </ul>
  8867. <p>If multiple modules implement this callback, they will be considered in order. If a
  8868. callback returns <code>RegistrationBehaviour.ALLOW</code>, Synapse falls through to the next one.
  8869. The value of the first callback that does not return <code>RegistrationBehaviour.ALLOW</code> will
  8870. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8871. this callback.</p>
  8872. <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>
  8873. <p><em>First introduced in Synapse v1.37.0</em></p>
  8874. <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>
  8875. <pre><code class="language-python">async def check_media_file_for_spam(
  8876. file_wrapper: &quot;synapse.rest.media.v1.media_storage.ReadableFileWrapper&quot;,
  8877. file_info: &quot;synapse.rest.media.v1._base.FileInfo&quot;,
  8878. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
  8879. </code></pre>
  8880. <p>Called when storing a local or remote file.</p>
  8881. <p>The callback must return one of:</p>
  8882. <ul>
  8883. <li>
  8884. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8885. decide to reject it.</p>
  8886. </li>
  8887. <li>
  8888. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8889. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8890. </li>
  8891. <li>
  8892. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8893. </li>
  8894. <li>
  8895. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8896. </li>
  8897. </ul>
  8898. <p>If multiple modules implement this callback, they will be considered in order. If a
  8899. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8900. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8901. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8902. this callback.</p>
  8903. <h3 id="should_drop_federated_event"><a class="header" href="#should_drop_federated_event"><code>should_drop_federated_event</code></a></h3>
  8904. <p><em>First introduced in Synapse v1.60.0</em></p>
  8905. <pre><code class="language-python">async def should_drop_federated_event(event: &quot;synapse.events.EventBase&quot;) -&gt; bool
  8906. </code></pre>
  8907. <p>Called when checking whether a remote server can federate an event with us. <strong>Returning
  8908. <code>True</code> from this function will silently drop a federated event and split-brain our view
  8909. of a room's DAG, and thus you shouldn't use this callback unless you know what you are
  8910. doing.</strong></p>
  8911. <p>If multiple modules implement this callback, they will be considered in order. If a
  8912. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  8913. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  8914. any of the subsequent implementations of this callback.</p>
  8915. <h2 id="example"><a class="header" href="#example">Example</a></h2>
  8916. <p>The example below is a module that implements the spam checker callback
  8917. <code>check_event_for_spam</code> to deny any message sent by users whose Matrix user IDs are
  8918. mentioned in a configured list, and registers a web resource to the path
  8919. <code>/_synapse/client/list_spam_checker/is_evil</code> that returns a JSON object indicating
  8920. whether the provided user appears in that list.</p>
  8921. <pre><code class="language-python">import json
  8922. from typing import Union
  8923. from twisted.web.resource import Resource
  8924. from twisted.web.server import Request
  8925. from synapse.module_api import ModuleApi
  8926. class IsUserEvilResource(Resource):
  8927. def __init__(self, config):
  8928. super(IsUserEvilResource, self).__init__()
  8929. self.evil_users = config.get(&quot;evil_users&quot;) or []
  8930. def render_GET(self, request: Request):
  8931. user = request.args.get(b&quot;user&quot;)[0].decode()
  8932. request.setHeader(b&quot;Content-Type&quot;, b&quot;application/json&quot;)
  8933. return json.dumps({&quot;evil&quot;: user in self.evil_users}).encode()
  8934. class ListSpamChecker:
  8935. def __init__(self, config: dict, api: ModuleApi):
  8936. self.api = api
  8937. self.evil_users = config.get(&quot;evil_users&quot;) or []
  8938. self.api.register_spam_checker_callbacks(
  8939. check_event_for_spam=self.check_event_for_spam,
  8940. )
  8941. self.api.register_web_resource(
  8942. path=&quot;/_synapse/client/list_spam_checker/is_evil&quot;,
  8943. resource=IsUserEvilResource(config),
  8944. )
  8945. async def check_event_for_spam(self, event: &quot;synapse.events.EventBase&quot;) -&gt; Union[Literal[&quot;NOT_SPAM&quot;], Codes]:
  8946. if event.sender in self.evil_users:
  8947. return Codes.FORBIDDEN
  8948. else:
  8949. return synapse.module_api.NOT_SPAM
  8950. </code></pre>
  8951. <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>
  8952. <p>Third party rules callbacks allow module developers to add extra checks to verify the
  8953. validity of incoming events. Third party event rules callbacks can be registered using
  8954. the module API's <code>register_third_party_rules_callbacks</code> method.</p>
  8955. <h2 id="callbacks-1"><a class="header" href="#callbacks-1">Callbacks</a></h2>
  8956. <p>The available third party rules callbacks are:</p>
  8957. <h3 id="check_event_allowed"><a class="header" href="#check_event_allowed"><code>check_event_allowed</code></a></h3>
  8958. <p><em>First introduced in Synapse v1.39.0</em></p>
  8959. <pre><code class="language-python">async def check_event_allowed(
  8960. event: &quot;synapse.events.EventBase&quot;,
  8961. state_events: &quot;synapse.types.StateMap&quot;,
  8962. ) -&gt; Tuple[bool, Optional[dict]]
  8963. </code></pre>
  8964. <p><strong><span style="color:red">
  8965. This callback is very experimental and can and will break without notice. Module developers
  8966. are encouraged to implement <code>check_event_for_spam</code> from the spam checker category instead.
  8967. </span></strong></p>
  8968. <p>Called when processing any incoming event, with the event and a <code>StateMap</code>
  8969. representing the current state of the room the event is being sent into. A <code>StateMap</code> is
  8970. a dictionary that maps tuples containing an event type and a state key to the
  8971. corresponding state event. For example retrieving the room's <code>m.room.create</code> event from
  8972. the <code>state_events</code> argument would look like this: <code>state_events.get((&quot;m.room.create&quot;, &quot;&quot;))</code>.
  8973. The module must return a boolean indicating whether the event can be allowed.</p>
  8974. <p>Note that this callback function processes incoming events coming via federation
  8975. traffic (on top of client traffic). This means denying an event might cause the local
  8976. copy of the room's history to diverge from that of remote servers. This may cause
  8977. federation issues in the room. It is strongly recommended to only deny events using this
  8978. callback function if the sender is a local user, or in a private federation in which all
  8979. servers are using the same module, with the same configuration.</p>
  8980. <p>If the boolean returned by the module is <code>True</code>, it may also tell Synapse to replace the
  8981. event with new data by returning the new event's data as a dictionary. In order to do
  8982. that, it is recommended the module calls <code>event.get_dict()</code> to get the current event as a
  8983. dictionary, and modify the returned dictionary accordingly.</p>
  8984. <p>If <code>check_event_allowed</code> raises an exception, the module is assumed to have failed.
  8985. The event will not be accepted but is not treated as explicitly rejected, either.
  8986. An HTTP request causing the module check will likely result in a 500 Internal
  8987. Server Error.</p>
  8988. <p>When the boolean returned by the module is <code>False</code>, the event is rejected.
  8989. (Module developers should not use exceptions for rejection.)</p>
  8990. <p>Note that replacing the event only works for events sent by local users, not for events
  8991. received over federation.</p>
  8992. <p>If multiple modules implement this callback, they will be considered in order. If a
  8993. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  8994. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  8995. any of the subsequent implementations of this callback.</p>
  8996. <h3 id="on_create_room"><a class="header" href="#on_create_room"><code>on_create_room</code></a></h3>
  8997. <p><em>First introduced in Synapse v1.39.0</em></p>
  8998. <pre><code class="language-python">async def on_create_room(
  8999. requester: &quot;synapse.types.Requester&quot;,
  9000. request_content: dict,
  9001. is_requester_admin: bool,
  9002. ) -&gt; None
  9003. </code></pre>
  9004. <p>Called when processing a room creation request, with the <code>Requester</code> object for the user
  9005. performing the request, a dictionary representing the room creation request's JSON body
  9006. (see <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom">the spec</a>
  9007. for a list of possible parameters), and a boolean indicating whether the user performing
  9008. the request is a server admin.</p>
  9009. <p>Modules can modify the <code>request_content</code> (by e.g. adding events to its <code>initial_state</code>),
  9010. or deny the room's creation by raising a <code>module_api.errors.SynapseError</code>.</p>
  9011. <p>If multiple modules implement this callback, they will be considered in order. If a
  9012. callback returns without raising an exception, Synapse falls through to the next one. The
  9013. room creation will be forbidden as soon as one of the callbacks raises an exception. If
  9014. this happens, Synapse will not call any of the subsequent implementations of this
  9015. callback.</p>
  9016. <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>
  9017. <p><em>First introduced in Synapse v1.39.0</em></p>
  9018. <pre><code class="language-python">async def check_threepid_can_be_invited(
  9019. medium: str,
  9020. address: str,
  9021. state_events: &quot;synapse.types.StateMap&quot;,
  9022. ) -&gt; bool:
  9023. </code></pre>
  9024. <p>Called when processing an invite via a third-party identifier (i.e. email or phone number).
  9025. The module must return a boolean indicating whether the invite can go through.</p>
  9026. <p>If multiple modules implement this callback, they will be considered in order. If a
  9027. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  9028. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  9029. any of the subsequent implementations of this callback.</p>
  9030. <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>
  9031. <p><em>First introduced in Synapse v1.39.0</em></p>
  9032. <pre><code class="language-python">async def check_visibility_can_be_modified(
  9033. room_id: str,
  9034. state_events: &quot;synapse.types.StateMap&quot;,
  9035. new_visibility: str,
  9036. ) -&gt; bool:
  9037. </code></pre>
  9038. <p>Called when changing the visibility of a room in the local public room directory. The
  9039. visibility is a string that's either &quot;public&quot; or &quot;private&quot;. The module must return a
  9040. boolean indicating whether the change can go through.</p>
  9041. <p>If multiple modules implement this callback, they will be considered in order. If a
  9042. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  9043. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  9044. any of the subsequent implementations of this callback.</p>
  9045. <h3 id="on_new_event"><a class="header" href="#on_new_event"><code>on_new_event</code></a></h3>
  9046. <p><em>First introduced in Synapse v1.47.0</em></p>
  9047. <pre><code class="language-python">async def on_new_event(
  9048. event: &quot;synapse.events.EventBase&quot;,
  9049. state_events: &quot;synapse.types.StateMap&quot;,
  9050. ) -&gt; None:
  9051. </code></pre>
  9052. <p>Called after sending an event into a room. The module is passed the event, as well
  9053. as the state of the room <em>after</em> the event. This means that if the event is a state event,
  9054. it will be included in this state.</p>
  9055. <p>Note that this callback is called when the event has already been processed and stored
  9056. into the room, which means this callback cannot be used to deny persisting the event. To
  9057. 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>
  9058. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9059. <h3 id="check_can_shutdown_room"><a class="header" href="#check_can_shutdown_room"><code>check_can_shutdown_room</code></a></h3>
  9060. <p><em>First introduced in Synapse v1.55.0</em></p>
  9061. <pre><code class="language-python">async def check_can_shutdown_room(
  9062. user_id: str, room_id: str,
  9063. ) -&gt; bool:
  9064. </code></pre>
  9065. <p>Called when an admin user requests the shutdown of a room. The module must return a
  9066. boolean indicating whether the shutdown can go through. If the callback returns <code>False</code>,
  9067. the shutdown will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
  9068. <p>If multiple modules implement this callback, they will be considered in order. If a
  9069. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  9070. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  9071. any of the subsequent implementations of this callback.</p>
  9072. <h3 id="check_can_deactivate_user"><a class="header" href="#check_can_deactivate_user"><code>check_can_deactivate_user</code></a></h3>
  9073. <p><em>First introduced in Synapse v1.55.0</em></p>
  9074. <pre><code class="language-python">async def check_can_deactivate_user(
  9075. user_id: str, by_admin: bool,
  9076. ) -&gt; bool:
  9077. </code></pre>
  9078. <p>Called when the deactivation of a user is requested. User deactivation can be
  9079. performed by an admin or the user themselves, so developers are encouraged to check the
  9080. requester when implementing this callback. The module must return a
  9081. boolean indicating whether the deactivation can go through. If the callback returns <code>False</code>,
  9082. the deactivation will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
  9083. <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>
  9084. <p>If multiple modules implement this callback, they will be considered in order. If a
  9085. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  9086. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  9087. any of the subsequent implementations of this callback.</p>
  9088. <h3 id="on_profile_update"><a class="header" href="#on_profile_update"><code>on_profile_update</code></a></h3>
  9089. <p><em>First introduced in Synapse v1.54.0</em></p>
  9090. <pre><code class="language-python">async def on_profile_update(
  9091. user_id: str,
  9092. new_profile: &quot;synapse.module_api.ProfileInfo&quot;,
  9093. by_admin: bool,
  9094. deactivation: bool,
  9095. ) -&gt; None:
  9096. </code></pre>
  9097. <p>Called after updating a local user's profile. The update can be triggered either by the
  9098. user themselves or a server admin. The update can also be triggered by a user being
  9099. deactivated (in which case their display name is set to an empty string (<code>&quot;&quot;</code>) and the
  9100. avatar URL is set to <code>None</code>). The module is passed the Matrix ID of the user whose profile
  9101. has been updated, their new profile, as well as a <code>by_admin</code> boolean that is <code>True</code> if the
  9102. update was triggered by a server admin (and <code>False</code> otherwise), and a <code>deactivated</code>
  9103. boolean that is <code>True</code> if the update is a result of the user being deactivated.</p>
  9104. <p>Note that the <code>by_admin</code> boolean is also <code>True</code> if the profile change happens as a result
  9105. of the user logging in through Single Sign-On, or if a server admin updates their own
  9106. profile.</p>
  9107. <p>Per-room profile changes do not trigger this callback to be called. Synapse administrators
  9108. wishing this callback to be called on every profile change are encouraged to disable
  9109. per-room profiles globally using the <code>allow_per_room_profiles</code> configuration setting in
  9110. Synapse's configuration file.
  9111. This callback is not called when registering a user, even when setting it through the
  9112. <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>
  9113. module callback.</p>
  9114. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9115. <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>
  9116. <p><em>First introduced in Synapse v1.54.0</em></p>
  9117. <pre><code class="language-python">async def on_user_deactivation_status_changed(
  9118. user_id: str, deactivated: bool, by_admin: bool
  9119. ) -&gt; None:
  9120. </code></pre>
  9121. <p>Called after deactivating a local user, or reactivating them through the admin API. The
  9122. deactivation can be triggered either by the user themselves or a server admin. The module
  9123. is passed the Matrix ID of the user whose status is changed, as well as a <code>deactivated</code>
  9124. boolean that is <code>True</code> if the user is being deactivated and <code>False</code> if they're being
  9125. reactivated, and a <code>by_admin</code> boolean that is <code>True</code> if the deactivation was triggered by
  9126. a server admin (and <code>False</code> otherwise). This latter <code>by_admin</code> boolean is always <code>True</code>
  9127. if the user is being reactivated, as this operation can only be performed through the
  9128. admin API.</p>
  9129. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9130. <h3 id="on_threepid_bind"><a class="header" href="#on_threepid_bind"><code>on_threepid_bind</code></a></h3>
  9131. <p><em>First introduced in Synapse v1.56.0</em></p>
  9132. <pre><code class="language-python">async def on_threepid_bind(user_id: str, medium: str, address: str) -&gt; None:
  9133. </code></pre>
  9134. <p>Called after creating an association between a local user and a third-party identifier
  9135. (email address, phone number). The module is given the Matrix ID of the user the
  9136. association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
  9137. third-party identifier.</p>
  9138. <p>Note that this callback is <em>not</em> called after a successful association on an <em>identity
  9139. server</em>.</p>
  9140. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9141. <h2 id="example-1"><a class="header" href="#example-1">Example</a></h2>
  9142. <p>The example below is a module that implements the third-party rules callback
  9143. <code>check_event_allowed</code> to censor incoming messages as dictated by a third-party service.</p>
  9144. <pre><code class="language-python">from typing import Optional, Tuple
  9145. from synapse.module_api import ModuleApi
  9146. _DEFAULT_CENSOR_ENDPOINT = &quot;https://my-internal-service.local/censor-event&quot;
  9147. class EventCensorer:
  9148. def __init__(self, config: dict, api: ModuleApi):
  9149. self.api = api
  9150. self._endpoint = config.get(&quot;endpoint&quot;, _DEFAULT_CENSOR_ENDPOINT)
  9151. self.api.register_third_party_rules_callbacks(
  9152. check_event_allowed=self.check_event_allowed,
  9153. )
  9154. async def check_event_allowed(
  9155. self,
  9156. event: &quot;synapse.events.EventBase&quot;,
  9157. state_events: &quot;synapse.types.StateMap&quot;,
  9158. ) -&gt; Tuple[bool, Optional[dict]]:
  9159. event_dict = event.get_dict()
  9160. new_event_content = await self.api.http_client.post_json_get_json(
  9161. uri=self._endpoint, post_json=event_dict,
  9162. )
  9163. event_dict[&quot;content&quot;] = new_event_content
  9164. return event_dict
  9165. </code></pre>
  9166. <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>
  9167. <p>Presence router callbacks allow module developers to specify additional users (local or remote)
  9168. to receive certain presence updates from local users. Presence router callbacks can be
  9169. registered using the module API's <code>register_presence_router_callbacks</code> method.</p>
  9170. <h2 id="callbacks-2"><a class="header" href="#callbacks-2">Callbacks</a></h2>
  9171. <p>The available presence router callbacks are:</p>
  9172. <h3 id="get_users_for_states"><a class="header" href="#get_users_for_states"><code>get_users_for_states</code></a></h3>
  9173. <p><em>First introduced in Synapse v1.42.0</em></p>
  9174. <pre><code class="language-python">async def get_users_for_states(
  9175. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  9176. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]
  9177. </code></pre>
  9178. <p><strong>Requires</strong> <code>get_interested_users</code> to also be registered</p>
  9179. <p>Called when processing updates to the presence state of one or more users. This callback can
  9180. be used to instruct the server to forward that presence state to specific users. The module
  9181. must return a dictionary that maps from Matrix user IDs (which can be local or remote) to the
  9182. <code>UserPresenceState</code> changes that they should be forwarded.</p>
  9183. <p>Synapse will then attempt to send the specified presence updates to each user when possible.</p>
  9184. <p>If multiple modules implement this callback, Synapse merges all the dictionaries returned
  9185. by the callbacks. If multiple callbacks return a dictionary containing the same key,
  9186. Synapse concatenates the sets associated with this key from each dictionary. </p>
  9187. <h3 id="get_interested_users"><a class="header" href="#get_interested_users"><code>get_interested_users</code></a></h3>
  9188. <p><em>First introduced in Synapse v1.42.0</em></p>
  9189. <pre><code class="language-python">async def get_interested_users(
  9190. user_id: str
  9191. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]
  9192. </code></pre>
  9193. <p><strong>Requires</strong> <code>get_users_for_states</code> to also be registered</p>
  9194. <p>Called when determining which users someone should be able to see the presence state of. This
  9195. callback should return complementary results to <code>get_users_for_state</code> or the presence information
  9196. may not be properly forwarded.</p>
  9197. <p>The callback is given the Matrix user ID for a local user that is requesting presence data and
  9198. should return the Matrix user IDs of the users whose presence state they are allowed to
  9199. query. The returned users can be local or remote. </p>
  9200. <p>Alternatively the callback can return <code>synapse.module_api.PRESENCE_ALL_USERS</code>
  9201. to indicate that the user should receive updates from all known users.</p>
  9202. <p>If multiple modules implement this callback, they will be considered in order. Synapse
  9203. calls each callback one by one, and use a concatenation of all the <code>set</code>s returned by the
  9204. callbacks. If one callback returns <code>synapse.module_api.PRESENCE_ALL_USERS</code>, Synapse uses
  9205. this value instead. If this happens, Synapse does not call any of the subsequent
  9206. implementations of this callback.</p>
  9207. <h2 id="example-2"><a class="header" href="#example-2">Example</a></h2>
  9208. <p>The example below is a module that implements both presence router callbacks, and ensures
  9209. that <code>@alice:example.org</code> receives all presence updates from <code>@bob:example.com</code> and
  9210. <code>@charlie:somewhere.org</code>, regardless of whether Alice shares a room with any of them.</p>
  9211. <pre><code class="language-python">from typing import Dict, Iterable, Set, Union
  9212. from synapse.module_api import ModuleApi
  9213. class CustomPresenceRouter:
  9214. def __init__(self, config: dict, api: ModuleApi):
  9215. self.api = api
  9216. self.api.register_presence_router_callbacks(
  9217. get_users_for_states=self.get_users_for_states,
  9218. get_interested_users=self.get_interested_users,
  9219. )
  9220. async def get_users_for_states(
  9221. self,
  9222. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  9223. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]:
  9224. res = {}
  9225. for update in state_updates:
  9226. if (
  9227. update.user_id == &quot;@bob:example.com&quot;
  9228. or update.user_id == &quot;@charlie:somewhere.org&quot;
  9229. ):
  9230. res.setdefault(&quot;@alice:example.com&quot;, set()).add(update)
  9231. return res
  9232. async def get_interested_users(
  9233. self,
  9234. user_id: str,
  9235. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]:
  9236. if user_id == &quot;@alice:example.com&quot;:
  9237. return {&quot;@bob:example.com&quot;, &quot;@charlie:somewhere.org&quot;}
  9238. return set()
  9239. </code></pre>
  9240. <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>
  9241. <p>Account validity callbacks allow module developers to add extra steps to verify the
  9242. validity on an account, i.e. see if a user can be granted access to their account on the
  9243. Synapse instance. Account validity callbacks can be registered using the module API's
  9244. <code>register_account_validity_callbacks</code> method.</p>
  9245. <p>The available account validity callbacks are:</p>
  9246. <h3 id="is_user_expired"><a class="header" href="#is_user_expired"><code>is_user_expired</code></a></h3>
  9247. <p><em>First introduced in Synapse v1.39.0</em></p>
  9248. <pre><code class="language-python">async def is_user_expired(user: str) -&gt; Optional[bool]
  9249. </code></pre>
  9250. <p>Called when processing any authenticated request (except for logout requests). The module
  9251. can return a <code>bool</code> to indicate whether the user has expired and should be locked out of
  9252. their account, or <code>None</code> if the module wasn't able to figure it out. The user is
  9253. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  9254. <p>If the module returns <code>True</code>, the current request will be denied with the error code
  9255. <code>ORG_MATRIX_EXPIRED_ACCOUNT</code> and the HTTP status code 403. Note that this doesn't
  9256. invalidate the user's access token.</p>
  9257. <p>If multiple modules implement this callback, they will be considered in order. If a
  9258. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  9259. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  9260. any of the subsequent implementations of this callback.</p>
  9261. <h3 id="on_user_registration"><a class="header" href="#on_user_registration"><code>on_user_registration</code></a></h3>
  9262. <p><em>First introduced in Synapse v1.39.0</em></p>
  9263. <pre><code class="language-python">async def on_user_registration(user: str) -&gt; None
  9264. </code></pre>
  9265. <p>Called after successfully registering a user, in case the module needs to perform extra
  9266. operations to keep track of them. (e.g. add them to a database table). The user is
  9267. represented by their Matrix user ID.</p>
  9268. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9269. <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>
  9270. <p>Password auth providers offer a way for server administrators to integrate
  9271. their Synapse installation with an external authentication system. The callbacks can be
  9272. registered by using the Module API's <code>register_password_auth_provider_callbacks</code> method.</p>
  9273. <h2 id="callbacks-3"><a class="header" href="#callbacks-3">Callbacks</a></h2>
  9274. <h3 id="auth_checkers"><a class="header" href="#auth_checkers"><code>auth_checkers</code></a></h3>
  9275. <p><em>First introduced in Synapse v1.46.0</em></p>
  9276. <pre><code class="language-python">auth_checkers: Dict[Tuple[str, Tuple[str, ...]], Callable]
  9277. </code></pre>
  9278. <p>A dict mapping from tuples of a login type identifier (such as <code>m.login.password</code>) and a
  9279. tuple of field names (such as <code>(&quot;password&quot;, &quot;secret_thing&quot;)</code>) to authentication checking
  9280. callbacks, which should be of the following form:</p>
  9281. <pre><code class="language-python">async def check_auth(
  9282. user: str,
  9283. login_type: str,
  9284. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  9285. ) -&gt; Optional[
  9286. Tuple[
  9287. str,
  9288. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  9289. ]
  9290. ]
  9291. </code></pre>
  9292. <p>The login type and field names should be provided by the user in the
  9293. request to the <code>/login</code> API. <a href="https://matrix.org/docs/spec/client_server/latest#authentication-types">The Matrix specification</a>
  9294. defines some types, however user defined ones are also allowed.</p>
  9295. <p>The callback is passed the <code>user</code> field provided by the client (which might not be in
  9296. <code>@username:server</code> form), the login type, and a dictionary of login secrets passed by
  9297. the client.</p>
  9298. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  9299. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the
  9300. <code>/login</code> request. If the module doesn't wish to return a callback, it must return <code>None</code>
  9301. instead.</p>
  9302. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  9303. <p>If multiple modules register an auth checker for the same login type but with different
  9304. fields, Synapse will refuse to start.</p>
  9305. <p>If multiple modules register an auth checker for the same login type with the same fields,
  9306. then the callbacks will be executed in order, until one returns a Matrix User ID (and
  9307. optionally a callback). In that case, the return value of that callback will be accepted
  9308. and subsequent callbacks will not be fired. If every callback returns <code>None</code>, then the
  9309. authentication fails.</p>
  9310. <h3 id="check_3pid_auth"><a class="header" href="#check_3pid_auth"><code>check_3pid_auth</code></a></h3>
  9311. <p><em>First introduced in Synapse v1.46.0</em></p>
  9312. <pre><code class="language-python">async def check_3pid_auth(
  9313. medium: str,
  9314. address: str,
  9315. password: str,
  9316. ) -&gt; Optional[
  9317. Tuple[
  9318. str,
  9319. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  9320. ]
  9321. ]
  9322. </code></pre>
  9323. <p>Called when a user attempts to register or log in with a third party identifier,
  9324. such as email. It is passed the medium (eg. <code>email</code>), an address (eg. <code>jdoe@example.com</code>)
  9325. and the user's password.</p>
  9326. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  9327. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the <code>/login</code> request.
  9328. If the module doesn't wish to return a callback, it must return None instead.</p>
  9329. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  9330. <p>If multiple modules implement this callback, they will be considered in order. If a
  9331. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  9332. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  9333. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  9334. the authentication is denied.</p>
  9335. <h3 id="on_logged_out"><a class="header" href="#on_logged_out"><code>on_logged_out</code></a></h3>
  9336. <p><em>First introduced in Synapse v1.46.0</em></p>
  9337. <pre><code class="language-python">async def on_logged_out(
  9338. user_id: str,
  9339. device_id: Optional[str],
  9340. access_token: str
  9341. ) -&gt; None
  9342. </code></pre>
  9343. <p>Called during a logout request for a user. It is passed the qualified user ID, the ID of the
  9344. deactivated device (if any: access tokens are occasionally created without an associated
  9345. device ID), and the (now deactivated) access token.</p>
  9346. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9347. <h3 id="get_username_for_registration"><a class="header" href="#get_username_for_registration"><code>get_username_for_registration</code></a></h3>
  9348. <p><em>First introduced in Synapse v1.52.0</em></p>
  9349. <pre><code class="language-python">async def get_username_for_registration(
  9350. uia_results: Dict[str, Any],
  9351. params: Dict[str, Any],
  9352. ) -&gt; Optional[str]
  9353. </code></pre>
  9354. <p>Called when registering a new user. The module can return a username to set for the user
  9355. being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  9356. username for this user. If a username is returned, it will be used as the local part of a
  9357. user's full Matrix ID (e.g. it's <code>alice</code> in <code>@alice:example.com</code>).</p>
  9358. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  9359. has been completed by the user. It is not called when registering a user via SSO. It is
  9360. passed two dictionaries, which include the information that the user has provided during
  9361. the registration process.</p>
  9362. <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>
  9363. flow followed by the user. Its keys are the identifiers of every step involved in the flow,
  9364. associated with either a boolean value indicating whether the step was correctly completed,
  9365. or additional information (e.g. email address, phone number...). A list of most existing
  9366. identifiers can be found in the <a href="https://spec.matrix.org/v1.1/client-server-api/#authentication-types">Matrix specification</a>.
  9367. Here's an example featuring all currently supported keys:</p>
  9368. <pre><code class="language-python">{
  9369. &quot;m.login.dummy&quot;: True, # Dummy authentication
  9370. &quot;m.login.terms&quot;: True, # User has accepted the terms of service for the homeserver
  9371. &quot;m.login.recaptcha&quot;: True, # User has completed the recaptcha challenge
  9372. &quot;m.login.email.identity&quot;: { # User has provided and verified an email address
  9373. &quot;medium&quot;: &quot;email&quot;,
  9374. &quot;address&quot;: &quot;alice@example.com&quot;,
  9375. &quot;validated_at&quot;: 1642701357084,
  9376. },
  9377. &quot;m.login.msisdn&quot;: { # User has provided and verified a phone number
  9378. &quot;medium&quot;: &quot;msisdn&quot;,
  9379. &quot;address&quot;: &quot;33123456789&quot;,
  9380. &quot;validated_at&quot;: 1642701357084,
  9381. },
  9382. &quot;m.login.registration_token&quot;: &quot;sometoken&quot;, # User has registered through a registration token
  9383. }
  9384. </code></pre>
  9385. <p>The second dictionary contains the parameters provided by the user's client in the request
  9386. to <code>/_matrix/client/v3/register</code>. See the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3register">Matrix specification</a>
  9387. for a complete list of these parameters.</p>
  9388. <p>If the module cannot, or does not wish to, generate a username for this user, it must
  9389. return <code>None</code>.</p>
  9390. <p>If multiple modules implement this callback, they will be considered in order. If a
  9391. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  9392. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  9393. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  9394. the username provided by the user is used, if any (otherwise one is automatically
  9395. generated).</p>
  9396. <h3 id="get_displayname_for_registration"><a class="header" href="#get_displayname_for_registration"><code>get_displayname_for_registration</code></a></h3>
  9397. <p><em>First introduced in Synapse v1.54.0</em></p>
  9398. <pre><code class="language-python">async def get_displayname_for_registration(
  9399. uia_results: Dict[str, Any],
  9400. params: Dict[str, Any],
  9401. ) -&gt; Optional[str]
  9402. </code></pre>
  9403. <p>Called when registering a new user. The module can return a display name to set for the
  9404. user being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  9405. display name for this user.</p>
  9406. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  9407. has been completed by the user. It is not called when registering a user via SSO. It is
  9408. passed two dictionaries, which include the information that the user has provided during
  9409. the registration process. These dictionaries are identical to the ones passed to
  9410. <a href="modules/password_auth_provider_callbacks.html#get_username_for_registration"><code>get_username_for_registration</code></a>, so refer to the
  9411. documentation of this callback for more information about them.</p>
  9412. <p>If multiple modules implement this callback, they will be considered in order. If a
  9413. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  9414. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  9415. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  9416. the username will be used (e.g. <code>alice</code> if the user being registered is <code>@alice:example.com</code>).</p>
  9417. <h2 id="is_3pid_allowed"><a class="header" href="#is_3pid_allowed"><code>is_3pid_allowed</code></a></h2>
  9418. <p><em>First introduced in Synapse v1.53.0</em></p>
  9419. <pre><code class="language-python">async def is_3pid_allowed(self, medium: str, address: str, registration: bool) -&gt; bool
  9420. </code></pre>
  9421. <p>Called when attempting to bind a third-party identifier (i.e. an email address or a phone
  9422. number). The module is given the medium of the third-party identifier (which is <code>email</code> if
  9423. the identifier is an email address, or <code>msisdn</code> if the identifier is a phone number) and
  9424. its address, as well as a boolean indicating whether the attempt to bind is happening as
  9425. part of registering a new user. The module must return a boolean indicating whether the
  9426. identifier can be allowed to be bound to an account on the local homeserver.</p>
  9427. <p>If multiple modules implement this callback, they will be considered in order. If a
  9428. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  9429. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  9430. any of the subsequent implementations of this callback.</p>
  9431. <h2 id="example-3"><a class="header" href="#example-3">Example</a></h2>
  9432. <p>The example module below implements authentication checkers for two different login types: </p>
  9433. <ul>
  9434. <li><code>my.login.type</code>
  9435. <ul>
  9436. <li>Expects a <code>my_field</code> field to be sent to <code>/login</code></li>
  9437. <li>Is checked by the method: <code>self.check_my_login</code></li>
  9438. </ul>
  9439. </li>
  9440. <li><code>m.login.password</code> (defined in <a href="https://matrix.org/docs/spec/client_server/latest#password-based">the spec</a>)
  9441. <ul>
  9442. <li>Expects a <code>password</code> field to be sent to <code>/login</code></li>
  9443. <li>Is checked by the method: <code>self.check_pass</code></li>
  9444. </ul>
  9445. </li>
  9446. </ul>
  9447. <pre><code class="language-python">from typing import Awaitable, Callable, Optional, Tuple
  9448. import synapse
  9449. from synapse import module_api
  9450. class MyAuthProvider:
  9451. def __init__(self, config: dict, api: module_api):
  9452. self.api = api
  9453. self.credentials = {
  9454. &quot;bob&quot;: &quot;building&quot;,
  9455. &quot;@scoop:matrix.org&quot;: &quot;digging&quot;,
  9456. }
  9457. api.register_password_auth_provider_callbacks(
  9458. auth_checkers={
  9459. (&quot;my.login_type&quot;, (&quot;my_field&quot;,)): self.check_my_login,
  9460. (&quot;m.login.password&quot;, (&quot;password&quot;,)): self.check_pass,
  9461. },
  9462. )
  9463. async def check_my_login(
  9464. self,
  9465. username: str,
  9466. login_type: str,
  9467. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  9468. ) -&gt; Optional[
  9469. Tuple[
  9470. str,
  9471. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  9472. ]
  9473. ]:
  9474. if login_type != &quot;my.login_type&quot;:
  9475. return None
  9476. if self.credentials.get(username) == login_dict.get(&quot;my_field&quot;):
  9477. return (self.api.get_qualified_user_id(username), None)
  9478. async def check_pass(
  9479. self,
  9480. username: str,
  9481. login_type: str,
  9482. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  9483. ) -&gt; Optional[
  9484. Tuple[
  9485. str,
  9486. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  9487. ]
  9488. ]:
  9489. if login_type != &quot;m.login.password&quot;:
  9490. return None
  9491. if self.credentials.get(username) == login_dict.get(&quot;password&quot;):
  9492. return (self.api.get_qualified_user_id(username), None)
  9493. </code></pre>
  9494. <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>
  9495. <p>Background update controller callbacks allow module developers to control (e.g. rate-limit)
  9496. how database background updates are run. A database background update is an operation
  9497. Synapse runs on its database in the background after it starts. It's usually used to run
  9498. database operations that would take too long if they were run at the same time as schema
  9499. updates (which are run on startup) and delay Synapse's startup too much: populating a
  9500. table with a big amount of data, adding an index on a big table, deleting superfluous data,
  9501. etc.</p>
  9502. <p>Background update controller callbacks can be registered using the module API's
  9503. <code>register_background_update_controller_callbacks</code> method. Only the first module (in order
  9504. of appearance in Synapse's configuration file) calling this method can register background
  9505. update controller callbacks, subsequent calls are ignored.</p>
  9506. <p>The available background update controller callbacks are:</p>
  9507. <h3 id="on_update"><a class="header" href="#on_update"><code>on_update</code></a></h3>
  9508. <p><em>First introduced in Synapse v1.49.0</em></p>
  9509. <pre><code class="language-python">def on_update(update_name: str, database_name: str, one_shot: bool) -&gt; AsyncContextManager[int]
  9510. </code></pre>
  9511. <p>Called when about to do an iteration of a background update. The module is given the name
  9512. of the update, the name of the database, and a flag to indicate whether the background
  9513. update will happen in one go and may take a long time (e.g. creating indices). If this last
  9514. argument is set to <code>False</code>, the update will be run in batches.</p>
  9515. <p>The module must return an async context manager. It will be entered before Synapse runs a
  9516. background update; this should return the desired duration of the iteration, in
  9517. milliseconds.</p>
  9518. <p>The context manager will be exited when the iteration completes. Note that the duration
  9519. returned by the context manager is a target, and an iteration may take substantially longer
  9520. or shorter. If the <code>one_shot</code> flag is set to <code>True</code>, the duration returned is ignored.</p>
  9521. <p><strong>Note</strong>: Unlike most module callbacks in Synapse, this one is <em>synchronous</em>. This is
  9522. because asynchronous operations are expected to be run by the async context manager.</p>
  9523. <p>This callback is required when registering any other background update controller callback.</p>
  9524. <h3 id="default_batch_size"><a class="header" href="#default_batch_size"><code>default_batch_size</code></a></h3>
  9525. <p><em>First introduced in Synapse v1.49.0</em></p>
  9526. <pre><code class="language-python">async def default_batch_size(update_name: str, database_name: str) -&gt; int
  9527. </code></pre>
  9528. <p>Called before the first iteration of a background update, with the name of the update and
  9529. of the database. The module must return the number of elements to process in this first
  9530. iteration.</p>
  9531. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  9532. <h3 id="min_batch_size"><a class="header" href="#min_batch_size"><code>min_batch_size</code></a></h3>
  9533. <p><em>First introduced in Synapse v1.49.0</em></p>
  9534. <pre><code class="language-python">async def min_batch_size(update_name: str, database_name: str) -&gt; int
  9535. </code></pre>
  9536. <p>Called before running a new batch for a background update, with the name of the update and
  9537. of the database. The module must return an integer representing the minimum number of
  9538. elements to process in this iteration. This number must be at least 1, and is used to
  9539. ensure that progress is always made.</p>
  9540. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  9541. <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>
  9542. <p>Account data callbacks allow module developers to react to changes of the account data
  9543. of local users. Account data callbacks can be registered using the module API's
  9544. <code>register_account_data_callbacks</code> method.</p>
  9545. <h2 id="callbacks-4"><a class="header" href="#callbacks-4">Callbacks</a></h2>
  9546. <p>The available account data callbacks are:</p>
  9547. <h3 id="on_account_data_updated"><a class="header" href="#on_account_data_updated"><code>on_account_data_updated</code></a></h3>
  9548. <p><em>First introduced in Synapse v1.57.0</em></p>
  9549. <pre><code class="language-python">async def on_account_data_updated(
  9550. user_id: str,
  9551. room_id: Optional[str],
  9552. account_data_type: str,
  9553. content: &quot;synapse.module_api.JsonDict&quot;,
  9554. ) -&gt; None:
  9555. </code></pre>
  9556. <p>Called after user's account data has been updated. The module is given the
  9557. Matrix ID of the user whose account data is changing, the room ID the data is associated
  9558. with, the type associated with the change, as well as the new content. If the account
  9559. data is not associated with a specific room, then the room ID is <code>None</code>.</p>
  9560. <p>This callback is triggered when new account data is added or when the data associated with
  9561. a given type (and optionally room) changes. This includes deletion, since in Matrix,
  9562. deleting account data consists of replacing the data associated with a given type
  9563. (and optionally room) with an empty dictionary (<code>{}</code>).</p>
  9564. <p>Note that this doesn't trigger when changing the tags associated with a room, as these are
  9565. processed separately by Synapse.</p>
  9566. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9567. <h2 id="example-4"><a class="header" href="#example-4">Example</a></h2>
  9568. <p>The example below is a module that implements the <code>on_account_data_updated</code> callback, and
  9569. sends an event to an audit room when a user changes their account data.</p>
  9570. <pre><code class="language-python">import json
  9571. import attr
  9572. from typing import Any, Dict, Optional
  9573. from synapse.module_api import JsonDict, ModuleApi
  9574. from synapse.module_api.errors import ConfigError
  9575. @attr.s(auto_attribs=True)
  9576. class CustomAccountDataConfig:
  9577. audit_room: str
  9578. sender: str
  9579. class CustomAccountDataModule:
  9580. def __init__(self, config: CustomAccountDataConfig, api: ModuleApi):
  9581. self.api = api
  9582. self.config = config
  9583. self.api.register_account_data_callbacks(
  9584. on_account_data_updated=self.log_new_account_data,
  9585. )
  9586. @staticmethod
  9587. def parse_config(config: Dict[str, Any]) -&gt; CustomAccountDataConfig:
  9588. def check_in_config(param: str):
  9589. if param not in config:
  9590. raise ConfigError(f&quot;'{param}' is required&quot;)
  9591. check_in_config(&quot;audit_room&quot;)
  9592. check_in_config(&quot;sender&quot;)
  9593. return CustomAccountDataConfig(
  9594. audit_room=config[&quot;audit_room&quot;],
  9595. sender=config[&quot;sender&quot;],
  9596. )
  9597. async def log_new_account_data(
  9598. self,
  9599. user_id: str,
  9600. room_id: Optional[str],
  9601. account_data_type: str,
  9602. content: JsonDict,
  9603. ) -&gt; None:
  9604. content_raw = json.dumps(content)
  9605. msg_content = f&quot;{user_id} has changed their account data for type {account_data_type} to: {content_raw}&quot;
  9606. if room_id is not None:
  9607. msg_content += f&quot; (in room {room_id})&quot;
  9608. await self.api.create_and_send_event_into_room(
  9609. {
  9610. &quot;room_id&quot;: self.config.audit_room,
  9611. &quot;sender&quot;: self.config.sender,
  9612. &quot;type&quot;: &quot;m.room.message&quot;,
  9613. &quot;content&quot;: {
  9614. &quot;msgtype&quot;: &quot;m.text&quot;,
  9615. &quot;body&quot;: msg_content
  9616. }
  9617. }
  9618. )
  9619. </code></pre>
  9620. <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>
  9621. <p>In order to port a module that uses Synapse's old module interface, its author needs to:</p>
  9622. <ul>
  9623. <li>ensure the module's callbacks are all asynchronous.</li>
  9624. <li>register their callbacks using one or more of the <code>register_[...]_callbacks</code> methods
  9625. 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>
  9626. for more info).</li>
  9627. </ul>
  9628. <p>Additionally, if the module is packaged with an additional web resource, the module
  9629. should register this resource in its <code>__init__</code> method using the <code>register_web_resource</code>
  9630. method from the <code>ModuleApi</code> class (see <a href="modules/writing_a_module.html#registering-a-web-resource">this section</a> for
  9631. more info).</p>
  9632. <p>There is no longer a <code>get_db_schema_files</code> callback provided for password auth provider modules. Any
  9633. changes to the database should now be made by the module using the module API class.</p>
  9634. <p>The module's author should also update any example in the module's configuration to only
  9635. use the new <code>modules</code> section in Synapse's configuration file (see <a href="modules/index.html#using-modules">this section</a>
  9636. for more info).</p>
  9637. <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>
  9638. <p>For small instances it is recommended to run Synapse in the default monolith mode.
  9639. For larger instances where performance is a concern it can be helpful to split
  9640. out functionality into multiple separate python processes. These processes are
  9641. called 'workers', and are (eventually) intended to scale horizontally
  9642. independently.</p>
  9643. <p>Synapse's worker support is under active development and subject to change as
  9644. we attempt to rapidly scale ever larger Synapse instances. However we are
  9645. documenting it here to help admins needing a highly scalable Synapse instance
  9646. similar to the one running <code>matrix.org</code>.</p>
  9647. <p>All processes continue to share the same database instance, and as such,
  9648. workers only work with PostgreSQL-based Synapse deployments. SQLite should only
  9649. be used for demo purposes and any admin considering workers should already be
  9650. running PostgreSQL.</p>
  9651. <p>See also <a href="https://matrix.org/blog/2020/11/03/how-we-fixed-synapses-scalability">Matrix.org blog post</a>
  9652. for a higher level overview.</p>
  9653. <h2 id="main-processworker-communication"><a class="header" href="#main-processworker-communication">Main process/worker communication</a></h2>
  9654. <p>The processes communicate with each other via a Synapse-specific protocol called
  9655. 'replication' (analogous to MySQL- or Postgres-style database replication) which
  9656. feeds streams of newly written data between processes so they can be kept in
  9657. sync with the database state.</p>
  9658. <p>When configured to do so, Synapse uses a
  9659. <a href="https://redis.io/docs/manual/pubsub/">Redis pub/sub channel</a> to send the replication
  9660. stream between all configured Synapse processes. Additionally, processes may
  9661. make HTTP requests to each other, primarily for operations which need to wait
  9662. for a reply ─ such as sending an event.</p>
  9663. <p>All the workers and the main process connect to Redis, which relays replication
  9664. commands between processes.</p>
  9665. <p>If Redis support is enabled Synapse will use it as a shared cache, as well as a
  9666. pub/sub mechanism.</p>
  9667. <p>See the <a href="workers.html#architectural-diagram">Architectural diagram</a> section at the end for
  9668. a visualisation of what this looks like.</p>
  9669. <h2 id="setting-up-workers"><a class="header" href="#setting-up-workers">Setting up workers</a></h2>
  9670. <p>A Redis server is required to manage the communication between the processes.
  9671. The Redis server should be installed following the normal procedure for your
  9672. distribution (e.g. <code>apt install redis-server</code> on Debian). It is safe to use an
  9673. existing Redis deployment if you have one.</p>
  9674. <p>Once installed, check that Redis is running and accessible from the host running
  9675. Synapse, for example by executing <code>echo PING | nc -q1 localhost 6379</code> and seeing
  9676. a response of <code>+PONG</code>.</p>
  9677. <p>The appropriate dependencies must also be installed for Synapse. If using a
  9678. virtualenv, these can be installed with:</p>
  9679. <pre><code class="language-sh">pip install &quot;matrix-synapse[redis]&quot;
  9680. </code></pre>
  9681. <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
  9682. <code>matrix.org</code> and in the docker images at
  9683. https://hub.docker.com/r/matrixdotorg/synapse/.</p>
  9684. <p>To make effective use of the workers, you will need to configure an HTTP
  9685. reverse-proxy such as nginx or haproxy, which will direct incoming requests to
  9686. the correct worker, or to the main synapse instance. See
  9687. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a reverse
  9688. proxy.</p>
  9689. <p>When using workers, each worker process has its own configuration file which
  9690. contains settings specific to that worker, such as the HTTP listener that it
  9691. provides (if any), logging configuration, etc.</p>
  9692. <p>Normally, the worker processes are configured to read from a shared
  9693. configuration file as well as the worker-specific configuration files. This
  9694. makes it easier to keep common configuration settings synchronised across all
  9695. the processes.</p>
  9696. <p>The main process is somewhat special in this respect: it does not normally
  9697. need its own configuration file and can take all of its configuration from the
  9698. shared configuration file.</p>
  9699. <h3 id="shared-configuration"><a class="header" href="#shared-configuration">Shared configuration</a></h3>
  9700. <p>Normally, only a couple of changes are needed to make an existing configuration
  9701. file suitable for use with workers. First, you need to enable an &quot;HTTP replication
  9702. listener&quot; for the main process; and secondly, you need to enable redis-based
  9703. replication. Optionally, a shared secret can be used to authenticate HTTP
  9704. traffic between workers. For example:</p>
  9705. <pre><code class="language-yaml"># extend the existing `listeners` section. This defines the ports that the
  9706. # main process will listen on.
  9707. listeners:
  9708. # The HTTP replication port
  9709. - port: 9093
  9710. bind_address: '127.0.0.1'
  9711. type: http
  9712. resources:
  9713. - names: [replication]
  9714. # Add a random shared secret to authenticate traffic.
  9715. worker_replication_secret: &quot;&quot;
  9716. redis:
  9717. enabled: true
  9718. </code></pre>
  9719. <p>See the <a href="usage/configuration/config_documentation.html">configuration manual</a> for the full documentation of each option.</p>
  9720. <p>Under <strong>no circumstances</strong> should the replication listener be exposed to the
  9721. public internet; replication traffic is:</p>
  9722. <ul>
  9723. <li>always unencrypted</li>
  9724. <li>unauthenticated, unless <code>worker_replication_secret</code> is configured</li>
  9725. </ul>
  9726. <h3 id="worker-configuration"><a class="header" href="#worker-configuration">Worker configuration</a></h3>
  9727. <p>In the config file for each worker, you must specify:</p>
  9728. <ul>
  9729. <li>The type of worker (<code>worker_app</code>). The currently available worker applications are listed below.</li>
  9730. <li>A unique name for the worker (<code>worker_name</code>).</li>
  9731. <li>The HTTP replication endpoint that it should talk to on the main synapse process
  9732. (<code>worker_replication_host</code> and <code>worker_replication_http_port</code>)</li>
  9733. <li>If handling HTTP requests, a <code>worker_listeners</code> option with an <code>http</code>
  9734. listener, in the same way as the <a href="usage/configuration/config_documentation.html#listeners"><code>listeners</code></a>
  9735. option in the shared config.</li>
  9736. <li>If handling the <code>^/_matrix/client/v3/keys/upload</code> endpoint, the HTTP URI for
  9737. the main process (<code>worker_main_http_uri</code>).</li>
  9738. </ul>
  9739. <p>For example:</p>
  9740. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  9741. worker_name: generic_worker1
  9742. # The replication listener on the main synapse process.
  9743. worker_replication_host: 127.0.0.1
  9744. worker_replication_http_port: 9093
  9745. worker_main_http_uri: http://localhost:8008/
  9746. worker_listeners:
  9747. - type: http
  9748. port: 8083
  9749. resources:
  9750. - names: [client, federation]
  9751. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  9752. </code></pre>
  9753. <p>...is a full configuration for a generic worker instance, which will expose a
  9754. plain HTTP endpoint on port 8083 separately serving various endpoints, e.g.
  9755. <code>/sync</code>, which are listed below.</p>
  9756. <p>Obviously you should configure your reverse-proxy to route the relevant
  9757. endpoints to the worker (<code>localhost:8083</code> in the above example).</p>
  9758. <h3 id="running-synapse-with-workers"><a class="header" href="#running-synapse-with-workers">Running Synapse with workers</a></h3>
  9759. <p>Finally, you need to start your worker processes. This can be done with either
  9760. <code>synctl</code> or your distribution's preferred service manager such as <code>systemd</code>. We
  9761. recommend the use of <code>systemd</code> where available: for information on setting up
  9762. <code>systemd</code> to start synapse workers, see
  9763. <a href="systemd-with-workers">Systemd with Workers</a>. To use <code>synctl</code>, see
  9764. <a href="synctl_workers.html">Using synctl with Workers</a>.</p>
  9765. <h2 id="available-worker-applications"><a class="header" href="#available-worker-applications">Available worker applications</a></h2>
  9766. <h3 id="synapseappgeneric_worker"><a class="header" href="#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a></h3>
  9767. <p>This worker can handle API requests matching the following regular expressions.
  9768. These endpoints can be routed to any worker. If a worker is set up to handle a
  9769. stream then, for maximum efficiency, additional endpoints should be routed to that
  9770. worker: refer to the <a href="workers.html#stream-writers">stream writers</a> section below for further
  9771. information.</p>
  9772. <pre><code># Sync requests
  9773. ^/_matrix/client/(r0|v3)/sync$
  9774. ^/_matrix/client/(api/v1|r0|v3)/events$
  9775. ^/_matrix/client/(api/v1|r0|v3)/initialSync$
  9776. ^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$
  9777. # Federation requests
  9778. ^/_matrix/federation/v1/event/
  9779. ^/_matrix/federation/v1/state/
  9780. ^/_matrix/federation/v1/state_ids/
  9781. ^/_matrix/federation/v1/backfill/
  9782. ^/_matrix/federation/v1/get_missing_events/
  9783. ^/_matrix/federation/v1/publicRooms
  9784. ^/_matrix/federation/v1/query/
  9785. ^/_matrix/federation/v1/make_join/
  9786. ^/_matrix/federation/v1/make_leave/
  9787. ^/_matrix/federation/(v1|v2)/send_join/
  9788. ^/_matrix/federation/(v1|v2)/send_leave/
  9789. ^/_matrix/federation/(v1|v2)/invite/
  9790. ^/_matrix/federation/v1/event_auth/
  9791. ^/_matrix/federation/v1/exchange_third_party_invite/
  9792. ^/_matrix/federation/v1/user/devices/
  9793. ^/_matrix/key/v2/query
  9794. ^/_matrix/federation/v1/hierarchy/
  9795. # Inbound federation transaction request
  9796. ^/_matrix/federation/v1/send/
  9797. # Client API requests
  9798. ^/_matrix/client/(api/v1|r0|v3|unstable)/createRoom$
  9799. ^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$
  9800. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$
  9801. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$
  9802. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$
  9803. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$
  9804. ^/_matrix/client/v1/rooms/.*/hierarchy$
  9805. ^/_matrix/client/unstable/org.matrix.msc2716/rooms/.*/batch_send$
  9806. ^/_matrix/client/unstable/im.nheko.summary/rooms/.*/summary$
  9807. ^/_matrix/client/(r0|v3|unstable)/account/3pid$
  9808. ^/_matrix/client/(r0|v3|unstable)/account/whoami$
  9809. ^/_matrix/client/(r0|v3|unstable)/devices$
  9810. ^/_matrix/client/versions$
  9811. ^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$
  9812. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event/
  9813. ^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms$
  9814. ^/_matrix/client/(api/v1|r0|v3|unstable)/search$
  9815. # Encryption requests
  9816. # Note that ^/_matrix/client/(r0|v3|unstable)/keys/upload/ requires `worker_main_http_uri`
  9817. ^/_matrix/client/(r0|v3|unstable)/keys/query$
  9818. ^/_matrix/client/(r0|v3|unstable)/keys/changes$
  9819. ^/_matrix/client/(r0|v3|unstable)/keys/claim$
  9820. ^/_matrix/client/(r0|v3|unstable)/room_keys/
  9821. ^/_matrix/client/(r0|v3|unstable)/keys/upload/
  9822. # Registration/login requests
  9823. ^/_matrix/client/(api/v1|r0|v3|unstable)/login$
  9824. ^/_matrix/client/(r0|v3|unstable)/register$
  9825. ^/_matrix/client/v1/register/m.login.registration_token/validity$
  9826. # Event sending requests
  9827. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact
  9828. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send
  9829. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state/
  9830. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$
  9831. ^/_matrix/client/(api/v1|r0|v3|unstable)/join/
  9832. ^/_matrix/client/(api/v1|r0|v3|unstable)/profile/
  9833. # Account data requests
  9834. ^/_matrix/client/(r0|v3|unstable)/.*/tags
  9835. ^/_matrix/client/(r0|v3|unstable)/.*/account_data
  9836. # Receipts requests
  9837. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
  9838. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
  9839. # Presence requests
  9840. ^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
  9841. # User directory search requests
  9842. ^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  9843. </code></pre>
  9844. <p>Additionally, the following REST endpoints can be handled for GET requests:</p>
  9845. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/pushrules/
  9846. </code></pre>
  9847. <p>Pagination requests can also be handled, but all requests for a given
  9848. room must be routed to the same instance. Additionally, care must be taken to
  9849. ensure that the purge history admin API is not used while pagination requests
  9850. for the room are in flight:</p>
  9851. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$
  9852. </code></pre>
  9853. <p>Additionally, the following endpoints should be included if Synapse is configured
  9854. to use SSO (you only need to include the ones for whichever SSO provider you're
  9855. using):</p>
  9856. <pre><code># for all SSO providers
  9857. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/sso/redirect
  9858. ^/_synapse/client/pick_idp$
  9859. ^/_synapse/client/pick_username
  9860. ^/_synapse/client/new_user_consent$
  9861. ^/_synapse/client/sso_register$
  9862. # OpenID Connect requests.
  9863. ^/_synapse/client/oidc/callback$
  9864. # SAML requests.
  9865. ^/_synapse/client/saml2/authn_response$
  9866. # CAS requests.
  9867. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/cas/ticket$
  9868. </code></pre>
  9869. <p>Ensure that all SSO logins go to a single process.
  9870. For multiple workers not handling the SSO endpoints properly, see
  9871. <a href="https://github.com/matrix-org/synapse/issues/7530">#7530</a> and
  9872. <a href="https://github.com/matrix-org/synapse/issues/9427">#9427</a>.</p>
  9873. <p>Note that a <a href="usage/configuration/config_documentation.html#listeners">HTTP listener</a>
  9874. with <code>client</code> and <code>federation</code> <code>resources</code> must be configured in the <code>worker_listeners</code>
  9875. option in the worker config.</p>
  9876. <h4 id="load-balancing"><a class="header" href="#load-balancing">Load balancing</a></h4>
  9877. <p>It is possible to run multiple instances of this worker app, with incoming requests
  9878. being load-balanced between them by the reverse-proxy. However, different endpoints
  9879. have different characteristics and so admins
  9880. may wish to run multiple groups of workers handling different endpoints so that
  9881. load balancing can be done in different ways.</p>
  9882. <p>For <code>/sync</code> and <code>/initialSync</code> requests it will be more efficient if all
  9883. requests from a particular user are routed to a single instance. Extracting a
  9884. user ID from the access token or <code>Authorization</code> header is currently left as an
  9885. exercise for the reader. Admins may additionally wish to separate out <code>/sync</code>
  9886. requests that have a <code>since</code> query parameter from those that don't (and
  9887. <code>/initialSync</code>), as requests that don't are known as &quot;initial sync&quot; that happens
  9888. when a user logs in on a new device and can be <em>very</em> resource intensive, so
  9889. isolating these requests will stop them from interfering with other users ongoing
  9890. syncs.</p>
  9891. <p>Federation and client requests can be balanced via simple round robin.</p>
  9892. <p>The inbound federation transaction request <code>^/_matrix/federation/v1/send/</code>
  9893. should be balanced by source IP so that transactions from the same remote server
  9894. go to the same process.</p>
  9895. <p>Registration/login requests can be handled separately purely to help ensure that
  9896. unexpected load doesn't affect new logins and sign ups.</p>
  9897. <p>Finally, event sending requests can be balanced by the room ID in the URI (or
  9898. the full URI, or even just round robin), the room ID is the path component after
  9899. <code>/rooms/</code>. If there is a large bridge connected that is sending or may send lots
  9900. of events, then a dedicated set of workers can be provisioned to limit the
  9901. effects of bursts of events from that bridge on events sent by normal users.</p>
  9902. <h4 id="stream-writers"><a class="header" href="#stream-writers">Stream writers</a></h4>
  9903. <p>Additionally, the writing of specific streams (such as events) can be moved off
  9904. of the main process to a particular worker.</p>
  9905. <p>To enable this, the worker must have a
  9906. <a href="usage/configuration/config_documentation.html#listeners">HTTP <code>replication</code> listener</a> configured,
  9907. have a <code>worker_name</code> and be listed in the <code>instance_map</code> config. The same worker
  9908. can handle multiple streams, but unless otherwise documented, each stream can only
  9909. have a single writer.</p>
  9910. <p>For example, to move event persistence off to a dedicated worker, the shared
  9911. configuration would include:</p>
  9912. <pre><code class="language-yaml">instance_map:
  9913. event_persister1:
  9914. host: localhost
  9915. port: 8034
  9916. stream_writers:
  9917. events: event_persister1
  9918. </code></pre>
  9919. <p>An example for a stream writer instance:</p>
  9920. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  9921. worker_name: event_persister1
  9922. # The replication listener on the main synapse process.
  9923. worker_replication_host: 127.0.0.1
  9924. worker_replication_http_port: 9093
  9925. worker_listeners:
  9926. - type: http
  9927. port: 8034
  9928. resources:
  9929. - names: [replication]
  9930. # Enable listener if this stream writer handles endpoints for the `typing` or
  9931. # `to_device` streams. Uses a different port to the `replication` listener to
  9932. # avoid exposing the `replication` listener publicly.
  9933. #
  9934. #- type: http
  9935. # port: 8035
  9936. # resources:
  9937. # - names: [client]
  9938. worker_log_config: /etc/matrix-synapse/event-persister-log.yaml
  9939. </code></pre>
  9940. <p>Some of the streams have associated endpoints which, for maximum efficiency, should
  9941. be routed to the workers handling that stream. See below for the currently supported
  9942. streams and the endpoints associated with them:</p>
  9943. <h5 id="the-events-stream"><a class="header" href="#the-events-stream">The <code>events</code> stream</a></h5>
  9944. <p>The <code>events</code> stream experimentally supports having multiple writers, where work
  9945. is sharded between them by room ID. Note that you <em>must</em> restart all worker
  9946. instances when adding or removing event persisters. An example <code>stream_writers</code>
  9947. configuration with multiple writers:</p>
  9948. <pre><code class="language-yaml">stream_writers:
  9949. events:
  9950. - event_persister1
  9951. - event_persister2
  9952. </code></pre>
  9953. <h5 id="the-typing-stream"><a class="header" href="#the-typing-stream">The <code>typing</code> stream</a></h5>
  9954. <p>The following endpoints should be routed directly to the worker configured as
  9955. the stream writer for the <code>typing</code> stream:</p>
  9956. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/typing
  9957. </code></pre>
  9958. <h5 id="the-to_device-stream"><a class="header" href="#the-to_device-stream">The <code>to_device</code> stream</a></h5>
  9959. <p>The following endpoints should be routed directly to the worker configured as
  9960. the stream writer for the <code>to_device</code> stream:</p>
  9961. <pre><code>^/_matrix/client/(r0|v3|unstable)/sendToDevice/
  9962. </code></pre>
  9963. <h5 id="the-account_data-stream"><a class="header" href="#the-account_data-stream">The <code>account_data</code> stream</a></h5>
  9964. <p>The following endpoints should be routed directly to the worker configured as
  9965. the stream writer for the <code>account_data</code> stream:</p>
  9966. <pre><code>^/_matrix/client/(r0|v3|unstable)/.*/tags
  9967. ^/_matrix/client/(r0|v3|unstable)/.*/account_data
  9968. </code></pre>
  9969. <h5 id="the-receipts-stream"><a class="header" href="#the-receipts-stream">The <code>receipts</code> stream</a></h5>
  9970. <p>The following endpoints should be routed directly to the worker configured as
  9971. the stream writer for the <code>receipts</code> stream:</p>
  9972. <pre><code>^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
  9973. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
  9974. </code></pre>
  9975. <h5 id="the-presence-stream"><a class="header" href="#the-presence-stream">The <code>presence</code> stream</a></h5>
  9976. <p>The following endpoints should be routed directly to the worker configured as
  9977. the stream writer for the <code>presence</code> stream:</p>
  9978. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
  9979. </code></pre>
  9980. <h4 id="background-tasks"><a class="header" href="#background-tasks">Background tasks</a></h4>
  9981. <p>There is also support for moving background tasks to a separate
  9982. worker. Background tasks are run periodically or started via replication. Exactly
  9983. which tasks are configured to run depends on your Synapse configuration (e.g. if
  9984. stats is enabled). This worker doesn't handle any REST endpoints itself.</p>
  9985. <p>To enable this, the worker must have a <code>worker_name</code> and can be configured to run
  9986. background tasks. For example, to move background tasks to a dedicated worker,
  9987. the shared configuration would include:</p>
  9988. <pre><code class="language-yaml">run_background_tasks_on: background_worker
  9989. </code></pre>
  9990. <p>You might also wish to investigate the <code>update_user_directory_from_worker</code> and
  9991. <code>media_instance_running_background_jobs</code> settings.</p>
  9992. <p>An example for a dedicated background worker instance:</p>
  9993. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  9994. worker_name: background_worker
  9995. # The replication listener on the main synapse process.
  9996. worker_replication_host: 127.0.0.1
  9997. worker_replication_http_port: 9093
  9998. worker_log_config: /etc/matrix-synapse/background-worker-log.yaml
  9999. </code></pre>
  10000. <h4 id="updating-the-user-directory"><a class="header" href="#updating-the-user-directory">Updating the User Directory</a></h4>
  10001. <p>You can designate one generic worker to update the user directory.</p>
  10002. <p>Specify its name in the shared configuration as follows:</p>
  10003. <pre><code class="language-yaml">update_user_directory_from_worker: worker_name
  10004. </code></pre>
  10005. <p>This work cannot be load-balanced; please ensure the main process is restarted
  10006. after setting this option in the shared configuration!</p>
  10007. <p>User directory updates allow REST endpoints matching the following regular
  10008. expressions to work:</p>
  10009. <pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  10010. </code></pre>
  10011. <p>The above endpoints can be routed to any worker, though you may choose to route
  10012. it to the chosen user directory worker.</p>
  10013. <p>This style of configuration supersedes the legacy <code>synapse.app.user_dir</code>
  10014. worker application type.</p>
  10015. <h4 id="notifying-application-services"><a class="header" href="#notifying-application-services">Notifying Application Services</a></h4>
  10016. <p>You can designate one generic worker to send output traffic to Application Services.
  10017. Doesn't handle any REST endpoints itself, but you should specify its name in the
  10018. shared configuration as follows:</p>
  10019. <pre><code class="language-yaml">notify_appservices_from_worker: worker_name
  10020. </code></pre>
  10021. <p>This work cannot be load-balanced; please ensure the main process is restarted
  10022. after setting this option in the shared configuration!</p>
  10023. <p>This style of configuration supersedes the legacy <code>synapse.app.appservice</code>
  10024. worker application type.</p>
  10025. <h3 id="synapseapppusher"><a class="header" href="#synapseapppusher"><code>synapse.app.pusher</code></a></h3>
  10026. <p>Handles sending push notifications to sygnal and email. Doesn't handle any
  10027. REST endpoints itself, but you should set <code>start_pushers: False</code> in the
  10028. shared configuration file to stop the main synapse sending push notifications.</p>
  10029. <p>To run multiple instances at once the <code>pusher_instances</code> option should list all
  10030. pusher instances by their worker name, e.g.:</p>
  10031. <pre><code class="language-yaml">pusher_instances:
  10032. - pusher_worker1
  10033. - pusher_worker2
  10034. </code></pre>
  10035. <h3 id="synapseappappservice"><a class="header" href="#synapseappappservice"><code>synapse.app.appservice</code></a></h3>
  10036. <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
  10037. <code>notify_appservices_from_worker</code> option instead.</a></p>
  10038. <p>Handles sending output traffic to Application Services. Doesn't handle any
  10039. REST endpoints itself, but you should set <code>notify_appservices: False</code> in the
  10040. shared configuration file to stop the main synapse sending appservice notifications.</p>
  10041. <p>Note this worker cannot be load-balanced: only one instance should be active.</p>
  10042. <h3 id="synapseappfederation_sender"><a class="header" href="#synapseappfederation_sender"><code>synapse.app.federation_sender</code></a></h3>
  10043. <p>Handles sending federation traffic to other servers. Doesn't handle any
  10044. REST endpoints itself, but you should set <code>send_federation: False</code> in the
  10045. shared configuration file to stop the main synapse sending this traffic.</p>
  10046. <p>If running multiple federation senders then you must list each
  10047. instance in the <code>federation_sender_instances</code> option by their <code>worker_name</code>.
  10048. All instances must be stopped and started when adding or removing instances.
  10049. For example:</p>
  10050. <pre><code class="language-yaml">federation_sender_instances:
  10051. - federation_sender1
  10052. - federation_sender2
  10053. </code></pre>
  10054. <h3 id="synapseappmedia_repository"><a class="header" href="#synapseappmedia_repository"><code>synapse.app.media_repository</code></a></h3>
  10055. <p>Handles the media repository. It can handle all endpoints starting with:</p>
  10056. <pre><code>/_matrix/media/
  10057. </code></pre>
  10058. <p>... and the following regular expressions matching media-specific administration APIs:</p>
  10059. <pre><code>^/_synapse/admin/v1/purge_media_cache$
  10060. ^/_synapse/admin/v1/room/.*/media.*$
  10061. ^/_synapse/admin/v1/user/.*/media.*$
  10062. ^/_synapse/admin/v1/media/.*$
  10063. ^/_synapse/admin/v1/quarantine_media/.*$
  10064. ^/_synapse/admin/v1/users/.*/media$
  10065. </code></pre>
  10066. <p>You should also set <code>enable_media_repo: False</code> in the shared configuration
  10067. file to stop the main synapse running background jobs related to managing the
  10068. media repository. Note that doing so will prevent the main process from being
  10069. able to handle the above endpoints.</p>
  10070. <p>In the <code>media_repository</code> worker configuration file, configure the
  10071. <a href="usage/configuration/config_documentation.html#listeners">HTTP listener</a> to
  10072. expose the <code>media</code> resource. For example:</p>
  10073. <pre><code class="language-yaml">worker_app: synapse.app.media_repository
  10074. worker_name: media_worker
  10075. # The replication listener on the main synapse process.
  10076. worker_replication_host: 127.0.0.1
  10077. worker_replication_http_port: 9093
  10078. worker_listeners:
  10079. - type: http
  10080. port: 8085
  10081. resources:
  10082. - names: [media]
  10083. worker_log_config: /etc/matrix-synapse/media-worker-log.yaml
  10084. </code></pre>
  10085. <p>Note that if running multiple media repositories they must be on the same server
  10086. and you must configure a single instance to run the background tasks, e.g.:</p>
  10087. <pre><code class="language-yaml">media_instance_running_background_jobs: &quot;media-repository-1&quot;
  10088. </code></pre>
  10089. <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>
  10090. <h3 id="synapseappuser_dir"><a class="header" href="#synapseappuser_dir"><code>synapse.app.user_dir</code></a></h3>
  10091. <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
  10092. <code>update_user_directory_from_worker</code> option instead.</a></p>
  10093. <p>Handles searches in the user directory. It can handle REST endpoints matching
  10094. the following regular expressions:</p>
  10095. <pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  10096. </code></pre>
  10097. <p>When using this worker you must also set <code>update_user_directory: false</code> in the
  10098. shared configuration file to stop the main synapse running background
  10099. jobs related to updating the user directory.</p>
  10100. <p>Above endpoint is not <em>required</em> to be routed to this worker. By default,
  10101. <code>update_user_directory</code> is set to <code>true</code>, which means the main process
  10102. will handle updates. All workers configured with <code>client</code> can handle the above
  10103. endpoint as long as either this worker or the main process are configured to
  10104. handle it, and are online.</p>
  10105. <p>If <code>update_user_directory</code> is set to <code>false</code>, and this worker is not running,
  10106. the above endpoint may give outdated results.</p>
  10107. <h3 id="historical-apps"><a class="header" href="#historical-apps">Historical apps</a></h3>
  10108. <p>The following used to be separate worker application types, but are now
  10109. equivalent to <code>synapse.app.generic_worker</code>:</p>
  10110. <ul>
  10111. <li><code>synapse.app.client_reader</code></li>
  10112. <li><code>synapse.app.event_creator</code></li>
  10113. <li><code>synapse.app.federation_reader</code></li>
  10114. <li><code>synapse.app.frontend_proxy</code></li>
  10115. <li><code>synapse.app.synchrotron</code></li>
  10116. </ul>
  10117. <h2 id="migration-from-old-config"><a class="header" href="#migration-from-old-config">Migration from old config</a></h2>
  10118. <p>A main change that has occurred is the merging of worker apps into
  10119. <code>synapse.app.generic_worker</code>. This change is backwards compatible and so no
  10120. changes to the config are required.</p>
  10121. <p>To migrate apps to use <code>synapse.app.generic_worker</code> simply update the
  10122. <code>worker_app</code> option in the worker configs, and where worker are started (e.g.
  10123. in systemd service files, but not required for synctl).</p>
  10124. <h2 id="architectural-diagram"><a class="header" href="#architectural-diagram">Architectural diagram</a></h2>
  10125. <p>The following shows an example setup using Redis and a reverse proxy:</p>
  10126. <pre><code> Clients &amp; Federation
  10127. |
  10128. v
  10129. +-----------+
  10130. | |
  10131. | Reverse |
  10132. | Proxy |
  10133. | |
  10134. +-----------+
  10135. | | |
  10136. | | | HTTP requests
  10137. +-------------------+ | +-----------+
  10138. | +---+ |
  10139. | | |
  10140. v v v
  10141. +--------------+ +--------------+ +--------------+ +--------------+
  10142. | Main | | Generic | | Generic | | Event |
  10143. | Process | | Worker 1 | | Worker 2 | | Persister |
  10144. +--------------+ +--------------+ +--------------+ +--------------+
  10145. ^ ^ | ^ | | ^ | | ^ ^
  10146. | | | | | | | | | | |
  10147. | | | | | HTTP | | | | | |
  10148. | +----------+&lt;--|---|---------+&lt;--|---|---------+ | |
  10149. | | +-------------|--&gt;+-------------+ |
  10150. | | | |
  10151. | | | |
  10152. v v v v
  10153. ======================================================================
  10154. Redis pub/sub channel
  10155. </code></pre>
  10156. <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>
  10157. <p>If you want to use <code>synctl</code> to manage your synapse processes, you will need to
  10158. create an an additional configuration file for the main synapse process. That
  10159. configuration should look like this:</p>
  10160. <pre><code class="language-yaml">worker_app: synapse.app.homeserver
  10161. </code></pre>
  10162. <p>Additionally, each worker app must be configured with the name of a &quot;pid file&quot;,
  10163. to which it will write its process ID when it starts. For example, for a
  10164. synchrotron, you might write:</p>
  10165. <pre><code class="language-yaml">worker_pid_file: /home/matrix/synapse/worker1.pid
  10166. </code></pre>
  10167. <p>Finally, to actually run your worker-based synapse, you must pass synctl the <code>-a</code>
  10168. commandline option to tell it to operate on all the worker configurations found
  10169. in the given directory, e.g.:</p>
  10170. <pre><code class="language-sh">synctl -a $CONFIG/workers start
  10171. </code></pre>
  10172. <p>Currently one should always restart all workers when restarting or upgrading
  10173. synapse, unless you explicitly know it's safe not to. For instance, restarting
  10174. synapse without restarting all the synchrotrons may result in broken typing
  10175. notifications.</p>
  10176. <p>To manipulate a specific worker, you pass the -w option to synctl:</p>
  10177. <pre><code class="language-sh">synctl -w $CONFIG/workers/worker1.yaml restart
  10178. </code></pre>
  10179. <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>
  10180. <p>This is a setup for managing synapse with systemd, including support for
  10181. managing workers. It provides a <code>matrix-synapse</code> service for the master, as
  10182. well as a <code>matrix-synapse-worker@</code> service template for any workers you
  10183. require. Additionally, to group the required services, it sets up a
  10184. <code>matrix-synapse.target</code>.</p>
  10185. <p>See the folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/system/">system</a>
  10186. for the systemd unit files.</p>
  10187. <p>The folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/workers/">workers</a>
  10188. contains an example configuration for the <code>generic_worker</code> worker.</p>
  10189. <h2 id="synapse-configuration-files"><a class="header" href="#synapse-configuration-files">Synapse configuration files</a></h2>
  10190. <p>See <a href="systemd-with-workers/../workers.html">the worker documentation</a> for information on how to set up the
  10191. configuration files and reverse-proxy correctly.
  10192. Below is a sample <code>generic_worker</code> worker configuration file.</p>
  10193. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  10194. worker_name: generic_worker1
  10195. # The replication listener on the main synapse process.
  10196. worker_replication_host: 127.0.0.1
  10197. worker_replication_http_port: 9093
  10198. worker_main_http_uri: http://localhost:8008/
  10199. worker_listeners:
  10200. - type: http
  10201. port: 8083
  10202. resources:
  10203. - names: [client, federation]
  10204. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  10205. </code></pre>
  10206. <p>Systemd manages daemonization itself, so ensure that none of the configuration
  10207. files set either <code>daemonize</code> or <code>worker_daemonize</code>.</p>
  10208. <p>The config files of all workers are expected to be located in
  10209. <code>/etc/matrix-synapse/workers</code>. If you want to use a different location, edit
  10210. the provided <code>*.service</code> files accordingly.</p>
  10211. <p>There is no need for a separate configuration file for the master process.</p>
  10212. <h2 id="set-up"><a class="header" href="#set-up">Set up</a></h2>
  10213. <ol>
  10214. <li>Adjust synapse configuration files as above.</li>
  10215. <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>
  10216. to <code>/etc/systemd/system</code>.</li>
  10217. <li>Run <code>systemctl daemon-reload</code> to tell systemd to load the new unit files.</li>
  10218. <li>Run <code>systemctl enable matrix-synapse.service</code>. This will configure the
  10219. synapse master process to be started as part of the <code>matrix-synapse.target</code>
  10220. target.</li>
  10221. <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
  10222. should be a corresponding configuration file.
  10223. <code>/etc/matrix-synapse/workers/&lt;worker_name&gt;.yaml</code>.</li>
  10224. <li>Start all the synapse processes with <code>systemctl start matrix-synapse.target</code>.</li>
  10225. <li>Tell systemd to start synapse on boot with <code>systemctl enable matrix-synapse.target</code>.</li>
  10226. </ol>
  10227. <h2 id="usage"><a class="header" href="#usage">Usage</a></h2>
  10228. <p>Once the services are correctly set up, you can use the following commands
  10229. to manage your synapse installation:</p>
  10230. <pre><code class="language-sh"># Restart Synapse master and all workers
  10231. systemctl restart matrix-synapse.target
  10232. # Stop Synapse and all workers
  10233. systemctl stop matrix-synapse.target
  10234. # Restart the master alone
  10235. systemctl start matrix-synapse.service
  10236. # Restart a specific worker (eg. generic_worker); the master is
  10237. # unaffected by this.
  10238. systemctl restart matrix-synapse-worker@generic_worker.service
  10239. # Add a new worker (assuming all configs are set up already)
  10240. systemctl enable matrix-synapse-worker@federation_writer.service
  10241. systemctl restart matrix-synapse.target
  10242. </code></pre>
  10243. <h2 id="hardening"><a class="header" href="#hardening">Hardening</a></h2>
  10244. <p><strong>Optional:</strong> If further hardening is desired, the file
  10245. <code>override-hardened.conf</code> may be copied from
  10246. <a href="https://github.com/matrix-org/synapse/tree/develop/contrib/systemd/">contrib/systemd/override-hardened.conf</a>
  10247. in this repository to the location
  10248. <code>/etc/systemd/system/matrix-synapse.service.d/override-hardened.conf</code> (the
  10249. directory may have to be created). It enables certain sandboxing features in
  10250. systemd to further secure the synapse service. You may read the comments to
  10251. understand what the override file is doing. The same file will need to be copied to
  10252. <code>/etc/systemd/system/matrix-synapse-worker@.service.d/override-hardened-worker.conf</code>
  10253. (this directory may also have to be created) in order to apply the same
  10254. hardening options to any worker processes.</p>
  10255. <p>Once these files have been copied to their appropriate locations, simply reload
  10256. systemd's manager config files and restart all Synapse services to apply the hardening options. They will automatically
  10257. be applied at every restart as long as the override files are present at the
  10258. specified locations.</p>
  10259. <pre><code class="language-sh">systemctl daemon-reload
  10260. # Restart services
  10261. systemctl restart matrix-synapse.target
  10262. </code></pre>
  10263. <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
  10264. the changes being applied at a glance.</p>
  10265. <div style="break-before: page; page-break-before: always;"></div><h1 id="administration"><a class="header" href="#administration">Administration</a></h1>
  10266. <p>This section contains information on managing your Synapse homeserver. This includes:</p>
  10267. <ul>
  10268. <li>Managing users, rooms and media via the Admin API.</li>
  10269. <li>Setting up metrics and monitoring to give you insight into your homeserver's health.</li>
  10270. <li>Configuring structured logging.</li>
  10271. </ul>
  10272. <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>
  10273. <h2 id="authenticate-as-a-server-admin"><a class="header" href="#authenticate-as-a-server-admin">Authenticate as a server admin</a></h2>
  10274. <p>Many of the API calls in the admin api will require an <code>access_token</code> for a
  10275. server admin. (Note that a server admin is distinct from a room admin.)</p>
  10276. <p>An existing user can be marked as a server admin by updating the database directly.</p>
  10277. <p>Check your <a href="usage/administration/admin_api/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>
  10278. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  10279. </code></pre>
  10280. <p>A new server admin user can also be created using the <code>register_new_matrix_user</code>
  10281. command. This is a script that is distributed as part of synapse. It is possibly
  10282. already on your <code>$PATH</code> depending on how Synapse was installed.</p>
  10283. <p>Finding your user's <code>access_token</code> is client-dependent, but will usually be shown in the client's settings.</p>
  10284. <h2 id="making-an-admin-api-request"><a class="header" href="#making-an-admin-api-request">Making an Admin API request</a></h2>
  10285. <p>For security reasons, we <a href="usage/administration/admin_api/reverse_proxy.html#synapse-administration-endpoints">recommend</a>
  10286. that the Admin API (<code>/_synapse/admin/...</code>) should be hidden from public view using a
  10287. reverse proxy. This means you should typically query the Admin API from a terminal on
  10288. the machine which runs Synapse.</p>
  10289. <p>Once you have your <code>access_token</code>, you will need to authenticate each request to an Admin API endpoint by
  10290. providing the token as either a query parameter or a request header. To add it as a request header in cURL:</p>
  10291. <pre><code class="language-sh">curl --header &quot;Authorization: Bearer &lt;access_token&gt;&quot; &lt;the_rest_of_your_API_request&gt;
  10292. </code></pre>
  10293. <p>For example, suppose we want to
  10294. <a href="usage/administration/admin_api/user_admin_api.html#query-user-account">query the account</a> of the user
  10295. <code>@foo:bar.com</code>. We need an admin access token (e.g.
  10296. <code>syt_AjfVef2_L33JNpafeif_0feKJfeaf0CQpoZk</code>), and we need to know which port
  10297. Synapse's <a href="usage/administration/admin_api/config_documentation.html#listeners"><code>client</code> listener</a> is listening
  10298. on (e.g. <code>8008</code>). Then we can use the following command to request the account
  10299. information from the Admin API.</p>
  10300. <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
  10301. </code></pre>
  10302. <p>For more details on access tokens in Matrix, please refer to the complete
  10303. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#using-access-tokens">matrix spec documentation</a>.</p>
  10304. <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>
  10305. <p>This API allows a server administrator to manage the validity of an account. To
  10306. use it, you must enable the account validity feature (under
  10307. <code>account_validity</code>) in Synapse's configuration.</p>
  10308. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10309. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10310. <h2 id="renew-account"><a class="header" href="#renew-account">Renew account</a></h2>
  10311. <p>This API extends the validity of an account by as much time as configured in the
  10312. <code>period</code> parameter from the <code>account_validity</code> configuration.</p>
  10313. <p>The API is:</p>
  10314. <pre><code>POST /_synapse/admin/v1/account_validity/validity
  10315. </code></pre>
  10316. <p>with the following body:</p>
  10317. <pre><code class="language-json">{
  10318. &quot;user_id&quot;: &quot;&lt;user ID for the account to renew&gt;&quot;,
  10319. &quot;expiration_ts&quot;: 0,
  10320. &quot;enable_renewal_emails&quot;: true
  10321. }
  10322. </code></pre>
  10323. <p><code>expiration_ts</code> is an optional parameter and overrides the expiration date,
  10324. which otherwise defaults to now + validity period.</p>
  10325. <p><code>enable_renewal_emails</code> is also an optional parameter and enables/disables
  10326. sending renewal emails to the user. Defaults to true.</p>
  10327. <p>The API returns with the new expiration date for this account, as a timestamp in
  10328. milliseconds since epoch:</p>
  10329. <pre><code class="language-json">{
  10330. &quot;expiration_ts&quot;: 0
  10331. }
  10332. </code></pre>
  10333. <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>
  10334. <p>This API allows a server administrator to manage the background updates being
  10335. run against the database.</p>
  10336. <h2 id="status"><a class="header" href="#status">Status</a></h2>
  10337. <p>This API gets the current status of the background updates.</p>
  10338. <p>The API is:</p>
  10339. <pre><code>GET /_synapse/admin/v1/background_updates/status
  10340. </code></pre>
  10341. <p>Returning:</p>
  10342. <pre><code class="language-json">{
  10343. &quot;enabled&quot;: true,
  10344. &quot;current_updates&quot;: {
  10345. &quot;&lt;db_name&gt;&quot;: {
  10346. &quot;name&quot;: &quot;&lt;background_update_name&gt;&quot;,
  10347. &quot;total_item_count&quot;: 50,
  10348. &quot;total_duration_ms&quot;: 10000.0,
  10349. &quot;average_items_per_ms&quot;: 2.2,
  10350. },
  10351. }
  10352. }
  10353. </code></pre>
  10354. <p><code>enabled</code> whether the background updates are enabled or disabled.</p>
  10355. <p><code>db_name</code> the database name (usually Synapse is configured with a single database named 'master').</p>
  10356. <p>For each update:</p>
  10357. <p><code>name</code> the name of the update.
  10358. <code>total_item_count</code> total number of &quot;items&quot; processed (the meaning of 'items' depends on the update in question).
  10359. <code>total_duration_ms</code> how long the background process has been running, not including time spent sleeping.
  10360. <code>average_items_per_ms</code> how many items are processed per millisecond based on an exponential average.</p>
  10361. <h2 id="enabled"><a class="header" href="#enabled">Enabled</a></h2>
  10362. <p>This API allow pausing background updates.</p>
  10363. <p>Background updates should <em>not</em> be paused for significant periods of time, as
  10364. this can affect the performance of Synapse.</p>
  10365. <p><em>Note</em>: This won't persist over restarts.</p>
  10366. <p><em>Note</em>: This won't cancel any update query that is currently running. This is
  10367. usually fine since most queries are short lived, except for <code>CREATE INDEX</code>
  10368. background updates which won't be cancelled once started.</p>
  10369. <p>The API is:</p>
  10370. <pre><code>POST /_synapse/admin/v1/background_updates/enabled
  10371. </code></pre>
  10372. <p>with the following body:</p>
  10373. <pre><code class="language-json">{
  10374. &quot;enabled&quot;: false
  10375. }
  10376. </code></pre>
  10377. <p><code>enabled</code> sets whether the background updates are enabled or disabled.</p>
  10378. <p>The API returns the <code>enabled</code> param.</p>
  10379. <pre><code class="language-json">{
  10380. &quot;enabled&quot;: false
  10381. }
  10382. </code></pre>
  10383. <p>There is also a <code>GET</code> version which returns the <code>enabled</code> state.</p>
  10384. <h2 id="run"><a class="header" href="#run">Run</a></h2>
  10385. <p>This API schedules a specific background update to run. The job starts immediately after calling the API.</p>
  10386. <p>The API is:</p>
  10387. <pre><code>POST /_synapse/admin/v1/background_updates/start_job
  10388. </code></pre>
  10389. <p>with the following body:</p>
  10390. <pre><code class="language-json">{
  10391. &quot;job_name&quot;: &quot;populate_stats_process_rooms&quot;
  10392. }
  10393. </code></pre>
  10394. <p>The following JSON body parameters are available:</p>
  10395. <ul>
  10396. <li><code>job_name</code> - A string which job to run. Valid values are:
  10397. <ul>
  10398. <li><code>populate_stats_process_rooms</code> - Recalculate the stats for all rooms.</li>
  10399. <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>
  10400. </ul>
  10401. </li>
  10402. </ul>
  10403. <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>
  10404. <p>This API returns information about reported events.</p>
  10405. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10406. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10407. <p>The api is:</p>
  10408. <pre><code>GET /_synapse/admin/v1/event_reports?from=0&amp;limit=10
  10409. </code></pre>
  10410. <p>It returns a JSON body like the following:</p>
  10411. <pre><code class="language-json">{
  10412. &quot;event_reports&quot;: [
  10413. {
  10414. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  10415. &quot;id&quot;: 2,
  10416. &quot;reason&quot;: &quot;foo&quot;,
  10417. &quot;score&quot;: -100,
  10418. &quot;received_ts&quot;: 1570897107409,
  10419. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  10420. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  10421. &quot;name&quot;: &quot;Matrix HQ&quot;,
  10422. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  10423. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  10424. },
  10425. {
  10426. &quot;event_id&quot;: &quot;$3IcdZsDaN_En-S1DF4EMCy3v4gNRKeOJs8W5qTOKj4I&quot;,
  10427. &quot;id&quot;: 3,
  10428. &quot;reason&quot;: &quot;bar&quot;,
  10429. &quot;score&quot;: -100,
  10430. &quot;received_ts&quot;: 1598889612059,
  10431. &quot;canonical_alias&quot;: &quot;#alias2:matrix.org&quot;,
  10432. &quot;room_id&quot;: &quot;!eGvUQuTCkHGVwNMOjv:matrix.org&quot;,
  10433. &quot;name&quot;: &quot;Your room name here&quot;,
  10434. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  10435. &quot;user_id&quot;: &quot;@bar:matrix.org&quot;
  10436. }
  10437. ],
  10438. &quot;next_token&quot;: 2,
  10439. &quot;total&quot;: 4
  10440. }
  10441. </code></pre>
  10442. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again with <code>from</code>
  10443. set to the value of <code>next_token</code>. This will return a new page.</p>
  10444. <p>If the endpoint does not return a <code>next_token</code> then there are no more reports to
  10445. paginate through.</p>
  10446. <p><strong>URL parameters:</strong></p>
  10447. <ul>
  10448. <li><code>limit</code>: integer - Is optional but is used for pagination, denoting the maximum number
  10449. of items to return in this call. Defaults to <code>100</code>.</li>
  10450. <li><code>from</code>: integer - Is optional but used for pagination, denoting the offset in the
  10451. returned results. This should be treated as an opaque value and not explicitly set to
  10452. anything other than the return value of <code>next_token</code> from a previous call. Defaults to <code>0</code>.</li>
  10453. <li><code>dir</code>: string - Direction of event report order. Whether to fetch the most recent
  10454. first (<code>b</code>) or the oldest first (<code>f</code>). Defaults to <code>b</code>.</li>
  10455. <li><code>user_id</code>: string - Is optional and filters to only return users with user IDs that
  10456. contain this value. This is the user who reported the event and wrote the reason.</li>
  10457. <li><code>room_id</code>: string - Is optional and filters to only return rooms with room IDs that
  10458. contain this value.</li>
  10459. </ul>
  10460. <p><strong>Response</strong></p>
  10461. <p>The following fields are returned in the JSON response body:</p>
  10462. <ul>
  10463. <li><code>id</code>: integer - ID of event report.</li>
  10464. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  10465. report was sent.</li>
  10466. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  10467. <li><code>name</code>: string - The name of the room.</li>
  10468. <li><code>event_id</code>: string - The ID of the reported event.</li>
  10469. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  10470. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank or <code>null</code>.</li>
  10471. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  10472. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;. May be <code>null</code>.</li>
  10473. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  10474. was reported.</li>
  10475. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  10476. have a canonical alias set.</li>
  10477. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  10478. <li><code>total</code>: integer - Total number of event reports related to the query
  10479. (<code>user_id</code> and <code>room_id</code>).</li>
  10480. </ul>
  10481. <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>
  10482. <p>This API returns information about a specific event report.</p>
  10483. <p>The api is:</p>
  10484. <pre><code>GET /_synapse/admin/v1/event_reports/&lt;report_id&gt;
  10485. </code></pre>
  10486. <p>It returns a JSON body like the following:</p>
  10487. <pre><code class="language-json">{
  10488. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  10489. &quot;event_json&quot;: {
  10490. &quot;auth_events&quot;: [
  10491. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;,
  10492. &quot;$oggsNXxzPFRE3y53SUNd7nsj69-QzKv03a1RucHu-ws&quot;
  10493. ],
  10494. &quot;content&quot;: {
  10495. &quot;body&quot;: &quot;matrix.org: This Week in Matrix&quot;,
  10496. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  10497. &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;,
  10498. &quot;msgtype&quot;: &quot;m.notice&quot;
  10499. },
  10500. &quot;depth&quot;: 546,
  10501. &quot;hashes&quot;: {
  10502. &quot;sha256&quot;: &quot;xK1//xnmvHJIOvbgXlkI8eEqdvoMmihVDJ9J4SNlsAw&quot;
  10503. },
  10504. &quot;origin&quot;: &quot;matrix.org&quot;,
  10505. &quot;origin_server_ts&quot;: 1592291711430,
  10506. &quot;prev_events&quot;: [
  10507. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;
  10508. ],
  10509. &quot;prev_state&quot;: [],
  10510. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  10511. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  10512. &quot;signatures&quot;: {
  10513. &quot;matrix.org&quot;: {
  10514. &quot;ed25519:a_JaEG&quot;: &quot;cs+OUKW/iHx5pEidbWxh0UiNNHwe46Ai9LwNz+Ah16aWDNszVIe2gaAcVZfvNsBhakQTew51tlKmL2kspXk/Dg&quot;
  10515. }
  10516. },
  10517. &quot;type&quot;: &quot;m.room.message&quot;,
  10518. &quot;unsigned&quot;: {
  10519. &quot;age_ts&quot;: 1592291711430
  10520. }
  10521. },
  10522. &quot;id&quot;: &lt;report_id&gt;,
  10523. &quot;reason&quot;: &quot;foo&quot;,
  10524. &quot;score&quot;: -100,
  10525. &quot;received_ts&quot;: 1570897107409,
  10526. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  10527. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  10528. &quot;name&quot;: &quot;Matrix HQ&quot;,
  10529. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  10530. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  10531. }
  10532. </code></pre>
  10533. <p><strong>URL parameters:</strong></p>
  10534. <ul>
  10535. <li><code>report_id</code>: string - The ID of the event report.</li>
  10536. </ul>
  10537. <p><strong>Response</strong></p>
  10538. <p>The following fields are returned in the JSON response body:</p>
  10539. <ul>
  10540. <li><code>id</code>: integer - ID of event report.</li>
  10541. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  10542. report was sent.</li>
  10543. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  10544. <li><code>name</code>: string - The name of the room.</li>
  10545. <li><code>event_id</code>: string - The ID of the reported event.</li>
  10546. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  10547. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank.</li>
  10548. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  10549. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;.</li>
  10550. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  10551. was reported.</li>
  10552. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  10553. have a canonical alias set.</li>
  10554. <li><code>event_json</code>: object - Details of the original event that was reported.</li>
  10555. </ul>
  10556. <div style="break-before: page; page-break-before: always;"></div><h1 id="querying-media"><a class="header" href="#querying-media">Querying media</a></h1>
  10557. <p>These APIs allow extracting media information from the homeserver.</p>
  10558. <p>Details about the format of the <code>media_id</code> and storage of the media in the file system
  10559. are documented under <a href="admin_api/../media_repository.html">media repository</a>.</p>
  10560. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10561. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10562. <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>
  10563. <p>This API gets a list of known media in a room.
  10564. However, it only shows media from unencrypted events or rooms.</p>
  10565. <p>The API is:</p>
  10566. <pre><code>GET /_synapse/admin/v1/room/&lt;room_id&gt;/media
  10567. </code></pre>
  10568. <p>The API returns a JSON body like the following:</p>
  10569. <pre><code class="language-json">{
  10570. &quot;local&quot;: [
  10571. &quot;mxc://localhost/xwvutsrqponmlkjihgfedcba&quot;,
  10572. &quot;mxc://localhost/abcdefghijklmnopqrstuvwx&quot;
  10573. ],
  10574. &quot;remote&quot;: [
  10575. &quot;mxc://matrix.org/xwvutsrqponmlkjihgfedcba&quot;,
  10576. &quot;mxc://matrix.org/abcdefghijklmnopqrstuvwx&quot;
  10577. ]
  10578. }
  10579. </code></pre>
  10580. <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>
  10581. <p>Listing all media that has been uploaded by a local user can be achieved through
  10582. the use of the
  10583. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>
  10584. Admin API.</p>
  10585. <h1 id="quarantine-media"><a class="header" href="#quarantine-media">Quarantine media</a></h1>
  10586. <p>Quarantining media means that it is marked as inaccessible by users. It applies
  10587. to any local media, and any locally-cached copies of remote media.</p>
  10588. <p>The media file itself (and any thumbnails) is not deleted from the server.</p>
  10589. <h2 id="quarantining-media-by-id"><a class="header" href="#quarantining-media-by-id">Quarantining media by ID</a></h2>
  10590. <p>This API quarantines a single piece of local or remote media.</p>
  10591. <p>Request:</p>
  10592. <pre><code>POST /_synapse/admin/v1/media/quarantine/&lt;server_name&gt;/&lt;media_id&gt;
  10593. {}
  10594. </code></pre>
  10595. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  10596. form of <code>abcdefg12345...</code>.</p>
  10597. <p>Response:</p>
  10598. <pre><code class="language-json">{}
  10599. </code></pre>
  10600. <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>
  10601. <p>This API removes a single piece of local or remote media from quarantine.</p>
  10602. <p>Request:</p>
  10603. <pre><code>POST /_synapse/admin/v1/media/unquarantine/&lt;server_name&gt;/&lt;media_id&gt;
  10604. {}
  10605. </code></pre>
  10606. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  10607. form of <code>abcdefg12345...</code>.</p>
  10608. <p>Response:</p>
  10609. <pre><code class="language-json">{}
  10610. </code></pre>
  10611. <h2 id="quarantining-media-in-a-room"><a class="header" href="#quarantining-media-in-a-room">Quarantining media in a room</a></h2>
  10612. <p>This API quarantines all local and remote media in a room.</p>
  10613. <p>Request:</p>
  10614. <pre><code>POST /_synapse/admin/v1/room/&lt;room_id&gt;/media/quarantine
  10615. {}
  10616. </code></pre>
  10617. <p>Where <code>room_id</code> is in the form of <code>!roomid12345:example.org</code>.</p>
  10618. <p>Response:</p>
  10619. <pre><code class="language-json">{
  10620. &quot;num_quarantined&quot;: 10
  10621. }
  10622. </code></pre>
  10623. <p>The following fields are returned in the JSON response body:</p>
  10624. <ul>
  10625. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  10626. </ul>
  10627. <p>Note that there is a legacy endpoint, <code>POST /_synapse/admin/v1/quarantine_media/&lt;room_id&gt;</code>, that operates the same.
  10628. However, it is deprecated and may be removed in a future release.</p>
  10629. <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>
  10630. <p>This API quarantines all <em>local</em> media that a <em>local</em> user has uploaded. That is to say, if
  10631. you would like to quarantine media uploaded by a user on a remote homeserver, you should
  10632. instead use one of the other APIs.</p>
  10633. <p>Request:</p>
  10634. <pre><code>POST /_synapse/admin/v1/user/&lt;user_id&gt;/media/quarantine
  10635. {}
  10636. </code></pre>
  10637. <p>URL Parameters</p>
  10638. <ul>
  10639. <li><code>user_id</code>: string - User ID in the form of <code>@bob:example.org</code></li>
  10640. </ul>
  10641. <p>Response:</p>
  10642. <pre><code class="language-json">{
  10643. &quot;num_quarantined&quot;: 10
  10644. }
  10645. </code></pre>
  10646. <p>The following fields are returned in the JSON response body:</p>
  10647. <ul>
  10648. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  10649. </ul>
  10650. <h2 id="protecting-media-from-being-quarantined"><a class="header" href="#protecting-media-from-being-quarantined">Protecting media from being quarantined</a></h2>
  10651. <p>This API protects a single piece of local media from being quarantined using the
  10652. above APIs. This is useful for sticker packs and other shared media which you do
  10653. not want to get quarantined, especially when
  10654. <a href="admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantining media in a room</a>.</p>
  10655. <p>Request:</p>
  10656. <pre><code>POST /_synapse/admin/v1/media/protect/&lt;media_id&gt;
  10657. {}
  10658. </code></pre>
  10659. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  10660. <p>Response:</p>
  10661. <pre><code class="language-json">{}
  10662. </code></pre>
  10663. <h2 id="unprotecting-media-from-being-quarantined"><a class="header" href="#unprotecting-media-from-being-quarantined">Unprotecting media from being quarantined</a></h2>
  10664. <p>This API reverts the protection of a media.</p>
  10665. <p>Request:</p>
  10666. <pre><code>POST /_synapse/admin/v1/media/unprotect/&lt;media_id&gt;
  10667. {}
  10668. </code></pre>
  10669. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  10670. <p>Response:</p>
  10671. <pre><code class="language-json">{}
  10672. </code></pre>
  10673. <h1 id="delete-local-media"><a class="header" href="#delete-local-media">Delete local media</a></h1>
  10674. <p>This API deletes the <em>local</em> media from the disk of your own server.
  10675. This includes any local thumbnails and copies of media downloaded from
  10676. remote homeservers.
  10677. This API will not affect media that has been uploaded to external
  10678. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).
  10679. See also <a href="admin_api/media_admin_api.html#purge-remote-media-api">Purge Remote Media API</a>.</p>
  10680. <h2 id="delete-a-specific-local-media"><a class="header" href="#delete-a-specific-local-media">Delete a specific local media</a></h2>
  10681. <p>Delete a specific <code>media_id</code>.</p>
  10682. <p>Request:</p>
  10683. <pre><code>DELETE /_synapse/admin/v1/media/&lt;server_name&gt;/&lt;media_id&gt;
  10684. {}
  10685. </code></pre>
  10686. <p>URL Parameters</p>
  10687. <ul>
  10688. <li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>)</li>
  10689. <li><code>media_id</code>: string - The ID of the media (e.g <code>abcdefghijklmnopqrstuvwx</code>)</li>
  10690. </ul>
  10691. <p>Response:</p>
  10692. <pre><code class="language-json">{
  10693. &quot;deleted_media&quot;: [
  10694. &quot;abcdefghijklmnopqrstuvwx&quot;
  10695. ],
  10696. &quot;total&quot;: 1
  10697. }
  10698. </code></pre>
  10699. <p>The following fields are returned in the JSON response body:</p>
  10700. <ul>
  10701. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  10702. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  10703. </ul>
  10704. <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>
  10705. <p>Request:</p>
  10706. <pre><code>POST /_synapse/admin/v1/media/&lt;server_name&gt;/delete?before_ts=&lt;before_ts&gt;
  10707. {}
  10708. </code></pre>
  10709. <p>URL Parameters</p>
  10710. <ul>
  10711. <li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>).</li>
  10712. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  10713. Files that were last used before this timestamp will be deleted. It is the timestamp of
  10714. last access, not the timestamp when the file was created.</li>
  10715. <li><code>size_gt</code>: Optional - string representing a positive integer - Size of the media in bytes.
  10716. Files that are larger will be deleted. Defaults to <code>0</code>.</li>
  10717. <li><code>keep_profiles</code>: Optional - string representing a boolean - Switch to also delete files
  10718. that are still used in image data (e.g user profile, room avatar).
  10719. If <code>false</code> these files will be deleted. Defaults to <code>true</code>.</li>
  10720. </ul>
  10721. <p>Response:</p>
  10722. <pre><code class="language-json">{
  10723. &quot;deleted_media&quot;: [
  10724. &quot;abcdefghijklmnopqrstuvwx&quot;,
  10725. &quot;abcdefghijklmnopqrstuvwz&quot;
  10726. ],
  10727. &quot;total&quot;: 2
  10728. }
  10729. </code></pre>
  10730. <p>The following fields are returned in the JSON response body:</p>
  10731. <ul>
  10732. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  10733. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  10734. </ul>
  10735. <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>
  10736. <p>You can find details of how to delete multiple media uploaded by a user in
  10737. <a href="admin_api/user_admin_api.html#delete-media-uploaded-by-a-user">User Admin API</a>.</p>
  10738. <h1 id="purge-remote-media-api"><a class="header" href="#purge-remote-media-api">Purge Remote Media API</a></h1>
  10739. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  10740. <p>The API is:</p>
  10741. <pre><code>POST /_synapse/admin/v1/purge_media_cache?before_ts=&lt;unix_timestamp_in_ms&gt;
  10742. {}
  10743. </code></pre>
  10744. <p>URL Parameters</p>
  10745. <ul>
  10746. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  10747. All cached media that was last accessed before this timestamp will be removed.</li>
  10748. </ul>
  10749. <p>Response:</p>
  10750. <pre><code class="language-json">{
  10751. &quot;deleted&quot;: 10
  10752. }
  10753. </code></pre>
  10754. <p>The following fields are returned in the JSON response body:</p>
  10755. <ul>
  10756. <li><code>deleted</code>: integer - The number of media items successfully deleted</li>
  10757. </ul>
  10758. <p>If the user re-requests purged remote media, synapse will re-request the media
  10759. from the originating server.</p>
  10760. <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>
  10761. <p>The purge history API allows server admins to purge historic events from their
  10762. database, reclaiming disk space.</p>
  10763. <p>Depending on the amount of history being purged a call to the API may take
  10764. several minutes or longer. During this period users will not be able to
  10765. paginate further back in the room from the point being purged from.</p>
  10766. <p>Note that Synapse requires at least one message in each room, so it will never
  10767. delete the last message in a room.</p>
  10768. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10769. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10770. <p>The API is:</p>
  10771. <pre><code>POST /_synapse/admin/v1/purge_history/&lt;room_id&gt;[/&lt;event_id&gt;]
  10772. </code></pre>
  10773. <p>By default, events sent by local users are not deleted, as they may represent
  10774. the only copies of this content in existence. (Events sent by remote users are
  10775. deleted.)</p>
  10776. <p>Room state data (such as joins, leaves, topic) is always preserved.</p>
  10777. <p>To delete local message events as well, set <code>delete_local_events</code> in the body:</p>
  10778. <pre><code class="language-json">{
  10779. &quot;delete_local_events&quot;: true
  10780. }
  10781. </code></pre>
  10782. <p>The caller must specify the point in the room to purge up to. This can be
  10783. specified by including an event_id in the URI, or by setting a
  10784. <code>purge_up_to_event_id</code> or <code>purge_up_to_ts</code> in the request body. If an event
  10785. id is given, that event (and others at the same graph depth) will be retained.
  10786. If <code>purge_up_to_ts</code> is given, it should be a timestamp since the unix epoch,
  10787. in milliseconds.</p>
  10788. <p>The API starts the purge running, and returns immediately with a JSON body with
  10789. a purge id:</p>
  10790. <pre><code class="language-json">{
  10791. &quot;purge_id&quot;: &quot;&lt;opaque id&gt;&quot;
  10792. }
  10793. </code></pre>
  10794. <h2 id="purge-status-query"><a class="header" href="#purge-status-query">Purge status query</a></h2>
  10795. <p>It is possible to poll for updates on recent purges with a second API;</p>
  10796. <pre><code>GET /_synapse/admin/v1/purge_history_status/&lt;purge_id&gt;
  10797. </code></pre>
  10798. <p>This API returns a JSON body like the following:</p>
  10799. <pre><code class="language-json">{
  10800. &quot;status&quot;: &quot;active&quot;
  10801. }
  10802. </code></pre>
  10803. <p>The status will be one of <code>active</code>, <code>complete</code>, or <code>failed</code>.</p>
  10804. <p>If <code>status</code> is <code>failed</code> there will be a string <code>error</code> with the error message.</p>
  10805. <h2 id="reclaim-disk-space-postgres"><a class="header" href="#reclaim-disk-space-postgres">Reclaim disk space (Postgres)</a></h2>
  10806. <p>To reclaim the disk space and return it to the operating system, you need to run
  10807. <code>VACUUM FULL;</code> on the database.</p>
  10808. <p><a href="https://www.postgresql.org/docs/current/sql-vacuum.html">https://www.postgresql.org/docs/current/sql-vacuum.html</a></p>
  10809. <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>
  10810. <p>This API allows for the creation of users in an administrative and
  10811. non-interactive way. This is generally used for bootstrapping a Synapse
  10812. instance with administrator accounts.</p>
  10813. <p>To authenticate yourself to the server, you will need both the shared secret
  10814. (<a href="admin_api/../usage/configuration/config_documentation.html#registration_shared_secret"><code>registration_shared_secret</code></a>
  10815. in the homeserver configuration), and a one-time nonce. If the registration
  10816. shared secret is not configured, this API is not enabled.</p>
  10817. <p>To fetch the nonce, you need to request one from the API:</p>
  10818. <pre><code>&gt; GET /_synapse/admin/v1/register
  10819. &lt; {&quot;nonce&quot;: &quot;thisisanonce&quot;}
  10820. </code></pre>
  10821. <p>Once you have the nonce, you can make a <code>POST</code> to the same URL with a JSON
  10822. body containing the nonce, username, password, whether they are an admin
  10823. (optional, False by default), and a HMAC digest of the content. Also you can
  10824. set the displayname (optional, <code>username</code> by default).</p>
  10825. <p>As an example:</p>
  10826. <pre><code>&gt; POST /_synapse/admin/v1/register
  10827. &gt; {
  10828. &quot;nonce&quot;: &quot;thisisanonce&quot;,
  10829. &quot;username&quot;: &quot;pepper_roni&quot;,
  10830. &quot;displayname&quot;: &quot;Pepper Roni&quot;,
  10831. &quot;password&quot;: &quot;pizza&quot;,
  10832. &quot;admin&quot;: true,
  10833. &quot;mac&quot;: &quot;mac_digest_here&quot;
  10834. }
  10835. &lt; {
  10836. &quot;access_token&quot;: &quot;token_here&quot;,
  10837. &quot;user_id&quot;: &quot;@pepper_roni:localhost&quot;,
  10838. &quot;home_server&quot;: &quot;test&quot;,
  10839. &quot;device_id&quot;: &quot;device_id_here&quot;
  10840. }
  10841. </code></pre>
  10842. <p>The MAC is the hex digest output of the HMAC-SHA1 algorithm, with the key being
  10843. the shared secret and the content being the nonce, user, password, either the
  10844. string &quot;admin&quot; or &quot;notadmin&quot;, and optionally the user_type
  10845. each separated by NULs.</p>
  10846. <p>Here is an easy way to generate the HMAC digest if you have Bash and OpenSSL:</p>
  10847. <pre><code class="language-bash"># Update these values and then paste this code block into a bash terminal
  10848. nonce='thisisanonce'
  10849. username='pepper_roni'
  10850. password='pizza'
  10851. admin='admin'
  10852. secret='shared_secret'
  10853. printf '%s\0%s\0%s\0%s' &quot;$nonce&quot; &quot;$username&quot; &quot;$password&quot; &quot;$admin&quot; |
  10854. openssl sha1 -hmac &quot;$secret&quot; |
  10855. awk '{print $2}'
  10856. </code></pre>
  10857. <p>For an example of generation in Python:</p>
  10858. <pre><code class="language-python">import hmac, hashlib
  10859. def generate_mac(nonce, user, password, admin=False, user_type=None):
  10860. mac = hmac.new(
  10861. key=shared_secret,
  10862. digestmod=hashlib.sha1,
  10863. )
  10864. mac.update(nonce.encode('utf8'))
  10865. mac.update(b&quot;\x00&quot;)
  10866. mac.update(user.encode('utf8'))
  10867. mac.update(b&quot;\x00&quot;)
  10868. mac.update(password.encode('utf8'))
  10869. mac.update(b&quot;\x00&quot;)
  10870. mac.update(b&quot;admin&quot; if admin else b&quot;notadmin&quot;)
  10871. if user_type:
  10872. mac.update(b&quot;\x00&quot;)
  10873. mac.update(user_type.encode('utf8'))
  10874. return mac.hexdigest()
  10875. </code></pre>
  10876. <div style="break-before: page; page-break-before: always;"></div><h1 id="registration-tokens"><a class="header" href="#registration-tokens">Registration Tokens</a></h1>
  10877. <p>This API allows you to manage tokens which can be used to authenticate
  10878. registration requests, as proposed in
  10879. <a href="https://github.com/matrix-org/matrix-doc/blob/main/proposals/3231-token-authenticated-registration.md">MSC3231</a>
  10880. and stabilised in version 1.2 of the Matrix specification.
  10881. To use it, you will need to enable the <code>registration_requires_token</code> config
  10882. option, and authenticate by providing an <code>access_token</code> for a server admin:
  10883. see <a href="usage/administration/admin_api/../admin_api">Admin API</a>.</p>
  10884. <h2 id="registration-token-objects"><a class="header" href="#registration-token-objects">Registration token objects</a></h2>
  10885. <p>Most endpoints make use of JSON objects that contain details about tokens.
  10886. These objects have the following fields:</p>
  10887. <ul>
  10888. <li><code>token</code>: The token which can be used to authenticate registration.</li>
  10889. <li><code>uses_allowed</code>: The number of times the token can be used to complete a
  10890. registration before it becomes invalid.</li>
  10891. <li><code>pending</code>: The number of pending uses the token has. When someone uses
  10892. the token to authenticate themselves, the pending counter is incremented
  10893. so that the token is not used more than the permitted number of times.
  10894. When the person completes registration the pending counter is decremented,
  10895. and the completed counter is incremented.</li>
  10896. <li><code>completed</code>: The number of times the token has been used to successfully
  10897. complete a registration.</li>
  10898. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  10899. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  10900. To convert this into a human-readable form you can remove the milliseconds
  10901. and use the <code>date</code> command. For example, <code>date -d '@1625394937'</code>.</li>
  10902. </ul>
  10903. <h2 id="list-all-tokens"><a class="header" href="#list-all-tokens">List all tokens</a></h2>
  10904. <p>Lists all tokens and details about them. If the request is successful, the top
  10905. level JSON object will have a <code>registration_tokens</code> key which is an array of
  10906. registration token objects.</p>
  10907. <pre><code>GET /_synapse/admin/v1/registration_tokens
  10908. </code></pre>
  10909. <p>Optional query parameters:</p>
  10910. <ul>
  10911. <li><code>valid</code>: <code>true</code> or <code>false</code>. If <code>true</code>, only valid tokens are returned.
  10912. If <code>false</code>, only tokens that have expired or have had all uses exhausted are
  10913. returned. If omitted, all tokens are returned regardless of validity.</li>
  10914. </ul>
  10915. <p>Example:</p>
  10916. <pre><code>GET /_synapse/admin/v1/registration_tokens
  10917. </code></pre>
  10918. <pre><code>200 OK
  10919. {
  10920. &quot;registration_tokens&quot;: [
  10921. {
  10922. &quot;token&quot;: &quot;abcd&quot;,
  10923. &quot;uses_allowed&quot;: 3,
  10924. &quot;pending&quot;: 0,
  10925. &quot;completed&quot;: 1,
  10926. &quot;expiry_time&quot;: null
  10927. },
  10928. {
  10929. &quot;token&quot;: &quot;pqrs&quot;,
  10930. &quot;uses_allowed&quot;: 2,
  10931. &quot;pending&quot;: 1,
  10932. &quot;completed&quot;: 1,
  10933. &quot;expiry_time&quot;: null
  10934. },
  10935. {
  10936. &quot;token&quot;: &quot;wxyz&quot;,
  10937. &quot;uses_allowed&quot;: null,
  10938. &quot;pending&quot;: 0,
  10939. &quot;completed&quot;: 9,
  10940. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  10941. }
  10942. ]
  10943. }
  10944. </code></pre>
  10945. <p>Example using the <code>valid</code> query parameter:</p>
  10946. <pre><code>GET /_synapse/admin/v1/registration_tokens?valid=false
  10947. </code></pre>
  10948. <pre><code>200 OK
  10949. {
  10950. &quot;registration_tokens&quot;: [
  10951. {
  10952. &quot;token&quot;: &quot;pqrs&quot;,
  10953. &quot;uses_allowed&quot;: 2,
  10954. &quot;pending&quot;: 1,
  10955. &quot;completed&quot;: 1,
  10956. &quot;expiry_time&quot;: null
  10957. },
  10958. {
  10959. &quot;token&quot;: &quot;wxyz&quot;,
  10960. &quot;uses_allowed&quot;: null,
  10961. &quot;pending&quot;: 0,
  10962. &quot;completed&quot;: 9,
  10963. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  10964. }
  10965. ]
  10966. }
  10967. </code></pre>
  10968. <h2 id="get-one-token"><a class="header" href="#get-one-token">Get one token</a></h2>
  10969. <p>Get details about a single token. If the request is successful, the response
  10970. body will be a registration token object.</p>
  10971. <pre><code>GET /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  10972. </code></pre>
  10973. <p>Path parameters:</p>
  10974. <ul>
  10975. <li><code>token</code>: The registration token to return details of.</li>
  10976. </ul>
  10977. <p>Example:</p>
  10978. <pre><code>GET /_synapse/admin/v1/registration_tokens/abcd
  10979. </code></pre>
  10980. <pre><code>200 OK
  10981. {
  10982. &quot;token&quot;: &quot;abcd&quot;,
  10983. &quot;uses_allowed&quot;: 3,
  10984. &quot;pending&quot;: 0,
  10985. &quot;completed&quot;: 1,
  10986. &quot;expiry_time&quot;: null
  10987. }
  10988. </code></pre>
  10989. <h2 id="create-token"><a class="header" href="#create-token">Create token</a></h2>
  10990. <p>Create a new registration token. If the request is successful, the newly created
  10991. token will be returned as a registration token object in the response body.</p>
  10992. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  10993. </code></pre>
  10994. <p>The request body must be a JSON object and can contain the following fields:</p>
  10995. <ul>
  10996. <li><code>token</code>: The registration token. A string of no more than 64 characters that
  10997. consists only of characters matched by the regex <code>[A-Za-z0-9._~-]</code>.
  10998. Default: randomly generated.</li>
  10999. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  11000. a registration before it becomes invalid.
  11001. Default: <code>null</code> (unlimited uses).</li>
  11002. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  11003. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  11004. You could use, for example, <code>date '+%s000' -d 'tomorrow'</code>.
  11005. Default: <code>null</code> (token does not expire).</li>
  11006. <li><code>length</code>: The length of the token randomly generated if <code>token</code> is not
  11007. specified. Must be between 1 and 64 inclusive. Default: <code>16</code>.</li>
  11008. </ul>
  11009. <p>If a field is omitted the default is used.</p>
  11010. <p>Example using defaults:</p>
  11011. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  11012. {}
  11013. </code></pre>
  11014. <pre><code>200 OK
  11015. {
  11016. &quot;token&quot;: &quot;0M-9jbkf2t_Tgiw1&quot;,
  11017. &quot;uses_allowed&quot;: null,
  11018. &quot;pending&quot;: 0,
  11019. &quot;completed&quot;: 0,
  11020. &quot;expiry_time&quot;: null
  11021. }
  11022. </code></pre>
  11023. <p>Example specifying some fields:</p>
  11024. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  11025. {
  11026. &quot;token&quot;: &quot;defg&quot;,
  11027. &quot;uses_allowed&quot;: 1
  11028. }
  11029. </code></pre>
  11030. <pre><code>200 OK
  11031. {
  11032. &quot;token&quot;: &quot;defg&quot;,
  11033. &quot;uses_allowed&quot;: 1,
  11034. &quot;pending&quot;: 0,
  11035. &quot;completed&quot;: 0,
  11036. &quot;expiry_time&quot;: null
  11037. }
  11038. </code></pre>
  11039. <h2 id="update-token"><a class="header" href="#update-token">Update token</a></h2>
  11040. <p>Update the number of allowed uses or expiry time of a token. If the request is
  11041. successful, the updated token will be returned as a registration token object
  11042. in the response body.</p>
  11043. <pre><code>PUT /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  11044. </code></pre>
  11045. <p>Path parameters:</p>
  11046. <ul>
  11047. <li><code>token</code>: The registration token to update.</li>
  11048. </ul>
  11049. <p>The request body must be a JSON object and can contain the following fields:</p>
  11050. <ul>
  11051. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  11052. a registration before it becomes invalid. By setting <code>uses_allowed</code> to <code>0</code>
  11053. the token can be easily made invalid without deleting it.
  11054. If <code>null</code> the token will have an unlimited number of uses.</li>
  11055. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  11056. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  11057. If <code>null</code> the token will not expire.</li>
  11058. </ul>
  11059. <p>If a field is omitted its value is not modified.</p>
  11060. <p>Example:</p>
  11061. <pre><code>PUT /_synapse/admin/v1/registration_tokens/defg
  11062. {
  11063. &quot;expiry_time&quot;: 4781243146000 // 2121-07-06 11:05:46 UTC
  11064. }
  11065. </code></pre>
  11066. <pre><code>200 OK
  11067. {
  11068. &quot;token&quot;: &quot;defg&quot;,
  11069. &quot;uses_allowed&quot;: 1,
  11070. &quot;pending&quot;: 0,
  11071. &quot;completed&quot;: 0,
  11072. &quot;expiry_time&quot;: 4781243146000
  11073. }
  11074. </code></pre>
  11075. <h2 id="delete-token"><a class="header" href="#delete-token">Delete token</a></h2>
  11076. <p>Delete a registration token. If the request is successful, the response body
  11077. will be an empty JSON object.</p>
  11078. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  11079. </code></pre>
  11080. <p>Path parameters:</p>
  11081. <ul>
  11082. <li><code>token</code>: The registration token to delete.</li>
  11083. </ul>
  11084. <p>Example:</p>
  11085. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/wxyz
  11086. </code></pre>
  11087. <pre><code>200 OK
  11088. {}
  11089. </code></pre>
  11090. <h2 id="errors"><a class="header" href="#errors">Errors</a></h2>
  11091. <p>If a request fails a &quot;standard error response&quot; will be returned as defined in
  11092. the <a href="https://matrix.org/docs/spec/client_server/r0.6.1#api-standards">Matrix Client-Server API specification</a>.</p>
  11093. <p>For example, if the token specified in a path parameter does not exist a
  11094. <code>404 Not Found</code> error will be returned.</p>
  11095. <pre><code>GET /_synapse/admin/v1/registration_tokens/1234
  11096. </code></pre>
  11097. <pre><code>404 Not Found
  11098. {
  11099. &quot;errcode&quot;: &quot;M_NOT_FOUND&quot;,
  11100. &quot;error&quot;: &quot;No such registration token: 1234&quot;
  11101. }
  11102. </code></pre>
  11103. <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>
  11104. <p>This API allows an administrator to join an user account with a given <code>user_id</code>
  11105. to a room with a given <code>room_id_or_alias</code>. You can only modify the membership of
  11106. local users. The server administrator must be in the room and have permission to
  11107. invite users.</p>
  11108. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11109. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  11110. <h2 id="parameters"><a class="header" href="#parameters">Parameters</a></h2>
  11111. <p>The following parameters are available:</p>
  11112. <ul>
  11113. <li><code>user_id</code> - Fully qualified user: for example, <code>@user:server.com</code>.</li>
  11114. <li><code>room_id_or_alias</code> - The room identifier or alias to join: for example,
  11115. <code>!636q39766251:server.com</code>.</li>
  11116. </ul>
  11117. <h2 id="usage-1"><a class="header" href="#usage-1">Usage</a></h2>
  11118. <pre><code>POST /_synapse/admin/v1/join/&lt;room_id_or_alias&gt;
  11119. {
  11120. &quot;user_id&quot;: &quot;@user:server.com&quot;
  11121. }
  11122. </code></pre>
  11123. <p>Response:</p>
  11124. <pre><code class="language-json">{
  11125. &quot;room_id&quot;: &quot;!636q39766251:server.com&quot;
  11126. }
  11127. </code></pre>
  11128. <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>
  11129. <p>The List Room admin API allows server admins to get a list of rooms on their
  11130. server. There are various parameters available that allow for filtering and
  11131. sorting the returned list. This API supports pagination.</p>
  11132. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11133. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  11134. <p><strong>Parameters</strong></p>
  11135. <p>The following query parameters are available:</p>
  11136. <ul>
  11137. <li>
  11138. <p><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</p>
  11139. </li>
  11140. <li>
  11141. <p><code>limit</code> - Maximum amount of rooms to return. Defaults to <code>100</code>.</p>
  11142. </li>
  11143. <li>
  11144. <p><code>order_by</code> - The method in which to sort the returned list of rooms. Valid values are:</p>
  11145. <ul>
  11146. <li><code>alphabetical</code> - Same as <code>name</code>. This is deprecated.</li>
  11147. <li><code>size</code> - Same as <code>joined_members</code>. This is deprecated.</li>
  11148. <li><code>name</code> - Rooms are ordered alphabetically by room name. This is the default.</li>
  11149. <li><code>canonical_alias</code> - Rooms are ordered alphabetically by main alias address of the room.</li>
  11150. <li><code>joined_members</code> - Rooms are ordered by the number of members. Largest to smallest.</li>
  11151. <li><code>joined_local_members</code> - Rooms are ordered by the number of local members. Largest to smallest.</li>
  11152. <li><code>version</code> - Rooms are ordered by room version. Largest to smallest.</li>
  11153. <li><code>creator</code> - Rooms are ordered alphabetically by creator of the room.</li>
  11154. <li><code>encryption</code> - Rooms are ordered alphabetically by the end-to-end encryption algorithm.</li>
  11155. <li><code>federatable</code> - Rooms are ordered by whether the room is federatable.</li>
  11156. <li><code>public</code> - Rooms are ordered by visibility in room list.</li>
  11157. <li><code>join_rules</code> - Rooms are ordered alphabetically by join rules of the room.</li>
  11158. <li><code>guest_access</code> - Rooms are ordered alphabetically by guest access option of the room.</li>
  11159. <li><code>history_visibility</code> - Rooms are ordered alphabetically by visibility of history of the room.</li>
  11160. <li><code>state_events</code> - Rooms are ordered by number of state events. Largest to smallest.</li>
  11161. </ul>
  11162. </li>
  11163. <li>
  11164. <p><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  11165. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  11166. </li>
  11167. <li>
  11168. <p><code>search_term</code> - Filter rooms by their room name, canonical alias and room id.
  11169. Specifically, rooms are selected if the search term is contained in</p>
  11170. <ul>
  11171. <li>the room's name,</li>
  11172. <li>the local part of the room's canonical alias, or</li>
  11173. <li>the complete (local and server part) room's id (case sensitive).</li>
  11174. </ul>
  11175. <p>Defaults to no filtering.</p>
  11176. </li>
  11177. </ul>
  11178. <p><strong>Response</strong></p>
  11179. <p>The following fields are possible in the JSON response body:</p>
  11180. <ul>
  11181. <li><code>rooms</code> - An array of objects, each containing information about a room.
  11182. <ul>
  11183. <li>Room objects contain the following fields:
  11184. <ul>
  11185. <li><code>room_id</code> - The ID of the room.</li>
  11186. <li><code>name</code> - The name of the room.</li>
  11187. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  11188. <li><code>joined_members</code> - How many users are currently in the room.</li>
  11189. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  11190. <li><code>version</code> - The version of the room as a string.</li>
  11191. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  11192. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  11193. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  11194. <li><code>public</code> - Whether the room is visible in room directory.</li>
  11195. <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>
  11196. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  11197. <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>
  11198. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  11199. <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>
  11200. </ul>
  11201. </li>
  11202. </ul>
  11203. </li>
  11204. <li><code>offset</code> - The current pagination offset in rooms. This parameter should be
  11205. used instead of <code>next_token</code> for room offset as <code>next_token</code> is
  11206. not intended to be parsed.</li>
  11207. <li><code>total_rooms</code> - The total number of rooms this query can return. Using this
  11208. and <code>offset</code>, you have enough information to know the current
  11209. progression through the list.</li>
  11210. <li><code>next_batch</code> - If this field is present, we know that there are potentially
  11211. more rooms on the server that did not all fit into this response.
  11212. We can use <code>next_batch</code> to get the &quot;next page&quot; of results. To do
  11213. so, simply repeat your request, setting the <code>from</code> parameter to
  11214. the value of <code>next_batch</code>.</li>
  11215. <li><code>prev_batch</code> - If this field is present, it is possible to paginate backwards.
  11216. Use <code>prev_batch</code> for the <code>from</code> value in the next request to
  11217. get the &quot;previous page&quot; of results.</li>
  11218. </ul>
  11219. <p>The API is:</p>
  11220. <p>A standard request with no filtering:</p>
  11221. <pre><code>GET /_synapse/admin/v1/rooms
  11222. </code></pre>
  11223. <p>A response body like the following is returned:</p>
  11224. <pre><code class="language-json">{
  11225. &quot;rooms&quot;: [
  11226. {
  11227. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  11228. &quot;name&quot;: &quot;Matrix HQ&quot;,
  11229. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  11230. &quot;joined_members&quot;: 8326,
  11231. &quot;joined_local_members&quot;: 2,
  11232. &quot;version&quot;: &quot;1&quot;,
  11233. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11234. &quot;encryption&quot;: null,
  11235. &quot;federatable&quot;: true,
  11236. &quot;public&quot;: true,
  11237. &quot;join_rules&quot;: &quot;invite&quot;,
  11238. &quot;guest_access&quot;: null,
  11239. &quot;history_visibility&quot;: &quot;shared&quot;,
  11240. &quot;state_events&quot;: 93534,
  11241. &quot;room_type&quot;: &quot;m.space&quot;
  11242. },
  11243. ... (8 hidden items) ...
  11244. {
  11245. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  11246. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  11247. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  11248. &quot;joined_members&quot;: 314,
  11249. &quot;joined_local_members&quot;: 20,
  11250. &quot;version&quot;: &quot;4&quot;,
  11251. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11252. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  11253. &quot;federatable&quot;: true,
  11254. &quot;public&quot;: false,
  11255. &quot;join_rules&quot;: &quot;invite&quot;,
  11256. &quot;guest_access&quot;: null,
  11257. &quot;history_visibility&quot;: &quot;shared&quot;,
  11258. &quot;state_events&quot;: 8345,
  11259. &quot;room_type&quot;: null
  11260. }
  11261. ],
  11262. &quot;offset&quot;: 0,
  11263. &quot;total_rooms&quot;: 10
  11264. }
  11265. </code></pre>
  11266. <p>Filtering by room name:</p>
  11267. <pre><code>GET /_synapse/admin/v1/rooms?search_term=TWIM
  11268. </code></pre>
  11269. <p>A response body like the following is returned:</p>
  11270. <pre><code class="language-json">{
  11271. &quot;rooms&quot;: [
  11272. {
  11273. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  11274. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  11275. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  11276. &quot;joined_members&quot;: 314,
  11277. &quot;joined_local_members&quot;: 20,
  11278. &quot;version&quot;: &quot;4&quot;,
  11279. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11280. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  11281. &quot;federatable&quot;: true,
  11282. &quot;public&quot;: false,
  11283. &quot;join_rules&quot;: &quot;invite&quot;,
  11284. &quot;guest_access&quot;: null,
  11285. &quot;history_visibility&quot;: &quot;shared&quot;,
  11286. &quot;state_events&quot;: 8,
  11287. &quot;room_type&quot;: null
  11288. }
  11289. ],
  11290. &quot;offset&quot;: 0,
  11291. &quot;total_rooms&quot;: 1
  11292. }
  11293. </code></pre>
  11294. <p>Paginating through a list of rooms:</p>
  11295. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size
  11296. </code></pre>
  11297. <p>A response body like the following is returned:</p>
  11298. <pre><code class="language-json">{
  11299. &quot;rooms&quot;: [
  11300. {
  11301. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  11302. &quot;name&quot;: &quot;Matrix HQ&quot;,
  11303. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  11304. &quot;joined_members&quot;: 8326,
  11305. &quot;joined_local_members&quot;: 2,
  11306. &quot;version&quot;: &quot;1&quot;,
  11307. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11308. &quot;encryption&quot;: null,
  11309. &quot;federatable&quot;: true,
  11310. &quot;public&quot;: true,
  11311. &quot;join_rules&quot;: &quot;invite&quot;,
  11312. &quot;guest_access&quot;: null,
  11313. &quot;history_visibility&quot;: &quot;shared&quot;,
  11314. &quot;state_events&quot;: 93534,
  11315. &quot;room_type&quot;: null
  11316. },
  11317. ... (98 hidden items) ...
  11318. {
  11319. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  11320. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  11321. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  11322. &quot;joined_members&quot;: 314,
  11323. &quot;joined_local_members&quot;: 20,
  11324. &quot;version&quot;: &quot;4&quot;,
  11325. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11326. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  11327. &quot;federatable&quot;: true,
  11328. &quot;public&quot;: false,
  11329. &quot;join_rules&quot;: &quot;invite&quot;,
  11330. &quot;guest_access&quot;: null,
  11331. &quot;history_visibility&quot;: &quot;shared&quot;,
  11332. &quot;state_events&quot;: 8345,
  11333. &quot;room_type&quot;: &quot;m.space&quot;
  11334. }
  11335. ],
  11336. &quot;offset&quot;: 0,
  11337. &quot;total_rooms&quot;: 150,
  11338. &quot;next_token&quot;: 100
  11339. }
  11340. </code></pre>
  11341. <p>The presence of the <code>next_token</code> parameter tells us that there are more rooms
  11342. than returned in this request, and we need to make another request to get them.
  11343. To get the next batch of room results, we repeat our request, setting the <code>from</code>
  11344. parameter to the value of <code>next_token</code>.</p>
  11345. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size&amp;from=100
  11346. </code></pre>
  11347. <p>A response body like the following is returned:</p>
  11348. <pre><code class="language-json">{
  11349. &quot;rooms&quot;: [
  11350. {
  11351. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  11352. &quot;name&quot;: &quot;Music Theory&quot;,
  11353. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  11354. &quot;joined_members&quot;: 127,
  11355. &quot;joined_local_members&quot;: 2,
  11356. &quot;version&quot;: &quot;1&quot;,
  11357. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11358. &quot;encryption&quot;: null,
  11359. &quot;federatable&quot;: true,
  11360. &quot;public&quot;: true,
  11361. &quot;join_rules&quot;: &quot;invite&quot;,
  11362. &quot;guest_access&quot;: null,
  11363. &quot;history_visibility&quot;: &quot;shared&quot;,
  11364. &quot;state_events&quot;: 93534,
  11365. &quot;room_type&quot;: &quot;m.space&quot;
  11366. },
  11367. ... (48 hidden items) ...
  11368. {
  11369. &quot;room_id&quot;: &quot;!twcBhHVdZlQWuuxBhN:termina.org.uk&quot;,
  11370. &quot;name&quot;: &quot;weechat-matrix&quot;,
  11371. &quot;canonical_alias&quot;: &quot;#weechat-matrix:termina.org.uk&quot;,
  11372. &quot;joined_members&quot;: 137,
  11373. &quot;joined_local_members&quot;: 20,
  11374. &quot;version&quot;: &quot;4&quot;,
  11375. &quot;creator&quot;: &quot;@foo:termina.org.uk&quot;,
  11376. &quot;encryption&quot;: null,
  11377. &quot;federatable&quot;: true,
  11378. &quot;public&quot;: true,
  11379. &quot;join_rules&quot;: &quot;invite&quot;,
  11380. &quot;guest_access&quot;: null,
  11381. &quot;history_visibility&quot;: &quot;shared&quot;,
  11382. &quot;state_events&quot;: 8345,
  11383. &quot;room_type&quot;: null
  11384. }
  11385. ],
  11386. &quot;offset&quot;: 100,
  11387. &quot;prev_batch&quot;: 0,
  11388. &quot;total_rooms&quot;: 150
  11389. }
  11390. </code></pre>
  11391. <p>Once the <code>next_token</code> parameter is no longer present, we know we've reached the
  11392. end of the list.</p>
  11393. <h1 id="room-details-api"><a class="header" href="#room-details-api">Room Details API</a></h1>
  11394. <p>The Room Details admin API allows server admins to get all details of a room.</p>
  11395. <p>The following fields are possible in the JSON response body:</p>
  11396. <ul>
  11397. <li><code>room_id</code> - The ID of the room.</li>
  11398. <li><code>name</code> - The name of the room.</li>
  11399. <li><code>topic</code> - The topic of the room.</li>
  11400. <li><code>avatar</code> - The <code>mxc</code> URI to the avatar of the room.</li>
  11401. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  11402. <li><code>joined_members</code> - How many users are currently in the room.</li>
  11403. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  11404. <li><code>joined_local_devices</code> - How many local devices are currently in the room.</li>
  11405. <li><code>version</code> - The version of the room as a string.</li>
  11406. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  11407. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  11408. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  11409. <li><code>public</code> - Whether the room is visible in room directory.</li>
  11410. <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>
  11411. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  11412. <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>
  11413. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  11414. <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.
  11415. If the room does not define a type, the value will be <code>null</code>.</li>
  11416. <li><code>forgotten</code> - Whether all local users have
  11417. <a href="https://spec.matrix.org/latest/client-server-api/#leaving-rooms">forgotten</a> the room.</li>
  11418. </ul>
  11419. <p>The API is:</p>
  11420. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;
  11421. </code></pre>
  11422. <p>A response body like the following is returned:</p>
  11423. <pre><code class="language-json">{
  11424. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  11425. &quot;name&quot;: &quot;Music Theory&quot;,
  11426. &quot;avatar&quot;: &quot;mxc://matrix.org/AQDaVFlbkQoErdOgqWRgiGSV&quot;,
  11427. &quot;topic&quot;: &quot;Theory, Composition, Notation, Analysis&quot;,
  11428. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  11429. &quot;joined_members&quot;: 127,
  11430. &quot;joined_local_members&quot;: 2,
  11431. &quot;joined_local_devices&quot;: 2,
  11432. &quot;version&quot;: &quot;1&quot;,
  11433. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11434. &quot;encryption&quot;: null,
  11435. &quot;federatable&quot;: true,
  11436. &quot;public&quot;: true,
  11437. &quot;join_rules&quot;: &quot;invite&quot;,
  11438. &quot;guest_access&quot;: null,
  11439. &quot;history_visibility&quot;: &quot;shared&quot;,
  11440. &quot;state_events&quot;: 93534,
  11441. &quot;room_type&quot;: &quot;m.space&quot;,
  11442. &quot;forgotten&quot;: false
  11443. }
  11444. </code></pre>
  11445. <p><em>Changed in Synapse 1.66:</em> Added the <code>forgotten</code> key to the response body.</p>
  11446. <h1 id="room-members-api"><a class="header" href="#room-members-api">Room Members API</a></h1>
  11447. <p>The Room Members admin API allows server admins to get a list of all members of a room.</p>
  11448. <p>The response includes the following fields:</p>
  11449. <ul>
  11450. <li><code>members</code> - A list of all the members that are present in the room, represented by their ids.</li>
  11451. <li><code>total</code> - Total number of members in the room.</li>
  11452. </ul>
  11453. <p>The API is:</p>
  11454. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/members
  11455. </code></pre>
  11456. <p>A response body like the following is returned:</p>
  11457. <pre><code class="language-json">{
  11458. &quot;members&quot;: [
  11459. &quot;@foo:matrix.org&quot;,
  11460. &quot;@bar:matrix.org&quot;,
  11461. &quot;@foobar:matrix.org&quot;
  11462. ],
  11463. &quot;total&quot;: 3
  11464. }
  11465. </code></pre>
  11466. <h1 id="room-state-api"><a class="header" href="#room-state-api">Room State API</a></h1>
  11467. <p>The Room State admin API allows server admins to get a list of all state events in a room.</p>
  11468. <p>The response includes the following fields:</p>
  11469. <ul>
  11470. <li><code>state</code> - The current state of the room at the time of request.</li>
  11471. </ul>
  11472. <p>The API is:</p>
  11473. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/state
  11474. </code></pre>
  11475. <p>A response body like the following is returned:</p>
  11476. <pre><code class="language-json">{
  11477. &quot;state&quot;: [
  11478. {&quot;type&quot;: &quot;m.room.create&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  11479. {&quot;type&quot;: &quot;m.room.power_levels&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  11480. {&quot;type&quot;: &quot;m.room.name&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true}
  11481. ]
  11482. }
  11483. </code></pre>
  11484. <h1 id="room-messages-api"><a class="header" href="#room-messages-api">Room Messages API</a></h1>
  11485. <p>The Room Messages admin API allows server admins to get all messages
  11486. sent to a room in a given timeframe. There are various parameters available
  11487. that allow for filtering and ordering the returned list. This API supports pagination.</p>
  11488. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11489. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  11490. <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>
  11491. <p>The API is:</p>
  11492. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/messages
  11493. </code></pre>
  11494. <p><strong>Parameters</strong></p>
  11495. <p>The following path parameters are required:</p>
  11496. <ul>
  11497. <li><code>room_id</code> - The ID of the room you wish you fetch messages from.</li>
  11498. </ul>
  11499. <p>The following query parameters are available:</p>
  11500. <ul>
  11501. <li><code>from</code> (required) - The token to start returning events from. This token can be obtained from a prev_batch
  11502. or next_batch token returned by the /sync endpoint, or from an end token returned by a previous request to this endpoint.</li>
  11503. <li><code>to</code> - The token to spot returning events at.</li>
  11504. <li><code>limit</code> - The maximum number of events to return. Defaults to <code>10</code>.</li>
  11505. <li><code>filter</code> - A JSON RoomEventFilter to filter returned events with.</li>
  11506. <li><code>dir</code> - The direction to return events from. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  11507. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  11508. </ul>
  11509. <p><strong>Response</strong></p>
  11510. <p>The following fields are possible in the JSON response body:</p>
  11511. <ul>
  11512. <li><code>chunk</code> - A list of room events. The order depends on the dir parameter.
  11513. 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>
  11514. <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.
  11515. If no further events are available, this property is omitted from the response.</li>
  11516. <li><code>start</code> - A token corresponding to the start of chunk.</li>
  11517. <li><code>state</code> - A list of state events relevant to showing the chunk.</li>
  11518. </ul>
  11519. <p><strong>Example</strong></p>
  11520. <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>
  11521. <pre><code class="language-json">{
  11522. &quot;chunk&quot;: [
  11523. {
  11524. &quot;content&quot;: {
  11525. &quot;body&quot;: &quot;This is an example text message&quot;,
  11526. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  11527. &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;,
  11528. &quot;msgtype&quot;: &quot;m.text&quot;
  11529. },
  11530. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  11531. &quot;origin_server_ts&quot;: 1432735824653,
  11532. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11533. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11534. &quot;type&quot;: &quot;m.room.message&quot;,
  11535. &quot;unsigned&quot;: {
  11536. &quot;age&quot;: 1234
  11537. }
  11538. },
  11539. {
  11540. &quot;content&quot;: {
  11541. &quot;name&quot;: &quot;The room name&quot;
  11542. },
  11543. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  11544. &quot;origin_server_ts&quot;: 1432735824653,
  11545. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11546. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11547. &quot;state_key&quot;: &quot;&quot;,
  11548. &quot;type&quot;: &quot;m.room.name&quot;,
  11549. &quot;unsigned&quot;: {
  11550. &quot;age&quot;: 1234
  11551. }
  11552. },
  11553. {
  11554. &quot;content&quot;: {
  11555. &quot;body&quot;: &quot;Gangnam Style&quot;,
  11556. &quot;info&quot;: {
  11557. &quot;duration&quot;: 2140786,
  11558. &quot;h&quot;: 320,
  11559. &quot;mimetype&quot;: &quot;video/mp4&quot;,
  11560. &quot;size&quot;: 1563685,
  11561. &quot;thumbnail_info&quot;: {
  11562. &quot;h&quot;: 300,
  11563. &quot;mimetype&quot;: &quot;image/jpeg&quot;,
  11564. &quot;size&quot;: 46144,
  11565. &quot;w&quot;: 300
  11566. },
  11567. &quot;thumbnail_url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;,
  11568. &quot;w&quot;: 480
  11569. },
  11570. &quot;msgtype&quot;: &quot;m.video&quot;,
  11571. &quot;url&quot;: &quot;mxc://example.org/a526eYUSFFxlgbQYZmo442&quot;
  11572. },
  11573. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  11574. &quot;origin_server_ts&quot;: 1432735824653,
  11575. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11576. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11577. &quot;type&quot;: &quot;m.room.message&quot;,
  11578. &quot;unsigned&quot;: {
  11579. &quot;age&quot;: 1234
  11580. }
  11581. }
  11582. ],
  11583. &quot;end&quot;: &quot;t47409-4357353_219380_26003_2265&quot;,
  11584. &quot;start&quot;: &quot;t47429-4392820_219380_26003_2265&quot;
  11585. }
  11586. </code></pre>
  11587. <h1 id="room-timestamp-to-event-api"><a class="header" href="#room-timestamp-to-event-api">Room Timestamp to Event API</a></h1>
  11588. <p>The Room Timestamp to Event API endpoint fetches the <code>event_id</code> of the closest event to the given
  11589. timestamp (<code>ts</code> query parameter) in the given direction (<code>dir</code> query parameter).</p>
  11590. <p>Useful for cases like jump to date so you can start paginating messages from
  11591. a given date in the archive.</p>
  11592. <p>The API is:</p>
  11593. <pre><code> GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/timestamp_to_event
  11594. </code></pre>
  11595. <p><strong>Parameters</strong></p>
  11596. <p>The following path parameters are required:</p>
  11597. <ul>
  11598. <li><code>room_id</code> - The ID of the room you wish to check.</li>
  11599. </ul>
  11600. <p>The following query parameters are available:</p>
  11601. <ul>
  11602. <li><code>ts</code> - a timestamp in milliseconds where we will find the closest event in
  11603. the given direction.</li>
  11604. <li><code>dir</code> - can be <code>f</code> or <code>b</code> to indicate forwards and backwards in time from the
  11605. given timestamp. Defaults to <code>f</code>.</li>
  11606. </ul>
  11607. <p><strong>Response</strong></p>
  11608. <ul>
  11609. <li><code>event_id</code> - converted from timestamp</li>
  11610. </ul>
  11611. <h1 id="block-room-api"><a class="header" href="#block-room-api">Block Room API</a></h1>
  11612. <p>The Block Room admin API allows server admins to block and unblock rooms,
  11613. and query to see if a given room is blocked.
  11614. This API can be used to pre-emptively block a room, even if it's unknown to this
  11615. homeserver. Users will be prevented from joining a blocked room.</p>
  11616. <h2 id="block-or-unblock-a-room"><a class="header" href="#block-or-unblock-a-room">Block or unblock a room</a></h2>
  11617. <p>The API is:</p>
  11618. <pre><code>PUT /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  11619. </code></pre>
  11620. <p>with a body of:</p>
  11621. <pre><code class="language-json">{
  11622. &quot;block&quot;: true
  11623. }
  11624. </code></pre>
  11625. <p>A response body like the following is returned:</p>
  11626. <pre><code class="language-json">{
  11627. &quot;block&quot;: true
  11628. }
  11629. </code></pre>
  11630. <p><strong>Parameters</strong></p>
  11631. <p>The following parameters should be set in the URL:</p>
  11632. <ul>
  11633. <li><code>room_id</code> - The ID of the room.</li>
  11634. </ul>
  11635. <p>The following JSON body parameters are available:</p>
  11636. <ul>
  11637. <li><code>block</code> - If <code>true</code> the room will be blocked and if <code>false</code> the room will be unblocked.</li>
  11638. </ul>
  11639. <p><strong>Response</strong></p>
  11640. <p>The following fields are possible in the JSON response body:</p>
  11641. <ul>
  11642. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  11643. </ul>
  11644. <h2 id="get-block-status"><a class="header" href="#get-block-status">Get block status</a></h2>
  11645. <p>The API is:</p>
  11646. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  11647. </code></pre>
  11648. <p>A response body like the following is returned:</p>
  11649. <pre><code class="language-json">{
  11650. &quot;block&quot;: true,
  11651. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  11652. }
  11653. </code></pre>
  11654. <p><strong>Parameters</strong></p>
  11655. <p>The following parameters should be set in the URL:</p>
  11656. <ul>
  11657. <li><code>room_id</code> - The ID of the room.</li>
  11658. </ul>
  11659. <p><strong>Response</strong></p>
  11660. <p>The following fields are possible in the JSON response body:</p>
  11661. <ul>
  11662. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  11663. <li><code>user_id</code> - An optional string. If the room is blocked (<code>block</code> is <code>true</code>) shows
  11664. the user who has add the room to blocking list. Otherwise it is not displayed.</li>
  11665. </ul>
  11666. <h1 id="delete-room-api"><a class="header" href="#delete-room-api">Delete Room API</a></h1>
  11667. <p>The Delete Room admin API allows server admins to remove rooms from the server
  11668. and block these rooms.</p>
  11669. <p>Shuts down a room. Moves all local users and room aliases automatically to a
  11670. new room if <code>new_room_user_id</code> is set. Otherwise local users only
  11671. leave the room without any information.</p>
  11672. <p>The new room will be created with the user specified by the <code>new_room_user_id</code> parameter
  11673. as room administrator and will contain a message explaining what happened. Users invited
  11674. to the new room will have power level <code>-10</code> by default, and thus be unable to speak.</p>
  11675. <p>If <code>block</code> is <code>true</code>, users will be prevented from joining the old room.
  11676. This option can in <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> also be used to pre-emptively
  11677. block a room, even if it's unknown to this homeserver. In this case, the room will be
  11678. blocked, and no further action will be taken. If <code>block</code> is <code>false</code>, attempting to
  11679. delete an unknown room is invalid and will be rejected as a bad request.</p>
  11680. <p>This API will remove all trace of the old room from your database after removing
  11681. all local users. If <code>purge</code> is <code>true</code> (the default), all traces of the old room will
  11682. be removed from your database after removing all local users. If you do not want
  11683. this to happen, set <code>purge</code> to <code>false</code>.
  11684. Depending on the amount of history being purged, a call to the API may take
  11685. several minutes or longer.</p>
  11686. <p>The local server will only have the power to move local user and room aliases to
  11687. the new room. Users on other servers will be unaffected.</p>
  11688. <h2 id="version-1-old-version"><a class="header" href="#version-1-old-version">Version 1 (old version)</a></h2>
  11689. <p>This version works synchronously. That means you only get the response once the server has
  11690. finished the action, which may take a long time. If you request the same action
  11691. a second time, and the server has not finished the first one, the second request will block.
  11692. This is fixed in version 2 of this API. The parameters are the same in both APIs.
  11693. This API will become deprecated in the future.</p>
  11694. <p>The API is:</p>
  11695. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id&gt;
  11696. </code></pre>
  11697. <p>with a body of:</p>
  11698. <pre><code class="language-json">{
  11699. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  11700. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  11701. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  11702. &quot;block&quot;: true,
  11703. &quot;purge&quot;: true
  11704. }
  11705. </code></pre>
  11706. <p>A response body like the following is returned:</p>
  11707. <pre><code class="language-json">{
  11708. &quot;kicked_users&quot;: [
  11709. &quot;@foobar:example.com&quot;
  11710. ],
  11711. &quot;failed_to_kick_users&quot;: [],
  11712. &quot;local_aliases&quot;: [
  11713. &quot;#badroom:example.com&quot;,
  11714. &quot;#evilsaloon:example.com&quot;
  11715. ],
  11716. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  11717. }
  11718. </code></pre>
  11719. <p>The parameters and response values have the same format as
  11720. <a href="admin_api/rooms.html#version-2-new-version">version 2</a> of the API.</p>
  11721. <h2 id="version-2-new-version"><a class="header" href="#version-2-new-version">Version 2 (new version)</a></h2>
  11722. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  11723. <p>This version works asynchronously, meaning you get the response from server immediately
  11724. while the server works on that task in background. You can then request the status of the action
  11725. to check if it has completed.</p>
  11726. <p>The API is:</p>
  11727. <pre><code>DELETE /_synapse/admin/v2/rooms/&lt;room_id&gt;
  11728. </code></pre>
  11729. <p>with a body of:</p>
  11730. <pre><code class="language-json">{
  11731. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  11732. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  11733. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  11734. &quot;block&quot;: true,
  11735. &quot;purge&quot;: true
  11736. }
  11737. </code></pre>
  11738. <p>The API starts the shut down and purge running, and returns immediately with a JSON body with
  11739. a purge id:</p>
  11740. <pre><code class="language-json">{
  11741. &quot;delete_id&quot;: &quot;&lt;opaque id&gt;&quot;
  11742. }
  11743. </code></pre>
  11744. <p><strong>Parameters</strong></p>
  11745. <p>The following parameters should be set in the URL:</p>
  11746. <ul>
  11747. <li><code>room_id</code> - The ID of the room.</li>
  11748. </ul>
  11749. <p>The following JSON body parameters are available:</p>
  11750. <ul>
  11751. <li><code>new_room_user_id</code> - Optional. If set, a new room will be created with this user ID
  11752. as the creator and admin, and all users in the old room will be moved into that
  11753. room. If not set, no new room will be created and the users will just be removed
  11754. from the old room. The user ID must be on the local server, but does not necessarily
  11755. have to belong to a registered user.</li>
  11756. <li><code>room_name</code> - Optional. A string representing the name of the room that new users will be
  11757. invited to. Defaults to <code>Content Violation Notification</code></li>
  11758. <li><code>message</code> - Optional. A string containing the first message that will be sent as
  11759. <code>new_room_user_id</code> in the new room. Ideally this will clearly convey why the
  11760. 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>
  11761. <li><code>block</code> - Optional. If set to <code>true</code>, this room will be added to a blocking list,
  11762. preventing future attempts to join the room. Rooms can be blocked
  11763. even if they're not yet known to the homeserver (only with
  11764. <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> of the API). Defaults to <code>false</code>.</li>
  11765. <li><code>purge</code> - Optional. If set to <code>true</code>, it will remove all traces of the room from your database.
  11766. Defaults to <code>true</code>.</li>
  11767. <li><code>force_purge</code> - Optional, and ignored unless <code>purge</code> is <code>true</code>. If set to <code>true</code>, it
  11768. will force a purge to go ahead even if there are local users still in the room. Do not
  11769. use this unless a regular <code>purge</code> operation fails, as it could leave those users'
  11770. clients in a confused state.</li>
  11771. </ul>
  11772. <p>The JSON body must not be empty. The body must be at least <code>{}</code>.</p>
  11773. <h2 id="status-of-deleting-rooms"><a class="header" href="#status-of-deleting-rooms">Status of deleting rooms</a></h2>
  11774. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  11775. <p>It is possible to query the status of the background task for deleting rooms.
  11776. The status can be queried up to 24 hours after completion of the task,
  11777. or until Synapse is restarted (whichever happens first).</p>
  11778. <h3 id="query-by-room_id"><a class="header" href="#query-by-room_id">Query by <code>room_id</code></a></h3>
  11779. <p>With this API you can get the status of all active deletion tasks, and all those completed in the last 24h,
  11780. for the given <code>room_id</code>.</p>
  11781. <p>The API is:</p>
  11782. <pre><code>GET /_synapse/admin/v2/rooms/&lt;room_id&gt;/delete_status
  11783. </code></pre>
  11784. <p>A response body like the following is returned:</p>
  11785. <pre><code class="language-json">{
  11786. &quot;results&quot;: [
  11787. {
  11788. &quot;delete_id&quot;: &quot;delete_id1&quot;,
  11789. &quot;status&quot;: &quot;failed&quot;,
  11790. &quot;error&quot;: &quot;error message&quot;,
  11791. &quot;shutdown_room&quot;: {
  11792. &quot;kicked_users&quot;: [],
  11793. &quot;failed_to_kick_users&quot;: [],
  11794. &quot;local_aliases&quot;: [],
  11795. &quot;new_room_id&quot;: null
  11796. }
  11797. }, {
  11798. &quot;delete_id&quot;: &quot;delete_id2&quot;,
  11799. &quot;status&quot;: &quot;purging&quot;,
  11800. &quot;shutdown_room&quot;: {
  11801. &quot;kicked_users&quot;: [
  11802. &quot;@foobar:example.com&quot;
  11803. ],
  11804. &quot;failed_to_kick_users&quot;: [],
  11805. &quot;local_aliases&quot;: [
  11806. &quot;#badroom:example.com&quot;,
  11807. &quot;#evilsaloon:example.com&quot;
  11808. ],
  11809. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  11810. }
  11811. }
  11812. ]
  11813. }
  11814. </code></pre>
  11815. <p><strong>Parameters</strong></p>
  11816. <p>The following parameters should be set in the URL:</p>
  11817. <ul>
  11818. <li><code>room_id</code> - The ID of the room.</li>
  11819. </ul>
  11820. <h3 id="query-by-delete_id"><a class="header" href="#query-by-delete_id">Query by <code>delete_id</code></a></h3>
  11821. <p>With this API you can get the status of one specific task by <code>delete_id</code>.</p>
  11822. <p>The API is:</p>
  11823. <pre><code>GET /_synapse/admin/v2/rooms/delete_status/&lt;delete_id&gt;
  11824. </code></pre>
  11825. <p>A response body like the following is returned:</p>
  11826. <pre><code class="language-json">{
  11827. &quot;status&quot;: &quot;purging&quot;,
  11828. &quot;shutdown_room&quot;: {
  11829. &quot;kicked_users&quot;: [
  11830. &quot;@foobar:example.com&quot;
  11831. ],
  11832. &quot;failed_to_kick_users&quot;: [],
  11833. &quot;local_aliases&quot;: [
  11834. &quot;#badroom:example.com&quot;,
  11835. &quot;#evilsaloon:example.com&quot;
  11836. ],
  11837. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  11838. }
  11839. }
  11840. </code></pre>
  11841. <p><strong>Parameters</strong></p>
  11842. <p>The following parameters should be set in the URL:</p>
  11843. <ul>
  11844. <li><code>delete_id</code> - The ID for this delete.</li>
  11845. </ul>
  11846. <h3 id="response"><a class="header" href="#response">Response</a></h3>
  11847. <p>The following fields are returned in the JSON response body:</p>
  11848. <ul>
  11849. <li><code>results</code> - An array of objects, each containing information about one task.
  11850. This field is omitted from the result when you query by <code>delete_id</code>.
  11851. Task objects contain the following fields:
  11852. <ul>
  11853. <li><code>delete_id</code> - The ID for this purge if you query by <code>room_id</code>.</li>
  11854. <li><code>status</code> - The status will be one of:
  11855. <ul>
  11856. <li><code>shutting_down</code> - The process is removing users from the room.</li>
  11857. <li><code>purging</code> - The process is purging the room and event data from database.</li>
  11858. <li><code>complete</code> - The process has completed successfully.</li>
  11859. <li><code>failed</code> - The process is aborted, an error has occurred.</li>
  11860. </ul>
  11861. </li>
  11862. <li><code>error</code> - A string that shows an error message if <code>status</code> is <code>failed</code>.
  11863. Otherwise this field is hidden.</li>
  11864. <li><code>shutdown_room</code> - An object containing information about the result of shutting down the room.
  11865. <em>Note:</em> The result is shown after removing the room members.
  11866. The delete process can still be running. Please pay attention to the <code>status</code>.
  11867. <ul>
  11868. <li><code>kicked_users</code> - An array of users (<code>user_id</code>) that were kicked.</li>
  11869. <li><code>failed_to_kick_users</code> - An array of users (<code>user_id</code>) that that were not kicked.</li>
  11870. <li><code>local_aliases</code> - An array of strings representing the local aliases that were
  11871. migrated from the old room to the new.</li>
  11872. <li><code>new_room_id</code> - A string representing the room ID of the new room, or <code>null</code> if
  11873. no such room was created.</li>
  11874. </ul>
  11875. </li>
  11876. </ul>
  11877. </li>
  11878. </ul>
  11879. <h2 id="undoing-room-deletions"><a class="header" href="#undoing-room-deletions">Undoing room deletions</a></h2>
  11880. <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,
  11881. the structure can and does change without notice.</p>
  11882. <p>First, it's important to understand that a room deletion is very destructive. Undoing a deletion is not as simple as pretending it
  11883. 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
  11884. to recover at all:</p>
  11885. <ul>
  11886. <li>If the room was invite-only, your users will need to be re-invited.</li>
  11887. <li>If the room no longer has any members at all, it'll be impossible to rejoin.</li>
  11888. <li>The first user to rejoin will have to do so via an alias on a different
  11889. server (or receive an invite from a user on a different server).</li>
  11890. </ul>
  11891. <p>With all that being said, if you still want to try and recover the room:</p>
  11892. <ol>
  11893. <li>
  11894. <p>If the room was <code>block</code>ed, you must unblock it on your server. This can be
  11895. accomplished as follows:</p>
  11896. <ol>
  11897. <li>For safety reasons, shut down Synapse.</li>
  11898. <li>In the database, run <code>DELETE FROM blocked_rooms WHERE room_id = '!example:example.org';</code>
  11899. <ul>
  11900. <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>
  11901. <li>The room ID is the same one supplied to the delete room API, not the Content Violation room.</li>
  11902. </ul>
  11903. </li>
  11904. <li>Restart Synapse.</li>
  11905. </ol>
  11906. <p>This step is unnecessary if <code>block</code> was not set.</p>
  11907. </li>
  11908. <li>
  11909. <p>Any room aliases on your server that pointed to the deleted room may have
  11910. been deleted, or redirected to the Content Violation room. These will need
  11911. to be restored manually.</p>
  11912. </li>
  11913. <li>
  11914. <p>Users on your server that were in the deleted room will have been kicked
  11915. from the room. Consider whether you want to update their membership
  11916. (possibly via the <a href="admin_api/room_membership.html">Edit Room Membership API</a>) or let
  11917. them handle rejoining themselves.</p>
  11918. </li>
  11919. <li>
  11920. <p>If <code>new_room_user_id</code> was given, a 'Content Violation' will have been
  11921. created. Consider whether you want to delete that roomm.</p>
  11922. </li>
  11923. </ol>
  11924. <h1 id="make-room-admin-api"><a class="header" href="#make-room-admin-api">Make Room Admin API</a></h1>
  11925. <p>Grants another user the highest power available to a local user who is in the room.
  11926. If the user is not in the room, and it is not publicly joinable, then invite the user.</p>
  11927. <p>By default the server admin (the caller) is granted power, but another user can
  11928. optionally be specified, e.g.:</p>
  11929. <pre><code>POST /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/make_room_admin
  11930. {
  11931. &quot;user_id&quot;: &quot;@foo:example.com&quot;
  11932. }
  11933. </code></pre>
  11934. <h1 id="forward-extremities-admin-api"><a class="header" href="#forward-extremities-admin-api">Forward Extremities Admin API</a></h1>
  11935. <p>Enables querying and deleting forward extremities from rooms. When a lot of forward
  11936. extremities accumulate in a room, performance can become degraded. For details, see
  11937. <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.</p>
  11938. <h2 id="check-for-forward-extremities"><a class="header" href="#check-for-forward-extremities">Check for forward extremities</a></h2>
  11939. <p>To check the status of forward extremities for a room:</p>
  11940. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  11941. </code></pre>
  11942. <p>A response as follows will be returned:</p>
  11943. <pre><code class="language-json">{
  11944. &quot;count&quot;: 1,
  11945. &quot;results&quot;: [
  11946. {
  11947. &quot;event_id&quot;: &quot;$M5SP266vsnxctfwFgFLNceaCo3ujhRtg_NiiHabcdefgh&quot;,
  11948. &quot;state_group&quot;: 439,
  11949. &quot;depth&quot;: 123,
  11950. &quot;received_ts&quot;: 1611263016761
  11951. }
  11952. ]
  11953. }
  11954. </code></pre>
  11955. <h2 id="deleting-forward-extremities"><a class="header" href="#deleting-forward-extremities">Deleting forward extremities</a></h2>
  11956. <p><strong>WARNING</strong>: Please ensure you know what you're doing and have read
  11957. the related issue <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.
  11958. Under no situations should this API be executed as an automated maintenance task!</p>
  11959. <p>If a room has lots of forward extremities, the extra can be
  11960. deleted as follows:</p>
  11961. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  11962. </code></pre>
  11963. <p>A response as follows will be returned, indicating the amount of forward extremities
  11964. that were deleted.</p>
  11965. <pre><code class="language-json">{
  11966. &quot;deleted&quot;: 1
  11967. }
  11968. </code></pre>
  11969. <h1 id="event-context-api"><a class="header" href="#event-context-api">Event Context API</a></h1>
  11970. <p>This API lets a client find the context of an event. This is designed primarily to investigate abuse reports.</p>
  11971. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/context/&lt;event_id&gt;
  11972. </code></pre>
  11973. <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>
  11974. <p>Example response:</p>
  11975. <pre><code class="language-json">{
  11976. &quot;end&quot;: &quot;t29-57_2_0_2&quot;,
  11977. &quot;events_after&quot;: [
  11978. {
  11979. &quot;content&quot;: {
  11980. &quot;body&quot;: &quot;This is an example text message&quot;,
  11981. &quot;msgtype&quot;: &quot;m.text&quot;,
  11982. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  11983. &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;
  11984. },
  11985. &quot;type&quot;: &quot;m.room.message&quot;,
  11986. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  11987. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11988. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11989. &quot;origin_server_ts&quot;: 1432735824653,
  11990. &quot;unsigned&quot;: {
  11991. &quot;age&quot;: 1234
  11992. }
  11993. }
  11994. ],
  11995. &quot;event&quot;: {
  11996. &quot;content&quot;: {
  11997. &quot;body&quot;: &quot;filename.jpg&quot;,
  11998. &quot;info&quot;: {
  11999. &quot;h&quot;: 398,
  12000. &quot;w&quot;: 394,
  12001. &quot;mimetype&quot;: &quot;image/jpeg&quot;,
  12002. &quot;size&quot;: 31037
  12003. },
  12004. &quot;url&quot;: &quot;mxc://example.org/JWEIFJgwEIhweiWJE&quot;,
  12005. &quot;msgtype&quot;: &quot;m.image&quot;
  12006. },
  12007. &quot;type&quot;: &quot;m.room.message&quot;,
  12008. &quot;event_id&quot;: &quot;$f3h4d129462ha:example.com&quot;,
  12009. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  12010. &quot;sender&quot;: &quot;@example:example.org&quot;,
  12011. &quot;origin_server_ts&quot;: 1432735824653,
  12012. &quot;unsigned&quot;: {
  12013. &quot;age&quot;: 1234
  12014. }
  12015. },
  12016. &quot;events_before&quot;: [
  12017. {
  12018. &quot;content&quot;: {
  12019. &quot;body&quot;: &quot;something-important.doc&quot;,
  12020. &quot;filename&quot;: &quot;something-important.doc&quot;,
  12021. &quot;info&quot;: {
  12022. &quot;mimetype&quot;: &quot;application/msword&quot;,
  12023. &quot;size&quot;: 46144
  12024. },
  12025. &quot;msgtype&quot;: &quot;m.file&quot;,
  12026. &quot;url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;
  12027. },
  12028. &quot;type&quot;: &quot;m.room.message&quot;,
  12029. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  12030. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  12031. &quot;sender&quot;: &quot;@example:example.org&quot;,
  12032. &quot;origin_server_ts&quot;: 1432735824653,
  12033. &quot;unsigned&quot;: {
  12034. &quot;age&quot;: 1234
  12035. }
  12036. }
  12037. ],
  12038. &quot;start&quot;: &quot;t27-54_2_0_2&quot;,
  12039. &quot;state&quot;: [
  12040. {
  12041. &quot;content&quot;: {
  12042. &quot;creator&quot;: &quot;@example:example.org&quot;,
  12043. &quot;room_version&quot;: &quot;1&quot;,
  12044. &quot;m.federate&quot;: true,
  12045. &quot;predecessor&quot;: {
  12046. &quot;event_id&quot;: &quot;$something:example.org&quot;,
  12047. &quot;room_id&quot;: &quot;!oldroom:example.org&quot;
  12048. }
  12049. },
  12050. &quot;type&quot;: &quot;m.room.create&quot;,
  12051. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  12052. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  12053. &quot;sender&quot;: &quot;@example:example.org&quot;,
  12054. &quot;origin_server_ts&quot;: 1432735824653,
  12055. &quot;unsigned&quot;: {
  12056. &quot;age&quot;: 1234
  12057. },
  12058. &quot;state_key&quot;: &quot;&quot;
  12059. },
  12060. {
  12061. &quot;content&quot;: {
  12062. &quot;membership&quot;: &quot;join&quot;,
  12063. &quot;avatar_url&quot;: &quot;mxc://example.org/SEsfnsuifSDFSSEF&quot;,
  12064. &quot;displayname&quot;: &quot;Alice Margatroid&quot;
  12065. },
  12066. &quot;type&quot;: &quot;m.room.member&quot;,
  12067. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  12068. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  12069. &quot;sender&quot;: &quot;@example:example.org&quot;,
  12070. &quot;origin_server_ts&quot;: 1432735824653,
  12071. &quot;unsigned&quot;: {
  12072. &quot;age&quot;: 1234
  12073. },
  12074. &quot;state_key&quot;: &quot;@alice:example.org&quot;
  12075. }
  12076. ]
  12077. }
  12078. </code></pre>
  12079. <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>
  12080. <p>The API to send notices is as follows:</p>
  12081. <pre><code>POST /_synapse/admin/v1/send_server_notice
  12082. </code></pre>
  12083. <p>or:</p>
  12084. <pre><code>PUT /_synapse/admin/v1/send_server_notice/{txnId}
  12085. </code></pre>
  12086. <p>You will need to authenticate with an access token for an admin user.</p>
  12087. <p>When using the <code>PUT</code> form, retransmissions with the same transaction ID will be
  12088. ignored in the same way as with <code>PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}</code>.</p>
  12089. <p>The request body should look something like the following:</p>
  12090. <pre><code class="language-json">{
  12091. &quot;user_id&quot;: &quot;@target_user:server_name&quot;,
  12092. &quot;content&quot;: {
  12093. &quot;msgtype&quot;: &quot;m.text&quot;,
  12094. &quot;body&quot;: &quot;This is my message&quot;
  12095. }
  12096. }
  12097. </code></pre>
  12098. <p>You can optionally include the following additional parameters:</p>
  12099. <ul>
  12100. <li><code>type</code>: the type of event. Defaults to <code>m.room.message</code>.</li>
  12101. <li><code>state_key</code>: Setting this will result in a state event being sent.</li>
  12102. </ul>
  12103. <p>Once the notice has been sent, the API will return the following response:</p>
  12104. <pre><code class="language-json">{
  12105. &quot;event_id&quot;: &quot;&lt;event_id&gt;&quot;
  12106. }
  12107. </code></pre>
  12108. <p>Note that server notices must be enabled in <code>homeserver.yaml</code> before this API
  12109. can be used. See <a href="admin_api/../server_notices.html">the server notices documentation</a> for more information.</p>
  12110. <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>
  12111. <p>Returns information about all local media usage of users. Gives the
  12112. possibility to filter them by time and user.</p>
  12113. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12114. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  12115. <p>The API is:</p>
  12116. <pre><code>GET /_synapse/admin/v1/statistics/users/media
  12117. </code></pre>
  12118. <p>A response body like the following is returned:</p>
  12119. <pre><code class="language-json">{
  12120. &quot;users&quot;: [
  12121. {
  12122. &quot;displayname&quot;: &quot;foo_user_0&quot;,
  12123. &quot;media_count&quot;: 2,
  12124. &quot;media_length&quot;: 134,
  12125. &quot;user_id&quot;: &quot;@foo_user_0:test&quot;
  12126. },
  12127. {
  12128. &quot;displayname&quot;: &quot;foo_user_1&quot;,
  12129. &quot;media_count&quot;: 2,
  12130. &quot;media_length&quot;: 134,
  12131. &quot;user_id&quot;: &quot;@foo_user_1:test&quot;
  12132. }
  12133. ],
  12134. &quot;next_token&quot;: 3,
  12135. &quot;total&quot;: 10
  12136. }
  12137. </code></pre>
  12138. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint
  12139. again with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  12140. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  12141. reports to paginate through.</p>
  12142. <p><strong>Parameters</strong></p>
  12143. <p>The following parameters should be set in the URL:</p>
  12144. <ul>
  12145. <li><code>limit</code>: string representing a positive integer - Is optional but is
  12146. used for pagination, denoting the maximum number of items to return
  12147. in this call. Defaults to <code>100</code>.</li>
  12148. <li><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  12149. denoting the offset in the returned results. This should be treated as an opaque value
  12150. and not explicitly set to anything other than the return value of <code>next_token</code> from a
  12151. previous call. Defaults to <code>0</code>.</li>
  12152. <li><code>order_by</code> - string - The method in which to sort the returned list of users. Valid values are:
  12153. <ul>
  12154. <li><code>user_id</code> - Users are ordered alphabetically by <code>user_id</code>. This is the default.</li>
  12155. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  12156. <li><code>media_length</code> - Users are ordered by the total size of uploaded media in bytes.
  12157. Smallest to largest.</li>
  12158. <li><code>media_count</code> - Users are ordered by number of uploaded media. Smallest to largest.</li>
  12159. </ul>
  12160. </li>
  12161. <li><code>from_ts</code> - string representing a positive integer - Considers only
  12162. files created at this timestamp or later. Unix timestamp in ms.</li>
  12163. <li><code>until_ts</code> - string representing a positive integer - Considers only
  12164. files created at this timestamp or earlier. Unix timestamp in ms.</li>
  12165. <li><code>search_term</code> - string - Filter users by their user ID localpart <strong>or</strong> displayname.
  12166. The search term can be found in any part of the string.
  12167. Defaults to no filtering.</li>
  12168. <li><code>dir</code> - string - Direction of order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  12169. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  12170. </ul>
  12171. <p><strong>Response</strong></p>
  12172. <p>The following fields are returned in the JSON response body:</p>
  12173. <ul>
  12174. <li><code>users</code> - An array of objects, each containing information
  12175. about the user and their local media. Objects contain the following fields:
  12176. <ul>
  12177. <li><code>displayname</code> - string - Displayname of this user.</li>
  12178. <li><code>media_count</code> - integer - Number of uploaded media by this user.</li>
  12179. <li><code>media_length</code> - integer - Size of uploaded media in bytes by this user.</li>
  12180. <li><code>user_id</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  12181. </ul>
  12182. </li>
  12183. <li><code>next_token</code> - integer - Opaque value used for pagination. See above.</li>
  12184. <li><code>total</code> - integer - Total number of users after filtering.</li>
  12185. </ul>
  12186. <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>
  12187. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  12188. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  12189. <h2 id="query-user-account"><a class="header" href="#query-user-account">Query User Account</a></h2>
  12190. <p>This API returns information about a specific user account.</p>
  12191. <p>The api is:</p>
  12192. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;
  12193. </code></pre>
  12194. <p>It returns a JSON body like the following:</p>
  12195. <pre><code class="language-jsonc">{
  12196. &quot;name&quot;: &quot;@user:example.com&quot;,
  12197. &quot;displayname&quot;: &quot;User&quot;, // can be null if not set
  12198. &quot;threepids&quot;: [
  12199. {
  12200. &quot;medium&quot;: &quot;email&quot;,
  12201. &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;,
  12202. &quot;added_at&quot;: 1586458409743,
  12203. &quot;validated_at&quot;: 1586458409743
  12204. },
  12205. {
  12206. &quot;medium&quot;: &quot;email&quot;,
  12207. &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;,
  12208. &quot;added_at&quot;: 1586458409743,
  12209. &quot;validated_at&quot;: 1586458409743
  12210. }
  12211. ],
  12212. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;, // can be null if not set
  12213. &quot;is_guest&quot;: 0,
  12214. &quot;admin&quot;: 0,
  12215. &quot;deactivated&quot;: 0,
  12216. &quot;shadow_banned&quot;: 0,
  12217. &quot;creation_ts&quot;: 1560432506,
  12218. &quot;appservice_id&quot;: null,
  12219. &quot;consent_server_notice_sent&quot;: null,
  12220. &quot;consent_version&quot;: null,
  12221. &quot;consent_ts&quot;: null,
  12222. &quot;external_ids&quot;: [
  12223. {
  12224. &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
  12225. &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
  12226. },
  12227. {
  12228. &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
  12229. &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
  12230. }
  12231. ],
  12232. &quot;user_type&quot;: null
  12233. }
  12234. </code></pre>
  12235. <p>URL parameters:</p>
  12236. <ul>
  12237. <li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
  12238. </ul>
  12239. <h2 id="create-or-modify-account"><a class="header" href="#create-or-modify-account">Create or modify Account</a></h2>
  12240. <p>This API allows an administrator to create or modify a user account with a
  12241. specific <code>user_id</code>.</p>
  12242. <p>This api is:</p>
  12243. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;
  12244. </code></pre>
  12245. <p>with a body of:</p>
  12246. <pre><code class="language-json">{
  12247. &quot;password&quot;: &quot;user_password&quot;,
  12248. &quot;displayname&quot;: &quot;User&quot;,
  12249. &quot;threepids&quot;: [
  12250. {
  12251. &quot;medium&quot;: &quot;email&quot;,
  12252. &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;
  12253. },
  12254. {
  12255. &quot;medium&quot;: &quot;email&quot;,
  12256. &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;
  12257. }
  12258. ],
  12259. &quot;external_ids&quot;: [
  12260. {
  12261. &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
  12262. &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
  12263. },
  12264. {
  12265. &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
  12266. &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
  12267. }
  12268. ],
  12269. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
  12270. &quot;admin&quot;: false,
  12271. &quot;deactivated&quot;: false,
  12272. &quot;user_type&quot;: null
  12273. }
  12274. </code></pre>
  12275. <p>Returns HTTP status code:</p>
  12276. <ul>
  12277. <li><code>201</code> - When a new user object was created.</li>
  12278. <li><code>200</code> - When a user was modified.</li>
  12279. </ul>
  12280. <p>URL parameters:</p>
  12281. <ul>
  12282. <li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
  12283. </ul>
  12284. <p>Body parameters:</p>
  12285. <ul>
  12286. <li><code>password</code> - string, optional. If provided, the user's password is updated and all
  12287. devices are logged out, unless <code>logout_devices</code> is set to <code>false</code>.</li>
  12288. <li><code>logout_devices</code> - bool, optional, defaults to <code>true</code>. If set to false, devices aren't
  12289. logged out even when <code>password</code> is provided.</li>
  12290. <li><code>displayname</code> - string, optional, defaults to the value of <code>user_id</code>.</li>
  12291. <li><code>threepids</code> - array, optional, allows setting the third-party IDs (email, msisdn)
  12292. <ul>
  12293. <li><code>medium</code> - string. Kind of third-party ID, either <code>email</code> or <code>msisdn</code>.</li>
  12294. <li><code>address</code> - string. Value of third-party ID.
  12295. belonging to a user.</li>
  12296. </ul>
  12297. </li>
  12298. <li><code>external_ids</code> - array, optional. Allow setting the identifier of the external identity
  12299. provider for SSO (Single sign-on). Details in the configuration manual under the
  12300. 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>.
  12301. <ul>
  12302. <li><code>auth_provider</code> - string. ID of the external identity provider. Value of <code>idp_id</code>
  12303. in the homeserver configuration. Note that no error is raised if the provided
  12304. value is not in the homeserver configuration.</li>
  12305. <li><code>external_id</code> - string, user ID in the external identity provider.</li>
  12306. </ul>
  12307. </li>
  12308. <li><code>avatar_url</code> - string, optional, must be a
  12309. <a href="https://matrix.org/docs/spec/client_server/r0.6.0#matrix-content-mxc-uris">MXC URI</a>.</li>
  12310. <li><code>admin</code> - bool, optional, defaults to <code>false</code>.</li>
  12311. <li><code>deactivated</code> - bool, optional. If unspecified, deactivation state will be left
  12312. unchanged on existing accounts and set to <code>false</code> for new accounts.
  12313. A user cannot be erased by deactivating with this API. For details on
  12314. deactivating users see <a href="admin_api/user_admin_api.html#deactivate-account">Deactivate Account</a>.</li>
  12315. <li><code>user_type</code> - string or null, optional. If provided, the user type will be
  12316. adjusted. If <code>null</code> given, the user type will be cleared. Other
  12317. allowed options are: <code>bot</code> and <code>support</code>.</li>
  12318. </ul>
  12319. <p>If the user already exists then optional parameters default to the current value.</p>
  12320. <p>In order to re-activate an account <code>deactivated</code> must be set to <code>false</code>. If
  12321. users do not login via single-sign-on, a new <code>password</code> must be provided.</p>
  12322. <h2 id="list-accounts"><a class="header" href="#list-accounts">List Accounts</a></h2>
  12323. <p>This API returns all local user accounts.
  12324. By default, the response is ordered by ascending user ID.</p>
  12325. <pre><code>GET /_synapse/admin/v2/users?from=0&amp;limit=10&amp;guests=false
  12326. </code></pre>
  12327. <p>A response body like the following is returned:</p>
  12328. <pre><code class="language-json">{
  12329. &quot;users&quot;: [
  12330. {
  12331. &quot;name&quot;: &quot;&lt;user_id1&gt;&quot;,
  12332. &quot;is_guest&quot;: 0,
  12333. &quot;admin&quot;: 0,
  12334. &quot;user_type&quot;: null,
  12335. &quot;deactivated&quot;: 0,
  12336. &quot;shadow_banned&quot;: 0,
  12337. &quot;displayname&quot;: &quot;&lt;User One&gt;&quot;,
  12338. &quot;avatar_url&quot;: null,
  12339. &quot;creation_ts&quot;: 1560432668000
  12340. }, {
  12341. &quot;name&quot;: &quot;&lt;user_id2&gt;&quot;,
  12342. &quot;is_guest&quot;: 0,
  12343. &quot;admin&quot;: 1,
  12344. &quot;user_type&quot;: null,
  12345. &quot;deactivated&quot;: 0,
  12346. &quot;shadow_banned&quot;: 0,
  12347. &quot;displayname&quot;: &quot;&lt;User Two&gt;&quot;,
  12348. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
  12349. &quot;creation_ts&quot;: 1561550621000
  12350. }
  12351. ],
  12352. &quot;next_token&quot;: &quot;100&quot;,
  12353. &quot;total&quot;: 200
  12354. }
  12355. </code></pre>
  12356. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  12357. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  12358. <p>If the endpoint does not return a <code>next_token</code> then there are no more users
  12359. to paginate through.</p>
  12360. <p><strong>Parameters</strong></p>
  12361. <p>The following parameters should be set in the URL:</p>
  12362. <ul>
  12363. <li>
  12364. <p><code>user_id</code> - Is optional and filters to only return users with user IDs
  12365. that contain this value. This parameter is ignored when using the <code>name</code> parameter.</p>
  12366. </li>
  12367. <li>
  12368. <p><code>name</code> - Is optional and filters to only return users with user ID localparts
  12369. <strong>or</strong> displaynames that contain this value.</p>
  12370. </li>
  12371. <li>
  12372. <p><code>guests</code> - string representing a bool - Is optional and if <code>false</code> will <strong>exclude</strong> guest users.
  12373. Defaults to <code>true</code> to include guest users.</p>
  12374. </li>
  12375. <li>
  12376. <p><code>deactivated</code> - string representing a bool - Is optional and if <code>true</code> will <strong>include</strong> deactivated users.
  12377. Defaults to <code>false</code> to exclude deactivated users.</p>
  12378. </li>
  12379. <li>
  12380. <p><code>limit</code> - string representing a positive integer - Is optional but is used for pagination,
  12381. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  12382. </li>
  12383. <li>
  12384. <p><code>from</code> - string representing a positive integer - Is optional but used for pagination,
  12385. denoting the offset in the returned results. This should be treated as an opaque value and
  12386. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  12387. Defaults to <code>0</code>.</p>
  12388. </li>
  12389. <li>
  12390. <p><code>order_by</code> - The method by which to sort the returned list of users.
  12391. If the ordered field has duplicates, the second order is always by ascending <code>name</code>,
  12392. which guarantees a stable ordering. Valid values are:</p>
  12393. <ul>
  12394. <li><code>name</code> - Users are ordered alphabetically by <code>name</code>. This is the default.</li>
  12395. <li><code>is_guest</code> - Users are ordered by <code>is_guest</code> status.</li>
  12396. <li><code>admin</code> - Users are ordered by <code>admin</code> status.</li>
  12397. <li><code>user_type</code> - Users are ordered alphabetically by <code>user_type</code>.</li>
  12398. <li><code>deactivated</code> - Users are ordered by <code>deactivated</code> status.</li>
  12399. <li><code>shadow_banned</code> - Users are ordered by <code>shadow_banned</code> status.</li>
  12400. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  12401. <li><code>avatar_url</code> - Users are ordered alphabetically by avatar URL.</li>
  12402. <li><code>creation_ts</code> - Users are ordered by when the users was created in ms.</li>
  12403. </ul>
  12404. </li>
  12405. <li>
  12406. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  12407. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  12408. </li>
  12409. </ul>
  12410. <p>Caution. The database only has indexes on the columns <code>name</code> and <code>creation_ts</code>.
  12411. This means that if a different sort order is used (<code>is_guest</code>, <code>admin</code>,
  12412. <code>user_type</code>, <code>deactivated</code>, <code>shadow_banned</code>, <code>avatar_url</code> or <code>displayname</code>),
  12413. this can cause a large load on the database, especially for large environments.</p>
  12414. <p><strong>Response</strong></p>
  12415. <p>The following fields are returned in the JSON response body:</p>
  12416. <ul>
  12417. <li>
  12418. <p><code>users</code> - An array of objects, each containing information about an user.
  12419. User objects contain the following fields:</p>
  12420. <ul>
  12421. <li><code>name</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  12422. <li><code>is_guest</code> - bool - Status if that user is a guest account.</li>
  12423. <li><code>admin</code> - bool - Status if that user is a server administrator.</li>
  12424. <li><code>user_type</code> - string - Type of the user. Normal users are type <code>None</code>.
  12425. This allows user type specific behaviour. There are also types <code>support</code> and <code>bot</code>. </li>
  12426. <li><code>deactivated</code> - bool - Status if that user has been marked as deactivated.</li>
  12427. <li><code>shadow_banned</code> - bool - Status if that user has been marked as shadow banned.</li>
  12428. <li><code>displayname</code> - string - The user's display name if they have set one.</li>
  12429. <li><code>avatar_url</code> - string - The user's avatar URL if they have set one.</li>
  12430. <li><code>creation_ts</code> - integer - The user's creation timestamp in ms.</li>
  12431. </ul>
  12432. </li>
  12433. <li>
  12434. <p><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</p>
  12435. </li>
  12436. <li>
  12437. <p><code>total</code> - integer - Total number of media.</p>
  12438. </li>
  12439. </ul>
  12440. <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>
  12441. <p>This API returns information about the active sessions for a specific user.</p>
  12442. <p>The endpoints are:</p>
  12443. <pre><code>GET /_synapse/admin/v1/whois/&lt;user_id&gt;
  12444. </code></pre>
  12445. <p>and:</p>
  12446. <pre><code>GET /_matrix/client/r0/admin/whois/&lt;userId&gt;
  12447. </code></pre>
  12448. <p>See also: <a href="https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-admin-whois-userid">Client Server
  12449. API Whois</a>.</p>
  12450. <p>It returns a JSON body like the following:</p>
  12451. <pre><code class="language-json">{
  12452. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;,
  12453. &quot;devices&quot;: {
  12454. &quot;&quot;: {
  12455. &quot;sessions&quot;: [
  12456. {
  12457. &quot;connections&quot;: [
  12458. {
  12459. &quot;ip&quot;: &quot;1.2.3.4&quot;,
  12460. &quot;last_seen&quot;: 1417222374433,
  12461. &quot;user_agent&quot;: &quot;Mozilla/5.0 ...&quot;
  12462. },
  12463. {
  12464. &quot;ip&quot;: &quot;1.2.3.10&quot;,
  12465. &quot;last_seen&quot;: 1417222374500,
  12466. &quot;user_agent&quot;: &quot;Dalvik/2.1.0 ...&quot;
  12467. }
  12468. ]
  12469. }
  12470. ]
  12471. }
  12472. }
  12473. }
  12474. </code></pre>
  12475. <p><code>last_seen</code> is measured in milliseconds since the Unix epoch.</p>
  12476. <h2 id="deactivate-account"><a class="header" href="#deactivate-account">Deactivate Account</a></h2>
  12477. <p>This API deactivates an account. It removes active access tokens, resets the
  12478. password, and deletes third-party IDs (to prevent the user requesting a
  12479. password reset).</p>
  12480. <p>It can also mark the user as GDPR-erased. This means messages sent by the
  12481. user will still be visible by anyone that was in the room when these messages
  12482. were sent, but hidden from users joining the room afterwards.</p>
  12483. <p>The api is:</p>
  12484. <pre><code>POST /_synapse/admin/v1/deactivate/&lt;user_id&gt;
  12485. </code></pre>
  12486. <p>with a body of:</p>
  12487. <pre><code class="language-json">{
  12488. &quot;erase&quot;: true
  12489. }
  12490. </code></pre>
  12491. <p>The erase parameter is optional and defaults to <code>false</code>.
  12492. An empty body may be passed for backwards compatibility.</p>
  12493. <p>The following actions are performed when deactivating an user:</p>
  12494. <ul>
  12495. <li>Try to unbind 3PIDs from the identity server</li>
  12496. <li>Remove all 3PIDs from the homeserver</li>
  12497. <li>Delete all devices and E2EE keys</li>
  12498. <li>Delete all access tokens</li>
  12499. <li>Delete all pushers</li>
  12500. <li>Delete the password hash</li>
  12501. <li>Removal from all rooms the user is a member of</li>
  12502. <li>Remove the user from the user directory</li>
  12503. <li>Reject all pending invites</li>
  12504. <li>Remove all account validity information related to the user</li>
  12505. <li>Remove the arbitrary data store known as <em>account data</em>. For example, this includes:
  12506. <ul>
  12507. <li>list of ignored users;</li>
  12508. <li>push rules;</li>
  12509. <li>secret storage keys; and</li>
  12510. <li>cross-signing keys.</li>
  12511. </ul>
  12512. </li>
  12513. </ul>
  12514. <p>The following additional actions are performed during deactivation if <code>erase</code>
  12515. is set to <code>true</code>:</p>
  12516. <ul>
  12517. <li>Remove the user's display name</li>
  12518. <li>Remove the user's avatar URL</li>
  12519. <li>Mark the user as erased</li>
  12520. </ul>
  12521. <p>The following actions are <strong>NOT</strong> performed. The list may be incomplete.</p>
  12522. <ul>
  12523. <li>Remove mappings of SSO IDs</li>
  12524. <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>
  12525. <li>Delete sent and received messages</li>
  12526. <li>Remove the user's creation (registration) timestamp</li>
  12527. <li><a href="admin_api/user_admin_api.html#override-ratelimiting-for-users">Remove rate limit overrides</a></li>
  12528. <li>Remove from monthly active users</li>
  12529. <li>Remove user's consent information (consent version and timestamp)</li>
  12530. </ul>
  12531. <h2 id="reset-password"><a class="header" href="#reset-password">Reset password</a></h2>
  12532. <p>Changes the password of another user. This will automatically log the user out of all their devices.</p>
  12533. <p>The api is:</p>
  12534. <pre><code>POST /_synapse/admin/v1/reset_password/&lt;user_id&gt;
  12535. </code></pre>
  12536. <p>with a body of:</p>
  12537. <pre><code class="language-json">{
  12538. &quot;new_password&quot;: &quot;&lt;secret&gt;&quot;,
  12539. &quot;logout_devices&quot;: true
  12540. }
  12541. </code></pre>
  12542. <p>The parameter <code>new_password</code> is required.
  12543. The parameter <code>logout_devices</code> is optional and defaults to <code>true</code>.</p>
  12544. <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>
  12545. <p>The api is:</p>
  12546. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  12547. </code></pre>
  12548. <p>A response body like the following is returned:</p>
  12549. <pre><code class="language-json">{
  12550. &quot;admin&quot;: true
  12551. }
  12552. </code></pre>
  12553. <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>
  12554. <p>Note that you cannot demote yourself.</p>
  12555. <p>The api is:</p>
  12556. <pre><code>PUT /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  12557. </code></pre>
  12558. <p>with a body of:</p>
  12559. <pre><code class="language-json">{
  12560. &quot;admin&quot;: true
  12561. }
  12562. </code></pre>
  12563. <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>
  12564. <p>Gets a list of all <code>room_id</code> that a specific <code>user_id</code> is member.</p>
  12565. <p>The API is:</p>
  12566. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/joined_rooms
  12567. </code></pre>
  12568. <p>A response body like the following is returned:</p>
  12569. <pre><code class="language-json"> {
  12570. &quot;joined_rooms&quot;: [
  12571. &quot;!DuGcnbhHGaSZQoNQR:matrix.org&quot;,
  12572. &quot;!ZtSaPCawyWtxfWiIy:matrix.org&quot;
  12573. ],
  12574. &quot;total&quot;: 2
  12575. }
  12576. </code></pre>
  12577. <p>The server returns the list of rooms of which the user and the server
  12578. are member. If the user is local, all the rooms of which the user is
  12579. member are returned.</p>
  12580. <p><strong>Parameters</strong></p>
  12581. <p>The following parameters should be set in the URL:</p>
  12582. <ul>
  12583. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12584. </ul>
  12585. <p><strong>Response</strong></p>
  12586. <p>The following fields are returned in the JSON response body:</p>
  12587. <ul>
  12588. <li><code>joined_rooms</code> - An array of <code>room_id</code>.</li>
  12589. <li><code>total</code> - Number of rooms.</li>
  12590. </ul>
  12591. <h2 id="account-data"><a class="header" href="#account-data">Account Data</a></h2>
  12592. <p>Gets information about account data for a specific <code>user_id</code>.</p>
  12593. <p>The API is:</p>
  12594. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/accountdata
  12595. </code></pre>
  12596. <p>A response body like the following is returned:</p>
  12597. <pre><code class="language-json">{
  12598. &quot;account_data&quot;: {
  12599. &quot;global&quot;: {
  12600. &quot;m.secret_storage.key.LmIGHTg5W&quot;: {
  12601. &quot;algorithm&quot;: &quot;m.secret_storage.v1.aes-hmac-sha2&quot;,
  12602. &quot;iv&quot;: &quot;fwjNZatxg==&quot;,
  12603. &quot;mac&quot;: &quot;eWh9kNnLWZUNOgnc=&quot;
  12604. },
  12605. &quot;im.vector.hide_profile&quot;: {
  12606. &quot;hide_profile&quot;: true
  12607. },
  12608. &quot;org.matrix.preview_urls&quot;: {
  12609. &quot;disable&quot;: false
  12610. },
  12611. &quot;im.vector.riot.breadcrumb_rooms&quot;: {
  12612. &quot;rooms&quot;: [
  12613. &quot;!LxcBDAsDUVAfJDEo:matrix.org&quot;,
  12614. &quot;!MAhRxqasbItjOqxu:matrix.org&quot;
  12615. ]
  12616. },
  12617. &quot;m.accepted_terms&quot;: {
  12618. &quot;accepted&quot;: [
  12619. &quot;https://example.org/somewhere/privacy-1.2-en.html&quot;,
  12620. &quot;https://example.org/somewhere/terms-2.0-en.html&quot;
  12621. ]
  12622. },
  12623. &quot;im.vector.setting.breadcrumbs&quot;: {
  12624. &quot;recent_rooms&quot;: [
  12625. &quot;!MAhRxqasbItqxuEt:matrix.org&quot;,
  12626. &quot;!ZtSaPCawyWtxiImy:matrix.org&quot;
  12627. ]
  12628. }
  12629. },
  12630. &quot;rooms&quot;: {
  12631. &quot;!GUdfZSHUJibpiVqHYd:matrix.org&quot;: {
  12632. &quot;m.fully_read&quot;: {
  12633. &quot;event_id&quot;: &quot;$156334540fYIhZ:matrix.org&quot;
  12634. }
  12635. },
  12636. &quot;!tOZwOOiqwCYQkLhV:matrix.org&quot;: {
  12637. &quot;m.fully_read&quot;: {
  12638. &quot;event_id&quot;: &quot;$xjsIyp4_NaVl2yPvIZs_k1Jl8tsC_Sp23wjqXPno&quot;
  12639. }
  12640. }
  12641. }
  12642. }
  12643. }
  12644. </code></pre>
  12645. <p><strong>Parameters</strong></p>
  12646. <p>The following parameters should be set in the URL:</p>
  12647. <ul>
  12648. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12649. </ul>
  12650. <p><strong>Response</strong></p>
  12651. <p>The following fields are returned in the JSON response body:</p>
  12652. <ul>
  12653. <li><code>account_data</code> - A map containing the account data for the user
  12654. <ul>
  12655. <li><code>global</code> - A map containing the global account data for the user</li>
  12656. <li><code>rooms</code> - A map containing the account data per room for the user</li>
  12657. </ul>
  12658. </li>
  12659. </ul>
  12660. <h2 id="user-media"><a class="header" href="#user-media">User media</a></h2>
  12661. <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>
  12662. <p>Gets a list of all local media that a specific <code>user_id</code> has created.
  12663. These are media that the user has uploaded themselves
  12664. (<a href="admin_api/../media_repository.html#local-media">local media</a>), as well as
  12665. <a href="admin_api/../media_repository.html#url-previews">URL preview images</a> requested by the user if the
  12666. <a href="admin_api/../usage/configuration/config_documentation.html#url_preview_enabled">feature is enabled</a>.</p>
  12667. <p>By default, the response is ordered by descending creation date and ascending media ID.
  12668. The newest media is on top. You can change the order with parameters
  12669. <code>order_by</code> and <code>dir</code>.</p>
  12670. <p>The API is:</p>
  12671. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/media
  12672. </code></pre>
  12673. <p>A response body like the following is returned:</p>
  12674. <pre><code class="language-json">{
  12675. &quot;media&quot;: [
  12676. {
  12677. &quot;created_ts&quot;: 100400,
  12678. &quot;last_access_ts&quot;: null,
  12679. &quot;media_id&quot;: &quot;qXhyRzulkwLsNHTbpHreuEgo&quot;,
  12680. &quot;media_length&quot;: 67,
  12681. &quot;media_type&quot;: &quot;image/png&quot;,
  12682. &quot;quarantined_by&quot;: null,
  12683. &quot;safe_from_quarantine&quot;: false,
  12684. &quot;upload_name&quot;: &quot;test1.png&quot;
  12685. },
  12686. {
  12687. &quot;created_ts&quot;: 200400,
  12688. &quot;last_access_ts&quot;: null,
  12689. &quot;media_id&quot;: &quot;FHfiSnzoINDatrXHQIXBtahw&quot;,
  12690. &quot;media_length&quot;: 67,
  12691. &quot;media_type&quot;: &quot;image/png&quot;,
  12692. &quot;quarantined_by&quot;: null,
  12693. &quot;safe_from_quarantine&quot;: false,
  12694. &quot;upload_name&quot;: &quot;test2.png&quot;
  12695. }
  12696. ],
  12697. &quot;next_token&quot;: 3,
  12698. &quot;total&quot;: 2
  12699. }
  12700. </code></pre>
  12701. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  12702. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  12703. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  12704. reports to paginate through.</p>
  12705. <p><strong>Parameters</strong></p>
  12706. <p>The following parameters should be set in the URL:</p>
  12707. <ul>
  12708. <li>
  12709. <p><code>user_id</code> - string - fully qualified: for example, <code>@user:server.com</code>.</p>
  12710. </li>
  12711. <li>
  12712. <p><code>limit</code>: string representing a positive integer - Is optional but is used for pagination,
  12713. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  12714. </li>
  12715. <li>
  12716. <p><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  12717. denoting the offset in the returned results. This should be treated as an opaque value and
  12718. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  12719. Defaults to <code>0</code>.</p>
  12720. </li>
  12721. <li>
  12722. <p><code>order_by</code> - The method by which to sort the returned list of media.
  12723. If the ordered field has duplicates, the second order is always by ascending <code>media_id</code>,
  12724. which guarantees a stable ordering. Valid values are:</p>
  12725. <ul>
  12726. <li><code>media_id</code> - Media are ordered alphabetically by <code>media_id</code>.</li>
  12727. <li><code>upload_name</code> - Media are ordered alphabetically by name the media was uploaded with.</li>
  12728. <li><code>created_ts</code> - Media are ordered by when the content was uploaded in ms.
  12729. Smallest to largest. This is the default.</li>
  12730. <li><code>last_access_ts</code> - Media are ordered by when the content was last accessed in ms.
  12731. Smallest to largest.</li>
  12732. <li><code>media_length</code> - Media are ordered by length of the media in bytes.
  12733. Smallest to largest.</li>
  12734. <li><code>media_type</code> - Media are ordered alphabetically by MIME-type.</li>
  12735. <li><code>quarantined_by</code> - Media are ordered alphabetically by the user ID that
  12736. initiated the quarantine request for this media.</li>
  12737. <li><code>safe_from_quarantine</code> - Media are ordered by the status if this media is safe
  12738. from quarantining.</li>
  12739. </ul>
  12740. </li>
  12741. <li>
  12742. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  12743. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  12744. </li>
  12745. </ul>
  12746. <p>If neither <code>order_by</code> nor <code>dir</code> is set, the default order is newest media on top
  12747. (corresponds to <code>order_by</code> = <code>created_ts</code> and <code>dir</code> = <code>b</code>).</p>
  12748. <p>Caution. The database only has indexes on the columns <code>media_id</code>,
  12749. <code>user_id</code> and <code>created_ts</code>. This means that if a different sort order is used
  12750. (<code>upload_name</code>, <code>last_access_ts</code>, <code>media_length</code>, <code>media_type</code>,
  12751. <code>quarantined_by</code> or <code>safe_from_quarantine</code>), this can cause a large load on the
  12752. database, especially for large environments.</p>
  12753. <p><strong>Response</strong></p>
  12754. <p>The following fields are returned in the JSON response body:</p>
  12755. <ul>
  12756. <li><code>media</code> - An array of objects, each containing information about a media.
  12757. Media objects contain the following fields:
  12758. <ul>
  12759. <li><code>created_ts</code> - integer - Timestamp when the content was uploaded in ms.</li>
  12760. <li><code>last_access_ts</code> - integer - Timestamp when the content was last accessed in ms.</li>
  12761. <li><code>media_id</code> - string - The id used to refer to the media. Details about the format
  12762. are documented under
  12763. <a href="admin_api/../media_repository.html">media repository</a>.</li>
  12764. <li><code>media_length</code> - integer - Length of the media in bytes.</li>
  12765. <li><code>media_type</code> - string - The MIME-type of the media.</li>
  12766. <li><code>quarantined_by</code> - string - The user ID that initiated the quarantine request
  12767. for this media.</li>
  12768. <li><code>safe_from_quarantine</code> - bool - Status if this media is safe from quarantining.</li>
  12769. <li><code>upload_name</code> - string - The name the media was uploaded with.</li>
  12770. </ul>
  12771. </li>
  12772. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  12773. <li><code>total</code> - integer - Total number of media.</li>
  12774. </ul>
  12775. <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>
  12776. <p>This API deletes the <em>local</em> media from the disk of your own server
  12777. that a specific <code>user_id</code> has created. This includes any local thumbnails.</p>
  12778. <p>This API will not affect media that has been uploaded to external
  12779. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).</p>
  12780. <p>By default, the API deletes media ordered by descending creation date and ascending media ID.
  12781. The newest media is deleted first. You can change the order with parameters
  12782. <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>
  12783. <p>The API is:</p>
  12784. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/media
  12785. </code></pre>
  12786. <p>A response body like the following is returned:</p>
  12787. <pre><code class="language-json">{
  12788. &quot;deleted_media&quot;: [
  12789. &quot;abcdefghijklmnopqrstuvwx&quot;
  12790. ],
  12791. &quot;total&quot;: 1
  12792. }
  12793. </code></pre>
  12794. <p>The following fields are returned in the JSON response body:</p>
  12795. <ul>
  12796. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  12797. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  12798. </ul>
  12799. <p><strong>Note</strong>: There is no <code>next_token</code>. This is not useful for deleting media, because
  12800. after deleting media the remaining media have a new order.</p>
  12801. <p><strong>Parameters</strong></p>
  12802. <p>This API has the same parameters as
  12803. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>.
  12804. With the parameters you can for example limit the number of files to delete at once or
  12805. delete largest/smallest or newest/oldest files first.</p>
  12806. <h2 id="login-as-a-user"><a class="header" href="#login-as-a-user">Login as a user</a></h2>
  12807. <p>Get an access token that can be used to authenticate as that user. Useful for
  12808. when admins wish to do actions on behalf of a user.</p>
  12809. <p>The API is:</p>
  12810. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/login
  12811. {}
  12812. </code></pre>
  12813. <p>An optional <code>valid_until_ms</code> field can be specified in the request body as an
  12814. integer timestamp that specifies when the token should expire. By default tokens
  12815. do not expire.</p>
  12816. <p>A response body like the following is returned:</p>
  12817. <pre><code class="language-json">{
  12818. &quot;access_token&quot;: &quot;&lt;opaque_access_token_string&gt;&quot;
  12819. }
  12820. </code></pre>
  12821. <p>This API does <em>not</em> generate a new device for the user, and so will not appear
  12822. their <code>/devices</code> list, and in general the target user should not be able to
  12823. tell they have been logged in as.</p>
  12824. <p>To expire the token call the standard <code>/logout</code> API with the token.</p>
  12825. <p>Note: The token will expire if the <em>admin</em> user calls <code>/logout/all</code> from any
  12826. of their devices, but the token will <em>not</em> expire if the target user does the
  12827. same.</p>
  12828. <h2 id="user-devices"><a class="header" href="#user-devices">User devices</a></h2>
  12829. <h3 id="list-all-devices"><a class="header" href="#list-all-devices">List all devices</a></h3>
  12830. <p>Gets information about all devices for a specific <code>user_id</code>.</p>
  12831. <p>The API is:</p>
  12832. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices
  12833. </code></pre>
  12834. <p>A response body like the following is returned:</p>
  12835. <pre><code class="language-json">{
  12836. &quot;devices&quot;: [
  12837. {
  12838. &quot;device_id&quot;: &quot;QBUAZIFURK&quot;,
  12839. &quot;display_name&quot;: &quot;android&quot;,
  12840. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  12841. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  12842. &quot;last_seen_ts&quot;: 1474491775024,
  12843. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  12844. },
  12845. {
  12846. &quot;device_id&quot;: &quot;AUIECTSRND&quot;,
  12847. &quot;display_name&quot;: &quot;ios&quot;,
  12848. &quot;last_seen_ip&quot;: &quot;1.2.3.5&quot;,
  12849. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  12850. &quot;last_seen_ts&quot;: 1474491775025,
  12851. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  12852. }
  12853. ],
  12854. &quot;total&quot;: 2
  12855. }
  12856. </code></pre>
  12857. <p><strong>Parameters</strong></p>
  12858. <p>The following parameters should be set in the URL:</p>
  12859. <ul>
  12860. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12861. </ul>
  12862. <p><strong>Response</strong></p>
  12863. <p>The following fields are returned in the JSON response body:</p>
  12864. <ul>
  12865. <li>
  12866. <p><code>devices</code> - An array of objects, each containing information about a device.
  12867. Device objects contain the following fields:</p>
  12868. <ul>
  12869. <li><code>device_id</code> - Identifier of device.</li>
  12870. <li><code>display_name</code> - Display name set by the user for this device.
  12871. Absent if no name has been set.</li>
  12872. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  12873. (May be a few minutes out of date, for efficiency reasons).</li>
  12874. <li><code>last_seen_user_agent</code> - The user agent of the device when it was last seen.
  12875. (May be a few minutes out of date, for efficiency reasons).</li>
  12876. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  12877. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  12878. <li><code>user_id</code> - Owner of device.</li>
  12879. </ul>
  12880. </li>
  12881. <li>
  12882. <p><code>total</code> - Total number of user's devices.</p>
  12883. </li>
  12884. </ul>
  12885. <h3 id="delete-multiple-devices"><a class="header" href="#delete-multiple-devices">Delete multiple devices</a></h3>
  12886. <p>Deletes the given devices for a specific <code>user_id</code>, and invalidates
  12887. any access token associated with them.</p>
  12888. <p>The API is:</p>
  12889. <pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/delete_devices
  12890. {
  12891. &quot;devices&quot;: [
  12892. &quot;QBUAZIFURK&quot;,
  12893. &quot;AUIECTSRND&quot;
  12894. ]
  12895. }
  12896. </code></pre>
  12897. <p>An empty JSON dict is returned.</p>
  12898. <p><strong>Parameters</strong></p>
  12899. <p>The following parameters should be set in the URL:</p>
  12900. <ul>
  12901. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12902. </ul>
  12903. <p>The following fields are required in the JSON request body:</p>
  12904. <ul>
  12905. <li><code>devices</code> - The list of device IDs to delete.</li>
  12906. </ul>
  12907. <h3 id="show-a-device"><a class="header" href="#show-a-device">Show a device</a></h3>
  12908. <p>Gets information on a single device, by <code>device_id</code> for a specific <code>user_id</code>.</p>
  12909. <p>The API is:</p>
  12910. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  12911. </code></pre>
  12912. <p>A response body like the following is returned:</p>
  12913. <pre><code class="language-json">{
  12914. &quot;device_id&quot;: &quot;&lt;device_id&gt;&quot;,
  12915. &quot;display_name&quot;: &quot;android&quot;,
  12916. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  12917. &quot;last_seen_user_agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0&quot;,
  12918. &quot;last_seen_ts&quot;: 1474491775024,
  12919. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  12920. }
  12921. </code></pre>
  12922. <p><strong>Parameters</strong></p>
  12923. <p>The following parameters should be set in the URL:</p>
  12924. <ul>
  12925. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12926. <li><code>device_id</code> - The device to retrieve.</li>
  12927. </ul>
  12928. <p><strong>Response</strong></p>
  12929. <p>The following fields are returned in the JSON response body:</p>
  12930. <ul>
  12931. <li><code>device_id</code> - Identifier of device.</li>
  12932. <li><code>display_name</code> - Display name set by the user for this device.
  12933. Absent if no name has been set.</li>
  12934. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  12935. (May be a few minutes out of date, for efficiency reasons).
  12936. <ul>
  12937. <li><code>last_seen_user_agent</code> - The user agent of the device when it was last seen.
  12938. (May be a few minutes out of date, for efficiency reasons).</li>
  12939. </ul>
  12940. </li>
  12941. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  12942. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  12943. <li><code>user_id</code> - Owner of device.</li>
  12944. </ul>
  12945. <h3 id="update-a-device"><a class="header" href="#update-a-device">Update a device</a></h3>
  12946. <p>Updates the metadata on the given <code>device_id</code> for a specific <code>user_id</code>.</p>
  12947. <p>The API is:</p>
  12948. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  12949. {
  12950. &quot;display_name&quot;: &quot;My other phone&quot;
  12951. }
  12952. </code></pre>
  12953. <p>An empty JSON dict is returned.</p>
  12954. <p><strong>Parameters</strong></p>
  12955. <p>The following parameters should be set in the URL:</p>
  12956. <ul>
  12957. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12958. <li><code>device_id</code> - The device to update.</li>
  12959. </ul>
  12960. <p>The following fields are required in the JSON request body:</p>
  12961. <ul>
  12962. <li><code>display_name</code> - The new display name for this device. If not given,
  12963. the display name is unchanged.</li>
  12964. </ul>
  12965. <h3 id="delete-a-device"><a class="header" href="#delete-a-device">Delete a device</a></h3>
  12966. <p>Deletes the given <code>device_id</code> for a specific <code>user_id</code>,
  12967. and invalidates any access token associated with it.</p>
  12968. <p>The API is:</p>
  12969. <pre><code>DELETE /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  12970. {}
  12971. </code></pre>
  12972. <p>An empty JSON dict is returned.</p>
  12973. <p><strong>Parameters</strong></p>
  12974. <p>The following parameters should be set in the URL:</p>
  12975. <ul>
  12976. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12977. <li><code>device_id</code> - The device to delete.</li>
  12978. </ul>
  12979. <h2 id="list-all-pushers"><a class="header" href="#list-all-pushers">List all pushers</a></h2>
  12980. <p>Gets information about all pushers for a specific <code>user_id</code>.</p>
  12981. <p>The API is:</p>
  12982. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/pushers
  12983. </code></pre>
  12984. <p>A response body like the following is returned:</p>
  12985. <pre><code class="language-json">{
  12986. &quot;pushers&quot;: [
  12987. {
  12988. &quot;app_display_name&quot;:&quot;HTTP Push Notifications&quot;,
  12989. &quot;app_id&quot;:&quot;m.http&quot;,
  12990. &quot;data&quot;: {
  12991. &quot;url&quot;:&quot;example.com&quot;
  12992. },
  12993. &quot;device_display_name&quot;:&quot;pushy push&quot;,
  12994. &quot;kind&quot;:&quot;http&quot;,
  12995. &quot;lang&quot;:&quot;None&quot;,
  12996. &quot;profile_tag&quot;:&quot;&quot;,
  12997. &quot;pushkey&quot;:&quot;a@example.com&quot;
  12998. }
  12999. ],
  13000. &quot;total&quot;: 1
  13001. }
  13002. </code></pre>
  13003. <p><strong>Parameters</strong></p>
  13004. <p>The following parameters should be set in the URL:</p>
  13005. <ul>
  13006. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  13007. </ul>
  13008. <p><strong>Response</strong></p>
  13009. <p>The following fields are returned in the JSON response body:</p>
  13010. <ul>
  13011. <li>
  13012. <p><code>pushers</code> - An array containing the current pushers for the user</p>
  13013. <ul>
  13014. <li>
  13015. <p><code>app_display_name</code> - string - A string that will allow the user to identify
  13016. what application owns this pusher.</p>
  13017. </li>
  13018. <li>
  13019. <p><code>app_id</code> - string - This is a reverse-DNS style identifier for the application.
  13020. Max length, 64 chars.</p>
  13021. </li>
  13022. <li>
  13023. <p><code>data</code> - A dictionary of information for the pusher implementation itself.</p>
  13024. <ul>
  13025. <li>
  13026. <p><code>url</code> - string - Required if <code>kind</code> is <code>http</code>. The URL to use to send
  13027. notifications to.</p>
  13028. </li>
  13029. <li>
  13030. <p><code>format</code> - string - The format to use when sending notifications to the
  13031. Push Gateway.</p>
  13032. </li>
  13033. </ul>
  13034. </li>
  13035. <li>
  13036. <p><code>device_display_name</code> - string - A string that will allow the user to identify
  13037. what device owns this pusher.</p>
  13038. </li>
  13039. <li>
  13040. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  13041. this pusher executes.</p>
  13042. </li>
  13043. <li>
  13044. <p><code>kind</code> - string - The kind of pusher. &quot;http&quot; is a pusher that sends HTTP pokes.</p>
  13045. </li>
  13046. <li>
  13047. <p><code>lang</code> - string - The preferred language for receiving notifications
  13048. (e.g. 'en' or 'en-US')</p>
  13049. </li>
  13050. <li>
  13051. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  13052. this pusher executes.</p>
  13053. </li>
  13054. <li>
  13055. <p><code>pushkey</code> - string - This is a unique identifier for this pusher.
  13056. Max length, 512 bytes.</p>
  13057. </li>
  13058. </ul>
  13059. </li>
  13060. <li>
  13061. <p><code>total</code> - integer - Number of pushers.</p>
  13062. </li>
  13063. </ul>
  13064. <p>See also the
  13065. <a href="https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-pushers">Client-Server API Spec on pushers</a>.</p>
  13066. <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>
  13067. <p>Shadow-banning is a useful tool for moderating malicious or egregiously abusive users.
  13068. A shadow-banned users receives successful responses to their client-server API requests,
  13069. but the events are not propagated into rooms. This can be an effective tool as it
  13070. (hopefully) takes longer for the user to realise they are being moderated before
  13071. pivoting to another account.</p>
  13072. <p>Shadow-banning a user should be used as a tool of last resort and may lead to confusing
  13073. or broken behaviour for the client. A shadow-banned user will not receive any
  13074. notification and it is generally more appropriate to ban or kick abusive users.
  13075. A shadow-banned user will be unable to contact anyone on the server.</p>
  13076. <p>To shadow-ban a user the API is:</p>
  13077. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  13078. </code></pre>
  13079. <p>To un-shadow-ban a user the API is:</p>
  13080. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  13081. </code></pre>
  13082. <p>An empty JSON dict is returned in both cases.</p>
  13083. <p><strong>Parameters</strong></p>
  13084. <p>The following parameters should be set in the URL:</p>
  13085. <ul>
  13086. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  13087. be local.</li>
  13088. </ul>
  13089. <h2 id="override-ratelimiting-for-users"><a class="header" href="#override-ratelimiting-for-users">Override ratelimiting for users</a></h2>
  13090. <p>This API allows to override or disable ratelimiting for a specific user.
  13091. There are specific APIs to set, get and delete a ratelimit.</p>
  13092. <h3 id="get-status-of-ratelimit"><a class="header" href="#get-status-of-ratelimit">Get status of ratelimit</a></h3>
  13093. <p>The API is:</p>
  13094. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  13095. </code></pre>
  13096. <p>A response body like the following is returned:</p>
  13097. <pre><code class="language-json">{
  13098. &quot;messages_per_second&quot;: 0,
  13099. &quot;burst_count&quot;: 0
  13100. }
  13101. </code></pre>
  13102. <p><strong>Parameters</strong></p>
  13103. <p>The following parameters should be set in the URL:</p>
  13104. <ul>
  13105. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  13106. be local.</li>
  13107. </ul>
  13108. <p><strong>Response</strong></p>
  13109. <p>The following fields are returned in the JSON response body:</p>
  13110. <ul>
  13111. <li><code>messages_per_second</code> - integer - The number of actions that can
  13112. be performed in a second. <code>0</code> mean that ratelimiting is disabled for this user.</li>
  13113. <li><code>burst_count</code> - integer - How many actions that can be performed before
  13114. being limited.</li>
  13115. </ul>
  13116. <p>If <strong>no</strong> custom ratelimit is set, an empty JSON dict is returned.</p>
  13117. <pre><code class="language-json">{}
  13118. </code></pre>
  13119. <h3 id="set-ratelimit"><a class="header" href="#set-ratelimit">Set ratelimit</a></h3>
  13120. <p>The API is:</p>
  13121. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  13122. </code></pre>
  13123. <p>A response body like the following is returned:</p>
  13124. <pre><code class="language-json">{
  13125. &quot;messages_per_second&quot;: 0,
  13126. &quot;burst_count&quot;: 0
  13127. }
  13128. </code></pre>
  13129. <p><strong>Parameters</strong></p>
  13130. <p>The following parameters should be set in the URL:</p>
  13131. <ul>
  13132. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  13133. be local.</li>
  13134. </ul>
  13135. <p>Body parameters:</p>
  13136. <ul>
  13137. <li><code>messages_per_second</code> - positive integer, optional. The number of actions that can
  13138. be performed in a second. Defaults to <code>0</code>.</li>
  13139. <li><code>burst_count</code> - positive integer, optional. How many actions that can be performed
  13140. before being limited. Defaults to <code>0</code>.</li>
  13141. </ul>
  13142. <p>To disable users' ratelimit set both values to <code>0</code>.</p>
  13143. <p><strong>Response</strong></p>
  13144. <p>The following fields are returned in the JSON response body:</p>
  13145. <ul>
  13146. <li><code>messages_per_second</code> - integer - The number of actions that can
  13147. be performed in a second.</li>
  13148. <li><code>burst_count</code> - integer - How many actions that can be performed before
  13149. being limited.</li>
  13150. </ul>
  13151. <h3 id="delete-ratelimit"><a class="header" href="#delete-ratelimit">Delete ratelimit</a></h3>
  13152. <p>The API is:</p>
  13153. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  13154. </code></pre>
  13155. <p>An empty JSON dict is returned.</p>
  13156. <pre><code class="language-json">{}
  13157. </code></pre>
  13158. <p><strong>Parameters</strong></p>
  13159. <p>The following parameters should be set in the URL:</p>
  13160. <ul>
  13161. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  13162. be local.</li>
  13163. </ul>
  13164. <h3 id="check-username-availability"><a class="header" href="#check-username-availability">Check username availability</a></h3>
  13165. <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
  13166. API</a>
  13167. for more information.</p>
  13168. <p>This endpoint will work even if registration is disabled on the server, unlike
  13169. <code>/_matrix/client/r0/register/available</code>.</p>
  13170. <p>The API is:</p>
  13171. <pre><code>GET /_synapse/admin/v1/username_available?username=$localpart
  13172. </code></pre>
  13173. <p>The request and response format is the same as the
  13174. <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>
  13175. <h3 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></h3>
  13176. <p>The API is:</p>
  13177. <pre><code>GET /_synapse/admin/v1/auth_providers/$provider/users/$external_id
  13178. </code></pre>
  13179. <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>
  13180. <pre><code class="language-json">{
  13181. &quot;user_id&quot;: &quot;@hello:example.org&quot;
  13182. }
  13183. </code></pre>
  13184. <p><strong>Parameters</strong></p>
  13185. <p>The following parameters should be set in the URL:</p>
  13186. <ul>
  13187. <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>
  13188. <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>
  13189. </ul>
  13190. <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>
  13191. <p><strong>Errors</strong></p>
  13192. <p>Returns a <code>404</code> HTTP status code if no user was found, with a response body like this:</p>
  13193. <pre><code class="language-json">{
  13194. &quot;errcode&quot;:&quot;M_NOT_FOUND&quot;,
  13195. &quot;error&quot;:&quot;User not found&quot;
  13196. }
  13197. </code></pre>
  13198. <p><em>Added in Synapse 1.68.0.</em></p>
  13199. <div style="break-before: page; page-break-before: always;"></div><h1 id="version-api"><a class="header" href="#version-api">Version API</a></h1>
  13200. <p>This API returns the running Synapse version and the Python version
  13201. on which Synapse is being run. This is useful when a Synapse instance
  13202. is behind a proxy that does not forward the 'Server' header (which also
  13203. contains Synapse version information).</p>
  13204. <p>The api is:</p>
  13205. <pre><code>GET /_synapse/admin/v1/server_version
  13206. </code></pre>
  13207. <p>It returns a JSON body like the following:</p>
  13208. <pre><code class="language-json">{
  13209. &quot;server_version&quot;: &quot;0.99.2rc1 (b=develop, abcdef123)&quot;,
  13210. &quot;python_version&quot;: &quot;3.7.8&quot;
  13211. }
  13212. </code></pre>
  13213. <div style="break-before: page; page-break-before: always;"></div><h1 id="federation-api"><a class="header" href="#federation-api">Federation API</a></h1>
  13214. <p>This API allows a server administrator to manage Synapse's federation with other homeservers.</p>
  13215. <p>Note: This API is new, experimental and &quot;subject to change&quot;.</p>
  13216. <h2 id="list-of-destinations"><a class="header" href="#list-of-destinations">List of destinations</a></h2>
  13217. <p>This API gets the current destination retry timing info for all remote servers.</p>
  13218. <p>The list contains all the servers with which the server federates,
  13219. regardless of whether an error occurred or not.
  13220. If an error occurs, it may take up to 20 minutes for the error to be displayed here,
  13221. as a complete retry must have failed.</p>
  13222. <p>The API is:</p>
  13223. <p>A standard request with no filtering:</p>
  13224. <pre><code>GET /_synapse/admin/v1/federation/destinations
  13225. </code></pre>
  13226. <p>A response body like the following is returned:</p>
  13227. <pre><code class="language-json">{
  13228. &quot;destinations&quot;:[
  13229. {
  13230. &quot;destination&quot;: &quot;matrix.org&quot;,
  13231. &quot;retry_last_ts&quot;: 1557332397936,
  13232. &quot;retry_interval&quot;: 3000000,
  13233. &quot;failure_ts&quot;: 1557329397936,
  13234. &quot;last_successful_stream_ordering&quot;: null
  13235. }
  13236. ],
  13237. &quot;total&quot;: 1
  13238. }
  13239. </code></pre>
  13240. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  13241. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  13242. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  13243. to paginate through.</p>
  13244. <p><strong>Parameters</strong></p>
  13245. <p>The following query parameters are available:</p>
  13246. <ul>
  13247. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  13248. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  13249. <li><code>order_by</code> - The method in which to sort the returned list of destinations.
  13250. Valid values are:
  13251. <ul>
  13252. <li><code>destination</code> - Destinations are ordered alphabetically by remote server name.
  13253. This is the default.</li>
  13254. <li><code>retry_last_ts</code> - Destinations are ordered by time of last retry attempt in ms.</li>
  13255. <li><code>retry_interval</code> - Destinations are ordered by how long until next retry in ms.</li>
  13256. <li><code>failure_ts</code> - Destinations are ordered by when the server started failing in ms.</li>
  13257. <li><code>last_successful_stream_ordering</code> - Destinations are ordered by the stream ordering
  13258. of the most recent successfully-sent PDU.</li>
  13259. </ul>
  13260. </li>
  13261. <li><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  13262. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  13263. </ul>
  13264. <p><em>Caution:</em> The database only has an index on the column <code>destination</code>.
  13265. This means that if a different sort order is used,
  13266. this can cause a large load on the database, especially for large environments.</p>
  13267. <p><strong>Response</strong></p>
  13268. <p>The following fields are returned in the JSON response body:</p>
  13269. <ul>
  13270. <li><code>destinations</code> - An array of objects, each containing information about a destination.
  13271. Destination objects contain the following fields:
  13272. <ul>
  13273. <li><code>destination</code> - string - Name of the remote server to federate.</li>
  13274. <li><code>retry_last_ts</code> - integer - The last time Synapse tried and failed to reach the
  13275. remote server, in ms. This is <code>0</code> if the last attempt to communicate with the
  13276. remote server was successful.</li>
  13277. <li><code>retry_interval</code> - integer - How long since the last time Synapse tried to reach
  13278. the remote server before trying again, in ms. This is <code>0</code> if no further retrying occuring.</li>
  13279. <li><code>failure_ts</code> - nullable integer - The first time Synapse tried and failed to reach the
  13280. remote server, in ms. This is <code>null</code> if communication with the remote server has never failed.</li>
  13281. <li><code>last_successful_stream_ordering</code> - nullable integer - The stream ordering of the most
  13282. recent successfully-sent <a href="usage/administration/admin_api/understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  13283. to this destination, or <code>null</code> if this information has not been tracked yet.</li>
  13284. </ul>
  13285. </li>
  13286. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  13287. <li><code>total</code> - integer - Total number of destinations.</li>
  13288. </ul>
  13289. <h2 id="destination-details-api"><a class="header" href="#destination-details-api">Destination Details API</a></h2>
  13290. <p>This API gets the retry timing info for a specific remote server.</p>
  13291. <p>The API is:</p>
  13292. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;
  13293. </code></pre>
  13294. <p>A response body like the following is returned:</p>
  13295. <pre><code class="language-json">{
  13296. &quot;destination&quot;: &quot;matrix.org&quot;,
  13297. &quot;retry_last_ts&quot;: 1557332397936,
  13298. &quot;retry_interval&quot;: 3000000,
  13299. &quot;failure_ts&quot;: 1557329397936,
  13300. &quot;last_successful_stream_ordering&quot;: null
  13301. }
  13302. </code></pre>
  13303. <p><strong>Parameters</strong></p>
  13304. <p>The following parameters should be set in the URL:</p>
  13305. <ul>
  13306. <li><code>destination</code> - Name of the remote server.</li>
  13307. </ul>
  13308. <p><strong>Response</strong></p>
  13309. <p>The response fields are the same like in the <code>destinations</code> array in
  13310. <a href="usage/administration/admin_api/federation.html#list-of-destinations">List of destinations</a> response.</p>
  13311. <h2 id="destination-rooms"><a class="header" href="#destination-rooms">Destination rooms</a></h2>
  13312. <p>This API gets the rooms that federate with a specific remote server.</p>
  13313. <p>The API is:</p>
  13314. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/rooms
  13315. </code></pre>
  13316. <p>A response body like the following is returned:</p>
  13317. <pre><code class="language-json">{
  13318. &quot;rooms&quot;:[
  13319. {
  13320. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  13321. &quot;stream_ordering&quot;: 8326
  13322. },
  13323. {
  13324. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  13325. &quot;stream_ordering&quot;: 93534
  13326. }
  13327. ],
  13328. &quot;total&quot;: 2
  13329. }
  13330. </code></pre>
  13331. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  13332. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  13333. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  13334. to paginate through.</p>
  13335. <p><strong>Parameters</strong></p>
  13336. <p>The following parameters should be set in the URL:</p>
  13337. <ul>
  13338. <li><code>destination</code> - Name of the remote server.</li>
  13339. </ul>
  13340. <p>The following query parameters are available:</p>
  13341. <ul>
  13342. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  13343. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  13344. <li><code>dir</code> - Direction of room order by <code>room_id</code>. Either <code>f</code> for forwards or <code>b</code> for
  13345. backwards. Defaults to <code>f</code>.</li>
  13346. </ul>
  13347. <p><strong>Response</strong></p>
  13348. <p>The following fields are returned in the JSON response body:</p>
  13349. <ul>
  13350. <li><code>rooms</code> - An array of objects, each containing information about a room.
  13351. Room objects contain the following fields:
  13352. <ul>
  13353. <li><code>room_id</code> - string - The ID of the room.</li>
  13354. <li><code>stream_ordering</code> - integer - The stream ordering of the most recent
  13355. successfully-sent <a href="usage/administration/admin_api/understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  13356. to this destination in this room.</li>
  13357. </ul>
  13358. </li>
  13359. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  13360. <li><code>total</code> - integer - Total number of destinations.</li>
  13361. </ul>
  13362. <h2 id="reset-connection-timeout"><a class="header" href="#reset-connection-timeout">Reset connection timeout</a></h2>
  13363. <p>Synapse makes federation requests to other homeservers. If a federation request fails,
  13364. Synapse will mark the destination homeserver as offline, preventing any future requests
  13365. to that server for a &quot;cooldown&quot; period. This period grows over time if the server
  13366. continues to fail its responses
  13367. (<a href="https://en.wikipedia.org/wiki/Exponential_backoff">exponential backoff</a>).</p>
  13368. <p>Admins can cancel the cooldown period with this API.</p>
  13369. <p>This API resets the retry timing for a specific remote server and tries to connect to
  13370. the remote server again. It does not wait for the next <code>retry_interval</code>.
  13371. The connection must have previously run into an error and <code>retry_last_ts</code>
  13372. (<a href="usage/administration/admin_api/federation.html#destination-details-api">Destination Details API</a>) must not be equal to <code>0</code>.</p>
  13373. <p>The connection attempt is carried out in the background and can take a while
  13374. even if the API already returns the http status 200.</p>
  13375. <p>The API is:</p>
  13376. <pre><code>POST /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/reset_connection
  13377. {}
  13378. </code></pre>
  13379. <p><strong>Parameters</strong></p>
  13380. <p>The following parameters should be set in the URL:</p>
  13381. <ul>
  13382. <li><code>destination</code> - Name of the remote server.</li>
  13383. </ul>
  13384. <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>
  13385. <p>The &quot;manhole&quot; allows server administrators to access a Python shell on a running
  13386. Synapse installation. This is a very powerful mechanism for administration and
  13387. debugging.</p>
  13388. <p><strong><em>Security Warning</em></strong></p>
  13389. <p>Note that this will give administrative access to synapse to <strong>all users</strong> with
  13390. shell access to the server. It should therefore <strong>not</strong> be enabled in
  13391. environments where untrusted users have shell access.</p>
  13392. <h2 id="configuring-the-manhole"><a class="header" href="#configuring-the-manhole">Configuring the manhole</a></h2>
  13393. <p>To enable it, first add the <code>manhole</code> listener configuration in your
  13394. <code>homeserver.yaml</code>. You can find information on how to do that
  13395. in the <a href="usage/configuration/config_documentation.html#manhole_settings">configuration manual</a>.
  13396. The configuration is slightly different if you're using docker.</p>
  13397. <h4 id="docker-config"><a class="header" href="#docker-config">Docker config</a></h4>
  13398. <p>If you are using Docker, set <code>bind_addresses</code> to <code>['0.0.0.0']</code> as shown:</p>
  13399. <pre><code class="language-yaml">listeners:
  13400. - port: 9000
  13401. bind_addresses: ['0.0.0.0']
  13402. type: manhole
  13403. </code></pre>
  13404. <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
  13405. <code>manhole</code> port forwarding. The <code>-p 127.0.0.1:9000:9000</code> below is important: it
  13406. ensures that access to the <code>manhole</code> is only possible for local users.</p>
  13407. <pre><code class="language-bash">docker run -d --name synapse \
  13408. --mount type=volume,src=synapse-data,dst=/data \
  13409. -p 8008:8008 \
  13410. -p 127.0.0.1:9000:9000 \
  13411. matrixdotorg/synapse:latest
  13412. </code></pre>
  13413. <h4 id="native-config"><a class="header" href="#native-config">Native config</a></h4>
  13414. <p>If you are not using docker, set <code>bind_addresses</code> to <code>['::1', '127.0.0.1']</code> as shown.
  13415. The <code>bind_addresses</code> in the example below is important: it ensures that access to the
  13416. <code>manhole</code> is only possible for local users).</p>
  13417. <pre><code class="language-yaml">listeners:
  13418. - port: 9000
  13419. bind_addresses: ['::1', '127.0.0.1']
  13420. type: manhole
  13421. </code></pre>
  13422. <h3 id="security-settings"><a class="header" href="#security-settings">Security settings</a></h3>
  13423. <p>The following config options are available:</p>
  13424. <ul>
  13425. <li><code>username</code> - The username for the manhole (defaults to <code>matrix</code>)</li>
  13426. <li><code>password</code> - The password for the manhole (defaults to <code>rabbithole</code>)</li>
  13427. <li><code>ssh_priv_key</code> - The path to a private SSH key (defaults to a hardcoded value)</li>
  13428. <li><code>ssh_pub_key</code> - The path to a public SSH key (defaults to a hardcoded value)</li>
  13429. </ul>
  13430. <p>For example:</p>
  13431. <pre><code class="language-yaml">manhole_settings:
  13432. username: manhole
  13433. password: mypassword
  13434. ssh_priv_key: &quot;/home/synapse/manhole_keys/id_rsa&quot;
  13435. ssh_pub_key: &quot;/home/synapse/manhole_keys/id_rsa.pub&quot;
  13436. </code></pre>
  13437. <h2 id="accessing-synapse-manhole"><a class="header" href="#accessing-synapse-manhole">Accessing synapse manhole</a></h2>
  13438. <p>Then restart synapse, and point an ssh client at port 9000 on localhost, using
  13439. the username and password configured in <code>homeserver.yaml</code> - with the default
  13440. configuration, this would be:</p>
  13441. <pre><code class="language-bash">ssh -p9000 matrix@localhost
  13442. </code></pre>
  13443. <p>Then enter the password when prompted (the default is <code>rabbithole</code>).</p>
  13444. <p>This gives a Python REPL in which <code>hs</code> gives access to the
  13445. <code>synapse.server.HomeServer</code> object - which in turn gives access to many other
  13446. parts of the process.</p>
  13447. <p>Note that, prior to Synapse 1.41, any call which returns a coroutine will need to be wrapped in <code>ensureDeferred</code>.</p>
  13448. <p>As a simple example, retrieving an event from the database:</p>
  13449. <pre><code class="language-pycon">&gt;&gt;&gt; from twisted.internet import defer
  13450. &gt;&gt;&gt; defer.ensureDeferred(hs.get_datastores().main.get_event('$1416420717069yeQaw:matrix.org'))
  13451. &lt;Deferred at 0x7ff253fc6998 current result: &lt;FrozenEvent event_id='$1416420717069yeQaw:matrix.org', type='m.room.create', state_key=''&gt;&gt;
  13452. </code></pre>
  13453. <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>
  13454. <ol>
  13455. <li>
  13456. <p>Install Prometheus:</p>
  13457. <p>Follow instructions at
  13458. <a href="http://prometheus.io/docs/introduction/install/">http://prometheus.io/docs/introduction/install/</a></p>
  13459. </li>
  13460. <li>
  13461. <p>Enable Synapse metrics:</p>
  13462. <p>In <code>homeserver.yaml</code>, make sure <code>enable_metrics</code> is
  13463. set to <code>True</code>.</p>
  13464. </li>
  13465. <li>
  13466. <p>Enable the <code>/_synapse/metrics</code> Synapse endpoint that Prometheus uses to
  13467. collect data:</p>
  13468. <p>There are two methods of enabling the metrics endpoint in Synapse.</p>
  13469. <p>The first serves the metrics as a part of the usual web server and
  13470. can be enabled by adding the &quot;metrics&quot; resource to the existing
  13471. listener as such:</p>
  13472. <pre><code class="language-yaml"> resources:
  13473. - names:
  13474. - client
  13475. - metrics
  13476. </code></pre>
  13477. <p>This provides a simple way of adding metrics to your Synapse
  13478. installation, and serves under <code>/_synapse/metrics</code>. If you do not
  13479. wish your metrics be publicly exposed, you will need to either
  13480. filter it out at your load balancer, or use the second method.</p>
  13481. <p>The second method runs the metrics server on a different port, in a
  13482. different thread to Synapse. This can make it more resilient to
  13483. heavy load meaning metrics cannot be retrieved, and can be exposed
  13484. to just internal networks easier. The served metrics are available
  13485. over HTTP only, and will be available at <code>/_synapse/metrics</code>.</p>
  13486. <p>Add a new listener to homeserver.yaml:</p>
  13487. <pre><code class="language-yaml"> listeners:
  13488. - type: metrics
  13489. port: 9000
  13490. bind_addresses:
  13491. - '0.0.0.0'
  13492. </code></pre>
  13493. </li>
  13494. <li>
  13495. <p>Restart Synapse.</p>
  13496. </li>
  13497. <li>
  13498. <p>Add a Prometheus target for Synapse.</p>
  13499. <p>It needs to set the <code>metrics_path</code> to a non-default value (under
  13500. <code>scrape_configs</code>):</p>
  13501. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  13502. scrape_interval: 15s
  13503. metrics_path: &quot;/_synapse/metrics&quot;
  13504. static_configs:
  13505. - targets: [&quot;my.server.here:port&quot;]
  13506. </code></pre>
  13507. <p>where <code>my.server.here</code> is the IP address of Synapse, and <code>port</code> is
  13508. the listener port configured with the <code>metrics</code> resource.</p>
  13509. <p>If your prometheus is older than 1.5.2, you will need to replace
  13510. <code>static_configs</code> in the above with <code>target_groups</code>.</p>
  13511. </li>
  13512. <li>
  13513. <p>Restart Prometheus.</p>
  13514. </li>
  13515. <li>
  13516. <p>Consider using the <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana/">grafana dashboard</a>
  13517. and required <a href="https://github.com/matrix-org/synapse/tree/master/contrib/prometheus/">recording rules</a> </p>
  13518. </li>
  13519. </ol>
  13520. <h2 id="monitoring-workers"><a class="header" href="#monitoring-workers">Monitoring workers</a></h2>
  13521. <p>To monitor a Synapse installation using <a href="workers.html">workers</a>,
  13522. every worker needs to be monitored independently, in addition to
  13523. the main homeserver process. This is because workers don't send
  13524. their metrics to the main homeserver process, but expose them
  13525. directly (if they are configured to do so).</p>
  13526. <p>To allow collecting metrics from a worker, you need to add a
  13527. <code>metrics</code> listener to its configuration, by adding the following
  13528. under <code>worker_listeners</code>:</p>
  13529. <pre><code class="language-yaml"> - type: metrics
  13530. bind_address: ''
  13531. port: 9101
  13532. </code></pre>
  13533. <p>The <code>bind_address</code> and <code>port</code> parameters should be set so that
  13534. the resulting listener can be reached by prometheus, and they
  13535. don't clash with an existing worker.
  13536. With this example, the worker's metrics would then be available
  13537. on <code>http://127.0.0.1:9101</code>.</p>
  13538. <p>Example Prometheus target for Synapse with workers:</p>
  13539. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  13540. scrape_interval: 15s
  13541. metrics_path: &quot;/_synapse/metrics&quot;
  13542. static_configs:
  13543. - targets: [&quot;my.server.here:port&quot;]
  13544. labels:
  13545. instance: &quot;my.server&quot;
  13546. job: &quot;master&quot;
  13547. index: 1
  13548. - targets: [&quot;my.workerserver.here:port&quot;]
  13549. labels:
  13550. instance: &quot;my.server&quot;
  13551. job: &quot;generic_worker&quot;
  13552. index: 1
  13553. - targets: [&quot;my.workerserver.here:port&quot;]
  13554. labels:
  13555. instance: &quot;my.server&quot;
  13556. job: &quot;generic_worker&quot;
  13557. index: 2
  13558. - targets: [&quot;my.workerserver.here:port&quot;]
  13559. labels:
  13560. instance: &quot;my.server&quot;
  13561. job: &quot;media_repository&quot;
  13562. index: 1
  13563. </code></pre>
  13564. <p>Labels (<code>instance</code>, <code>job</code>, <code>index</code>) can be defined as anything.
  13565. The labels are used to group graphs in grafana.</p>
  13566. <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>
  13567. <p>Synapse 1.2 updates the Prometheus metrics to match the naming
  13568. convention of the upstream <code>prometheus_client</code>. The old names are
  13569. considered deprecated and will be removed in a future version of
  13570. Synapse.
  13571. <strong>The old names will be disabled by default in Synapse v1.71.0 and removed
  13572. altogether in Synapse v1.73.0.</strong></p>
  13573. <table><thead><tr><th>New Name</th><th>Old Name</th></tr></thead><tbody>
  13574. <tr><td>python_gc_objects_collected_total</td><td>python_gc_objects_collected</td></tr>
  13575. <tr><td>python_gc_objects_uncollectable_total</td><td>python_gc_objects_uncollectable</td></tr>
  13576. <tr><td>python_gc_collections_total</td><td>python_gc_collections</td></tr>
  13577. <tr><td>process_cpu_seconds_total</td><td>process_cpu_seconds</td></tr>
  13578. <tr><td>synapse_federation_client_sent_transactions_total</td><td>synapse_federation_client_sent_transactions</td></tr>
  13579. <tr><td>synapse_federation_client_events_processed_total</td><td>synapse_federation_client_events_processed</td></tr>
  13580. <tr><td>synapse_event_processing_loop_count_total</td><td>synapse_event_processing_loop_count</td></tr>
  13581. <tr><td>synapse_event_processing_loop_room_count_total</td><td>synapse_event_processing_loop_room_count</td></tr>
  13582. <tr><td>synapse_util_caches_cache_hits</td><td>synapse_util_caches_cache:hits</td></tr>
  13583. <tr><td>synapse_util_caches_cache_size</td><td>synapse_util_caches_cache:size</td></tr>
  13584. <tr><td>synapse_util_caches_cache_evicted_size</td><td>synapse_util_caches_cache:evicted_size</td></tr>
  13585. <tr><td>synapse_util_caches_cache</td><td>synapse_util_caches_cache:total</td></tr>
  13586. <tr><td>synapse_util_caches_response_cache_size</td><td>synapse_util_caches_response_cache:size</td></tr>
  13587. <tr><td>synapse_util_caches_response_cache_hits</td><td>synapse_util_caches_response_cache:hits</td></tr>
  13588. <tr><td>synapse_util_caches_response_cache_evicted_size</td><td>synapse_util_caches_response_cache:evicted_size</td></tr>
  13589. <tr><td>synapse_util_metrics_block_count_total</td><td>synapse_util_metrics_block_count</td></tr>
  13590. <tr><td>synapse_util_metrics_block_time_seconds_total</td><td>synapse_util_metrics_block_time_seconds</td></tr>
  13591. <tr><td>synapse_util_metrics_block_ru_utime_seconds_total</td><td>synapse_util_metrics_block_ru_utime_seconds</td></tr>
  13592. <tr><td>synapse_util_metrics_block_ru_stime_seconds_total</td><td>synapse_util_metrics_block_ru_stime_seconds</td></tr>
  13593. <tr><td>synapse_util_metrics_block_db_txn_count_total</td><td>synapse_util_metrics_block_db_txn_count</td></tr>
  13594. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds_total</td><td>synapse_util_metrics_block_db_txn_duration_seconds</td></tr>
  13595. <tr><td>synapse_util_metrics_block_db_sched_duration_seconds_total</td><td>synapse_util_metrics_block_db_sched_duration_seconds</td></tr>
  13596. <tr><td>synapse_background_process_start_count_total</td><td>synapse_background_process_start_count</td></tr>
  13597. <tr><td>synapse_background_process_ru_utime_seconds_total</td><td>synapse_background_process_ru_utime_seconds</td></tr>
  13598. <tr><td>synapse_background_process_ru_stime_seconds_total</td><td>synapse_background_process_ru_stime_seconds</td></tr>
  13599. <tr><td>synapse_background_process_db_txn_count_total</td><td>synapse_background_process_db_txn_count</td></tr>
  13600. <tr><td>synapse_background_process_db_txn_duration_seconds_total</td><td>synapse_background_process_db_txn_duration_seconds</td></tr>
  13601. <tr><td>synapse_background_process_db_sched_duration_seconds_total</td><td>synapse_background_process_db_sched_duration_seconds</td></tr>
  13602. <tr><td>synapse_storage_events_persisted_events_total</td><td>synapse_storage_events_persisted_events</td></tr>
  13603. <tr><td>synapse_storage_events_persisted_events_sep_total</td><td>synapse_storage_events_persisted_events_sep</td></tr>
  13604. <tr><td>synapse_storage_events_state_delta_total</td><td>synapse_storage_events_state_delta</td></tr>
  13605. <tr><td>synapse_storage_events_state_delta_single_event_total</td><td>synapse_storage_events_state_delta_single_event</td></tr>
  13606. <tr><td>synapse_storage_events_state_delta_reuse_delta_total</td><td>synapse_storage_events_state_delta_reuse_delta</td></tr>
  13607. <tr><td>synapse_federation_server_received_pdus_total</td><td>synapse_federation_server_received_pdus</td></tr>
  13608. <tr><td>synapse_federation_server_received_edus_total</td><td>synapse_federation_server_received_edus</td></tr>
  13609. <tr><td>synapse_handler_presence_notified_presence_total</td><td>synapse_handler_presence_notified_presence</td></tr>
  13610. <tr><td>synapse_handler_presence_federation_presence_out_total</td><td>synapse_handler_presence_federation_presence_out</td></tr>
  13611. <tr><td>synapse_handler_presence_presence_updates_total</td><td>synapse_handler_presence_presence_updates</td></tr>
  13612. <tr><td>synapse_handler_presence_timers_fired_total</td><td>synapse_handler_presence_timers_fired</td></tr>
  13613. <tr><td>synapse_handler_presence_federation_presence_total</td><td>synapse_handler_presence_federation_presence</td></tr>
  13614. <tr><td>synapse_handler_presence_bump_active_time_total</td><td>synapse_handler_presence_bump_active_time</td></tr>
  13615. <tr><td>synapse_federation_client_sent_edus_total</td><td>synapse_federation_client_sent_edus</td></tr>
  13616. <tr><td>synapse_federation_client_sent_pdu_destinations_count_total</td><td>synapse_federation_client_sent_pdu_destinations:count</td></tr>
  13617. <tr><td>synapse_federation_client_sent_pdu_destinations_total</td><td>synapse_federation_client_sent_pdu_destinations:total</td></tr>
  13618. <tr><td>synapse_handlers_appservice_events_processed_total</td><td>synapse_handlers_appservice_events_processed</td></tr>
  13619. <tr><td>synapse_notifier_notified_events_total</td><td>synapse_notifier_notified_events</td></tr>
  13620. <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>
  13621. <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>
  13622. <tr><td>synapse_http_httppusher_http_pushes_processed_total</td><td>synapse_http_httppusher_http_pushes_processed</td></tr>
  13623. <tr><td>synapse_http_httppusher_http_pushes_failed_total</td><td>synapse_http_httppusher_http_pushes_failed</td></tr>
  13624. <tr><td>synapse_http_httppusher_badge_updates_processed_total</td><td>synapse_http_httppusher_badge_updates_processed</td></tr>
  13625. <tr><td>synapse_http_httppusher_badge_updates_failed_total</td><td>synapse_http_httppusher_badge_updates_failed</td></tr>
  13626. </tbody></table>
  13627. <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>
  13628. <p>The duplicated metrics deprecated in Synapse 0.27.0 have been removed.</p>
  13629. <p>All time duration-based metrics have been changed to be seconds. This
  13630. affects:</p>
  13631. <table><thead><tr><th>msec -&gt; sec metrics</th></tr></thead><tbody>
  13632. <tr><td>python_gc_time</td></tr>
  13633. <tr><td>python_twisted_reactor_tick_time</td></tr>
  13634. <tr><td>synapse_storage_query_time</td></tr>
  13635. <tr><td>synapse_storage_schedule_time</td></tr>
  13636. <tr><td>synapse_storage_transaction_time</td></tr>
  13637. </tbody></table>
  13638. <p>Several metrics have been changed to be histograms, which sort entries
  13639. into buckets and allow better analysis. The following metrics are now
  13640. histograms:</p>
  13641. <table><thead><tr><th>Altered metrics</th></tr></thead><tbody>
  13642. <tr><td>python_gc_time</td></tr>
  13643. <tr><td>python_twisted_reactor_pending_calls</td></tr>
  13644. <tr><td>python_twisted_reactor_tick_time</td></tr>
  13645. <tr><td>synapse_http_server_response_time_seconds</td></tr>
  13646. <tr><td>synapse_storage_query_time</td></tr>
  13647. <tr><td>synapse_storage_schedule_time</td></tr>
  13648. <tr><td>synapse_storage_transaction_time</td></tr>
  13649. </tbody></table>
  13650. <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>
  13651. <p>Synapse 0.27.0 begins the process of rationalising the duplicate
  13652. <code>*:count</code> metrics reported for the resource tracking for code blocks and
  13653. HTTP requests.</p>
  13654. <p>At the same time, the corresponding <code>*:total</code> metrics are being renamed,
  13655. as the <code>:total</code> suffix no longer makes sense in the absence of a
  13656. corresponding <code>:count</code> metric.</p>
  13657. <p>To enable a graceful migration path, this release just adds new names
  13658. for the metrics being renamed. A future release will remove the old
  13659. ones.</p>
  13660. <p>The following table shows the new metrics, and the old metrics which
  13661. they are replacing.</p>
  13662. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  13663. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_timer:count</td></tr>
  13664. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_utime:count</td></tr>
  13665. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_stime:count</td></tr>
  13666. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_count:count</td></tr>
  13667. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_duration:count</td></tr>
  13668. <tr><td>synapse_util_metrics_block_time_seconds</td><td>synapse_util_metrics_block_timer:total</td></tr>
  13669. <tr><td>synapse_util_metrics_block_ru_utime_seconds</td><td>synapse_util_metrics_block_ru_utime:total</td></tr>
  13670. <tr><td>synapse_util_metrics_block_ru_stime_seconds</td><td>synapse_util_metrics_block_ru_stime:total</td></tr>
  13671. <tr><td>synapse_util_metrics_block_db_txn_count</td><td>synapse_util_metrics_block_db_txn_count:total</td></tr>
  13672. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds</td><td>synapse_util_metrics_block_db_txn_duration:total</td></tr>
  13673. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_requests</td></tr>
  13674. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_time:count</td></tr>
  13675. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_utime:count</td></tr>
  13676. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_stime:count</td></tr>
  13677. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_count:count</td></tr>
  13678. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_duration:count</td></tr>
  13679. <tr><td>synapse_http_server_response_time_seconds</td><td>synapse_http_server_response_time:total</td></tr>
  13680. <tr><td>synapse_http_server_response_ru_utime_seconds</td><td>synapse_http_server_response_ru_utime:total</td></tr>
  13681. <tr><td>synapse_http_server_response_ru_stime_seconds</td><td>synapse_http_server_response_ru_stime:total</td></tr>
  13682. <tr><td>synapse_http_server_response_db_txn_count</td><td>synapse_http_server_response_db_txn_count:total</td></tr>
  13683. <tr><td>synapse_http_server_response_db_txn_duration_seconds</td><td>synapse_http_server_response_db_txn_duration:total</td></tr>
  13684. </tbody></table>
  13685. <h2 id="standard-metric-names"><a class="header" href="#standard-metric-names">Standard Metric Names</a></h2>
  13686. <p>As of synapse version 0.18.2, the format of the process-wide metrics has
  13687. been changed to fit prometheus standard naming conventions. Additionally
  13688. the units have been changed to seconds, from milliseconds.</p>
  13689. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  13690. <tr><td>process_cpu_user_seconds_total</td><td>process_resource_utime / 1000</td></tr>
  13691. <tr><td>process_cpu_system_seconds_total</td><td>process_resource_stime / 1000</td></tr>
  13692. <tr><td>process_open_fds (no 'type' label)</td><td>process_fds</td></tr>
  13693. </tbody></table>
  13694. <p>The python-specific counts of garbage collector performance have been
  13695. renamed.</p>
  13696. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  13697. <tr><td>python_gc_time</td><td>reactor_gc_time</td></tr>
  13698. <tr><td>python_gc_unreachable_total</td><td>reactor_gc_unreachable</td></tr>
  13699. <tr><td>python_gc_counts</td><td>reactor_gc_counts</td></tr>
  13700. </tbody></table>
  13701. <p>The twisted-specific reactor metrics have been renamed.</p>
  13702. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  13703. <tr><td>python_twisted_reactor_pending_calls</td><td>reactor_pending_calls</td></tr>
  13704. <tr><td>python_twisted_reactor_tick_time</td><td>reactor_tick_time</td></tr>
  13705. </tbody></table>
  13706. <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>
  13707. <p>When generating your Synapse configuration file, you are asked whether you
  13708. would like to report usage statistics to Matrix.org. These statistics
  13709. provide the foundation a glimpse into the number of Synapse homeservers
  13710. participating in the network, as well as statistics such as the number of
  13711. rooms being created and messages being sent. This feature is sometimes
  13712. affectionately called &quot;phone home&quot; stats. Reporting
  13713. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats">is optional</a>
  13714. and the reporting endpoint
  13715. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats_endpoint">can be configured</a>,
  13716. in case you would like to instead report statistics from a set of homeservers
  13717. to your own infrastructure.</p>
  13718. <p>This documentation aims to define the statistics available and the
  13719. homeserver configuration options that exist to tweak it.</p>
  13720. <h2 id="available-statistics"><a class="header" href="#available-statistics">Available Statistics</a></h2>
  13721. <p>The following statistics are sent to the configured reporting endpoint:</p>
  13722. <table><thead><tr><th>Statistic Name</th><th>Type</th><th>Description</th></tr></thead><tbody>
  13723. <tr><td><code>homeserver</code></td><td>string</td><td>The homeserver's server name.</td></tr>
  13724. <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>
  13725. <tr><td><code>cpu_average</code></td><td>int</td><td>CPU time in % of a single core (not % of all cores).</td></tr>
  13726. <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>
  13727. <tr><td><code>timestamp</code></td><td>int</td><td>The current time, represented as the number of seconds since the epoch.</td></tr>
  13728. <tr><td><code>uptime_seconds</code></td><td>int</td><td>The number of seconds since the homeserver was last started.</td></tr>
  13729. <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>
  13730. <tr><td><code>total_users</code></td><td>int</td><td>The number of registered users on the homeserver.</td></tr>
  13731. <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>
  13732. <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>
  13733. <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>
  13734. <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>
  13735. <tr><td><code>total_room_count</code></td><td>int</td><td>The total number of rooms present on the homeserver.</td></tr>
  13736. <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>
  13737. <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>
  13738. <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>
  13739. <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>
  13740. <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>
  13741. <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>
  13742. <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>
  13743. <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>
  13744. <tr><td><code>r30_users_all</code></td><td>int</td><td>The number of 30 day retained users, defined as users who have created their accounts more than 30 days ago, where they were last seen at most 30 days ago and where those two timestamps are over 30 days apart. Includes clients that do not fit into the below r30 client types.</td></tr>
  13745. <tr><td><code>r30_users_android</code></td><td>int</td><td>The number of 30 day retained users, as defined above. Filtered only to clients with &quot;Android&quot; in the user agent string.</td></tr>
  13746. <tr><td><code>r30_users_ios</code></td><td>int</td><td>The number of 30 day retained users, as defined above. Filtered only to clients with &quot;iOS&quot; in the user agent string.</td></tr>
  13747. <tr><td><code>r30_users_electron</code></td><td>int</td><td>The number of 30 day retained users, as defined above. Filtered only to clients with &quot;Electron&quot; in the user agent string.</td></tr>
  13748. <tr><td><code>r30_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; in the user agent string.</td></tr>
  13749. <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>
  13750. <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>
  13751. <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>
  13752. <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>
  13753. <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>
  13754. <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>
  13755. <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>
  13756. <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>
  13757. <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>
  13758. <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>
  13759. </tbody></table>
  13760. <div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
  13761. <p>Native matrix users and guests are always counted. If the
  13762. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a>
  13763. option is set to <code>true</code>, &quot;puppeted&quot; users (users that an Application Service have performed
  13764. <a href="https://spec.matrix.org/v1.3/application-service-api/#identity-assertion">an action on behalf of</a>)
  13765. will also be counted. Note that an Application Service can &quot;puppet&quot; any user in their
  13766. <a href="https://spec.matrix.org/v1.3/application-service-api/#registration">user namespace</a>,
  13767. not only users that the Application Service has created. If this happens, the Application Service
  13768. will additionally be counted as a user (irrespective of <code>track_puppeted_user_ips</code>).</p>
  13769. </div>
  13770. <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>
  13771. <p>If statistics reporting is enabled, the endpoint that Synapse sends metrics to is configured by the
  13772. <a href="usage/administration/monitoring/../../configuration/config_documentation.html#report_stats_endpoint"><code>report_stats_endpoint</code></a> config
  13773. option. By default, statistics are sent to Matrix.org.</p>
  13774. <p>If you would like to set up your own statistics collection server and send metrics there, you may
  13775. consider using one of the following known implementations:</p>
  13776. <ul>
  13777. <li><a href="https://github.com/matrix-org/panopticon">Matrix.org's Panopticon</a></li>
  13778. <li><a href="https://gitlab.com/famedly/company/devops/services/barad-dur">Famedly's Barad-dûr</a></li>
  13779. </ul>
  13780. <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>
  13781. <p>Synapse can be configured to record the number of monthly active users (also referred to as MAU) on a given homeserver.
  13782. For clarity's sake, MAU only tracks local users.</p>
  13783. <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>
  13784. are calculated differently. The <code>monthly_active_users</code> from the usage stats does not take into account any
  13785. of the rules below, and counts any users who have made a request to the homeserver in the last 30 days.</p>
  13786. <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>
  13787. <h2 id="calculating-active-users"><a class="header" href="#calculating-active-users">Calculating active users</a></h2>
  13788. <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
  13789. calculating the MAU figure, any users with a recorded action in the last 30 days are considered part of the cohort. Days are measured
  13790. as a rolling window from the current system time to 30 days ago.</p>
  13791. <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>
  13792. <p>A user is <strong>never</strong> considered active if they are either:</p>
  13793. <ul>
  13794. <li>Part of the trial day cohort (described below)</li>
  13795. <li>Owned by an application service.
  13796. <ul>
  13797. <li>Note: This <strong>only</strong> covers users that are part of an application service <code>namespaces.users</code> registration. The namespace
  13798. must also be marked as <code>exclusive</code>.</li>
  13799. </ul>
  13800. </li>
  13801. </ul>
  13802. <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>
  13803. they register with a 3pid that is included in the config field <code>mau_limits_reserved_threepids</code>.</p>
  13804. <p>The Prometheus metric for MAU is refreshed every 5 minutes.</p>
  13805. <p>Once an hour, Synapse checks to see if any users are inactive (with only activity timestamps later than 30 days). These users
  13806. are removed from the active users cohort. If they then become active, they are immediately restored to the cohort.</p>
  13807. <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
  13808. perform actions they will eventually be removed from the cohort.</p>
  13809. <h3 id="trial-days"><a class="header" href="#trial-days">Trial days</a></h3>
  13810. <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
  13811. trial period if their registration timestamp (also known as the <code>creation_ts</code>) is less than <code>mau_trial_days</code> old.</p>
  13812. <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>
  13813. <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.
  13814. 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>
  13815. <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>
  13816. <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
  13817. homeserver will begin to block some actions.</p>
  13818. <p>Individual users matching <strong>any</strong> of the below criteria never have their actions blocked:</p>
  13819. <ul>
  13820. <li>Considered part of the cohort of MAU users.</li>
  13821. <li>Considered part of the trial period.</li>
  13822. <li>Registered as a <code>support</code> user.</li>
  13823. <li>Application service users if <code>track_appservice_user_ips</code> is NOT set.</li>
  13824. </ul>
  13825. <p>Please not that server admins are <strong>not</strong> exempt from blocking.</p>
  13826. <p>The following actions are blocked when the MAU limit is exceeded:</p>
  13827. <ul>
  13828. <li>Logging in</li>
  13829. <li>Sending events</li>
  13830. <li>Creating rooms</li>
  13831. <li>Syncing</li>
  13832. </ul>
  13833. <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>
  13834. config value.</p>
  13835. <p>When a request is blocked, the response will have the <code>errcode</code> <code>M_RESOURCE_LIMIT_EXCEEDED</code>.</p>
  13836. <h2 id="metrics-1"><a class="header" href="#metrics-1">Metrics</a></h2>
  13837. <p>Synapse records several different prometheus metrics for MAU.</p>
  13838. <p><code>synapse_admin_mau:current</code> records the current MAU figure for native (non-application-service) users.</p>
  13839. <p><code>synapse_admin_mau:max</code> records the maximum MAU as dictated by the <code>max_mau_value</code> config value.</p>
  13840. <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
  13841. to filter by a specific service ID. This <em>also</em> includes non-application-service users under <code>app_service=native</code> .</p>
  13842. <p><code>synapse_admin_mau:registered_reserved_users</code> records the number of users specified in <code>mau_limits_reserved_threepids</code> which have
  13843. registered accounts on the homeserver.</p>
  13844. <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>
  13845. <p>It is possible to monitor much of the internal state of Synapse using <a href="https://prometheus.io">Prometheus</a>
  13846. metrics and <a href="https://grafana.com/">Grafana</a>.
  13847. A guide for configuring Synapse to provide metrics is available <a href="usage/administration/../../metrics-howto.html">here</a>
  13848. and information on setting up Grafana is <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana">here</a>.
  13849. In this setup, Prometheus will periodically scrape the information Synapse provides and
  13850. store a record of it over time. Grafana is then used as an interface to query and
  13851. present this information through a series of pretty graphs.</p>
  13852. <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>
  13853. <h2 id="message-event-send-time"><a class="header" href="#message-event-send-time">Message Event Send Time</a></h2>
  13854. <p><img src="https://user-images.githubusercontent.com/1342360/82239409-a1c8e900-9930-11ea-8081-e4614e0c63f4.png" alt="image" /></p>
  13855. <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>
  13856. <h2 id="transaction-count-and-transaction-duration"><a class="header" href="#transaction-count-and-transaction-duration">Transaction Count and Transaction Duration</a></h2>
  13857. <p><img src="https://user-images.githubusercontent.com/1342360/82239985-8d392080-9931-11ea-80d0-843ab2f22e1e.png" alt="image" /></p>
  13858. <p><img src="https://user-images.githubusercontent.com/1342360/82240050-ab068580-9931-11ea-98f1-f94671cbac9a.png" alt="image" /></p>
  13859. <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>
  13860. <p><img src="https://user-images.githubusercontent.com/1342360/82240192-e86b1300-9931-11ea-9aac-3e2c9bfa6fdc.png" alt="image" /></p>
  13861. <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>
  13862. <p><img src="https://user-images.githubusercontent.com/1342360/82240467-62030100-9932-11ea-8db9-917f2d977fe1.png" alt="image" /></p>
  13863. <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>
  13864. <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>
  13865. <h2 id="federation-1"><a class="header" href="#federation-1">Federation</a></h2>
  13866. <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>
  13867. <ul>
  13868. <li>PDU (Persistent Data Unit) - room events: messages, state events (join/leave), etc. These are permanently stored in the database.</li>
  13869. <li>EDU (Ephemeral Data Unit) - other data, which need not be stored permanently, such as read receipts, typing notifications.</li>
  13870. </ul>
  13871. <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>
  13872. <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>
  13873. <h2 id="caches"><a class="header" href="#caches">Caches</a></h2>
  13874. <p><img src="https://user-images.githubusercontent.com/1342360/82240572-8b239180-9932-11ea-96ff-6b5f0e57ebe5.png" alt="image" /></p>
  13875. <p><img src="https://user-images.githubusercontent.com/1342360/82240666-b8703f80-9932-11ea-86af-9f663988d8da.png" alt="image" /></p>
  13876. <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>
  13877. <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>
  13878. <p><img src="https://user-images.githubusercontent.com/1342360/82240766-de95df80-9932-11ea-8c15-5acfc57c48da.png" alt="image" /></p>
  13879. <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>
  13880. <h2 id="forward-extremities"><a class="header" href="#forward-extremities">Forward Extremities</a></h2>
  13881. <p><img src="https://user-images.githubusercontent.com/1342360/82241440-13566680-9934-11ea-8b88-ba468db937ed.png" alt="image" /></p>
  13882. <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>
  13883. <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>
  13884. <h2 id="garbage-collection"><a class="header" href="#garbage-collection">Garbage Collection</a></h2>
  13885. <p><img src="https://user-images.githubusercontent.com/1342360/82241911-da6ac180-9934-11ea-9a0d-a311fe22acd0.png" alt="image" /></p>
  13886. <p>Large spikes in garbage collection times (bigger than shown here, I'm talking in the
  13887. multiple seconds range), can cause lots of problems in Synapse performance. It's more an
  13888. indicator of problems, and a symptom of other problems though, so check other graphs for what might be causing it.</p>
  13889. <h2 id="final-thoughts"><a class="header" href="#final-thoughts">Final Thoughts</a></h2>
  13890. <p>If you're still having performance problems with your Synapse instance and you've
  13891. tried everything you can, it may just be a lack of system resources. Consider adding
  13892. more CPU and RAM, and make use of <a href="usage/administration/../../workers.html">worker mode</a>
  13893. to make use of multiple CPU cores / multiple machines for your homeserver.</p>
  13894. <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>
  13895. <h2 id="size-of-full-matrix-db"><a class="header" href="#size-of-full-matrix-db">Size of full matrix db</a></h2>
  13896. <pre><code class="language-sql">SELECT pg_size_pretty( pg_database_size( 'matrix' ) );
  13897. </code></pre>
  13898. <h3 id="result-example"><a class="header" href="#result-example">Result example:</a></h3>
  13899. <pre><code>pg_size_pretty
  13900. ----------------
  13901. 6420 MB
  13902. (1 row)
  13903. </code></pre>
  13904. <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>
  13905. <pre><code class="language-sql">SELECT relname, n_live_tup AS &quot;rows&quot;
  13906. FROM pg_stat_user_tables
  13907. ORDER BY n_live_tup DESC
  13908. LIMIT 20;
  13909. </code></pre>
  13910. <p>This query is quick, but may be very approximate, for exact number of rows use:</p>
  13911. <pre><code class="language-sql">SELECT COUNT(*) FROM &lt;table_name&gt;;
  13912. </code></pre>
  13913. <h3 id="result-example-1"><a class="header" href="#result-example-1">Result example:</a></h3>
  13914. <pre><code>state_groups_state - 161687170
  13915. event_auth - 8584785
  13916. event_edges - 6995633
  13917. event_json - 6585916
  13918. event_reference_hashes - 6580990
  13919. events - 6578879
  13920. received_transactions - 5713989
  13921. event_to_state_groups - 4873377
  13922. stream_ordering_to_exterm - 4136285
  13923. current_state_delta_stream - 3770972
  13924. event_search - 3670521
  13925. state_events - 2845082
  13926. room_memberships - 2785854
  13927. cache_invalidation_stream - 2448218
  13928. state_groups - 1255467
  13929. state_group_edges - 1229849
  13930. current_state_events - 1222905
  13931. users_in_public_rooms - 364059
  13932. device_lists_stream - 326903
  13933. user_directory_search - 316433
  13934. </code></pre>
  13935. <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>
  13936. <pre><code class="language-sql">SELECT nspname || '.' || relname AS &quot;relation&quot;,
  13937. pg_size_pretty(pg_total_relation_size(c.oid)) AS &quot;total_size&quot;
  13938. FROM pg_class c
  13939. LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
  13940. WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  13941. AND c.relkind &lt;&gt; 'i'
  13942. AND nspname !~ '^pg_toast'
  13943. ORDER BY pg_total_relation_size(c.oid) DESC
  13944. LIMIT 20;
  13945. </code></pre>
  13946. <h3 id="result-example-2"><a class="header" href="#result-example-2">Result example:</a></h3>
  13947. <pre><code>public.state_groups_state - 27 GB
  13948. public.event_json - 9855 MB
  13949. public.events - 3675 MB
  13950. public.event_edges - 3404 MB
  13951. public.received_transactions - 2745 MB
  13952. public.event_reference_hashes - 1864 MB
  13953. public.event_auth - 1775 MB
  13954. public.stream_ordering_to_exterm - 1663 MB
  13955. public.event_search - 1370 MB
  13956. public.room_memberships - 1050 MB
  13957. public.event_to_state_groups - 948 MB
  13958. public.current_state_delta_stream - 711 MB
  13959. public.state_events - 611 MB
  13960. public.presence_stream - 530 MB
  13961. public.current_state_events - 525 MB
  13962. public.cache_invalidation_stream - 466 MB
  13963. public.receipts_linearized - 279 MB
  13964. public.state_groups - 160 MB
  13965. public.device_lists_remote_cache - 124 MB
  13966. public.state_group_edges - 122 MB
  13967. </code></pre>
  13968. <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>
  13969. <p>You get the same information when you use the
  13970. <a href="usage/administration/../../admin_api/rooms.html#list-room-api">admin API</a>
  13971. and set parameter <code>order_by=state_events</code>.</p>
  13972. <pre><code class="language-sql">SELECT r.name, s.room_id, s.current_state_events
  13973. FROM room_stats_current s
  13974. LEFT JOIN room_stats_state r USING (room_id)
  13975. ORDER BY current_state_events DESC
  13976. LIMIT 20;
  13977. </code></pre>
  13978. <p>and by state_group_events count:</p>
  13979. <pre><code class="language-sql">SELECT rss.name, s.room_id, COUNT(s.room_id)
  13980. FROM state_groups_state s
  13981. LEFT JOIN room_stats_state rss USING (room_id)
  13982. GROUP BY s.room_id, rss.name
  13983. ORDER BY COUNT(s.room_id) DESC
  13984. LIMIT 20;
  13985. </code></pre>
  13986. <p>plus same, but with join removed for performance reasons:</p>
  13987. <pre><code class="language-sql">SELECT s.room_id, COUNT(s.room_id)
  13988. FROM state_groups_state s
  13989. GROUP BY s.room_id
  13990. ORDER BY COUNT(s.room_id) DESC
  13991. LIMIT 20;
  13992. </code></pre>
  13993. <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>
  13994. <pre><code class="language-sql">SELECT e.room_id, r.name, COUNT(e.event_id) cnt
  13995. FROM events e
  13996. LEFT JOIN room_stats_state r USING (room_id)
  13997. WHERE e.origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 day') * 1000
  13998. GROUP BY e.room_id, r.name
  13999. ORDER BY cnt DESC
  14000. LIMIT 20;
  14001. </code></pre>
  14002. <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>
  14003. <p>Caution. This query does not use any indexes, can be slow and create load on the database.</p>
  14004. <pre><code class="language-sql">SELECT COUNT(*), sender
  14005. FROM events
  14006. WHERE (type = 'm.room.encrypted' OR type = 'm.room.message')
  14007. AND origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 month') * 1000
  14008. GROUP BY sender
  14009. ORDER BY COUNT(*) DESC
  14010. LIMIT 20;
  14011. </code></pre>
  14012. <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>
  14013. <pre><code class="language-sql">SELECT e.room_id, r.name, e.event_id, e.type, e.content, j.json
  14014. FROM events e
  14015. LEFT JOIN event_json j USING (room_id)
  14016. LEFT JOIN room_stats_state r USING (room_id)
  14017. WHERE sender = '@LOGIN:example.com'
  14018. AND e.type = 'm.room.message'
  14019. ORDER BY stream_ordering DESC
  14020. LIMIT 100;
  14021. </code></pre>
  14022. <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>
  14023. <p><strong>Sort and order with bash</strong></p>
  14024. <pre><code class="language-bash">echo &quot;SELECT event_json.room_id, room_stats_state.name FROM event_json, room_stats_state \
  14025. WHERE room_stats_state.room_id = event_json.room_id&quot; | psql -d synapse -h localhost -U synapse_user -t \
  14026. | sort | uniq -c | sort -n
  14027. </code></pre>
  14028. <p>Documentation for <code>psql</code> command line parameters: https://www.postgresql.org/docs/current/app-psql.html</p>
  14029. <p><strong>Sort and order with SQL</strong></p>
  14030. <pre><code class="language-sql">SELECT COUNT(*), event_json.room_id, room_stats_state.name
  14031. FROM event_json, room_stats_state
  14032. WHERE room_stats_state.room_id = event_json.room_id
  14033. GROUP BY event_json.room_id, room_stats_state.name
  14034. ORDER BY COUNT(*) DESC
  14035. LIMIT 50;
  14036. </code></pre>
  14037. <h3 id="result-example-3"><a class="header" href="#result-example-3">Result example:</a></h3>
  14038. <pre><code> 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix
  14039. 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix (TWIM)
  14040. 17799 !iDIOImbmXxwNngznsa:matrix.org | Linux in Russian
  14041. 18739 !GnEEPYXUhoaHbkFBNX:matrix.org | Riot Android
  14042. 23373 !QtykxKocfZaZOUrTwp:matrix.org | Matrix HQ
  14043. 39504 !gTQfWzbYncrtNrvEkB:matrix.org | ru.[matrix]
  14044. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot
  14045. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot Web/Desktop
  14046. </code></pre>
  14047. <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>
  14048. <p>You get the same information when you use the
  14049. <a href="usage/administration/../../admin_api/rooms.html#room-details-api">admin API</a>.</p>
  14050. <pre><code class="language-sql">SELECT rss.room_id, rss.name, rss.canonical_alias, rss.topic, rss.encryption,
  14051. rsc.joined_members, rsc.local_users_in_room, rss.join_rules
  14052. FROM room_stats_state rss
  14053. LEFT JOIN room_stats_current rsc USING (room_id)
  14054. WHERE room_id IN ( WHERE room_id IN (
  14055. '!OGEhHVWSdvArJzumhm:matrix.org',
  14056. '!YTvKGNlinIzlkMTVRl:matrix.org'
  14057. );
  14058. </code></pre>
  14059. <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>
  14060. <pre><code class="language-sql">SELECT user_id, device_id, user_agent, TO_TIMESTAMP(last_seen / 1000) AS &quot;last_seen&quot;
  14061. FROM devices
  14062. WHERE last_seen &lt; DATE_PART('epoch', NOW() - INTERVAL '3 month') * 1000;
  14063. </code></pre>
  14064. <div style="break-before: page; page-break-before: always;"></div><p>This blog post by Victor Berger explains how to use many of the tools listed on this page: https://levans.fr/shrink-synapse-database.html</p>
  14065. <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>
  14066. <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>
  14067. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  14068. <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>
  14069. <p>This API deletes the <em>local</em> media from the disk of your own server.</p>
  14070. <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>
  14071. <p>The purge history API allows server admins to purge historic events from their database, reclaiming disk space.</p>
  14072. <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>
  14073. <p>Tool for compressing (deduplicating) <code>state_groups_state</code> table.</p>
  14074. <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>
  14075. <p>Some easy SQL that reports useful stats about your Synapse database.</p>
  14076. <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>
  14077. <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>
  14078. <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>
  14079. <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>
  14080. <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>
  14081. <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>
  14082. <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>
  14083. <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>
  14084. <p>A full state group just records the event id for each piece of state in the room at that point.</p>
  14085. <h2 id="known-bugs-with-state-groups"><a class="header" href="#known-bugs-with-state-groups">Known bugs with state groups</a></h2>
  14086. <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>
  14087. <h2 id="compression-tool"><a class="header" href="#compression-tool">Compression tool</a></h2>
  14088. <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>
  14089. <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>
  14090. <p>HTTP request logs are written by synapse (see <a href="usage/administration/../synapse/http/site.py"><code>site.py</code></a> for details).</p>
  14091. <p>See the following for how to decode the dense data available from the default logging configuration.</p>
  14092. <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]
  14093. -AAAAAAAAAAAAAAAAAAAAA- -BBBBBBBBBBBBBBBBBBBBBB- -C- -DD- -EEEEEE- -FFFFFFFFF- -GG- -HHHHHHHHHHHHHHHHHHHHHHH- -IIIIII- -JJJJJJJ- -KKKKKK-, -LLLLLL- -MMMMMMM- -NNNNNN- O -P- -QQ- -RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR- -SSSSSSSSSSSS- -TTTTTT-
  14094. </code></pre>
  14095. <table><thead><tr><th>Part</th><th>Explanation</th></tr></thead><tbody>
  14096. <tr><td>AAAA</td><td>Timestamp request was logged (not received)</td></tr>
  14097. <tr><td>BBBB</td><td>Logger name (<code>synapse.access.(http\|https).&lt;tag&gt;</code>, where 'tag' is defined in the <code>listeners</code> config section, normally the port)</td></tr>
  14098. <tr><td>CCCC</td><td>Line number in code</td></tr>
  14099. <tr><td>DDDD</td><td>Log Level</td></tr>
  14100. <tr><td>EEEE</td><td>Request Identifier (This identifier is shared by related log lines)</td></tr>
  14101. <tr><td>FFFF</td><td>Source IP (Or X-Forwarded-For if enabled)</td></tr>
  14102. <tr><td>GGGG</td><td>Server Port</td></tr>
  14103. <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>
  14104. <tr><td>IIII</td><td>Total Time to process the request</td></tr>
  14105. <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>
  14106. <tr><td>KKKK</td><td>Userland CPU time</td></tr>
  14107. <tr><td>LLLL</td><td>System CPU time</td></tr>
  14108. <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>
  14109. <tr><td>NNNN</td><td>Total time waiting for response to DB queries across all parallel DB work from this request</td></tr>
  14110. <tr><td>OOOO</td><td>Count of DB transactions performed</td></tr>
  14111. <tr><td>PPPP</td><td>Response body size</td></tr>
  14112. <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>
  14113. <tr><td>RRRR</td><td>Request</td></tr>
  14114. <tr><td>SSSS</td><td>User-agent</td></tr>
  14115. <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>
  14116. </tbody></table>
  14117. <p>MMMM / NNNN can be greater than IIII if there are multiple slow database queries
  14118. running in parallel.</p>
  14119. <p>Some actions can result in multiple identical http requests, which will return
  14120. the same data, but only the first request will report time/transactions in
  14121. <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
  14122. response and will simultaneously return with the first request, but with very
  14123. small processing times.</p>
  14124. <div style="break-before: page; page-break-before: always;"></div><h2 id="admin-faq"><a class="header" href="#admin-faq">Admin FAQ</a></h2>
  14125. <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>
  14126. <p>If your server already has an admin account you should use the <a href="usage/administration/../../admin_api/user_admin_api.html#Change-whether-a-user-is-a-server-administrator-or-not">User Admin API</a> to promote other accounts to become admins.</p>
  14127. <p>If you don't have any admin accounts yet you won't be able to use the admin API, so you'll have to edit the database manually. Manually editing the database is generally not recommended so once you have an admin account: use the admin APIs to make further changes.</p>
  14128. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  14129. </code></pre>
  14130. <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>
  14131. <p>Run this sql query on your db:</p>
  14132. <pre><code class="language-sql">SELECT * FROM destinations;
  14133. </code></pre>
  14134. <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>
  14135. <p>Run this sql query on your db:</p>
  14136. <pre><code class="language-sql">SELECT DISTINCT split_part(state_key, ':', 2)
  14137. FROM current_state_events AS c
  14138. INNER JOIN room_memberships AS m USING (room_id, event_id)
  14139. WHERE room_id = '!cURbafjkfsMDVwdRDQ:matrix.org' AND membership = 'join';
  14140. </code></pre>
  14141. <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>
  14142. <pre><code class="language-sql">SELECT NAME from users;
  14143. </code></pre>
  14144. <h2 id="manually-resetting-passwords"><a class="header" href="#manually-resetting-passwords">Manually resetting passwords</a></h2>
  14145. <p>Users can reset their password through their client. Alternatively, a server admin
  14146. can reset a user's password using the <a href="usage/administration/../../admin_api/user_admin_api.html#reset-password">admin API</a>.</p>
  14147. <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>
  14148. <p>Deleting your database is unlikely to make anything better. </p>
  14149. <p>It's easy to make the mistake of thinking that you can start again from a clean slate by dropping your database, but things don't work like that in a federated network: lots of other servers have information about your server.</p>
  14150. <p>For example: other servers might think that you are in a room, your server will think that you are not, and you'll probably be unable to interact with that room in a sensible way ever again.</p>
  14151. <p>In general, there are better solutions to any problem than dropping the database. Come and seek help in https://matrix.to/#/#synapse:matrix.org.</p>
  14152. <p>There are two exceptions when it might be sensible to delete your database and start again:</p>
  14153. <ul>
  14154. <li>You have <em>never</em> joined any rooms which are federated with other servers. For instance, a local deployment which the outside world can't talk to. </li>
  14155. <li>You are changing the <code>server_name</code> in the homeserver configuration. In effect this makes your server a completely new one from the point of view of the network, so in this case it makes sense to start with a clean database.
  14156. (In both cases you probably also want to clear out the media_store.)</li>
  14157. </ul>
  14158. <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>
  14159. <p>Using the following curl command:</p>
  14160. <pre><code>curl -H 'Authorization: Bearer &lt;access-token&gt;' -X DELETE https://matrix.org/_matrix/client/r0/directory/room/&lt;room-alias&gt;
  14161. </code></pre>
  14162. <p><code>&lt;access-token&gt;</code> - can be obtained in riot by looking in the riot settings, down the bottom is:
  14163. Access Token:&lt;click to reveal&gt; </p>
  14164. <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>
  14165. <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>
  14166. <p>Synapse tags each log line according to the HTTP request it is processing. When it finishes processing each request, it logs a line containing the words <code>Processed request: </code>. For example:</p>
  14167. <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;
  14168. </code></pre>
  14169. <p>Here we can see that the request has been tagged with <code>GET-37</code>. (The tag depends on the method of the HTTP request, so might start with <code>GET-</code>, <code>PUT-</code>, <code>POST-</code>, <code>OPTIONS-</code> or <code>DELETE-</code>.) So to find all lines corresponding to this request, we can do:</p>
  14170. <pre><code>grep 'GET-37' homeserver.log
  14171. </code></pre>
  14172. <p>If you want to paste that output into a github issue or matrix room, please remember to surround it with triple-backticks (```) to make it legible (see https://help.github.com/en/articles/basic-writing-and-formatting-syntax#quoting-code).</p>
  14173. <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>
  14174. <p>See <a href="usage/administration/request_log.html">Request log format</a>.</p>
  14175. <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>
  14176. <pre><code class="language-sql">SELECT s.canonical_alias, g.room_id, count(*) AS num_rows
  14177. FROM
  14178. state_groups_state AS g,
  14179. room_stats_state AS s
  14180. WHERE g.room_id = s.room_id
  14181. GROUP BY s.canonical_alias, g.room_id
  14182. ORDER BY num_rows desc
  14183. LIMIT 10;
  14184. </code></pre>
  14185. <p>You can also use the <a href="usage/administration/../../admin_api/rooms.html#list-room-api">List Room API</a>
  14186. and <code>order_by</code> <code>state_events</code>.</p>
  14187. <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>
  14188. <p>The typical failure mode here is that you send an invitation to someone
  14189. to join a room or direct chat, but when they go to accept it, they get an
  14190. error (typically along the lines of &quot;Invalid signature&quot;). They might see
  14191. something like the following in their logs:</p>
  14192. <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;
  14193. </code></pre>
  14194. <p>This is normally caused by a misconfiguration in your reverse-proxy. See <a href="usage/administration/docs/reverse_proxy.html">the reverse proxy docs</a> and double-check that your settings are correct.</p>
  14195. <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>
  14196. <p>First, ensure you are running the latest version of Synapse, using Python 3
  14197. with a <a href="usage/administration/../../postgres.html">PostgreSQL database</a>.</p>
  14198. <p>Synapse's architecture is quite RAM hungry currently - we deliberately
  14199. cache a lot of recent room data and metadata in RAM in order to speed up
  14200. common requests. We'll improve this in the future, but for now the easiest
  14201. way to either reduce the RAM usage (at the risk of slowing things down)
  14202. is to set the almost-undocumented <code>SYNAPSE_CACHE_FACTOR</code> environment
  14203. variable. The default is 0.5, which can be decreased to reduce RAM usage
  14204. in memory constrained environments, or increased if performance starts to
  14205. degrade.</p>
  14206. <p>However, degraded performance due to a low cache factor, common on
  14207. machines with slow disks, often leads to explosions in memory use due
  14208. backlogged requests. In this case, reducing the cache factor will make
  14209. things worse. Instead, try increasing it drastically. 2.0 is a good
  14210. starting value.</p>
  14211. <p>Using <a href="https://jemalloc.net">libjemalloc</a> can also yield a significant
  14212. improvement in overall memory use, and especially in terms of giving back
  14213. RAM to the OS. To use it, the library must simply be put in the
  14214. LD_PRELOAD environment variable when launching Synapse. On Debian, this
  14215. can be done by installing the <code>libjemalloc1</code> package and adding this
  14216. line to <code>/etc/default/matrix-synapse</code>:</p>
  14217. <pre><code>LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.1
  14218. </code></pre>
  14219. <p>This made a significant difference on Python 2.7 - it's unclear how
  14220. much of an improvement it provides on Python 3.x.</p>
  14221. <p>If you're encountering high CPU use by the Synapse process itself, you
  14222. may be affected by a bug with presence tracking that leads to a
  14223. massive excess of outgoing federation requests (see <a href="https://github.com/matrix-org/synapse/issues/3971">discussion</a>). If metrics
  14224. indicate that your server is also issuing far more outgoing federation
  14225. requests than can be accounted for by your users' activity, this is a
  14226. likely cause. The misbehavior can be worked around by disabling presence
  14227. in the Synapse config file: <a href="usage/administration/../configuration/config_documentation.html#presence">see here</a>.</p>
  14228. <h2 id="running-out-of-file-handles"><a class="header" href="#running-out-of-file-handles">Running out of File Handles</a></h2>
  14229. <p>If Synapse runs out of file handles, it typically fails badly - live-locking
  14230. at 100% CPU, and/or failing to accept new TCP connections (blocking the
  14231. connecting client). Matrix currently can legitimately use a lot of file handles,
  14232. thanks to busy rooms like <code>#matrix:matrix.org</code> containing hundreds of participating
  14233. servers. The first time a server talks in a room it will try to connect
  14234. simultaneously to all participating servers, which could exhaust the available
  14235. file descriptors between DNS queries &amp; HTTPS sockets, especially if DNS is slow
  14236. to respond. (We need to improve the routing algorithm used to be better than
  14237. full mesh, but as of March 2019 this hasn't happened yet).</p>
  14238. <p>If you hit this failure mode, we recommend increasing the maximum number of
  14239. open file handles to be at least 4096 (assuming a default of 1024 or 256).
  14240. This is typically done by editing <code>/etc/security/limits.conf</code></p>
  14241. <p>Separately, Synapse may leak file handles if inbound HTTP requests get stuck
  14242. during processing - e.g. blocked behind a lock or talking to a remote server etc.
  14243. This is best diagnosed by matching up the 'Received request' and 'Processed request'
  14244. log lines and looking for any 'Processed request' lines which take more than
  14245. 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
  14246. you see this failure mode so we can help debug it, however.</p>
  14247. <div style="break-before: page; page-break-before: always;"></div><h1 id="contributing"><a class="header" href="#contributing">Contributing</a></h1>
  14248. <p>This document aims to get you started with contributing to Synapse!</p>
  14249. <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>
  14250. <p>Everyone is welcome to contribute code to <a href="https://github.com/matrix-org">matrix.org
  14251. projects</a>, provided that they are willing to
  14252. license their contributions under the same license as the project itself. We
  14253. follow a simple 'inbound=outbound' model for contributions: the act of
  14254. submitting an 'inbound' contribution means that the contributor agrees to
  14255. license the code under the same terms as the project's overall 'outbound'
  14256. license - in our case, this is almost always Apache Software License v2 (see
  14257. <a href="https://github.com/matrix-org/synapse/blob/develop/LICENSE">LICENSE</a>).</p>
  14258. <h1 id="2-what-do-i-need"><a class="header" href="#2-what-do-i-need">2. What do I need?</a></h1>
  14259. <p>If you are running Windows, the Windows Subsystem for Linux (WSL) is strongly
  14260. recommended for development. More information about WSL can be found at
  14261. <a href="https://docs.microsoft.com/en-us/windows/wsl/install">https://docs.microsoft.com/en-us/windows/wsl/install</a>. Running Synapse natively
  14262. on Windows is not officially supported.</p>
  14263. <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>
  14264. <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>
  14265. <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>
  14266. <p>For some tests, you will need <a href="https://docs.docker.com/get-docker/">a recent version of Docker</a>.</p>
  14267. <p>A recent version of the Rust compiler is needed to build the native modules. The
  14268. easiest way of installing the latest version is to use <a href="https://rustup.rs/">rustup</a>.</p>
  14269. <h1 id="3-get-the-source"><a class="header" href="#3-get-the-source">3. Get the source.</a></h1>
  14270. <p>The preferred and easiest way to contribute changes is to fork the relevant
  14271. 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
  14272. changes into our repo.</p>
  14273. <p>Please base your changes on the <code>develop</code> branch.</p>
  14274. <pre><code class="language-sh">git clone git@github.com:YOUR_GITHUB_USER_NAME/synapse.git
  14275. git checkout develop
  14276. </code></pre>
  14277. <p>If you need help getting started with git, this is beyond the scope of the document, but you
  14278. can find many good git tutorials on the web.</p>
  14279. <h1 id="4-install-the-dependencies"><a class="header" href="#4-install-the-dependencies">4. Install the dependencies</a></h1>
  14280. <p>Synapse uses the <a href="https://python-poetry.org/">poetry</a> project to manage its dependencies
  14281. and development environment. Once you have installed Python 3 and added the
  14282. source, you should install <code>poetry</code>.
  14283. Of their installation methods, we recommend
  14284. <a href="https://python-poetry.org/docs/#installing-with-pipx">installing <code>poetry</code> using <code>pipx</code></a>,</p>
  14285. <pre><code class="language-shell">pip install --user pipx
  14286. pipx install poetry
  14287. </code></pre>
  14288. <p>but see poetry's <a href="https://python-poetry.org/docs/#installation">installation instructions</a>
  14289. for other installation methods.</p>
  14290. <p>Synapse requires Poetry version 1.2.0 or later.</p>
  14291. <p>Next, open a terminal and install dependencies as follows:</p>
  14292. <pre><code class="language-sh">cd path/where/you/have/cloned/the/repository
  14293. poetry install --extras all
  14294. </code></pre>
  14295. <p>This will install the runtime and developer dependencies for the project.</p>
  14296. <h1 id="5-get-in-touch"><a class="header" href="#5-get-in-touch">5. Get in touch.</a></h1>
  14297. <p>Join our developer community on Matrix: <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>!</p>
  14298. <h1 id="6-pick-an-issue"><a class="header" href="#6-pick-an-issue">6. Pick an issue.</a></h1>
  14299. <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>
  14300. to work on.</p>
  14301. <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>
  14302. <p>There is a growing amount of documentation located in the
  14303. <a href="https://github.com/matrix-org/synapse/tree/develop/docs"><code>docs</code></a>
  14304. directory, with a rendered version <a href="https://matrix-org.github.io/synapse">available online</a>.
  14305. This documentation is intended primarily for sysadmins running their
  14306. own Synapse instance, as well as developers interacting externally with
  14307. Synapse.
  14308. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/development"><code>docs/development</code></a>
  14309. exists primarily to house documentation for
  14310. Synapse developers.
  14311. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/admin_api"><code>docs/admin_api</code></a> houses documentation
  14312. regarding Synapse's Admin API, which is used mostly by sysadmins and external
  14313. service developers.</p>
  14314. <p>Synapse's code style is documented <a href="development/../code_style.html">here</a>. Please follow
  14315. it, including the conventions for the <a href="development/../code_style.html#configuration-file-format">sample configuration
  14316. file</a>.</p>
  14317. <p>We welcome improvements and additions to our documentation itself! When
  14318. writing new pages, please
  14319. <a href="https://github.com/matrix-org/synapse/tree/develop/docs#adding-to-the-documentation">build <code>docs</code> to a book</a>
  14320. to check that your contributions render correctly. The docs are written in
  14321. <a href="https://guides.github.com/features/mastering-markdown/">GitHub-Flavoured Markdown</a>.</p>
  14322. <p>Some documentation also exists in <a href="https://github.com/matrix-org/synapse/wiki">Synapse's GitHub
  14323. Wiki</a>, although this is primarily
  14324. contributed to by community authors.</p>
  14325. <p>When changes are made to any Rust code then you must call either <code>poetry install</code>
  14326. or <code>maturin develop</code> (if installed) to rebuild the Rust code. Using <a href="https://github.com/PyO3/maturin"><code>maturin</code></a>
  14327. is quicker than <code>poetry install</code>, so is recommended when making frequent
  14328. changes to the Rust code.</p>
  14329. <h1 id="8-test-test-test"><a class="header" href="#8-test-test-test">8. Test, test, test!</a></h1>
  14330. <p><a name="test-test-test"></a></p>
  14331. <p>While you're developing and before submitting a patch, you'll
  14332. want to test your code.</p>
  14333. <h2 id="run-the-linters"><a class="header" href="#run-the-linters">Run the linters.</a></h2>
  14334. <p>The linters look at your code and do two things:</p>
  14335. <ul>
  14336. <li>ensure that your code follows the coding style adopted by the project;</li>
  14337. <li>catch a number of errors in your code.</li>
  14338. </ul>
  14339. <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>
  14340. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh
  14341. </code></pre>
  14342. <p>Note that this script <em>will modify your files</em> to fix styling errors.
  14343. Make sure that you have saved all your files.</p>
  14344. <p>If you wish to restrict the linters to only the files changed since the last commit
  14345. (much faster!), you can instead run:</p>
  14346. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh -d
  14347. </code></pre>
  14348. <p>Or if you know exactly which files you wish to lint, you can instead run:</p>
  14349. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh path/to/file1.py path/to/file2.py path/to/folder
  14350. </code></pre>
  14351. <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>
  14352. <p>The unit tests run parts of Synapse, including your changes, to see if anything
  14353. was broken. They are slower than the linters but will typically catch more errors.</p>
  14354. <pre><code class="language-sh">poetry run trial tests
  14355. </code></pre>
  14356. <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>
  14357. <pre><code class="language-sh">poetry run trial -j4 tests
  14358. </code></pre>
  14359. <p>If you wish to only run <em>some</em> unit tests, you may specify
  14360. another module instead of <code>tests</code> - or a test class or a method:</p>
  14361. <pre><code class="language-sh">poetry run trial tests.rest.admin.test_room tests.handlers.test_admin.ExfiltrateData.test_invite
  14362. </code></pre>
  14363. <p>If your tests fail, you may wish to look at the logs (the default log level is <code>ERROR</code>):</p>
  14364. <pre><code class="language-sh">less _trial_temp/test.log
  14365. </code></pre>
  14366. <p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>:</p>
  14367. <pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG poetry run trial tests
  14368. </code></pre>
  14369. <p>By default, tests will use an in-memory SQLite database for test data. For additional
  14370. help with debugging, one can use an on-disk SQLite database file instead, in order to
  14371. review database state during and after running tests. This can be done by setting
  14372. the <code>SYNAPSE_TEST_PERSIST_SQLITE_DB</code> environment variable. Doing so will cause the
  14373. database state to be stored in a file named <code>test.db</code> under the trial process'
  14374. working directory. Typically, this ends up being <code>_trial_temp/test.db</code>. For example:</p>
  14375. <pre><code class="language-sh">SYNAPSE_TEST_PERSIST_SQLITE_DB=1 poetry run trial tests
  14376. </code></pre>
  14377. <p>The database file can then be inspected with:</p>
  14378. <pre><code class="language-sh">sqlite3 _trial_temp/test.db
  14379. </code></pre>
  14380. <p>Note that the database file is cleared at the beginning of each test run. Thus it
  14381. will always only contain the data generated by the <em>last run test</em>. Though generally
  14382. when debugging, one is only running a single test anyway.</p>
  14383. <h3 id="running-tests-under-postgresql"><a class="header" href="#running-tests-under-postgresql">Running tests under PostgreSQL</a></h3>
  14384. <p>Invoking <code>trial</code> as above will use an in-memory SQLite database. This is great for
  14385. quick development and testing. However, we recommend using a PostgreSQL database
  14386. in production (and indeed, we have some code paths specific to each database).
  14387. This means that we need to run our unit tests against PostgreSQL too. Our CI does
  14388. this automatically for pull requests and release candidates, but it's sometimes
  14389. useful to reproduce this locally.</p>
  14390. <h4 id="using-docker"><a class="header" href="#using-docker">Using Docker</a></h4>
  14391. <p>The easiest way to do so is to run Postgres via a docker container. In one
  14392. terminal:</p>
  14393. <pre><code class="language-shell">docker run --rm -e POSTGRES_PASSWORD=mysecretpassword -e POSTGRES_USER=postgres -e POSTGRES_DB=postgress -p 5432:5432 postgres:14
  14394. </code></pre>
  14395. <p>If you see an error like</p>
  14396. <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.
  14397. </code></pre>
  14398. <p>then something is already bound to port 5432. You're probably already running postgres locally.</p>
  14399. <p>Once you have a postgres server running, invoke <code>trial</code> in a second terminal:</p>
  14400. <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
  14401. </code></pre>
  14402. <h4 id="using-an-existing-postgres-installation"><a class="header" href="#using-an-existing-postgres-installation">Using an existing Postgres installation</a></h4>
  14403. <p>If you have postgres already installed on your system, you can run <code>trial</code> with the
  14404. following environment variables matching your configuration:</p>
  14405. <ul>
  14406. <li><code>SYNAPSE_POSTGRES</code> to anything nonempty</li>
  14407. <li><code>SYNAPSE_POSTGRES_HOST</code> (optional if it's the default: UNIX socket)</li>
  14408. <li><code>SYNAPSE_POSTGRES_PORT</code> (optional if it's the default: 5432)</li>
  14409. <li><code>SYNAPSE_POSTGRES_USER</code> (optional if using a UNIX socket)</li>
  14410. <li><code>SYNAPSE_POSTGRES_PASSWORD</code> (optional if using a UNIX socket)</li>
  14411. </ul>
  14412. <p>For example:</p>
  14413. <pre><code class="language-shell">export SYNAPSE_POSTGRES=1
  14414. export SYNAPSE_POSTGRES_HOST=localhost
  14415. export SYNAPSE_POSTGRES_USER=postgres
  14416. export SYNAPSE_POSTGRES_PASSWORD=mydevenvpassword
  14417. trial
  14418. </code></pre>
  14419. <p>You don't need to specify the host, user, port or password if your Postgres
  14420. server is set to authenticate you over the UNIX socket (i.e. if the <code>psql</code> command
  14421. works without further arguments).</p>
  14422. <p>Your Postgres account needs to be able to create databases; see the postgres
  14423. docs for <a href="https://www.postgresql.org/docs/current/sql-alterrole.html"><code>ALTER ROLE</code></a>.</p>
  14424. <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>
  14425. <p>The integration tests are a more comprehensive suite of tests. They
  14426. run a full version of Synapse, including your changes, to check if
  14427. anything was broken. They are slower than the unit tests but will
  14428. typically catch more errors.</p>
  14429. <p>The following command will let you run the integration test with the most common
  14430. configuration:</p>
  14431. <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:buster
  14432. </code></pre>
  14433. <p>(Note that the paths must be full paths! You could also write <code>$(realpath relative/path)</code> if needed.)</p>
  14434. <p>This configuration should generally cover your needs.</p>
  14435. <ul>
  14436. <li>To run with Postgres, supply the <code>-e POSTGRES=1 -e MULTI_POSTGRES=1</code> environment flags.</li>
  14437. <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>
  14438. </ul>
  14439. <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>
  14440. <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>
  14441. <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>
  14442. <p>It's often nice to develop on Synapse and write Complement tests at the same time.
  14443. Here is how to run your local Synapse checkout against your local Complement checkout.</p>
  14444. <p>(checkout <a href="https://github.com/matrix-org/complement"><code>complement</code></a> alongside your <code>synapse</code> checkout)</p>
  14445. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh
  14446. </code></pre>
  14447. <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>
  14448. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
  14449. </code></pre>
  14450. <p>To run a specific test, you can specify the whole name structure:</p>
  14451. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages/parallel/Historical_events_resolve_in_the_correct_order
  14452. </code></pre>
  14453. <p>The above will run a monolithic (single-process) Synapse with SQLite as the database. For other configurations, try:</p>
  14454. <ul>
  14455. <li>Passing <code>POSTGRES=1</code> as an environment variable to use the Postgres database instead.</li>
  14456. <li>Passing <code>WORKERS=1</code> as an environment variable to use a workerised setup instead. This option implies the use of Postgres.</li>
  14457. </ul>
  14458. <p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>, e.g:</p>
  14459. <pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
  14460. </code></pre>
  14461. <h3 id="prettier-formatting-with-gotestfmt"><a class="header" href="#prettier-formatting-with-gotestfmt">Prettier formatting with <code>gotestfmt</code></a></h3>
  14462. <p>If you want to format the output of the tests the same way as it looks in CI,
  14463. install <a href="https://github.com/haveyoudebuggedit/gotestfmt">gotestfmt</a>.</p>
  14464. <p>You can then use this incantation to format the tests appropriately:</p>
  14465. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -json | gotestfmt -hide successful-tests
  14466. </code></pre>
  14467. <p>(Remove <code>-hide successful-tests</code> if you don't want to hide successful tests.)</p>
  14468. <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>
  14469. <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>
  14470. <ol>
  14471. <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>
  14472. <li>Start the Complement tests</li>
  14473. <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>
  14474. <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>
  14475. <li>Install sqlite (database driver), <code>apt-get update &amp;&amp; apt-get install -y sqlite3</code></li>
  14476. <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>
  14477. </ol>
  14478. <h1 id="9-submit-your-patch"><a class="header" href="#9-submit-your-patch">9. Submit your patch.</a></h1>
  14479. <p>Once you're happy with your patch, it's time to prepare a Pull Request.</p>
  14480. <p>To prepare a Pull Request, please:</p>
  14481. <ol>
  14482. <li>verify that <a href="development/contributing_guide.html#test-test-test">all the tests pass</a>, including the coding style;</li>
  14483. <li><a href="development/contributing_guide.html#sign-off">sign off</a> your contribution;</li>
  14484. <li><code>git push</code> your commit to your fork of Synapse;</li>
  14485. <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>
  14486. <li>add a <a href="development/contributing_guide.html#changelog">changelog entry</a> and push it to your Pull Request;</li>
  14487. <li>that's it for now, a non-draft pull request will automatically request review from the team;</li>
  14488. <li>if you need to update your PR, please avoid rebasing and just add new commits to your branch.</li>
  14489. </ol>
  14490. <h2 id="changelog"><a class="header" href="#changelog">Changelog</a></h2>
  14491. <p>All changes, even minor ones, need a corresponding changelog / newsfragment
  14492. entry. These are managed by <a href="https://github.com/hawkowl/towncrier">Towncrier</a>.</p>
  14493. <p>To create a changelog entry, make a new file in the <code>changelog.d</code> directory named
  14494. in the format of <code>PRnumber.type</code>. The type can be one of the following:</p>
  14495. <ul>
  14496. <li><code>feature</code></li>
  14497. <li><code>bugfix</code></li>
  14498. <li><code>docker</code> (for updates to the Docker image)</li>
  14499. <li><code>doc</code> (for updates to the documentation)</li>
  14500. <li><code>removal</code> (also used for deprecations)</li>
  14501. <li><code>misc</code> (for internal-only changes)</li>
  14502. </ul>
  14503. <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
  14504. release, so the content of the file should be a short description of your
  14505. change in the same style as the rest of the changelog. The file can contain Markdown
  14506. formatting, and should end with a full stop (.) or an exclamation mark (!) for
  14507. consistency.</p>
  14508. <p>Adding credits to the changelog is encouraged, we value your
  14509. contributions and would like to have you shouted out in the release notes!</p>
  14510. <p>For example, a fix in PR #1234 would have its changelog entry in
  14511. <code>changelog.d/1234.bugfix</code>, and contain content like:</p>
  14512. <blockquote>
  14513. <p>The security levels of Florbs are now validated when received
  14514. via the <code>/federation/florb</code> endpoint. Contributed by Jane Matrix.</p>
  14515. </blockquote>
  14516. <p>If there are multiple pull requests involved in a single bugfix/feature/etc,
  14517. then the content for each <code>changelog.d</code> file should be the same. Towncrier will
  14518. merge the matching files together into a single changelog entry when we come to
  14519. release.</p>
  14520. <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>
  14521. <p>Obviously, you don't know if you should call your newsfile
  14522. <code>1234.bugfix</code> or <code>5678.bugfix</code> until you create the PR, which leads to a
  14523. chicken-and-egg problem.</p>
  14524. <p>There are two options for solving this:</p>
  14525. <ol>
  14526. <li>
  14527. <p>Open the PR without a changelog file, see what number you got, and <em>then</em>
  14528. add the changelog file to your branch (see <a href="development/contributing_guide.html#updating-your-pull-request">Updating your pull
  14529. request</a>), or:</p>
  14530. </li>
  14531. <li>
  14532. <p>Look at the <a href="https://github.com/matrix-org/synapse/issues?q=">list of all
  14533. issues/PRs</a>, add one to the
  14534. highest number you see, and quickly open the PR before somebody else claims
  14535. your number.</p>
  14536. <p><a href="https://github.com/richvdh/scripts/blob/master/next_github_number.sh">This
  14537. script</a>
  14538. might be helpful if you find yourself doing this a lot.</p>
  14539. </li>
  14540. </ol>
  14541. <p>Sorry, we know it's a bit fiddly, but it's <em>really</em> helpful for us when we come
  14542. to put together a release!</p>
  14543. <h3 id="debian-changelog"><a class="header" href="#debian-changelog">Debian changelog</a></h3>
  14544. <p>Changes which affect the debian packaging files (in <code>debian</code>) are an
  14545. exception to the rule that all changes require a <code>changelog.d</code> file.</p>
  14546. <p>In this case, you will need to add an entry to the debian changelog for the
  14547. next release. For this, run the following command:</p>
  14548. <pre><code>dch
  14549. </code></pre>
  14550. <p>This will make up a new version number (if there isn't already an unreleased
  14551. version in flight), and open an editor where you can add a new changelog entry.
  14552. (Our release process will ensure that the version number and maintainer name is
  14553. corrected for the release.)</p>
  14554. <p>If your change affects both the debian packaging <em>and</em> files outside the debian
  14555. directory, you will need both a regular newsfragment <em>and</em> an entry in the
  14556. debian changelog. (Though typically such changes should be submitted as two
  14557. separate pull requests.)</p>
  14558. <h2 id="sign-off"><a class="header" href="#sign-off">Sign off</a></h2>
  14559. <p>In order to have a concrete record that your contribution is intentional
  14560. and you agree to license it under the same terms as the project's license, we've adopted the
  14561. same lightweight approach that the Linux Kernel
  14562. <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>,
  14563. <a href="https://github.com/docker/docker/blob/master/CONTRIBUTING.md">Docker</a>, and many other
  14564. projects use: the DCO (<a href="http://developercertificate.org/">Developer Certificate of Origin</a>).
  14565. This is a simple declaration that you wrote
  14566. the contribution or otherwise have the right to contribute it to Matrix:</p>
  14567. <pre><code>Developer Certificate of Origin
  14568. Version 1.1
  14569. Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
  14570. 660 York Street, Suite 102,
  14571. San Francisco, CA 94110 USA
  14572. Everyone is permitted to copy and distribute verbatim copies of this
  14573. license document, but changing it is not allowed.
  14574. Developer's Certificate of Origin 1.1
  14575. By making a contribution to this project, I certify that:
  14576. (a) The contribution was created in whole or in part by me and I
  14577. have the right to submit it under the open source license
  14578. indicated in the file; or
  14579. (b) The contribution is based upon previous work that, to the best
  14580. of my knowledge, is covered under an appropriate open source
  14581. license and I have the right under that license to submit that
  14582. work with modifications, whether created in whole or in part
  14583. by me, under the same open source license (unless I am
  14584. permitted to submit under a different license), as indicated
  14585. in the file; or
  14586. (c) The contribution was provided directly to me by some other
  14587. person who certified (a), (b) or (c) and I have not modified
  14588. it.
  14589. (d) I understand and agree that this project and the contribution
  14590. are public and that a record of the contribution (including all
  14591. personal information I submit with it, including my sign-off) is
  14592. maintained indefinitely and may be redistributed consistent with
  14593. this project or the open source license(s) involved.
  14594. </code></pre>
  14595. <p>If you agree to this for your contribution, then all that's needed is to
  14596. include the line in your commit or pull request comment:</p>
  14597. <pre><code>Signed-off-by: Your Name &lt;your@email.example.org&gt;
  14598. </code></pre>
  14599. <p>We accept contributions under a legally identifiable name, such as
  14600. your name on government documentation or common-law names (names
  14601. claimed by legitimate usage or repute). Unfortunately, we cannot
  14602. accept anonymous contributions at this time.</p>
  14603. <p>Git allows you to add this signoff automatically when using the <code>-s</code>
  14604. flag to <code>git commit</code>, which uses the name and email set in your
  14605. <code>user.name</code> and <code>user.email</code> git configs.</p>
  14606. <h3 id="private-sign-off"><a class="header" href="#private-sign-off">Private Sign off</a></h3>
  14607. <p>If you would like to provide your legal name privately to the Matrix.org
  14608. Foundation (instead of in a public commit or comment), you can do so
  14609. by emailing your legal name and a link to the pull request to
  14610. <a href="mailto:dco@matrix.org?subject=Private%20sign%20off">dco@matrix.org</a>.
  14611. It helps to include &quot;sign off&quot; or similar in the subject line. You will then
  14612. be instructed further.</p>
  14613. <p>Once private sign off is complete, doing so for future contributions will not
  14614. be required.</p>
  14615. <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>
  14616. <p>Once the Pull Request is opened, you will see a few things:</p>
  14617. <ol>
  14618. <li>our automated CI (Continuous Integration) pipeline will run (again) the linters, the unit tests, the integration tests and more;</li>
  14619. <li>one or more of the developers will take a look at your Pull Request and offer feedback.</li>
  14620. </ol>
  14621. <p>From this point, you should:</p>
  14622. <ol>
  14623. <li>Look at the results of the CI pipeline.
  14624. <ul>
  14625. <li>If there is any error, fix the error.</li>
  14626. </ul>
  14627. </li>
  14628. <li>If a developer has requested changes, make these changes and let us know if it is ready for a developer to review again.
  14629. <ul>
  14630. <li>A pull request is a conversation, if you disagree with the suggestions, please respond and discuss it.</li>
  14631. </ul>
  14632. </li>
  14633. <li>Create a new commit with the changes.
  14634. <ul>
  14635. <li>Please do NOT overwrite the history. New commits make the reviewer's life easier.</li>
  14636. <li>Push this commits to your Pull Request.</li>
  14637. </ul>
  14638. </li>
  14639. <li>Back to 1.</li>
  14640. <li>Once the pull request is ready for review again please re-request review from whichever developer did your initial
  14641. review (or leave a comment in the pull request that you believe all required changes have been done).</li>
  14642. </ol>
  14643. <p>Once both the CI and the developers are happy, the patch will be merged into Synapse and released shortly!</p>
  14644. <h1 id="11-find-a-new-issue"><a class="header" href="#11-find-a-new-issue">11. Find a new issue.</a></h1>
  14645. <p>By now, you know the drill!</p>
  14646. <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>
  14647. <p>There are some notes for those with commit access to the project on how we
  14648. manage git <a href="development/git.html">here</a>.</p>
  14649. <h1 id="conclusion"><a class="header" href="#conclusion">Conclusion</a></h1>
  14650. <p>That's it! Matrix is a very open and collaborative project as you might expect
  14651. given our obsession with open communication. If we're going to successfully
  14652. matrix together all the fragmented communication technologies out there we are
  14653. reliant on contributions and collaboration from the community to do so. So
  14654. please get involved - and we hope you have as much fun hacking on Matrix as we
  14655. do!</p>
  14656. <div style="break-before: page; page-break-before: always;"></div><h1 id="code-style"><a class="header" href="#code-style">Code Style</a></h1>
  14657. <h2 id="formatting-tools"><a class="header" href="#formatting-tools">Formatting tools</a></h2>
  14658. <p>The Synapse codebase uses a number of code formatting tools in order to
  14659. quickly and automatically check for formatting (and sometimes logical)
  14660. errors in code.</p>
  14661. <p>The necessary tools are:</p>
  14662. <ul>
  14663. <li><a href="https://black.readthedocs.io/en/stable/">black</a>, a source code formatter;</li>
  14664. <li><a href="https://pycqa.github.io/isort/">isort</a>, which organises each file's imports;</li>
  14665. <li><a href="https://flake8.pycqa.org/en/latest/">flake8</a>, which can spot common errors; and</li>
  14666. <li><a href="https://mypy.readthedocs.io/en/stable/">mypy</a>, a type checker.</li>
  14667. </ul>
  14668. <p>Install them with:</p>
  14669. <pre><code class="language-sh">pip install -e &quot;.[lint,mypy]&quot;
  14670. </code></pre>
  14671. <p>The easiest way to run the lints is to invoke the linter script as follows.</p>
  14672. <pre><code class="language-sh">scripts-dev/lint.sh
  14673. </code></pre>
  14674. <p>It's worth noting that modern IDEs and text editors can run these tools
  14675. automatically on save. It may be worth looking into whether this
  14676. functionality is supported in your editor for a more convenient
  14677. development workflow. It is not, however, recommended to run <code>flake8</code> or <code>mypy</code>
  14678. on save as they take a while and can be very resource intensive.</p>
  14679. <h2 id="general-rules"><a class="header" href="#general-rules">General rules</a></h2>
  14680. <ul>
  14681. <li><strong>Naming</strong>:
  14682. <ul>
  14683. <li>Use <code>CamelCase</code> for class and type names</li>
  14684. <li>Use underscores for <code>function_names</code> and <code>variable_names</code>.</li>
  14685. </ul>
  14686. </li>
  14687. <li><strong>Docstrings</strong>: should follow the <a href="https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings">google code
  14688. style</a>.
  14689. See the
  14690. <a href="http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html">examples</a>
  14691. in the sphinx documentation.</li>
  14692. <li><strong>Imports</strong>:
  14693. <ul>
  14694. <li>
  14695. <p>Imports should be sorted by <code>isort</code> as described above.</p>
  14696. </li>
  14697. <li>
  14698. <p>Prefer to import classes and functions rather than packages or
  14699. modules.</p>
  14700. <p>Example:</p>
  14701. <pre><code class="language-python">from synapse.types import UserID
  14702. ...
  14703. user_id = UserID(local, server)
  14704. </code></pre>
  14705. <p>is preferred over:</p>
  14706. <pre><code class="language-python">from synapse import types
  14707. ...
  14708. user_id = types.UserID(local, server)
  14709. </code></pre>
  14710. <p>(or any other variant).</p>
  14711. <p>This goes against the advice in the Google style guide, but it
  14712. means that errors in the name are caught early (at import time).</p>
  14713. </li>
  14714. <li>
  14715. <p>Avoid wildcard imports (<code>from synapse.types import *</code>) and
  14716. relative imports (<code>from .types import UserID</code>).</p>
  14717. </li>
  14718. </ul>
  14719. </li>
  14720. </ul>
  14721. <h2 id="configuration-code-and-documentation-format"><a class="header" href="#configuration-code-and-documentation-format">Configuration code and documentation format</a></h2>
  14722. <p>When adding a configuration option to the code, if several settings are grouped into a single dict, ensure that your code
  14723. correctly handles the top-level option being set to <code>None</code> (as it will be if no sub-options are enabled).</p>
  14724. <p>The <a href="usage/configuration/config_documentation.html">configuration manual</a> acts as a
  14725. reference to Synapse's configuration options for server administrators.
  14726. Remember that many readers will be unfamiliar with YAML and server
  14727. administration in general, so it is important that when you add
  14728. a configuration option the documentation be as easy to understand as possible, which
  14729. includes following a consistent format.</p>
  14730. <p>Some guidelines follow:</p>
  14731. <ul>
  14732. <li>
  14733. <p>Each option should be listed in the config manual with the following format:</p>
  14734. <ul>
  14735. <li>
  14736. <p>The name of the option, prefixed by <code>###</code>. </p>
  14737. </li>
  14738. <li>
  14739. <p>A comment which describes the default behaviour (i.e. what
  14740. happens if the setting is omitted), as well as what the effect
  14741. will be if the setting is changed.</p>
  14742. </li>
  14743. <li>
  14744. <p>An example setting, using backticks to define the code block</p>
  14745. <p>For boolean (on/off) options, convention is that this example
  14746. should be the <em>opposite</em> to the default. For other options, the example should give
  14747. some non-default value which is likely to be useful to the reader.</p>
  14748. </li>
  14749. </ul>
  14750. </li>
  14751. <li>
  14752. <p>There should be a horizontal rule between each option, which can be achieved by adding <code>---</code> before and
  14753. after the option.</p>
  14754. </li>
  14755. <li>
  14756. <p><code>true</code> and <code>false</code> are spelt thus (as opposed to <code>True</code>, etc.)</p>
  14757. </li>
  14758. </ul>
  14759. <p>Example:</p>
  14760. <hr />
  14761. <h3 id="modules-3"><a class="header" href="#modules-3"><code>modules</code></a></h3>
  14762. <p>Use the <code>module</code> sub-option to add a module under <code>modules</code> to extend functionality.
  14763. The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
  14764. for the <code>module</code>.</p>
  14765. <p>Defaults to none.</p>
  14766. <p>Example configuration:</p>
  14767. <pre><code class="language-yaml">modules:
  14768. - module: my_super_module.MySuperClass
  14769. config:
  14770. do_thing: true
  14771. - module: my_other_super_module.SomeClass
  14772. config: {}
  14773. </code></pre>
  14774. <hr />
  14775. <p>Note that the sample configuration is generated from the synapse code
  14776. and is maintained by a script, <code>scripts-dev/generate_sample_config.sh</code>.
  14777. Making sure that the output from this script matches the desired format
  14778. is left as an exercise for the reader!</p>
  14779. <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>
  14780. <p>The Synapse team works off a shared review queue -- any new pull requests for
  14781. Synapse (or related projects) has a review requested from the entire team. Team
  14782. members should process this queue using the following rules:</p>
  14783. <ul>
  14784. <li>Any high urgency pull requests (e.g. fixes for broken continuous integration
  14785. or fixes for release blockers);</li>
  14786. <li>Follow-up reviews for pull requests which have previously received reviews;</li>
  14787. <li>Any remaining pull requests.</li>
  14788. </ul>
  14789. <p>For the latter two categories above, older pull requests should be prioritised.</p>
  14790. <p>It is explicit that there is no priority given to pull requests from the team
  14791. (vs from the community). If a pull request requires a quick turn around, please
  14792. explicitly communicate this via <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>
  14793. or as a comment on the pull request.</p>
  14794. <p>Once an initial review has been completed and the author has made additional changes,
  14795. follow-up reviews should go back to the same reviewer. This helps build a shared
  14796. context and conversation between author and reviewer.</p>
  14797. <p>As a team we aim to keep the number of inflight pull requests to a minimum to ensure
  14798. that ongoing work is finished before starting new work.</p>
  14799. <h2 id="performing-a-review"><a class="header" href="#performing-a-review">Performing a review</a></h2>
  14800. <p>To communicate to the rest of the team the status of each pull request, team
  14801. members should do the following:</p>
  14802. <ul>
  14803. <li>Assign themselves to the pull request (they should be left assigned to the
  14804. pull request until it is merged, closed, or are no longer the reviewer);</li>
  14805. <li>Review the pull request by leaving comments, questions, and suggestions;</li>
  14806. <li>Mark the pull request appropriately (as needing changes or accepted).</li>
  14807. </ul>
  14808. <p>If you are unsure about a particular part of the pull request (or are not confident
  14809. in your understanding of part of the code) then ask questions or request review
  14810. from the team again. When requesting review from the team be sure to leave a comment
  14811. with the rationale on why you're putting it back in the queue.</p>
  14812. <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>
  14813. <p>Releases of Synapse follow a two week release cycle with new releases usually
  14814. occurring on Tuesdays:</p>
  14815. <ul>
  14816. <li>Day 0: Synapse <code>N - 1</code> is released.</li>
  14817. <li>Day 7: Synapse <code>N</code> release candidate 1 is released.</li>
  14818. <li>Days 7 - 13: Synapse <code>N</code> release candidates 2+ are released, if bugs are found.</li>
  14819. <li>Day 14: Synapse <code>N</code> is released.</li>
  14820. </ul>
  14821. <p>Note that this schedule might be modified depending on the availability of the
  14822. Synapse team, e.g. releases may be skipped to avoid holidays.</p>
  14823. <p>Release announcements can be found in the
  14824. <a href="https://matrix.org/blog/category/releases">release category of the Matrix blog</a>.</p>
  14825. <h2 id="bugfix-releases"><a class="header" href="#bugfix-releases">Bugfix releases</a></h2>
  14826. <p>If a bug is found after release that is deemed severe enough (by a combination
  14827. of the impacted users and the impact on those users) then a bugfix release may
  14828. be issued. This may be at any point in the release cycle.</p>
  14829. <h2 id="security-releases"><a class="header" href="#security-releases">Security releases</a></h2>
  14830. <p>Security will sometimes be backported to the previous version and released
  14831. immediately before the next release candidate. An example of this might be:</p>
  14832. <ul>
  14833. <li>Day 0: Synapse N - 1 is released.</li>
  14834. <li>Day 7: Synapse (N - 1).1 is released as Synapse N - 1 + the security fix.</li>
  14835. <li>Day 7: Synapse N release candidate 1 is released (including the security fix).</li>
  14836. </ul>
  14837. <p>Depending on the impact and complexity of security fixes, multiple fixes might
  14838. be held to be released together.</p>
  14839. <p>In some cases, a pre-disclosure of a security release will be issued as a notice
  14840. to Synapse operators that there is an upcoming security release. These can be
  14841. found in the <a href="https://matrix.org/blog/category/security">security category of the Matrix blog</a>.</p>
  14842. <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>
  14843. <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>
  14844. <p>In an ideal world, our git commit history would be a linear progression of
  14845. commits each of which contains a single change building on what came
  14846. before. Here, by way of an arbitrary example, is the top of <code>git log --graph b2dba0607</code>:</p>
  14847. <img src="development/img/git/clean.png" alt="clean git graph" width="500px">
  14848. <p>Note how the commit comment explains clearly what is changing and why. Also
  14849. note the <em>absence</em> of merge commits, as well as the absence of commits called
  14850. things like (to pick a few culprits):
  14851. <a href="https://github.com/matrix-org/synapse/commit/84691da6c">“pep8”</a>, <a href="https://github.com/matrix-org/synapse/commit/474810d9d">“fix broken
  14852. test”</a>,
  14853. <a href="https://github.com/matrix-org/synapse/commit/c9d72e457">“oops”</a>,
  14854. <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
  14855. the president?”</a>.</p>
  14856. <p>There are a number of reasons why keeping a clean commit history is a good
  14857. thing:</p>
  14858. <ul>
  14859. <li>
  14860. <p>From time to time, after a change lands, it turns out to be necessary to
  14861. revert it, or to backport it to a release branch. Those operations are
  14862. <em>much</em> easier when the change is contained in a single commit.</p>
  14863. </li>
  14864. <li>
  14865. <p>Similarly, it's much easier to answer questions like “is the fix for
  14866. <code>/publicRooms</code> on the release branch?” if that change consists of a single
  14867. commit.</p>
  14868. </li>
  14869. <li>
  14870. <p>Likewise: “what has changed on this branch in the last week?” is much
  14871. clearer without merges and “pep8” commits everywhere.</p>
  14872. </li>
  14873. <li>
  14874. <p>Sometimes we need to figure out where a bug got introduced, or some
  14875. behaviour changed. One way of doing that is with <code>git bisect</code>: pick an
  14876. arbitrary commit between the known good point and the known bad point, and
  14877. see how the code behaves. However, that strategy fails if the commit you
  14878. chose is the middle of someone's epic branch in which they broke the world
  14879. before putting it back together again.</p>
  14880. </li>
  14881. </ul>
  14882. <p>One counterargument is that it is sometimes useful to see how a PR evolved as
  14883. it went through review cycles. This is true, but that information is always
  14884. 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
  14885. namespace</a>).</p>
  14886. <p>Of course, in reality, things are more complicated than that. We have release
  14887. branches as well as <code>develop</code> and <code>master</code>, and we deliberately merge changes
  14888. between them. Bugs often slip through and have to be fixed later. That's all
  14889. fine: this not a cast-iron rule which must be obeyed, but an ideal to aim
  14890. towards.</p>
  14891. <h2 id="merges-squashes-rebases-wtf"><a class="header" href="#merges-squashes-rebases-wtf">Merges, squashes, rebases: wtf?</a></h2>
  14892. <p>Ok, so that's what we'd like to achieve. How do we achieve it?</p>
  14893. <p>The TL;DR is: when you come to merge a pull request, you <em>probably</em> want to
  14894. “squash and merge”:</p>
  14895. <p><img src="development/img/git/squash.png" alt="squash and merge" />.</p>
  14896. <p>(This applies whether you are merging your own PR, or that of another
  14897. contributor.)</p>
  14898. <p>“Squash and merge”<sup id="a1"><a href="development/git.html#f1">1</a></sup> takes all of the changes in the
  14899. PR, and bundles them into a single commit. GitHub gives you the opportunity to
  14900. edit the commit message before you confirm, and normally you should do so,
  14901. because the default will be useless (again: <code>* woops typo</code> is not a useful
  14902. thing to keep in the historical record).</p>
  14903. <p>The main problem with this approach comes when you have a series of pull
  14904. requests which build on top of one another: as soon as you squash-merge the
  14905. first PR, you'll end up with a stack of conflicts to resolve in all of the
  14906. others. In general, it's best to avoid this situation in the first place by
  14907. trying not to have multiple related PRs in flight at the same time. Still,
  14908. sometimes that's not possible and doing a regular merge is the lesser evil.</p>
  14909. <p>Another occasion in which a regular merge makes more sense is a PR where you've
  14910. deliberately created a series of commits each of which makes sense in its own
  14911. right. For example: <a href="https://github.com/matrix-org/synapse/pull/6837">a PR which gradually propagates a refactoring operation
  14912. through the codebase</a>, or <a href="https://github.com/matrix-org/synapse/pull/5987">a
  14913. PR which is the culmination of several other
  14914. PRs</a>. In this case the ability
  14915. to figure out when a particular change/bug was introduced could be very useful.</p>
  14916. <p>Ultimately: <strong>this is not a hard-and-fast-rule</strong>. If in doubt, ask yourself “do
  14917. each of the commits I am about to merge make sense in their own right”, but
  14918. remember that we're just doing our best to balance “keeping the commit history
  14919. clean” with other factors.</p>
  14920. <h2 id="git-branching-model"><a class="header" href="#git-branching-model">Git branching model</a></h2>
  14921. <p>A <a href="https://nvie.com/posts/a-successful-git-branching-model/">lot</a>
  14922. <a href="http://scottchacon.com/2011/08/31/github-flow.html">of</a>
  14923. <a href="https://www.endoflineblog.com/gitflow-considered-harmful">words</a> have been
  14924. written in the past about git branching models (no really, <a href="https://martinfowler.com/articles/branching-patterns.html">a
  14925. lot</a>). I tend to
  14926. think the whole thing is overblown. Fundamentally, it's not that
  14927. complicated. Here's how we do it.</p>
  14928. <p>Let's start with a picture:</p>
  14929. <p><img src="development/img/git/branches.jpg" alt="branching model" /></p>
  14930. <p>It looks complicated, but it's really not. There's one basic rule: <em>anyone</em> is
  14931. free to merge from <em>any</em> more-stable branch to <em>any</em> less-stable branch at
  14932. <em>any</em> time<sup id="a2"><a href="development/git.html#f2">2</a></sup>. (The principle behind this is that if a
  14933. change is good enough for the more-stable branch, then it's also good enough go
  14934. put in a less-stable branch.)</p>
  14935. <p>Meanwhile, merging (or squashing, as per the above) from a less-stable to a
  14936. more-stable branch is a deliberate action in which you want to publish a change
  14937. or a set of changes to (some subset of) the world: for example, this happens
  14938. when a PR is landed, or as part of our release process.</p>
  14939. <p>So, what counts as a more- or less-stable branch? A little reflection will show
  14940. that our active branches are ordered thus, from more-stable to less-stable:</p>
  14941. <ul>
  14942. <li><code>master</code> (tracks our last release).</li>
  14943. <li><code>release-vX.Y</code> (the branch where we prepare the next release)<sup
  14944. id="a3"><a href="development/git.html#f3">3</a></sup>.</li>
  14945. <li>PR branches which are targeting the release.</li>
  14946. <li><code>develop</code> (our &quot;mainline&quot; branch containing our bleeding-edge).</li>
  14947. <li>regular PR branches.</li>
  14948. </ul>
  14949. <p>The corollary is: if you have a bugfix that needs to land in both
  14950. <code>release-vX.Y</code> <em>and</em> <code>develop</code>, then you should base your PR on
  14951. <code>release-vX.Y</code>, get it merged there, and then merge from <code>release-vX.Y</code> to
  14952. <code>develop</code>. (If a fix lands in <code>develop</code> and we later need it in a
  14953. release-branch, we can of course cherry-pick it, but landing it in the release
  14954. branch first helps reduce the chance of annoying conflicts.)</p>
  14955. <hr />
  14956. <p><b id="f1">[1]</b>: “Squash and merge” is GitHub's term for this
  14957. operation. Given that there is no merge involved, I'm not convinced it's the
  14958. most intuitive name. <a href="development/git.html#a1">^</a></p>
  14959. <p><b id="f2">[2]</b>: Well, anyone with commit access.<a href="development/git.html#a2">^</a></p>
  14960. <p><b id="f3">[3]</b>: Very, very occasionally (I think this has happened once in
  14961. the history of Synapse), we've had two releases in flight at once. Obviously,
  14962. <code>release-v1.2</code> is more-stable than <code>release-v1.3</code>. <a href="development/git.html#a3">^</a></p>
  14963. <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>
  14964. <p><strong>DO NOT USE THESE DEMO SERVERS IN PRODUCTION</strong></p>
  14965. <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>
  14966. <p>The demo setup allows running three federation Synapse servers, with server
  14967. names <code>localhost:8480</code>, <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
  14968. <p>You can access them via any Matrix client over HTTP at <code>localhost:8080</code>,
  14969. <code>localhost:8081</code>, and <code>localhost:8082</code> or over HTTPS at <code>localhost:8480</code>,
  14970. <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
  14971. <p>To enable the servers to communicate, self-signed SSL certificates are generated
  14972. and the servers are configured in a highly insecure way, including:</p>
  14973. <ul>
  14974. <li>Not checking certificates over federation.</li>
  14975. <li>Not verifying keys.</li>
  14976. </ul>
  14977. <p>The servers are configured to store their data under <code>demo/8080</code>, <code>demo/8081</code>, and
  14978. <code>demo/8082</code>. This includes configuration, logs, SQLite databases, and media.</p>
  14979. <p>Note that when joining a public room on a different homeserver via &quot;#foo:bar.net&quot;,
  14980. then you are (in the current implementation) joining a room with room_id &quot;foo&quot;.
  14981. This means that it won't work if your homeserver already has a room with that
  14982. name.</p>
  14983. <h2 id="using-the-demo-scripts"><a class="header" href="#using-the-demo-scripts">Using the demo scripts</a></h2>
  14984. <p>There's three main scripts with straightforward purposes:</p>
  14985. <ul>
  14986. <li><code>start.sh</code> will start the Synapse servers, generating any missing configuration.
  14987. <ul>
  14988. <li>This accepts a single parameter <code>--no-rate-limit</code> to &quot;disable&quot; rate limits
  14989. (they actually still exist, but are very high).</li>
  14990. </ul>
  14991. </li>
  14992. <li><code>stop.sh</code> will stop the Synapse servers.</li>
  14993. <li><code>clean.sh</code> will delete the configuration, databases, log files, etc.</li>
  14994. </ul>
  14995. <p>To start a completely new set of servers, run:</p>
  14996. <pre><code class="language-sh">./demo/stop.sh; ./demo/clean.sh &amp;&amp; ./demo/start.sh
  14997. </code></pre>
  14998. <div style="break-before: page; page-break-before: always;"></div><h1 id="opentracing-2"><a class="header" href="#opentracing-2">OpenTracing</a></h1>
  14999. <h2 id="background"><a class="header" href="#background">Background</a></h2>
  15000. <p>OpenTracing is a semi-standard being adopted by a number of distributed
  15001. tracing platforms. It is a common api for facilitating vendor-agnostic
  15002. tracing instrumentation. That is, we can use the OpenTracing api and
  15003. select one of a number of tracer implementations to do the heavy lifting
  15004. in the background. Our current selected implementation is Jaeger.</p>
  15005. <p>OpenTracing is a tool which gives an insight into the causal
  15006. relationship of work done in and between servers. The servers each track
  15007. events and report them to a centralised server - in Synapse's case:
  15008. Jaeger. The basic unit used to represent events is the span. The span
  15009. roughly represents a single piece of work that was done and the time at
  15010. which it occurred. A span can have child spans, meaning that the work of
  15011. the child had to be completed for the parent span to complete, or it can
  15012. have follow-on spans which represent work that is undertaken as a result
  15013. of the parent but is not depended on by the parent to in order to
  15014. finish.</p>
  15015. <p>Since this is undertaken in a distributed environment a request to
  15016. another server, such as an RPC or a simple GET, can be considered a span
  15017. (a unit or work) for the local server. This causal link is what
  15018. OpenTracing aims to capture and visualise. In order to do this metadata
  15019. about the local server's span, i.e the 'span context', needs to be
  15020. included with the request to the remote.</p>
  15021. <p>It is up to the remote server to decide what it does with the spans it
  15022. creates. This is called the sampling policy and it can be configured
  15023. through Jaeger's settings.</p>
  15024. <p>For OpenTracing concepts see
  15025. <a href="https://opentracing.io/docs/overview/what-is-tracing/">https://opentracing.io/docs/overview/what-is-tracing/</a>.</p>
  15026. <p>For more information about Jaeger's implementation see
  15027. <a href="https://www.jaegertracing.io/docs/">https://www.jaegertracing.io/docs/</a></p>
  15028. <h2 id="setting-up-opentracing"><a class="header" href="#setting-up-opentracing">Setting up OpenTracing</a></h2>
  15029. <p>To receive OpenTracing spans, start up a Jaeger server. This can be done
  15030. using docker like so:</p>
  15031. <pre><code class="language-sh">docker run -d --name jaeger \
  15032. -p 6831:6831/udp \
  15033. -p 6832:6832/udp \
  15034. -p 5778:5778 \
  15035. -p 16686:16686 \
  15036. -p 14268:14268 \
  15037. jaegertracing/all-in-one:1
  15038. </code></pre>
  15039. <p>Latest documentation is probably at
  15040. https://www.jaegertracing.io/docs/latest/getting-started.</p>
  15041. <h2 id="enable-opentracing-in-synapse"><a class="header" href="#enable-opentracing-in-synapse">Enable OpenTracing in Synapse</a></h2>
  15042. <p>OpenTracing is not enabled by default. It must be enabled in the
  15043. homeserver config by adding the <code>opentracing</code> option to your config file. You can find
  15044. documentation about how to do this in the <a href="usage/configuration/config_documentation.html#opentracing">config manual under the header 'Opentracing'</a>.
  15045. See below for an example Opentracing configuration: </p>
  15046. <pre><code class="language-yaml">opentracing:
  15047. enabled: true
  15048. homeserver_whitelist:
  15049. - &quot;mytrustedhomeserver.org&quot;
  15050. - &quot;*.myotherhomeservers.com&quot;
  15051. </code></pre>
  15052. <h2 id="homeserver-whitelisting"><a class="header" href="#homeserver-whitelisting">Homeserver whitelisting</a></h2>
  15053. <p>The homeserver whitelist is configured using regular expressions. A list
  15054. of regular expressions can be given and their union will be compared
  15055. when propagating any spans contexts to another homeserver.</p>
  15056. <p>Though it's mostly safe to send and receive span contexts to and from
  15057. untrusted users since span contexts are usually opaque ids it can lead
  15058. to two problems, namely:</p>
  15059. <ul>
  15060. <li>If the span context is marked as sampled by the sending homeserver
  15061. the receiver will sample it. Therefore two homeservers with wildly
  15062. different sampling policies could incur higher sampling counts than
  15063. intended.</li>
  15064. <li>Sending servers can attach arbitrary data to spans, known as
  15065. 'baggage'. For safety this has been disabled in Synapse but that
  15066. doesn't prevent another server sending you baggage which will be
  15067. logged to OpenTracing's logs.</li>
  15068. </ul>
  15069. <h2 id="configuring-jaeger"><a class="header" href="#configuring-jaeger">Configuring Jaeger</a></h2>
  15070. <p>Sampling strategies can be set as in this document:
  15071. <a href="https://www.jaegertracing.io/docs/latest/sampling/">https://www.jaegertracing.io/docs/latest/sampling/</a>.</p>
  15072. <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>
  15073. <p>Synapse's database schema is stored in the <code>synapse.storage.schema</code> module.</p>
  15074. <h2 id="logical-databases"><a class="header" href="#logical-databases">Logical databases</a></h2>
  15075. <p>Synapse supports splitting its datastore across multiple physical databases (which can
  15076. be useful for large installations), and the schema files are therefore split according
  15077. to the logical database they apply to.</p>
  15078. <p>At the time of writing, the following &quot;logical&quot; databases are supported:</p>
  15079. <ul>
  15080. <li><code>state</code> - used to store Matrix room state (more specifically, <code>state_groups</code>,
  15081. their relationships and contents).</li>
  15082. <li><code>main</code> - stores everything else.</li>
  15083. </ul>
  15084. <p>Additionally, the <code>common</code> directory contains schema files for tables which must be
  15085. present on <em>all</em> physical databases.</p>
  15086. <h2 id="synapse-schema-versions"><a class="header" href="#synapse-schema-versions">Synapse schema versions</a></h2>
  15087. <p>Synapse manages its database schema via &quot;schema versions&quot;. These are mainly used to
  15088. help avoid confusion if the Synapse codebase is rolled back after the database is
  15089. updated. They work as follows:</p>
  15090. <ul>
  15091. <li>
  15092. <p>The Synapse codebase defines a constant <code>synapse.storage.schema.SCHEMA_VERSION</code>
  15093. which represents the expectations made about the database by that version. For
  15094. example, as of Synapse v1.36, this is <code>59</code>.</p>
  15095. </li>
  15096. <li>
  15097. <p>The database stores a &quot;compatibility version&quot; in
  15098. <code>schema_compat_version.compat_version</code> which defines the <code>SCHEMA_VERSION</code> of the
  15099. oldest version of Synapse which will work with the database. On startup, if
  15100. <code>compat_version</code> is found to be newer than <code>SCHEMA_VERSION</code>, Synapse will refuse to
  15101. start.</p>
  15102. <p>Synapse automatically updates this field from
  15103. <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code>.</p>
  15104. </li>
  15105. <li>
  15106. <p>Whenever a backwards-incompatible change is made to the database format (normally
  15107. via a <code>delta</code> file), <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code> is also updated
  15108. so that administrators can not accidentally roll back to a too-old version of Synapse.</p>
  15109. </li>
  15110. </ul>
  15111. <p>Generally, the goal is to maintain compatibility with at least one or two previous
  15112. releases of Synapse, so any substantial change tends to require multiple releases and a
  15113. bit of forward-planning to get right.</p>
  15114. <p>As a worked example: we want to remove the <code>room_stats_historical</code> table. Here is how it
  15115. might pan out.</p>
  15116. <ol>
  15117. <li>
  15118. <p>Replace any code that <em>reads</em> from <code>room_stats_historical</code> with alternative
  15119. implementations, but keep writing to it in case of rollback to an earlier version.
  15120. Also, increase <code>synapse.storage.schema.SCHEMA_VERSION</code>. In this
  15121. instance, there is no existing code which reads from <code>room_stats_historical</code>, so
  15122. our starting point is:</p>
  15123. <p>v1.36.0: <code>SCHEMA_VERSION=59</code>, <code>SCHEMA_COMPAT_VERSION=59</code></p>
  15124. </li>
  15125. <li>
  15126. <p>Next (say in Synapse v1.37.0): remove the code that <em>writes</em> to
  15127. <code>room_stats_historical</code>, but don’t yet remove the table in case of rollback to
  15128. v1.36.0. Again, we increase <code>synapse.storage.schema.SCHEMA_VERSION</code>, but
  15129. because we have not broken compatibility with v1.36, we do not yet update
  15130. <code>SCHEMA_COMPAT_VERSION</code>. We now have:</p>
  15131. <p>v1.37.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=59</code>.</p>
  15132. </li>
  15133. <li>
  15134. <p>Later (say in Synapse v1.38.0): we can remove the table altogether. This will
  15135. break compatibility with v1.36.0, so we must update <code>SCHEMA_COMPAT_VERSION</code> accordingly.
  15136. There is no need to update <code>synapse.storage.schema.SCHEMA_VERSION</code>, since there is no
  15137. change to the Synapse codebase here. So we end up with:</p>
  15138. <p>v1.38.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=60</code>.</p>
  15139. </li>
  15140. </ol>
  15141. <p>If in doubt about whether to update <code>SCHEMA_VERSION</code> or not, it is generally best to
  15142. lean towards doing so.</p>
  15143. <h2 id="full-schema-dumps"><a class="header" href="#full-schema-dumps">Full schema dumps</a></h2>
  15144. <p>In the <code>full_schemas</code> directories, only the most recently-numbered snapshot is used
  15145. (<code>54</code> at the time of writing). Older snapshots (eg, <code>16</code>) are present for historical
  15146. reference only.</p>
  15147. <h3 id="building-full-schema-dumps"><a class="header" href="#building-full-schema-dumps">Building full schema dumps</a></h3>
  15148. <p>If you want to recreate these schemas, they need to be made from a database that
  15149. has had all background updates run.</p>
  15150. <p>To do so, use <code>scripts-dev/make_full_schema.sh</code>. This will produce new
  15151. <code>full.sql.postgres</code> and <code>full.sql.sqlite</code> files.</p>
  15152. <p>Ensure postgres is installed, then run:</p>
  15153. <pre><code class="language-sh">./scripts-dev/make_full_schema.sh -p postgres_username -o output_dir/
  15154. </code></pre>
  15155. <p>NB at the time of writing, this script predates the split into separate <code>state</code>/<code>main</code>
  15156. databases so will require updates to handle that correctly.</p>
  15157. <h2 id="delta-files"><a class="header" href="#delta-files">Delta files</a></h2>
  15158. <p>Delta files define the steps required to upgrade the database from an earlier version.
  15159. They can be written as either a file containing a series of SQL statements, or a Python
  15160. module.</p>
  15161. <p>Synapse remembers which delta files it has applied to a database (they are stored in the
  15162. <code>applied_schema_deltas</code> table) and will not re-apply them (even if a given file is
  15163. subsequently updated).</p>
  15164. <p>Delta files should be placed in a directory named <code>synapse/storage/schema/&lt;database&gt;/delta/&lt;version&gt;/</code>.
  15165. They are applied in alphanumeric order, so by convention the first two characters
  15166. of the filename should be an integer such as <code>01</code>, to put the file in the right order.</p>
  15167. <h3 id="sql-delta-files"><a class="header" href="#sql-delta-files">SQL delta files</a></h3>
  15168. <p>These should be named <code>*.sql</code>, or — for changes which should only be applied for a
  15169. given database engine — <code>*.sql.posgres</code> or <code>*.sql.sqlite</code>. For example, a delta which
  15170. adds a new column to the <code>foo</code> table might be called <code>01add_bar_to_foo.sql</code>.</p>
  15171. <p>Note that our SQL parser is a bit simple - it understands comments (<code>--</code> and <code>/*...*/</code>),
  15172. 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>
  15173. <h3 id="python-delta-files"><a class="header" href="#python-delta-files">Python delta files</a></h3>
  15174. <p>For more flexibility, a delta file can take the form of a python module. These should
  15175. be named <code>*.py</code>. Note that database-engine-specific modules are not supported here –
  15176. instead you can write <code>if isinstance(database_engine, PostgresEngine)</code> or similar.</p>
  15177. <p>A Python delta module should define either or both of the following functions:</p>
  15178. <pre><code class="language-python">import synapse.config.homeserver
  15179. import synapse.storage.engines
  15180. import synapse.storage.types
  15181. def run_create(
  15182. cur: synapse.storage.types.Cursor,
  15183. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  15184. ) -&gt; None:
  15185. &quot;&quot;&quot;Called whenever an existing or new database is to be upgraded&quot;&quot;&quot;
  15186. ...
  15187. def run_upgrade(
  15188. cur: synapse.storage.types.Cursor,
  15189. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  15190. config: synapse.config.homeserver.HomeServerConfig,
  15191. ) -&gt; None:
  15192. &quot;&quot;&quot;Called whenever an existing database is to be upgraded.&quot;&quot;&quot;
  15193. ...
  15194. </code></pre>
  15195. <h2 id="boolean-columns"><a class="header" href="#boolean-columns">Boolean columns</a></h2>
  15196. <p>Boolean columns require special treatment, since SQLite treats booleans the
  15197. same as integers.</p>
  15198. <p>There are three separate aspects to this:</p>
  15199. <ul>
  15200. <li>
  15201. <p>Any new boolean column must be added to the <code>BOOLEAN_COLUMNS</code> list in
  15202. <code>synapse/_scripts/synapse_port_db.py</code>. This tells the port script to cast
  15203. the integer value from SQLite to a boolean before writing the value to the
  15204. postgres database.</p>
  15205. </li>
  15206. <li>
  15207. <p>Before SQLite 3.23, <code>TRUE</code> and <code>FALSE</code> were not recognised as constants by
  15208. SQLite, and the <code>IS [NOT] TRUE</code>/<code>IS [NOT] FALSE</code> operators were not
  15209. supported. This makes it necessary to avoid using <code>TRUE</code> and <code>FALSE</code>
  15210. constants in SQL commands.</p>
  15211. <p>For example, to insert a <code>TRUE</code> value into the database, write:</p>
  15212. <pre><code class="language-python">txn.execute(&quot;INSERT INTO tbl(col) VALUES (?)&quot;, (True, ))
  15213. </code></pre>
  15214. </li>
  15215. <li>
  15216. <p>Default values for new boolean columns present a particular
  15217. difficulty. Generally it is best to create separate schema files for
  15218. Postgres and SQLite. For example:</p>
  15219. <pre><code class="language-sql"># in 00delta.sql.postgres:
  15220. ALTER TABLE tbl ADD COLUMN col BOOLEAN DEFAULT FALSE;
  15221. </code></pre>
  15222. <pre><code class="language-sql"># in 00delta.sql.sqlite:
  15223. ALTER TABLE tbl ADD COLUMN col BOOLEAN DEFAULT 0;
  15224. </code></pre>
  15225. <p>Note that there is a particularly insidious failure mode here: the Postgres
  15226. flavour will be accepted by SQLite 3.22, but will give a column whose
  15227. default value is the <strong>string</strong> <code>&quot;FALSE&quot;</code> - which, when cast back to a boolean
  15228. in Python, evaluates to <code>True</code>.</p>
  15229. </li>
  15230. </ul>
  15231. <h2 id="event_id-global-uniqueness"><a class="header" href="#event_id-global-uniqueness"><code>event_id</code> global uniqueness</a></h2>
  15232. <p><code>event_id</code>'s can be considered globally unique although there has been a lot of
  15233. debate on this topic in places like
  15234. <a href="https://github.com/matrix-org/matrix-spec-proposals/issues/2779">MSC2779</a> and
  15235. <a href="https://github.com/matrix-org/matrix-spec-proposals/pull/2848">MSC2848</a> which
  15236. has no resolution yet (as of 2022-09-01). There are several places in Synapse
  15237. 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>
  15238. where we assume that event IDs are globally unique.</p>
  15239. <p>When scoping <code>event_id</code> in a database schema, it is often nice to accompany it
  15240. 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
  15241. makes it very easy to find and clean up everything in a room when it needs to be
  15242. purged (no need to use sub-<code>select</code> query or join from the <code>events</code> table).</p>
  15243. <p>A note on collisions: In room versions <code>1</code> and <code>2</code> it's possible to end up with
  15244. two events with the same <code>event_id</code> (in the same or different rooms). After room
  15245. version <code>3</code>, that can only happen with a hash collision, which we basically hope
  15246. will never happen (SHA256 has a massive big key space).</p>
  15247. <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>
  15248. <p>It can be desirable to implement &quot;experimental&quot; features which are disabled by
  15249. default and must be explicitly enabled via the Synapse configuration. This is
  15250. applicable for features which:</p>
  15251. <ul>
  15252. <li>Are unstable in the Matrix spec (e.g. those defined by an MSC that has not yet been merged).</li>
  15253. <li>Developers are not confident in their use by general Synapse administrators/users
  15254. (e.g. a feature is incomplete, buggy, performs poorly, or needs further testing).</li>
  15255. </ul>
  15256. <p>Note that this only really applies to features which are expected to be desirable
  15257. to a broad audience. The <a href="development/../modules/index.html">module infrastructure</a> should
  15258. instead be investigated for non-standard features.</p>
  15259. <p>Guarding experimental features behind configuration flags should help with some
  15260. of the following scenarios:</p>
  15261. <ul>
  15262. <li>Ensure that clients do not assume that unstable features exist (failing
  15263. gracefully if they do not).</li>
  15264. <li>Unstable features do not become de-facto standards and can be removed
  15265. aggressively (since only those who have opted-in will be affected).</li>
  15266. <li>Ease finding the implementation of unstable features in Synapse (for future
  15267. removal or stabilization).</li>
  15268. <li>Ease testing a feature (or removal of feature) due to enabling/disabling without
  15269. code changes. It also becomes possible to ask for wider testing, if desired.</li>
  15270. </ul>
  15271. <p>Experimental configuration flags should be disabled by default (requiring Synapse
  15272. administrators to explicitly opt-in), although there are situations where it makes
  15273. sense (from a product point-of-view) to enable features by default. This is
  15274. expected and not an issue.</p>
  15275. <p>It is not a requirement for experimental features to be behind a configuration flag,
  15276. but one should be used if unsure.</p>
  15277. <p>New experimental configuration flags should be added under the <code>experimental</code>
  15278. configuration key (see the <code>synapse.config.experimental</code> file) and either explain
  15279. (briefly) what is being enabled, or include the MSC number.</p>
  15280. <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>
  15281. <p>This is a quick cheat sheet for developers on how to use <a href="https://python-poetry.org/"><code>poetry</code></a>.</p>
  15282. <h1 id="background-1"><a class="header" href="#background-1">Background</a></h1>
  15283. <p>Synapse uses a variety of third-party Python packages to function as a homeserver.
  15284. Some of these are direct dependencies, listed in <code>pyproject.toml</code> under the
  15285. <code>[tool.poetry.dependencies]</code> section. The rest are transitive dependencies (the
  15286. things that our direct dependencies themselves depend on, and so on recursively.)</p>
  15287. <p>We maintain a locked list of all our dependencies (transitive included) so that
  15288. we can track exactly which version of each dependency appears in a given release.
  15289. See <a href="https://github.com/matrix-org/synapse/issues/11537#issue-1074469665">here</a>
  15290. for discussion of why we wanted this for Synapse. We chose to use
  15291. <a href="https://python-poetry.org/"><code>poetry</code></a> to manage this locked list; see
  15292. <a href="https://github.com/matrix-org/synapse/issues/11537#issuecomment-1015975819">this comment</a>
  15293. for the reasoning.</p>
  15294. <p>The locked dependencies get included in our &quot;self-contained&quot; releases: namely,
  15295. our docker images and our debian packages. We also use the locked dependencies
  15296. in development and our continuous integration.</p>
  15297. <p>Separately, our &quot;broad&quot; dependencies—the version ranges specified in
  15298. <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
  15299. to PyPI</a>. Installing from PyPI or from
  15300. the Synapse source tree directly will <em>not</em> use the locked dependencies; instead,
  15301. they'll pull in the latest version of each package available at install time.</p>
  15302. <h2 id="example-dependency"><a class="header" href="#example-dependency">Example dependency</a></h2>
  15303. <p>An example may help. We have a broad dependency on
  15304. <a href="https://pypi.org/project/phonenumbers/"><code>phonenumbers</code></a>, as declared in
  15305. 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>
  15306. <pre><code class="language-toml">[tool.poetry.dependencies]
  15307. # ...
  15308. phonenumbers = &quot;&gt;=8.2.0&quot;
  15309. </code></pre>
  15310. <p>In our lockfile this is
  15311. <a href="https://github.com/matrix-org/synapse/blob/dfc7646504cef3e4ff396c36089e1c6f1b1634de/poetry.lock#L679-L685">pinned</a>
  15312. to version 8.12.44, even though
  15313. <a href="https://pypi.org/project/phonenumbers/#history">newer versions are available</a>.</p>
  15314. <pre><code class="language-toml">[[package]]
  15315. name = &quot;phonenumbers&quot;
  15316. version = &quot;8.12.44&quot;
  15317. description = &quot;Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.&quot;
  15318. category = &quot;main&quot;
  15319. optional = false
  15320. python-versions = &quot;*&quot;
  15321. </code></pre>
  15322. <p>The lockfile also includes a
  15323. <a href="https://github.com/matrix-org/synapse/blob/release-v1.57/poetry.lock#L2178-L2181">cryptographic checksum</a>
  15324. of the sdists and wheels provided for this version of <code>phonenumbers</code>.</p>
  15325. <pre><code class="language-toml">[metadata.files]
  15326. # ...
  15327. phonenumbers = [
  15328. {file = &quot;phonenumbers-8.12.44-py2.py3-none-any.whl&quot;, hash = &quot;sha256:cc1299cf37b309ecab6214297663ab86cb3d64ae37fd5b88e904fe7983a874a6&quot;},
  15329. {file = &quot;phonenumbers-8.12.44.tar.gz&quot;, hash = &quot;sha256:26cfd0257d1704fe2f88caff2caabb70d16a877b1e65b6aae51f9fbbe10aa8ce&quot;},
  15330. ]
  15331. </code></pre>
  15332. <p>We can see this pinned version inside the docker image for that release:</p>
  15333. <pre><code>$ docker pull matrixdotorg/synapse:v1.57.0
  15334. ...
  15335. $ docker run --entrypoint pip matrixdotorg/synapse:v1.57.0 show phonenumbers
  15336. Name: phonenumbers
  15337. Version: 8.12.44
  15338. Summary: Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.
  15339. Home-page: https://github.com/daviddrysdale/python-phonenumbers
  15340. Author: David Drysdale
  15341. Author-email: dmd@lurklurk.org
  15342. License: Apache License 2.0
  15343. Location: /usr/local/lib/python3.9/site-packages
  15344. Requires:
  15345. Required-by: matrix-synapse
  15346. </code></pre>
  15347. <p>Whereas the wheel metadata just contains the broad dependencies:</p>
  15348. <pre><code>$ cd /tmp
  15349. $ wget https://files.pythonhosted.org/packages/ca/5e/d722d572cc5b3092402b783d6b7185901b444427633bd8a6b00ea0dd41b7/matrix_synapse-1.57.0rc1-py3-none-any.whl
  15350. ...
  15351. $ unzip -c matrix_synapse-1.57.0rc1-py3-none-any.whl matrix_synapse-1.57.0rc1.dist-info/METADATA | grep phonenumbers
  15352. Requires-Dist: phonenumbers (&gt;=8.2.0)
  15353. </code></pre>
  15354. <h1 id="tooling-recommendation-direnv"><a class="header" href="#tooling-recommendation-direnv">Tooling recommendation: direnv</a></h1>
  15355. <p><a href="https://direnv.net/"><code>direnv</code></a> is a tool for activating environments in your
  15356. shell inside a given directory. Its support for poetry is unofficial (a
  15357. community wiki recipe only), but works solidly in our experience. We thoroughly
  15358. recommend it for daily use. To use it:</p>
  15359. <ol>
  15360. <li><a href="https://direnv.net/docs/installation.html">Install <code>direnv</code></a> - it's likely
  15361. packaged for your system already.</li>
  15362. <li>Teach direnv about poetry. The <a href="https://github.com/direnv/direnv/wiki/Python#poetry">shell config here</a>
  15363. needs to be added to <code>~/.config/direnv/direnvrc</code> (or more generally <code>$XDG_CONFIG_HOME/direnv/direnvrc</code>).</li>
  15364. <li>Mark the synapse checkout as a poetry project: <code>echo layout poetry &gt; .envrc</code>.</li>
  15365. <li>Convince yourself that you trust this <code>.envrc</code> configuration and project.
  15366. Then formally confirm this to <code>direnv</code> by running <code>direnv allow</code>.</li>
  15367. </ol>
  15368. <p>Then whenever you navigate to the synapse checkout, you should be able to run
  15369. e.g. <code>mypy</code> instead of <code>poetry run mypy</code>; <code>python</code> instead of
  15370. <code>poetry run python</code>; and your shell commands will automatically run in the
  15371. context of poetry's venv, without having to run <code>poetry shell</code> beforehand.</p>
  15372. <h1 id="how-do-i"><a class="header" href="#how-do-i">How do I...</a></h1>
  15373. <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>
  15374. <pre><code class="language-shell">poetry install --extras all --remove-untracked
  15375. </code></pre>
  15376. <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>
  15377. <pre><code class="language-shell"># Stop the current virtualenv if active
  15378. $ deactivate
  15379. # Remove all of the files from the current environment.
  15380. # Don't worry, even though it says &quot;all&quot;, this will only
  15381. # remove the Poetry virtualenvs for the current project.
  15382. $ poetry env remove --all
  15383. # Reactivate Poetry shell to create the virtualenv again
  15384. $ poetry shell
  15385. # Install everything again
  15386. $ poetry install --extras all
  15387. </code></pre>
  15388. <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>
  15389. <p>Use <code>poetry run cmd args</code> when you need the python virtualenv context.
  15390. To avoid typing <code>poetry run</code> all the time, you can run <code>poetry shell</code>
  15391. to start a new shell in the poetry virtualenv context. Within <code>poetry shell</code>,
  15392. <code>python</code>, <code>pip</code>, <code>mypy</code>, <code>trial</code>, etc. are all run inside the project virtualenv
  15393. and isolated from the rest o the system.</p>
  15394. <p>Roughly speaking, the translation from a traditional virtualenv is:</p>
  15395. <ul>
  15396. <li><code>env/bin/activate</code> -&gt; <code>poetry shell</code>, and</li>
  15397. <li><code>deactivate</code> -&gt; close the terminal (Ctrl-D, <code>exit</code>, etc.)</li>
  15398. </ul>
  15399. <p>See also the direnv recommendation above, which makes <code>poetry run</code> and
  15400. <code>poetry shell</code> unnecessary.</p>
  15401. <h2 id="inspect-the-poetry-virtualenv"><a class="header" href="#inspect-the-poetry-virtualenv">...inspect the <code>poetry</code> virtualenv?</a></h2>
  15402. <p>Some suggestions:</p>
  15403. <pre><code class="language-shell"># Current env only
  15404. poetry env info
  15405. # All envs: this allows you to have e.g. a poetry managed venv for Python 3.7,
  15406. # and another for Python 3.10.
  15407. poetry env list --full-path
  15408. poetry run pip list
  15409. </code></pre>
  15410. <p>Note that <code>poetry show</code> describes the abstract <em>lock file</em> rather than your
  15411. on-disk environment. With that said, <code>poetry show --tree</code> can sometimes be
  15412. useful.</p>
  15413. <h2 id="add-a-new-dependency"><a class="header" href="#add-a-new-dependency">...add a new dependency?</a></h2>
  15414. <p>Either:</p>
  15415. <ul>
  15416. <li>manually update <code>pyproject.toml</code>; then <code>poetry lock --no-update</code>; or else</li>
  15417. <li><code>poetry add packagename</code>. See <code>poetry add --help</code>; note the <code>--dev</code>,
  15418. <code>--extras</code> and <code>--optional</code> flags in particular.
  15419. <ul>
  15420. <li><strong>NB</strong>: this specifies the new package with a version given by a &quot;caret bound&quot;. This won't get forced to its lowest version in the old deps CI job: see <a href="https://github.com/matrix-org/synapse/blob/4e1374373857f2f7a911a31c50476342d9070681/.ci/scripts/test_old_deps.sh#L35-L39">this TODO</a>.</li>
  15421. </ul>
  15422. </li>
  15423. </ul>
  15424. <p>Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> files in your commit.</p>
  15425. <h2 id="remove-a-dependency"><a class="header" href="#remove-a-dependency">...remove a dependency?</a></h2>
  15426. <p>This is not done often and is untested, but</p>
  15427. <pre><code class="language-shell">poetry remove packagename
  15428. </code></pre>
  15429. <p>ought to do the trick. Alternatively, manually update <code>pyproject.toml</code> and
  15430. <code>poetry lock --no-update</code>. Include the updated <code>pyproject.toml</code> and poetry.lock`
  15431. files in your commit.</p>
  15432. <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>
  15433. <p>Best done by manually editing <code>pyproject.toml</code>, then <code>poetry lock --no-update</code>.
  15434. Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> in your commit.</p>
  15435. <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>
  15436. <p>Use</p>
  15437. <pre><code class="language-shell">poetry update packagename
  15438. </code></pre>
  15439. <p>to use the latest version of <code>packagename</code> in the locked environment, without
  15440. affecting the broad dependencies listed in the wheel.</p>
  15441. <p>There doesn't seem to be a way to do this whilst locking a <em>specific</em> version of
  15442. <code>packagename</code>. We can workaround this (crudely) as follows:</p>
  15443. <pre><code class="language-shell">poetry add packagename==1.2.3
  15444. # This should update pyproject.lock.
  15445. # Now undo the changes to pyproject.toml. For example
  15446. # git restore pyproject.toml
  15447. # Get poetry to recompute the content-hash of pyproject.toml without changing
  15448. # the locked package versions.
  15449. poetry lock --no-update
  15450. </code></pre>
  15451. <p>Either way, include the updated <code>poetry.lock</code> file in your commit.</p>
  15452. <h2 id="export-a-requirementstxt-file"><a class="header" href="#export-a-requirementstxt-file">...export a <code>requirements.txt</code> file?</a></h2>
  15453. <pre><code class="language-shell">poetry export --extras all
  15454. </code></pre>
  15455. <p>Be wary of bugs in <code>poetry export</code> and <code>pip install -r requirements.txt</code>.</p>
  15456. <p>Note: <code>poetry export</code> will be made a plugin in Poetry 1.2. Additional config may
  15457. be required.</p>
  15458. <h2 id="build-a-test-wheel"><a class="header" href="#build-a-test-wheel">...build a test wheel?</a></h2>
  15459. <p>I usually use</p>
  15460. <pre><code class="language-shell">poetry run pip install build &amp;&amp; poetry run python -m build
  15461. </code></pre>
  15462. <p>because <a href="https://github.com/pypa/build"><code>build</code></a> is a standardish tool which
  15463. doesn't require poetry. (It's what we use in CI too). However, you could try
  15464. <code>poetry build</code> too.</p>
  15465. <h1 id="troubleshooting-4"><a class="header" href="#troubleshooting-4">Troubleshooting</a></h1>
  15466. <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>
  15467. <p>The minimum version of poetry supported by Synapse is 1.2.</p>
  15468. <p>It can also be useful to check the version of <code>poetry-core</code> in use. If you've
  15469. installed <code>poetry</code> with <code>pipx</code>, try <code>pipx runpip poetry list | grep poetry-core</code>.</p>
  15470. <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>
  15471. <p>Poetry caches a bunch of information about packages that isn't readily available
  15472. from PyPI. (This is what makes poetry seem slow when doing the first
  15473. <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>
  15474. <h2 id="remove-outdated-egg-info"><a class="header" href="#remove-outdated-egg-info">Remove outdated egg-info</a></h2>
  15475. <p>Delete the <code>matrix_synapse.egg-info/</code> directory from the root of your Synapse
  15476. install.</p>
  15477. <p>This stores some cached information about dependencies and often conflicts with
  15478. letting Poetry do the right thing.</p>
  15479. <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>
  15480. <p>Sometimes useful to see what poetry's internal logic is.</p>
  15481. <div style="break-before: page; page-break-before: always;"></div><h1 id="cancellation"><a class="header" href="#cancellation">Cancellation</a></h1>
  15482. <p>Sometimes, requests take a long time to service and clients disconnect
  15483. before Synapse produces a response. To avoid wasting resources, Synapse
  15484. can cancel request processing for select endpoints marked with the
  15485. <code>@cancellable</code> decorator.</p>
  15486. <p>Synapse makes use of Twisted's <code>Deferred.cancel()</code> feature to make
  15487. cancellation work. The <code>@cancellable</code> decorator does nothing by itself
  15488. and merely acts as a flag, signalling to developers and other code alike
  15489. that a method can be cancelled.</p>
  15490. <h2 id="enabling-cancellation-for-an-endpoint"><a class="header" href="#enabling-cancellation-for-an-endpoint">Enabling cancellation for an endpoint</a></h2>
  15491. <ol>
  15492. <li>Check that the endpoint method, and any <code>async</code> functions in its call
  15493. tree handle cancellation correctly. See
  15494. <a href="development/synapse_architecture/cancellation.html#handling-cancellation-correctly">Handling cancellation correctly</a>
  15495. for a list of things to look out for.</li>
  15496. <li>Add the <code>@cancellable</code> decorator to the <code>on_GET/POST/PUT/DELETE</code>
  15497. method. It's not recommended to make non-<code>GET</code> methods cancellable,
  15498. since cancellation midway through some database updates is less
  15499. likely to be handled correctly.</li>
  15500. </ol>
  15501. <h2 id="mechanics"><a class="header" href="#mechanics">Mechanics</a></h2>
  15502. <p>There are two stages to cancellation: downward propagation of a
  15503. <code>cancel()</code> call, followed by upwards propagation of a <code>CancelledError</code>
  15504. out of a blocked <code>await</code>.
  15505. Both Twisted and asyncio have a cancellation mechanism.</p>
  15506. <table><thead><tr><th></th><th>Method</th><th>Exception</th><th>Exception inherits from</th></tr></thead><tbody>
  15507. <tr><td>Twisted</td><td><code>Deferred.cancel()</code></td><td><code>twisted.internet.defer.CancelledError</code></td><td><code>Exception</code> (!)</td></tr>
  15508. <tr><td>asyncio</td><td><code>Task.cancel()</code></td><td><code>asyncio.CancelledError</code></td><td><code>BaseException</code></td></tr>
  15509. </tbody></table>
  15510. <h3 id="deferredcancel"><a class="header" href="#deferredcancel">Deferred.cancel()</a></h3>
  15511. <p>When Synapse starts handling a request, it runs the async method
  15512. responsible for handling it using <code>defer.ensureDeferred</code>, which returns
  15513. a <code>Deferred</code>. For example:</p>
  15514. <pre><code class="language-python">def do_something() -&gt; Deferred[None]:
  15515. ...
  15516. @cancellable
  15517. async def on_GET() -&gt; Tuple[int, JsonDict]:
  15518. d = make_deferred_yieldable(do_something())
  15519. await d
  15520. return 200, {}
  15521. request = defer.ensureDeferred(on_GET())
  15522. </code></pre>
  15523. <p>When a client disconnects early, Synapse checks for the presence of the
  15524. <code>@cancellable</code> decorator on <code>on_GET</code>. Since <code>on_GET</code> is cancellable,
  15525. <code>Deferred.cancel()</code> is called on the <code>Deferred</code> from
  15526. <code>defer.ensureDeferred</code>, ie. <code>request</code>. Twisted knows which <code>Deferred</code>
  15527. <code>request</code> is waiting on and passes the <code>cancel()</code> call on to <code>d</code>.</p>
  15528. <p>The <code>Deferred</code> being waited on, <code>d</code>, may have its own handling for
  15529. <code>cancel()</code> and pass the call on to other <code>Deferred</code>s.</p>
  15530. <p>Eventually, a <code>Deferred</code> handles the <code>cancel()</code> call by resolving itself
  15531. with a <code>CancelledError</code>.</p>
  15532. <h3 id="cancellederror"><a class="header" href="#cancellederror">CancelledError</a></h3>
  15533. <p>The <code>CancelledError</code> gets raised out of the <code>await</code> and bubbles up, as
  15534. per normal Python exception handling.</p>
  15535. <h2 id="handling-cancellation-correctly"><a class="header" href="#handling-cancellation-correctly">Handling cancellation correctly</a></h2>
  15536. <p>In general, when writing code that might be subject to cancellation, two
  15537. things must be considered:</p>
  15538. <ul>
  15539. <li>The effect of <code>CancelledError</code>s raised out of <code>await</code>s.</li>
  15540. <li>The effect of <code>Deferred</code>s being <code>cancel()</code>ed.</li>
  15541. </ul>
  15542. <p>Examples of code that handles cancellation incorrectly include:</p>
  15543. <ul>
  15544. <li><code>try-except</code> blocks which swallow <code>CancelledError</code>s.</li>
  15545. <li>Code that shares the same <code>Deferred</code>, which may be cancelled, between
  15546. multiple requests.</li>
  15547. <li>Code that starts some processing that's exempt from cancellation, but
  15548. uses a logging context from cancellable code. The logging context
  15549. will be finished upon cancellation, while the uncancelled processing
  15550. is still using it.</li>
  15551. </ul>
  15552. <p>Some common patterns are listed below in more detail.</p>
  15553. <h3 id="async-function-calls"><a class="header" href="#async-function-calls"><code>async</code> function calls</a></h3>
  15554. <p>Most functions in Synapse are relatively straightforward from a
  15555. cancellation standpoint: they don't do anything with <code>Deferred</code>s and
  15556. purely call and <code>await</code> other <code>async</code> functions.</p>
  15557. <p>An <code>async</code> function handles cancellation correctly if its own code
  15558. handles cancellation correctly and all the async function it calls
  15559. handle cancellation correctly. For example:</p>
  15560. <pre><code class="language-python">async def do_two_things() -&gt; None:
  15561. check_something()
  15562. await do_something()
  15563. await do_something_else()
  15564. </code></pre>
  15565. <p><code>do_two_things</code> handles cancellation correctly if <code>do_something</code> and
  15566. <code>do_something_else</code> handle cancellation correctly.</p>
  15567. <p>That is, when checking whether a function handles cancellation
  15568. correctly, its implementation and all its <code>async</code> function calls need to
  15569. be checked, recursively.</p>
  15570. <p>As <code>check_something</code> is not <code>async</code>, it does not need to be checked.</p>
  15571. <h3 id="cancellederrors"><a class="header" href="#cancellederrors">CancelledErrors</a></h3>
  15572. <p>Because Twisted's <code>CancelledError</code>s are <code>Exception</code>s, it's easy to
  15573. accidentally catch and suppress them. Care must be taken to ensure that
  15574. <code>CancelledError</code>s are allowed to propagate upwards.</p>
  15575. <table width="100%">
  15576. <tr>
  15577. <td width="50%" valign="top">
  15578. <p><strong>Bad</strong>:</p>
  15579. <pre><code class="language-python">try:
  15580. await do_something()
  15581. except Exception:
  15582. # `CancelledError` gets swallowed here.
  15583. logger.info(...)
  15584. </code></pre>
  15585. </td>
  15586. <td width="50%" valign="top">
  15587. <p><strong>Good</strong>:</p>
  15588. <pre><code class="language-python">try:
  15589. await do_something()
  15590. except CancelledError:
  15591. raise
  15592. except Exception:
  15593. logger.info(...)
  15594. </code></pre>
  15595. </td>
  15596. </tr>
  15597. <tr>
  15598. <td width="50%" valign="top">
  15599. <p><strong>OK</strong>:</p>
  15600. <pre><code class="language-python">try:
  15601. check_something()
  15602. # A `CancelledError` won't ever be raised here.
  15603. except Exception:
  15604. logger.info(...)
  15605. </code></pre>
  15606. </td>
  15607. <td width="50%" valign="top">
  15608. <p><strong>Good</strong>:</p>
  15609. <pre><code class="language-python">try:
  15610. await do_something()
  15611. except ValueError:
  15612. logger.info(...)
  15613. </code></pre>
  15614. </td>
  15615. </tr>
  15616. </table>
  15617. <h4 id="defergatherresults"><a class="header" href="#defergatherresults">defer.gatherResults</a></h4>
  15618. <p><code>defer.gatherResults</code> produces a <code>Deferred</code> which:</p>
  15619. <ul>
  15620. <li>broadcasts <code>cancel()</code> calls to every <code>Deferred</code> being waited on.</li>
  15621. <li>wraps the first exception it sees in a <code>FirstError</code>.</li>
  15622. </ul>
  15623. <p>Together, this means that <code>CancelledError</code>s will be wrapped in
  15624. a <code>FirstError</code> unless unwrapped. Such <code>FirstError</code>s are liable to be
  15625. swallowed, so they must be unwrapped.</p>
  15626. <table width="100%">
  15627. <tr>
  15628. <td width="50%" valign="top">
  15629. <p><strong>Bad</strong>:</p>
  15630. <pre><code class="language-python">async def do_something() -&gt; None:
  15631. await make_deferred_yieldable(
  15632. defer.gatherResults([...], consumeErrors=True)
  15633. )
  15634. try:
  15635. await do_something()
  15636. except CancelledError:
  15637. raise
  15638. except Exception:
  15639. # `FirstError(CancelledError)` gets swallowed here.
  15640. logger.info(...)
  15641. </code></pre>
  15642. </td>
  15643. <td width="50%" valign="top">
  15644. <p><strong>Good</strong>:</p>
  15645. <pre><code class="language-python">async def do_something() -&gt; None:
  15646. await make_deferred_yieldable(
  15647. defer.gatherResults([...], consumeErrors=True)
  15648. ).addErrback(unwrapFirstError)
  15649. try:
  15650. await do_something()
  15651. except CancelledError:
  15652. raise
  15653. except Exception:
  15654. logger.info(...)
  15655. </code></pre>
  15656. </td>
  15657. </tr>
  15658. </table>
  15659. <h3 id="creation-of-deferreds"><a class="header" href="#creation-of-deferreds">Creation of <code>Deferred</code>s</a></h3>
  15660. <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>
  15661. <table width="100%">
  15662. <tr>
  15663. <td width="50%" valign="top">
  15664. <p><strong>Bad</strong>:</p>
  15665. <pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}
  15666. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  15667. deferred = cache.get(room_id)
  15668. if deferred is None:
  15669. deferred = Deferred()
  15670. cache[room_id] = deferred
  15671. # `deferred` can have multiple waiters.
  15672. # All of them will observe a `CancelledError`
  15673. # if any one of them is cancelled.
  15674. return make_deferred_yieldable(deferred)
  15675. # Request 1
  15676. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15677. # Request 2
  15678. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15679. </code></pre>
  15680. </td>
  15681. <td width="50%" valign="top">
  15682. <p><strong>Good</strong>:</p>
  15683. <pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}
  15684. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  15685. deferred = cache.get(room_id)
  15686. if deferred is None:
  15687. deferred = Deferred()
  15688. cache[room_id] = deferred
  15689. # `deferred` will never be cancelled now.
  15690. # A `CancelledError` will still come out of
  15691. # the `await`.
  15692. # `delay_cancellation` may also be used.
  15693. return make_deferred_yieldable(stop_cancellation(deferred))
  15694. # Request 1
  15695. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15696. # Request 2
  15697. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15698. </code></pre>
  15699. </td>
  15700. </tr>
  15701. <tr>
  15702. <td width="50%" valign="top">
  15703. </td>
  15704. <td width="50%" valign="top">
  15705. <p><strong>Good</strong>:</p>
  15706. <pre><code class="language-python">cache: Dict[str, List[Deferred[None]]] = {}
  15707. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  15708. if room_id not in cache:
  15709. cache[room_id] = []
  15710. # Each request gets its own `Deferred` to wait on.
  15711. deferred = Deferred()
  15712. cache[room_id]].append(deferred)
  15713. return make_deferred_yieldable(deferred)
  15714. # Request 1
  15715. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15716. # Request 2
  15717. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15718. </code></pre>
  15719. </td>
  15720. </table>
  15721. <h3 id="uncancelled-processing"><a class="header" href="#uncancelled-processing">Uncancelled processing</a></h3>
  15722. <p>Some <code>async</code> functions may kick off some <code>async</code> processing which is
  15723. intentionally protected from cancellation, by <code>stop_cancellation</code> or
  15724. other means. If the <code>async</code> processing inherits the logcontext of the
  15725. request which initiated it, care must be taken to ensure that the
  15726. logcontext is not finished before the <code>async</code> processing completes.</p>
  15727. <table width="100%">
  15728. <tr>
  15729. <td width="50%" valign="top">
  15730. <p><strong>Bad</strong>:</p>
  15731. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  15732. async def do_something_else(
  15733. to_resolve: Deferred[None]
  15734. ) -&gt; None:
  15735. await ...
  15736. logger.info(&quot;done!&quot;)
  15737. to_resolve.callback(None)
  15738. async def do_something() -&gt; None:
  15739. if not cache:
  15740. to_resolve = Deferred()
  15741. cache = ObservableDeferred(to_resolve)
  15742. # `do_something_else` will never be cancelled and
  15743. # can outlive the `request-1` logging context.
  15744. run_in_background(do_something_else, to_resolve)
  15745. await make_deferred_yieldable(cache.observe())
  15746. with LoggingContext(&quot;request-1&quot;):
  15747. await do_something()
  15748. </code></pre>
  15749. </td>
  15750. <td width="50%" valign="top">
  15751. <p><strong>Good</strong>:</p>
  15752. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  15753. async def do_something_else(
  15754. to_resolve: Deferred[None]
  15755. ) -&gt; None:
  15756. await ...
  15757. logger.info(&quot;done!&quot;)
  15758. to_resolve.callback(None)
  15759. async def do_something() -&gt; None:
  15760. if not cache:
  15761. to_resolve = Deferred()
  15762. cache = ObservableDeferred(to_resolve)
  15763. run_in_background(do_something_else, to_resolve)
  15764. # We'll wait until `do_something_else` is
  15765. # done before raising a `CancelledError`.
  15766. await make_deferred_yieldable(
  15767. delay_cancellation(cache.observe())
  15768. )
  15769. else:
  15770. await make_deferred_yieldable(cache.observe())
  15771. with LoggingContext(&quot;request-1&quot;):
  15772. await do_something()
  15773. </code></pre>
  15774. </td>
  15775. </tr>
  15776. <tr>
  15777. <td width="50%">
  15778. <p><strong>OK</strong>:</p>
  15779. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  15780. async def do_something_else(
  15781. to_resolve: Deferred[None]
  15782. ) -&gt; None:
  15783. await ...
  15784. logger.info(&quot;done!&quot;)
  15785. to_resolve.callback(None)
  15786. async def do_something() -&gt; None:
  15787. if not cache:
  15788. to_resolve = Deferred()
  15789. cache = ObservableDeferred(to_resolve)
  15790. # `do_something_else` will get its own independent
  15791. # logging context. `request-1` will not count any
  15792. # metrics from `do_something_else`.
  15793. run_as_background_process(
  15794. &quot;do_something_else&quot;,
  15795. do_something_else,
  15796. to_resolve,
  15797. )
  15798. await make_deferred_yieldable(cache.observe())
  15799. with LoggingContext(&quot;request-1&quot;):
  15800. await do_something()
  15801. </code></pre>
  15802. </td>
  15803. <td width="50%">
  15804. </td>
  15805. </tr>
  15806. </table>
  15807. <div style="break-before: page; page-break-before: always;"></div><h1 id="log-contexts"><a class="header" href="#log-contexts">Log Contexts</a></h1>
  15808. <p>To help track the processing of individual requests, synapse uses a
  15809. '<code>log context</code>' to track which request it is handling at any given
  15810. moment. This is done via a thread-local variable; a <code>logging.Filter</code> is
  15811. then used to fish the information back out of the thread-local variable
  15812. and add it to each log record.</p>
  15813. <p>Logcontexts are also used for CPU and database accounting, so that we
  15814. can track which requests were responsible for high CPU use or database
  15815. activity.</p>
  15816. <p>The <code>synapse.logging.context</code> module provides facilities for managing
  15817. the current log context (as well as providing the <code>LoggingContextFilter</code>
  15818. class).</p>
  15819. <p>Asynchronous functions make the whole thing complicated, so this document describes
  15820. how it all works, and how to write code which follows the rules.</p>
  15821. <p>In this document, &quot;awaitable&quot; refers to any object which can be <code>await</code>ed. In the context of
  15822. Synapse, that normally means either a coroutine or a Twisted
  15823. <a href="https://twistedmatrix.com/documents/current/api/twisted.internet.defer.Deferred.html"><code>Deferred</code></a>.</p>
  15824. <h2 id="logcontexts-without-asynchronous-code"><a class="header" href="#logcontexts-without-asynchronous-code">Logcontexts without asynchronous code</a></h2>
  15825. <p>In the absence of any asynchronous voodoo, things are simple enough. As with
  15826. any code of this nature, the rule is that our function should leave
  15827. things as it found them:</p>
  15828. <pre><code class="language-python">from synapse.logging import context # omitted from future snippets
  15829. def handle_request(request_id):
  15830. request_context = context.LoggingContext()
  15831. calling_context = context.set_current_context(request_context)
  15832. try:
  15833. request_context.request = request_id
  15834. do_request_handling()
  15835. logger.debug(&quot;finished&quot;)
  15836. finally:
  15837. context.set_current_context(calling_context)
  15838. def do_request_handling():
  15839. logger.debug(&quot;phew&quot;) # this will be logged against request_id
  15840. </code></pre>
  15841. <p>LoggingContext implements the context management methods, so the above
  15842. can be written much more succinctly as:</p>
  15843. <pre><code class="language-python">def handle_request(request_id):
  15844. with context.LoggingContext() as request_context:
  15845. request_context.request = request_id
  15846. do_request_handling()
  15847. logger.debug(&quot;finished&quot;)
  15848. def do_request_handling():
  15849. logger.debug(&quot;phew&quot;)
  15850. </code></pre>
  15851. <h2 id="using-logcontexts-with-awaitables"><a class="header" href="#using-logcontexts-with-awaitables">Using logcontexts with awaitables</a></h2>
  15852. <p>Awaitables break the linear flow of code so that there is no longer a single entry point
  15853. where we should set the logcontext and a single exit point where we should remove it.</p>
  15854. <p>Consider the example above, where <code>do_request_handling</code> needs to do some
  15855. blocking operation, and returns an awaitable:</p>
  15856. <pre><code class="language-python">async def handle_request(request_id):
  15857. with context.LoggingContext() as request_context:
  15858. request_context.request = request_id
  15859. await do_request_handling()
  15860. logger.debug(&quot;finished&quot;)
  15861. </code></pre>
  15862. <p>In the above flow:</p>
  15863. <ul>
  15864. <li>The logcontext is set</li>
  15865. <li><code>do_request_handling</code> is called, and returns an awaitable</li>
  15866. <li><code>handle_request</code> awaits the awaitable</li>
  15867. <li>Execution of <code>handle_request</code> is suspended</li>
  15868. </ul>
  15869. <p>So we have stopped processing the request (and will probably go on to
  15870. start processing the next), without clearing the logcontext.</p>
  15871. <p>To circumvent this problem, synapse code assumes that, wherever you have
  15872. an awaitable, you will want to <code>await</code> it. To that end, whereever
  15873. functions return awaitables, we adopt the following conventions:</p>
  15874. <p><strong>Rules for functions returning awaitables:</strong></p>
  15875. <blockquote>
  15876. <ul>
  15877. <li>If the awaitable is already complete, the function returns with the
  15878. same logcontext it started with.</li>
  15879. <li>If the awaitable is incomplete, the function clears the logcontext
  15880. before returning; when the awaitable completes, it restores the
  15881. logcontext before running any callbacks.</li>
  15882. </ul>
  15883. </blockquote>
  15884. <p>That sounds complicated, but actually it means a lot of code (including
  15885. the example above) &quot;just works&quot;. There are two cases:</p>
  15886. <ul>
  15887. <li>
  15888. <p>If <code>do_request_handling</code> returns a completed awaitable, then the
  15889. logcontext will still be in place. In this case, execution will
  15890. continue immediately after the <code>await</code>; the &quot;finished&quot; line will
  15891. be logged against the right context, and the <code>with</code> block restores
  15892. the original context before we return to the caller.</p>
  15893. </li>
  15894. <li>
  15895. <p>If the returned awaitable is incomplete, <code>do_request_handling</code> clears
  15896. the logcontext before returning. The logcontext is therefore clear
  15897. when <code>handle_request</code> <code>await</code>s the awaitable.</p>
  15898. <p>Once <code>do_request_handling</code>'s awaitable completes, it will reinstate
  15899. the logcontext, before running the second half of <code>handle_request</code>,
  15900. so again the &quot;finished&quot; line will be logged against the right context,
  15901. and the <code>with</code> block restores the original context.</p>
  15902. </li>
  15903. </ul>
  15904. <p>As an aside, it's worth noting that <code>handle_request</code> follows our rules</p>
  15905. <ul>
  15906. <li>though that only matters if the caller has its own logcontext which it
  15907. cares about.</li>
  15908. </ul>
  15909. <p>The following sections describe pitfalls and helpful patterns when
  15910. implementing these rules.</p>
  15911. <h2 id="always-await-your-awaitables"><a class="header" href="#always-await-your-awaitables">Always await your awaitables</a></h2>
  15912. <p>Whenever you get an awaitable back from a function, you should <code>await</code> on
  15913. it as soon as possible. Do not pass go; do not do any logging; do not
  15914. call any other functions.</p>
  15915. <pre><code class="language-python">async def fun():
  15916. logger.debug(&quot;starting&quot;)
  15917. await do_some_stuff() # just like this
  15918. coro = more_stuff()
  15919. result = await coro # also fine, of course
  15920. return result
  15921. </code></pre>
  15922. <p>Provided this pattern is followed all the way back up to the callchain
  15923. to where the logcontext was set, this will make things work out ok:
  15924. provided <code>do_some_stuff</code> and <code>more_stuff</code> follow the rules above, then
  15925. so will <code>fun</code>.</p>
  15926. <p>It's all too easy to forget to <code>await</code>: for instance if we forgot that
  15927. <code>do_some_stuff</code> returned an awaitable, we might plough on regardless. This
  15928. leads to a mess; it will probably work itself out eventually, but not
  15929. before a load of stuff has been logged against the wrong context.
  15930. (Normally, other things will break, more obviously, if you forget to
  15931. <code>await</code>, so this tends not to be a major problem in practice.)</p>
  15932. <p>Of course sometimes you need to do something a bit fancier with your
  15933. awaitable - not all code follows the linear A-then-B-then-C pattern.
  15934. Notes on implementing more complex patterns are in later sections.</p>
  15935. <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>
  15936. <p>Most of the time, an awaitable comes from another synapse function.
  15937. Sometimes, though, we need to make up a new awaitable, or we get an awaitable
  15938. back from external code. We need to make it follow our rules.</p>
  15939. <p>The easy way to do it is by using <code>context.make_deferred_yieldable</code>. Suppose we want to implement
  15940. <code>sleep</code>, which returns a deferred which will run its callbacks after a
  15941. given number of seconds. That might look like:</p>
  15942. <pre><code class="language-python"># not a logcontext-rules-compliant function
  15943. def get_sleep_deferred(seconds):
  15944. d = defer.Deferred()
  15945. reactor.callLater(seconds, d.callback, None)
  15946. return d
  15947. </code></pre>
  15948. <p>That doesn't follow the rules, but we can fix it by calling it through
  15949. <code>context.make_deferred_yieldable</code>:</p>
  15950. <pre><code class="language-python">async def sleep(seconds):
  15951. return await context.make_deferred_yieldable(get_sleep_deferred(seconds))
  15952. </code></pre>
  15953. <h2 id="fire-and-forget"><a class="header" href="#fire-and-forget">Fire-and-forget</a></h2>
  15954. <p>Sometimes you want to fire off a chain of execution, but not wait for
  15955. its result. That might look a bit like this:</p>
  15956. <pre><code class="language-python">async def do_request_handling():
  15957. await foreground_operation()
  15958. # *don't* do this
  15959. background_operation()
  15960. logger.debug(&quot;Request handling complete&quot;)
  15961. async def background_operation():
  15962. await first_background_step()
  15963. logger.debug(&quot;Completed first step&quot;)
  15964. await second_background_step()
  15965. logger.debug(&quot;Completed second step&quot;)
  15966. </code></pre>
  15967. <p>The above code does a couple of steps in the background after
  15968. <code>do_request_handling</code> has finished. The log lines are still logged
  15969. against the <code>request_context</code> logcontext, which may or may not be
  15970. desirable. There are two big problems with the above, however. The first
  15971. problem is that, if <code>background_operation</code> returns an incomplete
  15972. awaitable, it will expect its caller to <code>await</code> immediately, so will have
  15973. cleared the logcontext. In this example, that means that 'Request
  15974. handling complete' will be logged without any context.</p>
  15975. <p>The second problem, which is potentially even worse, is that when the
  15976. awaitable returned by <code>background_operation</code> completes, it will restore
  15977. the original logcontext. There is nothing waiting on that awaitable, so
  15978. the logcontext will leak into the reactor and possibly get attached to
  15979. some arbitrary future operation.</p>
  15980. <p>There are two potential solutions to this.</p>
  15981. <p>One option is to surround the call to <code>background_operation</code> with a
  15982. <code>PreserveLoggingContext</code> call. That will reset the logcontext before
  15983. starting <code>background_operation</code> (so the context restored when the
  15984. deferred completes will be the empty logcontext), and will restore the
  15985. current logcontext before continuing the foreground process:</p>
  15986. <pre><code class="language-python">async def do_request_handling():
  15987. await foreground_operation()
  15988. # start background_operation off in the empty logcontext, to
  15989. # avoid leaking the current context into the reactor.
  15990. with PreserveLoggingContext():
  15991. background_operation()
  15992. # this will now be logged against the request context
  15993. logger.debug(&quot;Request handling complete&quot;)
  15994. </code></pre>
  15995. <p>Obviously that option means that the operations done in
  15996. <code>background_operation</code> would be not be logged against a logcontext
  15997. (though that might be fixed by setting a different logcontext via a
  15998. <code>with LoggingContext(...)</code> in <code>background_operation</code>).</p>
  15999. <p>The second option is to use <code>context.run_in_background</code>, which wraps a
  16000. function so that it doesn't reset the logcontext even when it returns
  16001. an incomplete awaitable, and adds a callback to the returned awaitable to
  16002. reset the logcontext. In other words, it turns a function that follows
  16003. the Synapse rules about logcontexts and awaitables into one which behaves
  16004. more like an external function --- the opposite operation to that
  16005. described in the previous section. It can be used like this:</p>
  16006. <pre><code class="language-python">async def do_request_handling():
  16007. await foreground_operation()
  16008. context.run_in_background(background_operation)
  16009. # this will now be logged against the request context
  16010. logger.debug(&quot;Request handling complete&quot;)
  16011. </code></pre>
  16012. <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>
  16013. <p>A typical example of this is where we want to collect together two or
  16014. more awaitables via <code>defer.gatherResults</code>:</p>
  16015. <pre><code class="language-python">a1 = operation1()
  16016. a2 = operation2()
  16017. a3 = defer.gatherResults([a1, a2])
  16018. </code></pre>
  16019. <p>This is really a variation of the fire-and-forget problem above, in that
  16020. we are firing off <code>a1</code> and <code>a2</code> without awaiting on them. The difference
  16021. is that we now have third-party code attached to their callbacks. Anyway
  16022. either technique given in the <a href="log_contexts.html#fire-and-forget">Fire-and-forget</a>
  16023. section will work.</p>
  16024. <p>Of course, the new awaitable returned by <code>gather</code> needs to be
  16025. wrapped in order to make it follow the logcontext rules before we can
  16026. 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
  16027. follow the
  16028. rules</a>.</p>
  16029. <p>So, option one: reset the logcontext before starting the operations to
  16030. be gathered:</p>
  16031. <pre><code class="language-python">async def do_request_handling():
  16032. with PreserveLoggingContext():
  16033. a1 = operation1()
  16034. a2 = operation2()
  16035. result = await defer.gatherResults([a1, a2])
  16036. </code></pre>
  16037. <p>In this case particularly, though, option two, of using
  16038. <code>context.run_in_background</code> almost certainly makes more sense, so that
  16039. <code>operation1</code> and <code>operation2</code> are both logged against the original
  16040. logcontext. This looks like:</p>
  16041. <pre><code class="language-python">async def do_request_handling():
  16042. a1 = context.run_in_background(operation1)
  16043. a2 = context.run_in_background(operation2)
  16044. result = await make_deferred_yieldable(defer.gatherResults([a1, a2]))
  16045. </code></pre>
  16046. <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>
  16047. <p>It turns out that our logcontext rules do not play nicely with awaitable
  16048. chains which get orphaned and garbage-collected.</p>
  16049. <p>Imagine we have some code that looks like this:</p>
  16050. <pre><code class="language-python">listener_queue = []
  16051. def on_something_interesting():
  16052. for d in listener_queue:
  16053. d.callback(&quot;foo&quot;)
  16054. async def await_something_interesting():
  16055. new_awaitable = defer.Deferred()
  16056. listener_queue.append(new_awaitable)
  16057. with PreserveLoggingContext():
  16058. await new_awaitable
  16059. </code></pre>
  16060. <p>Obviously, the idea here is that we have a bunch of things which are
  16061. waiting for an event. (It's just an example of the problem here, but a
  16062. relatively common one.)</p>
  16063. <p>Now let's imagine two further things happen. First of all, whatever was
  16064. waiting for the interesting thing goes away. (Perhaps the request times
  16065. out, or something <em>even more</em> interesting happens.)</p>
  16066. <p>Secondly, let's suppose that we decide that the interesting thing is
  16067. never going to happen, and we reset the listener queue:</p>
  16068. <pre><code class="language-python">def reset_listener_queue():
  16069. listener_queue.clear()
  16070. </code></pre>
  16071. <p>So, both ends of the awaitable chain have now dropped their references,
  16072. and the awaitable chain is now orphaned, and will be garbage-collected at
  16073. some point. Note that <code>await_something_interesting</code> is a coroutine,
  16074. which Python implements as a generator function. When Python
  16075. garbage-collects generator functions, it gives them a chance to
  16076. clean up by making the <code>await</code> (or <code>yield</code>) raise a <code>GeneratorExit</code>
  16077. exception. In our case, that means that the <code>__exit__</code> handler of
  16078. <code>PreserveLoggingContext</code> will carefully restore the request context, but
  16079. there is now nothing waiting for its return, so the request context is
  16080. never cleared.</p>
  16081. <p>To reiterate, this problem only arises when <em>both</em> ends of a awaitable
  16082. chain are dropped. Dropping the the reference to an awaitable you're
  16083. supposed to be awaiting is bad practice, so this doesn't
  16084. actually happen too much. Unfortunately, when it does happen, it will
  16085. lead to leaked logcontexts which are incredibly hard to track down.</p>
  16086. <div style="break-before: page; page-break-before: always;"></div><h1 id="replication-architecture"><a class="header" href="#replication-architecture">Replication Architecture</a></h1>
  16087. <h2 id="motivation"><a class="header" href="#motivation">Motivation</a></h2>
  16088. <p>We'd like to be able to split some of the work that synapse does into
  16089. multiple python processes. In theory multiple synapse processes could
  16090. share a single postgresql database and we'd scale up by running more
  16091. synapse processes. However much of synapse assumes that only one process
  16092. is interacting with the database, both for assigning unique identifiers
  16093. when inserting into tables, notifying components about new updates, and
  16094. for invalidating its caches.</p>
  16095. <p>So running multiple copies of the current code isn't an option. One way
  16096. to run multiple processes would be to have a single writer process and
  16097. multiple reader processes connected to the same database. In order to do
  16098. this we'd need a way for the reader process to invalidate its in-memory
  16099. caches when an update happens on the writer. One way to do this is for
  16100. the writer to present an append-only log of updates which the readers
  16101. can consume to invalidate their caches and to push updates to listening
  16102. clients or pushers.</p>
  16103. <p>Synapse already stores much of its data as an append-only log so that it
  16104. can correctly respond to <code>/sync</code> requests so the amount of code changes
  16105. needed to expose the append-only log to the readers should be fairly
  16106. minimal.</p>
  16107. <h2 id="architecture"><a class="header" href="#architecture">Architecture</a></h2>
  16108. <h3 id="the-replication-protocol"><a class="header" href="#the-replication-protocol">The Replication Protocol</a></h3>
  16109. <p>See <a href="tcp_replication.html">the TCP replication documentation</a>.</p>
  16110. <h3 id="the-slaved-datastore"><a class="header" href="#the-slaved-datastore">The Slaved DataStore</a></h3>
  16111. <p>There are read-only version of the synapse storage layer in
  16112. <code>synapse/replication/slave/storage</code> that use the response of the
  16113. replication API to invalidate their caches.</p>
  16114. <h3 id="the-tcp-replication-module"><a class="header" href="#the-tcp-replication-module">The TCP Replication Module</a></h3>
  16115. <p>Information about how the tcp replication module is structured, including how
  16116. the classes interact, can be found in
  16117. <code>synapse/replication/tcp/__init__.py</code></p>
  16118. <div style="break-before: page; page-break-before: always;"></div><h1 id="tcp-replication"><a class="header" href="#tcp-replication">TCP Replication</a></h1>
  16119. <h2 id="motivation-1"><a class="header" href="#motivation-1">Motivation</a></h2>
  16120. <p>Previously the workers used an HTTP long poll mechanism to get updates
  16121. from the master, which had the problem of causing a lot of duplicate
  16122. work on the server. This TCP protocol replaces those APIs with the aim
  16123. of increased efficiency.</p>
  16124. <h2 id="overview-3"><a class="header" href="#overview-3">Overview</a></h2>
  16125. <p>The protocol is based on fire and forget, line based commands. An
  16126. example flow would be (where '&gt;' indicates master to worker and
  16127. '&lt;' worker to master flows):</p>
  16128. <pre><code>&gt; SERVER example.com
  16129. &lt; REPLICATE
  16130. &gt; POSITION events master 53 53
  16131. &gt; RDATA events master 54 [&quot;$foo1:bar.com&quot;, ...]
  16132. &gt; RDATA events master 55 [&quot;$foo4:bar.com&quot;, ...]
  16133. </code></pre>
  16134. <p>The example shows the server accepting a new connection and sending its identity
  16135. with the <code>SERVER</code> command, followed by the client server to respond with the
  16136. position of all streams. The server then periodically sends <code>RDATA</code> commands
  16137. which have the format <code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row&gt;</code>, where
  16138. the format of <code>&lt;row&gt;</code> is defined by the individual streams. The
  16139. <code>&lt;instance_name&gt;</code> is the name of the Synapse process that generated the data
  16140. (usually &quot;master&quot;).</p>
  16141. <p>Error reporting happens by either the client or server sending an ERROR
  16142. command, and usually the connection will be closed.</p>
  16143. <p>Since the protocol is a simple line based, its possible to manually
  16144. connect to the server using a tool like netcat. A few things should be
  16145. noted when manually using the protocol:</p>
  16146. <ul>
  16147. <li>The federation stream is only available if federation sending has
  16148. been disabled on the main process.</li>
  16149. <li>The server will only time connections out that have sent a <code>PING</code>
  16150. command. If a ping is sent then the connection will be closed if no
  16151. further commands are receieved within 15s. Both the client and
  16152. server protocol implementations will send an initial PING on
  16153. connection and ensure at least one command every 5s is sent (not
  16154. necessarily <code>PING</code>).</li>
  16155. <li><code>RDATA</code> commands <em>usually</em> include a numeric token, however if the
  16156. stream has multiple rows to replicate per token the server will send
  16157. multiple <code>RDATA</code> commands, with all but the last having a token of
  16158. <code>batch</code>. See the documentation on <code>commands.RdataCommand</code> for
  16159. further details.</li>
  16160. </ul>
  16161. <h2 id="architecture-1"><a class="header" href="#architecture-1">Architecture</a></h2>
  16162. <p>The basic structure of the protocol is line based, where the initial
  16163. word of each line specifies the command. The rest of the line is parsed
  16164. based on the command. For example, the RDATA command is defined as:</p>
  16165. <pre><code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row_json&gt;
  16166. </code></pre>
  16167. <p>(Note that &lt;row_json&gt; may contains spaces, but cannot contain
  16168. newlines.)</p>
  16169. <p>Blank lines are ignored.</p>
  16170. <h3 id="keep-alives"><a class="header" href="#keep-alives">Keep alives</a></h3>
  16171. <p>Both sides are expected to send at least one command every 5s or so, and
  16172. should send a <code>PING</code> command if necessary. If either side do not receive
  16173. a command within e.g. 15s then the connection should be closed.</p>
  16174. <p>Because the server may be connected to manually using e.g. netcat, the
  16175. timeouts aren't enabled until an initial <code>PING</code> command is seen. Both
  16176. the client and server implementations below send a <code>PING</code> command
  16177. immediately on connection to ensure the timeouts are enabled.</p>
  16178. <p>This ensures that both sides can quickly realize if the tcp connection
  16179. has gone and handle the situation appropriately.</p>
  16180. <h3 id="start-up"><a class="header" href="#start-up">Start up</a></h3>
  16181. <p>When a new connection is made, the server:</p>
  16182. <ul>
  16183. <li>Sends a <code>SERVER</code> command, which includes the identity of the server,
  16184. allowing the client to detect if its connected to the expected
  16185. server</li>
  16186. <li>Sends a <code>PING</code> command as above, to enable the client to time out
  16187. connections promptly.</li>
  16188. </ul>
  16189. <p>The client:</p>
  16190. <ul>
  16191. <li>Sends a <code>NAME</code> command, allowing the server to associate a human
  16192. friendly name with the connection. This is optional.</li>
  16193. <li>Sends a <code>PING</code> as above</li>
  16194. <li>Sends a <code>REPLICATE</code> to get the current position of all streams.</li>
  16195. <li>On receipt of a <code>SERVER</code> command, checks that the server name
  16196. matches the expected server name.</li>
  16197. </ul>
  16198. <h3 id="error-handling"><a class="header" href="#error-handling">Error handling</a></h3>
  16199. <p>If either side detects an error it can send an <code>ERROR</code> command and close
  16200. the connection.</p>
  16201. <p>If the client side loses the connection to the server it should
  16202. reconnect, following the steps above.</p>
  16203. <h3 id="congestion"><a class="header" href="#congestion">Congestion</a></h3>
  16204. <p>If the server sends messages faster than the client can consume them the
  16205. server will first buffer a (fairly large) number of commands and then
  16206. disconnect the client. This ensures that we don't queue up an unbounded
  16207. number of commands in memory and gives us a potential oppurtunity to
  16208. squawk loudly. When/if the client recovers it can reconnect to the
  16209. server and ask for missed messages.</p>
  16210. <h3 id="reliability"><a class="header" href="#reliability">Reliability</a></h3>
  16211. <p>In general the replication stream should be considered an unreliable
  16212. transport since e.g. commands are not resent if the connection
  16213. disappears.</p>
  16214. <p>The exception to that are the replication streams, i.e. RDATA commands,
  16215. since these include tokens which can be used to restart the stream on
  16216. connection errors.</p>
  16217. <p>The client should keep track of the token in the last RDATA command
  16218. received for each stream so that on reconneciton it can start streaming
  16219. from the correct place. Note: not all RDATA have valid tokens due to
  16220. batching. See <code>RdataCommand</code> for more details.</p>
  16221. <h3 id="example-5"><a class="header" href="#example-5">Example</a></h3>
  16222. <p>An example iteraction is shown below. Each line is prefixed with '&gt;'
  16223. or '&lt;' to indicate which side is sending, these are <em>not</em> included on
  16224. the wire:</p>
  16225. <pre><code>* connection established *
  16226. &gt; SERVER localhost:8823
  16227. &gt; PING 1490197665618
  16228. &lt; NAME synapse.app.appservice
  16229. &lt; PING 1490197665618
  16230. &lt; REPLICATE
  16231. &gt; POSITION events master 1 1
  16232. &gt; POSITION backfill master 1 1
  16233. &gt; POSITION caches master 1 1
  16234. &gt; RDATA caches master 2 [&quot;get_user_by_id&quot;,[&quot;@01register-user:localhost:8823&quot;],1490197670513]
  16235. &gt; RDATA events master 14 [&quot;$149019767112vOHxz:localhost:8823&quot;,
  16236. &quot;!AFDCvgApUmpdfVjIXm:localhost:8823&quot;,&quot;m.room.guest_access&quot;,&quot;&quot;,null]
  16237. &lt; PING 1490197675618
  16238. &gt; ERROR server stopping
  16239. * connection closed by server *
  16240. </code></pre>
  16241. <p>The <code>POSITION</code> command sent by the server is used to set the clients
  16242. position without needing to send data with the <code>RDATA</code> command.</p>
  16243. <p>An example of a batched set of <code>RDATA</code> is:</p>
  16244. <pre><code>&gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test:localhost:8823&quot;],1490197670513]
  16245. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test2:localhost:8823&quot;],1490197670513]
  16246. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test3:localhost:8823&quot;],1490197670513]
  16247. &gt; RDATA caches master 54 [&quot;get_user_by_id&quot;,[&quot;@test4:localhost:8823&quot;],1490197670513]
  16248. </code></pre>
  16249. <p>In this case the client shouldn't advance their caches token until it
  16250. sees the the last <code>RDATA</code>.</p>
  16251. <h3 id="list-of-commands"><a class="header" href="#list-of-commands">List of commands</a></h3>
  16252. <p>The list of valid commands, with which side can send it: server (S) or
  16253. client (C):</p>
  16254. <h4 id="server-s"><a class="header" href="#server-s">SERVER (S)</a></h4>
  16255. <p>Sent at the start to identify which server the client is talking to</p>
  16256. <h4 id="rdata-s"><a class="header" href="#rdata-s">RDATA (S)</a></h4>
  16257. <p>A single update in a stream</p>
  16258. <h4 id="position-s"><a class="header" href="#position-s">POSITION (S)</a></h4>
  16259. <p>On receipt of a POSITION command clients should check if they have missed any
  16260. updates, and if so then fetch them out of band. Sent in response to a
  16261. REPLICATE command (but can happen at any time).</p>
  16262. <p>The POSITION command includes the source of the stream. Currently all streams
  16263. are written by a single process (usually &quot;master&quot;). If fetching missing
  16264. updates via HTTP API, rather than via the DB, then processes should make the
  16265. request to the appropriate process.</p>
  16266. <p>Two positions are included, the &quot;new&quot; position and the last position sent respectively.
  16267. This allows servers to tell instances that the positions have advanced but no
  16268. data has been written, without clients needlessly checking to see if they
  16269. have missed any updates.</p>
  16270. <h4 id="error-s-c"><a class="header" href="#error-s-c">ERROR (S, C)</a></h4>
  16271. <p>There was an error</p>
  16272. <h4 id="ping-s-c"><a class="header" href="#ping-s-c">PING (S, C)</a></h4>
  16273. <p>Sent periodically to ensure the connection is still alive</p>
  16274. <h4 id="name-c"><a class="header" href="#name-c">NAME (C)</a></h4>
  16275. <p>Sent at the start by client to inform the server who they are</p>
  16276. <h4 id="replicate-c"><a class="header" href="#replicate-c">REPLICATE (C)</a></h4>
  16277. <p>Asks the server for the current position of all streams.</p>
  16278. <h4 id="user_sync-c"><a class="header" href="#user_sync-c">USER_SYNC (C)</a></h4>
  16279. <p>A user has started or stopped syncing on this process.</p>
  16280. <h4 id="clear_user_sync-c"><a class="header" href="#clear_user_sync-c">CLEAR_USER_SYNC (C)</a></h4>
  16281. <p>The server should clear all associated user sync data from the worker.</p>
  16282. <p>This is used when a worker is shutting down.</p>
  16283. <h4 id="federation_ack-c"><a class="header" href="#federation_ack-c">FEDERATION_ACK (C)</a></h4>
  16284. <p>Acknowledge receipt of some federation data</p>
  16285. <h3 id="remote_server_up-s-c"><a class="header" href="#remote_server_up-s-c">REMOTE_SERVER_UP (S, C)</a></h3>
  16286. <p>Inform other processes that a remote server may have come back online.</p>
  16287. <p>See <code>synapse/replication/tcp/commands.py</code> for a detailed description and
  16288. the format of each command.</p>
  16289. <h3 id="cache-invalidation-stream"><a class="header" href="#cache-invalidation-stream">Cache Invalidation Stream</a></h3>
  16290. <p>The cache invalidation stream is used to inform workers when they need
  16291. to invalidate any of their caches in the data store. This is done by
  16292. streaming all cache invalidations done on master down to the workers,
  16293. assuming that any caches on the workers also exist on the master.</p>
  16294. <p>Each individual cache invalidation results in a row being sent down
  16295. replication, which includes the cache name (the name of the function)
  16296. and they key to invalidate. For example:</p>
  16297. <pre><code>&gt; RDATA caches master 550953771 [&quot;get_user_by_id&quot;, [&quot;@bob:example.com&quot;], 1550574873251]
  16298. </code></pre>
  16299. <p>Alternatively, an entire cache can be invalidated by sending down a <code>null</code>
  16300. instead of the key. For example:</p>
  16301. <pre><code>&gt; RDATA caches master 550953772 [&quot;get_user_by_id&quot;, null, 1550574873252]
  16302. </code></pre>
  16303. <p>However, there are times when a number of caches need to be invalidated
  16304. at the same time with the same key. To reduce traffic we batch those
  16305. invalidations into a single poke by defining a special cache name that
  16306. workers understand to mean to expand to invalidate the correct caches.</p>
  16307. <p>Currently the special cache names are declared in
  16308. <code>synapse/storage/_base.py</code> and are:</p>
  16309. <ol>
  16310. <li><code>cs_cache_fake</code> ─ invalidates caches that depend on the current
  16311. state</li>
  16312. </ol>
  16313. <div style="break-before: page; page-break-before: always;"></div><h1 id="internal-documentation"><a class="header" href="#internal-documentation">Internal Documentation</a></h1>
  16314. <p>This section covers implementation documentation for various parts of Synapse.</p>
  16315. <p>If a developer is planning to make a change to a feature of Synapse, it can be useful for
  16316. general documentation of how that feature is implemented to be available. This saves the
  16317. developer time in place of needing to understand how the feature works by reading the
  16318. code.</p>
  16319. <p>Documentation that would be more useful for the perspective of a system administrator,
  16320. rather than a developer who's intending to change to code, should instead be placed
  16321. under the Usage section of the documentation.</p>
  16322. <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>
  16323. <p>https://fujifish.github.io/samling/samling.html (https://github.com/fujifish/samling) is a great resource for being able to tinker with the
  16324. SAML options within Synapse without needing to deploy and configure a complicated software stack.</p>
  16325. <p>To make Synapse (and therefore Element) use it:</p>
  16326. <ol>
  16327. <li>Use the samling.html URL above or deploy your own and visit the IdP Metadata tab.</li>
  16328. <li>Copy the XML to your clipboard.</li>
  16329. <li>On your Synapse server, create a new file <code>samling.xml</code> next to your <code>homeserver.yaml</code> with
  16330. the XML from step 2 as the contents.</li>
  16331. <li>Edit your <code>homeserver.yaml</code> to include:
  16332. <pre><code class="language-yaml">saml2_config:
  16333. sp_config:
  16334. allow_unknown_attributes: true # Works around a bug with AVA Hashes: https://github.com/IdentityPython/pysaml2/issues/388
  16335. metadata:
  16336. local: [&quot;samling.xml&quot;]
  16337. </code></pre>
  16338. </li>
  16339. <li>Ensure that your <code>homeserver.yaml</code> has a setting for <code>public_baseurl</code>:
  16340. <pre><code class="language-yaml">public_baseurl: http://localhost:8080/
  16341. </code></pre>
  16342. </li>
  16343. <li>Run <code>apt-get install xmlsec1</code> and <code>pip install --upgrade --force 'pysaml2&gt;=4.5.0'</code> to ensure
  16344. the dependencies are installed and ready to go.</li>
  16345. <li>Restart Synapse.</li>
  16346. </ol>
  16347. <p>Then in Element:</p>
  16348. <ol>
  16349. <li>Visit the login page and point Element towards your homeserver using the <code>public_baseurl</code> above.</li>
  16350. <li>Click the Single Sign-On button.</li>
  16351. <li>On the samling page, enter a Name Identifier and add a SAML Attribute for <code>uid=your_localpart</code>.
  16352. The response must also be signed.</li>
  16353. <li>Click &quot;Next&quot;.</li>
  16354. <li>Click &quot;Post Response&quot; (change nothing).</li>
  16355. <li>You should be logged in.</li>
  16356. </ol>
  16357. <p>If you try and repeat this process, you may be automatically logged in using the information you
  16358. gave previously. To fix this, open your developer console (<code>F12</code> or <code>Ctrl+Shift+I</code>) while on the
  16359. samling page and clear the site data. In Chrome, this will be a button on the Application tab.</p>
  16360. <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>
  16361. <p>The <a href="https://github.com/jbittel/django-mama-cas">django-mama-cas</a> project is an
  16362. easy to run CAS implementation built on top of Django.</p>
  16363. <h2 id="prerequisites"><a class="header" href="#prerequisites">Prerequisites</a></h2>
  16364. <ol>
  16365. <li>Create a new virtualenv: <code>python3 -m venv &lt;your virtualenv&gt;</code></li>
  16366. <li>Activate your virtualenv: <code>source /path/to/your/virtualenv/bin/activate</code></li>
  16367. <li>Install Django and django-mama-cas:
  16368. <pre><code class="language-sh">python -m pip install &quot;django&lt;3&quot; &quot;django-mama-cas==2.4.0&quot;
  16369. </code></pre>
  16370. </li>
  16371. <li>Create a Django project in the current directory:
  16372. <pre><code class="language-sh">django-admin startproject cas_test .
  16373. </code></pre>
  16374. </li>
  16375. <li>Follow the <a href="https://django-mama-cas.readthedocs.io/en/latest/installation.html#configuring">install directions</a> for django-mama-cas</li>
  16376. <li>Setup the SQLite database: <code>python manage.py migrate</code></li>
  16377. <li>Create a user:
  16378. <pre><code class="language-sh">python manage.py createsuperuser
  16379. </code></pre>
  16380. <ol>
  16381. <li>Use whatever you want as the username and password.</li>
  16382. <li>Leave the other fields blank.</li>
  16383. </ol>
  16384. </li>
  16385. <li>Use the built-in Django test server to serve the CAS endpoints on port 8000:
  16386. <pre><code class="language-sh">python manage.py runserver
  16387. </code></pre>
  16388. </li>
  16389. </ol>
  16390. <p>You should now have a Django project configured to serve CAS authentication with
  16391. a single user created.</p>
  16392. <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>
  16393. <ol>
  16394. <li>Modify your <code>homeserver.yaml</code> to enable CAS and point it to your locally
  16395. running Django test server:
  16396. <pre><code class="language-yaml">cas_config:
  16397. enabled: true
  16398. server_url: &quot;http://localhost:8000&quot;
  16399. service_url: &quot;http://localhost:8081&quot;
  16400. #displayname_attribute: name
  16401. #required_attributes:
  16402. # name: value
  16403. </code></pre>
  16404. </li>
  16405. <li>Restart Synapse.</li>
  16406. </ol>
  16407. <p>Note that the above configuration assumes the homeserver is running on port 8081
  16408. and that the CAS server is on port 8000, both on localhost.</p>
  16409. <h2 id="testing-the-configuration"><a class="header" href="#testing-the-configuration">Testing the configuration</a></h2>
  16410. <p>Then in Element:</p>
  16411. <ol>
  16412. <li>Visit the login page with a Element pointing at your homeserver.</li>
  16413. <li>Click the Single Sign-On button.</li>
  16414. <li>Login using the credentials created with <code>createsuperuser</code>.</li>
  16415. <li>You should be logged in.</li>
  16416. </ol>
  16417. <p>If you want to repeat this process you'll need to manually logout first:</p>
  16418. <ol>
  16419. <li>http://localhost:8000/admin/</li>
  16420. <li>Click &quot;logout&quot; in the top right.</li>
  16421. </ol>
  16422. <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>
  16423. <h2 id="edges"><a class="header" href="#edges">Edges</a></h2>
  16424. <p>The word &quot;edge&quot; comes from graph theory lingo. An edge is just a connection
  16425. between two events. In Synapse, we connect events by specifying their
  16426. <code>prev_events</code>. A subsequent event points back at a previous event.</p>
  16427. <pre><code>A (oldest) &lt;---- B &lt;---- C (most recent)
  16428. </code></pre>
  16429. <h2 id="depth-and-stream-ordering"><a class="header" href="#depth-and-stream-ordering">Depth and stream ordering</a></h2>
  16430. <p>Events are normally sorted by <code>(topological_ordering, stream_ordering)</code> where
  16431. <code>topological_ordering</code> is just <code>depth</code>. In other words, we first sort by <code>depth</code>
  16432. and then tie-break based on <code>stream_ordering</code>. <code>depth</code> is incremented as new
  16433. messages are added to the DAG. Normally, <code>stream_ordering</code> is an auto
  16434. incrementing integer, but backfilled events start with <code>stream_ordering=-1</code> and decrement.</p>
  16435. <hr />
  16436. <ul>
  16437. <li><code>/sync</code> returns things in the order they arrive at the server (<code>stream_ordering</code>).</li>
  16438. <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>
  16439. </ul>
  16440. <p>The general idea is that, if you're following a room in real-time (i.e.
  16441. <code>/sync</code>), you probably want to see the messages as they arrive at your server,
  16442. rather than skipping any that arrived late; whereas if you're looking at a
  16443. historical section of timeline (i.e. <code>/messages</code>), you want to see the best
  16444. representation of the state of the room as others were seeing it at the time.</p>
  16445. <h2 id="outliers"><a class="header" href="#outliers">Outliers</a></h2>
  16446. <p>We mark an event as an <code>outlier</code> when we haven't figured out the state for the
  16447. room at that point in the DAG yet. They are &quot;floating&quot; events that we haven't
  16448. yet correlated to the DAG.</p>
  16449. <p>Outliers typically arise when we fetch the auth chain or state for a given
  16450. event. When that happens, we just grab the events in the state/auth chain,
  16451. without calculating the state at those events, or backfilling their
  16452. <code>prev_events</code>. Since we don't have the state at any events fetched in that
  16453. way, we mark them as outliers.</p>
  16454. <p>So, typically, we won't have the <code>prev_events</code> of an <code>outlier</code> in the database,
  16455. (though it's entirely possible that we <em>might</em> have them for some other
  16456. reason). Other things that make outliers different from regular events:</p>
  16457. <ul>
  16458. <li>
  16459. <p>We don't have state for them, so there should be no entry in
  16460. <code>event_to_state_groups</code> for an outlier. (In practice this isn't always
  16461. the case, though I'm not sure why: see https://github.com/matrix-org/synapse/issues/12201).</p>
  16462. </li>
  16463. <li>
  16464. <p>We don't record entries for them in the <code>event_edges</code>,
  16465. <code>event_forward_extremeties</code> or <code>event_backward_extremities</code> tables.</p>
  16466. </li>
  16467. </ul>
  16468. <p>Since outliers are not tied into the DAG, they do not normally form part of the
  16469. timeline sent down to clients via <code>/sync</code> or <code>/messages</code>; however there is an
  16470. exception:</p>
  16471. <h3 id="out-of-band-membership-events"><a class="header" href="#out-of-band-membership-events">Out-of-band membership events</a></h3>
  16472. <p>A special case of outlier events are some membership events for federated rooms
  16473. that we aren't full members of. For example:</p>
  16474. <ul>
  16475. <li>invites received over federation, before we join the room</li>
  16476. <li><em>rejections</em> for said invites</li>
  16477. <li>knock events for rooms that we would like to join but have not yet joined.</li>
  16478. </ul>
  16479. <p>In all the above cases, we don't have the state for the room, which is why they
  16480. are treated as outliers. They are a bit special though, in that they are
  16481. proactively sent to clients via <code>/sync</code>.</p>
  16482. <h2 id="forward-extremity"><a class="header" href="#forward-extremity">Forward extremity</a></h2>
  16483. <p>Most-recent-in-time events in the DAG which are not referenced by any other
  16484. events' <code>prev_events</code> yet. (In this definition, outliers, rejected events, and
  16485. soft-failed events don't count.)</p>
  16486. <p>The forward extremities of a room (or at least, a subset of them, if there are
  16487. more than ten) are used as the <code>prev_events</code> when the next event is sent.</p>
  16488. <p>The &quot;current state&quot; of a room (ie: the state which would be used if we
  16489. generated a new event) is, therefore, the resolution of the room states
  16490. at each of the forward extremities.</p>
  16491. <h2 id="backward-extremity"><a class="header" href="#backward-extremity">Backward extremity</a></h2>
  16492. <p>The current marker of where we have backfilled up to and will generally be the
  16493. <code>prev_events</code> of the oldest-in-time events we have in the DAG. This gives a starting point when
  16494. backfilling history.</p>
  16495. <p>Note that, unlike forward extremities, we typically don't have any backward
  16496. extremity events themselves in the database - or, if we do, they will be &quot;outliers&quot; (see
  16497. above). Either way, we don't expect to have the room state at a backward extremity.</p>
  16498. <p>When we persist a non-outlier event, if it was previously a backward extremity,
  16499. we clear it as a backward extremity and set all of its <code>prev_events</code> as the new
  16500. backward extremities if they aren't already persisted as non-outliers. This
  16501. therefore keeps the backward extremities up-to-date.</p>
  16502. <h2 id="state-groups"><a class="header" href="#state-groups">State groups</a></h2>
  16503. <p>For every non-outlier event we need to know the state at that event. Instead of
  16504. storing the full state for each event in the DB (i.e. a <code>event_id -&gt; state</code>
  16505. mapping), which is <em>very</em> space inefficient when state doesn't change, we
  16506. instead assign each different set of state a &quot;state group&quot; and then have
  16507. mappings of <code>event_id -&gt; state_group</code> and <code>state_group -&gt; state</code>.</p>
  16508. <h3 id="stage-group-edges"><a class="header" href="#stage-group-edges">Stage group edges</a></h3>
  16509. <p>TODO: <code>state_group_edges</code> is a further optimization...
  16510. notes from @Azrenbeth, https://pastebin.com/seUGVGeT</p>
  16511. <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>
  16512. <p>The auth chain difference algorithm is used by V2 state resolution, where a
  16513. naive implementation can be a significant source of CPU and DB usage.</p>
  16514. <h3 id="definitions"><a class="header" href="#definitions">Definitions</a></h3>
  16515. <p>A <em>state set</em> is a set of state events; e.g. the input of a state resolution
  16516. algorithm is a collection of state sets.</p>
  16517. <p>The <em>auth chain</em> of a set of events are all the events' auth events and <em>their</em>
  16518. auth events, recursively (i.e. the events reachable by walking the graph induced
  16519. by an event's auth events links).</p>
  16520. <p>The <em>auth chain difference</em> of a collection of state sets is the union minus the
  16521. intersection of the sets of auth chains corresponding to the state sets, i.e an
  16522. event is in the auth chain difference if it is reachable by walking the auth
  16523. event graph from at least one of the state sets but not from <em>all</em> of the state
  16524. sets.</p>
  16525. <h2 id="breadth-first-walk-algorithm"><a class="header" href="#breadth-first-walk-algorithm">Breadth First Walk Algorithm</a></h2>
  16526. <p>A way of calculating the auth chain difference without calculating the full auth
  16527. chains for each state set is to do a parallel breadth first walk (ordered by
  16528. depth) of each state set's auth chain. By tracking which events are reachable
  16529. from each state set we can finish early if every pending event is reachable from
  16530. every state set.</p>
  16531. <p>This can work well for state sets that have a small auth chain difference, but
  16532. can be very inefficient for larger differences. However, this algorithm is still
  16533. used if we don't have a chain cover index for the room (e.g. because we're in
  16534. the process of indexing it).</p>
  16535. <h2 id="chain-cover-index"><a class="header" href="#chain-cover-index">Chain Cover Index</a></h2>
  16536. <p>Synapse computes auth chain differences by pre-computing a &quot;chain cover&quot; index
  16537. for the auth chain in a room, allowing us to efficiently make reachability queries
  16538. like &quot;is event <code>A</code> in the auth chain of event <code>B</code>?&quot;. We could do this with an index
  16539. that tracks all pairs <code>(A, B)</code> such that <code>A</code> is in the auth chain of <code>B</code>. However, this
  16540. would be prohibitively large, scaling poorly as the room accumulates more state
  16541. events.</p>
  16542. <p>Instead, we break down the graph into <em>chains</em>. A chain is a subset of a DAG
  16543. with the following property: for any pair of events <code>E</code> and <code>F</code> in the chain,
  16544. the chain contains a path <code>E -&gt; F</code> or a path <code>F -&gt; E</code>. This forces a chain to be
  16545. linear (without forks), e.g. <code>E -&gt; F -&gt; G -&gt; ... -&gt; H</code>. Each event in the chain
  16546. is given a <em>sequence number</em> local to that chain. The oldest event <code>E</code> in the
  16547. chain has sequence number 1. If <code>E</code> has a child <code>F</code> in the chain, then <code>F</code> has
  16548. sequence number 2. If <code>E</code> has a grandchild <code>G</code> in the chain, then <code>G</code> has
  16549. sequence number 3; and so on.</p>
  16550. <p>Synapse ensures that each persisted event belongs to exactly one chain, and
  16551. tracks how the chains are connected to one another. This allows us to
  16552. efficiently answer reachability queries. Doing so uses less storage than
  16553. tracking reachability on an event-by-event basis, particularly when we have
  16554. fewer and longer chains. See</p>
  16555. <blockquote>
  16556. <p>Jagadish, H. (1990). <a href="https://doi.org/10.1145/99935.99944">A compression technique to materialize transitive closure</a>.
  16557. <em>ACM Transactions on Database Systems (TODS)</em>, 15*(4)*, 558-598.</p>
  16558. </blockquote>
  16559. <p>for the original idea or</p>
  16560. <blockquote>
  16561. <p>Y. Chen, Y. Chen, <a href="https://doi.org/10.1109/ICDE.2008.4497498">An efficient algorithm for answering graph
  16562. reachability queries</a>,
  16563. in: 2008 IEEE 24th International Conference on Data Engineering, April 2008,
  16564. 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>
  16565. </blockquote>
  16566. <p>for a more modern take.</p>
  16567. <p>In practical terms, the chain cover assigns every event a
  16568. <em>chain ID</em> and <em>sequence number</em> (e.g. <code>(5,3)</code>), and maintains a map of <em>links</em>
  16569. between events in chains (e.g. <code>(5,3) -&gt; (2,4)</code>) such that <code>A</code> is reachable by <code>B</code>
  16570. (i.e. <code>A</code> is in the auth chain of <code>B</code>) if and only if either:</p>
  16571. <ol>
  16572. <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
  16573. sequence number; or</li>
  16574. <li>there is a link <code>L</code> between <code>B</code>'s chain ID and <code>A</code>'s chain ID such that
  16575. <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>
  16576. </ol>
  16577. <p>There are actually two potential implementations, one where we store links from
  16578. each chain to every other reachable chain (the transitive closure of the links
  16579. graph), and one where we remove redundant links (the transitive reduction of the
  16580. links graph) e.g. if we have chains <code>C3 -&gt; C2 -&gt; C1</code> then the link <code>C3 -&gt; C1</code>
  16581. would not be stored. Synapse uses the former implementation so that it doesn't
  16582. need to recurse to test reachability between chains. This trades-off extra storage
  16583. in order to save CPU cycles and DB queries.</p>
  16584. <h3 id="example-6"><a class="header" href="#example-6">Example</a></h3>
  16585. <p>An example auth graph would look like the following, where chains have been
  16586. formed based on type/state_key and are denoted by colour and are labelled with
  16587. <code>(chain ID, sequence number)</code>. Links are denoted by the arrows (links in grey
  16588. are those that would be remove in the second implementation described above).</p>
  16589. <p><img src="auth_chain_diff.dot.png" alt="Example" /></p>
  16590. <p>Note that we don't include all links between events and their auth events, as
  16591. most of those links would be redundant. For example, all events point to the
  16592. create event, but each chain only needs the one link from it's base to the
  16593. create event.</p>
  16594. <h2 id="using-the-index"><a class="header" href="#using-the-index">Using the Index</a></h2>
  16595. <p>This index can be used to calculate the auth chain difference of the state sets
  16596. by looking at the chain ID and sequence numbers reachable from each state set:</p>
  16597. <ol>
  16598. <li>For every state set lookup the chain ID/sequence numbers of each state event</li>
  16599. <li>Use the index to find all chains and the maximum sequence number reachable
  16600. from each state set.</li>
  16601. <li>The auth chain difference is then all events in each chain that have sequence
  16602. numbers between the maximum sequence number reachable from <em>any</em> state set and
  16603. the minimum reachable by <em>all</em> state sets (if any).</li>
  16604. </ol>
  16605. <p>Note that steps 2 is effectively calculating the auth chain for each state set
  16606. (in terms of chain IDs and sequence numbers), and step 3 is calculating the
  16607. difference between the union and intersection of the auth chains.</p>
  16608. <h3 id="worked-example"><a class="header" href="#worked-example">Worked Example</a></h3>
  16609. <p>For example, given the above graph, we can calculate the difference between
  16610. state sets consisting of:</p>
  16611. <ol>
  16612. <li><code>S1</code>: Alice's invite <code>(4,1)</code> and Bob's second join <code>(2,2)</code>; and</li>
  16613. <li><code>S2</code>: Alice's second join <code>(4,3)</code> and Bob's first join <code>(2,1)</code>.</li>
  16614. </ol>
  16615. <p>Using the index we see that the following auth chains are reachable from each
  16616. state set:</p>
  16617. <ol>
  16618. <li><code>S1</code>: <code>(1,1)</code>, <code>(2,2)</code>, <code>(3,1)</code> &amp; <code>(4,1)</code></li>
  16619. <li><code>S2</code>: <code>(1,1)</code>, <code>(2,1)</code>, <code>(3,2)</code> &amp; <code>(4,3)</code></li>
  16620. </ol>
  16621. <p>And so, for each the ranges that are in the auth chain difference:</p>
  16622. <ol>
  16623. <li>Chain 1: None, (since everything can reach the create event).</li>
  16624. <li>Chain 2: The range <code>(1, 2]</code> (i.e. just <code>2</code>), as <code>1</code> is reachable by all state
  16625. sets and the maximum reachable is <code>2</code> (corresponding to Bob's second join).</li>
  16626. <li>Chain 3: Similarly the range <code>(1, 2]</code> (corresponding to the second power
  16627. level).</li>
  16628. <li>Chain 4: The range <code>(1, 3]</code> (corresponding to both of Alice's joins).</li>
  16629. </ol>
  16630. <p>So the final result is: Bob's second join <code>(2,2)</code>, the second power level
  16631. <code>(3,2)</code> and both of Alice's joins <code>(4,2)</code> &amp; <code>(4,3)</code>.</p>
  16632. <div style="break-before: page; page-break-before: always;"></div><h1 id="media-repository"><a class="header" href="#media-repository">Media Repository</a></h1>
  16633. <p><em>Synapse implementation-specific details for the media repository</em></p>
  16634. <p>The media repository</p>
  16635. <ul>
  16636. <li>stores avatars, attachments and their thumbnails for media uploaded by local
  16637. users.</li>
  16638. <li>caches avatars, attachments and their thumbnails for media uploaded by remote
  16639. users.</li>
  16640. <li>caches resources and thumbnails used for URL previews.</li>
  16641. </ul>
  16642. <p>All media in Matrix can be identified by a unique
  16643. <a href="https://spec.matrix.org/latest/client-server-api/#matrix-content-mxc-uris">MXC URI</a>,
  16644. consisting of a server name and media ID:</p>
  16645. <pre><code>mxc://&lt;server-name&gt;/&lt;media-id&gt;
  16646. </code></pre>
  16647. <h2 id="local-media"><a class="header" href="#local-media">Local Media</a></h2>
  16648. <p>Synapse generates 24 character media IDs for content uploaded by local users.
  16649. These media IDs consist of upper and lowercase letters and are case-sensitive.
  16650. Other homeserver implementations may generate media IDs differently.</p>
  16651. <p>Local media is recorded in the <code>local_media_repository</code> table, which includes
  16652. metadata such as MIME types, upload times and file sizes.
  16653. Note that this table is shared by the URL cache, which has a different media ID
  16654. scheme.</p>
  16655. <h3 id="paths"><a class="header" href="#paths">Paths</a></h3>
  16656. <p>A file with media ID <code>aabbcccccccccccccccccccc</code> and its <code>128x96</code> <code>image/jpeg</code>
  16657. thumbnail, created by scaling, would be stored at:</p>
  16658. <pre><code>local_content/aa/bb/cccccccccccccccccccc
  16659. local_thumbnails/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  16660. </code></pre>
  16661. <h2 id="remote-media"><a class="header" href="#remote-media">Remote Media</a></h2>
  16662. <p>When media from a remote homeserver is requested from Synapse, it is assigned
  16663. a local <code>filesystem_id</code>, with the same format as locally-generated media IDs,
  16664. as described above.</p>
  16665. <p>A record of remote media is stored in the <code>remote_media_cache</code> table, which
  16666. can be used to map remote MXC URIs (server names and media IDs) to local
  16667. <code>filesystem_id</code>s.</p>
  16668. <h3 id="paths-1"><a class="header" href="#paths-1">Paths</a></h3>
  16669. <p>A file from <code>matrix.org</code> with <code>filesystem_id</code> <code>aabbcccccccccccccccccccc</code> and its
  16670. <code>128x96</code> <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  16671. <pre><code>remote_content/matrix.org/aa/bb/cccccccccccccccccccc
  16672. remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  16673. </code></pre>
  16674. <p>Older thumbnails may omit the thumbnailing method:</p>
  16675. <pre><code>remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg
  16676. </code></pre>
  16677. <p>Note that <code>remote_thumbnail/</code> does not have an <code>s</code>.</p>
  16678. <h2 id="url-previews-1"><a class="header" href="#url-previews-1">URL Previews</a></h2>
  16679. <p>When generating previews for URLs, Synapse may download and cache various
  16680. resources, including images. These resources are assigned temporary media IDs
  16681. of the form <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code>, where <code>yyyy-mm-dd</code> is the current
  16682. date and <code>aaaaaaaaaaaaaaaa</code> is a random sequence of 16 case-sensitive letters.</p>
  16683. <p>The metadata for these cached resources is stored in the
  16684. <code>local_media_repository</code> and <code>local_media_repository_url_cache</code> tables.</p>
  16685. <p>Resources for URL previews are deleted after a few days.</p>
  16686. <h3 id="paths-2"><a class="header" href="#paths-2">Paths</a></h3>
  16687. <p>The file with media ID <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code> and its <code>128x96</code>
  16688. <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  16689. <pre><code>url_cache/yyyy-mm-dd/aaaaaaaaaaaaaaaa
  16690. url_cache_thumbnails/yyyy-mm-dd/aaaaaaaaaaaaaaaa/128-96-image-jpeg-scale
  16691. </code></pre>
  16692. <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>
  16693. <p>Synapse maintains room and user statistics in various tables. These can be used
  16694. for administrative purposes but are also used when generating the public room
  16695. directory.</p>
  16696. <h1 id="synapse-developer-documentation"><a class="header" href="#synapse-developer-documentation">Synapse Developer Documentation</a></h1>
  16697. <h2 id="high-level-concepts"><a class="header" href="#high-level-concepts">High-Level Concepts</a></h2>
  16698. <h3 id="definitions-1"><a class="header" href="#definitions-1">Definitions</a></h3>
  16699. <ul>
  16700. <li><strong>subject</strong>: Something we are tracking stats about – currently a room or user.</li>
  16701. <li><strong>current row</strong>: An entry for a subject in the appropriate current statistics
  16702. table. Each subject can have only one.</li>
  16703. </ul>
  16704. <h3 id="overview-4"><a class="header" href="#overview-4">Overview</a></h3>
  16705. <p>Stats correspond to the present values. Current rows contain the most up-to-date
  16706. statistics for a room. Each subject can only have one entry.</p>
  16707. <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>
  16708. <p>Synapse has a number of platform dependencies, including Python, Rust,
  16709. PostgreSQL and SQLite. This document outlines the policy towards which versions
  16710. we support, and when we drop support for versions in the future.</p>
  16711. <h2 id="policy"><a class="header" href="#policy">Policy</a></h2>
  16712. <p>Synapse follows the upstream support life cycles for Python and PostgreSQL,
  16713. i.e. when a version reaches End of Life Synapse will withdraw support for that
  16714. version in future releases.</p>
  16715. <p>Details on the upstream support life cycles for Python and PostgreSQL are
  16716. documented at <a href="https://endoflife.date/python">https://endoflife.date/python</a> and
  16717. <a href="https://endoflife.date/postgresql">https://endoflife.date/postgresql</a>.</p>
  16718. <p>A Rust compiler is required to build Synapse from source. For any given release
  16719. the minimum required version may be bumped up to a recent Rust version, and so
  16720. people building from source should ensure they can fetch recent versions of Rust
  16721. (e.g. by using <a href="https://rustup.rs/">rustup</a>).</p>
  16722. <p>The oldest supported version of SQLite is the version
  16723. <a href="https://packages.debian.org/buster/libsqlite3-0">provided</a> by
  16724. <a href="https://wiki.debian.org/DebianOldStable">Debian oldstable</a>.</p>
  16725. <h2 id="context"><a class="header" href="#context">Context</a></h2>
  16726. <p>It is important for system admins to have a clear understanding of the platform
  16727. requirements of Synapse and its deprecation policies so that they can
  16728. effectively plan upgrading their infrastructure ahead of time. This is
  16729. especially important in contexts where upgrading the infrastructure requires
  16730. auditing and approval from a security team, or where otherwise upgrading is a
  16731. long process.</p>
  16732. <p>By following the upstream support life cycles Synapse can ensure that its
  16733. dependencies continue to get security patches, while not requiring system admins
  16734. to constantly update their platform dependencies to the latest versions.</p>
  16735. <p>For Rust, the situation is a bit different given that a) the Rust foundation
  16736. does not generally support older Rust versions, and b) the library ecosystem
  16737. generally bump their minimum support Rust versions frequently. In general, the
  16738. Synapse team will try to avoid updating the dependency on Rust to the absolute
  16739. latest version, but introducing a formal policy is hard given the constraints of
  16740. the ecosystem.</p>
  16741. <p>On a similar note, SQLite does not generally have a concept of &quot;supported
  16742. release&quot;; bugfixes are published for the latest minor release only. We chose to
  16743. track Debian's oldstable as this is relatively conservative, predictably updated
  16744. and is consistent with the <code>.deb</code> packages released by Matrix.org.</p>
  16745. <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>
  16746. <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>
  16747. <ul>
  16748. <li><strong>Platform</strong>: 2x1GHz armhf 2GiB ram <a href="https://wiki.debian.org/CheapServerBoxHardware">Single-board computers</a>, SSD, postgres.</li>
  16749. </ul>
  16750. <h3 id="presence-1"><a class="header" href="#presence-1">Presence</a></h3>
  16751. <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>
  16752. <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>
  16753. <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>
  16754. <h3 id="joining"><a class="header" href="#joining">Joining</a></h3>
  16755. <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>
  16756. <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>
  16757. <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>
  16758. <h3 id="sessions"><a class="header" href="#sessions">Sessions</a></h3>
  16759. <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>
  16760. <h3 id="recommended-configuration"><a class="header" href="#recommended-configuration">Recommended configuration</a></h3>
  16761. <p>Put the below in a new file at /etc/matrix-synapse/conf.d/sbc.yaml to override the defaults in homeserver.yaml.</p>
  16762. <pre><code># Disable presence tracking, which is currently fairly resource intensive
  16763. # More info: https://github.com/matrix-org/synapse/issues/9478
  16764. use_presence: false
  16765. # Set a small complexity limit, preventing users from joining large rooms
  16766. # which may be resource-intensive to remain a part of.
  16767. #
  16768. # Note that this will not prevent users from joining smaller rooms that
  16769. # eventually become complex.
  16770. limit_remote_rooms:
  16771. enabled: true
  16772. complexity: 3.0
  16773. # Database configuration
  16774. database:
  16775. # Use postgres for the best performance
  16776. name: psycopg2
  16777. args:
  16778. user: matrix-synapse
  16779. # Generate a long, secure password using a password manager
  16780. password: hunter2
  16781. database: matrix-synapse
  16782. host: localhost
  16783. </code></pre>
  16784. <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>
  16785. <pre><code>admin@homeserver:~$ zgrep '/client/r0/join/' /var/log/matrix-synapse/homeserver.log* | awk '{print $18, $25}' | sort --human-numeric-sort
  16786. 29.922sec/-0.002sec /_matrix/client/r0/join/%23debian-fasttrack%3Apoddery.com
  16787. 182.088sec/0.003sec /_matrix/client/r0/join/%23decentralizedweb-general%3Amatrix.org
  16788. 911.625sec/-570.847sec /_matrix/client/r0/join/%23synapse%3Amatrix.org
  16789. 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'
  16790. canonical_alias | joined_members | current_state_events
  16791. -------------------------------+----------------+----------------------
  16792. #_oftc_#debian:matrix.org | 871 | 52355
  16793. #matrix:matrix.org | 6379 | 10684
  16794. #irc:matrix.org | 461 | 3751
  16795. #decentralizedweb-general:matrix.org | 997 | 1509
  16796. #whatsapp:maunium.net | 554 | 854
  16797. </code></pre>
  16798. </main>
  16799. <nav class="nav-wrapper" aria-label="Page navigation">
  16800. <!-- Mobile navigation buttons -->
  16801. <div style="clear: both"></div>
  16802. </nav>
  16803. </div>
  16804. </div>
  16805. <nav class="nav-wide-wrapper" aria-label="Page navigation">
  16806. </nav>
  16807. </div>
  16808. <script type="text/javascript">
  16809. window.playground_copyable = true;
  16810. </script>
  16811. <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
  16812. <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
  16813. <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
  16814. <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
  16815. <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
  16816. <script src="book.js" type="text/javascript" charset="utf-8"></script>
  16817. <!-- Custom JS scripts -->
  16818. <script type="text/javascript" src="docs/website_files/table-of-contents.js"></script>
  16819. <script type="text/javascript">
  16820. window.addEventListener('load', function() {
  16821. window.setTimeout(window.print, 100);
  16822. });
  16823. </script>
  16824. </body>
  16825. </html>