print.html 927 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374
  1. <!DOCTYPE HTML>
  2. <html lang="en" class="sidebar-visible no-js light">
  3. <head>
  4. <!-- Book generated using mdBook -->
  5. <meta charset="UTF-8">
  6. <title>Synapse</title>
  7. <meta name="robots" content="noindex" />
  8. <!-- Custom HTML head -->
  9. <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  10. <meta name="description" content="">
  11. <meta name="viewport" content="width=device-width, initial-scale=1">
  12. <meta name="theme-color" content="#ffffff" />
  13. <link rel="icon" href="favicon.svg">
  14. <link rel="shortcut icon" href="favicon.png">
  15. <link rel="stylesheet" href="css/variables.css">
  16. <link rel="stylesheet" href="css/general.css">
  17. <link rel="stylesheet" href="css/chrome.css">
  18. <link rel="stylesheet" href="css/print.css" media="print">
  19. <!-- Fonts -->
  20. <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
  21. <link rel="stylesheet" href="fonts/fonts.css">
  22. <!-- Highlight.js Stylesheets -->
  23. <link rel="stylesheet" href="highlight.css">
  24. <link rel="stylesheet" href="tomorrow-night.css">
  25. <link rel="stylesheet" href="ayu-highlight.css">
  26. <!-- Custom theme stylesheets -->
  27. <link rel="stylesheet" href="docs/website_files/table-of-contents.css">
  28. <link rel="stylesheet" href="docs/website_files/remove-nav-buttons.css">
  29. <link rel="stylesheet" href="docs/website_files/indent-section-headers.css">
  30. <link rel="stylesheet" href="docs/website_files/version-picker.css">
  31. </head>
  32. <body>
  33. <!-- Provide site root to javascript -->
  34. <script type="text/javascript">
  35. var path_to_root = "";
  36. var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
  37. </script>
  38. <!-- Work around some values being stored in localStorage wrapped in quotes -->
  39. <script type="text/javascript">
  40. try {
  41. var theme = localStorage.getItem('mdbook-theme');
  42. var sidebar = localStorage.getItem('mdbook-sidebar');
  43. if (theme.startsWith('"') && theme.endsWith('"')) {
  44. localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
  45. }
  46. if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
  47. localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
  48. }
  49. } catch (e) { }
  50. </script>
  51. <!-- Set the theme before any content is loaded, prevents flash -->
  52. <script type="text/javascript">
  53. var theme;
  54. try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
  55. if (theme === null || theme === undefined) { theme = default_theme; }
  56. var html = document.querySelector('html');
  57. html.classList.remove('no-js')
  58. html.classList.remove('light')
  59. html.classList.add(theme);
  60. html.classList.add('js');
  61. </script>
  62. <!-- Hide / unhide sidebar before it is displayed -->
  63. <script type="text/javascript">
  64. var html = document.querySelector('html');
  65. var sidebar = 'hidden';
  66. if (document.body.clientWidth >= 1080) {
  67. try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
  68. sidebar = sidebar || 'visible';
  69. }
  70. html.classList.remove('sidebar-visible');
  71. html.classList.add("sidebar-" + sidebar);
  72. </script>
  73. <nav id="sidebar" class="sidebar" aria-label="Table of contents">
  74. <div class="sidebar-scrollbox">
  75. <ol class="chapter"><li class="chapter-item expanded affix "><li class="part-title">Introduction</li><li class="chapter-item expanded "><a href="welcome_and_overview.html">Welcome and Overview</a></li><li class="chapter-item expanded affix "><li class="part-title">Setup</li><li class="chapter-item expanded "><a href="setup/installation.html">Installation</a></li><li class="chapter-item expanded "><a href="postgres.html">Using Postgres</a></li><li class="chapter-item expanded "><a href="reverse_proxy.html">Configuring a Reverse Proxy</a></li><li class="chapter-item expanded "><a href="setup/forward_proxy.html">Configuring a Forward/Outbound Proxy</a></li><li class="chapter-item expanded "><a href="turn-howto.html">Configuring a Turn Server</a></li><li 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="development/url_previews.html">URL Previews</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 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/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>
  76. </div>
  77. <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
  78. </nav>
  79. <div id="page-wrapper" class="page-wrapper">
  80. <div class="page">
  81. <div id="menu-bar-hover-placeholder"></div>
  82. <div id="menu-bar" class="menu-bar sticky bordered">
  83. <div class="left-buttons">
  84. <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
  85. <i class="fa fa-bars"></i>
  86. </button>
  87. <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
  88. <i class="fa fa-paint-brush"></i>
  89. </button>
  90. <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
  91. <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
  92. <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
  93. <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
  94. <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
  95. <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
  96. </ul>
  97. <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
  98. <i class="fa fa-search"></i>
  99. </button>
  100. <div class="version-picker">
  101. <div class="dropdown">
  102. <div class="select">
  103. <span></span>
  104. <i class="fa fa-chevron-down"></i>
  105. </div>
  106. <input type="hidden" name="version">
  107. <ul class="dropdown-menu">
  108. <!-- Versions will be added dynamically in version-picker.js -->
  109. </ul>
  110. </div>
  111. </div>
  112. </div>
  113. <h1 class="menu-title">Synapse</h1>
  114. <div class="right-buttons">
  115. <a href="print.html" title="Print this book" aria-label="Print this book">
  116. <i id="print-button" class="fa fa-print"></i>
  117. </a>
  118. <a href="https://github.com/matrix-org/synapse" title="Git repository" aria-label="Git repository">
  119. <i id="git-repository-button" class="fa fa-github"></i>
  120. </a>
  121. </div>
  122. </div>
  123. <div id="search-wrapper" class="hidden">
  124. <form id="searchbar-outer" class="searchbar-outer">
  125. <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
  126. </form>
  127. <div id="searchresults-outer" class="searchresults-outer hidden">
  128. <div id="searchresults-header" class="searchresults-header"></div>
  129. <ul id="searchresults">
  130. </ul>
  131. </div>
  132. </div>
  133. <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
  134. <script type="text/javascript">
  135. document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
  136. document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
  137. Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
  138. link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
  139. });
  140. </script>
  141. <div id="content" class="content">
  142. <main>
  143. <!-- Page table of contents -->
  144. <div class="sidetoc">
  145. <nav class="pagetoc"></nav>
  146. </div>
  147. <div style="break-before: page; page-break-before: always;"></div><h1 id="introduction"><a class="header" href="#introduction">Introduction</a></h1>
  148. <p>Welcome to the documentation repository for Synapse, a
  149. <a href="https://matrix.org">Matrix</a> homeserver implementation developed by the matrix.org core
  150. team.</p>
  151. <h2 id="installing-and-using-synapse"><a class="header" href="#installing-and-using-synapse">Installing and using Synapse</a></h2>
  152. <p>This documentation covers topics for <strong>installation</strong>, <strong>configuration</strong> and
  153. <strong>maintenance</strong> of your Synapse process:</p>
  154. <ul>
  155. <li>
  156. <p>Learn how to <a href="setup/installation.html">install</a> and
  157. <a href="usage/configuration/config_documentation.html">configure</a> your own instance, perhaps with <a href="usage/configuration/user_authentication/index.html">Single
  158. Sign-On</a>.</p>
  159. </li>
  160. <li>
  161. <p>See how to <a href="upgrade.html">upgrade</a> between Synapse versions.</p>
  162. </li>
  163. <li>
  164. <p>Administer your instance using the <a href="usage/administration/admin_api/index.html">Admin
  165. API</a>, installing <a href="modules/index.html">pluggable
  166. modules</a>, or by accessing the <a href="manhole.html">manhole</a>.</p>
  167. </li>
  168. <li>
  169. <p>Learn how to <a href="usage/administration/request_log.html">read log lines</a>, configure
  170. <a href="usage/configuration/logging_sample_config.html">logging</a> or set up <a href="structured_logging.html">structured
  171. logging</a>.</p>
  172. </li>
  173. <li>
  174. <p>Scale Synapse through additional <a href="workers.html">worker processes</a>.</p>
  175. </li>
  176. <li>
  177. <p>Set up <a href="metrics-howto.html">monitoring and metrics</a> to keep an eye on your
  178. Synapse instance's performance.</p>
  179. </li>
  180. </ul>
  181. <h2 id="developing-on-synapse"><a class="header" href="#developing-on-synapse">Developing on Synapse</a></h2>
  182. <p>Contributions are welcome! Synapse is primarily written in
  183. <a href="https://python.org">Python</a>. As a developer, you may be interested in the
  184. following documentation:</p>
  185. <ul>
  186. <li>
  187. <p>Read the <a href="development/contributing_guide.html">Contributing Guide</a>. It is meant
  188. to walk new contributors through the process of developing and submitting a
  189. change to the Synapse codebase (which is <a href="https://github.com/matrix-org/synapse">hosted on
  190. GitHub</a>).</p>
  191. </li>
  192. <li>
  193. <p>Set up your <a href="development/contributing_guide.html#2-what-do-i-need">development
  194. environment</a>, then learn
  195. how to <a href="development/contributing_guide.html#run-the-linters">lint</a> and
  196. <a href="development/contributing_guide.html#8-test-test-test">test</a> your code.</p>
  197. </li>
  198. <li>
  199. <p>Look at <a href="https://github.com/matrix-org/synapse/issues">the issue tracker</a> for
  200. bugs to fix or features to add. If you're new, it may be best to start with
  201. those labeled <a href="https://github.com/matrix-org/synapse/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22">good first
  202. issue</a>.</p>
  203. </li>
  204. <li>
  205. <p>Understand <a href="development/internal_documentation/index.html">how Synapse is
  206. built</a>, how to <a href="development/database_schema.html">migrate
  207. database schemas</a>, learn about
  208. <a href="federate.html">federation</a> and how to <a href="federate.html#running-a-demo-federation-of-synapses">set up a local
  209. federation</a> for development.</p>
  210. </li>
  211. <li>
  212. <p>We like to keep our <code>git</code> history clean. <a href="development/git.html">Learn</a> how to
  213. do so!</p>
  214. </li>
  215. <li>
  216. <p>And finally, contribute to this documentation! The source for which is
  217. <a href="https://github.com/matrix-org/synapse/tree/develop/docs">located here</a>.</p>
  218. </li>
  219. </ul>
  220. <h2 id="donating-to-synapse-development"><a class="header" href="#donating-to-synapse-development">Donating to Synapse development</a></h2>
  221. <p>Want to help keep Synapse going but don't know how to code? Synapse is a
  222. <a href="https://matrix.org">Matrix.org Foundation</a> project. Consider becoming a
  223. supporter on <a href="https://liberapay.com/matrixdotorg">Liberapay</a>,
  224. <a href="https://patreon.com/matrixdotorg">Patreon</a> or through
  225. <a href="https://paypal.me/matrixdotorg">PayPal</a> via a one-time donation.</p>
  226. <p>If you are an organisation or enterprise and would like to sponsor development,
  227. reach out to us over email at: support (at) matrix.org</p>
  228. <h2 id="reporting-a-security-vulnerability"><a class="header" href="#reporting-a-security-vulnerability">Reporting a security vulnerability</a></h2>
  229. <p>If you've found a security issue in Synapse or any other Matrix.org Foundation
  230. project, please report it to us in accordance with our <a href="https://www.matrix.org/security-disclosure-policy/">Security Disclosure
  231. Policy</a>. Thank you!</p>
  232. <div style="break-before: page; page-break-before: always;"></div><h1 id="installation-instructions"><a class="header" href="#installation-instructions">Installation Instructions</a></h1>
  233. <h2 id="choosing-your-server-name"><a class="header" href="#choosing-your-server-name">Choosing your server name</a></h2>
  234. <p>It is important to choose the name for your server before you install Synapse,
  235. because it cannot be changed later.</p>
  236. <p>The server name determines the &quot;domain&quot; part of user-ids for users on your
  237. server: these will all be of the format <code>@user:my.domain.name</code>. It also
  238. determines how other matrix servers will reach yours for federation.</p>
  239. <p>For a test configuration, set this to the hostname of your server. For a more
  240. production-ready setup, you will probably want to specify your domain
  241. (<code>example.com</code>) rather than a matrix-specific hostname here (in the same way
  242. that your email address is probably <code>user@example.com</code> rather than
  243. <code>user@email.example.com</code>) - but doing so may require more advanced setup: see
  244. <a href="setup/../federate.html">Setting up Federation</a>.</p>
  245. <h2 id="installing-synapse"><a class="header" href="#installing-synapse">Installing Synapse</a></h2>
  246. <h3 id="prebuilt-packages"><a class="header" href="#prebuilt-packages">Prebuilt packages</a></h3>
  247. <p>Prebuilt packages are available for a number of platforms. These are recommended
  248. for most users.</p>
  249. <h4 id="docker-images-and-ansible-playbooks"><a class="header" href="#docker-images-and-ansible-playbooks">Docker images and Ansible playbooks</a></h4>
  250. <p>There is an official synapse image available at
  251. <a href="https://hub.docker.com/r/matrixdotorg/synapse">https://hub.docker.com/r/matrixdotorg/synapse</a> which can be used with
  252. the docker-compose file available at
  253. <a href="https://github.com/matrix-org/synapse/tree/develop/contrib/docker">contrib/docker</a>.
  254. Further information on this including configuration options is available in the README
  255. on hub.docker.com.</p>
  256. <p>Alternatively, Andreas Peters (previously Silvio Fricke) has contributed a
  257. Dockerfile to automate a synapse server in a single Docker image, at
  258. <a href="https://hub.docker.com/r/avhost/docker-matrix/tags/">https://hub.docker.com/r/avhost/docker-matrix/tags/</a></p>
  259. <p>Slavi Pantaleev has created an Ansible playbook,
  260. which installs the offical Docker image of Matrix Synapse
  261. along with many other Matrix-related services (Postgres database, Element, coturn,
  262. ma1sd, SSL support, etc.).
  263. For more details, see
  264. <a href="https://github.com/spantaleev/matrix-docker-ansible-deploy">https://github.com/spantaleev/matrix-docker-ansible-deploy</a></p>
  265. <h4 id="debianubuntu"><a class="header" href="#debianubuntu">Debian/Ubuntu</a></h4>
  266. <h5 id="matrixorg-packages"><a class="header" href="#matrixorg-packages">Matrix.org packages</a></h5>
  267. <p>Matrix.org provides Debian/Ubuntu packages of Synapse, for the amd64
  268. architecture via <a href="https://packages.matrix.org/debian/">https://packages.matrix.org/debian/</a>.</p>
  269. <p>To install the latest release:</p>
  270. <pre><code class="language-sh">sudo apt install -y lsb-release wget apt-transport-https
  271. sudo wget -O /usr/share/keyrings/matrix-org-archive-keyring.gpg https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg
  272. echo &quot;deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main&quot; |
  273. sudo tee /etc/apt/sources.list.d/matrix-org.list
  274. sudo apt update
  275. sudo apt install matrix-synapse-py3
  276. </code></pre>
  277. <p>Packages are also published for release candidates. To enable the prerelease
  278. channel, add <code>prerelease</code> to the <code>sources.list</code> line. For example:</p>
  279. <pre><code class="language-sh">sudo wget -O /usr/share/keyrings/matrix-org-archive-keyring.gpg https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg
  280. echo &quot;deb [signed-by=/usr/share/keyrings/matrix-org-archive-keyring.gpg] https://packages.matrix.org/debian/ $(lsb_release -cs) main prerelease&quot; |
  281. sudo tee /etc/apt/sources.list.d/matrix-org.list
  282. sudo apt update
  283. sudo apt install matrix-synapse-py3
  284. </code></pre>
  285. <p>The fingerprint of the repository signing key (as shown by <code>gpg /usr/share/keyrings/matrix-org-archive-keyring.gpg</code>) is
  286. <code>AAF9AE843A7584B5A3E4CD2BCF45A512DE2DA058</code>.</p>
  287. <p>When installing with Debian packages, you might prefer to place files in
  288. <code>/etc/matrix-synapse/conf.d/</code> to override your configuration without editing
  289. the main configuration file at <code>/etc/matrix-synapse/homeserver.yaml</code>.
  290. By doing that, you won't be asked if you want to replace your configuration
  291. file when you upgrade the Debian package to a later version.</p>
  292. <h5 id="downstream-debian-packages"><a class="header" href="#downstream-debian-packages">Downstream Debian packages</a></h5>
  293. <p>Andrej Shadura maintains a <code>matrix-synapse</code> package in the Debian repositories.
  294. For <code>bookworm</code> and <code>sid</code>, it can be installed simply with:</p>
  295. <pre><code class="language-sh">sudo apt install matrix-synapse
  296. </code></pre>
  297. <p>Synapse is also avaliable in <code>bullseye-backports</code>. Please
  298. see the <a href="https://backports.debian.org/Instructions/">Debian documentation</a>
  299. for information on how to use backports.</p>
  300. <p><code>matrix-synapse</code> is no longer maintained for <code>buster</code> and older.</p>
  301. <h5 id="downstream-ubuntu-packages"><a class="header" href="#downstream-ubuntu-packages">Downstream Ubuntu packages</a></h5>
  302. <p>We do not recommend using the packages in the default Ubuntu repository
  303. at this time, as they are old and suffer from known security vulnerabilities.
  304. The latest version of Synapse can be installed from <a href="setup/installation.html#matrixorg-packages">our repository</a>.</p>
  305. <h4 id="fedora"><a class="header" href="#fedora">Fedora</a></h4>
  306. <p>Synapse is in the Fedora repositories as <code>matrix-synapse</code>:</p>
  307. <pre><code class="language-sh">sudo dnf install matrix-synapse
  308. </code></pre>
  309. <p>Oleg Girko provides Fedora RPMs at
  310. <a href="https://obs.infoserver.lv/project/monitor/matrix-synapse">https://obs.infoserver.lv/project/monitor/matrix-synapse</a></p>
  311. <h4 id="opensuse"><a class="header" href="#opensuse">OpenSUSE</a></h4>
  312. <p>Synapse is in the OpenSUSE repositories as <code>matrix-synapse</code>:</p>
  313. <pre><code class="language-sh">sudo zypper install matrix-synapse
  314. </code></pre>
  315. <h4 id="suse-linux-enterprise-server"><a class="header" href="#suse-linux-enterprise-server">SUSE Linux Enterprise Server</a></h4>
  316. <p>Unofficial package are built for SLES 15 in the openSUSE:Backports:SLE-15 repository at
  317. <a href="https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/">https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/</a></p>
  318. <h4 id="archlinux"><a class="header" href="#archlinux">ArchLinux</a></h4>
  319. <p>The quickest way to get up and running with ArchLinux is probably with the community package
  320. <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
  321. the necessary dependencies.</p>
  322. <p>pip may be outdated (6.0.7-1 and needs to be upgraded to 6.0.8-1 ):</p>
  323. <pre><code class="language-sh">sudo pip install --upgrade pip
  324. </code></pre>
  325. <p>If you encounter an error with lib bcrypt causing an Wrong ELF Class:
  326. ELFCLASS32 (x64 Systems), you may need to reinstall py-bcrypt to correctly
  327. compile it under the right architecture. (This should not be needed if
  328. installing under virtualenv):</p>
  329. <pre><code class="language-sh">sudo pip uninstall py-bcrypt
  330. sudo pip install py-bcrypt
  331. </code></pre>
  332. <h4 id="void-linux"><a class="header" href="#void-linux">Void Linux</a></h4>
  333. <p>Synapse can be found in the void repositories as 'synapse':</p>
  334. <pre><code class="language-sh">xbps-install -Su
  335. xbps-install -S synapse
  336. </code></pre>
  337. <h4 id="freebsd"><a class="header" href="#freebsd">FreeBSD</a></h4>
  338. <p>Synapse can be installed via FreeBSD Ports or Packages contributed by Brendan Molloy from:</p>
  339. <ul>
  340. <li>Ports: <code>cd /usr/ports/net-im/py-matrix-synapse &amp;&amp; make install clean</code></li>
  341. <li>Packages: <code>pkg install py38-matrix-synapse</code></li>
  342. </ul>
  343. <h4 id="openbsd"><a class="header" href="#openbsd">OpenBSD</a></h4>
  344. <p>As of OpenBSD 6.7 Synapse is available as a pre-compiled binary. The filesystem
  345. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  346. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  347. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  348. <p>Installing Synapse:</p>
  349. <pre><code class="language-sh">doas pkg_add synapse
  350. </code></pre>
  351. <h4 id="nixos"><a class="header" href="#nixos">NixOS</a></h4>
  352. <p>Robin Lambertz has packaged Synapse for NixOS at:
  353. <a href="https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/services/misc/matrix-synapse.nix">https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/services/misc/matrix-synapse.nix</a></p>
  354. <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>
  355. <p>It's also possible to install Synapse as a Python module from PyPI.</p>
  356. <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>
  357. <p>System requirements:</p>
  358. <ul>
  359. <li>POSIX-compliant system (tested on Linux &amp; OS X)</li>
  360. <li>Python 3.7 or later, up to Python 3.10.</li>
  361. <li>At least 1GB of free RAM if you want to join large public rooms like #matrix:matrix.org</li>
  362. </ul>
  363. <p>To install the Synapse homeserver run:</p>
  364. <pre><code class="language-sh">mkdir -p ~/synapse
  365. virtualenv -p python3 ~/synapse/env
  366. source ~/synapse/env/bin/activate
  367. pip install --upgrade pip
  368. pip install --upgrade setuptools
  369. pip install matrix-synapse
  370. </code></pre>
  371. <p>This will download Synapse from <a href="https://pypi.org/project/matrix-synapse">PyPI</a>
  372. and install it, along with the python libraries it uses, into a virtual environment
  373. under <code>~/synapse/env</code>. Feel free to pick a different directory if you
  374. prefer.</p>
  375. <p>This Synapse installation can then be later upgraded by using pip again with the
  376. update flag:</p>
  377. <pre><code class="language-sh">source ~/synapse/env/bin/activate
  378. pip install -U matrix-synapse
  379. </code></pre>
  380. <p>Before you can start Synapse, you will need to generate a configuration
  381. file. To do this, run (in your virtualenv, as before):</p>
  382. <pre><code class="language-sh">cd ~/synapse
  383. python -m synapse.app.homeserver \
  384. --server-name my.domain.name \
  385. --config-path homeserver.yaml \
  386. --generate-config \
  387. --report-stats=[yes|no]
  388. </code></pre>
  389. <p>... substituting an appropriate value for <code>--server-name</code>.</p>
  390. <p>This command will generate you a config file that you can then customise, but it will
  391. also generate a set of keys for you. These keys will allow your homeserver to
  392. identify itself to other homeserver, so don't lose or delete them. It would be
  393. wise to back them up somewhere safe. (If, for whatever reason, you do need to
  394. change your homeserver's keys, you may find that other homeserver have the
  395. old key cached. If you update the signing key, you should change the name of the
  396. key in the <code>&lt;server name&gt;.signing.key</code> file (the second word) to something
  397. 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>
  398. <p>To actually run your new homeserver, pick a working directory for Synapse to
  399. run (e.g. <code>~/synapse</code>), and:</p>
  400. <pre><code class="language-sh">cd ~/synapse
  401. source env/bin/activate
  402. synctl start
  403. </code></pre>
  404. <h4 id="platform-specific-prerequisites"><a class="header" href="#platform-specific-prerequisites">Platform-specific prerequisites</a></h4>
  405. <p>Synapse is written in Python but some of the libraries it uses are written in
  406. C. So before we can install Synapse itself we need a working C compiler and the
  407. header files for Python C extensions.</p>
  408. <h5 id="debianubunturaspbian"><a class="header" href="#debianubunturaspbian">Debian/Ubuntu/Raspbian</a></h5>
  409. <p>Installing prerequisites on Ubuntu or Debian:</p>
  410. <pre><code class="language-sh">sudo apt install build-essential python3-dev libffi-dev \
  411. python3-pip python3-setuptools sqlite3 \
  412. libssl-dev virtualenv libjpeg-dev libxslt1-dev
  413. </code></pre>
  414. <h5 id="archlinux-1"><a class="header" href="#archlinux-1">ArchLinux</a></h5>
  415. <p>Installing prerequisites on ArchLinux:</p>
  416. <pre><code class="language-sh">sudo pacman -S base-devel python python-pip \
  417. python-setuptools python-virtualenv sqlite3
  418. </code></pre>
  419. <h5 id="centosfedora"><a class="header" href="#centosfedora">CentOS/Fedora</a></h5>
  420. <p>Installing prerequisites on CentOS or Fedora Linux:</p>
  421. <pre><code class="language-sh">sudo dnf install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
  422. libwebp-devel libxml2-devel libxslt-devel libpq-devel \
  423. python3-virtualenv libffi-devel openssl-devel python3-devel
  424. sudo dnf groupinstall &quot;Development Tools&quot;
  425. </code></pre>
  426. <h5 id="macos"><a class="header" href="#macos">macOS</a></h5>
  427. <p>Installing prerequisites on macOS:</p>
  428. <p>You may need to install the latest Xcode developer tools:</p>
  429. <pre><code class="language-sh">xcode-select --install
  430. </code></pre>
  431. <p>On ARM-based Macs you may need to explicitly install libjpeg which is a pillow dependency. You can use Homebrew (https://brew.sh):</p>
  432. <pre><code class="language-sh"> brew install jpeg
  433. </code></pre>
  434. <p>On macOS Catalina (10.15) you may need to explicitly install OpenSSL
  435. via brew and inform <code>pip</code> about it so that <code>psycopg2</code> builds:</p>
  436. <pre><code class="language-sh">brew install openssl@1.1
  437. export LDFLAGS=&quot;-L/usr/local/opt/openssl/lib&quot;
  438. export CPPFLAGS=&quot;-I/usr/local/opt/openssl/include&quot;
  439. </code></pre>
  440. <h5 id="opensuse-1"><a class="header" href="#opensuse-1">OpenSUSE</a></h5>
  441. <p>Installing prerequisites on openSUSE:</p>
  442. <pre><code class="language-sh">sudo zypper in -t pattern devel_basis
  443. sudo zypper in python-pip python-setuptools sqlite3 python-virtualenv \
  444. python-devel libffi-devel libopenssl-devel libjpeg62-devel
  445. </code></pre>
  446. <h5 id="openbsd-1"><a class="header" href="#openbsd-1">OpenBSD</a></h5>
  447. <p>A port of Synapse is available under <code>net/synapse</code>. The filesystem
  448. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  449. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  450. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  451. <p>To be able to build Synapse's dependency on python the <code>WRKOBJDIR</code>
  452. (cf. <code>bsd.port.mk(5)</code>) for building python, too, needs to be on a filesystem
  453. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>).</p>
  454. <p>Creating a <code>WRKOBJDIR</code> for building python under <code>/usr/local</code> (which on a
  455. default OpenBSD installation is mounted with <code>wxallowed</code>):</p>
  456. <pre><code class="language-sh">doas mkdir /usr/local/pobj_wxallowed
  457. </code></pre>
  458. <p>Assuming <code>PORTS_PRIVSEP=Yes</code> (cf. <code>bsd.port.mk(5)</code>) and <code>SUDO=doas</code> are
  459. configured in <code>/etc/mk.conf</code>:</p>
  460. <pre><code class="language-sh">doas chown _pbuild:_pbuild /usr/local/pobj_wxallowed
  461. </code></pre>
  462. <p>Setting the <code>WRKOBJDIR</code> for building python:</p>
  463. <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
  464. </code></pre>
  465. <p>Building Synapse:</p>
  466. <pre><code class="language-sh">cd /usr/ports/net/synapse
  467. make install
  468. </code></pre>
  469. <h5 id="windows"><a class="header" href="#windows">Windows</a></h5>
  470. <p>Running Synapse natively on Windows is not officially supported.</p>
  471. <p>If you wish to run or develop Synapse on Windows, the Windows Subsystem for
  472. Linux provides a Linux environment which is capable of using the Debian, Fedora,
  473. or source installation methods. More information about WSL can be found at
  474. <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
  475. <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
  476. Windows Server.</p>
  477. <h2 id="setting-up-synapse"><a class="header" href="#setting-up-synapse">Setting up Synapse</a></h2>
  478. <p>Once you have installed synapse as above, you will need to configure it.</p>
  479. <h3 id="using-postgresql"><a class="header" href="#using-postgresql">Using PostgreSQL</a></h3>
  480. <p>By default Synapse uses an <a href="https://sqlite.org/">SQLite</a> database and in doing so trades
  481. performance for convenience. Almost all installations should opt to use <a href="https://www.postgresql.org">PostgreSQL</a>
  482. instead. Advantages include:</p>
  483. <ul>
  484. <li>significant performance improvements due to the superior threading and
  485. caching model, smarter query optimiser</li>
  486. <li>allowing the DB to be run on separate hardware</li>
  487. </ul>
  488. <p>For information on how to install and use PostgreSQL in Synapse, please see
  489. <a href="setup/../postgres.html">Using Postgres</a></p>
  490. <p>SQLite is only acceptable for testing purposes. SQLite should not be used in
  491. a production server. Synapse will perform poorly when using
  492. SQLite, especially when participating in large rooms.</p>
  493. <h3 id="tls-certificates"><a class="header" href="#tls-certificates">TLS certificates</a></h3>
  494. <p>The default configuration exposes a single HTTP port on the local
  495. interface: <code>http://localhost:8008</code>. It is suitable for local testing,
  496. but for any practical use, you will need Synapse's APIs to be served
  497. over HTTPS.</p>
  498. <p>The recommended way to do so is to set up a reverse proxy on port
  499. <code>8448</code>. You can find documentation on doing so in
  500. <a href="setup/../reverse_proxy.html">the reverse proxy documentation</a>.</p>
  501. <p>Alternatively, you can configure Synapse to expose an HTTPS port. To do
  502. so, you will need to edit <code>homeserver.yaml</code>, as follows:</p>
  503. <ul>
  504. <li>First, under the <code>listeners</code> section, uncomment the configuration for the
  505. TLS-enabled listener. (Remove the hash sign (<code>#</code>) at the start of
  506. each line). The relevant lines are like this:</li>
  507. </ul>
  508. <pre><code class="language-yaml"> - port: 8448
  509. type: http
  510. tls: true
  511. resources:
  512. - names: [client, federation]
  513. </code></pre>
  514. <ul>
  515. <li>
  516. <p>You will also need to uncomment the <code>tls_certificate_path</code> and
  517. <code>tls_private_key_path</code> lines under the <code>TLS</code> section. You will need to manage
  518. provisioning of these certificates yourself.</p>
  519. <p>If you are using your own certificate, be sure to use a <code>.pem</code> file that
  520. includes the full certificate chain including any intermediate certificates
  521. (for instance, if using certbot, use <code>fullchain.pem</code> as your certificate, not
  522. <code>cert.pem</code>).</p>
  523. </li>
  524. </ul>
  525. <p>For a more detailed guide to configuring your server for federation, see
  526. <a href="setup/../federate.html">Federation</a>.</p>
  527. <h3 id="client-well-known-uri"><a class="header" href="#client-well-known-uri">Client Well-Known URI</a></h3>
  528. <p>Setting up the client Well-Known URI is optional but if you set it up, it will
  529. allow users to enter their full username (e.g. <code>@user:&lt;server_name&gt;</code>) into clients
  530. which support well-known lookup to automatically configure the homeserver and
  531. identity server URLs. This is useful so that users don't have to memorize or think
  532. about the actual homeserver URL you are using.</p>
  533. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/client</code> should return JSON in
  534. the following format.</p>
  535. <pre><code class="language-json">{
  536. &quot;m.homeserver&quot;: {
  537. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  538. }
  539. }
  540. </code></pre>
  541. <p>It can optionally contain identity server information as well.</p>
  542. <pre><code class="language-json">{
  543. &quot;m.homeserver&quot;: {
  544. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  545. },
  546. &quot;m.identity_server&quot;: {
  547. &quot;base_url&quot;: &quot;https://&lt;identity.example.com&gt;&quot;
  548. }
  549. }
  550. </code></pre>
  551. <p>To work in browser based clients, the file must be served with the appropriate
  552. Cross-Origin Resource Sharing (CORS) headers. A recommended value would be
  553. <code>Access-Control-Allow-Origin: *</code> which would allow all browser based clients to
  554. view it.</p>
  555. <p>In nginx this would be something like:</p>
  556. <pre><code class="language-nginx">location /.well-known/matrix/client {
  557. return 200 '{&quot;m.homeserver&quot;: {&quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;}}';
  558. default_type application/json;
  559. add_header Access-Control-Allow-Origin *;
  560. }
  561. </code></pre>
  562. <p>You should also ensure the <code>public_baseurl</code> option in <code>homeserver.yaml</code> is set
  563. correctly. <code>public_baseurl</code> should be set to the URL that clients will use to
  564. connect to your server. This is the same URL you put for the <code>m.homeserver</code>
  565. <code>base_url</code> above.</p>
  566. <pre><code class="language-yaml">public_baseurl: &quot;https://&lt;matrix.example.com&gt;&quot;
  567. </code></pre>
  568. <h3 id="email"><a class="header" href="#email">Email</a></h3>
  569. <p>It is desirable for Synapse to have the capability to send email. This allows
  570. Synapse to send password reset emails, send verifications when an email address
  571. is added to a user's account, and send email notifications to users when they
  572. receive new messages.</p>
  573. <p>To configure an SMTP server for Synapse, modify the configuration section
  574. headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>, <code>smtp_port</code>
  575. and <code>notif_from</code> fields filled out. You may also need to set <code>smtp_user</code>,
  576. <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  577. <p>If email is not configured, password reset, registration and notifications via
  578. email will be disabled.</p>
  579. <h3 id="registering-a-user"><a class="header" href="#registering-a-user">Registering a user</a></h3>
  580. <p>The easiest way to create a new user is to do so from a client like <a href="https://element.io/">Element</a>.</p>
  581. <p>Alternatively, you can do so from the command line. This can be done as follows:</p>
  582. <ol>
  583. <li>If synapse was installed via pip, activate the virtualenv as follows (if Synapse was
  584. installed via a prebuilt package, <code>register_new_matrix_user</code> should already be
  585. on the search path):
  586. <pre><code class="language-sh">cd ~/synapse
  587. source env/bin/activate
  588. synctl start # if not already running
  589. </code></pre>
  590. </li>
  591. <li>Run the following command:
  592. <pre><code class="language-sh">register_new_matrix_user -c homeserver.yaml http://localhost:8008
  593. </code></pre>
  594. </li>
  595. </ol>
  596. <p>This will prompt you to add details for the new user, and will then connect to
  597. the running Synapse to create the new user. For example:</p>
  598. <pre><code>New user localpart: erikj
  599. Password:
  600. Confirm password:
  601. Make admin [no]:
  602. Success!
  603. </code></pre>
  604. <p>This process uses a setting <code>registration_shared_secret</code> in
  605. <code>homeserver.yaml</code>, which is shared between Synapse itself and the
  606. <code>register_new_matrix_user</code> script. It doesn't matter what it is (a random
  607. value is generated by <code>--generate-config</code>), but it should be kept secret, as
  608. anyone with knowledge of it can register users, including admin accounts,
  609. on your server even if <code>enable_registration</code> is <code>false</code>.</p>
  610. <h3 id="setting-up-a-turn-server"><a class="header" href="#setting-up-a-turn-server">Setting up a TURN server</a></h3>
  611. <p>For reliable VoIP calls to be routed via this homeserver, you MUST configure
  612. a TURN server. See <a href="setup/../turn-howto.html">TURN setup</a> for details.</p>
  613. <h3 id="url-previews"><a class="header" href="#url-previews">URL previews</a></h3>
  614. <p>Synapse includes support for previewing URLs, which is disabled by default. To
  615. turn it on you must enable the <code>url_preview_enabled: True</code> config parameter
  616. and explicitly specify the IP ranges that Synapse is not allowed to spider for
  617. previewing in the <code>url_preview_ip_range_blacklist</code> configuration parameter.
  618. This is critical from a security perspective to stop arbitrary Matrix users
  619. spidering 'internal' URLs on your network. At the very least we recommend that
  620. your loopback and RFC1918 IP addresses are blacklisted.</p>
  621. <p>This also requires the optional <code>lxml</code> python dependency to be installed. This
  622. in turn requires the <code>libxml2</code> library to be available - on Debian/Ubuntu this
  623. means <code>apt-get install libxml2-dev</code>, or equivalent for your OS.</p>
  624. <h3 id="troubleshooting-installation"><a class="header" href="#troubleshooting-installation">Troubleshooting Installation</a></h3>
  625. <p><code>pip</code> seems to leak <em>lots</em> of memory during installation. For instance, a Linux
  626. host with 512MB of RAM may run out of memory whilst installing Twisted. If this
  627. happens, you will have to individually install the dependencies which are
  628. failing, e.g.:</p>
  629. <pre><code class="language-sh">pip install twisted
  630. </code></pre>
  631. <p>If you have any other problems, feel free to ask in
  632. <a href="https://matrix.to/#/#synapse:matrix.org">#synapse:matrix.org</a>.</p>
  633. <div style="break-before: page; page-break-before: always;"></div><h1 id="using-postgres"><a class="header" href="#using-postgres">Using Postgres</a></h1>
  634. <p>Synapse supports PostgreSQL versions 10 or later.</p>
  635. <h2 id="install-postgres-client-libraries"><a class="header" href="#install-postgres-client-libraries">Install postgres client libraries</a></h2>
  636. <p>Synapse will require the python postgres client library in order to
  637. connect to a postgres database.</p>
  638. <ul>
  639. <li>
  640. <p>If you are using the <a href="setup/installation.html#matrixorg-packages">matrix.org debian/ubuntu
  641. packages</a>, the necessary python
  642. library will already be installed, but you will need to ensure the
  643. low-level postgres library is installed, which you can do with
  644. <code>apt install libpq5</code>.</p>
  645. </li>
  646. <li>
  647. <p>For other pre-built packages, please consult the documentation from
  648. the relevant package.</p>
  649. </li>
  650. <li>
  651. <p>If you installed synapse <a href="setup/installation.html#installing-from-source">in a
  652. virtualenv</a>, you can install
  653. the library with:</p>
  654. <pre><code>~/synapse/env/bin/pip install &quot;matrix-synapse[postgres]&quot;
  655. </code></pre>
  656. <p>(substituting the path to your virtualenv for <code>~/synapse/env</code>, if
  657. you used a different path). You will require the postgres
  658. development files. These are in the <code>libpq-dev</code> package on
  659. Debian-derived distributions.</p>
  660. </li>
  661. </ul>
  662. <h2 id="set-up-database"><a class="header" href="#set-up-database">Set up database</a></h2>
  663. <p>Assuming your PostgreSQL database user is called <code>postgres</code>, first authenticate as the database user with:</p>
  664. <pre><code class="language-sh">su - postgres
  665. # Or, if your system uses sudo to get administrative rights
  666. sudo -u postgres bash
  667. </code></pre>
  668. <p>Then, create a postgres user and a database with:</p>
  669. <pre><code class="language-sh"># this will prompt for a password for the new user
  670. createuser --pwprompt synapse_user
  671. createdb --encoding=UTF8 --locale=C --template=template0 --owner=synapse_user synapse
  672. </code></pre>
  673. <p>The above will create a user called <code>synapse_user</code>, and a database called
  674. <code>synapse</code>.</p>
  675. <p>Note that the PostgreSQL database <em>must</em> have the correct encoding set
  676. (as shown above), otherwise it will not be able to store UTF8 strings.</p>
  677. <p>You may need to enable password authentication so <code>synapse_user</code> can
  678. connect to the database. See
  679. <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>
  680. <h2 id="synapse-config"><a class="header" href="#synapse-config">Synapse config</a></h2>
  681. <p>When you are ready to start using PostgreSQL, edit the <code>database</code>
  682. section in your config file to match the following lines:</p>
  683. <pre><code class="language-yaml">database:
  684. name: psycopg2
  685. args:
  686. user: &lt;user&gt;
  687. password: &lt;pass&gt;
  688. database: &lt;db&gt;
  689. host: &lt;host&gt;
  690. cp_min: 5
  691. cp_max: 10
  692. </code></pre>
  693. <p>All key, values in <code>args</code> are passed to the <code>psycopg2.connect(..)</code>
  694. function, except keys beginning with <code>cp_</code>, which are consumed by the
  695. twisted adbapi connection pool. See the <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">libpq
  696. documentation</a>
  697. for a list of options which can be passed.</p>
  698. <p>You should consider tuning the <code>args.keepalives_*</code> options if there is any danger of
  699. the connection between your homeserver and database dropping, otherwise Synapse
  700. may block for an extended period while it waits for a response from the
  701. database server. Example values might be:</p>
  702. <pre><code class="language-yaml">database:
  703. args:
  704. # ... as above
  705. # seconds of inactivity after which TCP should send a keepalive message to the server
  706. keepalives_idle: 10
  707. # the number of seconds after which a TCP keepalive message that is not
  708. # acknowledged by the server should be retransmitted
  709. keepalives_interval: 10
  710. # the number of TCP keepalives that can be lost before the client's connection
  711. # to the server is considered dead
  712. keepalives_count: 3
  713. </code></pre>
  714. <h2 id="tuning-postgres"><a class="header" href="#tuning-postgres">Tuning Postgres</a></h2>
  715. <p>The default settings should be fine for most deployments. For larger
  716. scale deployments tuning some of the settings is recommended, details of
  717. which can be found at
  718. <a href="https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server">https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server</a>.</p>
  719. <p>In particular, we've found tuning the following values helpful for
  720. performance:</p>
  721. <ul>
  722. <li><code>shared_buffers</code></li>
  723. <li><code>effective_cache_size</code></li>
  724. <li><code>work_mem</code></li>
  725. <li><code>maintenance_work_mem</code></li>
  726. <li><code>autovacuum_work_mem</code></li>
  727. </ul>
  728. <p>Note that the appropriate values for those fields depend on the amount
  729. of free memory the database host has available.</p>
  730. <p>Additionally, admins of large deployments might want to consider using huge pages
  731. to help manage memory, especially when using large values of <code>shared_buffers</code>. You
  732. can read more about that <a href="https://www.postgresql.org/docs/10/kernel-resources.html#LINUX-HUGE-PAGES">here</a>.</p>
  733. <h2 id="porting-from-sqlite"><a class="header" href="#porting-from-sqlite">Porting from SQLite</a></h2>
  734. <h3 id="overview"><a class="header" href="#overview">Overview</a></h3>
  735. <p>The script <code>synapse_port_db</code> allows porting an existing synapse server
  736. backed by SQLite to using PostgreSQL. This is done in as a two phase
  737. process:</p>
  738. <ol>
  739. <li>Copy the existing SQLite database to a separate location and run
  740. the port script against that offline database.</li>
  741. <li>Shut down the server. Rerun the port script to port any data that
  742. has come in since taking the first snapshot. Restart server against
  743. the PostgreSQL database.</li>
  744. </ol>
  745. <p>The port script is designed to be run repeatedly against newer snapshots
  746. of the SQLite database file. This makes it safe to repeat step 1 if
  747. there was a delay between taking the previous snapshot and being ready
  748. to do step 2.</p>
  749. <p>It is safe to at any time kill the port script and restart it.</p>
  750. <p>Note that the database may take up significantly more (25% - 100% more)
  751. space on disk after porting to Postgres.</p>
  752. <h3 id="using-the-port-script"><a class="header" href="#using-the-port-script">Using the port script</a></h3>
  753. <p>Firstly, shut down the currently running synapse server and copy its
  754. database file (typically <code>homeserver.db</code>) to another location. Once the
  755. copy is complete, restart synapse. For instance:</p>
  756. <pre><code class="language-sh">synctl stop
  757. cp homeserver.db homeserver.db.snapshot
  758. synctl start
  759. </code></pre>
  760. <p>Copy the old config file into a new config file:</p>
  761. <pre><code class="language-sh">cp homeserver.yaml homeserver-postgres.yaml
  762. </code></pre>
  763. <p>Edit the database section as described in the section <em>Synapse config</em>
  764. above and with the SQLite snapshot located at <code>homeserver.db.snapshot</code>
  765. simply run:</p>
  766. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db.snapshot \
  767. --postgres-config homeserver-postgres.yaml
  768. </code></pre>
  769. <p>The flag <code>--curses</code> displays a coloured curses progress UI.</p>
  770. <p>If the script took a long time to complete, or time has otherwise passed
  771. since the original snapshot was taken, repeat the previous steps with a
  772. newer snapshot.</p>
  773. <p>To complete the conversion shut down the synapse server and run the port
  774. script one last time, e.g. if the SQLite database is at <code>homeserver.db</code>
  775. run:</p>
  776. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db \
  777. --postgres-config homeserver-postgres.yaml
  778. </code></pre>
  779. <p>Once that has completed, change the synapse config to point at the
  780. PostgreSQL database configuration file <code>homeserver-postgres.yaml</code>:</p>
  781. <pre><code class="language-sh">synctl stop
  782. mv homeserver.yaml homeserver-old-sqlite.yaml
  783. mv homeserver-postgres.yaml homeserver.yaml
  784. synctl start
  785. </code></pre>
  786. <p>Synapse should now be running against PostgreSQL.</p>
  787. <h2 id="troubleshooting"><a class="header" href="#troubleshooting">Troubleshooting</a></h2>
  788. <h3 id="alternative-auth-methods"><a class="header" href="#alternative-auth-methods">Alternative auth methods</a></h3>
  789. <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
  790. <code>ident</code>:</p>
  791. <ul>
  792. <li>
  793. <p>If the <code>synapse_user</code> user has a password, add the password to the <code>database:</code>
  794. section of <code>homeserver.yaml</code>. Then add the following to <code>pg_hba.conf</code>:</p>
  795. <pre><code>host synapse synapse_user ::1/128 md5 # or `scram-sha-256` instead of `md5` if you use that
  796. </code></pre>
  797. </li>
  798. <li>
  799. <p>If the <code>synapse_user</code> user does not have a password, then a password doesn't
  800. have to be added to <code>homeserver.yaml</code>. But the following does need to be added
  801. to <code>pg_hba.conf</code>:</p>
  802. <pre><code>host synapse synapse_user ::1/128 trust
  803. </code></pre>
  804. </li>
  805. </ul>
  806. <p>Note that line order matters in <code>pg_hba.conf</code>, so make sure that if you do add a
  807. new line, it is inserted before:</p>
  808. <pre><code>host all all ::1/128 ident
  809. </code></pre>
  810. <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>
  811. <p>Synapse will refuse to set up a new database if it has the wrong values of
  812. <code>COLLATE</code> and <code>CTYPE</code> set. Synapse will also refuse to start an existing database with incorrect values
  813. of <code>COLLATE</code> and <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the
  814. <code>database</code> section of the config, is set to true. Using different locales can cause issues if the locale library is updated from
  815. underneath the database, or if a different version of the locale is used on any
  816. replicas.</p>
  817. <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
  818. the correct locale parameter (as shown above). It is also possible to change the
  819. parameters on a live database and run a <code>REINDEX</code> on the entire database,
  820. however extreme care must be taken to avoid database corruption.</p>
  821. <p>Note that the above may fail with an error about duplicate rows if corruption
  822. has already occurred, and such duplicate rows will need to be manually removed.</p>
  823. <h3 id="fixing-inconsistent-sequences-error"><a class="header" href="#fixing-inconsistent-sequences-error">Fixing inconsistent sequences error</a></h3>
  824. <p>Synapse uses Postgres sequences to generate IDs for various tables. A sequence
  825. and associated table can get out of sync if, for example, Synapse has been
  826. downgraded and then upgraded again.</p>
  827. <p>To fix the issue shut down Synapse (including any and all workers) and run the
  828. SQL command included in the error message. Once done Synapse should start
  829. successfully.</p>
  830. <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>
  831. <p>It is recommended to put a reverse proxy such as
  832. <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">nginx</a>,
  833. <a href="https://httpd.apache.org/docs/current/mod/mod_proxy_http.html">Apache</a>,
  834. <a href="https://caddyserver.com/docs/quick-starts/reverse-proxy">Caddy</a>,
  835. <a href="https://www.haproxy.org/">HAProxy</a> or
  836. <a href="https://man.openbsd.org/relayd.8">relayd</a> in front of Synapse. One advantage
  837. of doing so is that it means that you can expose the default https port
  838. (443) to Matrix clients without needing to run Synapse with root
  839. privileges.</p>
  840. <p>You should configure your reverse proxy to forward requests to <code>/_matrix</code> or
  841. <code>/_synapse/client</code> to Synapse, and have it set the <code>X-Forwarded-For</code> and
  842. <code>X-Forwarded-Proto</code> request headers.</p>
  843. <p>You should remember that Matrix clients and other Matrix servers do not
  844. necessarily need to connect to your server via the same server name or
  845. port. Indeed, clients will use port 443 by default, whereas servers default to
  846. port 8448. Where these are different, we refer to the 'client port' and the
  847. 'federation port'. See <a href="https://matrix.org/docs/spec/server_server/latest#resolving-server-names">the Matrix
  848. specification</a>
  849. for more details of the algorithm used for federation connections, and
  850. <a href="delegate.html">Delegation</a> for instructions on setting up delegation.</p>
  851. <p><strong>NOTE</strong>: Your reverse proxy must not <code>canonicalise</code> or <code>normalise</code>
  852. the requested URI in any way (for example, by decoding <code>%xx</code> escapes).
  853. Beware that Apache <em>will</em> canonicalise URIs unless you specify
  854. <code>nocanon</code>.</p>
  855. <p>Let's assume that we expect clients to connect to our server at
  856. <code>https://matrix.example.com</code>, and other servers to connect at
  857. <code>https://example.com:8448</code>. The following sections detail the configuration of
  858. the reverse proxy and the homeserver.</p>
  859. <h2 id="homeserver-configuration"><a class="header" href="#homeserver-configuration">Homeserver Configuration</a></h2>
  860. <p>The HTTP configuration will need to be updated for Synapse to correctly record
  861. client IP addresses and generate redirect URLs while behind a reverse proxy. </p>
  862. <p>In <code>homeserver.yaml</code> set <code>x_forwarded: true</code> in the port 8008 section and
  863. consider setting <code>bind_addresses: ['127.0.0.1']</code> so that the server only
  864. listens to traffic on localhost. (Do not change <code>bind_addresses</code> to <code>127.0.0.1</code>
  865. when using a containerized Synapse, as that will prevent it from responding
  866. to proxied traffic.)</p>
  867. <h2 id="reverse-proxy-configuration-examples"><a class="header" href="#reverse-proxy-configuration-examples">Reverse-proxy configuration examples</a></h2>
  868. <p><strong>NOTE</strong>: You only need one of these.</p>
  869. <h3 id="nginx"><a class="header" href="#nginx">nginx</a></h3>
  870. <pre><code class="language-nginx">server {
  871. listen 443 ssl http2;
  872. listen [::]:443 ssl http2;
  873. # For the federation port
  874. listen 8448 ssl http2 default_server;
  875. listen [::]:8448 ssl http2 default_server;
  876. server_name matrix.example.com;
  877. location ~ ^(/_matrix|/_synapse/client) {
  878. # note: do not add a path (even a single /) after the port in `proxy_pass`,
  879. # otherwise nginx will canonicalise the URI and cause signature verification
  880. # errors.
  881. proxy_pass http://localhost:8008;
  882. proxy_set_header X-Forwarded-For $remote_addr;
  883. proxy_set_header X-Forwarded-Proto $scheme;
  884. proxy_set_header Host $host;
  885. # Nginx by default only allows file uploads up to 1M in size
  886. # Increase client_max_body_size to match max_upload_size defined in homeserver.yaml
  887. client_max_body_size 50M;
  888. }
  889. }
  890. </code></pre>
  891. <h3 id="caddy-v1"><a class="header" href="#caddy-v1">Caddy v1</a></h3>
  892. <pre><code>matrix.example.com {
  893. proxy /_matrix http://localhost:8008 {
  894. transparent
  895. }
  896. proxy /_synapse/client http://localhost:8008 {
  897. transparent
  898. }
  899. }
  900. example.com:8448 {
  901. proxy / http://localhost:8008 {
  902. transparent
  903. }
  904. }
  905. </code></pre>
  906. <h3 id="caddy-v2"><a class="header" href="#caddy-v2">Caddy v2</a></h3>
  907. <pre><code>matrix.example.com {
  908. reverse_proxy /_matrix/* http://localhost:8008
  909. reverse_proxy /_synapse/client/* http://localhost:8008
  910. }
  911. example.com:8448 {
  912. reverse_proxy http://localhost:8008
  913. }
  914. </code></pre>
  915. <p><a href="delegate.html">Delegation</a> example:</p>
  916. <pre><code>(matrix-well-known-header) {
  917. # Headers
  918. header Access-Control-Allow-Origin &quot;*&quot;
  919. header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  920. header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  921. header Content-Type &quot;application/json&quot;
  922. }
  923. example.com {
  924. handle /.well-known/matrix/server {
  925. import matrix-well-known-header
  926. respond `{&quot;m.server&quot;:&quot;matrix.example.com:443&quot;}`
  927. }
  928. handle /.well-known/matrix/client {
  929. import matrix-well-known-header
  930. respond `{&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;}}`
  931. }
  932. }
  933. matrix.example.com {
  934. reverse_proxy /_matrix/* http://localhost:8008
  935. reverse_proxy /_synapse/client/* http://localhost:8008
  936. }
  937. </code></pre>
  938. <h3 id="apache"><a class="header" href="#apache">Apache</a></h3>
  939. <pre><code class="language-apache">&lt;VirtualHost *:443&gt;
  940. SSLEngine on
  941. ServerName matrix.example.com
  942. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  943. AllowEncodedSlashes NoDecode
  944. ProxyPreserveHost on
  945. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  946. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  947. ProxyPass /_synapse/client http://127.0.0.1:8008/_synapse/client nocanon
  948. ProxyPassReverse /_synapse/client http://127.0.0.1:8008/_synapse/client
  949. &lt;/VirtualHost&gt;
  950. &lt;VirtualHost *:8448&gt;
  951. SSLEngine on
  952. ServerName example.com
  953. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  954. AllowEncodedSlashes NoDecode
  955. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  956. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  957. &lt;/VirtualHost&gt;
  958. </code></pre>
  959. <p><strong>NOTE</strong>: ensure the <code>nocanon</code> options are included.</p>
  960. <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>
  961. <pre><code class="language-apache">&lt;IfModule security2_module&gt;
  962. SecRuleEngine off
  963. &lt;/IfModule&gt;
  964. </code></pre>
  965. <p><strong>NOTE 3</strong>: Missing <code>ProxyPreserveHost on</code> can lead to a redirect loop.</p>
  966. <h3 id="haproxy"><a class="header" href="#haproxy">HAProxy</a></h3>
  967. <pre><code>frontend https
  968. bind *:443,[::]:443 ssl crt /etc/ssl/haproxy/ strict-sni alpn h2,http/1.1
  969. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  970. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  971. http-request set-header X-Forwarded-For %[src]
  972. # Matrix client traffic
  973. acl matrix-host hdr(host) -i matrix.example.com matrix.example.com:443
  974. acl matrix-path path_beg /_matrix
  975. acl matrix-path path_beg /_synapse/client
  976. use_backend matrix if matrix-host matrix-path
  977. frontend matrix-federation
  978. bind *:8448,[::]:8448 ssl crt /etc/ssl/haproxy/synapse.pem alpn h2,http/1.1
  979. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  980. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  981. http-request set-header X-Forwarded-For %[src]
  982. default_backend matrix
  983. backend matrix
  984. server matrix 127.0.0.1:8008
  985. </code></pre>
  986. <p><a href="delegate.html">Delegation</a> example:</p>
  987. <pre><code>frontend https
  988. acl matrix-well-known-client-path path /.well-known/matrix/client
  989. acl matrix-well-known-server-path path /.well-known/matrix/server
  990. use_backend matrix-well-known-client if matrix-well-known-client-path
  991. use_backend matrix-well-known-server if matrix-well-known-server-path
  992. backend matrix-well-known-client
  993. http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  994. http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  995. http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  996. 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;}}'
  997. backend matrix-well-known-server
  998. http-after-response set-header Access-Control-Allow-Origin &quot;*&quot;
  999. http-after-response set-header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  1000. http-after-response set-header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  1001. http-request return status 200 content-type application/json string '{&quot;m.server&quot;:&quot;matrix.example.com:443&quot;}'
  1002. </code></pre>
  1003. <h3 id="relayd"><a class="header" href="#relayd">Relayd</a></h3>
  1004. <pre><code>table &lt;webserver&gt; { 127.0.0.1 }
  1005. table &lt;matrixserver&gt; { 127.0.0.1 }
  1006. http protocol &quot;https&quot; {
  1007. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  1008. tls keypair &quot;example.com&quot;
  1009. match header set &quot;X-Forwarded-For&quot; value &quot;$REMOTE_ADDR&quot;
  1010. match header set &quot;X-Forwarded-Proto&quot; value &quot;https&quot;
  1011. # set CORS header for .well-known/matrix/server, .well-known/matrix/client
  1012. # httpd does not support setting headers, so do it here
  1013. match request path &quot;/.well-known/matrix/*&quot; tag &quot;matrix-cors&quot;
  1014. match response tagged &quot;matrix-cors&quot; header set &quot;Access-Control-Allow-Origin&quot; value &quot;*&quot;
  1015. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1016. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1017. # pass on non-matrix traffic to webserver
  1018. pass forward to &lt;webserver&gt;
  1019. }
  1020. relay &quot;https_traffic&quot; {
  1021. listen on egress port 443 tls
  1022. protocol &quot;https&quot;
  1023. forward to &lt;matrixserver&gt; port 8008 check tcp
  1024. forward to &lt;webserver&gt; port 8080 check tcp
  1025. }
  1026. http protocol &quot;matrix&quot; {
  1027. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  1028. tls keypair &quot;example.com&quot;
  1029. block
  1030. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1031. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1032. }
  1033. relay &quot;matrix_federation&quot; {
  1034. listen on egress port 8448 tls
  1035. protocol &quot;matrix&quot;
  1036. forward to &lt;matrixserver&gt; port 8008 check tcp
  1037. }
  1038. </code></pre>
  1039. <h2 id="health-check-endpoint"><a class="header" href="#health-check-endpoint">Health check endpoint</a></h2>
  1040. <p>Synapse exposes a health check endpoint for use by reverse proxies.
  1041. Each configured HTTP listener has a <code>/health</code> endpoint which always returns
  1042. 200 OK (and doesn't get logged).</p>
  1043. <h2 id="synapse-administration-endpoints"><a class="header" href="#synapse-administration-endpoints">Synapse administration endpoints</a></h2>
  1044. <p>Endpoints for administering your Synapse instance are placed under
  1045. <code>/_synapse/admin</code>. These require authentication through an access token of an
  1046. admin user. However as access to these endpoints grants the caller a lot of power,
  1047. we do not recommend exposing them to the public internet without good reason.</p>
  1048. <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>
  1049. <p>You can use Synapse with a forward or outbound proxy. An example of when
  1050. this is necessary is in corporate environments behind a DMZ (demilitarized zone).
  1051. Synapse supports routing outbound HTTP(S) requests via a proxy. Only HTTP(S)
  1052. proxy is supported, not SOCKS proxy or anything else.</p>
  1053. <h2 id="configure"><a class="header" href="#configure">Configure</a></h2>
  1054. <p>The <code>http_proxy</code>, <code>https_proxy</code>, <code>no_proxy</code> environment variables are used to
  1055. specify proxy settings. The environment variable is not case sensitive.</p>
  1056. <ul>
  1057. <li><code>http_proxy</code>: Proxy server to use for HTTP requests.</li>
  1058. <li><code>https_proxy</code>: Proxy server to use for HTTPS requests.</li>
  1059. <li><code>no_proxy</code>: Comma-separated list of hosts, IP addresses, or IP ranges in CIDR
  1060. format which should not use the proxy. Synapse will directly connect to these hosts.</li>
  1061. </ul>
  1062. <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>
  1063. <ul>
  1064. <li>
  1065. <p>Supported schemes are <code>http://</code> and <code>https://</code>. The default scheme is <code>http://</code>
  1066. for compatibility reasons; it is recommended to set a scheme. If scheme is set
  1067. to <code>https://</code> the connection uses TLS between Synapse and the proxy.</p>
  1068. <p><strong>NOTE</strong>: Synapse validates the certificates. If the certificate is not
  1069. valid, then the connection is dropped.</p>
  1070. </li>
  1071. <li>
  1072. <p>Default port if not given is <code>1080</code>.</p>
  1073. </li>
  1074. <li>
  1075. <p>Username and password are optional and will be used to authenticate against
  1076. the proxy.</p>
  1077. </li>
  1078. </ul>
  1079. <p><strong>Examples</strong></p>
  1080. <ul>
  1081. <li>HTTP_PROXY=http://USERNAME:PASSWORD@10.0.1.1:8080/</li>
  1082. <li>HTTPS_PROXY=http://USERNAME:PASSWORD@proxy.example.com:8080/</li>
  1083. <li>NO_PROXY=master.hostname.example.com,10.1.0.0/16,172.30.0.0/16</li>
  1084. </ul>
  1085. <p><strong>NOTE</strong>:
  1086. Synapse does not apply the IP blacklist to connections through the proxy (since
  1087. the DNS resolution is done by the proxy). It is expected that the proxy or firewall
  1088. will apply blacklisting of IP addresses.</p>
  1089. <h2 id="connection-types"><a class="header" href="#connection-types">Connection types</a></h2>
  1090. <p>The proxy will be <strong>used</strong> for:</p>
  1091. <ul>
  1092. <li>push</li>
  1093. <li>url previews</li>
  1094. <li>phone-home stats</li>
  1095. <li>recaptcha validation</li>
  1096. <li>CAS auth validation</li>
  1097. <li>OpenID Connect</li>
  1098. <li>Outbound federation</li>
  1099. <li>Federation (checking public key revocation)</li>
  1100. <li>Fetching public keys of other servers</li>
  1101. <li>Downloading remote media</li>
  1102. </ul>
  1103. <p>It will <strong>not be used</strong> for:</p>
  1104. <ul>
  1105. <li>Application Services</li>
  1106. <li>Identity servers</li>
  1107. <li>In worker configurations
  1108. <ul>
  1109. <li>connections between workers</li>
  1110. <li>connections from workers to Redis</li>
  1111. </ul>
  1112. </li>
  1113. </ul>
  1114. <h2 id="troubleshooting-1"><a class="header" href="#troubleshooting-1">Troubleshooting</a></h2>
  1115. <p>If a proxy server is used with TLS (HTTPS) and no connections are established,
  1116. it is most likely due to the proxy's certificates. To test this, the validation
  1117. in Synapse can be deactivated.</p>
  1118. <p><strong>NOTE</strong>: This has an impact on security and is for testing purposes only!</p>
  1119. <p>To deactivate the certificate validation, the following setting must be made in
  1120. <a href="setup/../usage/configuration/homeserver_sample_config.html">homserver.yaml</a>.</p>
  1121. <pre><code class="language-yaml">use_insecure_ssl_client_just_for_testing_do_not_use: true
  1122. </code></pre>
  1123. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-1"><a class="header" href="#overview-1">Overview</a></h1>
  1124. <p>This document explains how to enable VoIP relaying on your homeserver with
  1125. TURN.</p>
  1126. <p>The synapse Matrix homeserver supports integration with TURN server via the
  1127. <a href="https://tools.ietf.org/html/draft-uberti-behave-turn-rest-00">TURN server REST API</a>. This
  1128. allows the homeserver to generate credentials that are valid for use on the
  1129. TURN server through the use of a secret shared between the homeserver and the
  1130. TURN server.</p>
  1131. <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>
  1132. <h2 id="requirements"><a class="header" href="#requirements">Requirements</a></h2>
  1133. <p>For TURN relaying with <code>coturn</code> to work, it must be hosted on a server/endpoint with a public IP.</p>
  1134. <p>Hosting TURN behind NAT requires port forwaring and for the NAT gateway to have a public IP.
  1135. However, even with appropriate configuration, NAT is known to cause issues and to often not work.</p>
  1136. <h2 id="coturn-setup"><a class="header" href="#coturn-setup"><code>coturn</code> setup</a></h2>
  1137. <h3 id="initial-installation"><a class="header" href="#initial-installation">Initial installation</a></h3>
  1138. <p>The TURN daemon <code>coturn</code> is available from a variety of sources such as native package managers, or installation from source.</p>
  1139. <h4 id="debian-installation"><a class="header" href="#debian-installation">Debian installation</a></h4>
  1140. <p>Just install the debian package:</p>
  1141. <pre><code class="language-sh">apt install coturn
  1142. </code></pre>
  1143. <p>This will install and start a systemd service called <code>coturn</code>.</p>
  1144. <h4 id="source-installation"><a class="header" href="#source-installation">Source installation</a></h4>
  1145. <ol>
  1146. <li>
  1147. <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>
  1148. </li>
  1149. <li>
  1150. <p>Configure it:</p>
  1151. <pre><code class="language-sh">./configure
  1152. </code></pre>
  1153. <p>You may need to install <code>libevent2</code>: if so, you should do so in
  1154. the way recommended by your operating system. You can ignore
  1155. warnings about lack of database support: a database is unnecessary
  1156. for this purpose.</p>
  1157. </li>
  1158. <li>
  1159. <p>Build and install it:</p>
  1160. <pre><code class="language-sh">make
  1161. make install
  1162. </code></pre>
  1163. </li>
  1164. </ol>
  1165. <h3 id="configuration"><a class="header" href="#configuration">Configuration</a></h3>
  1166. <ol>
  1167. <li>
  1168. <p>Create or edit the config file in <code>/etc/turnserver.conf</code>. The relevant
  1169. lines, with example values, are:</p>
  1170. <pre><code>use-auth-secret
  1171. static-auth-secret=[your secret key here]
  1172. realm=turn.myserver.org
  1173. </code></pre>
  1174. <p>See <code>turnserver.conf</code> for explanations of the options. One way to generate
  1175. the <code>static-auth-secret</code> is with <code>pwgen</code>:</p>
  1176. <pre><code class="language-sh">pwgen -s 64 1
  1177. </code></pre>
  1178. <p>A <code>realm</code> must be specified, but its value is somewhat arbitrary. (It is
  1179. sent to clients as part of the authentication flow.) It is conventional to
  1180. set it to be your server name.</p>
  1181. </li>
  1182. <li>
  1183. <p>You will most likely want to configure coturn to write logs somewhere. The
  1184. easiest way is normally to send them to the syslog:</p>
  1185. <pre><code class="language-sh">syslog
  1186. </code></pre>
  1187. <p>(in which case, the logs will be available via <code>journalctl -u coturn</code> on a
  1188. systemd system). Alternatively, coturn can be configured to write to a
  1189. logfile - check the example config file supplied with coturn.</p>
  1190. </li>
  1191. <li>
  1192. <p>Consider your security settings. TURN lets users request a relay which will
  1193. connect to arbitrary IP addresses and ports. The following configuration is
  1194. suggested as a minimum starting point:</p>
  1195. <pre><code># VoIP traffic is all UDP. There is no reason to let users connect to arbitrary TCP endpoints via the relay.
  1196. no-tcp-relay
  1197. # don't let the relay ever try to connect to private IP address ranges within your network (if any)
  1198. # given the turn server is likely behind your firewall, remember to include any privileged public IPs too.
  1199. denied-peer-ip=10.0.0.0-10.255.255.255
  1200. denied-peer-ip=192.168.0.0-192.168.255.255
  1201. denied-peer-ip=172.16.0.0-172.31.255.255
  1202. # recommended additional local peers to block, to mitigate external access to internal services.
  1203. # https://www.rtcsec.com/article/slack-webrtc-turn-compromise-and-bug-bounty/#how-to-fix-an-open-turn-relay-to-address-this-vulnerability
  1204. no-multicast-peers
  1205. denied-peer-ip=0.0.0.0-0.255.255.255
  1206. denied-peer-ip=100.64.0.0-100.127.255.255
  1207. denied-peer-ip=127.0.0.0-127.255.255.255
  1208. denied-peer-ip=169.254.0.0-169.254.255.255
  1209. denied-peer-ip=192.0.0.0-192.0.0.255
  1210. denied-peer-ip=192.0.2.0-192.0.2.255
  1211. denied-peer-ip=192.88.99.0-192.88.99.255
  1212. denied-peer-ip=198.18.0.0-198.19.255.255
  1213. denied-peer-ip=198.51.100.0-198.51.100.255
  1214. denied-peer-ip=203.0.113.0-203.0.113.255
  1215. denied-peer-ip=240.0.0.0-255.255.255.255
  1216. # special case the turn server itself so that client-&gt;TURN-&gt;TURN-&gt;client flows work
  1217. # this should be one of the turn server's listening IPs
  1218. allowed-peer-ip=10.0.0.1
  1219. # consider whether you want to limit the quota of relayed streams per user (or total) to avoid risk of DoS.
  1220. user-quota=12 # 4 streams per video call, so 12 streams = 3 simultaneous relayed calls per user.
  1221. total-quota=1200
  1222. </code></pre>
  1223. </li>
  1224. <li>
  1225. <p>Also consider supporting TLS/DTLS. To do this, add the following settings
  1226. to <code>turnserver.conf</code>:</p>
  1227. <pre><code># TLS certificates, including intermediate certs.
  1228. # For Let's Encrypt certificates, use `fullchain.pem` here.
  1229. cert=/path/to/fullchain.pem
  1230. # TLS private key file
  1231. pkey=/path/to/privkey.pem
  1232. # Ensure the configuration lines that disable TLS/DTLS are commented-out or removed
  1233. #no-tls
  1234. #no-dtls
  1235. </code></pre>
  1236. <p>In this case, replace the <code>turn:</code> schemes in the <code>turn_uris</code> settings below
  1237. with <code>turns:</code>.</p>
  1238. <p>We recommend that you only try to set up TLS/DTLS once you have set up a
  1239. basic installation and got it working.</p>
  1240. <p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
  1241. not work with any Matrix client that uses Chromium's WebRTC library. This
  1242. currently includes Element Android &amp; iOS; for more details, see their
  1243. <a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
  1244. <a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
  1245. <a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
  1246. Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
  1247. </li>
  1248. <li>
  1249. <p>Ensure your firewall allows traffic into the TURN server on the ports
  1250. you've configured it to listen on (By default: 3478 and 5349 for TURN
  1251. traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
  1252. for the UDP relay.)</p>
  1253. </li>
  1254. <li>
  1255. <p>If your TURN server is behind NAT, the NAT gateway must have an external,
  1256. publicly-reachable IP address. You must configure coturn to advertise that
  1257. address to connecting clients:</p>
  1258. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1259. </code></pre>
  1260. <p>You may optionally limit the TURN server to listen only on the local
  1261. address that is mapped by NAT to the external address:</p>
  1262. <pre><code>listening-ip=INTERNAL_TURNSERVER_IPv4_ADDRESS
  1263. </code></pre>
  1264. <p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
  1265. configure coturn to advertise each available address:</p>
  1266. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1267. external-ip=EXTERNAL_NAT_IPv6_ADDRESS
  1268. </code></pre>
  1269. <p>When advertising an external IPv6 address, ensure that the firewall and
  1270. network settings of the system running your TURN server are configured to
  1271. accept IPv6 traffic, and that the TURN server is listening on the local
  1272. IPv6 address that is mapped by NAT to the external IPv6 address.</p>
  1273. </li>
  1274. <li>
  1275. <p>(Re)start the turn server:</p>
  1276. <ul>
  1277. <li>
  1278. <p>If you used the Debian package (or have set up a systemd unit yourself):</p>
  1279. <pre><code class="language-sh">systemctl restart coturn
  1280. </code></pre>
  1281. </li>
  1282. <li>
  1283. <p>If you installed from source:</p>
  1284. <pre><code class="language-sh">bin/turnserver -o
  1285. </code></pre>
  1286. </li>
  1287. </ul>
  1288. </li>
  1289. </ol>
  1290. <h2 id="synapse-setup"><a class="header" href="#synapse-setup">Synapse setup</a></h2>
  1291. <p>Your homeserver configuration file needs the following extra keys:</p>
  1292. <ol>
  1293. <li>&quot;<code>turn_uris</code>&quot;: This needs to be a yaml list of public-facing URIs
  1294. for your TURN server to be given out to your clients. Add separate
  1295. entries for each transport your TURN server supports.</li>
  1296. <li>&quot;<code>turn_shared_secret</code>&quot;: This is the secret shared between your
  1297. homeserver and your TURN server, so you should set it to the same
  1298. string you used in turnserver.conf.</li>
  1299. <li>&quot;<code>turn_user_lifetime</code>&quot;: This is the amount of time credentials
  1300. generated by your homeserver are valid for (in milliseconds).
  1301. Shorter times offer less potential for abuse at the expense of
  1302. increased traffic between web clients and your homeserver to
  1303. refresh credentials. The TURN REST API specification recommends
  1304. one day (86400000).</li>
  1305. <li>&quot;<code>turn_allow_guests</code>&quot;: Whether to allow guest users to use the
  1306. TURN server. This is enabled by default, as otherwise VoIP will
  1307. not work reliably for guests. However, it does introduce a
  1308. security risk as it lets guests connect to arbitrary endpoints
  1309. without having gone through a CAPTCHA or similar to register a
  1310. real account.</li>
  1311. </ol>
  1312. <p>As an example, here is the relevant section of the config file for <code>matrix.org</code>. The
  1313. <code>turn_uris</code> are appropriate for TURN servers listening on the default ports, with no TLS.</p>
  1314. <pre><code>turn_uris: [ &quot;turn:turn.matrix.org?transport=udp&quot;, &quot;turn:turn.matrix.org?transport=tcp&quot; ]
  1315. turn_shared_secret: &quot;n0t4ctuAllymatr1Xd0TorgSshar3d5ecret4obvIousreAsons&quot;
  1316. turn_user_lifetime: 86400000
  1317. turn_allow_guests: True
  1318. </code></pre>
  1319. <p>After updating the homeserver configuration, you must restart synapse:</p>
  1320. <ul>
  1321. <li>If you use synctl:
  1322. <pre><code class="language-sh"># Depending on how Synapse is installed, synctl may already be on
  1323. # your PATH. If not, you may need to activate a virtual environment.
  1324. synctl restart
  1325. </code></pre>
  1326. </li>
  1327. <li>If you use systemd:
  1328. <pre><code class="language-sh">systemctl restart matrix-synapse.service
  1329. </code></pre>
  1330. </li>
  1331. </ul>
  1332. <p>... and then reload any clients (or wait an hour for them to refresh their
  1333. settings).</p>
  1334. <h2 id="troubleshooting-2"><a class="header" href="#troubleshooting-2">Troubleshooting</a></h2>
  1335. <p>The normal symptoms of a misconfigured TURN server are that calls between
  1336. devices on different networks ring, but get stuck at &quot;call
  1337. connecting&quot;. Unfortunately, troubleshooting this can be tricky.</p>
  1338. <p>Here are a few things to try:</p>
  1339. <ul>
  1340. <li>
  1341. <p>Check that you have opened your firewall to allow TCP and UDP traffic to the
  1342. TURN ports (normally 3478 and 5349).</p>
  1343. </li>
  1344. <li>
  1345. <p>Check that you have opened your firewall to allow UDP traffic to the UDP
  1346. relay ports (49152-65535 by default).</p>
  1347. </li>
  1348. <li>
  1349. <p>Try disabling <code>coturn</code>'s TLS/DTLS listeners and enable only its (unencrypted)
  1350. TCP/UDP listeners. (This will only leave signaling traffic unencrypted;
  1351. voice &amp; video WebRTC traffic is always encrypted.)</p>
  1352. </li>
  1353. <li>
  1354. <p>Some WebRTC implementations (notably, that of Google Chrome) appear to get
  1355. confused by TURN servers which are reachable over IPv6 (this appears to be
  1356. an unexpected side-effect of its handling of multiple IP addresses as
  1357. defined by
  1358. <a href="https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12"><code>draft-ietf-rtcweb-ip-handling</code></a>).</p>
  1359. <p>Try removing any AAAA records for your TURN server, so that it is only
  1360. reachable over IPv4.</p>
  1361. </li>
  1362. <li>
  1363. <p>If your TURN server is behind NAT:</p>
  1364. <ul>
  1365. <li>
  1366. <p>double-check that your NAT gateway is correctly forwarding all TURN
  1367. ports (normally 3478 &amp; 5349 for TCP &amp; UDP TURN traffic, and 49152-65535 for the UDP
  1368. relay) to the NAT-internal address of your TURN server. If advertising
  1369. both IPv4 and IPv6 external addresses via the <code>external-ip</code> option, ensure
  1370. that the NAT is forwarding both IPv4 and IPv6 traffic to the IPv4 and IPv6
  1371. internal addresses of your TURN server. When in doubt, remove AAAA records
  1372. for your TURN server and specify only an IPv4 address as your <code>external-ip</code>.</p>
  1373. </li>
  1374. <li>
  1375. <p>ensure that your TURN server uses the NAT gateway as its default route.</p>
  1376. </li>
  1377. </ul>
  1378. </li>
  1379. <li>
  1380. <p>Enable more verbose logging in coturn via the <code>verbose</code> setting:</p>
  1381. <pre><code>verbose
  1382. </code></pre>
  1383. <p>... and then see if there are any clues in its logs.</p>
  1384. </li>
  1385. <li>
  1386. <p>If you are using a browser-based client under Chrome, check
  1387. <code>chrome://webrtc-internals/</code> for insights into the internals of the
  1388. negotiation. On Firefox, check the &quot;Connection Log&quot; on <code>about:webrtc</code>.</p>
  1389. <p>(Understanding the output is beyond the scope of this document!)</p>
  1390. </li>
  1391. <li>
  1392. <p>You can test your Matrix homeserver TURN setup with <a href="https://test.voip.librepush.net/">https://test.voip.librepush.net/</a>.
  1393. Note that this test is not fully reliable yet, so don't be discouraged if
  1394. the test fails.
  1395. <a href="https://github.com/matrix-org/voip-tester">Here</a> is the github repo of the
  1396. source of the tester, where you can file bug reports.</p>
  1397. </li>
  1398. <li>
  1399. <p>There is a WebRTC test tool at
  1400. <a href="https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/">https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/</a>. To
  1401. use it, you will need a username/password for your TURN server. You can
  1402. either:</p>
  1403. <ul>
  1404. <li>
  1405. <p>look for the <code>GET /_matrix/client/r0/voip/turnServer</code> request made by a
  1406. matrix client to your homeserver in your browser's network inspector. In
  1407. the response you should see <code>username</code> and <code>password</code>. Or:</p>
  1408. </li>
  1409. <li>
  1410. <p>Use the following shell commands:</p>
  1411. <pre><code class="language-sh">secret=staticAuthSecretHere
  1412. u=$((`date +%s` + 3600)):test
  1413. p=$(echo -n $u | openssl dgst -hmac $secret -sha1 -binary | base64)
  1414. echo -e &quot;username: $u\npassword: $p&quot;
  1415. </code></pre>
  1416. <p>Or:</p>
  1417. </li>
  1418. <li>
  1419. <p>Temporarily configure coturn to accept a static username/password. To do
  1420. this, comment out <code>use-auth-secret</code> and <code>static-auth-secret</code> and add the
  1421. following:</p>
  1422. <pre><code>lt-cred-mech
  1423. user=username:password
  1424. </code></pre>
  1425. <p><strong>Note</strong>: these settings will not take effect unless <code>use-auth-secret</code>
  1426. and <code>static-auth-secret</code> are disabled.</p>
  1427. <p>Restart coturn after changing the configuration file.</p>
  1428. <p>Remember to restore the original settings to go back to testing with
  1429. Matrix clients!</p>
  1430. </li>
  1431. </ul>
  1432. <p>If the TURN server is working correctly, you should see at least one <code>relay</code>
  1433. entry in the results.</p>
  1434. </li>
  1435. </ul>
  1436. <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>
  1437. <p>In the following documentation, we use the term <code>server_name</code> to refer to that setting
  1438. in your homeserver configuration file. It appears at the ends of user ids, and tells
  1439. other homeservers where they can find your server.</p>
  1440. <p>By default, other homeservers will expect to be able to reach yours via
  1441. your <code>server_name</code>, on port 8448. For example, if you set your <code>server_name</code>
  1442. to <code>example.com</code> (so that your user names look like <code>@user:example.com</code>),
  1443. other servers will try to connect to yours at <code>https://example.com:8448/</code>.</p>
  1444. <p>Delegation is a Matrix feature allowing a homeserver admin to retain a
  1445. <code>server_name</code> of <code>example.com</code> so that user IDs, room aliases, etc continue
  1446. to look like <code>*:example.com</code>, whilst having federation traffic routed
  1447. to a different server and/or port (e.g. <code>synapse.example.com:443</code>).</p>
  1448. <h2 id="well-known-delegation"><a class="header" href="#well-known-delegation">.well-known delegation</a></h2>
  1449. <p>To use this method, you need to be able to configure the server at
  1450. <code>https://&lt;server_name&gt;</code> to serve a file at
  1451. <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>. There are two ways to do this, shown below.</p>
  1452. <p>Note that the <code>.well-known</code> file is hosted on the default port for <code>https</code> (port 443).</p>
  1453. <h3 id="external-server"><a class="header" href="#external-server">External server</a></h3>
  1454. <p>For maximum flexibility, you need to configure an external server such as nginx, Apache
  1455. or HAProxy to serve the <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> file. Setting
  1456. up such a server is out of the scope of this documentation, but note that it is often
  1457. possible to configure your <a href="reverse_proxy.html">reverse proxy</a> for this.</p>
  1458. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> should be configured
  1459. return a JSON structure containing the key <code>m.server</code> like this:</p>
  1460. <pre><code class="language-json">{
  1461. &quot;m.server&quot;: &quot;&lt;synapse.server.name&gt;[:&lt;yourport&gt;]&quot;
  1462. }
  1463. </code></pre>
  1464. <p>In our example (where we want federation traffic to be routed to
  1465. <code>https://synapse.example.com</code>, on port 443), this would mean that
  1466. <code>https://example.com/.well-known/matrix/server</code> should return:</p>
  1467. <pre><code class="language-json">{
  1468. &quot;m.server&quot;: &quot;synapse.example.com:443&quot;
  1469. }
  1470. </code></pre>
  1471. <p>Note, specifying a port is optional. If no port is specified, then it defaults
  1472. to 8448.</p>
  1473. <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>
  1474. <p>If you are able to set up your domain so that <code>https://&lt;server_name&gt;</code> is routed to
  1475. Synapse (i.e., the only change needed is to direct federation traffic to port 443
  1476. instead of port 8448), then it is possible to configure Synapse to serve a suitable
  1477. <code>.well-known/matrix/server</code> file. To do so, add the following to your <code>homeserver.yaml</code>
  1478. file:</p>
  1479. <pre><code class="language-yaml">serve_server_wellknown: true
  1480. </code></pre>
  1481. <p><strong>Note</strong>: this <em>only</em> works if <code>https://&lt;server_name&gt;</code> is routed to Synapse, so is
  1482. generally not suitable if Synapse is hosted at a subdomain such as
  1483. <code>https://synapse.example.com</code>.</p>
  1484. <h2 id="srv-dns-record-delegation"><a class="header" href="#srv-dns-record-delegation">SRV DNS record delegation</a></h2>
  1485. <p>It is also possible to do delegation using a SRV DNS record. However, that is generally
  1486. not recommended, as it can be difficult to configure the TLS certificates correctly in
  1487. this case, and it offers little advantage over <code>.well-known</code> delegation.</p>
  1488. <p>However, if you really need it, you can find some documentation on what such a
  1489. 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
  1490. specification</a>.</p>
  1491. <h2 id="delegation-faq"><a class="header" href="#delegation-faq">Delegation FAQ</a></h2>
  1492. <h3 id="when-do-i-need-delegation"><a class="header" href="#when-do-i-need-delegation">When do I need delegation?</a></h3>
  1493. <p>If your homeserver's APIs are accessible on the default federation port (8448)
  1494. and the domain your <code>server_name</code> points to, you do not need any delegation.</p>
  1495. <p>For instance, if you registered <code>example.com</code> and pointed its DNS A record at a
  1496. fresh server, you could install Synapse on that host, giving it a <code>server_name</code>
  1497. of <code>example.com</code>, and once a reverse proxy has been set up to proxy all requests
  1498. sent to the port <code>8448</code> and serve TLS certificates for <code>example.com</code>, you
  1499. wouldn't need any delegation set up.</p>
  1500. <p><strong>However</strong>, if your homeserver's APIs aren't accessible on port 8448 and on the
  1501. domain <code>server_name</code> points to, you will need to let other servers know how to
  1502. find it using delegation.</p>
  1503. <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>
  1504. <p>Generally, using a reverse proxy for both the federation and client traffic is a good
  1505. idea, since it saves handling TLS traffic in Synapse. See
  1506. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a
  1507. reverse proxy.</p>
  1508. <div style="break-before: page; page-break-before: always;"></div><h1 id="upgrading-synapse"><a class="header" href="#upgrading-synapse">Upgrading Synapse</a></h1>
  1509. <p>Before upgrading check if any special steps are required to upgrade from
  1510. the version you currently have installed to the current version of
  1511. Synapse. The extra instructions that may be required are listed later in
  1512. this document.</p>
  1513. <ul>
  1514. <li>
  1515. <p>Check that your versions of Python and PostgreSQL are still
  1516. supported.</p>
  1517. <p>Synapse follows upstream lifecycles for <a href="https://endoflife.date/python">Python</a> and
  1518. <a href="https://endoflife.date/postgresql">PostgreSQL</a>, and removes support for versions
  1519. which are no longer maintained.</p>
  1520. <p>The website <a href="https://endoflife.date">https://endoflife.date</a> also offers convenient
  1521. summaries.</p>
  1522. </li>
  1523. <li>
  1524. <p>If Synapse was installed using <a href="setup/installation.html#prebuilt-packages">prebuilt
  1525. packages</a>, you will need to follow the
  1526. normal process for upgrading those packages.</p>
  1527. </li>
  1528. <li>
  1529. <p>If Synapse was installed using pip then upgrade to the latest
  1530. version by running:</p>
  1531. <pre><code class="language-bash">pip install --upgrade matrix-synapse
  1532. </code></pre>
  1533. </li>
  1534. <li>
  1535. <p>If Synapse was installed from source, then:</p>
  1536. <ol>
  1537. <li>
  1538. <p>Obtain the latest version of the source code. Git users can run
  1539. <code>git pull</code> to do this.</p>
  1540. </li>
  1541. <li>
  1542. <p>If you're running Synapse in a virtualenv, make sure to activate it before
  1543. upgrading. For example, if Synapse is installed in a virtualenv in <code>~/synapse/env</code> then
  1544. run:</p>
  1545. <pre><code class="language-bash">source ~/synapse/env/bin/activate
  1546. pip install --upgrade .
  1547. </code></pre>
  1548. <p>Include any relevant extras between square brackets, e.g. <code>pip install --upgrade &quot;.[postgres,oidc]&quot;</code>.</p>
  1549. </li>
  1550. <li>
  1551. <p>If you're using <code>poetry</code> to manage a Synapse installation, run:</p>
  1552. <pre><code class="language-bash">poetry install
  1553. </code></pre>
  1554. <p>Include any relevant extras with <code>--extras</code>, e.g. <code>poetry install --extras postgres --extras oidc</code>.
  1555. It's probably easiest to run <code>poetry install --extras all</code>.</p>
  1556. </li>
  1557. <li>
  1558. <p>Restart Synapse:</p>
  1559. <pre><code class="language-bash">synctl restart
  1560. </code></pre>
  1561. </li>
  1562. </ol>
  1563. </li>
  1564. </ul>
  1565. <p>To check whether your update was successful, you can check the running
  1566. server version with:</p>
  1567. <pre><code class="language-bash"># you may need to replace 'localhost:8008' if synapse is not configured
  1568. # to listen on port 8008.
  1569. curl http://localhost:8008/_synapse/admin/v1/server_version
  1570. </code></pre>
  1571. <h2 id="rolling-back-to-older-versions"><a class="header" href="#rolling-back-to-older-versions">Rolling back to older versions</a></h2>
  1572. <p>Rolling back to previous releases can be difficult, due to database
  1573. schema changes between releases. Where we have been able to test the
  1574. rollback process, this will be noted below.</p>
  1575. <p>In general, you will need to undo any changes made during the upgrade
  1576. process, for example:</p>
  1577. <ul>
  1578. <li>
  1579. <p>pip:</p>
  1580. <pre><code class="language-bash">source env/bin/activate
  1581. # replace `1.3.0` accordingly:
  1582. pip install matrix-synapse==1.3.0
  1583. </code></pre>
  1584. </li>
  1585. <li>
  1586. <p>Debian:</p>
  1587. <pre><code class="language-bash"># replace `1.3.0` and `stretch` accordingly:
  1588. wget https://packages.matrix.org/debian/pool/main/m/matrix-synapse-py3/matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1589. dpkg -i matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1590. </code></pre>
  1591. </li>
  1592. </ul>
  1593. <h1 id="upgrading-to-v1620"><a class="header" href="#upgrading-to-v1620">Upgrading to v1.62.0</a></h1>
  1594. <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>
  1595. <p>As a followup to changes in v1.60.0, the following spam-checker callbacks have changed signature:</p>
  1596. <ul>
  1597. <li><code>user_may_join_room</code></li>
  1598. <li><code>user_may_invite</code></li>
  1599. <li><code>user_may_send_3pid_invite</code></li>
  1600. <li><code>user_may_create_room</code></li>
  1601. <li><code>user_may_create_room_alias</code></li>
  1602. <li><code>user_may_publish_room</code></li>
  1603. <li><code>check_media_file_for_spam</code></li>
  1604. </ul>
  1605. <p>For each of these methods, the previous callback signature has been deprecated.</p>
  1606. <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>
  1607. <p>For instance, if your module implements <code>user_may_join_room</code> as follows:</p>
  1608. <pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
  1609. if ...:
  1610. # Request is spam
  1611. return False
  1612. # Request is not spam
  1613. return True
  1614. </code></pre>
  1615. <p>you should rewrite it as follows:</p>
  1616. <pre><code class="language-python">async def user_may_join_room(self, user_id: str, room_id: str, is_invited: bool)
  1617. if ...:
  1618. # Request is spam, mark it as forbidden (you may use some more precise error
  1619. # code if it is useful).
  1620. return synapse.module_api.errors.Codes.FORBIDDEN
  1621. # Request is not spam, mark it as such.
  1622. return synapse.module_api.NOT_SPAM
  1623. </code></pre>
  1624. <h1 id="upgrading-to-v1610"><a class="header" href="#upgrading-to-v1610">Upgrading to v1.61.0</a></h1>
  1625. <h2 id="removal-of-deprecated-communitygroups"><a class="header" href="#removal-of-deprecated-communitygroups">Removal of deprecated community/groups</a></h2>
  1626. <p>This release of Synapse will remove deprecated community/groups from codebase.</p>
  1627. <h3 id="worker-endpoints"><a class="header" href="#worker-endpoints">Worker endpoints</a></h3>
  1628. <p>For those who have deployed workers, following worker endpoints will no longer
  1629. exist and they can be removed from the reverse proxy configuration:</p>
  1630. <ul>
  1631. <li><code>^/_matrix/federation/v1/get_groups_publicised$</code></li>
  1632. <li><code>^/_matrix/client/(r0|v3|unstable)/joined_groups$</code></li>
  1633. <li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups$</code></li>
  1634. <li><code>^/_matrix/client/(r0|v3|unstable)/publicised_groups/</code></li>
  1635. <li><code>^/_matrix/federation/v1/groups/</code></li>
  1636. <li><code>^/_matrix/client/(r0|v3|unstable)/groups/</code></li>
  1637. </ul>
  1638. <h1 id="upgrading-to-v1600"><a class="header" href="#upgrading-to-v1600">Upgrading to v1.60.0</a></h1>
  1639. <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>
  1640. <p>This release of Synapse will add a unique index to the <code>state_group_edges</code> table, in order
  1641. to prevent accidentally introducing duplicate information (for example, because a database
  1642. backup was restored multiple times).</p>
  1643. <p>Duplicate rows being present in this table could cause drastic performance problems; see
  1644. <a href="https://github.com/matrix-org/synapse/issues/11779">issue 11779</a> for more details.</p>
  1645. <p>If your Synapse database already has had duplicate rows introduced into this table,
  1646. this could fail, with either of these errors:</p>
  1647. <p><strong>On Postgres:</strong></p>
  1648. <pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
  1649. synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
  1650. ...
  1651. psycopg2.errors.UniqueViolation: could not create unique index &quot;state_group_edges_unique_idx&quot;
  1652. DETAIL: Key (state_group, prev_state_group)=(2, 1) is duplicated.
  1653. </code></pre>
  1654. <p>(The numbers may be different.)</p>
  1655. <p><strong>On SQLite:</strong></p>
  1656. <pre><code>synapse.storage.background_updates - 623 - INFO - background_updates-0 - Adding index state_group_edges_unique_idx to state_group_edges
  1657. synapse.storage.background_updates - 282 - ERROR - background_updates-0 - Error doing update
  1658. ...
  1659. sqlite3.IntegrityError: UNIQUE constraint failed: state_group_edges.state_group, state_group_edges.prev_state_group
  1660. </code></pre>
  1661. <details>
  1662. <summary><b>Expand this section for steps to resolve this problem</b></summary>
  1663. <h3 id="on-postgres"><a class="header" href="#on-postgres">On Postgres</a></h3>
  1664. <p>Connect to your database with <code>psql</code>.</p>
  1665. <pre><code class="language-sql">BEGIN;
  1666. DELETE FROM state_group_edges WHERE (ctid, state_group, prev_state_group) IN (
  1667. SELECT row_id, state_group, prev_state_group
  1668. FROM (
  1669. SELECT
  1670. ctid AS row_id,
  1671. MIN(ctid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
  1672. state_group,
  1673. prev_state_group
  1674. FROM state_group_edges
  1675. ) AS t1
  1676. WHERE row_id &lt;&gt; min_row_id
  1677. );
  1678. COMMIT;
  1679. </code></pre>
  1680. <h3 id="on-sqlite"><a class="header" href="#on-sqlite">On SQLite</a></h3>
  1681. <p>At the command-line, use <code>sqlite3 path/to/your-homeserver-database.db</code>:</p>
  1682. <pre><code class="language-sql">BEGIN;
  1683. DELETE FROM state_group_edges WHERE (rowid, state_group, prev_state_group) IN (
  1684. SELECT row_id, state_group, prev_state_group
  1685. FROM (
  1686. SELECT
  1687. rowid AS row_id,
  1688. MIN(rowid) OVER (PARTITION BY state_group, prev_state_group) AS min_row_id,
  1689. state_group,
  1690. prev_state_group
  1691. FROM state_group_edges
  1692. )
  1693. WHERE row_id &lt;&gt; min_row_id
  1694. );
  1695. COMMIT;
  1696. </code></pre>
  1697. <h3 id="for-more-details"><a class="header" href="#for-more-details">For more details</a></h3>
  1698. <p><a href="https://github.com/matrix-org/synapse/issues/11779#issuecomment-1131545970">This comment on issue 11779</a>
  1699. has queries that can be used to check a database for this problem in advance.</p>
  1700. </details>
  1701. <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>
  1702. <p>The previous signature has been deprecated.</p>
  1703. <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>
  1704. <p>This is part of an ongoing refactoring of the SpamChecker API to make it less ambiguous and more powerful.</p>
  1705. <p>If your module implements <code>check_event_for_spam</code> as follows:</p>
  1706. <pre><code class="language-python">async def check_event_for_spam(event):
  1707. if ...:
  1708. # Event is spam
  1709. return True
  1710. # Event is not spam
  1711. return False
  1712. </code></pre>
  1713. <p>you should rewrite it as follows:</p>
  1714. <pre><code class="language-python">async def check_event_for_spam(event):
  1715. if ...:
  1716. # Event is spam, mark it as forbidden (you may use some more precise error
  1717. # code if it is useful).
  1718. return synapse.module_api.errors.Codes.FORBIDDEN
  1719. # Event is not spam, mark it as such.
  1720. return synapse.module_api.NOT_SPAM
  1721. </code></pre>
  1722. <h1 id="upgrading-to-v1590"><a class="header" href="#upgrading-to-v1590">Upgrading to v1.59.0</a></h1>
  1723. <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>
  1724. <p>The names of user devices are no longer visible to users on other homeservers by default.
  1725. Device IDs are unaffected, as these are necessary to facilitate end-to-end encryption.</p>
  1726. <p>To re-enable this functionality, set the
  1727. <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>
  1728. homeserver config option to <code>true</code>.</p>
  1729. <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>
  1730. <p>The <code>synapse.app.appservice</code> worker application type allowed you to configure a
  1731. single worker to use to notify application services of new events, as long
  1732. as this functionality was disabled on the main process with <code>notify_appservices: False</code>.
  1733. Further, the <code>synapse.app.user_dir</code> worker application type allowed you to configure
  1734. a single worker to be responsible for updating the user directory, as long as this
  1735. was disabled on the main process with <code>update_user_directory: False</code>.</p>
  1736. <p>To unify Synapse's worker types, the <code>synapse.app.appservice</code> worker application
  1737. type and the <code>notify_appservices</code> configuration option have been deprecated.
  1738. The <code>synapse.app.user_dir</code> worker application type and <code>update_user_directory</code>
  1739. configuration option have also been deprecated.</p>
  1740. <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>
  1741. worker application type is used and that the <code>notify_appservices_from_worker</code> and/or
  1742. <code>update_user_directory_from_worker</code> options are set to the name of a worker.</p>
  1743. <p>For the time being, the old options can be used alongside the new options to make
  1744. it easier to transition between the two configurations, however please note that:</p>
  1745. <ul>
  1746. <li>the options must not contradict each other (otherwise Synapse won't start); and</li>
  1747. <li>the <code>notify_appservices</code> and <code>update_user_directory</code> options will be removed in a future release of Synapse.</li>
  1748. </ul>
  1749. <p>Please see the <a href="workers.html#notifying-application-services"><em>Notifying Application Services</em></a> and
  1750. <a href="workers.html#updating-the-user-directory"><em>Updating the User Directory</em></a> sections of the worker
  1751. documentation for more information.</p>
  1752. <h1 id="upgrading-to-v1580"><a class="header" href="#upgrading-to-v1580">Upgrading to v1.58.0</a></h1>
  1753. <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>
  1754. <p>The non-standard groups/communities feature in Synapse has been disabled by default
  1755. and will be removed in Synapse v1.61.0.</p>
  1756. <h1 id="upgrading-to-v1570"><a class="header" href="#upgrading-to-v1570">Upgrading to v1.57.0</a></h1>
  1757. <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>
  1758. <p>Synapse v1.57.0 includes a <a href="https://github.com/matrix-org/synapse/pull/12209">change</a> to the
  1759. way transaction IDs are managed for application services. If your deployment uses a dedicated
  1760. worker for application service traffic, <strong>it must be stopped</strong> when the database is upgraded
  1761. (which normally happens when the main process is upgraded), to ensure the change is made safely
  1762. without any risk of reusing transaction IDs.</p>
  1763. <p>Deployments which do not use separate worker processes can be upgraded as normal. Similarly,
  1764. deployments where no application services are in use can be upgraded as normal.</p>
  1765. <details>
  1766. <summary><b>Recovering from an incorrect upgrade</b></summary>
  1767. <p>If the database schema is upgraded <em>without</em> stopping the worker responsible
  1768. for AS traffic, then the following error may be given when attempting to start
  1769. a Synapse worker or master process:</p>
  1770. <pre><code>**********************************************************************************
  1771. Error during initialisation:
  1772. Postgres sequence 'application_services_txn_id_seq' is inconsistent with associated
  1773. table 'application_services_txns'. This can happen if Synapse has been downgraded and
  1774. then upgraded again, or due to a bad migration.
  1775. To fix this error, shut down Synapse (including any and all workers)
  1776. and run the following SQL:
  1777. SELECT setval('application_services_txn_id_seq', (
  1778. SELECT GREATEST(MAX(txn_id), 0) FROM application_services_txns
  1779. ));
  1780. See docs/postgres.md for more information.
  1781. There may be more information in the logs.
  1782. **********************************************************************************
  1783. </code></pre>
  1784. <p>This error may also be seen if Synapse is <em>downgraded</em> to an earlier version,
  1785. and then upgraded again to v1.57.0 or later.</p>
  1786. <p>In either case:</p>
  1787. <ol>
  1788. <li>Ensure that the worker responsible for AS traffic is stopped.</li>
  1789. <li>Run the SQL command given in the error message via <code>psql</code>.</li>
  1790. </ol>
  1791. <p>Synapse should then start correctly.</p>
  1792. </details>
  1793. <h1 id="upgrading-to-v1560"><a class="header" href="#upgrading-to-v1560">Upgrading to v1.56.0</a></h1>
  1794. <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>
  1795. <p>Synapse will refuse to start if registration is enabled without email, captcha, or token-based verification unless the new config
  1796. flag <code>enable_registration_without_verification</code> is set to &quot;true&quot;.</p>
  1797. <h2 id="groupscommunities-feature-has-been-deprecated"><a class="header" href="#groupscommunities-feature-has-been-deprecated">Groups/communities feature has been deprecated</a></h2>
  1798. <p>The non-standard groups/communities feature in Synapse has been deprecated and will
  1799. be disabled by default in Synapse v1.58.0.</p>
  1800. <p>You can test disabling it by adding the following to your homeserver configuration:</p>
  1801. <pre><code class="language-yaml">experimental_features:
  1802. groups_enabled: false
  1803. </code></pre>
  1804. <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>
  1805. <p>Synapse now refuses to start when using PostgreSQL with non-<code>C</code> values for <code>COLLATE</code> and
  1806. <code>CTYPE</code> unless the config flag <code>allow_unsafe_locale</code>, found in the database section of
  1807. 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>
  1808. for more information and instructions on how to fix a database with incorrect values.</p>
  1809. <h1 id="upgrading-to-v1550"><a class="header" href="#upgrading-to-v1550">Upgrading to v1.55.0</a></h1>
  1810. <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>
  1811. <p>The <code>synctl</code> script
  1812. <a href="https://github.com/matrix-org/synapse/pull/12140">has been made</a> an
  1813. <a href="https://packaging.python.org/en/latest/specifications/entry-points/">entry point</a>
  1814. and no longer exists at the root of Synapse's source tree. If you wish to use
  1815. <code>synctl</code> to manage your homeserver, you should invoke <code>synctl</code> directly, e.g.
  1816. <code>synctl start</code> instead of <code>./synctl start</code> or <code>/path/to/synctl start</code>.</p>
  1817. <p>You will need to ensure <code>synctl</code> is on your <code>PATH</code>.</p>
  1818. <ul>
  1819. <li>This is automatically the case when using
  1820. <a href="https://packages.matrix.org/debian/">Debian packages</a> or
  1821. <a href="https://hub.docker.com/r/matrixdotorg/synapse">docker images</a>
  1822. provided by Matrix.org.</li>
  1823. <li>When installing from a wheel, sdist, or PyPI, a <code>synctl</code> executable is added
  1824. to your Python installation's <code>bin</code>. This should be on your <code>PATH</code>
  1825. automatically, though you might need to activate a virtual environment
  1826. depending on how you installed Synapse.</li>
  1827. </ul>
  1828. <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>
  1829. <p>Synapse v1.55.0 drops support for Mjolnir 1.3.1 and earlier.
  1830. If you use the Mjolnir module to moderate your homeserver,
  1831. please upgrade Mjolnir to version 1.3.2 or later before upgrading Synapse.</p>
  1832. <h1 id="upgrading-to-v1540"><a class="header" href="#upgrading-to-v1540">Upgrading to v1.54.0</a></h1>
  1833. <h2 id="legacy-structured-logging-configuration-removal"><a class="header" href="#legacy-structured-logging-configuration-removal">Legacy structured logging configuration removal</a></h2>
  1834. <p>This release removes support for the <code>structured: true</code> logging configuration
  1835. which was deprecated in Synapse v1.23.0. If your logging configuration contains
  1836. <code>structured: true</code> then it should be modified based on the
  1837. <a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
  1838. <h1 id="upgrading-to-v1530"><a class="header" href="#upgrading-to-v1530">Upgrading to v1.53.0</a></h1>
  1839. <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>
  1840. <p>Per the deprecation notice in Synapse v1.51.0, listeners of type <code>webclient</code>
  1841. are no longer supported and configuring them is a now a configuration error.</p>
  1842. <p>Configuring a non-HTTP(S) <code>web_client_location</code> configuration is is now a
  1843. configuration error. Since the <code>webclient</code> listener is no longer supported, this
  1844. setting only applies to the root path <code>/</code> of Synapse's web server and no longer
  1845. the <code>/_matrix/client/</code> path.</p>
  1846. <h2 id="stablisation-of-msc3231"><a class="header" href="#stablisation-of-msc3231">Stablisation of MSC3231</a></h2>
  1847. <p>The unstable validity-check endpoint for the
  1848. <a href="https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv1registermloginregistration_tokenvalidity">Registration Tokens</a>
  1849. feature has been stabilised and moved from:</p>
  1850. <p><code>/_matrix/client/unstable/org.matrix.msc3231/register/org.matrix.msc3231.login.registration_token/validity</code></p>
  1851. <p>to:</p>
  1852. <p><code>/_matrix/client/v1/register/m.login.registration_token/validity</code></p>
  1853. <p>Please update any relevant reverse proxy or firewall configurations appropriately.</p>
  1854. <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>
  1855. <p>Formerly, entries in the cache were not evicted regardless of whether they were accessed after storing.
  1856. This behavior has now changed. By default entries in the cache are now evicted after 30m of not being accessed.
  1857. To change the default behavior, go to the <code>caches</code> section of the config and change the <code>expire_caches</code> and
  1858. <code>cache_entry_ttl</code> flags as necessary. Please note that these flags replace the <code>expiry_time</code> flag in the config.
  1859. The <code>expiry_time</code> flag will still continue to work, but it has been deprecated and will be removed in the future.</p>
  1860. <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>
  1861. <p>The <code>capabilities</code> of MSC3283 from the REST API <code>/_matrix/client/r0/capabilities</code>
  1862. becomes stable.</p>
  1863. <p>The old <code>capabilities</code></p>
  1864. <ul>
  1865. <li><code>org.matrix.msc3283.set_displayname</code>,</li>
  1866. <li><code>org.matrix.msc3283.set_avatar_url</code> and</li>
  1867. <li><code>org.matrix.msc3283.3pid_changes</code></li>
  1868. </ul>
  1869. <p>are deprecated and scheduled to be removed in Synapse v1.54.0.</p>
  1870. <p>The new <code>capabilities</code></p>
  1871. <ul>
  1872. <li><code>m.set_displayname</code>,</li>
  1873. <li><code>m.set_avatar_url</code> and</li>
  1874. <li><code>m.3pid_changes</code></li>
  1875. </ul>
  1876. <p>are now active by default.</p>
  1877. <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>
  1878. <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>,
  1879. the deprecated <code>user_may_create_room_with_invites</code> module callback has been removed.</p>
  1880. <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>
  1881. 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>
  1882. 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>
  1883. 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>
  1884. <h1 id="upgrading-to-v1520"><a class="header" href="#upgrading-to-v1520">Upgrading to v1.52.0</a></h1>
  1885. <h2 id="twisted-security-release"><a class="header" href="#twisted-security-release">Twisted security release</a></h2>
  1886. <p>Note that <a href="https://github.com/twisted/twisted/releases/tag/twisted-22.1.0">Twisted 22.1.0</a>
  1887. has recently been released, which fixes a <a href="https://github.com/twisted/twisted/security/advisories/GHSA-92x2-jw7w-xvvx">security issue</a>
  1888. within the Twisted library. We do not believe Synapse is affected by this vulnerability,
  1889. though we advise server administrators who installed Synapse via pip to upgrade Twisted
  1890. with <code>pip install --upgrade Twisted treq</code> as a matter of good practice. The Docker image
  1891. <code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> are using the
  1892. updated library.</p>
  1893. <h1 id="upgrading-to-v1510"><a class="header" href="#upgrading-to-v1510">Upgrading to v1.51.0</a></h1>
  1894. <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>
  1895. <p>Listeners of type <code>webclient</code> are deprecated and scheduled to be removed in
  1896. Synapse v1.53.0.</p>
  1897. <p>Similarly, a non-HTTP(S) <code>web_client_location</code> configuration is deprecated and
  1898. will become a configuration error in Synapse v1.53.0.</p>
  1899. <h1 id="upgrading-to-v1500"><a class="header" href="#upgrading-to-v1500">Upgrading to v1.50.0</a></h1>
  1900. <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>
  1901. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  1902. we've dropped support for Python 3.6 and PostgreSQL 9.6, as they are no
  1903. longer supported upstream.</p>
  1904. <p>This release of Synapse requires Python 3.7+ and PostgreSQL 10+.</p>
  1905. <h1 id="upgrading-to-v1470"><a class="header" href="#upgrading-to-v1470">Upgrading to v1.47.0</a></h1>
  1906. <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>
  1907. <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>
  1908. (released on 2021-05-17) and have now been removed:</p>
  1909. <ul>
  1910. <li><code>POST /_synapse/admin/v1/&lt;room_id&gt;/delete</code></li>
  1911. </ul>
  1912. <p>Any scripts still using the above APIs should be converted to use the
  1913. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  1914. <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>
  1915. <p>The <code>user_may_create_room_with_invites</code> is deprecated and will be removed in a future
  1916. version of Synapse. Modules implementing this callback can instead implement
  1917. <a href="https://matrix-org.github.io/synapse/latest/modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a>
  1918. 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>
  1919. module API method to infer whether the invite is happening in the context of creating a
  1920. room.</p>
  1921. <p>We plan to remove this callback in January 2022.</p>
  1922. <h1 id="upgrading-to-v1450"><a class="header" href="#upgrading-to-v1450">Upgrading to v1.45.0</a></h1>
  1923. <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>
  1924. <p>Media storage provider modules that read from the Synapse configuration object (i.e. that
  1925. read the value of <code>hs.config.[...]</code>) now need to specify the configuration section they're
  1926. reading from. This means that if a module reads the value of e.g. <code>hs.config.media_store_path</code>,
  1927. it needs to replace it with <code>hs.config.media.media_store_path</code>.</p>
  1928. <h1 id="upgrading-to-v1440"><a class="header" href="#upgrading-to-v1440">Upgrading to v1.44.0</a></h1>
  1929. <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>
  1930. <p>The <code>url_cache/</code> and <code>url_cache_thumbnails/</code> directories in the media store are
  1931. no longer mirrored to storage providers. These two directories can be safely
  1932. deleted from any configured storage providers to reclaim space.</p>
  1933. <h1 id="upgrading-to-v1430"><a class="header" href="#upgrading-to-v1430">Upgrading to v1.43.0</a></h1>
  1934. <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>
  1935. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#available-worker-applications">available worker applications documentation</a>
  1936. has been updated to reflect that calls to the <code>/spaces</code>, <code>/hierarchy</code>, and
  1937. <code>/summary</code> endpoints can now be routed to workers for both client API and
  1938. federation requests.</p>
  1939. <h1 id="upgrading-to-v1420"><a class="header" href="#upgrading-to-v1420">Upgrading to v1.42.0</a></h1>
  1940. <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>
  1941. <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>
  1942. (released on 2021-01-13) and have now been removed:</p>
  1943. <ul>
  1944. <li><code>POST /_synapse/admin/v1/purge_room</code></li>
  1945. <li><code>POST /_synapse/admin/v1/shutdown_room/&lt;room_id&gt;</code></li>
  1946. </ul>
  1947. <p>Any scripts still using the above APIs should be converted to use the
  1948. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  1949. <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>
  1950. <p>This may affect you if you make use of custom HTML templates for the
  1951. <a href="../synapse/res/templates/recaptcha.html">reCAPTCHA</a> or
  1952. <a href="../synapse/res/templates/terms.html">terms</a> fallback pages.</p>
  1953. <p>The template is now provided an <code>error</code> variable if the authentication
  1954. process failed. See the default templates linked above for an example.</p>
  1955. <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>
  1956. <p>Users will stop receiving message updates via email for addresses that were
  1957. once, but not still, linked to their account.</p>
  1958. <h1 id="upgrading-to-v1410"><a class="header" href="#upgrading-to-v1410">Upgrading to v1.41.0</a></h1>
  1959. <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>
  1960. <p>Since Synapse 1.6.0 (2019-11-26) you can set a proxy for outbound HTTP requests via
  1961. http_proxy/https_proxy environment variables. This proxy was set for:</p>
  1962. <ul>
  1963. <li>push</li>
  1964. <li>url previews</li>
  1965. <li>phone-home stats</li>
  1966. <li>recaptcha validation</li>
  1967. <li>CAS auth validation</li>
  1968. <li>OpenID Connect</li>
  1969. <li>Federation (checking public key revocation)</li>
  1970. </ul>
  1971. <p>In this version we have added support for outbound requests for:</p>
  1972. <ul>
  1973. <li>Outbound federation</li>
  1974. <li>Downloading remote media</li>
  1975. <li>Fetching public keys of other servers</li>
  1976. </ul>
  1977. <p>These requests use the same proxy configuration. If you have a proxy configuration we
  1978. recommend to verify the configuration. It may be necessary to adjust the <code>no_proxy</code>
  1979. environment variable.</p>
  1980. <p>See <a href="setup/forward_proxy.html">using a forward proxy with Synapse documentation</a> for
  1981. details.</p>
  1982. <h2 id="deprecation-of-template_dir"><a class="header" href="#deprecation-of-template_dir">Deprecation of <code>template_dir</code></a></h2>
  1983. <p>The <code>template_dir</code> settings in the <code>sso</code>, <code>account_validity</code> and <code>email</code> sections of the
  1984. configuration file are now deprecated. Server admins should use the new
  1985. <code>templates.custom_template_directory</code> setting in the configuration file and use one single
  1986. custom template directory for all aforementioned features. Template file names remain
  1987. unchanged. See <a href="https://matrix-org.github.io/synapse/latest/templates.html">the related documentation</a>
  1988. for more information and examples.</p>
  1989. <p>We plan to remove support for these settings in October 2021.</p>
  1990. <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>
  1991. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#synapseappmedia_repository">media repository worker documentation</a>
  1992. has been updated to reflect that calls to <code>/_synapse/admin/v1/users/{userId}/media</code>
  1993. must now be handled by media repository workers. This is due to the new <code>DELETE</code> method
  1994. of this endpoint modifying the media store.</p>
  1995. <h1 id="upgrading-to-v1390"><a class="header" href="#upgrading-to-v1390">Upgrading to v1.39.0</a></h1>
  1996. <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>
  1997. <p>The current third-party rules module interface is deprecated in favour of the new generic
  1998. modules system introduced in Synapse v1.37.0. Authors of third-party rules modules can refer
  1999. to <a href="modules/porting_legacy_module.html">this documentation</a>
  2000. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this documentation</a>
  2001. to update their configuration once the modules they are using have been updated.</p>
  2002. <p>We plan to remove support for the current third-party rules interface in September 2021.</p>
  2003. <h1 id="upgrading-to-v1380"><a class="header" href="#upgrading-to-v1380">Upgrading to v1.38.0</a></h1>
  2004. <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>
  2005. <p>This release includes a database schema update which requires re-indexing one of
  2006. the larger tables in the database, <code>events</code>. This could result in increased
  2007. disk I/O for several hours or days after upgrading while the migration
  2008. completes. Furthermore, because we have to keep the old indexes until the new
  2009. indexes are ready, it could result in a significant, temporary, increase in
  2010. disk space.</p>
  2011. <p>To get a rough idea of the disk space required, check the current size of one
  2012. of the indexes. For example, from a <code>psql</code> shell, run the following sql:</p>
  2013. <pre><code class="language-sql">SELECT pg_size_pretty(pg_relation_size('events_order_room'));
  2014. </code></pre>
  2015. <p>We need to rebuild <strong>four</strong> indexes, so you will need to multiply this result
  2016. by four to give an estimate of the disk space required. For example, on one
  2017. particular server:</p>
  2018. <pre><code>synapse=# select pg_size_pretty(pg_relation_size('events_order_room'));
  2019. pg_size_pretty
  2020. ----------------
  2021. 288 MB
  2022. (1 row)
  2023. </code></pre>
  2024. <p>On this server, it would be wise to ensure that at least 1152MB are free.</p>
  2025. <p>The additional disk space will be freed once the migration completes.</p>
  2026. <p>SQLite databases are unaffected by this change.</p>
  2027. <h1 id="upgrading-to-v1370"><a class="header" href="#upgrading-to-v1370">Upgrading to v1.37.0</a></h1>
  2028. <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>
  2029. <p>The current spam checker interface is deprecated in favour of a new generic modules system.
  2030. Authors of spam checker modules can refer to [this
  2031. documentation](modules/porting_legacy_module.md
  2032. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this
  2033. documentation</a>
  2034. to update their configuration once the modules they are using have been updated.</p>
  2035. <p>We plan to remove support for the current spam checker interface in August 2021.</p>
  2036. <p>More module interfaces will be ported over to this new generic system in future versions
  2037. of Synapse.</p>
  2038. <h1 id="upgrading-to-v1340"><a class="header" href="#upgrading-to-v1340">Upgrading to v1.34.0</a></h1>
  2039. <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>
  2040. <p>The <code>room_invite_state_types</code> configuration setting has been deprecated
  2041. 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
  2042. file</a>.</p>
  2043. <p>If you have set <code>room_invite_state_types</code> to the default value you
  2044. should simply remove it from your configuration file. The default value
  2045. used to be:</p>
  2046. <pre><code class="language-yaml">room_invite_state_types:
  2047. - &quot;m.room.join_rules&quot;
  2048. - &quot;m.room.canonical_alias&quot;
  2049. - &quot;m.room.avatar&quot;
  2050. - &quot;m.room.encryption&quot;
  2051. - &quot;m.room.name&quot;
  2052. </code></pre>
  2053. <p>If you have customised this value, you should remove
  2054. <code>room_invite_state_types</code> and configure <code>room_prejoin_state</code> instead.</p>
  2055. <h1 id="upgrading-to-v1330"><a class="header" href="#upgrading-to-v1330">Upgrading to v1.33.0</a></h1>
  2056. <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>
  2057. <p>This may affect you if you have enabled the account validity feature,
  2058. and have made use of a custom HTML template specified by the
  2059. <code>account_validity.template_dir</code> or
  2060. <code>account_validity.account_renewed_html_path</code> Synapse config options.</p>
  2061. <p>The template can now accept an <code>expiration_ts</code> variable, which
  2062. represents the unix timestamp in milliseconds for the future date of
  2063. 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
  2064. template</a>
  2065. for an example of usage.</p>
  2066. <p>ALso note that a new HTML template, <code>account_previously_renewed.html</code>,
  2067. has been added. This is is shown to users when they attempt to renew
  2068. their account with a valid renewal token that has already been used
  2069. before. The default template contents can been found
  2070. <a href="https://github.com/matrix-org/synapse/blob/release-v1.33.0/synapse/res/templates/account_previously_renewed.html">here</a>,
  2071. and can also accept an <code>expiration_ts</code> variable. This template replaces
  2072. the error message users would previously see upon attempting to use a
  2073. valid renewal token more than once.</p>
  2074. <h1 id="upgrading-to-v1320"><a class="header" href="#upgrading-to-v1320">Upgrading to v1.32.0</a></h1>
  2075. <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>
  2076. <p>This release introduces <a href="https://github.com/matrix-org/synapse/issues/9853">a
  2077. regression</a> that can
  2078. overwhelm connected Prometheus instances. This issue is not present in
  2079. Synapse v1.32.0rc1.</p>
  2080. <p>If you have been affected, please downgrade to 1.31.0. You then may need
  2081. to remove excess writeahead logs in order for Prometheus to recover.
  2082. Instructions for doing so are provided
  2083. <a href="https://github.com/matrix-org/synapse/pull/9854#issuecomment-823472183">here</a>.</p>
  2084. <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>
  2085. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  2086. we've dropped support for Python 3.5 and PostgreSQL 9.5, as they are no
  2087. longer supported upstream.</p>
  2088. <p>This release of Synapse requires Python 3.6+ and PostgresSQL 9.6+ or
  2089. SQLite 3.22+.</p>
  2090. <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>
  2091. <p>The deprecated v1 &quot;list accounts&quot; admin API
  2092. (<code>GET /_synapse/admin/v1/users/&lt;user_id&gt;</code>) has been removed in this
  2093. version.</p>
  2094. <p>The <a href="admin_api/user_admin_api.html#list-accounts">v2 list accounts API</a>
  2095. has been available since Synapse 1.7.0 (2019-12-13), and is accessible
  2096. under <code>GET /_synapse/admin/v2/users</code>.</p>
  2097. <p>The deprecation of the old endpoint was announced with Synapse 1.28.0
  2098. (released on 2021-02-25).</p>
  2099. <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>
  2100. <p>In compliance with the <a href="https://matrix.org/docs/spec/application_service/r0.1.2#server-admin-style-permissions">Application Service
  2101. spec</a>,
  2102. Application Services are now required to use the
  2103. <code>m.login.application_service</code> type when registering users via the
  2104. <code>/_matrix/client/r0/register</code> endpoint. This behaviour was deprecated in
  2105. Synapse v1.30.0.</p>
  2106. <p>Please ensure your Application Services are up to date.</p>
  2107. <h1 id="upgrading-to-v1290"><a class="header" href="#upgrading-to-v1290">Upgrading to v1.29.0</a></h1>
  2108. <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>
  2109. <p>When using Synapse with a reverse proxy (in particular, when using the
  2110. <code>x_forwarded</code> option on an HTTP listener), Synapse now
  2111. expects to receive an <code>X-Forwarded-Proto</code> header on incoming
  2112. HTTP requests. If it is not set, Synapse will log a warning on each
  2113. received request.</p>
  2114. <p>To avoid the warning, administrators using a reverse proxy should ensure
  2115. that the reverse proxy sets <code>X-Forwarded-Proto</code> header to
  2116. <code>https</code> or <code>http</code> to indicate the protocol used
  2117. by the client.</p>
  2118. <p>Synapse also requires the <code>Host</code> header to be preserved.</p>
  2119. <p>See the <a href="reverse_proxy.html">reverse proxy documentation</a>, where the
  2120. example configurations have been updated to show how to set these
  2121. headers.</p>
  2122. <p>(Users of <a href="https://caddyserver.com/">Caddy</a> are unaffected, since we
  2123. believe it sets <code>X-Forwarded-Proto</code> by default.)</p>
  2124. <h1 id="upgrading-to-v1270"><a class="header" href="#upgrading-to-v1270">Upgrading to v1.27.0</a></h1>
  2125. <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>
  2126. <p>This version changes the URI used for callbacks from OAuth2 and SAML2
  2127. identity providers:</p>
  2128. <ul>
  2129. <li>
  2130. <p>If your server is configured for single sign-on via an OpenID
  2131. Connect or OAuth2 identity provider, you will need to add
  2132. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> to the list
  2133. of permitted &quot;redirect URIs&quot; at the identity provider.</p>
  2134. <p>See the <a href="openid.html">OpenID docs</a> for more information on setting
  2135. up OpenID Connect.</p>
  2136. </li>
  2137. <li>
  2138. <p>If your server is configured for single sign-on via a SAML2 identity
  2139. provider, you will need to add
  2140. <code>[synapse public baseurl]/_synapse/client/saml2/authn_response</code> as a
  2141. permitted &quot;ACS location&quot; (also known as &quot;allowed callback URLs&quot;)
  2142. at the identity provider.</p>
  2143. <p>The &quot;Issuer&quot; in the &quot;AuthnRequest&quot; to the SAML2 identity
  2144. provider is also updated to
  2145. <code>[synapse public baseurl]/_synapse/client/saml2/metadata.xml</code>. If
  2146. your SAML2 identity provider uses this property to validate or
  2147. otherwise identify Synapse, its configuration will need to be
  2148. updated to use the new URL. Alternatively you could create a new,
  2149. separate &quot;EntityDescriptor&quot; in your SAML2 identity provider with
  2150. the new URLs and leave the URLs in the existing &quot;EntityDescriptor&quot;
  2151. as they were.</p>
  2152. </li>
  2153. </ul>
  2154. <h2 id="changes-to-html-templates"><a class="header" href="#changes-to-html-templates">Changes to HTML templates</a></h2>
  2155. <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
  2156. autoescape</a>
  2157. enabled for files ending in <code>.html</code>, <code>.htm</code>, and <code>.xml</code>. If you have
  2158. customised these templates and see issues when viewing them you might
  2159. need to update them. It is expected that most configurations will need
  2160. no changes.</p>
  2161. <p>If you have customised the templates <em>names</em> for these templates, it is
  2162. recommended to verify they end in <code>.html</code> to ensure autoescape is
  2163. enabled.</p>
  2164. <p>The above applies to the following templates:</p>
  2165. <ul>
  2166. <li><code>add_threepid.html</code></li>
  2167. <li><code>add_threepid_failure.html</code></li>
  2168. <li><code>add_threepid_success.html</code></li>
  2169. <li><code>notice_expiry.html</code></li>
  2170. <li><code>notice_expiry.html</code></li>
  2171. <li><code>notif_mail.html</code> (which, by default, includes <code>room.html</code> and
  2172. <code>notif.html</code>)</li>
  2173. <li><code>password_reset.html</code></li>
  2174. <li><code>password_reset_confirmation.html</code></li>
  2175. <li><code>password_reset_failure.html</code></li>
  2176. <li><code>password_reset_success.html</code></li>
  2177. <li><code>registration.html</code></li>
  2178. <li><code>registration_failure.html</code></li>
  2179. <li><code>registration_success.html</code></li>
  2180. <li><code>sso_account_deactivated.html</code></li>
  2181. <li><code>sso_auth_bad_user.html</code></li>
  2182. <li><code>sso_auth_confirm.html</code></li>
  2183. <li><code>sso_auth_success.html</code></li>
  2184. <li><code>sso_error.html</code></li>
  2185. <li><code>sso_login_idp_picker.html</code></li>
  2186. <li><code>sso_redirect_confirm.html</code></li>
  2187. </ul>
  2188. <h1 id="upgrading-to-v1260"><a class="header" href="#upgrading-to-v1260">Upgrading to v1.26.0</a></h1>
  2189. <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>
  2190. <p>v1.26.0 includes a lot of large changes. If something problematic
  2191. occurs, you may want to roll-back to a previous version of Synapse.
  2192. Because v1.26.0 also includes a new database schema version, reverting
  2193. that version is also required alongside the generic rollback
  2194. instructions mentioned above. In short, to roll back to v1.25.0 you need
  2195. to:</p>
  2196. <ol>
  2197. <li>
  2198. <p>Stop the server</p>
  2199. </li>
  2200. <li>
  2201. <p>Decrease the schema version in the database:</p>
  2202. <pre><code class="language-sql">UPDATE schema_version SET version = 58;
  2203. </code></pre>
  2204. </li>
  2205. <li>
  2206. <p>Delete the ignored users &amp; chain cover data:</p>
  2207. <pre><code class="language-sql">DROP TABLE IF EXISTS ignored_users;
  2208. UPDATE rooms SET has_auth_chain_index = false;
  2209. </code></pre>
  2210. <p>For PostgreSQL run:</p>
  2211. <pre><code class="language-sql">TRUNCATE event_auth_chain_links;
  2212. TRUNCATE event_auth_chains;
  2213. </code></pre>
  2214. <p>For SQLite run:</p>
  2215. <pre><code class="language-sql">DELETE FROM event_auth_chain_links;
  2216. DELETE FROM event_auth_chains;
  2217. </code></pre>
  2218. </li>
  2219. <li>
  2220. <p>Mark the deltas as not run (so they will re-run on upgrade).</p>
  2221. <pre><code class="language-sql">DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/01ignored_user.py&quot;;
  2222. DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/06chain_cover_index.sql&quot;;
  2223. </code></pre>
  2224. </li>
  2225. <li>
  2226. <p>Downgrade Synapse by following the instructions for your
  2227. installation method in the &quot;Rolling back to older versions&quot;
  2228. section above.</p>
  2229. </li>
  2230. </ol>
  2231. <h1 id="upgrading-to-v1250"><a class="header" href="#upgrading-to-v1250">Upgrading to v1.25.0</a></h1>
  2232. <h2 id="last-release-supporting-python-35"><a class="header" href="#last-release-supporting-python-35">Last release supporting Python 3.5</a></h2>
  2233. <p>This is the last release of Synapse which guarantees support with Python
  2234. 3.5, which passed its upstream End of Life date several months ago.</p>
  2235. <p>We will attempt to maintain support through March 2021, but without
  2236. guarantees.</p>
  2237. <p>In the future, Synapse will follow upstream schedules for ending support
  2238. of older versions of Python and PostgreSQL. Please upgrade to at least
  2239. Python 3.6 and PostgreSQL 9.6 as soon as possible.</p>
  2240. <h2 id="blacklisting-ip-ranges"><a class="header" href="#blacklisting-ip-ranges">Blacklisting IP ranges</a></h2>
  2241. <p>Synapse v1.25.0 includes new settings, <code>ip_range_blacklist</code> and
  2242. <code>ip_range_whitelist</code>, for controlling outgoing requests from Synapse for
  2243. federation, identity servers, push, and for checking key validity for
  2244. third-party invite events. The previous setting,
  2245. <code>federation_ip_range_blacklist</code>, is deprecated. The new
  2246. <code>ip_range_blacklist</code> defaults to private IP ranges if it is not defined.</p>
  2247. <p>If you have never customised <code>federation_ip_range_blacklist</code> it is
  2248. recommended that you remove that setting.</p>
  2249. <p>If you have customised <code>federation_ip_range_blacklist</code> you should update
  2250. the setting name to <code>ip_range_blacklist</code>.</p>
  2251. <p>If you have a custom push server that is reached via private IP space
  2252. you may need to customise <code>ip_range_blacklist</code> or <code>ip_range_whitelist</code>.</p>
  2253. <h1 id="upgrading-to-v1240"><a class="header" href="#upgrading-to-v1240">Upgrading to v1.24.0</a></h1>
  2254. <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>
  2255. <p>This release allows the OpenID Connect mapping provider to perform
  2256. normalisation of the localpart of the Matrix ID. This allows for the
  2257. mapping provider to specify different algorithms, instead of the
  2258. <a href="https://matrix.org/docs/spec/appendices#mapping-from-other-character-sets">default
  2259. way</a>.</p>
  2260. <p>If your Synapse configuration uses a custom mapping provider
  2261. (<code>oidc_config.user_mapping_provider.module</code> is specified and
  2262. not equal to
  2263. <code>synapse.handlers.oidc_handler.JinjaOidcMappingProvider</code>)
  2264. then you <em>must</em> ensure that <code>map_user_attributes</code> of the
  2265. mapping provider performs some normalisation of the
  2266. <code>localpart</code> returned. To match previous behaviour you can
  2267. use the <code>map_username_to_mxid_localpart</code> function provided
  2268. by Synapse. An example is shown below:</p>
  2269. <pre><code class="language-python">from synapse.types import map_username_to_mxid_localpart
  2270. class MyMappingProvider:
  2271. def map_user_attributes(self, userinfo, token):
  2272. # ... your custom logic ...
  2273. sso_user_id = ...
  2274. localpart = map_username_to_mxid_localpart(sso_user_id)
  2275. return {&quot;localpart&quot;: localpart}
  2276. </code></pre>
  2277. <h2 id="removal-historical-synapse-admin-api"><a class="header" href="#removal-historical-synapse-admin-api">Removal historical Synapse Admin API</a></h2>
  2278. <p>Historically, the Synapse Admin API has been accessible under:</p>
  2279. <ul>
  2280. <li><code>/_matrix/client/api/v1/admin</code></li>
  2281. <li><code>/_matrix/client/unstable/admin</code></li>
  2282. <li><code>/_matrix/client/r0/admin</code></li>
  2283. <li><code>/_synapse/admin/v1</code></li>
  2284. </ul>
  2285. <p>The endpoints with <code>/_matrix/client/*</code> prefixes have been removed as of
  2286. v1.24.0. The Admin API is now only accessible under:</p>
  2287. <ul>
  2288. <li><code>/_synapse/admin/v1</code></li>
  2289. </ul>
  2290. <p>The only exception is the <code>/admin/whois</code> endpoint, which is
  2291. <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
  2292. API</a>.</p>
  2293. <p>The deprecation of the old endpoints was announced with Synapse 1.20.0
  2294. (released on 2020-09-22) and makes it easier for homeserver admins to
  2295. lock down external access to the Admin API endpoints.</p>
  2296. <h1 id="upgrading-to-v1230"><a class="header" href="#upgrading-to-v1230">Upgrading to v1.23.0</a></h1>
  2297. <h2 id="structured-logging-configuration-breaking-changes"><a class="header" href="#structured-logging-configuration-breaking-changes">Structured logging configuration breaking changes</a></h2>
  2298. <p>This release deprecates use of the <code>structured: true</code> logging
  2299. configuration for structured logging. If your logging configuration
  2300. contains <code>structured: true</code> then it should be modified based on the
  2301. <a href="https://matrix-org.github.io/synapse/v1.56/structured_logging.html#upgrading-from-legacy-structured-logging-configuration">structured logging documentation</a>.</p>
  2302. <p>The <code>structured</code> and <code>drains</code> logging options are now deprecated and
  2303. should be replaced by standard logging configuration of <code>handlers</code> and
  2304. <code>formatters</code>.</p>
  2305. <p>A future will release of Synapse will make using <code>structured: true</code> an
  2306. error.</p>
  2307. <h1 id="upgrading-to-v1220"><a class="header" href="#upgrading-to-v1220">Upgrading to v1.22.0</a></h1>
  2308. <h2 id="thirdpartyeventrules-breaking-changes"><a class="header" href="#thirdpartyeventrules-breaking-changes">ThirdPartyEventRules breaking changes</a></h2>
  2309. <p>This release introduces a backwards-incompatible change to modules
  2310. making use of <code>ThirdPartyEventRules</code> in Synapse. If you make use of a
  2311. module defined under the <code>third_party_event_rules</code> config option, please
  2312. make sure it is updated to handle the below change:</p>
  2313. <p>The <code>http_client</code> argument is no longer passed to modules as they are
  2314. initialised. Instead, modules are expected to make use of the
  2315. <code>http_client</code> property on the <code>ModuleApi</code> class. Modules are now passed
  2316. a <code>module_api</code> argument during initialisation, which is an instance of
  2317. <code>ModuleApi</code>. <code>ModuleApi</code> instances have a <code>http_client</code> property which
  2318. acts the same as the <code>http_client</code> argument previously passed to
  2319. <code>ThirdPartyEventRules</code> modules.</p>
  2320. <h1 id="upgrading-to-v1210"><a class="header" href="#upgrading-to-v1210">Upgrading to v1.21.0</a></h1>
  2321. <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>
  2322. <p>The <a href="reverse_proxy.html">reverse proxy documentation</a>
  2323. has been updated to include reverse proxy directives for
  2324. <code>/_synapse/client/*</code> endpoints. As the user password reset flow now uses
  2325. endpoints under this prefix, <strong>you must update your reverse proxy
  2326. configurations for user password reset to work</strong>.</p>
  2327. <p>Additionally, note that the <a href="workers.html">Synapse worker documentation</a> has been updated to</p>
  2328. <p>: state that the <code>/_synapse/client/password_reset/email/submit_token</code>
  2329. endpoint can be handled</p>
  2330. <p>by all workers. If you make use of Synapse's worker feature, please
  2331. update your reverse proxy configuration to reflect this change.</p>
  2332. <h2 id="new-html-templates"><a class="header" href="#new-html-templates">New HTML templates</a></h2>
  2333. <p>A new HTML template,
  2334. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/res/templates/password_reset_confirmation.html">password_reset_confirmation.html</a>,
  2335. has been added to the <code>synapse/res/templates</code> directory. If you are
  2336. using a custom template directory, you may want to copy the template
  2337. over and modify it.</p>
  2338. <p>Note that as of v1.20.0, templates do not need to be included in custom
  2339. template directories for Synapse to start. The default templates will be
  2340. used if a custom template cannot be found.</p>
  2341. <p>This page will appear to the user after clicking a password reset link
  2342. that has been emailed to them.</p>
  2343. <p>To complete password reset, the page must include a way to make a
  2344. <code>POST</code> request to
  2345. <code>/_synapse/client/password_reset/{medium}/submit_token</code> with the query
  2346. parameters from the original link, presented as a URL-encoded form. See
  2347. the file itself for more details.</p>
  2348. <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>
  2349. <p>The <code>saml_error.html</code> template was removed from Synapse and replaced
  2350. with the <code>sso_error.html</code> template. If your Synapse is configured to use
  2351. SAML and a custom <code>sso_redirect_confirm_template_dir</code> configuration then
  2352. any customisations of the <code>saml_error.html</code> template will need to be
  2353. merged into the <code>sso_error.html</code> template. These templates are similar,
  2354. but the parameters are slightly different:</p>
  2355. <ul>
  2356. <li>The <code>msg</code> parameter should be renamed to <code>error_description</code>.</li>
  2357. <li>There is no longer a <code>code</code> parameter for the response code.</li>
  2358. <li>A string <code>error</code> parameter is available that includes a short hint
  2359. of why a user is seeing the error page.</li>
  2360. </ul>
  2361. <h1 id="upgrading-to-v1180"><a class="header" href="#upgrading-to-v1180">Upgrading to v1.18.0</a></h1>
  2362. <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>
  2363. <p>From 10th August 2020, we will no longer publish Docker images with the
  2364. <code>-py3</code> tag suffix. The images tagged with the
  2365. <code>-py3</code> suffix have been identical to the non-suffixed tags
  2366. since release 0.99.0, and the suffix is obsolete.</p>
  2367. <p>On 10th August, we will remove the <code>latest-py3</code> tag.
  2368. Existing per-release tags (such as <code>v1.18.0-py3</code> will not
  2369. be removed, but no new <code>-py3</code> tags will be added.</p>
  2370. <p>Scripts relying on the <code>-py3</code> suffix will need to be
  2371. updated.</p>
  2372. <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>
  2373. <p>When setting up worker processes, we now recommend the use of a Redis
  2374. server for replication. <strong>The old direct TCP connection method is
  2375. deprecated and will be removed in a future release.</strong> See
  2376. <a href="workers.html">workers</a> for more details.</p>
  2377. <h1 id="upgrading-to-v1140"><a class="header" href="#upgrading-to-v1140">Upgrading to v1.14.0</a></h1>
  2378. <p>This version includes a database update which is run as part of the
  2379. upgrade, and which may take a couple of minutes in the case of a large
  2380. server. Synapse will not respond to HTTP requests while this update is
  2381. taking place.</p>
  2382. <h1 id="upgrading-to-v1130"><a class="header" href="#upgrading-to-v1130">Upgrading to v1.13.0</a></h1>
  2383. <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>
  2384. <p>A bug was introduced in Synapse 1.4.0 which could cause the room
  2385. directory to be incomplete or empty if Synapse was upgraded directly
  2386. from v1.2.1 or earlier, to versions between v1.4.0 and v1.12.x.</p>
  2387. <p>This will <em>not</em> be a problem for Synapse installations which were:</p>
  2388. <p>: - created at v1.4.0 or later,
  2389. - upgraded via v1.3.x, or
  2390. - upgraded straight from v1.2.1 or earlier to v1.13.0 or later.</p>
  2391. <p>If completeness of the room directory is a concern, installations which
  2392. are affected can be repaired as follows:</p>
  2393. <ol>
  2394. <li>
  2395. <p>Run the following sql from a <code>psql</code> or
  2396. <code>sqlite3</code> console:</p>
  2397. <pre><code class="language-sql">INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2398. ('populate_stats_process_rooms', '{}', 'current_state_events_membership');
  2399. INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2400. ('populate_stats_process_users', '{}', 'populate_stats_process_rooms');
  2401. </code></pre>
  2402. </li>
  2403. <li>
  2404. <p>Restart synapse.</p>
  2405. </li>
  2406. </ol>
  2407. <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>
  2408. <p>New templates (<code>sso_auth_confirm.html</code>, <code>sso_auth_success.html</code>, and
  2409. <code>sso_account_deactivated.html</code>) were added to Synapse. If your Synapse
  2410. is configured to use SSO and a custom
  2411. <code>sso_redirect_confirm_template_dir</code> configuration then these templates
  2412. will need to be copied from
  2413. <a href="synapse/res/templates">synapse/res/templates</a> into that directory.</p>
  2414. <h2 id="synapse-sso-plugins-method-deprecation"><a class="header" href="#synapse-sso-plugins-method-deprecation">Synapse SSO Plugins Method Deprecation</a></h2>
  2415. <p>Plugins using the <code>complete_sso_login</code> method of
  2416. <code>synapse.module_api.ModuleApi</code> should update to using the async/await
  2417. version <code>complete_sso_login_async</code> which includes additional checks. The
  2418. non-async version is considered deprecated.</p>
  2419. <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>
  2420. <p>v1.13.0 includes a lot of large changes. If something problematic
  2421. occurs, you may want to roll-back to a previous version of Synapse.
  2422. Because v1.13.0 also includes a new database schema version, reverting
  2423. that version is also required alongside the generic rollback
  2424. instructions mentioned above. In short, to roll back to v1.12.4 you need
  2425. to:</p>
  2426. <ol>
  2427. <li>
  2428. <p>Stop the server</p>
  2429. </li>
  2430. <li>
  2431. <p>Decrease the schema version in the database:</p>
  2432. <pre><code class="language-sql">UPDATE schema_version SET version = 57;
  2433. </code></pre>
  2434. </li>
  2435. <li>
  2436. <p>Downgrade Synapse by following the instructions for your
  2437. installation method in the &quot;Rolling back to older versions&quot;
  2438. section above.</p>
  2439. </li>
  2440. </ol>
  2441. <h1 id="upgrading-to-v1120"><a class="header" href="#upgrading-to-v1120">Upgrading to v1.12.0</a></h1>
  2442. <p>This version includes a database update which is run as part of the
  2443. upgrade, and which may take some time (several hours in the case of a
  2444. large server). Synapse will not respond to HTTP requests while this
  2445. update is taking place.</p>
  2446. <p>This is only likely to be a problem in the case of a server which is
  2447. participating in many rooms.</p>
  2448. <ol start="0">
  2449. <li>
  2450. <p>As with all upgrades, it is recommended that you have a recent
  2451. backup of your database which can be used for recovery in the event
  2452. of any problems.</p>
  2453. </li>
  2454. <li>
  2455. <p>As an initial check to see if you will be affected, you can try
  2456. running the following query from the <code>psql</code> or
  2457. <code>sqlite3</code> console. It is safe to run it while Synapse is
  2458. still running.</p>
  2459. <pre><code class="language-sql">SELECT MAX(q.v) FROM (
  2460. SELECT (
  2461. SELECT ej.json AS v
  2462. FROM state_events se INNER JOIN event_json ej USING (event_id)
  2463. WHERE se.room_id=rooms.room_id AND se.type='m.room.create' AND se.state_key=''
  2464. LIMIT 1
  2465. ) FROM rooms WHERE rooms.room_version IS NULL
  2466. ) q;
  2467. </code></pre>
  2468. <p>This query will take about the same amount of time as the upgrade
  2469. process: ie, if it takes 5 minutes, then it is likely that Synapse
  2470. will be unresponsive for 5 minutes during the upgrade.</p>
  2471. <p>If you consider an outage of this duration to be acceptable, no
  2472. further action is necessary and you can simply start Synapse 1.12.0.</p>
  2473. <p>If you would prefer to reduce the downtime, continue with the steps
  2474. below.</p>
  2475. </li>
  2476. <li>
  2477. <p>The easiest workaround for this issue is to manually create a new
  2478. index before upgrading. On PostgreSQL, his can be done as follows:</p>
  2479. <pre><code class="language-sql">CREATE INDEX CONCURRENTLY tmp_upgrade_1_12_0_index
  2480. ON state_events(room_id) WHERE type = 'm.room.create';
  2481. </code></pre>
  2482. <p>The above query may take some time, but is also safe to run while
  2483. Synapse is running.</p>
  2484. <p>We assume that no SQLite users have databases large enough to be
  2485. affected. If you <em>are</em> affected, you can run a similar query,
  2486. omitting the <code>CONCURRENTLY</code> keyword. Note however that this
  2487. operation may in itself cause Synapse to stop running for some time.
  2488. Synapse admins are reminded that <a href="postgres.html">SQLite is not recommended for use
  2489. outside a test environment</a>.</p>
  2490. </li>
  2491. <li>
  2492. <p>Once the index has been created, the <code>SELECT</code> query in step 1 above
  2493. should complete quickly. It is therefore safe to upgrade to Synapse
  2494. 1.12.0.</p>
  2495. </li>
  2496. <li>
  2497. <p>Once Synapse 1.12.0 has successfully started and is responding to
  2498. HTTP requests, the temporary index can be removed:</p>
  2499. <pre><code class="language-sql">DROP INDEX tmp_upgrade_1_12_0_index;
  2500. </code></pre>
  2501. </li>
  2502. </ol>
  2503. <h1 id="upgrading-to-v1100"><a class="header" href="#upgrading-to-v1100">Upgrading to v1.10.0</a></h1>
  2504. <p>Synapse will now log a warning on start up if used with a PostgreSQL
  2505. database that has a non-recommended locale set.</p>
  2506. <p>See <a href="postgres.html">Postgres</a> for details.</p>
  2507. <h1 id="upgrading-to-v180"><a class="header" href="#upgrading-to-v180">Upgrading to v1.8.0</a></h1>
  2508. <p>Specifying a <code>log_file</code> config option will now cause Synapse to refuse
  2509. to start, and should be replaced by with the <code>log_config</code> option.
  2510. Support for the <code>log_file</code> option was removed in v1.3.0 and has since
  2511. had no effect.</p>
  2512. <h1 id="upgrading-to-v170"><a class="header" href="#upgrading-to-v170">Upgrading to v1.7.0</a></h1>
  2513. <p>In an attempt to configure Synapse in a privacy preserving way, the
  2514. default behaviours of <code>allow_public_rooms_without_auth</code> and
  2515. <code>allow_public_rooms_over_federation</code> have been inverted. This means that
  2516. by default, only authenticated users querying the Client/Server API will
  2517. be able to query the room directory, and relatedly that the server will
  2518. not share room directory information with other servers over federation.</p>
  2519. <p>If your installation does not explicitly set these settings one way or
  2520. the other and you want either setting to be <code>true</code> then it will
  2521. necessary to update your homeserver configuration file accordingly.</p>
  2522. <p>For more details on the surrounding context see our
  2523. <a href="https://matrix.org/blog/2019/11/09/avoiding-unwelcome-visitors-on-private-matrix-servers">explainer</a>.</p>
  2524. <h1 id="upgrading-to-v150"><a class="header" href="#upgrading-to-v150">Upgrading to v1.5.0</a></h1>
  2525. <p>This release includes a database migration which may take several
  2526. minutes to complete if there are a large number (more than a million or
  2527. so) of entries in the <code>devices</code> table. This is only likely to a be a
  2528. problem on very large installations.</p>
  2529. <h1 id="upgrading-to-v140"><a class="header" href="#upgrading-to-v140">Upgrading to v1.4.0</a></h1>
  2530. <h2 id="new-custom-templates"><a class="header" href="#new-custom-templates">New custom templates</a></h2>
  2531. <p>If you have configured a custom template directory with the
  2532. <code>email.template_dir</code> option, be aware that there are new templates
  2533. regarding registration and threepid management (see below) that must be
  2534. included.</p>
  2535. <ul>
  2536. <li><code>registration.html</code> and <code>registration.txt</code></li>
  2537. <li><code>registration_success.html</code> and <code>registration_failure.html</code></li>
  2538. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code></li>
  2539. <li><code>add_threepid_failure.html</code> and <code>add_threepid_success.html</code></li>
  2540. </ul>
  2541. <p>Synapse will expect these files to exist inside the configured template
  2542. directory, and <strong>will fail to start</strong> if they are absent. To view the
  2543. default templates, see
  2544. <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">synapse/res/templates</a>.</p>
  2545. <h2 id="3pid-verification-changes"><a class="header" href="#3pid-verification-changes">3pid verification changes</a></h2>
  2546. <p><strong>Note: As of this release, users will be unable to add phone numbers or
  2547. email addresses to their accounts, without changes to the Synapse
  2548. configuration. This includes adding an email address during
  2549. registration.</strong></p>
  2550. <p>It is possible for a user to associate an email address or phone number
  2551. with their account, for a number of reasons:</p>
  2552. <ul>
  2553. <li>for use when logging in, as an alternative to the user id.</li>
  2554. <li>in the case of email, as an alternative contact to help with account
  2555. recovery.</li>
  2556. <li>in the case of email, to receive notifications of missed messages.</li>
  2557. </ul>
  2558. <p>Before an email address or phone number can be added to a user's
  2559. account, or before such an address is used to carry out a
  2560. password-reset, Synapse must confirm the operation with the owner of the
  2561. email address or phone number. It does this by sending an email or text
  2562. giving the user a link or token to confirm receipt. This process is
  2563. known as '3pid verification'. ('3pid', or 'threepid', stands for
  2564. third-party identifier, and we use it to refer to external identifiers
  2565. such as email addresses and phone numbers.)</p>
  2566. <p>Previous versions of Synapse delegated the task of 3pid verification to
  2567. an identity server by default. In most cases this server is <code>vector.im</code>
  2568. or <code>matrix.org</code>.</p>
  2569. <p>In Synapse 1.4.0, for security and privacy reasons, the homeserver will
  2570. no longer delegate this task to an identity server by default. Instead,
  2571. the server administrator will need to explicitly decide how they would
  2572. like the verification messages to be sent.</p>
  2573. <p>In the medium term, the <code>vector.im</code> and <code>matrix.org</code> identity servers
  2574. will disable support for delegated 3pid verification entirely. However,
  2575. in order to ease the transition, they will retain the capability for a
  2576. limited period. Delegated email verification will be disabled on Monday
  2577. 2nd December 2019 (giving roughly 2 months notice). Disabling delegated
  2578. SMS verification will follow some time after that once SMS verification
  2579. support lands in Synapse.</p>
  2580. <p>Once delegated 3pid verification support has been disabled in the
  2581. <code>vector.im</code> and <code>matrix.org</code> identity servers, all Synapse versions that
  2582. depend on those instances will be unable to verify email and phone
  2583. numbers through them. There are no imminent plans to remove delegated
  2584. 3pid verification from Sydent generally. (Sydent is the identity server
  2585. project that backs the <code>vector.im</code> and <code>matrix.org</code> instances).</p>
  2586. <h3 id="email-1"><a class="header" href="#email-1">Email</a></h3>
  2587. <p>Following upgrade, to continue verifying email (e.g. as part of the
  2588. registration process), admins can either:-</p>
  2589. <ul>
  2590. <li>Configure Synapse to use an email server.</li>
  2591. <li>Run or choose an identity server which allows delegated email
  2592. verification and delegate to it.</li>
  2593. </ul>
  2594. <h4 id="configure-smtp-in-synapse"><a class="header" href="#configure-smtp-in-synapse">Configure SMTP in Synapse</a></h4>
  2595. <p>To configure an SMTP server for Synapse, modify the configuration
  2596. section headed <code>email</code>, and be sure to have at least the
  2597. <code>smtp_host, smtp_port</code> and <code>notif_from</code> fields filled out.</p>
  2598. <p>You may also need to set <code>smtp_user</code>, <code>smtp_pass</code>, and
  2599. <code>require_transport_security</code>.</p>
  2600. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2601. for more details on these settings.</p>
  2602. <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>
  2603. <p>Some admins will wish to continue using email verification as part of
  2604. the registration process, but will not immediately have an appropriate
  2605. SMTP server at hand.</p>
  2606. <p>To this end, we will continue to support email verification delegation
  2607. via the <code>vector.im</code> and <code>matrix.org</code> identity servers for two months.
  2608. Support for delegated email verification will be disabled on Monday 2nd
  2609. December.</p>
  2610. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  2611. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  2612. server</a>) to handle
  2613. sending confirmation messages via email and SMS.</p>
  2614. <p>So to delegate email verification, in <code>homeserver.yaml</code>, set
  2615. <code>account_threepid_delegates.email</code> to the base URL of an identity
  2616. server. For example:</p>
  2617. <pre><code class="language-yaml">account_threepid_delegates:
  2618. email: https://example.com # Delegate email sending to example.com
  2619. </code></pre>
  2620. <p>Note that <code>account_threepid_delegates.email</code> replaces the deprecated
  2621. <code>email.trust_identity_server_for_password_resets</code>: if
  2622. <code>email.trust_identity_server_for_password_resets</code> is set to <code>true</code>, and
  2623. <code>account_threepid_delegates.email</code> is not set, then the first entry in
  2624. <code>trusted_third_party_id_servers</code> will be used as the
  2625. <code>account_threepid_delegate</code> for email. This is to ensure compatibility
  2626. with existing Synapse installs that set up external server handling for
  2627. these tasks before v1.4.0. If
  2628. <code>email.trust_identity_server_for_password_resets</code> is <code>true</code> and no
  2629. trusted identity server domains are configured, Synapse will report an
  2630. error and refuse to start.</p>
  2631. <p>If <code>email.trust_identity_server_for_password_resets</code> is <code>false</code> or
  2632. absent and no <code>email</code> delegate is configured in
  2633. <code>account_threepid_delegates</code>, then Synapse will send email verification
  2634. messages itself, using the configured SMTP server (see above). that
  2635. type.</p>
  2636. <h3 id="phone-numbers"><a class="header" href="#phone-numbers">Phone numbers</a></h3>
  2637. <p>Synapse does not support phone-number verification itself, so the only
  2638. way to maintain the ability for users to add phone numbers to their
  2639. accounts will be by continuing to delegate phone number verification to
  2640. the <code>matrix.org</code> and <code>vector.im</code> identity servers (or another identity
  2641. server that supports SMS sending).</p>
  2642. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  2643. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  2644. server</a>) to handle
  2645. sending confirmation messages via email and SMS.</p>
  2646. <p>So to delegate phone number verification, in <code>homeserver.yaml</code>, set
  2647. <code>account_threepid_delegates.msisdn</code> to the base URL of an identity
  2648. server. For example:</p>
  2649. <pre><code class="language-yaml">account_threepid_delegates:
  2650. msisdn: https://example.com # Delegate sms sending to example.com
  2651. </code></pre>
  2652. <p>The <code>matrix.org</code> and <code>vector.im</code> identity servers will continue to
  2653. support delegated phone number verification via SMS until such time as
  2654. it is possible for admins to configure their servers to perform phone
  2655. number verification directly. More details will follow in a future
  2656. release.</p>
  2657. <h2 id="rolling-back-to-v131"><a class="header" href="#rolling-back-to-v131">Rolling back to v1.3.1</a></h2>
  2658. <p>If you encounter problems with v1.4.0, it should be possible to roll
  2659. back to v1.3.1, subject to the following:</p>
  2660. <ul>
  2661. <li>
  2662. <p>The 'room statistics' engine was heavily reworked in this release
  2663. (see <a href="https://github.com/matrix-org/synapse/pull/5971">#5971</a>),
  2664. including significant changes to the database schema, which are not
  2665. easily reverted. This will cause the room statistics engine to stop
  2666. updating when you downgrade.</p>
  2667. <p>The room statistics are essentially unused in v1.3.1 (in future
  2668. versions of Synapse, they will be used to populate the room
  2669. directory), so there should be no loss of functionality. However,
  2670. the statistics engine will write errors to the logs, which can be
  2671. avoided by setting the following in <code>homeserver.yaml</code>:</p>
  2672. <pre><code class="language-yaml">stats:
  2673. enabled: false
  2674. </code></pre>
  2675. <p>Don't forget to re-enable it when you upgrade again, in preparation
  2676. for its use in the room directory!</p>
  2677. </li>
  2678. </ul>
  2679. <h1 id="upgrading-to-v120"><a class="header" href="#upgrading-to-v120">Upgrading to v1.2.0</a></h1>
  2680. <p>Some counter metrics have been renamed, with the old names deprecated.
  2681. See <a href="metrics-howto.html#renaming-of-metrics--deprecation-of-old-names-in-12">the metrics
  2682. documentation</a>
  2683. for details.</p>
  2684. <h1 id="upgrading-to-v110"><a class="header" href="#upgrading-to-v110">Upgrading to v1.1.0</a></h1>
  2685. <p>Synapse v1.1.0 removes support for older Python and PostgreSQL versions,
  2686. as outlined in <a href="https://matrix.org/blog/2019/04/08/synapse-deprecating-postgres-9-4-and-python-2-x">our deprecation
  2687. notice</a>.</p>
  2688. <h2 id="minimum-python-version"><a class="header" href="#minimum-python-version">Minimum Python Version</a></h2>
  2689. <p>Synapse v1.1.0 has a minimum Python requirement of Python 3.5. Python
  2690. 3.6 or Python 3.7 are recommended as they have improved internal string
  2691. handling, significantly reducing memory usage.</p>
  2692. <p>If you use current versions of the Matrix.org-distributed Debian
  2693. packages or Docker images, action is not required.</p>
  2694. <p>If you install Synapse in a Python virtual environment, please see
  2695. &quot;Upgrading to v0.34.0&quot; for notes on setting up a new virtualenv under
  2696. Python 3.</p>
  2697. <h2 id="minimum-postgresql-version"><a class="header" href="#minimum-postgresql-version">Minimum PostgreSQL Version</a></h2>
  2698. <p>If using PostgreSQL under Synapse, you will need to use PostgreSQL 9.5
  2699. or above. Please see the <a href="https://www.postgresql.org/docs/11/upgrading.html">PostgreSQL
  2700. documentation</a> for
  2701. more details on upgrading your database.</p>
  2702. <h1 id="upgrading-to-v10"><a class="header" href="#upgrading-to-v10">Upgrading to v1.0</a></h1>
  2703. <h2 id="validation-of-tls-certificates"><a class="header" href="#validation-of-tls-certificates">Validation of TLS certificates</a></h2>
  2704. <p>Synapse v1.0 is the first release to enforce validation of TLS
  2705. certificates for the federation API. It is therefore essential that your
  2706. certificates are correctly configured.</p>
  2707. <p>Note, v1.0 installations will also no longer be able to federate with
  2708. servers that have not correctly configured their certificates.</p>
  2709. <p>In rare cases, it may be desirable to disable certificate checking: for
  2710. example, it might be essential to be able to federate with a given
  2711. legacy server in a closed federation. This can be done in one of two
  2712. ways:-</p>
  2713. <ul>
  2714. <li>Configure the global switch <code>federation_verify_certificates</code> to
  2715. <code>false</code>.</li>
  2716. <li>Configure a whitelist of server domains to trust via
  2717. <code>federation_certificate_verification_whitelist</code>.</li>
  2718. </ul>
  2719. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2720. for more details on these settings.</p>
  2721. <h2 id="email-2"><a class="header" href="#email-2">Email</a></h2>
  2722. <p>When a user requests a password reset, Synapse will send an email to the
  2723. user to confirm the request.</p>
  2724. <p>Previous versions of Synapse delegated the job of sending this email to
  2725. an identity server. If the identity server was somehow malicious or
  2726. became compromised, it would be theoretically possible to hijack an
  2727. account through this means.</p>
  2728. <p>Therefore, by default, Synapse v1.0 will send the confirmation email
  2729. itself. If Synapse is not configured with an SMTP server, password reset
  2730. via email will be disabled.</p>
  2731. <p>To configure an SMTP server for Synapse, modify the configuration
  2732. section headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>,
  2733. <code>smtp_port</code> and <code>notif_from</code> fields filled out. You may also need to set
  2734. <code>smtp_user</code>, <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  2735. <p>If you are absolutely certain that you wish to continue using an
  2736. identity server for password resets, set
  2737. <code>trust_identity_server_for_password_resets</code> to <code>true</code>.</p>
  2738. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2739. for more details on these settings.</p>
  2740. <h2 id="new-email-templates"><a class="header" href="#new-email-templates">New email templates</a></h2>
  2741. <p>Some new templates have been added to the default template directory for the purpose of
  2742. the homeserver sending its own password reset emails. If you have configured a
  2743. custom <code>template_dir</code> in your Synapse config, these files will need to be added.</p>
  2744. <p><code>password_reset.html</code> and <code>password_reset.txt</code> are HTML and plain text
  2745. templates respectively that contain the contents of what will be emailed
  2746. to the user upon attempting to reset their password via email.
  2747. <code>password_reset_success.html</code> and <code>password_reset_failure.html</code> are HTML
  2748. files that the content of which (assuming no redirect URL is set) will
  2749. be shown to the user after they attempt to click the link in the email
  2750. sent to them.</p>
  2751. <h1 id="upgrading-to-v0990"><a class="header" href="#upgrading-to-v0990">Upgrading to v0.99.0</a></h1>
  2752. <p>Please be aware that, before Synapse v1.0 is released around March 2019,
  2753. you will need to replace any self-signed certificates with those
  2754. verified by a root CA. Information on how to do so can be found at the
  2755. ACME docs.</p>
  2756. <h1 id="upgrading-to-v0340"><a class="header" href="#upgrading-to-v0340">Upgrading to v0.34.0</a></h1>
  2757. <ol>
  2758. <li>
  2759. <p>This release is the first to fully support Python 3. Synapse will
  2760. now run on Python versions 3.5, or 3.6 (as well as 2.7). We
  2761. recommend switching to Python 3, as it has been shown to give
  2762. performance improvements.</p>
  2763. <p>For users who have installed Synapse into a virtualenv, we recommend
  2764. doing this by creating a new virtualenv. For example:</p>
  2765. <pre><code class="language-sh">virtualenv -p python3 ~/synapse/env3
  2766. source ~/synapse/env3/bin/activate
  2767. pip install matrix-synapse
  2768. </code></pre>
  2769. <p>You can then start synapse as normal, having activated the new
  2770. virtualenv:</p>
  2771. <pre><code class="language-sh">cd ~/synapse
  2772. source env3/bin/activate
  2773. synctl start
  2774. </code></pre>
  2775. <p>Users who have installed from distribution packages should see the
  2776. relevant package documentation. See below for notes on Debian
  2777. packages.</p>
  2778. <ul>
  2779. <li>
  2780. <p>When upgrading to Python 3, you <strong>must</strong> make sure that your log
  2781. files are configured as UTF-8, by adding <code>encoding: utf8</code> to the
  2782. <code>RotatingFileHandler</code> configuration (if you have one) in your
  2783. <code>&lt;server&gt;.log.config</code> file. For example, if your <code>log.config</code>
  2784. file contains:</p>
  2785. <pre><code class="language-yaml">handlers:
  2786. file:
  2787. class: logging.handlers.RotatingFileHandler
  2788. formatter: precise
  2789. filename: homeserver.log
  2790. maxBytes: 104857600
  2791. backupCount: 10
  2792. filters: [context]
  2793. console:
  2794. class: logging.StreamHandler
  2795. formatter: precise
  2796. filters: [context]
  2797. </code></pre>
  2798. <p>Then you should update this to be:</p>
  2799. <pre><code class="language-yaml">handlers:
  2800. file:
  2801. class: logging.handlers.RotatingFileHandler
  2802. formatter: precise
  2803. filename: homeserver.log
  2804. maxBytes: 104857600
  2805. backupCount: 10
  2806. filters: [context]
  2807. encoding: utf8
  2808. console:
  2809. class: logging.StreamHandler
  2810. formatter: precise
  2811. filters: [context]
  2812. </code></pre>
  2813. <p>There is no need to revert this change if downgrading to
  2814. Python 2.</p>
  2815. </li>
  2816. </ul>
  2817. <p>We are also making available Debian packages which will run Synapse
  2818. on Python 3. You can switch to these packages with
  2819. <code>apt-get install matrix-synapse-py3</code>, however, please read
  2820. <a href="https://github.com/matrix-org/synapse/blob/release-v0.34.0/debian/NEWS">debian/NEWS</a>
  2821. before doing so. The existing <code>matrix-synapse</code> packages will
  2822. continue to use Python 2 for the time being.</p>
  2823. </li>
  2824. <li>
  2825. <p>This release removes the <code>riot.im</code> from the default list of trusted
  2826. identity servers.</p>
  2827. <p>If <code>riot.im</code> is in your homeserver's list of
  2828. <code>trusted_third_party_id_servers</code>, you should remove it. It was added
  2829. in case a hypothetical future identity server was put there. If you
  2830. don't remove it, users may be unable to deactivate their accounts.</p>
  2831. </li>
  2832. <li>
  2833. <p>This release no longer installs the (unmaintained) Matrix Console
  2834. web client as part of the default installation. It is possible to
  2835. re-enable it by installing it separately and setting the
  2836. <code>web_client_location</code> config option, but please consider switching
  2837. to another client.</p>
  2838. </li>
  2839. </ol>
  2840. <h1 id="upgrading-to-v0337"><a class="header" href="#upgrading-to-v0337">Upgrading to v0.33.7</a></h1>
  2841. <p>This release removes the example email notification templates from
  2842. <code>res/templates</code> (they are now internal to the python package). This
  2843. should only affect you if you (a) deploy your Synapse instance from a
  2844. git checkout or a github snapshot URL, and (b) have email notifications
  2845. enabled.</p>
  2846. <p>If you have email notifications enabled, you should ensure that
  2847. <code>email.template_dir</code> is either configured to point at a directory where
  2848. you have installed customised templates, or leave it unset to use the
  2849. default templates.</p>
  2850. <h1 id="upgrading-to-v0273"><a class="header" href="#upgrading-to-v0273">Upgrading to v0.27.3</a></h1>
  2851. <p>This release expands the anonymous usage stats sent if the opt-in
  2852. <code>report_stats</code> configuration is set to <code>true</code>. We now capture RSS memory
  2853. and cpu use at a very coarse level. This requires administrators to
  2854. install the optional <code>psutil</code> python module.</p>
  2855. <p>We would appreciate it if you could assist by ensuring this module is
  2856. available and <code>report_stats</code> is enabled. This will let us see if
  2857. performance changes to synapse are having an impact to the general
  2858. community.</p>
  2859. <h1 id="upgrading-to-v0150"><a class="header" href="#upgrading-to-v0150">Upgrading to v0.15.0</a></h1>
  2860. <p>If you want to use the new URL previewing API
  2861. (<code>/_matrix/media/r0/preview_url</code>) then you have to explicitly enable it
  2862. in the config and update your dependencies dependencies. See README.rst
  2863. for details.</p>
  2864. <h1 id="upgrading-to-v0110"><a class="header" href="#upgrading-to-v0110">Upgrading to v0.11.0</a></h1>
  2865. <p>This release includes the option to send anonymous usage stats to
  2866. matrix.org, and requires that administrators explictly opt in or out by
  2867. setting the <code>report_stats</code> option to either <code>true</code> or <code>false</code>.</p>
  2868. <p>We would really appreciate it if you could help our project out by
  2869. reporting anonymized usage statistics from your homeserver. Only very
  2870. basic aggregate data (e.g. number of users) will be reported, but it
  2871. helps us to track the growth of the Matrix community, and helps us to
  2872. make Matrix a success, as well as to convince other networks that they
  2873. should peer with us.</p>
  2874. <h1 id="upgrading-to-v090"><a class="header" href="#upgrading-to-v090">Upgrading to v0.9.0</a></h1>
  2875. <p>Application services have had a breaking API change in this version.</p>
  2876. <p>They can no longer register themselves with a home server using the AS
  2877. HTTP API. This decision was made because a compromised application
  2878. service with free reign to register any regex in effect grants full
  2879. read/write access to the home server if a regex of <code>.*</code> is used. An
  2880. attack where a compromised AS re-registers itself with <code>.*</code> was deemed
  2881. too big of a security risk to ignore, and so the ability to register
  2882. with the HS remotely has been removed.</p>
  2883. <p>It has been replaced by specifying a list of application service
  2884. registrations in <code>homeserver.yaml</code>:</p>
  2885. <pre><code class="language-yaml">app_service_config_files: [&quot;registration-01.yaml&quot;, &quot;registration-02.yaml&quot;]
  2886. </code></pre>
  2887. <p>Where <code>registration-01.yaml</code> looks like:</p>
  2888. <pre><code class="language-yaml">url: &lt;String&gt; # e.g. &quot;https://my.application.service.com&quot;
  2889. as_token: &lt;String&gt;
  2890. hs_token: &lt;String&gt;
  2891. sender_localpart: &lt;String&gt; # This is a new field which denotes the user_id localpart when using the AS token
  2892. namespaces:
  2893. users:
  2894. - exclusive: &lt;Boolean&gt;
  2895. regex: &lt;String&gt; # e.g. &quot;@prefix_.*&quot;
  2896. aliases:
  2897. - exclusive: &lt;Boolean&gt;
  2898. regex: &lt;String&gt;
  2899. rooms:
  2900. - exclusive: &lt;Boolean&gt;
  2901. regex: &lt;String&gt;
  2902. </code></pre>
  2903. <h1 id="upgrading-to-v080"><a class="header" href="#upgrading-to-v080">Upgrading to v0.8.0</a></h1>
  2904. <p>Servers which use captchas will need to add their public key to:</p>
  2905. <pre><code>static/client/register/register_config.js
  2906. window.matrixRegistrationConfig = {
  2907. recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  2908. };
  2909. </code></pre>
  2910. <p>This is required in order to support registration fallback (typically
  2911. used on mobile devices).</p>
  2912. <h1 id="upgrading-to-v070"><a class="header" href="#upgrading-to-v070">Upgrading to v0.7.0</a></h1>
  2913. <p>New dependencies are:</p>
  2914. <ul>
  2915. <li>pydenticon</li>
  2916. <li>simplejson</li>
  2917. <li>syutil</li>
  2918. <li>matrix-angular-sdk</li>
  2919. </ul>
  2920. <p>To pull in these dependencies in a virtual env, run:</p>
  2921. <pre><code>python synapse/python_dependencies.py | xargs -n 1 pip install
  2922. </code></pre>
  2923. <h1 id="upgrading-to-v060"><a class="header" href="#upgrading-to-v060">Upgrading to v0.6.0</a></h1>
  2924. <p>To pull in new dependencies, run:</p>
  2925. <pre><code>python setup.py develop --user
  2926. </code></pre>
  2927. <p>This update includes a change to the database schema. To upgrade you
  2928. first need to upgrade the database by running:</p>
  2929. <pre><code>python scripts/upgrade_db_to_v0.6.0.py &lt;db&gt; &lt;server_name&gt; &lt;signing_key&gt;
  2930. </code></pre>
  2931. <p>Where <code>&lt;db&gt;</code> is the location of the database,
  2932. <code>&lt;server_name&gt;</code> is the server name as specified in the
  2933. synapse configuration, and <code>&lt;signing_key&gt;</code> is the location
  2934. of the signing key as specified in the synapse configuration.</p>
  2935. <p>This may take some time to complete. Failures of signatures and content
  2936. hashes can safely be ignored.</p>
  2937. <h1 id="upgrading-to-v051"><a class="header" href="#upgrading-to-v051">Upgrading to v0.5.1</a></h1>
  2938. <p>Depending on precisely when you installed v0.5.0 you may have ended up
  2939. with a stale release of the reference matrix webclient installed as a
  2940. python module. To uninstall it and ensure you are depending on the
  2941. latest module, please run:</p>
  2942. <pre><code>$ pip uninstall syweb
  2943. </code></pre>
  2944. <h1 id="upgrading-to-v050"><a class="header" href="#upgrading-to-v050">Upgrading to v0.5.0</a></h1>
  2945. <p>The webclient has been split out into a seperate repository/pacakage in
  2946. this release. Before you restart your homeserver you will need to pull
  2947. in the webclient package by running:</p>
  2948. <pre><code>python setup.py develop --user
  2949. </code></pre>
  2950. <p>This release completely changes the database schema and so requires
  2951. upgrading it before starting the new version of the homeserver.</p>
  2952. <p>The script &quot;database-prepare-for-0.5.0.sh&quot; should be used to upgrade
  2953. the database. This will save all user information, such as logins and
  2954. profiles, but will otherwise purge the database. This includes messages,
  2955. which rooms the home server was a member of and room alias mappings.</p>
  2956. <p>If you would like to keep your history, please take a copy of your
  2957. database file and ask for help in #matrix:matrix.org. The upgrade
  2958. process is, unfortunately, non trivial and requires human intervention
  2959. to resolve any resulting conflicts during the upgrade process.</p>
  2960. <p>Before running the command the homeserver should be first completely
  2961. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  2962. <blockquote>
  2963. <p>./scripts/database-prepare-for-0.5.0.sh &quot;homeserver.db&quot;</p>
  2964. </blockquote>
  2965. <p>Once this has successfully completed it will be safe to restart the
  2966. homeserver. You may notice that the homeserver takes a few seconds
  2967. longer to restart than usual as it reinitializes the database.</p>
  2968. <p>On startup of the new version, users can either rejoin remote rooms
  2969. using room aliases or by being reinvited. Alternatively, if any other
  2970. homeserver sends a message to a room that the homeserver was previously
  2971. in the local HS will automatically rejoin the room.</p>
  2972. <h1 id="upgrading-to-v040"><a class="header" href="#upgrading-to-v040">Upgrading to v0.4.0</a></h1>
  2973. <p>This release needs an updated syutil version. Run:</p>
  2974. <pre><code>python setup.py develop
  2975. </code></pre>
  2976. <p>You will also need to upgrade your configuration as the signing key
  2977. format has changed. Run:</p>
  2978. <pre><code>python -m synapse.app.homeserver --config-path &lt;CONFIG&gt; --generate-config
  2979. </code></pre>
  2980. <h1 id="upgrading-to-v030"><a class="header" href="#upgrading-to-v030">Upgrading to v0.3.0</a></h1>
  2981. <p>This registration API now closely matches the login API. This introduces
  2982. a bit more backwards and forwards between the HS and the client, but
  2983. this improves the overall flexibility of the API. You can now GET on
  2984. /register to retrieve a list of valid registration flows. Upon choosing
  2985. one, they are submitted in the same way as login, e.g:</p>
  2986. <pre><code>{
  2987. type: m.login.password,
  2988. user: foo,
  2989. password: bar
  2990. }
  2991. </code></pre>
  2992. <p>The default HS supports 2 flows, with and without Identity Server email
  2993. authentication. Enabling captcha on the HS will add in an extra step to
  2994. all flows: <code>m.login.recaptcha</code> which must be completed before you can
  2995. transition to the next stage. There is a new login type:
  2996. <code>m.login.email.identity</code> which contains the <code>threepidCreds</code> key which
  2997. were previously sent in the original register request. For more
  2998. information on this, see the specification.</p>
  2999. <h2 id="web-client"><a class="header" href="#web-client">Web Client</a></h2>
  3000. <p>The VoIP specification has changed between v0.2.0 and v0.3.0. Users
  3001. should refresh any browser tabs to get the latest web client code. Users
  3002. on v0.2.0 of the web client will not be able to call those on v0.3.0 and
  3003. vice versa.</p>
  3004. <h1 id="upgrading-to-v020"><a class="header" href="#upgrading-to-v020">Upgrading to v0.2.0</a></h1>
  3005. <p>The home server now requires setting up of SSL config before it can run.
  3006. To automatically generate default config use:</p>
  3007. <pre><code>$ python synapse/app/homeserver.py \
  3008. --server-name machine.my.domain.name \
  3009. --bind-port 8448 \
  3010. --config-path homeserver.config \
  3011. --generate-config
  3012. </code></pre>
  3013. <p>This config can be edited if desired, for example to specify a different
  3014. SSL certificate to use. Once done you can run the home server using:</p>
  3015. <pre><code>$ python synapse/app/homeserver.py --config-path homeserver.config
  3016. </code></pre>
  3017. <p>See the README.rst for more information.</p>
  3018. <p>Also note that some config options have been renamed, including:</p>
  3019. <ul>
  3020. <li>&quot;host&quot; to &quot;server-name&quot;</li>
  3021. <li>&quot;database&quot; to &quot;database-path&quot;</li>
  3022. <li>&quot;port&quot; to &quot;bind-port&quot; and &quot;unsecure-port&quot;</li>
  3023. </ul>
  3024. <h1 id="upgrading-to-v001"><a class="header" href="#upgrading-to-v001">Upgrading to v0.0.1</a></h1>
  3025. <p>This release completely changes the database schema and so requires
  3026. upgrading it before starting the new version of the homeserver.</p>
  3027. <p>The script &quot;database-prepare-for-0.0.1.sh&quot; should be used to upgrade
  3028. the database. This will save all user information, such as logins and
  3029. profiles, but will otherwise purge the database. This includes messages,
  3030. which rooms the home server was a member of and room alias mappings.</p>
  3031. <p>Before running the command the homeserver should be first completely
  3032. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  3033. <blockquote>
  3034. <p>./scripts/database-prepare-for-0.0.1.sh &quot;homeserver.db&quot;</p>
  3035. </blockquote>
  3036. <p>Once this has successfully completed it will be safe to restart the
  3037. homeserver. You may notice that the homeserver takes a few seconds
  3038. longer to restart than usual as it reinitializes the database.</p>
  3039. <p>On startup of the new version, users can either rejoin remote rooms
  3040. using room aliases or by being reinvited. Alternatively, if any other
  3041. homeserver sends a message to a room that the homeserver was previously
  3042. in the local HS will automatically rejoin the room.</p>
  3043. <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>
  3044. <p>Federation is the process by which users on different servers can participate
  3045. in the same room. For this to work, those other servers must be able to contact
  3046. yours to send messages.</p>
  3047. <p>The <code>server_name</code> configured in the Synapse configuration file (often
  3048. <code>homeserver.yaml</code>) defines how resources (users, rooms, etc.) will be
  3049. identified (eg: <code>@user:example.com</code>, <code>#room:example.com</code>). By default,
  3050. it is also the domain that other servers will use to try to reach your
  3051. server (via port 8448). This is easy to set up and will work provided
  3052. you set the <code>server_name</code> to match your machine's public DNS hostname.</p>
  3053. <p>For this default configuration to work, you will need to listen for TLS
  3054. connections on port 8448. The preferred way to do that is by using a
  3055. reverse proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions
  3056. on how to correctly set one up.</p>
  3057. <p>In some cases you might not want to run Synapse on the machine that has
  3058. the <code>server_name</code> as its public DNS hostname, or you might want federation
  3059. traffic to use a different port than 8448. For example, you might want to
  3060. have your user names look like <code>@user:example.com</code>, but you want to run
  3061. Synapse on <code>synapse.example.com</code> on port 443. This can be done using
  3062. delegation, which allows an admin to control where federation traffic should
  3063. be sent. See <a href="delegate.html">the delegation documentation</a> for instructions on how to set this up.</p>
  3064. <p>Once federation has been configured, you should be able to join a room over
  3065. federation. A good place to start is <code>#synapse:matrix.org</code> - a room for
  3066. Synapse admins.</p>
  3067. <h2 id="troubleshooting-3"><a class="header" href="#troubleshooting-3">Troubleshooting</a></h2>
  3068. <p>You can use the <a href="https://matrix.org/federationtester">federation tester</a>
  3069. to check if your homeserver is configured correctly. Alternatively try the
  3070. <a href="https://matrix.org/federationtester/api/report?server_name=DOMAIN">JSON API used by the federation tester</a>.
  3071. Note that you'll have to modify this URL to replace <code>DOMAIN</code> with your
  3072. <code>server_name</code>. Hitting the API directly provides extra detail.</p>
  3073. <p>The typical failure mode for federation is that when the server tries to join
  3074. a room, it is rejected with &quot;401: Unauthorized&quot;. Generally this means that other
  3075. servers in the room could not access yours. (Joining a room over federation is
  3076. a complicated dance which requires connections in both directions).</p>
  3077. <p>Another common problem is that people on other servers can't join rooms that
  3078. you invite them to. This can be caused by an incorrectly-configured reverse
  3079. proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions on how
  3080. to correctly configure a reverse proxy.</p>
  3081. <h3 id="known-issues"><a class="header" href="#known-issues">Known issues</a></h3>
  3082. <p><strong>HTTP <code>308 Permanent Redirect</code> redirects are not followed</strong>: Due to missing features
  3083. in the HTTP library used by Synapse, 308 redirects are currently not followed by
  3084. federating servers, which can cause <code>M_UNKNOWN</code> or <code>401 Unauthorized</code> errors. This
  3085. may affect users who are redirecting apex-to-www (e.g. <code>example.com</code> -&gt; <code>www.example.com</code>),
  3086. and especially users of the Kubernetes <em>Nginx Ingress</em> module, which uses 308 redirect
  3087. codes by default. For those Kubernetes users, <a href="https://stackoverflow.com/a/52617528/5096871">this Stackoverflow post</a>
  3088. might be helpful. For other users, switching to a <code>301 Moved Permanently</code> code may be
  3089. an option. 308 redirect codes will be supported properly in a future
  3090. release of Synapse.</p>
  3091. <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>
  3092. <p>If you want to get up and running quickly with a trio of homeservers in a
  3093. private federation, there is a script in the <code>demo</code> directory. This is mainly
  3094. useful just for development purposes. See
  3095. <a href="https://matrix-org.github.io/synapse/develop/development/demo.html">demo scripts</a>.</p>
  3096. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuration-1"><a class="header" href="#configuration-1">Configuration</a></h1>
  3097. <p>This section contains information on tweaking Synapse via the various options in the configuration file. A configuration
  3098. file should have been generated when you <a href="usage/configuration/../../setup/installation.html">installed Synapse</a>.</p>
  3099. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuring-synapse"><a class="header" href="#configuring-synapse">Configuring Synapse</a></h1>
  3100. <p>This is intended as a guide to the Synapse configuration. The behavior of a Synapse instance can be modified
  3101. through the many configuration settings documented here — each config option is explained,
  3102. including what the default is, how to change the default and what sort of behaviour the setting governs.
  3103. Also included is an example configuration for each setting. If you don't want to spend a lot of time
  3104. thinking about options, the config as generated sets sensible defaults for all values. Do note however that the
  3105. database defaults to SQLite, which is not recommended for production usage. You can read more on this subject
  3106. <a href="usage/configuration/../../setup/installation.html#using-postgresql">here</a>.</p>
  3107. <h2 id="config-conventions"><a class="header" href="#config-conventions">Config Conventions</a></h2>
  3108. <p>Configuration options that take a time period can be set using a number
  3109. followed by a letter. Letters have the following meanings:</p>
  3110. <ul>
  3111. <li><code>s</code> = second</li>
  3112. <li><code>m</code> = minute</li>
  3113. <li><code>h</code> = hour</li>
  3114. <li><code>d</code> = day</li>
  3115. <li><code>w</code> = week</li>
  3116. <li><code>y</code> = year</li>
  3117. </ul>
  3118. <p>For example, setting <code>redaction_retention_period: 5m</code> would remove redacted
  3119. messages from the database after 5 minutes, rather than 5 months.</p>
  3120. <p>In addition, configuration options referring to size use the following suffixes:</p>
  3121. <ul>
  3122. <li><code>M</code> = MiB, or 1,048,576 bytes</li>
  3123. <li><code>K</code> = KiB, or 1024 bytes </li>
  3124. </ul>
  3125. <p>For example, setting <code>max_avatar_size: 10M</code> means that Synapse will not accept files larger than 10,485,760 bytes
  3126. for a user avatar. </p>
  3127. <h3 id="yaml"><a class="header" href="#yaml">YAML</a></h3>
  3128. <p>The configuration file is a <a href="https://yaml.org/">YAML</a> file, which means that certain syntax rules
  3129. apply if you want your config file to be read properly. A few helpful things to know:</p>
  3130. <ul>
  3131. <li>
  3132. <p><code>#</code> before any option in the config will comment out that setting and either a default (if available) will
  3133. be applied or Synapse will ignore the setting. Thus, in example #1 below, the setting will be read and
  3134. applied, but in example #2 the setting will not be read and a default will be applied.</p>
  3135. <p>Example #1:</p>
  3136. <pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
  3137. </code></pre>
  3138. <p>Example #2:</p>
  3139. <pre><code class="language-yaml">#pid_file: DATADIR/homeserver.pid
  3140. </code></pre>
  3141. </li>
  3142. <li>
  3143. <p>Indentation matters! The indentation before a setting
  3144. will determine whether a given setting is read as part of another
  3145. setting, or considered on its own. Thus, in example #1, the <code>enabled</code> setting
  3146. is read as a sub-option of the <code>presence</code> setting, and will be properly applied.</p>
  3147. <p>However, the lack of indentation before the <code>enabled</code> setting in example #2 means
  3148. that when reading the config, Synapse will consider both <code>presence</code> and <code>enabled</code> as
  3149. different settings. In this case, <code>presence</code> has no value, and thus a default applied, and <code>enabled</code>
  3150. is an option that Synapse doesn't recognize and thus ignores.</p>
  3151. <p>Example #1: </p>
  3152. <pre><code class="language-yaml">presence:
  3153. enabled: false
  3154. </code></pre>
  3155. <p>Example #2:</p>
  3156. <pre><code class="language-yaml">presence:
  3157. enabled: false
  3158. </code></pre>
  3159. <p>In this manual, all top-level settings (ones with no indentation) are identified
  3160. at the beginning of their section (i.e. &quot;### <code>example_setting</code>&quot;) and
  3161. the sub-options, if any, are identified and listed in the body of the section.
  3162. In addition, each setting has an example of its usage, with the proper indentation
  3163. shown. </p>
  3164. </li>
  3165. </ul>
  3166. <h2 id="contents"><a class="header" href="#contents">Contents</a></h2>
  3167. <p><a href="usage/configuration/config_documentation.html#modules">Modules</a></p>
  3168. <p><a href="usage/configuration/config_documentation.html#server">Server</a></p>
  3169. <p><a href="usage/configuration/config_documentation.html#homeserver-blocking">Homeserver Blocking</a></p>
  3170. <p><a href="usage/configuration/config_documentation.html#tls">TLS</a></p>
  3171. <p><a href="usage/configuration/config_documentation.html#federation">Federation</a></p>
  3172. <p><a href="usage/configuration/config_documentation.html#caching">Caching</a></p>
  3173. <p><a href="usage/configuration/config_documentation.html#database">Database</a></p>
  3174. <p><a href="usage/configuration/config_documentation.html#logging">Logging</a></p>
  3175. <p><a href="usage/configuration/config_documentation.html#ratelimiting">Ratelimiting</a></p>
  3176. <p><a href="usage/configuration/config_documentation.html#media-store">Media Store</a></p>
  3177. <p><a href="usage/configuration/config_documentation.html#captcha">Captcha</a></p>
  3178. <p><a href="usage/configuration/config_documentation.html#turn">TURN</a></p>
  3179. <p><a href="usage/configuration/config_documentation.html#registration">Registration</a></p>
  3180. <p><a href="usage/configuration/config_documentation.html#api-configuration">API Configuration</a></p>
  3181. <p><a href="usage/configuration/config_documentation.html#signing-keys">Signing Keys</a></p>
  3182. <p><a href="usage/configuration/config_documentation.html#single-sign-on-integration">Single Sign On Integration</a></p>
  3183. <p><a href="usage/configuration/config_documentation.html#push">Push</a></p>
  3184. <p><a href="usage/configuration/config_documentation.html#rooms">Rooms</a></p>
  3185. <p><a href="usage/configuration/config_documentation.html#opentracing">Opentracing</a></p>
  3186. <p><a href="usage/configuration/config_documentation.html#workers">Workers</a></p>
  3187. <p><a href="usage/configuration/config_documentation.html#background-updates">Background Updates</a></p>
  3188. <h2 id="modules"><a class="header" href="#modules">Modules</a></h2>
  3189. <p>Server admins can expand Synapse's functionality with external modules.</p>
  3190. <p>See <a href="usage/configuration/../../modules/index.html">here</a> for more
  3191. documentation on how to configure or create custom modules for Synapse.</p>
  3192. <hr />
  3193. <h3 id="modules-1"><a class="header" href="#modules-1"><code>modules</code></a></h3>
  3194. <p>Use the <code>module</code> sub-option to add modules under this option to extend functionality.
  3195. The <code>module</code> setting then has a sub-option, <code>config</code>, which can be used to define some configuration
  3196. for the <code>module</code>.</p>
  3197. <p>Defaults to none.</p>
  3198. <p>Example configuration:</p>
  3199. <pre><code class="language-yaml">modules:
  3200. - module: my_super_module.MySuperClass
  3201. config:
  3202. do_thing: true
  3203. - module: my_other_super_module.SomeClass
  3204. config: {}
  3205. </code></pre>
  3206. <hr />
  3207. <h2 id="server"><a class="header" href="#server">Server</a></h2>
  3208. <p>Define your homeserver name and other base options.</p>
  3209. <hr />
  3210. <h3 id="server_name"><a class="header" href="#server_name"><code>server_name</code></a></h3>
  3211. <p>This sets the public-facing domain of the server.</p>
  3212. <p>The <code>server_name</code> name will appear at the end of usernames and room addresses
  3213. created on your server. For example if the <code>server_name</code> was example.com,
  3214. usernames on your server would be in the format <code>@user:example.com</code></p>
  3215. <p>In most cases you should avoid using a matrix specific subdomain such as
  3216. matrix.example.com or synapse.example.com as the <code>server_name</code> for the same
  3217. reasons you wouldn't use user@email.example.com as your email address.
  3218. See <a href="usage/configuration/../../delegate.html">here</a>
  3219. for information on how to host Synapse on a subdomain while preserving
  3220. a clean <code>server_name</code>.</p>
  3221. <p>The <code>server_name</code> cannot be changed later so it is important to
  3222. configure this correctly before you start Synapse. It should be all
  3223. lowercase and may contain an explicit port.</p>
  3224. <p>There is no default for this option. </p>
  3225. <p>Example configuration #1:</p>
  3226. <pre><code class="language-yaml">server_name: matrix.org
  3227. </code></pre>
  3228. <p>Example configuration #2:</p>
  3229. <pre><code class="language-yaml">server_name: localhost:8080
  3230. </code></pre>
  3231. <hr />
  3232. <h3 id="pid_file"><a class="header" href="#pid_file"><code>pid_file</code></a></h3>
  3233. <p>When running Synapse as a daemon, the file to store the pid in. Defaults to none.</p>
  3234. <p>Example configuration:</p>
  3235. <pre><code class="language-yaml">pid_file: DATADIR/homeserver.pid
  3236. </code></pre>
  3237. <hr />
  3238. <h3 id="web_client_location"><a class="header" href="#web_client_location"><code>web_client_location</code></a></h3>
  3239. <p>The absolute URL to the web client which <code>/</code> will redirect to. Defaults to none. </p>
  3240. <p>Example configuration:</p>
  3241. <pre><code class="language-yaml">web_client_location: https://riot.example.com/
  3242. </code></pre>
  3243. <hr />
  3244. <h3 id="public_baseurl"><a class="header" href="#public_baseurl"><code>public_baseurl</code></a></h3>
  3245. <p>The public-facing base URL that clients use to access this Homeserver (not
  3246. including _matrix/...). This is the same URL a user might enter into the
  3247. 'Custom Homeserver URL' field on their client. If you use Synapse with a
  3248. reverse proxy, this should be the URL to reach Synapse via the proxy.
  3249. Otherwise, it should be the URL to reach Synapse's client HTTP listener (see
  3250. 'listeners' below).</p>
  3251. <p>Defaults to <code>https://&lt;server_name&gt;/</code>.</p>
  3252. <p>Example configuration:</p>
  3253. <pre><code class="language-yaml">public_baseurl: https://example.com/
  3254. </code></pre>
  3255. <hr />
  3256. <h3 id="serve_server_wellknown"><a class="header" href="#serve_server_wellknown"><code>serve_server_wellknown</code></a></h3>
  3257. <p>By default, other servers will try to reach our server on port 8448, which can
  3258. be inconvenient in some environments.</p>
  3259. <p>Provided <code>https://&lt;server_name&gt;/</code> on port 443 is routed to Synapse, this
  3260. option configures Synapse to serve a file at <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>.
  3261. This will tell other servers to send traffic to port 443 instead.</p>
  3262. <p>This option currently defaults to false.</p>
  3263. <p>See https://matrix-org.github.io/synapse/latest/delegate.html for more
  3264. information.</p>
  3265. <p>Example configuration:</p>
  3266. <pre><code class="language-yaml">serve_server_wellknown: true
  3267. </code></pre>
  3268. <hr />
  3269. <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>
  3270. <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>.
  3271. 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>
  3272. <p>If this option is provided, it parses the given yaml to json and
  3273. serves it on <code>/.well-known/matrix/client</code> endpoint
  3274. alongside the standard properties.</p>
  3275. <p>Example configuration:</p>
  3276. <pre><code class="language-yaml">extra_well_known_client_content :
  3277. option1: value1
  3278. option2: value2
  3279. </code></pre>
  3280. <hr />
  3281. <h3 id="soft_file_limit"><a class="header" href="#soft_file_limit"><code>soft_file_limit</code></a></h3>
  3282. <p>Set the soft limit on the number of file descriptors synapse can use.
  3283. Zero is used to indicate synapse should set the soft limit to the hard limit.
  3284. Defaults to 0. </p>
  3285. <p>Example configuration:</p>
  3286. <pre><code class="language-yaml">soft_file_limit: 3
  3287. </code></pre>
  3288. <hr />
  3289. <h3 id="presence"><a class="header" href="#presence"><code>presence</code></a></h3>
  3290. <p>Presence tracking allows users to see the state (e.g online/offline)
  3291. of other local and remote users. Set the <code>enabled</code> sub-option to false to<br />
  3292. disable presence tracking on this homeserver. Defaults to true.
  3293. This option replaces the previous top-level 'use_presence' option.</p>
  3294. <p>Example configuration:</p>
  3295. <pre><code class="language-yaml">presence:
  3296. enabled: false
  3297. </code></pre>
  3298. <hr />
  3299. <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>
  3300. <p>Whether to require authentication to retrieve profile data (avatars, display names) of other
  3301. users through the client API. Defaults to false. Note that profile data is also available
  3302. via the federation API, unless <code>allow_profile_lookup_over_federation</code> is set to false.</p>
  3303. <p>Example configuration:</p>
  3304. <pre><code class="language-yaml">require_auth_for_profile_requests: true
  3305. </code></pre>
  3306. <hr />
  3307. <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>
  3308. <p>Use this option to require a user to share a room with another user in order
  3309. to retrieve their profile information. Only checked on Client-Server
  3310. requests. Profile requests from other servers should be checked by the
  3311. requesting server. Defaults to false.</p>
  3312. <p>Example configuration: </p>
  3313. <pre><code class="language-yaml">limit_profile_requests_to_users_who_share_rooms: true
  3314. </code></pre>
  3315. <hr />
  3316. <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>
  3317. <p>Use this option to prevent a user's profile data from being retrieved and
  3318. displayed in a room until they have joined it. By default, a user's
  3319. profile data is included in an invite event, regardless of the values
  3320. of the above two settings, and whether or not the users share a server.
  3321. Defaults to true.</p>
  3322. <p>Example configuration:</p>
  3323. <pre><code class="language-yaml">include_profile_data_on_invite: false
  3324. </code></pre>
  3325. <hr />
  3326. <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>
  3327. <p>If set to true, removes the need for authentication to access the server's
  3328. public rooms directory through the client API, meaning that anyone can
  3329. query the room directory. Defaults to false.</p>
  3330. <p>Example configuration:</p>
  3331. <pre><code class="language-yaml">allow_public_rooms_without_auth: true
  3332. </code></pre>
  3333. <hr />
  3334. <h3 id="allow_public_rooms_without_auth-1"><a class="header" href="#allow_public_rooms_without_auth-1"><code>allow_public_rooms_without_auth</code></a></h3>
  3335. <p>If set to true, allows any other homeserver to fetch the server's public
  3336. rooms directory via federation. Defaults to false.</p>
  3337. <p>Example configuration:</p>
  3338. <pre><code class="language-yaml">allow_public_rooms_over_federation: true
  3339. </code></pre>
  3340. <hr />
  3341. <h3 id="default_room_version"><a class="header" href="#default_room_version"><code>default_room_version</code></a></h3>
  3342. <p>The default room version for newly created rooms on this server.</p>
  3343. <p>Known room versions are listed <a href="https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions">here</a></p>
  3344. <p>For example, for room version 1, <code>default_room_version</code> should be set
  3345. to &quot;1&quot;. </p>
  3346. <p>Currently defaults to &quot;9&quot;.</p>
  3347. <p>Example configuration:</p>
  3348. <pre><code class="language-yaml">default_room_version: &quot;8&quot;
  3349. </code></pre>
  3350. <hr />
  3351. <h3 id="gc_thresholds"><a class="header" href="#gc_thresholds"><code>gc_thresholds</code></a></h3>
  3352. <p>The garbage collection threshold parameters to pass to <code>gc.set_threshold</code>, if defined.
  3353. Defaults to none. </p>
  3354. <p>Example configuration:</p>
  3355. <pre><code class="language-yaml">gc_thresholds: [700, 10, 10]
  3356. </code></pre>
  3357. <hr />
  3358. <h3 id="gc_min_interval"><a class="header" href="#gc_min_interval"><code>gc_min_interval</code></a></h3>
  3359. <p>The minimum time in seconds between each GC for a generation, regardless of
  3360. the GC thresholds. This ensures that we don't do GC too frequently. A value of <code>[1s, 10s, 30s]</code>
  3361. indicates that a second must pass between consecutive generation 0 GCs, etc.</p>
  3362. <p>Defaults to <code>[1s, 10s, 30s]</code>.</p>
  3363. <p>Example configuration:</p>
  3364. <pre><code class="language-yaml">gc_min_interval: [0.5s, 30s, 1m]
  3365. </code></pre>
  3366. <hr />
  3367. <h3 id="filter_timeline_limit"><a class="header" href="#filter_timeline_limit"><code>filter_timeline_limit</code></a></h3>
  3368. <p>Set the limit on the returned events in the timeline in the get
  3369. and sync operations. Defaults to 100. A value of -1 means no upper limit.</p>
  3370. <p>Example configuration:</p>
  3371. <pre><code class="language-yaml">filter_timeline_limit: 5000
  3372. </code></pre>
  3373. <hr />
  3374. <h3 id="block_non_admin_invites"><a class="header" href="#block_non_admin_invites"><code>block_non_admin_invites</code></a></h3>
  3375. <p>Whether room invites to users on this server should be blocked
  3376. (except those sent by local server admins). Defaults to false.</p>
  3377. <p>Example configuration:</p>
  3378. <pre><code class="language-yaml">block_non_admin_invites: true
  3379. </code></pre>
  3380. <hr />
  3381. <h3 id="enable_search"><a class="header" href="#enable_search"><code>enable_search</code></a></h3>
  3382. <p>If set to false, new messages will not be indexed for searching and users
  3383. will receive errors when searching for messages. Defaults to true.</p>
  3384. <p>Example configuration:</p>
  3385. <pre><code class="language-yaml">enable_search: false
  3386. </code></pre>
  3387. <hr />
  3388. <h3 id="ip_range_blacklist"><a class="header" href="#ip_range_blacklist"><code>ip_range_blacklist</code></a></h3>
  3389. <p>This option prevents outgoing requests from being sent to the specified blacklisted IP address
  3390. CIDR ranges. If this option is not specified then it defaults to private IP
  3391. address ranges (see the example below).</p>
  3392. <p>The blacklist applies to the outbound requests for federation, identity servers,
  3393. push servers, and for checking key validity for third-party invite events.</p>
  3394. <p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  3395. listed here, since they correspond to unroutable addresses.)</p>
  3396. <p>This option replaces <code>federation_ip_range_blacklist</code> in Synapse v1.25.0.</p>
  3397. <p>Note: The value is ignored when an HTTP proxy is in use.</p>
  3398. <p>Example configuration:</p>
  3399. <pre><code class="language-yaml">ip_range_blacklist:
  3400. - '127.0.0.0/8'
  3401. - '10.0.0.0/8'
  3402. - '172.16.0.0/12'
  3403. - '192.168.0.0/16'
  3404. - '100.64.0.0/10'
  3405. - '192.0.0.0/24'
  3406. - '169.254.0.0/16'
  3407. - '192.88.99.0/24'
  3408. - '198.18.0.0/15'
  3409. - '192.0.2.0/24'
  3410. - '198.51.100.0/24'
  3411. - '203.0.113.0/24'
  3412. - '224.0.0.0/4'
  3413. - '::1/128'
  3414. - 'fe80::/10'
  3415. - 'fc00::/7'
  3416. - '2001:db8::/32'
  3417. - 'ff00::/8'
  3418. - 'fec0::/10'
  3419. </code></pre>
  3420. <hr />
  3421. <h3 id="ip_range_whitelist"><a class="header" href="#ip_range_whitelist"><code>ip_range_whitelist</code></a></h3>
  3422. <p>List of IP address CIDR ranges that should be allowed for federation,
  3423. identity servers, push servers, and for checking key validity for
  3424. third-party invite events. This is useful for specifying exceptions to
  3425. wide-ranging blacklisted target IP ranges - e.g. for communication with
  3426. a push server only visible in your network.</p>
  3427. <p>This whitelist overrides <code>ip_range_blacklist</code> and defaults to an empty
  3428. list.</p>
  3429. <p>Example configuration:</p>
  3430. <pre><code class="language-yaml">ip_range_whitelist:
  3431. - '192.168.1.1'
  3432. </code></pre>
  3433. <hr />
  3434. <h3 id="listeners"><a class="header" href="#listeners"><code>listeners</code></a></h3>
  3435. <p>List of ports that Synapse should listen on, their purpose and their
  3436. configuration.</p>
  3437. <p>Sub-options for each listener include:</p>
  3438. <ul>
  3439. <li>
  3440. <p><code>port</code>: the TCP port to bind to. </p>
  3441. </li>
  3442. <li>
  3443. <p><code>bind_addresses</code>: a list of local addresses to listen on. The default is
  3444. 'all local interfaces'.</p>
  3445. </li>
  3446. <li>
  3447. <p><code>type</code>: the type of listener. Normally <code>http</code>, but other valid options are:</p>
  3448. <ul>
  3449. <li>
  3450. <p><code>manhole</code>: (see the docs <a href="usage/configuration/../../manhole.html">here</a>),</p>
  3451. </li>
  3452. <li>
  3453. <p><code>metrics</code>: (see the docs <a href="usage/configuration/../../metrics-howto.html">here</a>),</p>
  3454. </li>
  3455. <li>
  3456. <p><code>replication</code>: (see the docs <a href="usage/configuration/../../workers.html">here</a>).</p>
  3457. </li>
  3458. </ul>
  3459. </li>
  3460. <li>
  3461. <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>
  3462. </li>
  3463. <li>
  3464. <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
  3465. behind a reverse-proxy.</p>
  3466. </li>
  3467. <li>
  3468. <p><code>resources</code>: Only valid for an 'http' listener. A list of resources to host
  3469. on this port. Sub-options for each resource are:</p>
  3470. <ul>
  3471. <li>
  3472. <p><code>names</code>: a list of names of HTTP resources. See below for a list of valid resource names.</p>
  3473. </li>
  3474. <li>
  3475. <p><code>compress</code>: set to true to enable HTTP compression for this resource.</p>
  3476. </li>
  3477. </ul>
  3478. </li>
  3479. <li>
  3480. <p><code>additional_resources</code>: Only valid for an 'http' listener. A map of
  3481. additional endpoints which should be loaded via dynamic modules.</p>
  3482. </li>
  3483. </ul>
  3484. <p>Valid resource names are:</p>
  3485. <ul>
  3486. <li>
  3487. <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>
  3488. </li>
  3489. <li>
  3490. <p><code>consent</code>: user consent forms (/_matrix/consent). See <a href="usage/configuration/../../consent_tracking.html">here</a> for more.</p>
  3491. </li>
  3492. <li>
  3493. <p><code>federation</code>: the server-server API (/_matrix/federation). Also implies <code>media</code>, <code>keys</code>, <code>openid</code></p>
  3494. </li>
  3495. <li>
  3496. <p><code>keys</code>: the key discovery API (/_matrix/key).</p>
  3497. </li>
  3498. <li>
  3499. <p><code>media</code>: the media API (/_matrix/media).</p>
  3500. </li>
  3501. <li>
  3502. <p><code>metrics</code>: the metrics interface. See <a href="usage/configuration/../../metrics-howto.html">here</a>.</p>
  3503. </li>
  3504. <li>
  3505. <p><code>openid</code>: OpenID authentication. See <a href="usage/configuration/../../openid.html">here</a>.</p>
  3506. </li>
  3507. <li>
  3508. <p><code>replication</code>: the HTTP replication API (/_synapse/replication). See <a href="usage/configuration/../../workers.html">here</a>.</p>
  3509. </li>
  3510. <li>
  3511. <p><code>static</code>: static resources under synapse/static (/_matrix/static). (Mostly useful for 'fallback authentication'.)</p>
  3512. </li>
  3513. </ul>
  3514. <p>Example configuration #1:</p>
  3515. <pre><code class="language-yaml">listeners:
  3516. # TLS-enabled listener: for when matrix traffic is sent directly to synapse.
  3517. #
  3518. # (Note that you will also need to give Synapse a TLS key and certificate: see the TLS section
  3519. # below.)
  3520. #
  3521. - port: 8448
  3522. type: http
  3523. tls: true
  3524. resources:
  3525. - names: [client, federation]
  3526. </code></pre>
  3527. <p>Example configuration #2:</p>
  3528. <pre><code class="language-yaml">listeners:
  3529. # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy
  3530. # that unwraps TLS.
  3531. #
  3532. # If you plan to use a reverse proxy, please see
  3533. # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  3534. #
  3535. - port: 8008
  3536. tls: false
  3537. type: http
  3538. x_forwarded: true
  3539. bind_addresses: ['::1', '127.0.0.1']
  3540. resources:
  3541. - names: [client, federation]
  3542. compress: false
  3543. # example additional_resources:
  3544. additional_resources:
  3545. &quot;/_matrix/my/custom/endpoint&quot;:
  3546. module: my_module.CustomRequestHandler
  3547. config: {}
  3548. # Turn on the twisted ssh manhole service on localhost on the given
  3549. # port.
  3550. - port: 9000
  3551. bind_addresses: ['::1', '127.0.0.1']
  3552. type: manhole
  3553. </code></pre>
  3554. <hr />
  3555. <h3 id="manhole_settings"><a class="header" href="#manhole_settings"><code>manhole_settings</code></a></h3>
  3556. <p>Connection settings for the manhole. You can find more information
  3557. on the manhole <a href="usage/configuration/../../manhole.html">here</a>. Manhole sub-options include:</p>
  3558. <ul>
  3559. <li><code>username</code> : the username for the manhole. This defaults to 'matrix'.</li>
  3560. <li><code>password</code>: The password for the manhole. This defaults to 'rabbithole'.</li>
  3561. <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.
  3562. If these are left unset, then hardcoded and non-secret keys are used,
  3563. which could allow traffic to be intercepted if sent over a public network.</li>
  3564. </ul>
  3565. <p>Example configuration:</p>
  3566. <pre><code class="language-yaml">manhole_settings:
  3567. username: manhole
  3568. password: mypassword
  3569. ssh_priv_key_path: CONFDIR/id_rsa
  3570. ssh_pub_key_path: CONFDIR/id_rsa.pub
  3571. </code></pre>
  3572. <hr />
  3573. <h3 id="dummy_events_threshold"><a class="header" href="#dummy_events_threshold"><code>dummy_events_threshold</code></a></h3>
  3574. <p>Forward extremities can build up in a room due to networking delays between
  3575. homeservers. Once this happens in a large room, calculation of the state of
  3576. that room can become quite expensive. To mitigate this, once the number of
  3577. forward extremities reaches a given threshold, Synapse will send an
  3578. <code>org.matrix.dummy_event</code> event, which will reduce the forward extremities
  3579. in the room.</p>
  3580. <p>This setting defines the threshold (i.e. number of forward extremities in the room) at which dummy events are sent.
  3581. The default value is 10.</p>
  3582. <p>Example configuration:</p>
  3583. <pre><code class="language-yaml">dummy_events_threshold: 5
  3584. </code></pre>
  3585. <hr />
  3586. <p>Config option <code>delete_stale_devices_after</code></p>
  3587. <p>An optional duration. If set, Synapse will run a daily background task to log out and
  3588. delete any device that hasn't been accessed for more than the specified amount of time.</p>
  3589. <p>Defaults to no duration, which means devices are never pruned.</p>
  3590. <p>Example configuration:</p>
  3591. <pre><code class="language-yaml">delete_stale_devices_after: 1y
  3592. </code></pre>
  3593. <h2 id="homeserver-blocking"><a class="header" href="#homeserver-blocking">Homeserver blocking</a></h2>
  3594. <p>Useful options for Synapse admins.</p>
  3595. <hr />
  3596. <h3 id="admin_contact"><a class="header" href="#admin_contact"><code>admin_contact</code></a></h3>
  3597. <p>How to reach the server admin, used in <code>ResourceLimitError</code>. Defaults to none. </p>
  3598. <p>Example configuration:</p>
  3599. <pre><code class="language-yaml">admin_contact: 'mailto:admin@server.com'
  3600. </code></pre>
  3601. <hr />
  3602. <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>
  3603. <p>Blocks users from connecting to the homeserver and provides a human-readable reason
  3604. why the connection was blocked. Defaults to false. </p>
  3605. <p>Example configuration:</p>
  3606. <pre><code class="language-yaml">hs_disabled: true
  3607. hs_disabled_message: 'Reason for why the HS is blocked'
  3608. </code></pre>
  3609. <hr />
  3610. <h3 id="limit_usage_by_mau"><a class="header" href="#limit_usage_by_mau"><code>limit_usage_by_mau</code></a></h3>
  3611. <p>This option disables/enables monthly active user blocking. Used in cases where the admin or
  3612. server owner wants to limit to the number of monthly active users. When enabled and a limit is
  3613. reached the server returns a <code>ResourceLimitError</code> with error type <code>Codes.RESOURCE_LIMIT_EXCEEDED</code>.
  3614. Defaults to false. If this is enabled, a value for <code>max_mau_value</code> must also be set.</p>
  3615. <p>Example configuration:</p>
  3616. <pre><code class="language-yaml">limit_usage_by_mau: true
  3617. </code></pre>
  3618. <hr />
  3619. <h3 id="max_mau_value"><a class="header" href="#max_mau_value"><code>max_mau_value</code></a></h3>
  3620. <p>This option sets the hard limit of monthly active users above which the server will start
  3621. blocking user actions if <code>limit_usage_by_mau</code> is enabled. Defaults to 0.</p>
  3622. <p>Example configuration:</p>
  3623. <pre><code class="language-yaml">max_mau_value: 50
  3624. </code></pre>
  3625. <hr />
  3626. <h3 id="mau_trial_days"><a class="header" href="#mau_trial_days"><code>mau_trial_days</code></a></h3>
  3627. <p>The option <code>mau_trial_days</code> is a means to add a grace period for active users. It
  3628. means that users must be active for the specified number of days before they
  3629. can be considered active and guards against the case where lots of users
  3630. sign up in a short space of time never to return after their initial
  3631. session. Defaults to 0. </p>
  3632. <p>Example configuration:</p>
  3633. <pre><code class="language-yaml">mau_trial_days: 5
  3634. </code></pre>
  3635. <hr />
  3636. <h3 id="mau_appservice_trial_days"><a class="header" href="#mau_appservice_trial_days"><code>mau_appservice_trial_days</code></a></h3>
  3637. <p>The option <code>mau_appservice_trial_days</code> is similar to <code>mau_trial_days</code>, but applies a different
  3638. trial number if the user was registered by an appservice. A value
  3639. of 0 means no trial days are applied. Appservices not listed in this dictionary
  3640. use the value of <code>mau_trial_days</code> instead.</p>
  3641. <p>Example configuration:</p>
  3642. <pre><code class="language-yaml">mau_appservice_trial_days:
  3643. my_appservice_id: 3
  3644. another_appservice_id: 6
  3645. </code></pre>
  3646. <hr />
  3647. <h3 id="mau_limit_alerting"><a class="header" href="#mau_limit_alerting"><code>mau_limit_alerting</code></a></h3>
  3648. <p>The option <code>mau_limit_alerting</code> is a means of limiting client-side alerting
  3649. should the mau limit be reached. This is useful for small instances
  3650. where the admin has 5 mau seats (say) for 5 specific people and no
  3651. interest increasing the mau limit further. Defaults to true, which
  3652. means that alerting is enabled.</p>
  3653. <p>Example configuration:</p>
  3654. <pre><code class="language-yaml">mau_limit_alerting: false
  3655. </code></pre>
  3656. <hr />
  3657. <h3 id="mau_stats_only"><a class="header" href="#mau_stats_only"><code>mau_stats_only</code></a></h3>
  3658. <p>If enabled, the metrics for the number of monthly active users will
  3659. be populated, however no one will be limited based on these numbers. If <code>limit_usage_by_mau</code>
  3660. is true, this is implied to be true. Defaults to false. </p>
  3661. <p>Example configuration:</p>
  3662. <pre><code class="language-yaml">mau_stats_only: true
  3663. </code></pre>
  3664. <hr />
  3665. <h3 id="mau_limit_reserved_threepids"><a class="header" href="#mau_limit_reserved_threepids"><code>mau_limit_reserved_threepids</code></a></h3>
  3666. <p>Sometimes the server admin will want to ensure certain accounts are
  3667. never blocked by mau checking. These accounts are specified by this option.
  3668. Defaults to none. Add accounts by specifying the <code>medium</code> and <code>address</code> of the
  3669. reserved threepid (3rd party identifier).</p>
  3670. <p>Example configuration:</p>
  3671. <pre><code class="language-yaml">mau_limit_reserved_threepids:
  3672. - medium: 'email'
  3673. address: 'reserved_user@example.com'
  3674. </code></pre>
  3675. <hr />
  3676. <h3 id="server_context"><a class="header" href="#server_context"><code>server_context</code></a></h3>
  3677. <p>This option is used by phonehome stats to group together related servers.
  3678. Defaults to none. </p>
  3679. <p>Example configuration:</p>
  3680. <pre><code class="language-yaml">server_context: context
  3681. </code></pre>
  3682. <hr />
  3683. <h3 id="limit_remote_rooms"><a class="header" href="#limit_remote_rooms"><code>limit_remote_rooms</code></a></h3>
  3684. <p>When this option is enabled, the room &quot;complexity&quot; will be checked before a user
  3685. joins a new remote room. If it is above the complexity limit, the server will
  3686. disallow joining, or will instantly leave. This is useful for homeservers that are
  3687. resource-constrained. Options for this setting include:</p>
  3688. <ul>
  3689. <li><code>enabled</code>: whether this check is enabled. Defaults to false.</li>
  3690. <li><code>complexity</code>: the limit above which rooms cannot be joined. The default is 1.0.</li>
  3691. <li><code>complexity_error</code>: override the error which is returned when the room is too complex with a
  3692. custom message. </li>
  3693. <li><code>admins_can_join</code>: allow server admins to join complex rooms. Default is false.</li>
  3694. </ul>
  3695. <p>Room complexity is an arbitrary measure based on factors such as the number of
  3696. users in the room. </p>
  3697. <p>Example configuration:</p>
  3698. <pre><code class="language-yaml">limit_remote_rooms:
  3699. enabled: true
  3700. complexity: 0.5
  3701. complexity_error: &quot;I can't let you do that, Dave.&quot;
  3702. admins_can_join: true
  3703. </code></pre>
  3704. <hr />
  3705. <h3 id="require_membership_for_aliases"><a class="header" href="#require_membership_for_aliases"><code>require_membership_for_aliases</code></a></h3>
  3706. <p>Whether to require a user to be in the room to add an alias to it.
  3707. Defaults to true.</p>
  3708. <p>Example configuration:</p>
  3709. <pre><code class="language-yaml">require_membership_for_aliases: false
  3710. </code></pre>
  3711. <hr />
  3712. <h3 id="allow_per_room_profiles"><a class="header" href="#allow_per_room_profiles"><code>allow_per_room_profiles</code></a></h3>
  3713. <p>Whether to allow per-room membership profiles through the sending of membership
  3714. events with profile information that differs from the target's global profile.
  3715. Defaults to true.</p>
  3716. <p>Example configuration:</p>
  3717. <pre><code class="language-yaml">allow_per_room_profiles: false
  3718. </code></pre>
  3719. <hr />
  3720. <h3 id="max_avatar_size"><a class="header" href="#max_avatar_size"><code>max_avatar_size</code></a></h3>
  3721. <p>The largest permissible file size in bytes for a user avatar. Defaults to no restriction.
  3722. Use M for MB and K for KB. </p>
  3723. <p>Note that user avatar changes will not work if this is set without using Synapse's media repository.</p>
  3724. <p>Example configuration:</p>
  3725. <pre><code class="language-yaml">max_avatar_size: 10M
  3726. </code></pre>
  3727. <hr />
  3728. <h3 id="allowed_avatar_mimetypes"><a class="header" href="#allowed_avatar_mimetypes"><code>allowed_avatar_mimetypes</code></a></h3>
  3729. <p>The MIME types allowed for user avatars. Defaults to no restriction.</p>
  3730. <p>Note that user avatar changes will not work if this is set without
  3731. using Synapse's media repository.</p>
  3732. <p>Example configuration:</p>
  3733. <pre><code class="language-yaml">allowed_avatar_mimetypes: [&quot;image/png&quot;, &quot;image/jpeg&quot;, &quot;image/gif&quot;]
  3734. </code></pre>
  3735. <hr />
  3736. <h3 id="redaction_retention_period"><a class="header" href="#redaction_retention_period"><code>redaction_retention_period</code></a></h3>
  3737. <p>How long to keep redacted events in unredacted form in the database. After
  3738. this period redacted events get replaced with their redacted form in the DB.</p>
  3739. <p>Defaults to <code>7d</code>. Set to <code>null</code> to disable.</p>
  3740. <p>Example configuration:</p>
  3741. <pre><code class="language-yaml">redaction_retention_period: 28d
  3742. </code></pre>
  3743. <hr />
  3744. <h3 id="user_ips_max_age"><a class="header" href="#user_ips_max_age"><code>user_ips_max_age</code></a></h3>
  3745. <p>How long to track users' last seen time and IPs in the database.</p>
  3746. <p>Defaults to <code>28d</code>. Set to <code>null</code> to disable clearing out of old rows.</p>
  3747. <p>Example configuration:</p>
  3748. <pre><code class="language-yaml">user_ips_max_age: 14d
  3749. </code></pre>
  3750. <hr />
  3751. <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>
  3752. <p>Inhibits the <code>/requestToken</code> endpoints from returning an error that might leak
  3753. information about whether an e-mail address is in use or not on this
  3754. homeserver. Defaults to false.
  3755. Note that for some endpoints the error situation is the e-mail already being
  3756. used, and for others the error is entering the e-mail being unused.
  3757. If this option is enabled, instead of returning an error, these endpoints will
  3758. act as if no error happened and return a fake session ID ('sid') to clients.</p>
  3759. <p>Example configuration:</p>
  3760. <pre><code class="language-yaml">request_token_inhibit_3pid_errors: true
  3761. </code></pre>
  3762. <hr />
  3763. <h3 id="next_link_domain_whitelist"><a class="header" href="#next_link_domain_whitelist"><code>next_link_domain_whitelist</code></a></h3>
  3764. <p>A list of domains that the domain portion of <code>next_link</code> parameters
  3765. must match.</p>
  3766. <p>This parameter is optionally provided by clients while requesting
  3767. validation of an email or phone number, and maps to a link that
  3768. users will be automatically redirected to after validation
  3769. succeeds. Clients can make use this parameter to aid the validation
  3770. process.</p>
  3771. <p>The whitelist is applied whether the homeserver or an identity server is handling validation.</p>
  3772. <p>The default value is no whitelist functionality; all domains are
  3773. allowed. Setting this value to an empty list will instead disallow
  3774. all domains.</p>
  3775. <p>Example configuration:</p>
  3776. <pre><code class="language-yaml">next_link_domain_whitelist: [&quot;matrix.org&quot;]
  3777. </code></pre>
  3778. <hr />
  3779. <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>
  3780. <p>These options define templates to use when generating email or HTML page contents.
  3781. The <code>custom_template_directory</code> determines which directory Synapse will try to
  3782. find template files in to use to generate email or HTML page contents.
  3783. If not set, or a file is not found within the template directory, a default
  3784. template from within the Synapse package will be used.</p>
  3785. <p>See <a href="usage/configuration/../../templates.html">here</a> for more
  3786. information about using custom templates.</p>
  3787. <p>Example configuration:</p>
  3788. <pre><code class="language-yaml">templates:
  3789. custom_template_directory: /path/to/custom/templates/
  3790. </code></pre>
  3791. <hr />
  3792. <h3 id="retention"><a class="header" href="#retention"><code>retention</code></a></h3>
  3793. <p>This option and the associated options determine message retention policy at the
  3794. server level.</p>
  3795. <p>Room admins and mods can define a retention period for their rooms using the
  3796. <code>m.room.retention</code> state event, and server admins can cap this period by setting
  3797. the <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> config options.</p>
  3798. <p>If this feature is enabled, Synapse will regularly look for and purge events
  3799. which are older than the room's maximum retention period. Synapse will also
  3800. filter events received over federation so that events that should have been
  3801. purged are ignored and not stored again. </p>
  3802. <p>The message retention policies feature is disabled by default.</p>
  3803. <p>This setting has the following sub-options:</p>
  3804. <ul>
  3805. <li>
  3806. <p><code>default_policy</code>: Default retention policy. If set, Synapse will apply it to rooms that lack the
  3807. 'm.room.retention' state event. This option is further specified by the
  3808. <code>min_lifetime</code> and <code>max_lifetime</code> sub-options associated with it. Note that the
  3809. value of <code>min_lifetime</code> doesn't matter much because Synapse doesn't take it into account yet. </p>
  3810. </li>
  3811. <li>
  3812. <p><code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code>: Retention policy limits. If
  3813. set, and the state of a room contains a <code>m.room.retention</code> event in its state
  3814. which contains a <code>min_lifetime</code> or a <code>max_lifetime</code> that's out of these bounds,
  3815. Synapse will cap the room's policy to these limits when running purge jobs.</p>
  3816. </li>
  3817. <li>
  3818. <p><code>purge_jobs</code> and the associated <code>shortest_max_lifetime</code> and <code>longest_max_lifetime</code> sub-options:
  3819. Server admins can define the settings of the background jobs purging the
  3820. events whose lifetime has expired under the <code>purge_jobs</code> section.</p>
  3821. <p>If no configuration is provided for this option, a single job will be set up to delete
  3822. expired events in every room daily.</p>
  3823. <p>Each job's configuration defines which range of message lifetimes the job
  3824. takes care of. For example, if <code>shortest_max_lifetime</code> is '2d' and
  3825. <code>longest_max_lifetime</code> is '3d', the job will handle purging expired events in
  3826. rooms whose state defines a <code>max_lifetime</code> that's both higher than 2 days, and
  3827. lower than or equal to 3 days. Both the minimum and the maximum value of a
  3828. range are optional, e.g. a job with no <code>shortest_max_lifetime</code> and a
  3829. <code>longest_max_lifetime</code> of '3d' will handle every room with a retention policy
  3830. whose <code>max_lifetime</code> is lower than or equal to three days.</p>
  3831. <p>The rationale for this per-job configuration is that some rooms might have a
  3832. retention policy with a low <code>max_lifetime</code>, where history needs to be purged
  3833. of outdated messages on a more frequent basis than for the rest of the rooms
  3834. (e.g. every 12h), but not want that purge to be performed by a job that's
  3835. iterating over every room it knows, which could be heavy on the server.</p>
  3836. <p>If any purge job is configured, it is strongly recommended to have at least
  3837. a single job with neither <code>shortest_max_lifetime</code> nor <code>longest_max_lifetime</code>
  3838. set, or one job without <code>shortest_max_lifetime</code> and one job without
  3839. <code>longest_max_lifetime</code> set. Otherwise some rooms might be ignored, even if
  3840. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> are set, because capping a
  3841. room's policy to these values is done after the policies are retrieved from
  3842. Synapse's database (which is done using the range specified in a purge job's
  3843. configuration).</p>
  3844. </li>
  3845. </ul>
  3846. <p>Example configuration:</p>
  3847. <pre><code class="language-yaml">retention:
  3848. enabled: true
  3849. default_policy:
  3850. min_lifetime: 1d
  3851. max_lifetime: 1y
  3852. allowed_lifetime_min: 1d
  3853. allowed_lifetime_max: 1y
  3854. purge_jobs:
  3855. - longest_max_lifetime: 3d
  3856. interval: 12h
  3857. - shortest_max_lifetime: 3d
  3858. interval: 1d
  3859. </code></pre>
  3860. <hr />
  3861. <h2 id="tls"><a class="header" href="#tls">TLS</a></h2>
  3862. <p>Options related to TLS.</p>
  3863. <hr />
  3864. <h3 id="tls_certificate_path"><a class="header" href="#tls_certificate_path"><code>tls_certificate_path</code></a></h3>
  3865. <p>This option specifies a PEM-encoded X509 certificate for TLS.
  3866. This certificate, as of Synapse 1.0, will need to be a valid and verifiable
  3867. certificate, signed by a recognised Certificate Authority. Defaults to none. </p>
  3868. <p>Be sure to use a <code>.pem</code> file that includes the full certificate chain including
  3869. any intermediate certificates (for instance, if using certbot, use
  3870. <code>fullchain.pem</code> as your certificate, not <code>cert.pem</code>). </p>
  3871. <p>Example configuration:</p>
  3872. <pre><code class="language-yaml">tls_certificate_path: &quot;CONFDIR/SERVERNAME.tls.crt&quot;
  3873. </code></pre>
  3874. <hr />
  3875. <h3 id="tls_private_key_path"><a class="header" href="#tls_private_key_path"><code>tls_private_key_path</code></a></h3>
  3876. <p>PEM-encoded private key for TLS. Defaults to none. </p>
  3877. <p>Example configuration:</p>
  3878. <pre><code class="language-yaml">tls_private_key_path: &quot;CONFDIR/SERVERNAME.tls.key&quot;
  3879. </code></pre>
  3880. <hr />
  3881. <h3 id="federation_verify_certificates"><a class="header" href="#federation_verify_certificates"><code>federation_verify_certificates</code></a></h3>
  3882. <p>Whether to verify TLS server certificates for outbound federation requests.</p>
  3883. <p>Defaults to true. To disable certificate verification, set the option to false.</p>
  3884. <p>Example configuration:</p>
  3885. <pre><code class="language-yaml">federation_verify_certificates: false
  3886. </code></pre>
  3887. <hr />
  3888. <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>
  3889. <p>The minimum TLS version that will be used for outbound federation requests.</p>
  3890. <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
  3891. that setting this value higher than <code>1.2</code> will prevent federation to most
  3892. of the public Matrix network: only configure it to <code>1.3</code> if you have an
  3893. entirely private federation setup and you can ensure TLS 1.3 support.</p>
  3894. <p>Example configuration:</p>
  3895. <pre><code class="language-yaml">federation_client_minimum_tls_version: 1.2
  3896. </code></pre>
  3897. <hr />
  3898. <h3 id="federation_certificate_verification_whitelist"><a class="header" href="#federation_certificate_verification_whitelist"><code>federation_certificate_verification_whitelist</code></a></h3>
  3899. <p>Skip federation certificate verification on a given whitelist
  3900. of domains.</p>
  3901. <p>This setting should only be used in very specific cases, such as
  3902. federation over Tor hidden services and similar. For private networks
  3903. of homeservers, you likely want to use a private CA instead.</p>
  3904. <p>Only effective if <code>federation_verify_certicates</code> is <code>true</code>.</p>
  3905. <p>Example configuration:</p>
  3906. <pre><code class="language-yaml">federation_certificate_verification_whitelist:
  3907. - lon.example.com
  3908. - &quot;*.domain.com&quot;
  3909. - &quot;*.onion&quot;
  3910. </code></pre>
  3911. <hr />
  3912. <h3 id="federation_custom_ca_list"><a class="header" href="#federation_custom_ca_list"><code>federation_custom_ca_list</code></a></h3>
  3913. <p>List of custom certificate authorities for federation traffic.</p>
  3914. <p>This setting should only normally be used within a private network of
  3915. homeservers.</p>
  3916. <p>Note that this list will replace those that are provided by your
  3917. operating environment. Certificates must be in PEM format.</p>
  3918. <p>Example configuration:</p>
  3919. <pre><code class="language-yaml">federation_custom_ca_list:
  3920. - myCA1.pem
  3921. - myCA2.pem
  3922. - myCA3.pem
  3923. </code></pre>
  3924. <hr />
  3925. <h2 id="federation"><a class="header" href="#federation">Federation</a></h2>
  3926. <p>Options related to federation.</p>
  3927. <hr />
  3928. <h3 id="federation_domain_whitelist"><a class="header" href="#federation_domain_whitelist"><code>federation_domain_whitelist</code></a></h3>
  3929. <p>Restrict federation to the given whitelist of domains.
  3930. N.B. we recommend also firewalling your federation listener to limit
  3931. inbound federation traffic as early as possible, rather than relying
  3932. purely on this application-layer restriction. If not specified, the
  3933. default is to whitelist everything.</p>
  3934. <p>Example configuration:</p>
  3935. <pre><code class="language-yaml">federation_domain_whitelist:
  3936. - lon.example.com
  3937. - nyc.example.com
  3938. - syd.example.com
  3939. </code></pre>
  3940. <hr />
  3941. <h3 id="federation_metrics_domains"><a class="header" href="#federation_metrics_domains"><code>federation_metrics_domains</code></a></h3>
  3942. <p>Report prometheus metrics on the age of PDUs being sent to and received from
  3943. the given domains. This can be used to give an idea of &quot;delay&quot; on inbound
  3944. and outbound federation, though be aware that any delay can be due to problems
  3945. at either end or with the intermediate network.</p>
  3946. <p>By default, no domains are monitored in this way.</p>
  3947. <p>Example configuration:</p>
  3948. <pre><code class="language-yaml">federation_metrics_domains:
  3949. - matrix.org
  3950. - example.com
  3951. </code></pre>
  3952. <hr />
  3953. <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>
  3954. <p>Set to false to disable profile lookup over federation. By default, the
  3955. Federation API allows other homeservers to obtain profile data of any user
  3956. on this homeserver.</p>
  3957. <p>Example configuration:</p>
  3958. <pre><code class="language-yaml">allow_profile_lookup_over_federation: false
  3959. </code></pre>
  3960. <hr />
  3961. <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>
  3962. <p>Set this option to true to allow device display name lookup over federation. By default, the
  3963. Federation API prevents other homeservers from obtaining the display names of any user devices
  3964. on this homeserver.</p>
  3965. <p>Example configuration:</p>
  3966. <pre><code class="language-yaml">allow_device_name_lookup_over_federation: true
  3967. </code></pre>
  3968. <hr />
  3969. <h2 id="caching"><a class="header" href="#caching">Caching</a></h2>
  3970. <p>Options related to caching</p>
  3971. <hr />
  3972. <h3 id="event_cache_size"><a class="header" href="#event_cache_size"><code>event_cache_size</code></a></h3>
  3973. <p>The number of events to cache in memory. Not affected by
  3974. <code>caches.global_factor</code>. Defaults to 10K.</p>
  3975. <p>Example configuration:</p>
  3976. <pre><code class="language-yaml">event_cache_size: 15K
  3977. </code></pre>
  3978. <hr />
  3979. <h3 id="cache-and-associated-values"><a class="header" href="#cache-and-associated-values"><code>cache</code> and associated values</a></h3>
  3980. <p>A cache 'factor' is a multiplier that can be applied to each of
  3981. Synapse's caches in order to increase or decrease the maximum
  3982. number of entries that can be stored.</p>
  3983. <p>Caching can be configured through the following sub-options:</p>
  3984. <ul>
  3985. <li>
  3986. <p><code>global_factor</code>: Controls the global cache factor, which is the default cache factor
  3987. for all caches if a specific factor for that cache is not otherwise
  3988. set.</p>
  3989. <p>This can also be set by the <code>SYNAPSE_CACHE_FACTOR</code> environment
  3990. variable. Setting by environment variable takes priority over
  3991. setting through the config file.</p>
  3992. <p>Defaults to 0.5, which will halve the size of all caches.</p>
  3993. </li>
  3994. <li>
  3995. <p><code>per_cache_factors</code>: A dictionary of cache name to cache factor for that individual
  3996. cache. Overrides the global cache factor for a given cache.</p>
  3997. <p>These can also be set through environment variables comprised
  3998. of <code>SYNAPSE_CACHE_FACTOR_</code> + the name of the cache in capital
  3999. letters and underscores. Setting by environment variable
  4000. takes priority over setting through the config file.
  4001. Ex. <code>SYNAPSE_CACHE_FACTOR_GET_USERS_WHO_SHARE_ROOM_WITH_USER=2.0</code></p>
  4002. <p>Some caches have '*' and other characters that are not
  4003. alphanumeric or underscores. These caches can be named with or
  4004. without the special characters stripped. For example, to specify
  4005. the cache factor for <code>*stateGroupCache*</code> via an environment
  4006. variable would be <code>SYNAPSE_CACHE_FACTOR_STATEGROUPCACHE=2.0</code>.</p>
  4007. </li>
  4008. <li>
  4009. <p><code>expire_caches</code>: Controls whether cache entries are evicted after a specified time
  4010. period. Defaults to true. Set to false to disable this feature. Note that never expiring
  4011. caches may result in excessive memory usage. </p>
  4012. </li>
  4013. <li>
  4014. <p><code>cache_entry_ttl</code>: If <code>expire_caches</code> is enabled, this flag controls how long an entry can
  4015. be in a cache without having been accessed before being evicted.
  4016. Defaults to 30m. </p>
  4017. </li>
  4018. <li>
  4019. <p><code>sync_response_cache_duration</code>: Controls how long the results of a /sync request are
  4020. cached for after a successful response is returned. A higher duration can help clients
  4021. with intermittent connections, at the cost of higher memory usage.
  4022. A value of zero means that sync responses are not cached.
  4023. Defaults to 2m.</p>
  4024. </li>
  4025. <li>
  4026. <p><code>cache_autotuning</code> and its sub-options <code>max_cache_memory_usage</code>, <code>target_cache_memory_usage</code>, and
  4027. <code>min_cache_ttl</code> work in conjunction with each other to maintain a balance between cache memory
  4028. 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>
  4029. to utilize this option, and all three of the options must be specified for this feature to work. This option
  4030. defaults to off, enable it by providing values for the sub-options listed below. Please note that the feature will not work
  4031. and may cause unstable behavior (such as excessive emptying of caches or exceptions) if all of the values are not provided.
  4032. 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
  4033. durations.</p>
  4034. <ul>
  4035. <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.
  4036. They will continue to be evicted until the memory usage drops below the <code>target_memory_usage</code>, set in
  4037. the setting below, or until the <code>min_cache_ttl</code> is hit. There is no default value for this option.</li>
  4038. <li><code>target_memory_usage</code> sets a rough target for the desired memory usage of the caches. There is no default value
  4039. for this option.</li>
  4040. <li><code>min_cache_ttl</code> sets a limit under which newer cache entries are not evicted and is only applied when
  4041. caches are actively being evicted/<code>max_cache_memory_usage</code> has been exceeded. This is to protect hot caches
  4042. from being emptied while Synapse is evicting due to memory. There is no default value for this option. </li>
  4043. </ul>
  4044. </li>
  4045. </ul>
  4046. <p>Example configuration:</p>
  4047. <pre><code class="language-yaml">caches:
  4048. global_factor: 1.0
  4049. per_cache_factors:
  4050. get_users_who_share_room_with_user: 2.0
  4051. sync_response_cache_duration: 2m
  4052. cache_autotuning:
  4053. max_cache_memory_usage: 1024M
  4054. target_cache_memory_usage: 758M
  4055. min_cache_ttl: 5m
  4056. </code></pre>
  4057. <h3 id="reloading-cache-factors"><a class="header" href="#reloading-cache-factors">Reloading cache factors</a></h3>
  4058. <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
  4059. <a href="https://en.wikipedia.org/wiki/SIGHUP"><code>SIGHUP</code></a> signal to Synapse using e.g.</p>
  4060. <pre><code class="language-commandline">kill -HUP [PID_OF_SYNAPSE_PROCESS]
  4061. </code></pre>
  4062. <p>If you are running multiple workers, you must individually update the worker
  4063. config file and send this signal to each worker process.</p>
  4064. <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>
  4065. file in Synapse's <code>contrib</code> directory, you can send a <code>SIGHUP</code> signal by using
  4066. <code>systemctl reload matrix-synapse</code>.</p>
  4067. <hr />
  4068. <h2 id="database"><a class="header" href="#database">Database</a></h2>
  4069. <p>Config options related to database settings.</p>
  4070. <hr />
  4071. <h3 id="database-1"><a class="header" href="#database-1"><code>database</code></a></h3>
  4072. <p>The <code>database</code> setting defines the database that synapse uses to store all of
  4073. its data.</p>
  4074. <p>Associated sub-options:</p>
  4075. <ul>
  4076. <li>
  4077. <p><code>name</code>: this option specifies the database engine to use: either <code>sqlite3</code> (for SQLite)
  4078. or <code>psycopg2</code> (for PostgreSQL). If no name is specified Synapse will default to SQLite. </p>
  4079. </li>
  4080. <li>
  4081. <p><code>txn_limit</code> gives the maximum number of transactions to run per connection
  4082. before reconnecting. Defaults to 0, which means no limit.</p>
  4083. </li>
  4084. <li>
  4085. <p><code>allow_unsafe_locale</code> is an option specific to Postgres. Under the default behavior, Synapse will refuse to
  4086. start if the postgres db is set to a non-C locale. You can override this behavior (which is <em>not</em> recommended)
  4087. by setting <code>allow_unsafe_locale</code> to true. Note that doing so may corrupt your database. You can find more information
  4088. <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>
  4089. </li>
  4090. <li>
  4091. <p><code>args</code> gives options which are passed through to the database engine,
  4092. except for options starting with <code>cp_</code>, which are used to configure the Twisted
  4093. connection pool. For a reference to valid arguments, see:</p>
  4094. <ul>
  4095. <li>for <a href="https://docs.python.org/3/library/sqlite3.html#sqlite3.connect">sqlite</a></li>
  4096. <li>for <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">postgres</a></li>
  4097. <li>for <a href="https://twistedmatrix.com/documents/current/api/twisted.enterprise.adbapi.ConnectionPool.html#__init__">the connection pool</a></li>
  4098. </ul>
  4099. </li>
  4100. </ul>
  4101. <p>For more information on using Synapse with Postgres,
  4102. see <a href="usage/configuration/../../postgres.html">here</a>.</p>
  4103. <p>Example SQLite configuration:</p>
  4104. <pre><code class="language-yaml">database:
  4105. name: sqlite3
  4106. args:
  4107. database: /path/to/homeserver.db
  4108. </code></pre>
  4109. <p>Example Postgres configuration:</p>
  4110. <pre><code class="language-yaml">database:
  4111. name: psycopg2
  4112. txn_limit: 10000
  4113. args:
  4114. user: synapse_user
  4115. password: secretpassword
  4116. database: synapse
  4117. host: localhost
  4118. port: 5432
  4119. cp_min: 5
  4120. cp_max: 10
  4121. </code></pre>
  4122. <hr />
  4123. <h2 id="logging"><a class="header" href="#logging">Logging</a></h2>
  4124. <p>Config options related to logging. </p>
  4125. <hr />
  4126. <h3 id="log_config"><a class="header" href="#log_config"><code>log_config</code></a></h3>
  4127. <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>
  4128. <p>Example configuration:</p>
  4129. <pre><code class="language-yaml">log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  4130. </code></pre>
  4131. <hr />
  4132. <h2 id="ratelimiting"><a class="header" href="#ratelimiting">Ratelimiting</a></h2>
  4133. <p>Options related to ratelimiting in Synapse. </p>
  4134. <p>Each ratelimiting configuration is made of two parameters:</p>
  4135. <ul>
  4136. <li><code>per_second</code>: number of requests a client can send per second.</li>
  4137. <li><code>burst_count</code>: number of requests a client can send before being throttled.</li>
  4138. </ul>
  4139. <hr />
  4140. <h3 id="rc_message"><a class="header" href="#rc_message"><code>rc_message</code></a></h3>
  4141. <p>Ratelimiting settings for client messaging.</p>
  4142. <p>This is a ratelimiting option for messages that ratelimits sending based on the account the client
  4143. is using. It defaults to: <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
  4144. <p>Example configuration:</p>
  4145. <pre><code class="language-yaml">rc_message:
  4146. per_second: 0.5
  4147. burst_count: 15
  4148. </code></pre>
  4149. <hr />
  4150. <h3 id="rc_registration"><a class="header" href="#rc_registration"><code>rc_registration</code></a></h3>
  4151. <p>This option ratelimits registration requests based on the client's IP address.
  4152. It defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>. </p>
  4153. <p>Example configuration:</p>
  4154. <pre><code class="language-yaml">rc_registration:
  4155. per_second: 0.15
  4156. burst_count: 2
  4157. </code></pre>
  4158. <hr />
  4159. <h3 id="rc_registration_token_validity"><a class="header" href="#rc_registration_token_validity"><code>rc_registration_token_validity</code></a></h3>
  4160. <p>This option checks the validity of registration tokens that ratelimits requests based on
  4161. the client's IP address.
  4162. Defaults to <code>per_second: 0.1</code>, <code>burst_count: 5</code>.</p>
  4163. <p>Example configuration:</p>
  4164. <pre><code class="language-yaml">rc_registration_token_validity:
  4165. per_second: 0.3
  4166. burst_count: 6
  4167. </code></pre>
  4168. <hr />
  4169. <h3 id="rc_login"><a class="header" href="#rc_login"><code>rc_login</code></a></h3>
  4170. <p>This option specifies several limits for login:</p>
  4171. <ul>
  4172. <li>
  4173. <p><code>address</code> ratelimits login requests based on the client's IP
  4174. address. Defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  4175. </li>
  4176. <li>
  4177. <p><code>account</code> ratelimits login requests based on the account the
  4178. client is attempting to log into. Defaults to <code>per_second: 0.17</code>,
  4179. <code>burst_count: 3</code>.</p>
  4180. </li>
  4181. <li>
  4182. <p><code>failted_attempts</code> ratelimits login requests based on the account the
  4183. client is attempting to log into, based on the amount of failed login
  4184. attempts for this account. Defaults to <code>per_second: 0.17</code>, <code>burst_count: 3</code>.</p>
  4185. </li>
  4186. </ul>
  4187. <p>Example configuration:</p>
  4188. <pre><code class="language-yaml">rc_login:
  4189. address:
  4190. per_second: 0.15
  4191. burst_count: 5
  4192. account:
  4193. per_second: 0.18
  4194. burst_count: 4
  4195. failed_attempts:
  4196. per_second: 0.19
  4197. burst_count: 7
  4198. </code></pre>
  4199. <hr />
  4200. <h3 id="rc_admin_redaction"><a class="header" href="#rc_admin_redaction"><code>rc_admin_redaction</code></a></h3>
  4201. <p>This option sets ratelimiting redactions by room admins. If this is not explicitly
  4202. set then it uses the same ratelimiting as per <code>rc_message</code>. This is useful
  4203. to allow room admins to deal with abuse quickly. </p>
  4204. <p>Example configuration:</p>
  4205. <pre><code class="language-yaml">rc_admin_redaction:
  4206. per_second: 1
  4207. burst_count: 50
  4208. </code></pre>
  4209. <hr />
  4210. <h3 id="rc_joins"><a class="header" href="#rc_joins"><code>rc_joins</code></a></h3>
  4211. <p>This option allows for ratelimiting number of rooms a user can join. This setting has the following sub-options:</p>
  4212. <ul>
  4213. <li>
  4214. <p><code>local</code>: ratelimits when users are joining rooms the server is already in.
  4215. Defaults to <code>per_second: 0.1</code>, <code>burst_count: 10</code>.</p>
  4216. </li>
  4217. <li>
  4218. <p><code>remote</code>: ratelimits when users are trying to join rooms not on the server (which
  4219. can be more computationally expensive than restricting locally). Defaults to
  4220. <code>per_second: 0.01</code>, <code>burst_count: 10</code> </p>
  4221. </li>
  4222. </ul>
  4223. <p>Example configuration:</p>
  4224. <pre><code class="language-yaml">rc_joins:
  4225. local:
  4226. per_second: 0.2
  4227. burst_count: 15
  4228. remote:
  4229. per_second: 0.03
  4230. burst_count: 12
  4231. </code></pre>
  4232. <hr />
  4233. <h3 id="rc_3pid_validation"><a class="header" href="#rc_3pid_validation"><code>rc_3pid_validation</code></a></h3>
  4234. <p>This option ratelimits how often a user or IP can attempt to validate a 3PID.
  4235. Defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>.</p>
  4236. <p>Example configuration:</p>
  4237. <pre><code class="language-yaml">rc_3pid_validation:
  4238. per_second: 0.003
  4239. burst_count: 5
  4240. </code></pre>
  4241. <hr />
  4242. <h3 id="rc_invites"><a class="header" href="#rc_invites"><code>rc_invites</code></a></h3>
  4243. <p>This option sets ratelimiting how often invites can be sent in a room or to a
  4244. specific user. <code>per_room</code> defaults to <code>per_second: 0.3</code>, <code>burst_count: 10</code> and
  4245. <code>per_user</code> defaults to <code>per_second: 0.003</code>, <code>burst_count: 5</code>. </p>
  4246. <p>Client requests that invite user(s) when <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3createroom">creating a
  4247. room</a>
  4248. will count against the <code>rc_invites.per_room</code> limit, whereas
  4249. client requests to <a href="https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3roomsroomidinvite">invite a single user to a
  4250. room</a>
  4251. will count against both the <code>rc_invites.per_user</code> and <code>rc_invites.per_room</code> limits.</p>
  4252. <p>Federation requests to invite a user will count against the <code>rc_invites.per_user</code>
  4253. limit only, as Synapse presumes ratelimiting by room will be done by the sending server.</p>
  4254. <p>The <code>rc_invites.per_user</code> limit applies to the <em>receiver</em> of the invite, rather than the
  4255. sender, meaning that a <code>rc_invite.per_user.burst_count</code> of 5 mandates that a single user
  4256. cannot <em>receive</em> more than a burst of 5 invites at a time.</p>
  4257. <p>Example configuration:</p>
  4258. <pre><code class="language-yaml">rc_invites:
  4259. per_room:
  4260. per_second: 0.5
  4261. burst_count: 5
  4262. per_user:
  4263. per_second: 0.004
  4264. burst_count: 3
  4265. </code></pre>
  4266. <hr />
  4267. <h3 id="rc_third_party_invite"><a class="header" href="#rc_third_party_invite"><code>rc_third_party_invite</code></a></h3>
  4268. <p>This option ratelimits 3PID invites (i.e. invites sent to a third-party ID
  4269. such as an email address or a phone number) based on the account that's
  4270. sending the invite. Defaults to <code>per_second: 0.2</code>, <code>burst_count: 10</code>.</p>
  4271. <p>Example configuration:</p>
  4272. <pre><code class="language-yaml">rc_third_party_invite:
  4273. per_second: 0.2
  4274. burst_count: 10
  4275. </code></pre>
  4276. <hr />
  4277. <h3 id="rc_federation"><a class="header" href="#rc_federation"><code>rc_federation</code></a></h3>
  4278. <p>Defines limits on federation requests. </p>
  4279. <p>The <code>rc_federation</code> configuration has the following sub-options:</p>
  4280. <ul>
  4281. <li><code>window_size</code>: window size in milliseconds. Defaults to 1000.</li>
  4282. <li><code>sleep_limit</code>: number of federation requests from a single server in
  4283. a window before the server will delay processing the request. Defaults to 10.</li>
  4284. <li><code>sleep_delay</code>: duration in milliseconds to delay processing events
  4285. from remote servers by if they go over the sleep limit. Defaults to 500.</li>
  4286. <li><code>reject_limit</code>: maximum number of concurrent federation requests
  4287. allowed from a single server. Defaults to 50.</li>
  4288. <li><code>concurrent</code>: number of federation requests to concurrently process
  4289. from a single server. Defaults to 3.</li>
  4290. </ul>
  4291. <p>Example configuration:</p>
  4292. <pre><code class="language-yaml">rc_federation:
  4293. window_size: 750
  4294. sleep_limit: 15
  4295. sleep_delay: 400
  4296. reject_limit: 40
  4297. concurrent: 5
  4298. </code></pre>
  4299. <hr />
  4300. <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>
  4301. <p>Sets outgoing federation transaction frequency for sending read-receipts,
  4302. per-room.</p>
  4303. <p>If we end up trying to send out more read-receipts, they will get buffered up
  4304. into fewer transactions. Defaults to 50. </p>
  4305. <p>Example configuration:</p>
  4306. <pre><code class="language-yaml">federation_rr_transactions_per_room_per_second: 40
  4307. </code></pre>
  4308. <hr />
  4309. <h2 id="media-store"><a class="header" href="#media-store">Media Store</a></h2>
  4310. <p>Config options related to Synapse's media store.</p>
  4311. <hr />
  4312. <h3 id="enable_media_repo"><a class="header" href="#enable_media_repo"><code>enable_media_repo</code></a></h3>
  4313. <p>Enable the media store service in the Synapse master. Defaults to true.
  4314. Set to false if you are using a separate media store worker.</p>
  4315. <p>Example configuration:</p>
  4316. <pre><code class="language-yaml">enable_media_repo: false
  4317. </code></pre>
  4318. <hr />
  4319. <h3 id="media_store_path"><a class="header" href="#media_store_path"><code>media_store_path</code></a></h3>
  4320. <p>Directory where uploaded images and attachments are stored.</p>
  4321. <p>Example configuration:</p>
  4322. <pre><code class="language-yaml">media_store_path: &quot;DATADIR/media_store&quot;
  4323. </code></pre>
  4324. <hr />
  4325. <h3 id="media_storage_providers"><a class="header" href="#media_storage_providers"><code>media_storage_providers</code></a></h3>
  4326. <p>Media storage providers allow media to be stored in different
  4327. locations. Defaults to none. Associated sub-options are:</p>
  4328. <ul>
  4329. <li><code>module</code>: type of resource, e.g. <code>file_system</code>.</li>
  4330. <li><code>store_local</code>: whether to store newly uploaded local files</li>
  4331. <li><code>store_remote</code>: whether to store newly downloaded local files</li>
  4332. <li><code>store_synchronous</code>: whether to wait for successful storage for local uploads</li>
  4333. <li><code>config</code>: sets a path to the resource through the <code>directory</code> option </li>
  4334. </ul>
  4335. <p>Example configuration:</p>
  4336. <pre><code class="language-yaml">media_storage_providers:
  4337. - module: file_system
  4338. store_local: false
  4339. store_remote: false
  4340. store_synchronous: false
  4341. config:
  4342. directory: /mnt/some/other/directory
  4343. </code></pre>
  4344. <hr />
  4345. <h3 id="max_upload_size"><a class="header" href="#max_upload_size"><code>max_upload_size</code></a></h3>
  4346. <p>The largest allowed upload size in bytes.</p>
  4347. <p>If you are using a reverse proxy you may also need to set this value in
  4348. your reverse proxy's config. Defaults to 50M. Notably Nginx has a small max body size by default.
  4349. See <a href="usage/configuration/../../reverse_proxy.html">here</a> for more on using a reverse proxy with Synapse. </p>
  4350. <p>Example configuration:</p>
  4351. <pre><code class="language-yaml">max_upload_size: 60M
  4352. </code></pre>
  4353. <hr />
  4354. <h3 id="max_image_pixels"><a class="header" href="#max_image_pixels"><code>max_image_pixels</code></a></h3>
  4355. <p>Maximum number of pixels that will be thumbnailed. Defaults to 32M.</p>
  4356. <p>Example configuration:</p>
  4357. <pre><code class="language-yaml">max_image_pixels: 35M
  4358. </code></pre>
  4359. <hr />
  4360. <h3 id="dynamic_thumbnails"><a class="header" href="#dynamic_thumbnails"><code>dynamic_thumbnails</code></a></h3>
  4361. <p>Whether to generate new thumbnails on the fly to precisely match
  4362. the resolution requested by the client. If true then whenever
  4363. a new resolution is requested by the client the server will
  4364. generate a new thumbnail. If false the server will pick a thumbnail
  4365. from a precalculated list. Defaults to false. </p>
  4366. <p>Example configuration:</p>
  4367. <pre><code class="language-yaml">dynamic_thumbnails: true
  4368. </code></pre>
  4369. <hr />
  4370. <h3 id="thumbnail_sizes"><a class="header" href="#thumbnail_sizes"><code>thumbnail_sizes</code></a></h3>
  4371. <p>List of thumbnails to precalculate when an image is uploaded. Associated sub-options are:</p>
  4372. <ul>
  4373. <li><code>width</code></li>
  4374. <li><code>height</code></li>
  4375. <li><code>method</code>: i.e. <code>crop</code>, <code>scale</code>, etc.</li>
  4376. </ul>
  4377. <p>Example configuration:</p>
  4378. <pre><code class="language-yaml">thumbnail_sizes:
  4379. - width: 32
  4380. height: 32
  4381. method: crop
  4382. - width: 96
  4383. height: 96
  4384. method: crop
  4385. - width: 320
  4386. height: 240
  4387. method: scale
  4388. - width: 640
  4389. height: 480
  4390. method: scale
  4391. - width: 800
  4392. height: 600
  4393. method: scale
  4394. </code></pre>
  4395. <hr />
  4396. <h3 id="media_retention"><a class="header" href="#media_retention"><code>media_retention</code></a></h3>
  4397. <p>Controls whether local media and entries in the remote media cache
  4398. (media that is downloaded from other homeservers) should be removed
  4399. under certain conditions, typically for the purpose of saving space.</p>
  4400. <p>Purging media files will be the carried out by the media worker
  4401. (that is, the worker that has the <code>enable_media_repo</code> homeserver config
  4402. option set to 'true'). This may be the main process.</p>
  4403. <p>The <code>media_retention.local_media_lifetime</code> and
  4404. <code>media_retention.remote_media_lifetime</code> config options control whether
  4405. media will be purged if it has not been accessed in a given amount of
  4406. time. Note that media is 'accessed' when loaded in a room in a client, or
  4407. otherwise downloaded by a local or remote user. If the media has never
  4408. been accessed, the media's creation time is used instead. Both thumbnails
  4409. and the original media will be removed. If either of these options are unset,
  4410. then media of that type will not be purged.</p>
  4411. <p>Local or cached remote media that has been
  4412. <a href="usage/configuration/../../admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantined</a>
  4413. will not be deleted. Similarly, local media that has been marked as
  4414. <a href="usage/configuration/../../admin_api/media_admin_api.html#protecting-media-from-being-quarantined">protected from quarantine</a>
  4415. will not be deleted.</p>
  4416. <p>Example configuration:</p>
  4417. <pre><code class="language-yaml">media_retention:
  4418. local_media_lifetime: 90d
  4419. remote_media_lifetime: 14d
  4420. </code></pre>
  4421. <hr />
  4422. <h3 id="url_preview_enabled"><a class="header" href="#url_preview_enabled"><code>url_preview_enabled</code></a></h3>
  4423. <p>This setting determines whether the preview URL API is enabled.
  4424. It is disabled by default. Set to true to enable. If enabled you must specify a
  4425. <code>url_preview_ip_range_blacklist</code> blacklist.</p>
  4426. <p>Example configuration:</p>
  4427. <pre><code class="language-yaml">url_preview_enabled: true
  4428. </code></pre>
  4429. <hr />
  4430. <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>
  4431. <p>List of IP address CIDR ranges that the URL preview spider is denied
  4432. from accessing. There are no defaults: you must explicitly
  4433. specify a list for URL previewing to work. You should specify any
  4434. internal services in your network that you do not want synapse to try
  4435. to connect to, otherwise anyone in any Matrix room could cause your
  4436. synapse to issue arbitrary GET requests to your internal services,
  4437. causing serious security issues.</p>
  4438. <p>(0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  4439. listed here, since they correspond to unroutable addresses.)</p>
  4440. <p>This must be specified if <code>url_preview_enabled</code> is set. It is recommended that
  4441. you use the following example list as a starting point.</p>
  4442. <p>Note: The value is ignored when an HTTP proxy is in use.</p>
  4443. <p>Example configuration:</p>
  4444. <pre><code class="language-yaml">url_preview_ip_range_blacklist:
  4445. - '127.0.0.0/8'
  4446. - '10.0.0.0/8'
  4447. - '172.16.0.0/12'
  4448. - '192.168.0.0/16'
  4449. - '100.64.0.0/10'
  4450. - '192.0.0.0/24'
  4451. - '169.254.0.0/16'
  4452. - '192.88.99.0/24'
  4453. - '198.18.0.0/15'
  4454. - '192.0.2.0/24'
  4455. - '198.51.100.0/24'
  4456. - '203.0.113.0/24'
  4457. - '224.0.0.0/4'
  4458. - '::1/128'
  4459. - 'fe80::/10'
  4460. - 'fc00::/7'
  4461. - '2001:db8::/32'
  4462. - 'ff00::/8'
  4463. - 'fec0::/10'
  4464. </code></pre>
  4465. <hr />
  4466. <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>
  4467. <p>This option sets a list of IP address CIDR ranges that the URL preview spider is allowed
  4468. to access even if they are specified in <code>url_preview_ip_range_blacklist</code>.
  4469. This is useful for specifying exceptions to wide-ranging blacklisted
  4470. target IP ranges - e.g. for enabling URL previews for a specific private
  4471. website only visible in your network. Defaults to none. </p>
  4472. <p>Example configuration:</p>
  4473. <pre><code class="language-yaml">url_preview_ip_range_whitelist:
  4474. - '192.168.1.1'
  4475. </code></pre>
  4476. <hr />
  4477. <h3 id="url_preview_url_blacklist"><a class="header" href="#url_preview_url_blacklist"><code>url_preview_url_blacklist</code></a></h3>
  4478. <p>Optional list of URL matches that the URL preview spider is
  4479. denied from accessing. You should use <code>url_preview_ip_range_blacklist</code>
  4480. in preference to this, otherwise someone could define a public DNS
  4481. entry that points to a private IP address and circumvent the blacklist.
  4482. This is more useful if you know there is an entire shape of URL that
  4483. you know that will never want synapse to try to spider.</p>
  4484. <p>Each list entry is a dictionary of url component attributes as returned
  4485. by urlparse.urlsplit as applied to the absolute form of the URL. See
  4486. <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit">here</a> for more
  4487. information. Some examples are:</p>
  4488. <ul>
  4489. <li><code>username</code></li>
  4490. <li><code>netloc</code></li>
  4491. <li><code>scheme</code></li>
  4492. <li><code>path</code></li>
  4493. </ul>
  4494. <p>The values of the dictionary are treated as a filename match pattern
  4495. applied to that component of URLs, unless they start with a ^ in which
  4496. case they are treated as a regular expression match. If all the
  4497. specified component matches for a given list item succeed, the URL is
  4498. blacklisted.</p>
  4499. <p>Example configuration:</p>
  4500. <pre><code class="language-yaml">url_preview_url_blacklist:
  4501. # blacklist any URL with a username in its URI
  4502. - username: '*'
  4503. # blacklist all *.google.com URLs
  4504. - netloc: 'google.com'
  4505. - netloc: '*.google.com'
  4506. # blacklist all plain HTTP URLs
  4507. - scheme: 'http'
  4508. # blacklist http(s)://www.acme.com/foo
  4509. - netloc: 'www.acme.com'
  4510. path: '/foo'
  4511. # blacklist any URL with a literal IPv4 address
  4512. - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
  4513. </code></pre>
  4514. <hr />
  4515. <h3 id="max_spider_size"><a class="header" href="#max_spider_size"><code>max_spider_size</code></a></h3>
  4516. <p>The largest allowed URL preview spidering size in bytes. Defaults to 10M.</p>
  4517. <p>Example configuration:</p>
  4518. <pre><code class="language-yaml">max_spider_size: 8M
  4519. </code></pre>
  4520. <hr />
  4521. <h3 id="url_preview_language"><a class="header" href="#url_preview_language"><code>url_preview_language</code></a></h3>
  4522. <p>A list of values for the Accept-Language HTTP header used when
  4523. downloading webpages during URL preview generation. This allows
  4524. Synapse to specify the preferred languages that URL previews should
  4525. be in when communicating with remote servers.</p>
  4526. <p>Each value is a IETF language tag; a 2-3 letter identifier for a
  4527. language, optionally followed by subtags separated by '-', specifying
  4528. a country or region variant.</p>
  4529. <p>Multiple values can be provided, and a weight can be added to each by
  4530. using quality value syntax (;q=). '*' translates to any language.</p>
  4531. <p>Defaults to &quot;en&quot;.</p>
  4532. <p>Example configuration:</p>
  4533. <pre><code class="language-yaml"> url_preview_accept_language:
  4534. - 'en-UK'
  4535. - 'en-US;q=0.9'
  4536. - 'fr;q=0.8'
  4537. - '*;q=0.7'
  4538. </code></pre>
  4539. <hr />
  4540. <h3 id="oembed"><a class="header" href="#oembed"><code>oembed</code></a></h3>
  4541. <p>oEmbed allows for easier embedding content from a website. It can be
  4542. used for generating URLs previews of services which support it. A default list of oEmbed providers
  4543. is included with Synapse. Set <code>disable_default_providers</code> to true to disable using
  4544. these default oEmbed URLs. Use <code>additional_providers</code> to specify additional files with oEmbed configuration (each
  4545. should be in the form of providers.json). By default this list is empty. </p>
  4546. <p>Example configuration:</p>
  4547. <pre><code class="language-yaml">oembed:
  4548. disable_default_providers: true
  4549. additional_providers:
  4550. - oembed/my_providers.json
  4551. </code></pre>
  4552. <hr />
  4553. <h2 id="captcha"><a class="header" href="#captcha">Captcha</a></h2>
  4554. <p>See <a href="usage/configuration/../../CAPTCHA_SETUP.html">here</a> for full details on setting up captcha.</p>
  4555. <hr />
  4556. <h3 id="recaptcha_public_key"><a class="header" href="#recaptcha_public_key"><code>recaptcha_public_key</code></a></h3>
  4557. <p>This homeserver's ReCAPTCHA public key. Must be specified if <code>enable_registration_captcha</code> is
  4558. enabled.</p>
  4559. <p>Example configuration:</p>
  4560. <pre><code class="language-yaml">recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  4561. </code></pre>
  4562. <hr />
  4563. <h3 id="recaptcha_private_key"><a class="header" href="#recaptcha_private_key"><code>recaptcha_private_key</code></a></h3>
  4564. <p>This homeserver's ReCAPTCHA private key. Must be specified if <code>enable_registration_captcha</code> is
  4565. enabled.</p>
  4566. <p>Example configuration:</p>
  4567. <pre><code class="language-yaml">recaptcha_private_key: &quot;YOUR_PRIVATE_KEY&quot;
  4568. </code></pre>
  4569. <hr />
  4570. <h3 id="enable_registration_captcha"><a class="header" href="#enable_registration_captcha"><code>enable_registration_captcha</code></a></h3>
  4571. <p>Set to true to enable ReCaptcha checks when registering, preventing signup
  4572. unless a captcha is answered. Requires a valid ReCaptcha public/private key.
  4573. Defaults to false.</p>
  4574. <p>Example configuration:</p>
  4575. <pre><code class="language-yaml">enable_registration_captcha: true
  4576. </code></pre>
  4577. <hr />
  4578. <h3 id="recaptcha_siteverify_api"><a class="header" href="#recaptcha_siteverify_api"><code>recaptcha_siteverify_api</code></a></h3>
  4579. <p>The API endpoint to use for verifying <code>m.login.recaptcha</code> responses.
  4580. Defaults to <code>https://www.recaptcha.net/recaptcha/api/siteverify</code>.</p>
  4581. <p>Example configuration:</p>
  4582. <pre><code class="language-yaml">recaptcha_siteverify_api: &quot;https://my.recaptcha.site&quot;
  4583. </code></pre>
  4584. <hr />
  4585. <h2 id="turn"><a class="header" href="#turn">TURN</a></h2>
  4586. <p>Options related to adding a TURN server to Synapse.</p>
  4587. <hr />
  4588. <h3 id="turn_uris"><a class="header" href="#turn_uris"><code>turn_uris</code></a></h3>
  4589. <p>The public URIs of the TURN server to give to clients.</p>
  4590. <p>Example configuration:</p>
  4591. <pre><code class="language-yaml">turn_uris: [turn:example.org]
  4592. </code></pre>
  4593. <hr />
  4594. <h3 id="turn_shared_secret"><a class="header" href="#turn_shared_secret"><code>turn_shared_secret</code></a></h3>
  4595. <p>The shared secret used to compute passwords for the TURN server.</p>
  4596. <p>Example configuration:</p>
  4597. <pre><code class="language-yaml">turn_shared_secret: &quot;YOUR_SHARED_SECRET&quot;
  4598. </code></pre>
  4599. <hr />
  4600. <p>Config options: <code>turn_username</code> and <code>turn_password</code></p>
  4601. <p>The Username and password if the TURN server needs them and does not use a token.</p>
  4602. <p>Example configuration:</p>
  4603. <pre><code class="language-yaml">turn_username: &quot;TURNSERVER_USERNAME&quot;
  4604. turn_password: &quot;TURNSERVER_PASSWORD&quot;
  4605. </code></pre>
  4606. <hr />
  4607. <h3 id="turn_user_lifetime"><a class="header" href="#turn_user_lifetime"><code>turn_user_lifetime</code></a></h3>
  4608. <p>How long generated TURN credentials last. Defaults to 1h.</p>
  4609. <p>Example configuration:</p>
  4610. <pre><code class="language-yaml">turn_user_lifetime: 2h
  4611. </code></pre>
  4612. <hr />
  4613. <h3 id="turn_allow_guests"><a class="header" href="#turn_allow_guests"><code>turn_allow_guests</code></a></h3>
  4614. <p>Whether guests should be allowed to use the TURN server. This defaults to true, otherwise
  4615. VoIP will be unreliable for guests. However, it does introduce a slight security risk as
  4616. it allows users to connect to arbitrary endpoints without having first signed up for a valid account (e.g. by passing a CAPTCHA).</p>
  4617. <p>Example configuration:</p>
  4618. <pre><code class="language-yaml">turn_allow_guests: false
  4619. </code></pre>
  4620. <hr />
  4621. <h2 id="registration"><a class="header" href="#registration">Registration</a></h2>
  4622. <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>
  4623. <hr />
  4624. <h3 id="enable_registration"><a class="header" href="#enable_registration"><code>enable_registration</code></a></h3>
  4625. <p>Enable registration for new users. Defaults to false. It is highly recommended that if you enable registration,
  4626. you use either captcha, email, or token-based verification to verify that new users are not bots. In order to enable registration
  4627. without any verification, you must also set <code>enable_registration_without_verification</code> to true.</p>
  4628. <p>Example configuration:</p>
  4629. <pre><code class="language-yaml">enable_registration: true
  4630. </code></pre>
  4631. <hr />
  4632. <h3 id="enable_registration_without_verification"><a class="header" href="#enable_registration_without_verification"><code>enable_registration_without_verification</code></a></h3>
  4633. <p>Enable registration without email or captcha verification. Note: this option is <em>not</em> recommended,
  4634. as registration without verification is a known vector for spam and abuse. Defaults to false. Has no effect
  4635. unless <code>enable_registration</code> is also enabled.</p>
  4636. <p>Example configuration:</p>
  4637. <pre><code class="language-yaml">enable_registration_without_verification: true
  4638. </code></pre>
  4639. <hr />
  4640. <h3 id="session_lifetime"><a class="header" href="#session_lifetime"><code>session_lifetime</code></a></h3>
  4641. <p>Time that a user's session remains valid for, after they log in.</p>
  4642. <p>Note that this is not currently compatible with guest logins.</p>
  4643. <p>Note also that this is calculated at login time: changes are not applied retrospectively to users who have already
  4644. logged in.</p>
  4645. <p>By default, this is infinite.</p>
  4646. <p>Example configuration:</p>
  4647. <pre><code class="language-yaml">session_lifetime: 24h
  4648. </code></pre>
  4649. <hr />
  4650. <h3 id="refresh_access_token_lifetime"><a class="header" href="#refresh_access_token_lifetime"><code>refresh_access_token_lifetime</code></a></h3>
  4651. <p>Time that an access token remains valid for, if the session is using refresh tokens.</p>
  4652. <p>For more information about refresh tokens, please see the <a href="usage/configuration/user_authentication/refresh_tokens.html">manual</a>.</p>
  4653. <p>Note that this only applies to clients which advertise support for refresh tokens.</p>
  4654. <p>Note also that this is calculated at login time and refresh time: changes are not applied to
  4655. existing sessions until they are refreshed.</p>
  4656. <p>By default, this is 5 minutes.</p>
  4657. <p>Example configuration:</p>
  4658. <pre><code class="language-yaml">refreshable_access_token_lifetime: 10m
  4659. </code></pre>
  4660. <hr />
  4661. <h3 id="refresh_token_lifetime-24h"><a class="header" href="#refresh_token_lifetime-24h"><code>refresh_token_lifetime: 24h</code></a></h3>
  4662. <p>Time that a refresh token remains valid for (provided that it is not
  4663. exchanged for another one first).
  4664. This option can be used to automatically log-out inactive sessions.
  4665. Please see the manual for more information.</p>
  4666. <p>Note also that this is calculated at login time and refresh time:
  4667. changes are not applied to existing sessions until they are refreshed.</p>
  4668. <p>By default, this is infinite.</p>
  4669. <p>Example configuration:</p>
  4670. <pre><code class="language-yaml">refresh_token_lifetime: 24h
  4671. </code></pre>
  4672. <hr />
  4673. <h3 id="nonrefreshable_access_token_lifetime"><a class="header" href="#nonrefreshable_access_token_lifetime"><code>nonrefreshable_access_token_lifetime</code></a></h3>
  4674. <p>Time that an access token remains valid for, if the session is NOT
  4675. using refresh tokens.</p>
  4676. <p>Please note that not all clients support refresh tokens, so setting
  4677. this to a short value may be inconvenient for some users who will
  4678. then be logged out frequently.</p>
  4679. <p>Note also that this is calculated at login time: changes are not applied
  4680. retrospectively to existing sessions for users that have already logged in.</p>
  4681. <p>By default, this is infinite.</p>
  4682. <p>Example configuration:</p>
  4683. <pre><code class="language-yaml">nonrefreshable_access_token_lifetime: 24h
  4684. </code></pre>
  4685. <hr />
  4686. <h3 id="registrations_require_3pid"><a class="header" href="#registrations_require_3pid"><code>registrations_require_3pid</code></a></h3>
  4687. <p>If this is set, the user must provide all of the specified types of 3PID when registering.</p>
  4688. <p>Example configuration:</p>
  4689. <pre><code class="language-yaml">registrations_require_3pid:
  4690. - email
  4691. - msisdn
  4692. </code></pre>
  4693. <hr />
  4694. <h3 id="disable_msisdn_registration"><a class="header" href="#disable_msisdn_registration"><code>disable_msisdn_registration</code></a></h3>
  4695. <p>Explicitly disable asking for MSISDNs from the registration
  4696. flow (overrides <code>registrations_require_3pid</code> if MSISDNs are set as required).</p>
  4697. <p>Example configuration:</p>
  4698. <pre><code class="language-yaml">disable_msisdn_registration: true
  4699. </code></pre>
  4700. <hr />
  4701. <h3 id="allowed_local_3pids"><a class="header" href="#allowed_local_3pids"><code>allowed_local_3pids</code></a></h3>
  4702. <p>Mandate that users are only allowed to associate certain formats of
  4703. 3PIDs with accounts on this server, as specified by the <code>medium</code> and <code>pattern</code> sub-options.</p>
  4704. <p>Example configuration:</p>
  4705. <pre><code class="language-yaml">allowed_local_3pids:
  4706. - medium: email
  4707. pattern: '^[^@]+@matrix\.org$'
  4708. - medium: email
  4709. pattern: '^[^@]+@vector\.im$'
  4710. - medium: msisdn
  4711. pattern: '\+44'
  4712. </code></pre>
  4713. <hr />
  4714. <h3 id="enable_3pid_lookup"><a class="header" href="#enable_3pid_lookup"><code>enable_3pid_lookup</code></a></h3>
  4715. <p>Enable 3PIDs lookup requests to identity servers from this server. Defaults to true.</p>
  4716. <p>Example configuration:</p>
  4717. <pre><code class="language-yaml">enable_3pid_lookup: false
  4718. </code></pre>
  4719. <hr />
  4720. <h3 id="registration_requires_token"><a class="header" href="#registration_requires_token"><code>registration_requires_token</code></a></h3>
  4721. <p>Require users to submit a token during registration.
  4722. Tokens can be managed using the admin <a href="usage/configuration/../administration/admin_api/registration_tokens.html">API</a>.
  4723. Note that <code>enable_registration</code> must be set to true.
  4724. Disabling this option will not delete any tokens previously generated.
  4725. Defaults to false. Set to true to enable.</p>
  4726. <p>Example configuration:</p>
  4727. <pre><code class="language-yaml">registration_requires_token: true
  4728. </code></pre>
  4729. <hr />
  4730. <h3 id="registration_shared_secret"><a class="header" href="#registration_shared_secret"><code>registration_shared_secret</code></a></h3>
  4731. <p>If set, allows registration of standard or admin accounts by anyone who
  4732. has the shared secret, even if registration is otherwise disabled.</p>
  4733. <p>Example configuration:</p>
  4734. <pre><code class="language-yaml">registration_shared_secret: &lt;PRIVATE STRING&gt;
  4735. </code></pre>
  4736. <hr />
  4737. <h3 id="bcrypt_rounds"><a class="header" href="#bcrypt_rounds"><code>bcrypt_rounds</code></a></h3>
  4738. <p>Set the number of bcrypt rounds used to generate password hash.
  4739. Larger numbers increase the work factor needed to generate the hash.
  4740. The default number is 12 (which equates to 2^12 rounds).
  4741. N.B. that increasing this will exponentially increase the time required
  4742. to register or login - e.g. 24 =&gt; 2^24 rounds which will take &gt;20 mins.
  4743. Example configuration:</p>
  4744. <pre><code class="language-yaml">bcrypt_rounds: 14
  4745. </code></pre>
  4746. <hr />
  4747. <h3 id="allow_guest_access"><a class="header" href="#allow_guest_access"><code>allow_guest_access</code></a></h3>
  4748. <p>Allows users to register as guests without a password/email/etc, and
  4749. participate in rooms hosted on this server which have been made
  4750. accessible to anonymous users. Defaults to false.</p>
  4751. <p>Example configuration:</p>
  4752. <pre><code class="language-yaml">allow_guest_access: true
  4753. </code></pre>
  4754. <hr />
  4755. <h3 id="default_identity_server"><a class="header" href="#default_identity_server"><code>default_identity_server</code></a></h3>
  4756. <p>The identity server which we suggest that clients should use when users log
  4757. in on this server.</p>
  4758. <p>(By default, no suggestion is made, so it is left up to the client.
  4759. This setting is ignored unless <code>public_baseurl</code> is also explicitly set.)</p>
  4760. <p>Example configuration:</p>
  4761. <pre><code class="language-yaml">default_identity_server: https://matrix.org
  4762. </code></pre>
  4763. <hr />
  4764. <h3 id="account_threepid_delegates"><a class="header" href="#account_threepid_delegates"><code>account_threepid_delegates</code></a></h3>
  4765. <p>Handle threepid (email/phone etc) registration and password resets through a set of
  4766. <em>trusted</em> identity servers. Note that this allows the configured identity server to
  4767. reset passwords for accounts!</p>
  4768. <p>Be aware that if <code>email</code> is not set, and SMTP options have not been
  4769. configured in the email config block, registration and user password resets via
  4770. email will be globally disabled.</p>
  4771. <p>Additionally, if <code>msisdn</code> is not set, registration and password resets via msisdn
  4772. will be disabled regardless, and users will not be able to associate an msisdn
  4773. identifier to their account. This is due to Synapse currently not supporting
  4774. any method of sending SMS messages on its own.</p>
  4775. <p>To enable using an identity server for operations regarding a particular third-party
  4776. identifier type, set the value to the URL of that identity server as shown in the
  4777. examples below.</p>
  4778. <p>Servers handling the these requests must answer the <code>/requestToken</code> endpoints defined
  4779. by the Matrix Identity Service API <a href="https://matrix.org/docs/spec/identity_service/latest">specification</a>.</p>
  4780. <p>Example configuration:</p>
  4781. <pre><code class="language-yaml">account_threepid_delegates:
  4782. email: https://example.com # Delegate email sending to example.com
  4783. msisdn: http://localhost:8090 # Delegate SMS sending to this local process
  4784. </code></pre>
  4785. <hr />
  4786. <h3 id="enable_set_displayname"><a class="header" href="#enable_set_displayname"><code>enable_set_displayname</code></a></h3>
  4787. <p>Whether users are allowed to change their displayname after it has
  4788. been initially set. Useful when provisioning users based on the
  4789. contents of a third-party directory.</p>
  4790. <p>Does not apply to server administrators. Defaults to true.</p>
  4791. <p>Example configuration:</p>
  4792. <pre><code class="language-yaml">enable_set_displayname: false
  4793. </code></pre>
  4794. <hr />
  4795. <h3 id="enable_set_avatar_url"><a class="header" href="#enable_set_avatar_url"><code>enable_set_avatar_url</code></a></h3>
  4796. <p>Whether users are allowed to change their avatar after it has been
  4797. initially set. Useful when provisioning users based on the contents
  4798. of a third-party directory.</p>
  4799. <p>Does not apply to server administrators. Defaults to true.</p>
  4800. <p>Example configuration:</p>
  4801. <pre><code class="language-yaml">enable_set_avatar_url: false
  4802. </code></pre>
  4803. <hr />
  4804. <h3 id="enable_3pid_changes"><a class="header" href="#enable_3pid_changes"><code>enable_3pid_changes</code></a></h3>
  4805. <p>Whether users can change the third-party IDs associated with their accounts
  4806. (email address and msisdn).</p>
  4807. <p>Defaults to true.</p>
  4808. <p>Example configuration:</p>
  4809. <pre><code class="language-yaml">enable_3pid_changes: false
  4810. </code></pre>
  4811. <hr />
  4812. <h3 id="auto_join_rooms"><a class="header" href="#auto_join_rooms"><code>auto_join_rooms</code></a></h3>
  4813. <p>Users who register on this homeserver will automatically be joined
  4814. to the rooms listed under this option.</p>
  4815. <p>By default, any room aliases included in this list will be created
  4816. as a publicly joinable room when the first user registers for the
  4817. homeserver. If the room already exists, make certain it is a publicly joinable
  4818. room, i.e. the join rule of the room must be set to 'public'. You can find more options
  4819. relating to auto-joining rooms below. </p>
  4820. <p>Example configuration:</p>
  4821. <pre><code class="language-yaml">auto_join_rooms:
  4822. - &quot;#exampleroom:example.com&quot;
  4823. - &quot;#anotherexampleroom:example.com&quot;
  4824. </code></pre>
  4825. <hr />
  4826. <h3 id="autocreate_auto_join_rooms"><a class="header" href="#autocreate_auto_join_rooms"><code>autocreate_auto_join_rooms</code></a></h3>
  4827. <p>Where <code>auto_join_rooms</code> are specified, setting this flag ensures that
  4828. the rooms exist by creating them when the first user on the
  4829. homeserver registers.</p>
  4830. <p>By default the auto-created rooms are publicly joinable from any federated
  4831. server. Use the <code>autocreate_auto_join_rooms_federated</code> and
  4832. <code>autocreate_auto_join_room_preset</code> settings to customise this behaviour.</p>
  4833. <p>Setting to false means that if the rooms are not manually created,
  4834. users cannot be auto-joined since they do not exist.</p>
  4835. <p>Defaults to true.</p>
  4836. <p>Example configuration:</p>
  4837. <pre><code class="language-yaml">autocreate_auto_join_rooms: false
  4838. </code></pre>
  4839. <hr />
  4840. <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>
  4841. <p>Whether the rooms listen in <code>auto_join_rooms</code> that are auto-created are available
  4842. via federation. Only has an effect if <code>autocreate_auto_join_rooms</code> is true.</p>
  4843. <p>Note that whether a room is federated cannot be modified after
  4844. creation.</p>
  4845. <p>Defaults to true: the room will be joinable from other servers.
  4846. Set to false to prevent users from other homeservers from
  4847. joining these rooms.</p>
  4848. <p>Example configuration:</p>
  4849. <pre><code class="language-yaml">autocreate_auto_join_rooms_federated: false
  4850. </code></pre>
  4851. <hr />
  4852. <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>
  4853. <p>The room preset to use when auto-creating one of <code>auto_join_rooms</code>. Only has an
  4854. effect if <code>autocreate_auto_join_rooms</code> is true.</p>
  4855. <p>Possible values for this option are:</p>
  4856. <ul>
  4857. <li>&quot;public_chat&quot;: the room is joinable by anyone, including
  4858. federated servers if <code>autocreate_auto_join_rooms_federated</code> is true (the default).</li>
  4859. <li>&quot;private_chat&quot;: an invitation is required to join these rooms. </li>
  4860. <li>&quot;trusted_private_chat&quot;: an invitation is required to join this room and the invitee is
  4861. assigned a power level of 100 upon joining the room. </li>
  4862. </ul>
  4863. <p>If a value of &quot;private_chat&quot; or &quot;trusted_private_chat&quot; is used then
  4864. <code>auto_join_mxid_localpart</code> must also be configured.</p>
  4865. <p>Defaults to &quot;public_chat&quot;.</p>
  4866. <p>Example configuration:</p>
  4867. <pre><code class="language-yaml">autocreate_auto_join_room_preset: private_chat
  4868. </code></pre>
  4869. <hr />
  4870. <h3 id="auto_join_mxid_localpart"><a class="header" href="#auto_join_mxid_localpart"><code>auto_join_mxid_localpart</code></a></h3>
  4871. <p>The local part of the user id which is used to create <code>auto_join_rooms</code> if
  4872. <code>autocreate_auto_join_rooms</code> is true. If this is not provided then the
  4873. initial user account that registers will be used to create the rooms.</p>
  4874. <p>The user id is also used to invite new users to any auto-join rooms which
  4875. are set to invite-only.</p>
  4876. <p>It <em>must</em> be configured if <code>autocreate_auto_join_room_preset</code> is set to
  4877. &quot;private_chat&quot; or &quot;trusted_private_chat&quot;.</p>
  4878. <p>Note that this must be specified in order for new users to be correctly
  4879. invited to any auto-join rooms which have been set to invite-only (either
  4880. at the time of creation or subsequently).</p>
  4881. <p>Note that, if the room already exists, this user must be joined and
  4882. have the appropriate permissions to invite new members.</p>
  4883. <p>Example configuration:</p>
  4884. <pre><code class="language-yaml">auto_join_mxid_localpart: system
  4885. </code></pre>
  4886. <hr />
  4887. <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>
  4888. <p>When <code>auto_join_rooms</code> is specified, setting this flag to false prevents
  4889. guest accounts from being automatically joined to the rooms.</p>
  4890. <p>Defaults to true.</p>
  4891. <p>Example configuration:</p>
  4892. <pre><code class="language-yaml">auto_join_rooms_for_guests: false
  4893. </code></pre>
  4894. <hr />
  4895. <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>
  4896. <p>Whether to inhibit errors raised when registering a new account if the user ID
  4897. already exists. If turned on, requests to <code>/register/available</code> will always
  4898. show a user ID as available, and Synapse won't raise an error when starting
  4899. a registration with a user ID that already exists. However, Synapse will still
  4900. raise an error if the registration completes and the username conflicts.</p>
  4901. <p>Defaults to false.</p>
  4902. <p>Example configuration:</p>
  4903. <pre><code class="language-yaml">inhibit_user_in_use_error: true
  4904. </code></pre>
  4905. <hr />
  4906. <h2 id="metrics"><a class="header" href="#metrics">Metrics</a></h2>
  4907. <p>Config options related to metrics.</p>
  4908. <hr />
  4909. <h3 id="enable_metrics"><a class="header" href="#enable_metrics"><code>enable_metrics</code></a></h3>
  4910. <p>Set to true to enable collection and rendering of performance metrics.
  4911. Defaults to false.</p>
  4912. <p>Example configuration:</p>
  4913. <pre><code class="language-yaml">enable_metrics: true
  4914. </code></pre>
  4915. <hr />
  4916. <h3 id="sentry"><a class="header" href="#sentry"><code>sentry</code></a></h3>
  4917. <p>Use this option to enable sentry integration. Provide the DSN assigned to you by sentry
  4918. with the <code>dsn</code> setting. </p>
  4919. <p>NOTE: While attempts are made to ensure that the logs don't contain
  4920. any sensitive information, this cannot be guaranteed. By enabling
  4921. this option the sentry server may therefore receive sensitive
  4922. information, and it in turn may then disseminate sensitive information
  4923. through insecure notification channels if so configured.</p>
  4924. <p>Example configuration:</p>
  4925. <pre><code class="language-yaml">sentry:
  4926. dsn: &quot;...&quot;
  4927. </code></pre>
  4928. <hr />
  4929. <h3 id="metrics_flags"><a class="header" href="#metrics_flags"><code>metrics_flags</code></a></h3>
  4930. <p>Flags to enable Prometheus metrics which are not suitable to be
  4931. enabled by default, either for performance reasons or limited use.
  4932. Currently the only option is <code>known_servers</code>, which publishes
  4933. <code>synapse_federation_known_servers</code>, a gauge of the number of
  4934. servers this homeserver knows about, including itself. May cause
  4935. performance problems on large homeservers.</p>
  4936. <p>Example configuration:</p>
  4937. <pre><code class="language-yaml">metrics_flags:
  4938. known_servers: true
  4939. </code></pre>
  4940. <hr />
  4941. <h3 id="report_stats"><a class="header" href="#report_stats"><code>report_stats</code></a></h3>
  4942. <p>Whether or not to report anonymized homeserver usage statistics. This is originally
  4943. set when generating the config. Set this option to true or false to change the current
  4944. behavior. </p>
  4945. <p>Example configuration:</p>
  4946. <pre><code class="language-yaml">report_stats: true
  4947. </code></pre>
  4948. <hr />
  4949. <h3 id="report_stats_endpoint"><a class="header" href="#report_stats_endpoint"><code>report_stats_endpoint</code></a></h3>
  4950. <p>The endpoint to report the anonymized homeserver usage statistics to.
  4951. Defaults to https://matrix.org/report-usage-stats/push</p>
  4952. <p>Example configuration:</p>
  4953. <pre><code class="language-yaml">report_stats_endpoint: https://example.com/report-usage-stats/push
  4954. </code></pre>
  4955. <hr />
  4956. <h2 id="api-configuration"><a class="header" href="#api-configuration">API Configuration</a></h2>
  4957. <p>Config settings related to the client/server API</p>
  4958. <hr />
  4959. <h3 id="room_prejoin_state"><a class="header" href="#room_prejoin_state"><code>room_prejoin_state:</code></a></h3>
  4960. <p>Controls for the state that is shared with users who receive an invite
  4961. to a room. By default, the following state event types are shared with users who
  4962. receive invites to the room:</p>
  4963. <ul>
  4964. <li>m.room.join_rules</li>
  4965. <li>m.room.canonical_alias</li>
  4966. <li>m.room.avatar</li>
  4967. <li>m.room.encryption</li>
  4968. <li>m.room.name</li>
  4969. <li>m.room.create</li>
  4970. <li>m.room.topic</li>
  4971. </ul>
  4972. <p>To change the default behavior, use the following sub-options:</p>
  4973. <ul>
  4974. <li><code>disable_default_event_types</code>: set to true to disable the above defaults. If this
  4975. is enabled, only the event types listed in <code>additional_event_types</code> are shared.
  4976. Defaults to false.</li>
  4977. <li><code>additional_event_types</code>: Additional state event types to share with users when they are invited
  4978. to a room. By default, this list is empty (so only the default event types are shared).</li>
  4979. </ul>
  4980. <p>Example configuration:</p>
  4981. <pre><code class="language-yaml">room_prejoin_state:
  4982. disable_default_event_types: true
  4983. additional_event_types:
  4984. - org.example.custom.event.type
  4985. - m.room.join_rules
  4986. </code></pre>
  4987. <hr />
  4988. <h3 id="track_puppeted_user_ips"><a class="header" href="#track_puppeted_user_ips"><code>track_puppeted_user_ips</code></a></h3>
  4989. <p>We record the IP address of clients used to access the API for various
  4990. reasons, including displaying it to the user in the &quot;Where you're signed in&quot;
  4991. dialog.</p>
  4992. <p>By default, when puppeting another user via the admin API, the client IP
  4993. address is recorded against the user who created the access token (ie, the
  4994. admin user), and <em>not</em> the puppeted user.</p>
  4995. <p>Set this option to true to also record the IP address against the puppeted
  4996. user. (This also means that the puppeted user will count as an &quot;active&quot; user
  4997. for the purpose of monthly active user tracking - see <code>limit_usage_by_mau</code> etc
  4998. above.)</p>
  4999. <p>Example configuration:</p>
  5000. <pre><code class="language-yaml">track_puppeted_user_ips: true
  5001. </code></pre>
  5002. <hr />
  5003. <h3 id="app_service_config_files"><a class="header" href="#app_service_config_files"><code>app_service_config_files</code></a></h3>
  5004. <p>A list of application service config files to use.</p>
  5005. <p>Example configuration:</p>
  5006. <pre><code class="language-yaml">app_service_config_files:
  5007. - app_service_1.yaml
  5008. - app_service_2.yaml
  5009. </code></pre>
  5010. <hr />
  5011. <h3 id="track_appservice_user_ips"><a class="header" href="#track_appservice_user_ips"><code>track_appservice_user_ips</code></a></h3>
  5012. <p>Defaults to false. Set to true to enable tracking of application service IP addresses.
  5013. Implicitly enables MAU tracking for application service users.</p>
  5014. <p>Example configuration:</p>
  5015. <pre><code class="language-yaml">track_appservice_user_ips: true
  5016. </code></pre>
  5017. <hr />
  5018. <h3 id="macaroon_secret_key"><a class="header" href="#macaroon_secret_key"><code>macaroon_secret_key</code></a></h3>
  5019. <p>A secret which is used to sign access tokens. If none is specified,
  5020. the <code>registration_shared_secret</code> is used, if one is given; otherwise,
  5021. a secret key is derived from the signing key.</p>
  5022. <p>Example configuration:</p>
  5023. <pre><code class="language-yaml">macaroon_secret_key: &lt;PRIVATE STRING&gt;
  5024. </code></pre>
  5025. <hr />
  5026. <h3 id="form_secret"><a class="header" href="#form_secret"><code>form_secret</code></a></h3>
  5027. <p>A secret which is used to calculate HMACs for form values, to stop
  5028. falsification of values. Must be specified for the User Consent
  5029. forms to work.</p>
  5030. <p>Example configuration:</p>
  5031. <pre><code class="language-yaml">form_secret: &lt;PRIVATE STRING&gt;
  5032. </code></pre>
  5033. <hr />
  5034. <h2 id="signing-keys"><a class="header" href="#signing-keys">Signing Keys</a></h2>
  5035. <p>Config options relating to signing keys</p>
  5036. <hr />
  5037. <h3 id="signing_key_path"><a class="header" href="#signing_key_path"><code>signing_key_path</code></a></h3>
  5038. <p>Path to the signing key to sign messages with.</p>
  5039. <p>Example configuration:</p>
  5040. <pre><code class="language-yaml">signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  5041. </code></pre>
  5042. <hr />
  5043. <h3 id="old_signing_keys"><a class="header" href="#old_signing_keys"><code>old_signing_keys</code></a></h3>
  5044. <p>The keys that the server used to sign messages with but won't use
  5045. to sign new messages. For each key, <code>key</code> should be the base64-encoded public key, and
  5046. <code>expired_ts</code>should be the time (in milliseconds since the unix epoch) that
  5047. it was last used.</p>
  5048. <p>It is possible to build an entry from an old <code>signing.key</code> file using the
  5049. <code>export_signing_key</code> script which is provided with synapse.</p>
  5050. <p>Example configuration:</p>
  5051. <pre><code class="language-yaml">old_signing_keys:
  5052. &quot;ed25519:id&quot;: { key: &quot;base64string&quot;, expired_ts: 123456789123 }
  5053. </code></pre>
  5054. <hr />
  5055. <h3 id="key_refresh_interval"><a class="header" href="#key_refresh_interval"><code>key_refresh_interval</code></a></h3>
  5056. <p>How long key response published by this server is valid for.
  5057. Used to set the <code>valid_until_ts</code> in <code>/key/v2</code> APIs.
  5058. Determines how quickly servers will query to check which keys
  5059. are still valid. Defaults to 1d.</p>
  5060. <p>Example configuration:</p>
  5061. <pre><code class="language-yaml">key_refresh_interval: 2d
  5062. </code></pre>
  5063. <hr />
  5064. <h3 id="trusted_key_servers"><a class="header" href="#trusted_key_servers"><code>trusted_key_servers:</code></a></h3>
  5065. <p>The trusted servers to download signing keys from.</p>
  5066. <p>When we need to fetch a signing key, each server is tried in parallel.</p>
  5067. <p>Normally, the connection to the key server is validated via TLS certificates.
  5068. Additional security can be provided by configuring a <code>verify key</code>, which
  5069. will make synapse check that the response is signed by that key.</p>
  5070. <p>This setting supercedes an older setting named <code>perspectives</code>. The old format
  5071. is still supported for backwards-compatibility, but it is deprecated.</p>
  5072. <p><code>trusted_key_servers</code> defaults to matrix.org, but using it will generate a
  5073. warning on start-up. To suppress this warning, set
  5074. <code>suppress_key_server_warning</code> to true.</p>
  5075. <p>Options for each entry in the list include:</p>
  5076. <ul>
  5077. <li><code>server_name</code>: the name of the server. Required.</li>
  5078. <li><code>verify_keys</code>: an optional map from key id to base64-encoded public key.
  5079. If specified, we will check that the response is signed by at least
  5080. one of the given keys.</li>
  5081. <li><code>accept_keys_insecurely</code>: a boolean. Normally, if <code>verify_keys</code> is unset,
  5082. and <code>federation_verify_certificates</code> is not <code>true</code>, synapse will refuse
  5083. to start, because this would allow anyone who can spoof DNS responses
  5084. to masquerade as the trusted key server. If you know what you are doing
  5085. and are sure that your network environment provides a secure connection
  5086. to the key server, you can set this to <code>true</code> to override this behaviour.</li>
  5087. </ul>
  5088. <p>Example configuration #1:</p>
  5089. <pre><code class="language-yaml">trusted_key_servers:
  5090. - server_name: &quot;my_trusted_server.example.com&quot;
  5091. verify_keys:
  5092. &quot;ed25519:auto&quot;: &quot;abcdefghijklmnopqrstuvwxyzabcdefghijklmopqr&quot;
  5093. - server_name: &quot;my_other_trusted_server.example.com&quot;
  5094. </code></pre>
  5095. <p>Example configuration #2:</p>
  5096. <pre><code class="language-yaml">trusted_key_servers:
  5097. - server_name: &quot;matrix.org&quot;
  5098. </code></pre>
  5099. <hr />
  5100. <h3 id="suppress_key_server_warning"><a class="header" href="#suppress_key_server_warning"><code>suppress_key_server_warning</code></a></h3>
  5101. <p>Set the following to true to disable the warning that is emitted when the
  5102. <code>trusted_key_servers</code> include 'matrix.org'. See above.</p>
  5103. <p>Example configuration:</p>
  5104. <pre><code class="language-yaml">suppress_key_server_warning: true
  5105. </code></pre>
  5106. <hr />
  5107. <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>
  5108. <p>The signing keys to use when acting as a trusted key server. If not specified
  5109. defaults to the server signing key.</p>
  5110. <p>Can contain multiple keys, one per line.</p>
  5111. <p>Example configuration:</p>
  5112. <pre><code class="language-yaml">key_server_signing_keys_path: &quot;key_server_signing_keys.key&quot;
  5113. </code></pre>
  5114. <hr />
  5115. <h2 id="single-sign-on-integration"><a class="header" href="#single-sign-on-integration">Single sign-on integration</a></h2>
  5116. <p>The following settings can be used to make Synapse use a single sign-on
  5117. provider for authentication, instead of its internal password database.</p>
  5118. <p>You will probably also want to set the following options to false to
  5119. disable the regular login/registration flows:</p>
  5120. <ul>
  5121. <li><code>enable_registration</code></li>
  5122. <li><code>password_config.enabled</code></li>
  5123. </ul>
  5124. <p>You will also want to investigate the settings under the &quot;sso&quot; configuration
  5125. section below.</p>
  5126. <hr />
  5127. <h3 id="saml2_config"><a class="header" href="#saml2_config"><code>saml2_config</code></a></h3>
  5128. <p>Enable SAML2 for registration and login. Uses pysaml2. To learn more about pysaml and
  5129. to find a full list options for configuring pysaml, read the docs <a href="https://pysaml2.readthedocs.io/en/latest/">here</a>.</p>
  5130. <p>At least one of <code>sp_config</code> or <code>config_path</code> must be set in this section to
  5131. enable SAML login. You can either put your entire pysaml config inline using the <code>sp_config</code>
  5132. option, or you can specify a path to a psyaml config file with the sub-option <code>config_path</code>.
  5133. This setting has the following sub-options:</p>
  5134. <ul>
  5135. <li><code>sp_config</code>: the configuration for the pysaml2 Service Provider. See pysaml2 docs for format of config.
  5136. Default values will be used for the <code>entityid</code> and <code>service</code> settings,
  5137. so it is not normally necessary to specify them unless you need to
  5138. override them. Here are a few useful sub-options for configuring pysaml:
  5139. <ul>
  5140. <li><code>metadata</code>: Point this to the IdP's metadata. You must provide either a local
  5141. file via the <code>local</code> attribute or (preferably) a URL via the
  5142. <code>remote</code> attribute.</li>
  5143. <li><code>accepted_time_diff: 3</code>: Allowed clock difference in seconds between the homeserver and IdP.
  5144. Defaults to 0.</li>
  5145. <li><code>service</code>: By default, the user has to go to our login page first. If you'd like
  5146. to allow IdP-initiated login, set <code>allow_unsolicited</code> to true under <code>sp</code> in the <code>service</code>
  5147. section.</li>
  5148. </ul>
  5149. </li>
  5150. <li><code>config_path</code>: specify a separate pysaml2 configuration file thusly:
  5151. <code>config_path: &quot;CONFDIR/sp_conf.py&quot;</code></li>
  5152. <li><code>saml_session_lifetime</code>: The lifetime of a SAML session. This defines how long a user has to
  5153. complete the authentication process, if <code>allow_unsolicited</code> is unset. The default is 15 minutes.</li>
  5154. <li><code>user_mapping_provider</code>: Using this option, an external module can be provided as a
  5155. custom solution to mapping attributes returned from a saml provider onto a matrix user. The
  5156. <code>user_mapping_provider</code> has the following attributes:
  5157. <ul>
  5158. <li><code>module</code>: The custom module's class. </li>
  5159. <li><code>config</code>: Custom configuration values for the module. Use the values provided in the
  5160. example if you are using the built-in user_mapping_provider, or provide your own
  5161. config values for a custom class if you are using one. This section will be passed as a Python
  5162. dictionary to the module's <code>parse_config</code> method. The built-in provider takes the following two
  5163. options:
  5164. <ul>
  5165. <li><code>mxid_source_attribute</code>: The SAML attribute (after mapping via the attribute maps) to use
  5166. to derive the Matrix ID from. It is 'uid' by default. Note: This used to be configured by the
  5167. <code>saml2_config.mxid_source_attribute option</code>. If that is still defined, its value will be used instead.</li>
  5168. <li><code>mxid_mapping</code>: The mapping system to use for mapping the saml attribute onto a
  5169. matrix ID. Options include: <code>hexencode</code> (which maps unpermitted characters to '=xx')
  5170. and <code>dotreplace</code> (which replaces unpermitted characters with '.').
  5171. The default is <code>hexencode</code>. Note: This used to be configured by the
  5172. <code>saml2_config.mxid_mapping option</code>. If that is still defined, its value will be used instead.</li>
  5173. </ul>
  5174. </li>
  5175. </ul>
  5176. </li>
  5177. <li><code>grandfathered_mxid_source_attribute</code>: In previous versions of synapse, the mapping from SAML attribute to
  5178. MXID was always calculated dynamically rather than stored in a table. For backwards- compatibility, we will look for <code>user_ids</code>
  5179. matching such a pattern before creating a new account. This setting controls the SAML attribute which will be used for this
  5180. backwards-compatibility lookup. Typically it should be 'uid', but if the attribute maps are changed, it may be necessary to change it.
  5181. The default is 'uid'. </li>
  5182. <li><code>attribute_requirements</code>: It is possible to configure Synapse to only allow logins if SAML attributes
  5183. match particular values. The requirements can be listed under
  5184. <code>attribute_requirements</code> as shown in the example. All of the listed attributes must
  5185. match for the login to be permitted.</li>
  5186. <li><code>idp_entityid</code>: If the metadata XML contains multiple IdP entities then the <code>idp_entityid</code>
  5187. option must be set to the entity to redirect users to.
  5188. Most deployments only have a single IdP entity and so should omit this option.</li>
  5189. </ul>
  5190. <p>Once SAML support is enabled, a metadata file will be exposed at
  5191. <code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/metadata.xml</code>, which you may be able to
  5192. use to configure your SAML IdP with. Alternatively, you can manually configure
  5193. the IdP to use an ACS location of
  5194. <code>https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/authn_response</code>.</p>
  5195. <p>Example configuration:</p>
  5196. <pre><code class="language-yaml">saml2_config:
  5197. sp_config:
  5198. metadata:
  5199. local: [&quot;saml2/idp.xml&quot;]
  5200. remote:
  5201. - url: https://our_idp/metadata.xml
  5202. accepted_time_diff: 3
  5203. service:
  5204. sp:
  5205. allow_unsolicited: true
  5206. # The examples below are just used to generate our metadata xml, and you
  5207. # may well not need them, depending on your setup. Alternatively you
  5208. # may need a whole lot more detail - see the pysaml2 docs!
  5209. description: [&quot;My awesome SP&quot;, &quot;en&quot;]
  5210. name: [&quot;Test SP&quot;, &quot;en&quot;]
  5211. ui_info:
  5212. display_name:
  5213. - lang: en
  5214. text: &quot;Display Name is the descriptive name of your service.&quot;
  5215. description:
  5216. - lang: en
  5217. text: &quot;Description should be a short paragraph explaining the purpose of the service.&quot;
  5218. information_url:
  5219. - lang: en
  5220. text: &quot;https://example.com/terms-of-service&quot;
  5221. privacy_statement_url:
  5222. - lang: en
  5223. text: &quot;https://example.com/privacy-policy&quot;
  5224. keywords:
  5225. - lang: en
  5226. text: [&quot;Matrix&quot;, &quot;Element&quot;]
  5227. logo:
  5228. - lang: en
  5229. text: &quot;https://example.com/logo.svg&quot;
  5230. width: &quot;200&quot;
  5231. height: &quot;80&quot;
  5232. organization:
  5233. name: Example com
  5234. display_name:
  5235. - [&quot;Example co&quot;, &quot;en&quot;]
  5236. url: &quot;http://example.com&quot;
  5237. contact_person:
  5238. - given_name: Bob
  5239. sur_name: &quot;the Sysadmin&quot;
  5240. email_address&quot;: [&quot;admin@example.com&quot;]
  5241. contact_type&quot;: technical
  5242. saml_session_lifetime: 5m
  5243. user_mapping_provider:
  5244. # Below options are intended for the built-in provider, they should be
  5245. # changed if using a custom module.
  5246. config:
  5247. mxid_source_attribute: displayName
  5248. mxid_mapping: dotreplace
  5249. grandfathered_mxid_source_attribute: upn
  5250. attribute_requirements:
  5251. - attribute: userGroup
  5252. value: &quot;staff&quot;
  5253. - attribute: department
  5254. value: &quot;sales&quot;
  5255. idp_entityid: 'https://our_idp/entityid'
  5256. </code></pre>
  5257. <hr />
  5258. <h3 id="oidc_providers"><a class="header" href="#oidc_providers"><code>oidc_providers</code></a></h3>
  5259. <p>List of OpenID Connect (OIDC) / OAuth 2.0 identity providers, for registration
  5260. and login. See <a href="usage/configuration/../../openid.html">here</a>
  5261. for information on how to configure these options.</p>
  5262. <p>For backwards compatibility, it is also possible to configure a single OIDC
  5263. provider via an <code>oidc_config</code> setting. This is now deprecated and admins are
  5264. advised to migrate to the <code>oidc_providers</code> format. (When doing that migration,
  5265. use <code>oidc</code> for the <code>idp_id</code> to ensure that existing users continue to be
  5266. recognised.)</p>
  5267. <p>Options for each entry include:</p>
  5268. <ul>
  5269. <li>
  5270. <p><code>idp_id</code>: a unique identifier for this identity provider. Used internally
  5271. by Synapse; should be a single word such as 'github'.
  5272. Note that, if this is changed, users authenticating via that provider
  5273. will no longer be recognised as the same user!
  5274. (Use &quot;oidc&quot; here if you are migrating from an old <code>oidc_config</code> configuration.)</p>
  5275. </li>
  5276. <li>
  5277. <p><code>idp_name</code>: A user-facing name for this identity provider, which is used to
  5278. offer the user a choice of login mechanisms.</p>
  5279. </li>
  5280. <li>
  5281. <p><code>idp_icon</code>: An optional icon for this identity provider, which is presented
  5282. by clients and Synapse's own IdP picker page. If given, must be an
  5283. MXC URI of the format mxc://<server-name>/<media-id>. (An easy way to
  5284. obtain such an MXC URI is to upload an image to an (unencrypted) room
  5285. and then copy the &quot;url&quot; from the source of the event.)</p>
  5286. </li>
  5287. <li>
  5288. <p><code>idp_brand</code>: An optional brand for this identity provider, allowing clients
  5289. to style the login flow according to the identity provider in question.
  5290. See the <a href="https://spec.matrix.org/latest/">spec</a> for possible options here.</p>
  5291. </li>
  5292. <li>
  5293. <p><code>discover</code>: set to false to disable the use of the OIDC discovery mechanism
  5294. to discover endpoints. Defaults to true.</p>
  5295. </li>
  5296. <li>
  5297. <p><code>issuer</code>: Required. The OIDC issuer. Used to validate tokens and (if discovery
  5298. is enabled) to discover the provider's endpoints.</p>
  5299. </li>
  5300. <li>
  5301. <p><code>client_id</code>: Required. oauth2 client id to use.</p>
  5302. </li>
  5303. <li>
  5304. <p><code>client_secret</code>: oauth2 client secret to use. May be omitted if
  5305. <code>client_secret_jwt_key</code> is given, or if <code>client_auth_method</code> is 'none'.</p>
  5306. </li>
  5307. <li>
  5308. <p><code>client_secret_jwt_key</code>: Alternative to client_secret: details of a key used
  5309. to create a JSON Web Token to be used as an OAuth2 client secret. If
  5310. given, must be a dictionary with the following properties:</p>
  5311. <ul>
  5312. <li>
  5313. <p><code>key</code>: a pem-encoded signing key. Must be a suitable key for the
  5314. algorithm specified. Required unless <code>key_file</code> is given.</p>
  5315. </li>
  5316. <li>
  5317. <p><code>key_file</code>: the path to file containing a pem-encoded signing key file.
  5318. Required unless <code>key</code> is given.</p>
  5319. </li>
  5320. <li>
  5321. <p><code>jwt_header</code>: a dictionary giving properties to include in the JWT
  5322. header. Must include the key <code>alg</code>, giving the algorithm used to
  5323. sign the JWT, such as &quot;ES256&quot;, using the JWA identifiers in
  5324. RFC7518.</p>
  5325. </li>
  5326. <li>
  5327. <p><code>jwt_payload</code>: an optional dictionary giving properties to include in
  5328. the JWT payload. Normally this should include an <code>iss</code> key.</p>
  5329. </li>
  5330. </ul>
  5331. </li>
  5332. <li>
  5333. <p><code>client_auth_method</code>: auth method to use when exchanging the token. Valid
  5334. values are <code>client_secret_basic</code> (default), <code>client_secret_post</code> and
  5335. <code>none</code>.</p>
  5336. </li>
  5337. <li>
  5338. <p><code>scopes</code>: list of scopes to request. This should normally include the &quot;openid&quot;
  5339. scope. Defaults to [&quot;openid&quot;].</p>
  5340. </li>
  5341. <li>
  5342. <p><code>authorization_endpoint</code>: the oauth2 authorization endpoint. Required if
  5343. provider discovery is disabled.</p>
  5344. </li>
  5345. <li>
  5346. <p><code>token_endpoint</code>: the oauth2 token endpoint. Required if provider discovery is
  5347. disabled.</p>
  5348. </li>
  5349. <li>
  5350. <p><code>userinfo_endpoint</code>: the OIDC userinfo endpoint. Required if discovery is
  5351. disabled and the 'openid' scope is not requested.</p>
  5352. </li>
  5353. <li>
  5354. <p><code>jwks_uri</code>: URI where to fetch the JWKS. Required if discovery is disabled and
  5355. the 'openid' scope is used.</p>
  5356. </li>
  5357. <li>
  5358. <p><code>skip_verification</code>: set to 'true' to skip metadata verification. Use this if
  5359. you are connecting to a provider that is not OpenID Connect compliant.
  5360. Defaults to false. Avoid this in production.</p>
  5361. </li>
  5362. <li>
  5363. <p><code>user_profile_method</code>: Whether to fetch the user profile from the userinfo
  5364. endpoint, or to rely on the data returned in the id_token from the <code>token_endpoint</code>.
  5365. Valid values are: <code>auto</code> or <code>userinfo_endpoint</code>.
  5366. Defaults to <code>auto</code>, which uses the userinfo endpoint if <code>openid</code> is
  5367. not included in <code>scopes</code>. Set to <code>userinfo_endpoint</code> to always use the
  5368. userinfo endpoint.</p>
  5369. </li>
  5370. <li>
  5371. <p><code>allow_existing_users</code>: set to true to allow a user logging in via OIDC to
  5372. match a pre-existing account instead of failing. This could be used if
  5373. switching from password logins to OIDC. Defaults to false.</p>
  5374. </li>
  5375. <li>
  5376. <p><code>user_mapping_provider</code>: Configuration for how attributes returned from a OIDC
  5377. provider are mapped onto a matrix user. This setting has the following
  5378. sub-properties:</p>
  5379. <ul>
  5380. <li>
  5381. <p><code>module</code>: The class name of a custom mapping module. Default is
  5382. <code>synapse.handlers.oidc.JinjaOidcMappingProvider</code>.
  5383. See https://matrix-org.github.io/synapse/latest/sso_mapping_providers.html#openid-mapping-providers
  5384. for information on implementing a custom mapping provider.</p>
  5385. </li>
  5386. <li>
  5387. <p><code>config</code>: Configuration for the mapping provider module. This section will
  5388. be passed as a Python dictionary to the user mapping provider
  5389. module's <code>parse_config</code> method.</p>
  5390. <p>For the default provider, the following settings are available:</p>
  5391. <ul>
  5392. <li>
  5393. <p>subject_claim: name of the claim containing a unique identifier
  5394. for the user. Defaults to 'sub', which OpenID Connect
  5395. compliant providers should provide.</p>
  5396. </li>
  5397. <li>
  5398. <p><code>localpart_template</code>: Jinja2 template for the localpart of the MXID.
  5399. If this is not set, the user will be prompted to choose their
  5400. own username (see the documentation for the <code>sso_auth_account_details.html</code>
  5401. template). This template can use the <code>localpart_from_email</code> filter.</p>
  5402. </li>
  5403. <li>
  5404. <p><code>confirm_localpart</code>: Whether to prompt the user to validate (or
  5405. change) the generated localpart (see the documentation for the
  5406. 'sso_auth_account_details.html' template), instead of
  5407. registering the account right away.</p>
  5408. </li>
  5409. <li>
  5410. <p><code>display_name_template</code>: Jinja2 template for the display name to set
  5411. on first login. If unset, no displayname will be set.</p>
  5412. </li>
  5413. <li>
  5414. <p><code>email_template</code>: Jinja2 template for the email address of the user.
  5415. If unset, no email address will be added to the account.</p>
  5416. </li>
  5417. <li>
  5418. <p><code>extra_attributes</code>: a map of Jinja2 templates for extra attributes
  5419. to send back to the client during login. Note that these are non-standard and clients will ignore them
  5420. without modifications.</p>
  5421. </li>
  5422. </ul>
  5423. </li>
  5424. </ul>
  5425. <p>When rendering, the Jinja2 templates are given a 'user' variable,
  5426. which is set to the claims returned by the UserInfo Endpoint and/or
  5427. in the ID Token.</p>
  5428. </li>
  5429. </ul>
  5430. <p>It is possible to configure Synapse to only allow logins if certain attributes
  5431. match particular values in the OIDC userinfo. The requirements can be listed under
  5432. <code>attribute_requirements</code> as shown here:</p>
  5433. <pre><code class="language-yaml">attribute_requirements:
  5434. - attribute: family_name
  5435. value: &quot;Stephensson&quot;
  5436. - attribute: groups
  5437. value: &quot;admin&quot;
  5438. </code></pre>
  5439. <p>All of the listed attributes must match for the login to be permitted. Additional attributes can be added to
  5440. userinfo by expanding the <code>scopes</code> section of the OIDC config to retrieve
  5441. additional information from the OIDC provider.</p>
  5442. <p>If the OIDC claim is a list, then the attribute must match any value in the list.
  5443. Otherwise, it must exactly match the value of the claim. Using the example
  5444. above, the <code>family_name</code> claim MUST be &quot;Stephensson&quot;, but the <code>groups</code>
  5445. claim MUST contain &quot;admin&quot;.</p>
  5446. <p>Example configuration:</p>
  5447. <pre><code class="language-yaml">oidc_providers:
  5448. # Generic example
  5449. #
  5450. - idp_id: my_idp
  5451. idp_name: &quot;My OpenID provider&quot;
  5452. idp_icon: &quot;mxc://example.com/mediaid&quot;
  5453. discover: false
  5454. issuer: &quot;https://accounts.example.com/&quot;
  5455. client_id: &quot;provided-by-your-issuer&quot;
  5456. client_secret: &quot;provided-by-your-issuer&quot;
  5457. client_auth_method: client_secret_post
  5458. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  5459. authorization_endpoint: &quot;https://accounts.example.com/oauth2/auth&quot;
  5460. token_endpoint: &quot;https://accounts.example.com/oauth2/token&quot;
  5461. userinfo_endpoint: &quot;https://accounts.example.com/userinfo&quot;
  5462. jwks_uri: &quot;https://accounts.example.com/.well-known/jwks.json&quot;
  5463. skip_verification: true
  5464. user_mapping_provider:
  5465. config:
  5466. subject_claim: &quot;id&quot;
  5467. localpart_template: &quot;{{ user.login }}&quot;
  5468. display_name_template: &quot;{{ user.name }}&quot;
  5469. email_template: &quot;{{ user.email }}&quot;
  5470. attribute_requirements:
  5471. - attribute: userGroup
  5472. value: &quot;synapseUsers&quot;
  5473. </code></pre>
  5474. <hr />
  5475. <h3 id="cas_config"><a class="header" href="#cas_config"><code>cas_config</code></a></h3>
  5476. <p>Enable Central Authentication Service (CAS) for registration and login.
  5477. Has the following sub-options:</p>
  5478. <ul>
  5479. <li><code>enabled</code>: Set this to true to enable authorization against a CAS server.
  5480. Defaults to false.</li>
  5481. <li><code>server_url</code>: The URL of the CAS authorization endpoint.</li>
  5482. <li><code>displayname_attribute</code>: The attribute of the CAS response to use as the display name.
  5483. If no name is given here, no displayname will be set.</li>
  5484. <li><code>required_attributes</code>: It is possible to configure Synapse to only allow logins if CAS attributes
  5485. match particular values. All of the keys given below must exist
  5486. and the values must match the given value. Alternately if the given value
  5487. is <code>None</code> then any value is allowed (the attribute just must exist).
  5488. All of the listed attributes must match for the login to be permitted.</li>
  5489. </ul>
  5490. <p>Example configuration:</p>
  5491. <pre><code class="language-yaml">cas_config:
  5492. enabled: true
  5493. server_url: &quot;https://cas-server.com&quot;
  5494. displayname_attribute: name
  5495. required_attributes:
  5496. userGroup: &quot;staff&quot;
  5497. department: None
  5498. </code></pre>
  5499. <hr />
  5500. <h3 id="sso"><a class="header" href="#sso"><code>sso</code></a></h3>
  5501. <p>Additional settings to use with single-sign on systems such as OpenID Connect,
  5502. SAML2 and CAS.</p>
  5503. <p>Server admins can configure custom templates for pages related to SSO. See
  5504. <a href="usage/configuration/../../templates.html">here</a> for more information.</p>
  5505. <p>Options include:</p>
  5506. <ul>
  5507. <li><code>client_whitelist</code>: A list of client URLs which are whitelisted so that the user does not
  5508. have to confirm giving access to their account to the URL. Any client
  5509. whose URL starts with an entry in the following list will not be subject
  5510. to an additional confirmation step after the SSO login is completed.
  5511. WARNING: An entry such as &quot;https://my.client&quot; is insecure, because it
  5512. will also match &quot;https://my.client.evil.site&quot;, exposing your users to
  5513. phishing attacks from evil.site. To avoid this, include a slash after the
  5514. hostname: &quot;https://my.client/&quot;.
  5515. The login fallback page (used by clients that don't natively support the
  5516. required login flows) is whitelisted in addition to any URLs in this list.
  5517. By default, this list contains only the login fallback page.</li>
  5518. <li><code>update_profile_information</code>: Use this setting to keep a user's profile fields in sync with information from
  5519. the identity provider. Currently only syncing the displayname is supported. Fields
  5520. are checked on every SSO login, and are updated if necessary.
  5521. Note that enabling this option will override user profile information,
  5522. regardless of whether users have opted-out of syncing that
  5523. information when first signing in. Defaults to false.</li>
  5524. </ul>
  5525. <p>Example configuration:</p>
  5526. <pre><code class="language-yaml">sso:
  5527. client_whitelist:
  5528. - https://riot.im/develop
  5529. - https://my.custom.client/
  5530. update_profile_information: true
  5531. </code></pre>
  5532. <hr />
  5533. <h3 id="jwt_config"><a class="header" href="#jwt_config"><code>jwt_config</code></a></h3>
  5534. <p>JSON web token integration. The following settings can be used to make
  5535. Synapse JSON web tokens for authentication, instead of its internal
  5536. password database.</p>
  5537. <p>Each JSON Web Token needs to contain a &quot;sub&quot; (subject) claim, which is
  5538. used as the localpart of the mxid.</p>
  5539. <p>Additionally, the expiration time (&quot;exp&quot;), not before time (&quot;nbf&quot;),
  5540. and issued at (&quot;iat&quot;) claims are validated if present.</p>
  5541. <p>Note that this is a non-standard login type and client support is
  5542. expected to be non-existent.</p>
  5543. <p>See <a href="usage/configuration/../../jwt.html">here</a> for more.</p>
  5544. <p>Additional sub-options for this setting include:</p>
  5545. <ul>
  5546. <li><code>enabled</code>: Set to true to enable authorization using JSON web
  5547. tokens. Defaults to false.</li>
  5548. <li><code>secret</code>: This is either the private shared secret or the public key used to
  5549. decode the contents of the JSON web token. Required if <code>enabled</code> is set to true.</li>
  5550. <li><code>algorithm</code>: The algorithm used to sign (or HMAC) the JSON web token.
  5551. Supported algorithms are listed
  5552. <a href="https://docs.authlib.org/en/latest/specs/rfc7518.html">here (section JWS)</a>.
  5553. Required if <code>enabled</code> is set to true.</li>
  5554. <li><code>subject_claim</code>: Name of the claim containing a unique identifier for the user.
  5555. Optional, defaults to <code>sub</code>.</li>
  5556. <li><code>issuer</code>: The issuer to validate the &quot;iss&quot; claim against. Optional. If provided the
  5557. &quot;iss&quot; claim will be required and validated for all JSON web tokens.</li>
  5558. <li><code>audiences</code>: A list of audiences to validate the &quot;aud&quot; claim against. Optional.
  5559. If provided the &quot;aud&quot; claim will be required and validated for all JSON web tokens.
  5560. Note that if the &quot;aud&quot; claim is included in a JSON web token then
  5561. validation will fail without configuring audiences.</li>
  5562. </ul>
  5563. <p>Example configuration:</p>
  5564. <pre><code class="language-yaml">jwt_config:
  5565. enabled: true
  5566. secret: &quot;provided-by-your-issuer&quot;
  5567. algorithm: &quot;provided-by-your-issuer&quot;
  5568. subject_claim: &quot;name_of_claim&quot;
  5569. issuer: &quot;provided-by-your-issuer&quot;
  5570. audiences:
  5571. - &quot;provided-by-your-issuer&quot;
  5572. </code></pre>
  5573. <hr />
  5574. <h3 id="password_config"><a class="header" href="#password_config"><code>password_config</code></a></h3>
  5575. <p>Use this setting to enable password-based logins. </p>
  5576. <p>This setting has the following sub-options:</p>
  5577. <ul>
  5578. <li><code>enabled</code>: Defaults to true.
  5579. Set to false to disable password authentication.
  5580. Set to <code>only_for_reauth</code> to allow users with existing passwords to use them
  5581. to log in and reauthenticate, whilst preventing new users from setting passwords.</li>
  5582. <li><code>localdb_enabled</code>: Set to false to disable authentication against the local password
  5583. database. This is ignored if <code>enabled</code> is false, and is only useful
  5584. if you have other <code>password_providers</code>. Defaults to true. </li>
  5585. <li><code>pepper</code>: Set the value here to a secret random string for extra security. # Uncomment and change to a secret random string for extra security.
  5586. DO NOT CHANGE THIS AFTER INITIAL SETUP!</li>
  5587. <li><code>policy</code>: Define and enforce a password policy, such as minimum lengths for passwords, etc.
  5588. Each parameter is optional. This is an implementation of MSC2000. Parameters are as follows:
  5589. <ul>
  5590. <li><code>enabled</code>: Defaults to false. Set to true to enable.</li>
  5591. <li><code>minimum_length</code>: Minimum accepted length for a password. Defaults to 0.</li>
  5592. <li><code>require_digit</code>: Whether a password must contain at least one digit.
  5593. Defaults to false.</li>
  5594. <li><code>require_symbol</code>: Whether a password must contain at least one symbol.
  5595. A symbol is any character that's not a number or a letter. Defaults to false.</li>
  5596. <li><code>require_lowercase</code>: Whether a password must contain at least one lowercase letter.
  5597. Defaults to false.</li>
  5598. <li><code>require_uppercase</code>: Whether a password must contain at least one uppercase letter.
  5599. Defaults to false.</li>
  5600. </ul>
  5601. </li>
  5602. </ul>
  5603. <p>Example configuration:</p>
  5604. <pre><code class="language-yaml">password_config:
  5605. enabled: false
  5606. localdb_enabled: false
  5607. pepper: &quot;EVEN_MORE_SECRET&quot;
  5608. policy:
  5609. enabled: true
  5610. minimum_length: 15
  5611. require_digit: true
  5612. require_symbol: true
  5613. require_lowercase: true
  5614. require_uppercase: true
  5615. </code></pre>
  5616. <hr />
  5617. <h3 id="ui_auth"><a class="header" href="#ui_auth"><code>ui_auth</code></a></h3>
  5618. <p>The amount of time to allow a user-interactive authentication session to be active.</p>
  5619. <p>This defaults to 0, meaning the user is queried for their credentials
  5620. before every action, but this can be overridden to allow a single
  5621. validation to be re-used. This weakens the protections afforded by
  5622. the user-interactive authentication process, by allowing for multiple
  5623. (and potentially different) operations to use the same validation session.</p>
  5624. <p>This is ignored for potentially &quot;dangerous&quot; operations (including
  5625. deactivating an account, modifying an account password, and
  5626. adding a 3PID).</p>
  5627. <p>Use the <code>session_timeout</code> sub-option here to change the time allowed for credential validation.</p>
  5628. <p>Example configuration:</p>
  5629. <pre><code class="language-yaml">ui_auth:
  5630. session_timeout: &quot;15s&quot;
  5631. </code></pre>
  5632. <hr />
  5633. <h3 id="email-3"><a class="header" href="#email-3"><code>email</code></a></h3>
  5634. <p>Configuration for sending emails from Synapse.</p>
  5635. <p>Server admins can configure custom templates for email content. See
  5636. <a href="usage/configuration/../../templates.html">here</a> for more information.</p>
  5637. <p>This setting has the following sub-options:</p>
  5638. <ul>
  5639. <li>
  5640. <p><code>smtp_host</code>: The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.</p>
  5641. </li>
  5642. <li>
  5643. <p><code>smtp_port</code>: The port on the mail server for outgoing SMTP. Defaults to 25.</p>
  5644. </li>
  5645. <li>
  5646. <p><code>smtp_user</code> and <code>smtp_pass</code>: Username/password for authentication to the SMTP server. By default, no
  5647. authentication is attempted.</p>
  5648. </li>
  5649. <li>
  5650. <p><code>require_transport_security</code>: Set to true to require TLS transport security for SMTP.
  5651. By default, Synapse will connect over plain text, and will then switch to
  5652. TLS via STARTTLS <em>if the SMTP server supports it</em>. If this option is set,
  5653. Synapse will refuse to connect unless the server supports STARTTLS.</p>
  5654. </li>
  5655. <li>
  5656. <p><code>enable_tls</code>: By default, if the server supports TLS, it will be used, and the server
  5657. must present a certificate that is valid for 'smtp_host'. If this option
  5658. is set to false, TLS will not be used.</p>
  5659. </li>
  5660. <li>
  5661. <p><code>notif_from</code>: defines the &quot;From&quot; address to use when sending emails.
  5662. It must be set if email sending is enabled. The placeholder '%(app)s' will be replaced by the application name,
  5663. which is normally set in <code>app_name</code>, but may be overridden by the
  5664. Matrix client application. Note that the placeholder must be written '%(app)s', including the
  5665. trailing 's'.</p>
  5666. </li>
  5667. <li>
  5668. <p><code>app_name</code>: <code>app_name</code> defines the default value for '%(app)s' in <code>notif_from</code> and email
  5669. subjects. It defaults to 'Matrix'.</p>
  5670. </li>
  5671. <li>
  5672. <p><code>enable_notifs</code>: Set to true to enable sending emails for messages that the user
  5673. has missed. Disabled by default.</p>
  5674. </li>
  5675. <li>
  5676. <p><code>notif_for_new_users</code>: Set to false to disable automatic subscription to email
  5677. notifications for new users. Enabled by default.</p>
  5678. </li>
  5679. <li>
  5680. <p><code>client_base_url</code>: Custom URL for client links within the email notifications. By default
  5681. links will be based on &quot;https://matrix.to&quot;. (This setting used to be called <code>riot_base_url</code>;
  5682. the old name is still supported for backwards-compatibility but is now deprecated.)</p>
  5683. </li>
  5684. <li>
  5685. <p><code>validation_token_lifetime</code>: Configures the time that a validation email will expire after sending.
  5686. Defaults to 1h.</p>
  5687. </li>
  5688. <li>
  5689. <p><code>invite_client_location</code>: The web client location to direct users to during an invite. This is passed
  5690. to the identity server as the <code>org.matrix.web_client_location</code> key. Defaults
  5691. to unset, giving no guidance to the identity server.</p>
  5692. </li>
  5693. <li>
  5694. <p><code>subjects</code>: Subjects to use when sending emails from Synapse. The placeholder '%(app)s' will
  5695. be replaced with the value of the <code>app_name</code> setting, or by a value dictated by the Matrix client application.
  5696. In addition, each subject can use the following placeholders: '%(person)s', which will be replaced by the displayname
  5697. 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
  5698. message(s) have been sent to, e.g. &quot;My super room&quot;. In addition, emails related to account administration will
  5699. can use the '%(server_name)s' placeholder, which will be replaced by the value of the
  5700. <code>server_name</code> setting in your Synapse configuration.</p>
  5701. <p>Here is a list of subjects for notification emails that can be set: </p>
  5702. <ul>
  5703. <li><code>message_from_person_in_room</code>: Subject to use to notify about one message from one or more user(s) in a
  5704. 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>
  5705. <li><code>message_from_person</code>: Subject to use to notify about one message from one or more user(s) in a
  5706. room which doesn't have a name. Defaults to &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;</li>
  5707. <li><code>messages_from_person</code>: Subject to use to notify about multiple messages from one or more users in
  5708. a room which doesn't have a name. Defaults to &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;</li>
  5709. <li><code>messages_in_room</code>: Subject to use to notify about multiple messages in a room which has a
  5710. name. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;</li>
  5711. <li><code>messages_in_room_and_others</code>: Subject to use to notify about multiple messages in multiple rooms.
  5712. Defaults to &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;</li>
  5713. <li><code>messages_from_person_and_others</code>: Subject to use to notify about multiple messages from multiple persons in
  5714. multiple rooms. This is similar to the setting above except it's used when
  5715. the room in which the notification was triggered has no name. Defaults to
  5716. &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;</li>
  5717. <li><code>invite_from_person_to_room</code>: Subject to use to notify about an invite to a room which has a name.
  5718. Defaults to &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;</li>
  5719. <li><code>invite_from_person</code>: Subject to use to notify about an invite to a room which doesn't have a
  5720. name. Defaults to &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;</li>
  5721. <li><code>password_reset</code>: Subject to use when sending a password reset email. Defaults to &quot;[%(server_name)s] Password reset&quot;</li>
  5722. <li><code>email_validation</code>: Subject to use when sending a verification email to assert an address's
  5723. ownership. Defaults to &quot;[%(server_name)s] Validate your email&quot;</li>
  5724. </ul>
  5725. </li>
  5726. </ul>
  5727. <p>Example configuration:</p>
  5728. <pre><code class="language-yaml">email:
  5729. smtp_host: mail.server
  5730. smtp_port: 587
  5731. smtp_user: &quot;exampleusername&quot;
  5732. smtp_pass: &quot;examplepassword&quot;
  5733. require_transport_security: true
  5734. enable_tls: false
  5735. notif_from: &quot;Your Friendly %(app)s homeserver &lt;noreply@example.com&gt;&quot;
  5736. app_name: my_branded_matrix_server
  5737. enable_notifs: true
  5738. notif_for_new_users: false
  5739. client_base_url: &quot;http://localhost/riot&quot;
  5740. validation_token_lifetime: 15m
  5741. invite_client_location: https://app.element.io
  5742. subjects:
  5743. message_from_person_in_room: &quot;[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...&quot;
  5744. message_from_person: &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;
  5745. messages_from_person: &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;
  5746. messages_in_room: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;
  5747. messages_in_room_and_others: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;
  5748. messages_from_person_and_others: &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;
  5749. invite_from_person_to_room: &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;
  5750. invite_from_person: &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;
  5751. password_reset: &quot;[%(server_name)s] Password reset&quot;
  5752. email_validation: &quot;[%(server_name)s] Validate your email&quot;
  5753. </code></pre>
  5754. <hr />
  5755. <h2 id="push"><a class="header" href="#push">Push</a></h2>
  5756. <p>Configuration settings related to push notifications</p>
  5757. <hr />
  5758. <h3 id="push-1"><a class="header" href="#push-1"><code>push</code></a></h3>
  5759. <p>This setting defines options for push notifications. </p>
  5760. <p>This option has a number of sub-options. They are as follows:</p>
  5761. <ul>
  5762. <li><code>include_content</code>: Clients requesting push notifications can either have the body of
  5763. the message sent in the notification poke along with other details
  5764. like the sender, or just the event ID and room ID (<code>event_id_only</code>).
  5765. If clients choose the to have the body sent, this option controls whether the
  5766. notification request includes the content of the event (other details
  5767. like the sender are still included). If <code>event_id_only</code> is enabled, it
  5768. has no effect.
  5769. For modern android devices the notification content will still appear
  5770. because it is loaded by the app. iPhone, however will send a
  5771. notification saying only that a message arrived and who it came from.
  5772. Defaults to true. Set to false to only include the event ID and room ID in push notification payloads.</li>
  5773. <li><code>group_unread_count_by_room: false</code>: When a push notification is received, an unread count is also sent.
  5774. This number can either be calculated as the number of unread messages for the user, or the number of <em>rooms</em> the
  5775. user has unread messages in. Defaults to true, meaning push clients will see the number of
  5776. rooms with unread messages in them. Set to false to instead send the number
  5777. of unread messages.</li>
  5778. </ul>
  5779. <p>Example configuration:</p>
  5780. <pre><code class="language-yaml">push:
  5781. include_content: false
  5782. group_unread_count_by_room: false
  5783. </code></pre>
  5784. <hr />
  5785. <h2 id="rooms"><a class="header" href="#rooms">Rooms</a></h2>
  5786. <p>Config options relating to rooms.</p>
  5787. <hr />
  5788. <h3 id="encryption_enabled_by_default"><a class="header" href="#encryption_enabled_by_default"><code>encryption_enabled_by_default</code></a></h3>
  5789. <p>Controls whether locally-created rooms should be end-to-end encrypted by
  5790. default.</p>
  5791. <p>Possible options are &quot;all&quot;, &quot;invite&quot;, and &quot;off&quot;. They are defined as:</p>
  5792. <ul>
  5793. <li>&quot;all&quot;: any locally-created room</li>
  5794. <li>&quot;invite&quot;: any room created with the <code>private_chat</code> or <code>trusted_private_chat</code>
  5795. room creation presets</li>
  5796. <li>&quot;off&quot;: this option will take no effect</li>
  5797. </ul>
  5798. <p>The default value is &quot;off&quot;.</p>
  5799. <p>Note that this option will only affect rooms created after it is set. It
  5800. will also not affect rooms created by other servers.</p>
  5801. <p>Example configuration:</p>
  5802. <pre><code class="language-yaml">encryption_enabled_by_default_for_room_type: invite
  5803. </code></pre>
  5804. <hr />
  5805. <h3 id="user_directory"><a class="header" href="#user_directory"><code>user_directory</code></a></h3>
  5806. <p>This setting defines options related to the user directory. </p>
  5807. <p>This option has the following sub-options:</p>
  5808. <ul>
  5809. <li><code>enabled</code>: Defines whether users can search the user directory. If false then
  5810. empty responses are returned to all queries. Defaults to true.</li>
  5811. <li><code>search_all_users</code>: Defines whether to search all users visible to your HS when searching
  5812. the user directory. If false, search results will only contain users
  5813. visible in public rooms and users sharing a room with the requester.
  5814. Defaults to false.
  5815. NB. If you set this to true, and the last time the user_directory search
  5816. indexes were (re)built was before Synapse 1.44, you'll have to
  5817. rebuild the indexes in order to search through all known users.
  5818. These indexes are built the first time Synapse starts; admins can
  5819. manually trigger a rebuild via API following the instructions at
  5820. https://matrix-org.github.io/synapse/latest/usage/administration/admin_api/background_updates.html#run
  5821. Set to true to return search results containing all known users, even if that
  5822. user does not share a room with the requester.</li>
  5823. <li><code>prefer_local_users</code>: Defines whether to prefer local users in search query results.
  5824. If set to true, local users are more likely to appear above remote users when searching the
  5825. user directory. Defaults to false.</li>
  5826. </ul>
  5827. <p>Example configuration:</p>
  5828. <pre><code class="language-yaml">user_directory:
  5829. enabled: false
  5830. search_all_users: true
  5831. prefer_local_users: true
  5832. </code></pre>
  5833. <hr />
  5834. <h3 id="user_consent"><a class="header" href="#user_consent"><code>user_consent</code></a></h3>
  5835. <p>For detailed instructions on user consent configuration, see <a href="usage/configuration/../../consent_tracking.html">here</a>.</p>
  5836. <p>Parts of this section are required if enabling the <code>consent</code> resource under
  5837. <code>listeners</code>, in particular <code>template_dir</code> and <code>version</code>. # TODO: link <code>listeners</code></p>
  5838. <ul>
  5839. <li>
  5840. <p><code>template_dir</code>: gives the location of the templates for the HTML forms.
  5841. This directory should contain one subdirectory per language (eg, <code>en</code>, <code>fr</code>),
  5842. and each language directory should contain the policy document (named as
  5843. <version>.html) and a success page (success.html).</p>
  5844. </li>
  5845. <li>
  5846. <p><code>version</code>: specifies the 'current' version of the policy document. It defines
  5847. the version to be served by the consent resource if there is no 'v'
  5848. parameter.</p>
  5849. </li>
  5850. <li>
  5851. <p><code>server_notice_content</code>: if enabled, will send a user a &quot;Server Notice&quot;
  5852. asking them to consent to the privacy policy. The <code>server_notices</code> section ##TODO: link
  5853. must also be configured for this to work. Notices will <em>not</em> be sent to
  5854. guest users unless <code>send_server_notice_to_guests</code> is set to true.</p>
  5855. </li>
  5856. <li>
  5857. <p><code>block_events_error</code>, if set, will block any attempts to send events
  5858. until the user consents to the privacy policy. The value of the setting is
  5859. used as the text of the error.</p>
  5860. </li>
  5861. <li>
  5862. <p><code>require_at_registration</code>, if enabled, will add a step to the registration
  5863. process, similar to how captcha works. Users will be required to accept the
  5864. policy before their account is created.</p>
  5865. </li>
  5866. <li>
  5867. <p><code>policy_name</code> is the display name of the policy users will see when registering
  5868. for an account. Has no effect unless <code>require_at_registration</code> is enabled.
  5869. Defaults to &quot;Privacy Policy&quot;.</p>
  5870. </li>
  5871. </ul>
  5872. <p>Example configuration:</p>
  5873. <pre><code class="language-yaml">user_consent:
  5874. template_dir: res/templates/privacy
  5875. version: 1.0
  5876. server_notice_content:
  5877. msgtype: m.text
  5878. body: &gt;-
  5879. To continue using this homeserver you must review and agree to the
  5880. terms and conditions at %(consent_uri)s
  5881. send_server_notice_to_guests: true
  5882. block_events_error: &gt;-
  5883. To continue using this homeserver you must review and agree to the
  5884. terms and conditions at %(consent_uri)s
  5885. require_at_registration: false
  5886. policy_name: Privacy Policy
  5887. </code></pre>
  5888. <hr />
  5889. <h3 id="stats"><a class="header" href="#stats"><code>stats</code></a></h3>
  5890. <p>Settings for local room and user statistics collection. See <a href="usage/configuration/../../room_and_user_statistics.html">here</a>
  5891. for more. </p>
  5892. <ul>
  5893. <li><code>enabled</code>: Set to false to disable room and user statistics. Note that doing
  5894. so may cause certain features (such as the room directory) not to work
  5895. correctly. Defaults to true. </li>
  5896. </ul>
  5897. <p>Example configuration:</p>
  5898. <pre><code class="language-yaml">stats:
  5899. enabled: false
  5900. </code></pre>
  5901. <hr />
  5902. <h3 id="server_notices"><a class="header" href="#server_notices"><code>server_notices</code></a></h3>
  5903. <p>Use this setting to enable a room which can be used to send notices
  5904. from the server to users. It is a special room which users cannot leave; notices
  5905. in the room come from a special &quot;notices&quot; user id.</p>
  5906. <p>If you use this setting, you <em>must</em> define the <code>system_mxid_localpart</code>
  5907. sub-setting, which defines the id of the user which will be used to send the
  5908. notices.</p>
  5909. <p>Sub-options for this setting include:</p>
  5910. <ul>
  5911. <li><code>system_mxid_display_name</code>: set the display name of the &quot;notices&quot; user</li>
  5912. <li><code>system_mxid_avatar_url</code>: set the avatar for the &quot;notices&quot; user</li>
  5913. <li><code>room_name</code>: set the room name of the server notices room</li>
  5914. </ul>
  5915. <p>Example configuration:</p>
  5916. <pre><code class="language-yaml">server_notices:
  5917. system_mxid_localpart: notices
  5918. system_mxid_display_name: &quot;Server Notices&quot;
  5919. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  5920. room_name: &quot;Server Notices&quot;
  5921. </code></pre>
  5922. <hr />
  5923. <h3 id="enable_room_list_search"><a class="header" href="#enable_room_list_search"><code>enable_room_list_search</code></a></h3>
  5924. <p>Set to false to disable searching the public room list. When disabled
  5925. blocks searching local and remote room lists for local and remote
  5926. users by always returning an empty list for all queries. Defaults to true. </p>
  5927. <p>Example configuration:</p>
  5928. <pre><code class="language-yaml">enable_room_list_search: false
  5929. </code></pre>
  5930. <hr />
  5931. <h3 id="alias_creation"><a class="header" href="#alias_creation"><code>alias_creation</code></a></h3>
  5932. <p>The <code>alias_creation</code> option controls who is allowed to create aliases
  5933. on this server.</p>
  5934. <p>The format of this option is a list of rules that contain globs that
  5935. match against user_id, room_id and the new alias (fully qualified with
  5936. server name). The action in the first rule that matches is taken,
  5937. which can currently either be &quot;allow&quot; or &quot;deny&quot;.</p>
  5938. <p>Missing user_id/room_id/alias fields default to &quot;*&quot;.</p>
  5939. <p>If no rules match the request is denied. An empty list means no one
  5940. can create aliases.</p>
  5941. <p>Options for the rules include:</p>
  5942. <ul>
  5943. <li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
  5944. <li><code>alias</code>: Matches against the alias being created. Defaults to &quot;*&quot;.</li>
  5945. <li><code>room_id</code>: Matches against the room ID the alias is being pointed at. Defaults to &quot;*&quot;</li>
  5946. <li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow. </li>
  5947. </ul>
  5948. <p>Example configuration:</p>
  5949. <pre><code class="language-yaml">alias_creation_rules:
  5950. - user_id: &quot;bad_user&quot;
  5951. alias: &quot;spammy_alias&quot;
  5952. room_id: &quot;*&quot;
  5953. action: deny
  5954. </code></pre>
  5955. <hr />
  5956. <p>Config options: <code>room_list_publication_rules</code></p>
  5957. <p>The <code>room_list_publication_rules</code> option controls who can publish and
  5958. which rooms can be published in the public room list.</p>
  5959. <p>The format of this option is the same as that for
  5960. <code>alias_creation_rules</code>.</p>
  5961. <p>If the room has one or more aliases associated with it, only one of
  5962. the aliases needs to match the alias rule. If there are no aliases
  5963. then only rules with <code>alias: *</code> match.</p>
  5964. <p>If no rules match the request is denied. An empty list means no one
  5965. can publish rooms.</p>
  5966. <p>Options for the rules include:</p>
  5967. <ul>
  5968. <li><code>user_id</code>: Matches against the creator of the alias. Defaults to &quot;*&quot;.</li>
  5969. <li><code>alias</code>: Matches against any current local or canonical aliases associated with the room. Defaults to &quot;*&quot;.</li>
  5970. <li><code>room_id</code>: Matches against the room ID being published. Defaults to &quot;*&quot;.</li>
  5971. <li><code>action</code>: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches. Defaults to allow. </li>
  5972. </ul>
  5973. <p>Example configuration:</p>
  5974. <pre><code class="language-yaml">room_list_publication_rules:
  5975. - user_id: &quot;*&quot;
  5976. alias: &quot;*&quot;
  5977. room_id: &quot;*&quot;
  5978. action: allow
  5979. </code></pre>
  5980. <hr />
  5981. <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>
  5982. <p>The <code>default_power_level_content_override</code> option controls the default power
  5983. levels for rooms.</p>
  5984. <p>Useful if you know that your users need special permissions in rooms
  5985. that they create (e.g. to send particular types of state events without
  5986. needing an elevated power level). This takes the same shape as the
  5987. <code>power_level_content_override</code> parameter in the /createRoom API, but
  5988. is applied before that parameter.</p>
  5989. <p>Note that each key provided inside a preset (for example <code>events</code> in the example
  5990. below) will overwrite all existing defaults inside that key. So in the example
  5991. below, newly-created private_chat rooms will have no rules for any event types
  5992. except <code>com.example.foo</code>.</p>
  5993. <p>Example configuration:</p>
  5994. <pre><code class="language-yaml">default_power_level_content_override:
  5995. private_chat: { &quot;events&quot;: { &quot;com.example.foo&quot; : 0 } }
  5996. trusted_private_chat: null
  5997. public_chat: null
  5998. </code></pre>
  5999. <hr />
  6000. <h2 id="opentracing"><a class="header" href="#opentracing">Opentracing</a></h2>
  6001. <p>Configuration options related to Opentracing support.</p>
  6002. <hr />
  6003. <h3 id="opentracing-1"><a class="header" href="#opentracing-1"><code>opentracing</code></a></h3>
  6004. <p>These settings enable and configure opentracing, which implements distributed tracing.
  6005. This allows you to observe the causal chains of events across servers
  6006. including requests, key lookups etc., across any server running
  6007. synapse or any other services which support opentracing
  6008. (specifically those implemented with Jaeger).</p>
  6009. <p>Sub-options include:</p>
  6010. <ul>
  6011. <li><code>enabled</code>: whether tracing is enabled. Set to true to enable. Disabled by default.</li>
  6012. <li><code>homeserver_whitelist</code>: The list of homeservers we wish to send and receive span contexts and span baggage.
  6013. See <a href="usage/configuration/../../opentracing.html">here</a> for more.
  6014. This is a list of regexes which are matched against the <code>server_name</code> of the homeserver.
  6015. By default, it is empty, so no servers are matched.</li>
  6016. <li><code>force_tracing_for_users</code>: # A list of the matrix IDs of users whose requests will always be traced,
  6017. even if the tracing system would otherwise drop the traces due to probabilistic sampling.
  6018. By default, the list is empty.</li>
  6019. <li><code>jaeger_config</code>: Jaeger can be configured to sample traces at different rates.
  6020. All configuration options provided by Jaeger can be set here. Jaeger's configuration is
  6021. mostly related to trace sampling which is documented <a href="https://www.jaegertracing.io/docs/latest/sampling/">here</a>.</li>
  6022. </ul>
  6023. <p>Example configuration:</p>
  6024. <pre><code class="language-yaml">opentracing:
  6025. enabled: true
  6026. homeserver_whitelist:
  6027. - &quot;.*&quot;
  6028. force_tracing_for_users:
  6029. - &quot;@user1:server_name&quot;
  6030. - &quot;@user2:server_name&quot;
  6031. jaeger_config:
  6032. sampler:
  6033. type: const
  6034. param: 1
  6035. logging:
  6036. false
  6037. </code></pre>
  6038. <hr />
  6039. <h2 id="workers"><a class="header" href="#workers">Workers</a></h2>
  6040. <p>Configuration options related to workers.</p>
  6041. <hr />
  6042. <h3 id="send_federation"><a class="header" href="#send_federation"><code>send_federation</code></a></h3>
  6043. <p>Controls sending of outbound federation transactions on the main process.
  6044. Set to false if using a federation sender worker. Defaults to true. </p>
  6045. <p>Example configuration:</p>
  6046. <pre><code class="language-yaml">send_federation: false
  6047. </code></pre>
  6048. <hr />
  6049. <h3 id="federation_sender_instances"><a class="header" href="#federation_sender_instances"><code>federation_sender_instances</code></a></h3>
  6050. <p>It is possible to run multiple federation sender workers, in which case the
  6051. work is balanced across them. Use this setting to list the senders. </p>
  6052. <p>This configuration setting must be shared between all federation sender workers, and if
  6053. changed all federation sender workers must be stopped at the same time and then
  6054. started, to ensure that all instances are running with the same config (otherwise
  6055. events may be dropped). </p>
  6056. <p>Example configuration:</p>
  6057. <pre><code class="language-yaml">federation_sender_instances:
  6058. - federation_sender1
  6059. </code></pre>
  6060. <hr />
  6061. <h3 id="instance_map"><a class="header" href="#instance_map"><code>instance_map</code></a></h3>
  6062. <p>When using workers this should be a map from worker name to the
  6063. HTTP replication listener of the worker, if configured. </p>
  6064. <p>Example configuration:</p>
  6065. <pre><code class="language-yaml">instance_map:
  6066. worker1:
  6067. host: localhost
  6068. port: 8034
  6069. </code></pre>
  6070. <hr />
  6071. <h3 id="stream_writers"><a class="header" href="#stream_writers"><code>stream_writers</code></a></h3>
  6072. <p>Experimental: When using workers you can define which workers should
  6073. handle event persistence and typing notifications. Any worker
  6074. specified here must also be in the <code>instance_map</code>.</p>
  6075. <p>Example configuration:</p>
  6076. <pre><code class="language-yaml">stream_writers:
  6077. events: worker1
  6078. typing: worker1
  6079. </code></pre>
  6080. <hr />
  6081. <h3 id="run_background_tasks_on"><a class="header" href="#run_background_tasks_on"><code>run_background_tasks_on</code></a></h3>
  6082. <p>The worker that is used to run background tasks (e.g. cleaning up expired
  6083. data). If not provided this defaults to the main process.</p>
  6084. <p>Example configuration:</p>
  6085. <pre><code class="language-yaml">run_background_tasks_on: worker1
  6086. </code></pre>
  6087. <hr />
  6088. <h3 id="worker_replication_secret"><a class="header" href="#worker_replication_secret"><code>worker_replication_secret</code></a></h3>
  6089. <p>A shared secret used by the replication APIs to authenticate HTTP requests
  6090. from workers.</p>
  6091. <p>By default this is unused and traffic is not authenticated.</p>
  6092. <p>Example configuration:</p>
  6093. <pre><code class="language-yaml">worker_replication_secret: &quot;secret_secret&quot;
  6094. </code></pre>
  6095. <h3 id="redis"><a class="header" href="#redis"><code>redis</code></a></h3>
  6096. <p>Configuration for Redis when using workers. This <em>must</em> be enabled when
  6097. using workers (unless using old style direct TCP configuration).
  6098. This setting has the following sub-options:</p>
  6099. <ul>
  6100. <li><code>enabled</code>: whether to use Redis support. Defaults to false. </li>
  6101. <li><code>host</code> and <code>port</code>: Optional host and port to use to connect to redis. Defaults to
  6102. localhost and 6379</li>
  6103. <li><code>password</code>: Optional password if configured on the Redis instance.</li>
  6104. </ul>
  6105. <p>Example configuration:</p>
  6106. <pre><code class="language-yaml">redis:
  6107. enabled: true
  6108. host: localhost
  6109. port: 6379
  6110. password: &lt;secret_password&gt;
  6111. </code></pre>
  6112. <h2 id="background-updates"><a class="header" href="#background-updates">Background Updates</a></h2>
  6113. <p>Configuration settings related to background updates. </p>
  6114. <hr />
  6115. <h3 id="background_updates"><a class="header" href="#background_updates"><code>background_updates</code></a></h3>
  6116. <p>Background updates are database updates that are run in the background in batches.
  6117. The duration, minimum batch size, default batch size, whether to sleep between batches and if so, how long to
  6118. sleep can all be configured. This is helpful to speed up or slow down the updates.
  6119. This setting has the following sub-options:</p>
  6120. <ul>
  6121. <li><code>background_update_duration_ms</code>: How long in milliseconds to run a batch of background updates for. Defaults to 100.
  6122. Set a different time to change the default.</li>
  6123. <li><code>sleep_enabled</code>: Whether to sleep between updates. Defaults to true. Set to false to change the default.</li>
  6124. <li><code>sleep_duration_ms</code>: If sleeping between updates, how long in milliseconds to sleep for. Defaults to 1000.
  6125. Set a duration to change the default.</li>
  6126. <li><code>min_batch_size</code>: Minimum size a batch of background updates can be. Must be greater than 0. Defaults to 1.
  6127. Set a size to change the default.</li>
  6128. <li><code>default_batch_size</code>: The batch size to use for the first iteration of a new background update. The default is 100.
  6129. Set a size to change the default.</li>
  6130. </ul>
  6131. <p>Example configuration: </p>
  6132. <pre><code class="language-yaml">background_updates:
  6133. background_update_duration_ms: 500
  6134. sleep_enabled: false
  6135. sleep_duration_ms: 300
  6136. min_batch_size: 10
  6137. default_batch_size: 50
  6138. </code></pre>
  6139. <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>
  6140. <p>Below is a sample homeserver configuration file. The homeserver configuration file
  6141. can be tweaked to change the behaviour of your homeserver. A restart of the server is
  6142. generally required to apply any changes made to this file.</p>
  6143. <p>Note that the contents below are <em>not</em> intended to be copied and used as the basis for
  6144. a real homeserver.yaml. Instead, if you are starting from scratch, please generate
  6145. a fresh config using Synapse by following the instructions in
  6146. <a href="usage/configuration/../../setup/installation.html">Installation</a>.</p>
  6147. <pre><code class="language-yaml"># This file is maintained as an up-to-date snapshot of the default
  6148. # homeserver.yaml configuration generated by Synapse. You can find a
  6149. # complete accounting of possible configuration options at
  6150. # https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
  6151. #
  6152. # It is *not* intended to be copied and used as the basis for a real
  6153. # homeserver.yaml. Instead, if you are starting from scratch, please generate
  6154. # a fresh config using Synapse by following the instructions in
  6155. # https://matrix-org.github.io/synapse/latest/setup/installation.html.
  6156. #
  6157. ################################################################################
  6158. # Configuration file for Synapse.
  6159. #
  6160. # This is a YAML file: see [1] for a quick introduction. Note in particular
  6161. # that *indentation is important*: all the elements of a list or dictionary
  6162. # should have the same indentation.
  6163. #
  6164. # [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
  6165. #
  6166. # For more information on how to configure Synapse, including a complete accounting of
  6167. # each option, go to docs/usage/configuration/config_documentation.md or
  6168. # https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
  6169. server_name: &quot;SERVERNAME&quot;
  6170. pid_file: DATADIR/homeserver.pid
  6171. listeners:
  6172. - port: 8008
  6173. tls: false
  6174. type: http
  6175. x_forwarded: true
  6176. bind_addresses: ['::1', '127.0.0.1']
  6177. resources:
  6178. - names: [client, federation]
  6179. compress: false
  6180. database:
  6181. name: sqlite3
  6182. args:
  6183. database: DATADIR/homeserver.db
  6184. log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  6185. media_store_path: DATADIR/media_store
  6186. signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  6187. trusted_key_servers:
  6188. - server_name: &quot;matrix.org&quot;
  6189. </code></pre>
  6190. <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>
  6191. <p>Below is a sample logging configuration file. This file can be tweaked to control how your
  6192. homeserver will output logs. A restart of the server is generally required to apply any
  6193. changes made to this file. The value of the <code>log_config</code> option in your homeserver
  6194. config should be the path to this file.</p>
  6195. <p>Note that a default logging configuration (shown below) is created automatically alongside
  6196. the homeserver config when following the <a href="usage/configuration/../../setup/installation.html">installation instructions</a>.
  6197. It should be named <code>&lt;SERVERNAME&gt;.log.config</code> by default.</p>
  6198. <pre><code class="language-yaml"># Log configuration for Synapse.
  6199. #
  6200. # This is a YAML file containing a standard Python logging configuration
  6201. # dictionary. See [1] for details on the valid settings.
  6202. #
  6203. # Synapse also supports structured logging for machine readable logs which can
  6204. # be ingested by ELK stacks. See [2] for details.
  6205. #
  6206. # [1]: https://docs.python.org/3.7/library/logging.config.html#configuration-dictionary-schema
  6207. # [2]: https://matrix-org.github.io/synapse/latest/structured_logging.html
  6208. version: 1
  6209. formatters:
  6210. precise:
  6211. format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s'
  6212. handlers:
  6213. file:
  6214. class: logging.handlers.TimedRotatingFileHandler
  6215. formatter: precise
  6216. filename: /var/log/matrix-synapse/homeserver.log
  6217. when: midnight
  6218. backupCount: 3 # Does not include the current log file.
  6219. encoding: utf8
  6220. # Default to buffering writes to log file for efficiency.
  6221. # WARNING/ERROR logs will still be flushed immediately, but there will be a
  6222. # delay (of up to `period` seconds, or until the buffer is full with
  6223. # `capacity` messages) before INFO/DEBUG logs get written.
  6224. buffer:
  6225. class: synapse.logging.handlers.PeriodicallyFlushingMemoryHandler
  6226. target: file
  6227. # The capacity is the maximum number of log lines that are buffered
  6228. # before being written to disk. Increasing this will lead to better
  6229. # performance, at the expensive of it taking longer for log lines to
  6230. # be written to disk.
  6231. # This parameter is required.
  6232. capacity: 10
  6233. # Logs with a level at or above the flush level will cause the buffer to
  6234. # be flushed immediately.
  6235. # Default value: 40 (ERROR)
  6236. # Other values: 50 (CRITICAL), 30 (WARNING), 20 (INFO), 10 (DEBUG)
  6237. flushLevel: 30 # Flush immediately for WARNING logs and higher
  6238. # The period of time, in seconds, between forced flushes.
  6239. # Messages will not be delayed for longer than this time.
  6240. # Default value: 5 seconds
  6241. period: 5
  6242. # A handler that writes logs to stderr. Unused by default, but can be used
  6243. # instead of &quot;buffer&quot; and &quot;file&quot; in the logger handlers.
  6244. console:
  6245. class: logging.StreamHandler
  6246. formatter: precise
  6247. loggers:
  6248. synapse.storage.SQL:
  6249. # beware: increasing this to DEBUG will make synapse log sensitive
  6250. # information such as access tokens.
  6251. level: INFO
  6252. root:
  6253. level: INFO
  6254. # Write logs to the `buffer` handler, which will buffer them together in memory,
  6255. # then write them to a file.
  6256. #
  6257. # Replace &quot;buffer&quot; with &quot;console&quot; to log to stderr instead. (Note that you'll
  6258. # also need to update the configuration for the `twisted` logger above, in
  6259. # this case.)
  6260. #
  6261. handlers: [buffer]
  6262. disable_existing_loggers: false
  6263. </code></pre>
  6264. <div style="break-before: page; page-break-before: always;"></div><h1 id="structured-logging"><a class="header" href="#structured-logging">Structured Logging</a></h1>
  6265. <p>A structured logging system can be useful when your logs are destined for a
  6266. machine to parse and process. By maintaining its machine-readable characteristics,
  6267. it enables more efficient searching and aggregations when consumed by software
  6268. such as the &quot;ELK stack&quot;.</p>
  6269. <p>Synapse's structured logging system is configured via the file that Synapse's
  6270. <code>log_config</code> config option points to. The file should include a formatter which
  6271. uses the <code>synapse.logging.TerseJsonFormatter</code> class included with Synapse and a
  6272. handler which uses the above formatter.</p>
  6273. <p>There is also a <code>synapse.logging.JsonFormatter</code> option which does not include
  6274. a timestamp in the resulting JSON. This is useful if the log ingester adds its
  6275. own timestamp.</p>
  6276. <p>A structured logging configuration looks similar to the following:</p>
  6277. <pre><code class="language-yaml">version: 1
  6278. formatters:
  6279. structured:
  6280. class: synapse.logging.TerseJsonFormatter
  6281. handlers:
  6282. file:
  6283. class: logging.handlers.TimedRotatingFileHandler
  6284. formatter: structured
  6285. filename: /path/to/my/logs/homeserver.log
  6286. when: midnight
  6287. backupCount: 3 # Does not include the current log file.
  6288. encoding: utf8
  6289. loggers:
  6290. synapse:
  6291. level: INFO
  6292. handlers: [remote]
  6293. synapse.storage.SQL:
  6294. level: WARNING
  6295. </code></pre>
  6296. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  6297. with the SQL layer at 'WARNING', and will log to a file, stored as JSON.</p>
  6298. <p>It is also possible to configure Synapse to log to a remote endpoint by using the
  6299. <code>synapse.logging.RemoteHandler</code> class included with Synapse. It takes the
  6300. following arguments:</p>
  6301. <ul>
  6302. <li><code>host</code>: Hostname or IP address of the log aggregator.</li>
  6303. <li><code>port</code>: Numerical port to contact on the host.</li>
  6304. <li><code>maximum_buffer</code>: (Optional, defaults to 1000) The maximum buffer size to allow.</li>
  6305. </ul>
  6306. <p>A remote structured logging configuration looks similar to the following:</p>
  6307. <pre><code class="language-yaml">version: 1
  6308. formatters:
  6309. structured:
  6310. class: synapse.logging.TerseJsonFormatter
  6311. handlers:
  6312. remote:
  6313. class: synapse.logging.RemoteHandler
  6314. formatter: structured
  6315. host: 10.1.2.3
  6316. port: 9999
  6317. loggers:
  6318. synapse:
  6319. level: INFO
  6320. handlers: [remote]
  6321. synapse.storage.SQL:
  6322. level: WARNING
  6323. </code></pre>
  6324. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  6325. with the SQL layer at 'WARNING', and will log JSON formatted messages to a
  6326. remote endpoint at 10.1.2.3:9999.</p>
  6327. <div style="break-before: page; page-break-before: always;"></div><h1 id="templates"><a class="header" href="#templates">Templates</a></h1>
  6328. <p>Synapse uses parametrised templates to generate the content of emails it sends and
  6329. webpages it shows to users.</p>
  6330. <p>By default, Synapse will use the templates listed <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">here</a>.
  6331. Server admins can configure an additional directory for Synapse to look for templates
  6332. in, allowing them to specify custom templates:</p>
  6333. <pre><code class="language-yaml">templates:
  6334. custom_templates_directory: /path/to/custom/templates/
  6335. </code></pre>
  6336. <p>If this setting is not set, or the files named below are not found within the directory,
  6337. default templates from within the Synapse package will be used.</p>
  6338. <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>.
  6339. Templates rendered by Jinja 2 can also access two functions on top of the functions
  6340. already available as part of Jinja 2:</p>
  6341. <pre><code class="language-python">format_ts(value: int, format: str) -&gt; str
  6342. </code></pre>
  6343. <p>Formats a timestamp in milliseconds.</p>
  6344. <p>Example: <code>reason.last_sent_ts|format_ts(&quot;%c&quot;)</code></p>
  6345. <pre><code class="language-python">mxc_to_http(value: str, width: int, height: int, resize_method: str = &quot;crop&quot;) -&gt; str
  6346. </code></pre>
  6347. <p>Turns a <code>mxc://</code> URL for media content into an HTTP(S) one using the homeserver's
  6348. <code>public_baseurl</code> configuration setting as the URL's base.</p>
  6349. <p>Example: <code>message.sender_avatar_url|mxc_to_http(32,32)</code></p>
  6350. <pre><code class="language-python">localpart_from_email(address: str) -&gt; str
  6351. </code></pre>
  6352. <p>Returns the local part of an email address (e.g. <code>alice</code> in <code>alice@example.com</code>).</p>
  6353. <p>Example: <code>user.email_address|localpart_from_email</code></p>
  6354. <h2 id="email-templates"><a class="header" href="#email-templates">Email templates</a></h2>
  6355. <p>Below are the templates Synapse will look for when generating the content of an email:</p>
  6356. <ul>
  6357. <li><code>notif_mail.html</code> and <code>notif_mail.txt</code>: The contents of email notifications of missed
  6358. events.
  6359. When rendering, this template is given the following variables:
  6360. <ul>
  6361. <li><code>user_display_name</code>: the display name for the user receiving the notification</li>
  6362. <li><code>unsubscribe_link</code>: the link users can click to unsubscribe from email notifications</li>
  6363. <li><code>summary_text</code>: a summary of the notification(s). The text used can be customised
  6364. by configuring the various settings in the <code>email.subjects</code> section of the
  6365. configuration file.</li>
  6366. <li><code>rooms</code>: a list of rooms containing events to include in the email. Each element is
  6367. an object with the following attributes:
  6368. <ul>
  6369. <li><code>title</code>: a human-readable name for the room</li>
  6370. <li><code>hash</code>: a hash of the ID of the room</li>
  6371. <li><code>invite</code>: a boolean, which is <code>True</code> if the room is an invite the user hasn't
  6372. accepted yet, <code>False</code> otherwise</li>
  6373. <li><code>notifs</code>: a list of events, or an empty list if <code>invite</code> is <code>True</code>. Each element
  6374. is an object with the following attributes:
  6375. <ul>
  6376. <li><code>link</code>: a <code>matrix.to</code> link to the event</li>
  6377. <li><code>ts</code>: the time in milliseconds at which the event was received</li>
  6378. <li><code>messages</code>: a list of messages containing one message before the event, the
  6379. message in the event, and one message after the event. Each element is an
  6380. object with the following attributes:
  6381. <ul>
  6382. <li><code>event_type</code>: the type of the event</li>
  6383. <li><code>is_historical</code>: a boolean, which is <code>False</code> if the message is the one
  6384. that triggered the notification, <code>True</code> otherwise</li>
  6385. <li><code>id</code>: the ID of the event</li>
  6386. <li><code>ts</code>: the time in milliseconds at which the event was sent</li>
  6387. <li><code>sender_name</code>: the display name for the event's sender</li>
  6388. <li><code>sender_avatar_url</code>: the avatar URL (as a <code>mxc://</code> URL) for the event's
  6389. sender</li>
  6390. <li><code>sender_hash</code>: a hash of the user ID of the sender</li>
  6391. <li><code>msgtype</code>: the type of the message</li>
  6392. <li><code>body_text_html</code>: html representation of the message</li>
  6393. <li><code>body_text_plain</code>: plaintext representation of the message</li>
  6394. <li><code>image_url</code>: mxc url of an image, when &quot;msgtype&quot; is &quot;m.image&quot;</li>
  6395. </ul>
  6396. </li>
  6397. </ul>
  6398. </li>
  6399. <li><code>link</code>: a <code>matrix.to</code> link to the room</li>
  6400. <li><code>avator_url</code>: url to the room's avator</li>
  6401. </ul>
  6402. </li>
  6403. <li><code>reason</code>: information on the event that triggered the email to be sent. It's an
  6404. object with the following attributes:
  6405. <ul>
  6406. <li><code>room_id</code>: the ID of the room the event was sent in</li>
  6407. <li><code>room_name</code>: a human-readable name for the room the event was sent in</li>
  6408. <li><code>now</code>: the current time in milliseconds</li>
  6409. <li><code>received_at</code>: the time in milliseconds at which the event was received</li>
  6410. <li><code>delay_before_mail_ms</code>: the amount of time in milliseconds Synapse always waits
  6411. before ever emailing about a notification (to give the user a chance to respond
  6412. to other push or notice the window)</li>
  6413. <li><code>last_sent_ts</code>: the time in milliseconds at which a notification was last sent
  6414. for an event in this room</li>
  6415. <li><code>throttle_ms</code>: the minimum amount of time in milliseconds between two
  6416. notifications can be sent for this room</li>
  6417. </ul>
  6418. </li>
  6419. </ul>
  6420. </li>
  6421. <li><code>password_reset.html</code> and <code>password_reset.txt</code>: The contents of password reset emails
  6422. sent by the homeserver.
  6423. When rendering, these templates are given a <code>link</code> variable which contains the link the
  6424. user must click in order to reset their password.</li>
  6425. <li><code>registration.html</code> and <code>registration.txt</code>: The contents of address verification emails
  6426. sent during registration.
  6427. When rendering, these templates are given a <code>link</code> variable which contains the link the
  6428. user must click in order to validate their email address.</li>
  6429. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code>: The contents of address verification emails
  6430. sent when an address is added to a Matrix account.
  6431. When rendering, these templates are given a <code>link</code> variable which contains the link the
  6432. user must click in order to validate their email address.</li>
  6433. </ul>
  6434. <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>
  6435. <p>Below are the templates Synapse will look for when generating pages related to
  6436. registration and password reset:</p>
  6437. <ul>
  6438. <li><code>password_reset_confirmation.html</code>: An HTML page that a user will see when they follow
  6439. the link in the password reset email. The user will be asked to confirm the action
  6440. before their password is reset.
  6441. When rendering, this template is given the following variables:
  6442. <ul>
  6443. <li><code>sid</code>: the session ID for the password reset</li>
  6444. <li><code>token</code>: the token for the password reset</li>
  6445. <li><code>client_secret</code>: the client secret for the password reset</li>
  6446. </ul>
  6447. </li>
  6448. <li><code>password_reset_success.html</code> and <code>password_reset_failure.html</code>: HTML pages for success
  6449. and failure that a user will see when they confirm the password reset flow using the
  6450. page above.
  6451. When rendering, <code>password_reset_success.html</code> is given no variable, and
  6452. <code>password_reset_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  6453. for the password reset failure. </li>
  6454. <li><code>registration_success.html</code> and <code>registration_failure.html</code>: HTML pages for success and
  6455. failure that a user will see when they follow the link in an address verification email
  6456. sent during registration.
  6457. When rendering, <code>registration_success.html</code> is given no variable, and
  6458. <code>registration_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  6459. for the registration failure.</li>
  6460. <li><code>add_threepid_success.html</code> and <code>add_threepid_failure.html</code>: HTML pages for success and
  6461. failure that a user will see when they follow the link in an address verification email
  6462. sent when an address is added to a Matrix account.
  6463. When rendering, <code>add_threepid_success.html</code> is given no variable, and
  6464. <code>add_threepid_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  6465. for the registration failure.</li>
  6466. </ul>
  6467. <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>
  6468. <p>Below are the templates Synapse will look for when generating pages related to SSO:</p>
  6469. <ul>
  6470. <li><code>sso_login_idp_picker.html</code>: HTML page to prompt the user to choose an
  6471. Identity Provider during login.
  6472. This is only used if multiple SSO Identity Providers are configured.
  6473. When rendering, this template is given the following variables:
  6474. <ul>
  6475. <li><code>redirect_url</code>: the URL that the user will be redirected to after
  6476. login.</li>
  6477. <li><code>server_name</code>: the homeserver's name.</li>
  6478. <li><code>providers</code>: a list of available Identity Providers. Each element is
  6479. an object with the following attributes:
  6480. <ul>
  6481. <li><code>idp_id</code>: unique identifier for the IdP</li>
  6482. <li><code>idp_name</code>: user-facing name for the IdP</li>
  6483. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  6484. for the IdP</li>
  6485. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  6486. for the brand of the IdP
  6487. The rendered HTML page should contain a form which submits its results
  6488. back as a GET request, with the following query parameters:</li>
  6489. </ul>
  6490. </li>
  6491. <li><code>redirectUrl</code>: the client redirect URI (ie, the <code>redirect_url</code> passed
  6492. to the template)</li>
  6493. <li><code>idp</code>: the 'idp_id' of the chosen IDP.</li>
  6494. </ul>
  6495. </li>
  6496. <li><code>sso_auth_account_details.html</code>: HTML page to prompt new users to enter a
  6497. userid and confirm other details. This is only shown if the
  6498. SSO implementation (with any <code>user_mapping_provider</code>) does not return
  6499. a localpart.
  6500. When rendering, this template is given the following variables:
  6501. <ul>
  6502. <li><code>server_name</code>: the homeserver's name.</li>
  6503. <li><code>idp</code>: details of the SSO Identity Provider that the user logged in
  6504. with: an object with the following attributes:
  6505. <ul>
  6506. <li><code>idp_id</code>: unique identifier for the IdP</li>
  6507. <li><code>idp_name</code>: user-facing name for the IdP</li>
  6508. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  6509. for the IdP</li>
  6510. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  6511. for the brand of the IdP</li>
  6512. </ul>
  6513. </li>
  6514. <li><code>user_attributes</code>: an object containing details about the user that
  6515. we received from the IdP. May have the following attributes:
  6516. <ul>
  6517. <li><code>display_name</code>: the user's display name</li>
  6518. <li><code>emails</code>: a list of email addresses</li>
  6519. <li><code>localpart</code>: the local part of the Matrix user ID to register,
  6520. if <code>localpart_template</code> is set in the mapping provider configuration (empty
  6521. string if not)
  6522. The template should render a form which submits the following fields:</li>
  6523. </ul>
  6524. </li>
  6525. <li><code>username</code>: the localpart of the user's chosen user id</li>
  6526. </ul>
  6527. </li>
  6528. <li><code>sso_new_user_consent.html</code>: HTML page allowing the user to consent to the
  6529. server's terms and conditions. This is only shown for new users, and only if
  6530. <code>user_consent.require_at_registration</code> is set.
  6531. When rendering, this template is given the following variables:
  6532. <ul>
  6533. <li><code>server_name</code>: the homeserver's name.</li>
  6534. <li><code>user_id</code>: the user's matrix proposed ID.</li>
  6535. <li><code>user_profile.display_name</code>: the user's proposed display name, if any.</li>
  6536. <li>consent_version: the version of the terms that the user will be
  6537. shown</li>
  6538. <li><code>terms_url</code>: a link to the page showing the terms.
  6539. The template should render a form which submits the following fields:</li>
  6540. <li><code>accepted_version</code>: the version of the terms accepted by the user
  6541. (ie, 'consent_version' from the input variables).</li>
  6542. </ul>
  6543. </li>
  6544. <li><code>sso_redirect_confirm.html</code>: HTML page for a confirmation step before redirecting back
  6545. to the client with the login token.
  6546. When rendering, this template is given the following variables:
  6547. <ul>
  6548. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  6549. <li><code>display_url</code>: the same as <code>redirect_url</code>, but with the query
  6550. parameters stripped. The intention is to have a
  6551. human-readable URL to show to users, not to use it as
  6552. the final address to redirect to.</li>
  6553. <li><code>server_name</code>: the homeserver's name.</li>
  6554. <li><code>new_user</code>: a boolean indicating whether this is the user's first time
  6555. logging in.</li>
  6556. <li><code>user_id</code>: the user's matrix ID.</li>
  6557. <li><code>user_profile.avatar_url</code>: an MXC URI for the user's avatar, if any.
  6558. <code>None</code> if the user has not set an avatar.</li>
  6559. <li><code>user_profile.display_name</code>: the user's display name. <code>None</code> if the user
  6560. has not set a display name.</li>
  6561. </ul>
  6562. </li>
  6563. <li><code>sso_auth_confirm.html</code>: HTML page which notifies the user that they are authenticating
  6564. to confirm an operation on their account during the user interactive authentication
  6565. process.
  6566. When rendering, this template is given the following variables:
  6567. <ul>
  6568. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  6569. <li><code>description</code>: the operation which the user is being asked to confirm</li>
  6570. <li><code>idp</code>: details of the Identity Provider that we will use to confirm
  6571. the user's identity: an object with the following attributes:
  6572. <ul>
  6573. <li><code>idp_id</code>: unique identifier for the IdP</li>
  6574. <li><code>idp_name</code>: user-facing name for the IdP</li>
  6575. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  6576. for the IdP</li>
  6577. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  6578. for the brand of the IdP</li>
  6579. </ul>
  6580. </li>
  6581. </ul>
  6582. </li>
  6583. <li><code>sso_auth_success.html</code>: HTML page shown after a successful user interactive
  6584. authentication session.
  6585. Note that this page must include the JavaScript which notifies of a successful
  6586. authentication (see https://matrix.org/docs/spec/client_server/r0.6.0#fallback).
  6587. This template has no additional variables.</li>
  6588. <li><code>sso_auth_bad_user.html</code>: HTML page shown after a user-interactive authentication
  6589. session which does not map correctly onto the expected user.
  6590. When rendering, this template is given the following variables:
  6591. <ul>
  6592. <li><code>server_name</code>: the homeserver's name.</li>
  6593. <li><code>user_id_to_verify</code>: the MXID of the user that we are trying to
  6594. validate.</li>
  6595. </ul>
  6596. </li>
  6597. <li><code>sso_account_deactivated.html</code>: HTML page shown during single sign-on if a deactivated
  6598. user (according to Synapse's database) attempts to login.
  6599. This template has no additional variables.</li>
  6600. <li><code>sso_error.html</code>: HTML page to display to users if something goes wrong during the
  6601. OpenID Connect authentication process.
  6602. When rendering, this template is given two variables:
  6603. <ul>
  6604. <li><code>error</code>: the technical name of the error</li>
  6605. <li><code>error_description</code>: a human-readable message for the error</li>
  6606. </ul>
  6607. </li>
  6608. </ul>
  6609. <div style="break-before: page; page-break-before: always;"></div><h1 id="user-authentication"><a class="header" href="#user-authentication">User Authentication</a></h1>
  6610. <p>Synapse supports multiple methods of authenticating users, either out-of-the-box or through custom pluggable
  6611. authentication modules.</p>
  6612. <p>Included in Synapse is support for authenticating users via:</p>
  6613. <ul>
  6614. <li>A username and password.</li>
  6615. <li>An email address and password.</li>
  6616. <li>Single Sign-On through the SAML, Open ID Connect or CAS protocols.</li>
  6617. <li>JSON Web Tokens.</li>
  6618. <li>An administrator's shared secret.</li>
  6619. </ul>
  6620. <p>Synapse can additionally be extended to support custom authentication schemes through optional &quot;password auth provider&quot;
  6621. modules.</p>
  6622. <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>
  6623. <p>Synapse supports single sign-on through the SAML, Open ID Connect or CAS protocols.
  6624. LDAP and other login methods are supported through first and third-party password
  6625. auth provider modules.</p>
  6626. <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>
  6627. <p>Synapse can be configured to use an OpenID Connect Provider (OP) for
  6628. authentication, instead of its own local password database.</p>
  6629. <p>Any OP should work with Synapse, as long as it supports the authorization code
  6630. flow. There are a few options for that:</p>
  6631. <ul>
  6632. <li>
  6633. <p>start a local OP. Synapse has been tested with <a href="https://www.ory.sh/docs/hydra/">Hydra</a> and
  6634. <a href="https://github.com/dexidp/dex">Dex</a>. Note that for an OP to work, it should be served under a
  6635. secure (HTTPS) origin. A certificate signed with a self-signed, locally
  6636. trusted CA should work. In that case, start Synapse with a <code>SSL_CERT_FILE</code>
  6637. environment variable set to the path of the CA.</p>
  6638. </li>
  6639. <li>
  6640. <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
  6641. <a href="https://www.okta.com/">Okta</a>. Synapse has been tested with Auth0 and Google.</p>
  6642. </li>
  6643. </ul>
  6644. <p>It may also be possible to use other OAuth2 providers which provide the
  6645. <a href="https://tools.ietf.org/html/rfc6749#section-4.1">authorization code grant type</a>,
  6646. such as <a href="https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps">Github</a>.</p>
  6647. <h2 id="preparing-synapse"><a class="header" href="#preparing-synapse">Preparing Synapse</a></h2>
  6648. <p>The OpenID integration in Synapse uses the
  6649. <a href="https://pypi.org/project/Authlib/"><code>authlib</code></a> library, which must be installed
  6650. as follows:</p>
  6651. <ul>
  6652. <li>
  6653. <p>The relevant libraries are included in the Docker images and Debian packages
  6654. provided by <code>matrix.org</code> so no further action is needed.</p>
  6655. </li>
  6656. <li>
  6657. <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>
  6658. </li>
  6659. <li>
  6660. <p>For other installation mechanisms, see the documentation provided by the
  6661. maintainer.</p>
  6662. </li>
  6663. </ul>
  6664. <p>To enable the OpenID integration, you should then add a section to the <code>oidc_providers</code>
  6665. setting in your configuration file (or uncomment one of the existing examples).
  6666. See <a href="./sample_config.yaml">sample_config.yaml</a> for some sample settings, as well as
  6667. the text below for example configurations for specific providers.</p>
  6668. <h2 id="sample-configs"><a class="header" href="#sample-configs">Sample configs</a></h2>
  6669. <p>Here are a few configs for providers that should work with Synapse.</p>
  6670. <h3 id="microsoft-azure-active-directory"><a class="header" href="#microsoft-azure-active-directory">Microsoft Azure Active Directory</a></h3>
  6671. <p>Azure AD can act as an OpenID Connect Provider. Register a new application under
  6672. <em>App registrations</em> in the Azure AD management console. The RedirectURI for your
  6673. application should point to your matrix server:
  6674. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  6675. <p>Go to <em>Certificates &amp; secrets</em> and register a new client secret. Make note of your
  6676. Directory (tenant) ID as it will be used in the Azure links.
  6677. Edit your Synapse config file and change the <code>oidc_config</code> section:</p>
  6678. <pre><code class="language-yaml">oidc_providers:
  6679. - idp_id: microsoft
  6680. idp_name: Microsoft
  6681. issuer: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/v2.0&quot;
  6682. client_id: &quot;&lt;client id&gt;&quot;
  6683. client_secret: &quot;&lt;client secret&gt;&quot;
  6684. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6685. authorization_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/authorize&quot;
  6686. token_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/token&quot;
  6687. userinfo_endpoint: &quot;https://graph.microsoft.com/oidc/userinfo&quot;
  6688. user_mapping_provider:
  6689. config:
  6690. localpart_template: &quot;{{ user.preferred_username.split('@')[0] }}&quot;
  6691. display_name_template: &quot;{{ user.name }}&quot;
  6692. </code></pre>
  6693. <h3 id="dex"><a class="header" href="#dex">Dex</a></h3>
  6694. <p><a href="https://github.com/dexidp/dex">Dex</a> is a simple, open-source OpenID Connect Provider.
  6695. Although it is designed to help building a full-blown provider with an
  6696. external database, it can be configured with static passwords in a config file.</p>
  6697. <p>Follow the <a href="https://dexidp.io/docs/getting-started/">Getting Started guide</a>
  6698. to install Dex.</p>
  6699. <p>Edit <code>examples/config-dev.yaml</code> config file from the Dex repo to add a client:</p>
  6700. <pre><code class="language-yaml">staticClients:
  6701. - id: synapse
  6702. secret: secret
  6703. redirectURIs:
  6704. - '[synapse public baseurl]/_synapse/client/oidc/callback'
  6705. name: 'Synapse'
  6706. </code></pre>
  6707. <p>Run with <code>dex serve examples/config-dev.yaml</code>.</p>
  6708. <p>Synapse config:</p>
  6709. <pre><code class="language-yaml">oidc_providers:
  6710. - idp_id: dex
  6711. idp_name: &quot;My Dex server&quot;
  6712. skip_verification: true # This is needed as Dex is served on an insecure endpoint
  6713. issuer: &quot;http://127.0.0.1:5556/dex&quot;
  6714. client_id: &quot;synapse&quot;
  6715. client_secret: &quot;secret&quot;
  6716. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6717. user_mapping_provider:
  6718. config:
  6719. localpart_template: &quot;{{ user.name }}&quot;
  6720. display_name_template: &quot;{{ user.name|capitalize }}&quot;
  6721. </code></pre>
  6722. <h3 id="keycloak"><a class="header" href="#keycloak">Keycloak</a></h3>
  6723. <p><a href="https://www.keycloak.org/docs/latest/server_admin/#sso-protocols">Keycloak</a> is an opensource IdP maintained by Red Hat.</p>
  6724. <p>Follow the <a href="https://www.keycloak.org/getting-started">Getting Started Guide</a> to install Keycloak and set up a realm.</p>
  6725. <ol>
  6726. <li>
  6727. <p>Click <code>Clients</code> in the sidebar and click <code>Create</code></p>
  6728. </li>
  6729. <li>
  6730. <p>Fill in the fields as below:</p>
  6731. </li>
  6732. </ol>
  6733. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  6734. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  6735. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  6736. </tbody></table>
  6737. <ol start="3">
  6738. <li>Click <code>Save</code></li>
  6739. <li>Fill in the fields as below:</li>
  6740. </ol>
  6741. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  6742. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  6743. <tr><td>Enabled</td><td><code>On</code></td></tr>
  6744. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  6745. <tr><td>Access Type</td><td><code>confidential</code></td></tr>
  6746. <tr><td>Valid Redirect URIs</td><td><code>[synapse public baseurl]/_synapse/client/oidc/callback</code></td></tr>
  6747. </tbody></table>
  6748. <ol start="5">
  6749. <li>Click <code>Save</code></li>
  6750. <li>On the Credentials tab, update the fields:</li>
  6751. </ol>
  6752. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  6753. <tr><td>Client Authenticator</td><td><code>Client ID and Secret</code></td></tr>
  6754. </tbody></table>
  6755. <ol start="7">
  6756. <li>Click <code>Regenerate Secret</code></li>
  6757. <li>Copy Secret</li>
  6758. </ol>
  6759. <pre><code class="language-yaml">oidc_providers:
  6760. - idp_id: keycloak
  6761. idp_name: &quot;My KeyCloak server&quot;
  6762. issuer: &quot;https://127.0.0.1:8443/realms/{realm_name}&quot;
  6763. client_id: &quot;synapse&quot;
  6764. client_secret: &quot;copy secret generated from above&quot;
  6765. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6766. user_mapping_provider:
  6767. config:
  6768. localpart_template: &quot;{{ user.preferred_username }}&quot;
  6769. display_name_template: &quot;{{ user.name }}&quot;
  6770. </code></pre>
  6771. <h3 id="auth0"><a class="header" href="#auth0">Auth0</a></h3>
  6772. <p><a href="https://auth0.com/">Auth0</a> is a hosted SaaS IdP solution.</p>
  6773. <ol>
  6774. <li>
  6775. <p>Create a regular web application for Synapse</p>
  6776. </li>
  6777. <li>
  6778. <p>Set the Allowed Callback URLs to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  6779. </li>
  6780. <li>
  6781. <p>Add a rule to add the <code>preferred_username</code> claim.</p>
  6782. <details>
  6783. <summary>Code sample</summary>
  6784. <pre><code class="language-js">function addPersistenceAttribute(user, context, callback) {
  6785. user.user_metadata = user.user_metadata || {};
  6786. user.user_metadata.preferred_username = user.user_metadata.preferred_username || user.user_id;
  6787. context.idToken.preferred_username = user.user_metadata.preferred_username;
  6788. auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
  6789. .then(function(){
  6790. callback(null, user, context);
  6791. })
  6792. .catch(function(err){
  6793. callback(err);
  6794. });
  6795. }
  6796. </code></pre>
  6797. </li>
  6798. </ol>
  6799. </details>
  6800. <p>Synapse config:</p>
  6801. <pre><code class="language-yaml">oidc_providers:
  6802. - idp_id: auth0
  6803. idp_name: Auth0
  6804. issuer: &quot;https://your-tier.eu.auth0.com/&quot; # TO BE FILLED
  6805. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6806. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6807. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6808. user_mapping_provider:
  6809. config:
  6810. localpart_template: &quot;{{ user.preferred_username }}&quot;
  6811. display_name_template: &quot;{{ user.name }}&quot;
  6812. </code></pre>
  6813. <h3 id="authentik"><a class="header" href="#authentik">Authentik</a></h3>
  6814. <p><a href="https://goauthentik.io/">Authentik</a> is an open-source IdP solution.</p>
  6815. <ol>
  6816. <li>Create a provider in Authentik, with type OAuth2/OpenID.</li>
  6817. <li>The parameters are:</li>
  6818. </ol>
  6819. <ul>
  6820. <li>Client Type: Confidential</li>
  6821. <li>JWT Algorithm: RS256</li>
  6822. <li>Scopes: OpenID, Email and Profile</li>
  6823. <li>RSA Key: Select any available key</li>
  6824. <li>Redirect URIs: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  6825. </ul>
  6826. <ol start="3">
  6827. <li>Create an application for synapse in Authentik and link it to the provider.</li>
  6828. <li>Note the slug of your application, Client ID and Client Secret.</li>
  6829. </ol>
  6830. <p>Note: RSA keys must be used for signing for Authentik, ECC keys do not work.</p>
  6831. <p>Synapse config:</p>
  6832. <pre><code class="language-yaml">oidc_providers:
  6833. - idp_id: authentik
  6834. idp_name: authentik
  6835. discover: true
  6836. issuer: &quot;https://your.authentik.example.org/application/o/your-app-slug/&quot; # TO BE FILLED: domain and slug
  6837. client_id: &quot;your client id&quot; # TO BE FILLED
  6838. client_secret: &quot;your client secret&quot; # TO BE FILLED
  6839. scopes:
  6840. - &quot;openid&quot;
  6841. - &quot;profile&quot;
  6842. - &quot;email&quot;
  6843. user_mapping_provider:
  6844. config:
  6845. localpart_template: &quot;{{ user.preferred_username }}&quot;
  6846. 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.
  6847. </code></pre>
  6848. <h3 id="lemonldap"><a class="header" href="#lemonldap">LemonLDAP</a></h3>
  6849. <p><a href="https://lemonldap-ng.org/">LemonLDAP::NG</a> is an open-source IdP solution.</p>
  6850. <ol>
  6851. <li>Create an OpenID Connect Relying Parties in LemonLDAP::NG</li>
  6852. <li>The parameters are:</li>
  6853. </ol>
  6854. <ul>
  6855. <li>Client ID under the basic menu of the new Relying Parties (<code>Options &gt; Basic &gt; Client ID</code>)</li>
  6856. <li>Client secret (<code>Options &gt; Basic &gt; Client secret</code>)</li>
  6857. <li>JWT Algorithm: RS256 within the security menu of the new Relying Parties
  6858. (<code>Options &gt; Security &gt; ID Token signature algorithm</code> and <code>Options &gt; Security &gt; Access Token signature algorithm</code>)</li>
  6859. <li>Scopes: OpenID, Email and Profile</li>
  6860. <li>Allowed redirection addresses for login (<code>Options &gt; Basic &gt; Allowed redirection addresses for login</code> ) :
  6861. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  6862. </ul>
  6863. <p>Synapse config:</p>
  6864. <pre><code class="language-yaml">oidc_providers:
  6865. - idp_id: lemonldap
  6866. idp_name: lemonldap
  6867. discover: true
  6868. issuer: &quot;https://auth.example.org/&quot; # TO BE FILLED: replace with your domain
  6869. client_id: &quot;your client id&quot; # TO BE FILLED
  6870. client_secret: &quot;your client secret&quot; # TO BE FILLED
  6871. scopes:
  6872. - &quot;openid&quot;
  6873. - &quot;profile&quot;
  6874. - &quot;email&quot;
  6875. user_mapping_provider:
  6876. config:
  6877. localpart_template: &quot;{{ user.preferred_username }}}&quot;
  6878. # 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.
  6879. display_name_template: &quot;{{ user.preferred_username|capitalize }}&quot;
  6880. </code></pre>
  6881. <h3 id="github"><a class="header" href="#github">GitHub</a></h3>
  6882. <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
  6883. just a regular OAuth2 provider.</p>
  6884. <p>The <a href="https://developer.github.com/v3/users/#get-the-authenticated-user"><code>/user</code> API endpoint</a>
  6885. can be used to retrieve information on the authenticated user. As the Synapse
  6886. login mechanism needs an attribute to uniquely identify users, and that endpoint
  6887. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  6888. <ol>
  6889. <li>Create a new OAuth application: <a href="https://github.com/settings/applications/new">https://github.com/settings/applications/new</a>.</li>
  6890. <li>Set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  6891. </ol>
  6892. <p>Synapse config:</p>
  6893. <pre><code class="language-yaml">oidc_providers:
  6894. - idp_id: github
  6895. idp_name: Github
  6896. idp_brand: &quot;github&quot; # optional: styling hint for clients
  6897. discover: false
  6898. issuer: &quot;https://github.com/&quot;
  6899. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6900. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6901. authorization_endpoint: &quot;https://github.com/login/oauth/authorize&quot;
  6902. token_endpoint: &quot;https://github.com/login/oauth/access_token&quot;
  6903. userinfo_endpoint: &quot;https://api.github.com/user&quot;
  6904. scopes: [&quot;read:user&quot;]
  6905. user_mapping_provider:
  6906. config:
  6907. subject_claim: &quot;id&quot;
  6908. localpart_template: &quot;{{ user.login }}&quot;
  6909. display_name_template: &quot;{{ user.name }}&quot;
  6910. </code></pre>
  6911. <h3 id="google"><a class="header" href="#google">Google</a></h3>
  6912. <p><a href="https://developers.google.com/identity/protocols/oauth2/openid-connect">Google</a> is an OpenID certified authentication and authorisation provider.</p>
  6913. <ol>
  6914. <li>Set up a project in the Google API Console (see
  6915. <a href="https://developers.google.com/identity/protocols/oauth2/openid-connect#appsetup">documentation</a>).</li>
  6916. <li>Add an &quot;OAuth Client ID&quot; for a Web Application under &quot;Credentials&quot;.</li>
  6917. <li>Copy the Client ID and Client Secret, and add the following to your synapse config:
  6918. <pre><code class="language-yaml">oidc_providers:
  6919. - idp_id: google
  6920. idp_name: Google
  6921. idp_brand: &quot;google&quot; # optional: styling hint for clients
  6922. issuer: &quot;https://accounts.google.com/&quot;
  6923. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6924. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6925. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6926. user_mapping_provider:
  6927. config:
  6928. localpart_template: &quot;{{ user.given_name|lower }}&quot;
  6929. display_name_template: &quot;{{ user.name }}&quot;
  6930. </code></pre>
  6931. </li>
  6932. <li>Back in the Google console, add this Authorized redirect URI: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  6933. </ol>
  6934. <h3 id="twitch"><a class="header" href="#twitch">Twitch</a></h3>
  6935. <ol>
  6936. <li>Setup a developer account on <a href="https://dev.twitch.tv/">Twitch</a></li>
  6937. <li>Obtain the OAuth 2.0 credentials by <a href="https://dev.twitch.tv/console/apps/">creating an app</a></li>
  6938. <li>Add this OAuth Redirect URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  6939. </ol>
  6940. <p>Synapse config:</p>
  6941. <pre><code class="language-yaml">oidc_providers:
  6942. - idp_id: twitch
  6943. idp_name: Twitch
  6944. issuer: &quot;https://id.twitch.tv/oauth2/&quot;
  6945. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6946. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6947. client_auth_method: &quot;client_secret_post&quot;
  6948. user_mapping_provider:
  6949. config:
  6950. localpart_template: &quot;{{ user.preferred_username }}&quot;
  6951. display_name_template: &quot;{{ user.name }}&quot;
  6952. </code></pre>
  6953. <h3 id="gitlab"><a class="header" href="#gitlab">GitLab</a></h3>
  6954. <ol>
  6955. <li>Create a <a href="https://gitlab.com/profile/applications">new application</a>.</li>
  6956. <li>Add the <code>read_user</code> and <code>openid</code> scopes.</li>
  6957. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  6958. </ol>
  6959. <p>Synapse config:</p>
  6960. <pre><code class="language-yaml">oidc_providers:
  6961. - idp_id: gitlab
  6962. idp_name: Gitlab
  6963. idp_brand: &quot;gitlab&quot; # optional: styling hint for clients
  6964. issuer: &quot;https://gitlab.com/&quot;
  6965. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6966. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6967. client_auth_method: &quot;client_secret_post&quot;
  6968. scopes: [&quot;openid&quot;, &quot;read_user&quot;]
  6969. user_profile_method: &quot;userinfo_endpoint&quot;
  6970. user_mapping_provider:
  6971. config:
  6972. localpart_template: '{{ user.nickname }}'
  6973. display_name_template: '{{ user.name }}'
  6974. </code></pre>
  6975. <h3 id="facebook"><a class="header" href="#facebook">Facebook</a></h3>
  6976. <ol start="0">
  6977. <li>You will need a Facebook developer account. You can register for one
  6978. <a href="https://developers.facebook.com/async/registration/">here</a>.</li>
  6979. <li>On the <a href="https://developers.facebook.com/apps/">apps</a> page of the developer
  6980. console, &quot;Create App&quot;, and choose &quot;Build Connected Experiences&quot;.</li>
  6981. <li>Once the app is created, add &quot;Facebook Login&quot; and choose &quot;Web&quot;. You don't
  6982. need to go through the whole form here.</li>
  6983. <li>In the left-hand menu, open &quot;Products&quot;/&quot;Facebook Login&quot;/&quot;Settings&quot;.
  6984. <ul>
  6985. <li>Add <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> as an OAuth Redirect
  6986. URL.</li>
  6987. </ul>
  6988. </li>
  6989. <li>In the left-hand menu, open &quot;Settings/Basic&quot;. Here you can copy the &quot;App ID&quot;
  6990. and &quot;App Secret&quot; for use below.</li>
  6991. </ol>
  6992. <p>Synapse config:</p>
  6993. <pre><code class="language-yaml"> - idp_id: facebook
  6994. idp_name: Facebook
  6995. idp_brand: &quot;facebook&quot; # optional: styling hint for clients
  6996. discover: false
  6997. issuer: &quot;https://www.facebook.com&quot;
  6998. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6999. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7000. scopes: [&quot;openid&quot;, &quot;email&quot;]
  7001. authorization_endpoint: &quot;https://facebook.com/dialog/oauth&quot;
  7002. token_endpoint: &quot;https://graph.facebook.com/v9.0/oauth/access_token&quot;
  7003. jwks_uri: &quot;https://www.facebook.com/.well-known/oauth/openid/jwks/&quot;
  7004. user_mapping_provider:
  7005. config:
  7006. display_name_template: &quot;{{ user.name }}&quot;
  7007. email_template: &quot;{{ '{{ user.email }}' }}&quot;
  7008. </code></pre>
  7009. <p>Relevant documents:</p>
  7010. <ul>
  7011. <li><a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow">Manually Build a Login Flow</a></li>
  7012. <li><a href="https://developers.facebook.com/docs/graph-api/using-graph-api/">Using Facebook's Graph API</a></li>
  7013. <li><a href="https://developers.facebook.com/docs/graph-api/reference/user">Reference to the User endpoint</a></li>
  7014. </ul>
  7015. <p>Facebook do have an <a href="https://www.facebook.com/.well-known/openid-configuration">OIDC discovery endpoint</a>,
  7016. but it has a <code>response_types_supported</code> which excludes &quot;code&quot; (which we rely on, and
  7017. is even mentioned in their <a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#login">documentation</a>),
  7018. so we have to disable discovery and configure the URIs manually.</p>
  7019. <h3 id="gitea"><a class="header" href="#gitea">Gitea</a></h3>
  7020. <p>Gitea is, like Github, not an OpenID provider, but just an OAuth2 provider.</p>
  7021. <p>The <a href="https://try.gitea.io/api/swagger#/user/userGetCurrent"><code>/user</code> API endpoint</a>
  7022. can be used to retrieve information on the authenticated user. As the Synapse
  7023. login mechanism needs an attribute to uniquely identify users, and that endpoint
  7024. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  7025. <ol>
  7026. <li>Create a new application.</li>
  7027. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  7028. </ol>
  7029. <p>Synapse config:</p>
  7030. <pre><code class="language-yaml">oidc_providers:
  7031. - idp_id: gitea
  7032. idp_name: Gitea
  7033. discover: false
  7034. issuer: &quot;https://your-gitea.com/&quot;
  7035. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7036. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  7037. client_auth_method: client_secret_post
  7038. scopes: [] # Gitea doesn't support Scopes
  7039. authorization_endpoint: &quot;https://your-gitea.com/login/oauth/authorize&quot;
  7040. token_endpoint: &quot;https://your-gitea.com/login/oauth/access_token&quot;
  7041. userinfo_endpoint: &quot;https://your-gitea.com/api/v1/user&quot;
  7042. user_mapping_provider:
  7043. config:
  7044. subject_claim: &quot;id&quot;
  7045. localpart_template: &quot;{{ user.login }}&quot;
  7046. display_name_template: &quot;{{ user.full_name }}&quot;
  7047. </code></pre>
  7048. <h3 id="xwiki"><a class="header" href="#xwiki">XWiki</a></h3>
  7049. <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>
  7050. <p>Synapse config:</p>
  7051. <pre><code class="language-yaml">oidc_providers:
  7052. - idp_id: xwiki
  7053. idp_name: &quot;XWiki&quot;
  7054. issuer: &quot;https://myxwikihost/xwiki/oidc/&quot;
  7055. client_id: &quot;your-client-id&quot; # TO BE FILLED
  7056. client_auth_method: none
  7057. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  7058. user_profile_method: &quot;userinfo_endpoint&quot;
  7059. user_mapping_provider:
  7060. config:
  7061. localpart_template: &quot;{{ user.preferred_username }}&quot;
  7062. display_name_template: &quot;{{ user.name }}&quot;
  7063. </code></pre>
  7064. <h3 id="apple"><a class="header" href="#apple">Apple</a></h3>
  7065. <p>Configuring &quot;Sign in with Apple&quot; (SiWA) requires an Apple Developer account.</p>
  7066. <p>You will need to create a new &quot;Services ID&quot; for SiWA, and create and download a
  7067. private key with &quot;SiWA&quot; enabled.</p>
  7068. <p>As well as the private key file, you will need:</p>
  7069. <ul>
  7070. <li>Client ID: the &quot;identifier&quot; you gave the &quot;Services ID&quot;</li>
  7071. <li>Team ID: a 10-character ID associated with your developer account.</li>
  7072. <li>Key ID: the 10-character identifier for the key.</li>
  7073. </ul>
  7074. <p><a href="https://help.apple.com/developer-account/?lang=en#/dev77c875b7e">Apple's developer documentation</a>
  7075. has more information on setting up SiWA.</p>
  7076. <p>The synapse config will look like this:</p>
  7077. <pre><code class="language-yaml"> - idp_id: apple
  7078. idp_name: Apple
  7079. issuer: &quot;https://appleid.apple.com&quot;
  7080. client_id: &quot;your-client-id&quot; # Set to the &quot;identifier&quot; for your &quot;ServicesID&quot;
  7081. client_auth_method: &quot;client_secret_post&quot;
  7082. client_secret_jwt_key:
  7083. key_file: &quot;/path/to/AuthKey_KEYIDCODE.p8&quot; # point to your key file
  7084. jwt_header:
  7085. alg: ES256
  7086. kid: &quot;KEYIDCODE&quot; # Set to the 10-char Key ID
  7087. jwt_payload:
  7088. iss: TEAMIDCODE # Set to the 10-char Team ID
  7089. scopes: [&quot;name&quot;, &quot;email&quot;, &quot;openid&quot;]
  7090. authorization_endpoint: https://appleid.apple.com/auth/authorize?response_mode=form_post
  7091. user_mapping_provider:
  7092. config:
  7093. email_template: &quot;{{ user.email }}&quot;
  7094. </code></pre>
  7095. <h3 id="django-oauth-toolkit"><a class="header" href="#django-oauth-toolkit">Django OAuth Toolkit</a></h3>
  7096. <p><a href="https://github.com/jazzband/django-oauth-toolkit">django-oauth-toolkit</a> is a
  7097. Django application providing out of the box all the endpoints, data and logic
  7098. needed to add OAuth2 capabilities to your Django projects. It supports
  7099. <a href="https://django-oauth-toolkit.readthedocs.io/en/latest/oidc.html">OpenID Connect too</a>.</p>
  7100. <p>Configuration on Django's side:</p>
  7101. <ol>
  7102. <li>Add an application: <code>https://example.com/admin/oauth2_provider/application/add/</code> and choose parameters like this:</li>
  7103. </ol>
  7104. <ul>
  7105. <li><code>Redirect uris</code>: <code>https://synapse.example.com/_synapse/client/oidc/callback</code></li>
  7106. <li><code>Client type</code>: <code>Confidential</code></li>
  7107. <li><code>Authorization grant type</code>: <code>Authorization code</code></li>
  7108. <li><code>Algorithm</code>: <code>HMAC with SHA-2 256</code></li>
  7109. </ul>
  7110. <ol start="2">
  7111. <li>
  7112. <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>
  7113. <details>
  7114. <summary>Code sample</summary>
  7115. <pre><code class="language-python">class CustomOAuth2Validator(OAuth2Validator):
  7116. def get_additional_claims(self, request):
  7117. return {
  7118. &quot;sub&quot;: request.user.email,
  7119. &quot;email&quot;: request.user.email,
  7120. &quot;first_name&quot;: request.user.first_name,
  7121. &quot;last_name&quot;: request.user.last_name,
  7122. }
  7123. </code></pre>
  7124. </details>
  7125. </li>
  7126. </ol>
  7127. <p>Your synapse config is then:</p>
  7128. <pre><code class="language-yaml">oidc_providers:
  7129. - idp_id: django_example
  7130. idp_name: &quot;Django Example&quot;
  7131. issuer: &quot;https://example.com/o/&quot;
  7132. client_id: &quot;your-client-id&quot; # CHANGE ME
  7133. client_secret: &quot;your-client-secret&quot; # CHANGE ME
  7134. scopes: [&quot;openid&quot;]
  7135. user_profile_method: &quot;userinfo_endpoint&quot; # needed because oauth-toolkit does not include user information in the authorization response
  7136. user_mapping_provider:
  7137. config:
  7138. localpart_template: &quot;{{ user.email.split('@')[0] }}&quot;
  7139. display_name_template: &quot;{{ user.first_name }} {{ user.last_name }}&quot;
  7140. email_template: &quot;{{ user.email }}&quot;
  7141. </code></pre>
  7142. <div style="break-before: page; page-break-before: always;"></div><h1 id="saml"><a class="header" href="#saml">SAML</a></h1>
  7143. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language">Security Assertion
  7144. Markup Language</a>
  7145. (SAML) protocol natively.</p>
  7146. <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
  7147. file</a> for more details.</p>
  7148. <div style="break-before: page; page-break-before: always;"></div><h1 id="cas"><a class="header" href="#cas">CAS</a></h1>
  7149. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Central_Authentication_Service">Central Authentication
  7150. Service protocol</a>
  7151. (CAS) natively.</p>
  7152. <p>Please see the <code>cas_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
  7153. file</a> for more details.</p>
  7154. <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>
  7155. <p>A mapping provider is a Python class (loaded via a Python module) that
  7156. works out how to map attributes of a SSO response to Matrix-specific
  7157. user attributes. Details such as user ID localpart, displayname, and even avatar
  7158. URLs are all things that can be mapped from talking to a SSO service.</p>
  7159. <p>As an example, a SSO service may return the email address
  7160. &quot;john.smith@example.com&quot; for a user, whereas Synapse will need to figure out how
  7161. to turn that into a displayname when creating a Matrix user for this individual.
  7162. It may choose <code>John Smith</code>, or <code>Smith, John [Example.com]</code> or any number of
  7163. variations. As each Synapse configuration may want something different, this is
  7164. where SAML mapping providers come into play.</p>
  7165. <p>SSO mapping providers are currently supported for OpenID and SAML SSO
  7166. configurations. Please see the details below for how to implement your own.</p>
  7167. <p>It is up to the mapping provider whether the user should be assigned a predefined
  7168. Matrix ID based on the SSO attributes, or if the user should be allowed to
  7169. choose their own username.</p>
  7170. <p>In the first case - where users are automatically allocated a Matrix ID - it is
  7171. the responsibility of the mapping provider to normalise the SSO attributes and
  7172. map them to a valid Matrix ID. The <a href="https://matrix.org/docs/spec/appendices#user-identifiers">specification for Matrix
  7173. IDs</a> has some
  7174. information about what is considered valid.</p>
  7175. <p>If the mapping provider does not assign a Matrix ID, then Synapse will
  7176. automatically serve an HTML page allowing the user to pick their own username.</p>
  7177. <p>External mapping providers are provided to Synapse in the form of an external
  7178. Python module. You can retrieve this module from <a href="https://pypi.org">PyPI</a> or elsewhere,
  7179. but it must be importable via Synapse (e.g. it must be in the same virtualenv
  7180. as Synapse). The Synapse config is then modified to point to the mapping provider
  7181. (and optionally provide additional configuration for it).</p>
  7182. <h2 id="openid-mapping-providers"><a class="header" href="#openid-mapping-providers">OpenID Mapping Providers</a></h2>
  7183. <p>The OpenID mapping provider can be customized by editing the
  7184. <code>oidc_config.user_mapping_provider.module</code> config option.</p>
  7185. <p><code>oidc_config.user_mapping_provider.config</code> allows you to provide custom
  7186. configuration options to the module. Check with the module's documentation for
  7187. what options it provides (if any). The options listed by default are for the
  7188. user mapping provider built in to Synapse. If using a custom module, you should
  7189. comment these options out and use those specified by the module instead.</p>
  7190. <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>
  7191. <p>A custom mapping provider must specify the following methods:</p>
  7192. <ul>
  7193. <li><code>def __init__(self, parsed_config)</code>
  7194. <ul>
  7195. <li>Arguments:
  7196. <ul>
  7197. <li><code>parsed_config</code> - A configuration object that is the return value of the
  7198. <code>parse_config</code> method. You should set any configuration options needed by
  7199. the module here.</li>
  7200. </ul>
  7201. </li>
  7202. </ul>
  7203. </li>
  7204. <li><code>def parse_config(config)</code>
  7205. <ul>
  7206. <li>This method should have the <code>@staticmethod</code> decoration.</li>
  7207. <li>Arguments:
  7208. <ul>
  7209. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  7210. <code>oidc_config.user_mapping_provider.config</code> homeserver config option.
  7211. Runs on homeserver startup. Providers should extract and validate
  7212. any option values they need here.</li>
  7213. </ul>
  7214. </li>
  7215. <li>Whatever is returned will be passed back to the user mapping provider module's
  7216. <code>__init__</code> method during construction.</li>
  7217. </ul>
  7218. </li>
  7219. <li><code>def get_remote_user_id(self, userinfo)</code>
  7220. <ul>
  7221. <li>Arguments:
  7222. <ul>
  7223. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  7224. information from.</li>
  7225. </ul>
  7226. </li>
  7227. <li>This method must return a string, which is the unique, immutable identifier
  7228. for the user. Commonly the <code>sub</code> claim of the response.</li>
  7229. </ul>
  7230. </li>
  7231. <li><code>async def map_user_attributes(self, userinfo, token, failures)</code>
  7232. <ul>
  7233. <li>This method must be async.</li>
  7234. <li>Arguments:
  7235. <ul>
  7236. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  7237. information from.</li>
  7238. <li><code>token</code> - A dictionary which includes information necessary to make
  7239. further requests to the OpenID provider.</li>
  7240. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  7241. mxid localpart mapping has failed. This should be used
  7242. to create a deduplicated mxid localpart which should be
  7243. returned instead. For example, if this method returns
  7244. <code>john.doe</code> as the value of <code>localpart</code> in the returned
  7245. dict, and that is already taken on the homeserver, this
  7246. method will be called again with the same parameters but
  7247. with failures=1. The method should then return a different
  7248. <code>localpart</code> value, such as <code>john.doe1</code>.</li>
  7249. </ul>
  7250. </li>
  7251. <li>Returns a dictionary with two keys:
  7252. <ul>
  7253. <li><code>localpart</code>: A string, used to generate the Matrix ID. If this is
  7254. <code>None</code>, the user is prompted to pick their own username. This is only used
  7255. during a user's first login. Once a localpart has been associated with a
  7256. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  7257. <li><code>displayname</code>: An optional string, the display name for the user.</li>
  7258. </ul>
  7259. </li>
  7260. </ul>
  7261. </li>
  7262. <li><code>async def get_extra_attributes(self, userinfo, token)</code>
  7263. <ul>
  7264. <li>
  7265. <p>This method must be async.</p>
  7266. </li>
  7267. <li>
  7268. <p>Arguments:</p>
  7269. <ul>
  7270. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  7271. information from.</li>
  7272. <li><code>token</code> - A dictionary which includes information necessary to make
  7273. further requests to the OpenID provider.</li>
  7274. </ul>
  7275. </li>
  7276. <li>
  7277. <p>Returns a dictionary that is suitable to be serialized to JSON. This
  7278. will be returned as part of the response during a successful login.</p>
  7279. <p>Note that care should be taken to not overwrite any of the parameters
  7280. usually returned as part of the <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-login">login response</a>.</p>
  7281. </li>
  7282. </ul>
  7283. </li>
  7284. </ul>
  7285. <h3 id="default-openid-mapping-provider"><a class="header" href="#default-openid-mapping-provider">Default OpenID Mapping Provider</a></h3>
  7286. <p>Synapse has a built-in OpenID mapping provider if a custom provider isn't
  7287. specified in the config. It is located at
  7288. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/oidc.py"><code>synapse.handlers.oidc.JinjaOidcMappingProvider</code></a>.</p>
  7289. <h2 id="saml-mapping-providers"><a class="header" href="#saml-mapping-providers">SAML Mapping Providers</a></h2>
  7290. <p>The SAML mapping provider can be customized by editing the
  7291. <code>saml2_config.user_mapping_provider.module</code> config option.</p>
  7292. <p><code>saml2_config.user_mapping_provider.config</code> allows you to provide custom
  7293. configuration options to the module. Check with the module's documentation for
  7294. what options it provides (if any). The options listed by default are for the
  7295. user mapping provider built in to Synapse. If using a custom module, you should
  7296. comment these options out and use those specified by the module instead.</p>
  7297. <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>
  7298. <p>A custom mapping provider must specify the following methods:</p>
  7299. <ul>
  7300. <li><code>def __init__(self, parsed_config, module_api)</code>
  7301. <ul>
  7302. <li>Arguments:
  7303. <ul>
  7304. <li><code>parsed_config</code> - A configuration object that is the return value of the
  7305. <code>parse_config</code> method. You should set any configuration options needed by
  7306. the module here.</li>
  7307. <li><code>module_api</code> - a <code>synapse.module_api.ModuleApi</code> object which provides the
  7308. stable API available for extension modules.</li>
  7309. </ul>
  7310. </li>
  7311. </ul>
  7312. </li>
  7313. <li><code>def parse_config(config)</code>
  7314. <ul>
  7315. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  7316. <li>Arguments:
  7317. <ul>
  7318. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  7319. <code>saml_config.user_mapping_provider.config</code> homeserver config option.
  7320. Runs on homeserver startup. Providers should extract and validate
  7321. any option values they need here.</li>
  7322. </ul>
  7323. </li>
  7324. <li>Whatever is returned will be passed back to the user mapping provider module's
  7325. <code>__init__</code> method during construction.</li>
  7326. </ul>
  7327. </li>
  7328. <li><code>def get_saml_attributes(config)</code>
  7329. <ul>
  7330. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  7331. <li>Arguments:
  7332. <ul>
  7333. <li><code>config</code> - A object resulting from a call to <code>parse_config</code>.</li>
  7334. </ul>
  7335. </li>
  7336. <li>Returns a tuple of two sets. The first set equates to the SAML auth
  7337. response attributes that are required for the module to function, whereas
  7338. the second set consists of those attributes which can be used if available,
  7339. but are not necessary.</li>
  7340. </ul>
  7341. </li>
  7342. <li><code>def get_remote_user_id(self, saml_response, client_redirect_url)</code>
  7343. <ul>
  7344. <li>Arguments:
  7345. <ul>
  7346. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  7347. information from.</li>
  7348. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  7349. redirected to.</li>
  7350. </ul>
  7351. </li>
  7352. <li>This method must return a string, which is the unique, immutable identifier
  7353. for the user. Commonly the <code>uid</code> claim of the response.</li>
  7354. </ul>
  7355. </li>
  7356. <li><code>def saml_response_to_user_attributes(self, saml_response, failures, client_redirect_url)</code>
  7357. <ul>
  7358. <li>
  7359. <p>Arguments:</p>
  7360. <ul>
  7361. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  7362. information from.</li>
  7363. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  7364. mxid localpart mapping has failed. This should be used
  7365. to create a deduplicated mxid localpart which should be
  7366. returned instead. For example, if this method returns
  7367. <code>john.doe</code> as the value of <code>mxid_localpart</code> in the returned
  7368. dict, and that is already taken on the homeserver, this
  7369. method will be called again with the same parameters but
  7370. with failures=1. The method should then return a different
  7371. <code>mxid_localpart</code> value, such as <code>john.doe1</code>.</li>
  7372. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  7373. redirected to.</li>
  7374. </ul>
  7375. </li>
  7376. <li>
  7377. <p>This method must return a dictionary, which will then be used by Synapse
  7378. to build a new user. The following keys are allowed:</p>
  7379. <ul>
  7380. <li><code>mxid_localpart</code> - A string, the mxid localpart of the new user. If this is
  7381. <code>None</code>, the user is prompted to pick their own username. This is only used
  7382. during a user's first login. Once a localpart has been associated with a
  7383. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  7384. <li><code>displayname</code> - The displayname of the new user. If not provided, will default to
  7385. the value of <code>mxid_localpart</code>.</li>
  7386. <li><code>emails</code> - A list of emails for the new user. If not provided, will
  7387. default to an empty list.</li>
  7388. </ul>
  7389. <p>Alternatively it can raise a <code>synapse.api.errors.RedirectException</code> to
  7390. redirect the user to another page. This is useful to prompt the user for
  7391. additional information, e.g. if you want them to provide their own username.
  7392. It is the responsibility of the mapping provider to either redirect back
  7393. to <code>client_redirect_url</code> (including any additional information) or to
  7394. complete registration using methods from the <code>ModuleApi</code>.</p>
  7395. </li>
  7396. </ul>
  7397. </li>
  7398. </ul>
  7399. <h3 id="default-saml-mapping-provider"><a class="header" href="#default-saml-mapping-provider">Default SAML Mapping Provider</a></h3>
  7400. <p>Synapse has a built-in SAML mapping provider if a custom provider isn't
  7401. specified in the config. It is located at
  7402. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/saml.py"><code>synapse.handlers.saml.DefaultSamlMappingProvider</code></a>.</p>
  7403. <div style="break-before: page; page-break-before: always;"></div><h2 style="color:red">
  7404. This page of the Synapse documentation is now deprecated. For up to date
  7405. documentation on setting up or writing a password auth provider module, please see
  7406. <a href="modules/index.html">this page</a>.
  7407. </h2>
  7408. <h1 id="password-auth-provider-modules"><a class="header" href="#password-auth-provider-modules">Password auth provider modules</a></h1>
  7409. <p>Password auth providers offer a way for server administrators to
  7410. integrate their Synapse installation with an existing authentication
  7411. system.</p>
  7412. <p>A password auth provider is a Python class which is dynamically loaded
  7413. into Synapse, and provides a number of methods by which it can integrate
  7414. with the authentication system.</p>
  7415. <p>This document serves as a reference for those looking to implement their
  7416. own password auth providers. Additionally, here is a list of known
  7417. password auth provider module implementations:</p>
  7418. <ul>
  7419. <li><a href="https://github.com/matrix-org/matrix-synapse-ldap3/">matrix-synapse-ldap3</a></li>
  7420. <li><a href="https://github.com/devture/matrix-synapse-shared-secret-auth">matrix-synapse-shared-secret-auth</a></li>
  7421. <li><a href="https://github.com/ma1uta/matrix-synapse-rest-password-provider">matrix-synapse-rest-password-provider</a></li>
  7422. </ul>
  7423. <h2 id="required-methods"><a class="header" href="#required-methods">Required methods</a></h2>
  7424. <p>Password auth provider classes must provide the following methods:</p>
  7425. <ul>
  7426. <li>
  7427. <p><code>parse_config(config)</code>
  7428. This method is passed the <code>config</code> object for this module from the
  7429. homeserver configuration file.</p>
  7430. <p>It should perform any appropriate sanity checks on the provided
  7431. configuration, and return an object which is then passed into
  7432. <code>__init__</code>.</p>
  7433. <p>This method should have the <code>@staticmethod</code> decoration.</p>
  7434. </li>
  7435. <li>
  7436. <p><code>__init__(self, config, account_handler)</code></p>
  7437. <p>The constructor is passed the config object returned by
  7438. <code>parse_config</code>, and a <code>synapse.module_api.ModuleApi</code> object which
  7439. allows the password provider to check if accounts exist and/or create
  7440. new ones.</p>
  7441. </li>
  7442. </ul>
  7443. <h2 id="optional-methods"><a class="header" href="#optional-methods">Optional methods</a></h2>
  7444. <p>Password auth provider classes may optionally provide the following methods:</p>
  7445. <ul>
  7446. <li>
  7447. <p><code>get_db_schema_files(self)</code></p>
  7448. <p>This method, if implemented, should return an Iterable of
  7449. <code>(name, stream)</code> pairs of database schema files. Each file is applied
  7450. in turn at initialisation, and a record is then made in the database
  7451. so that it is not re-applied on the next start.</p>
  7452. </li>
  7453. <li>
  7454. <p><code>get_supported_login_types(self)</code></p>
  7455. <p>This method, if implemented, should return a <code>dict</code> mapping from a
  7456. login type identifier (such as <code>m.login.password</code>) to an iterable
  7457. giving the fields which must be provided by the user in the submission
  7458. to <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-login">the <code>/login</code> API</a>.
  7459. These fields are passed in the <code>login_dict</code> dictionary to <code>check_auth</code>.</p>
  7460. <p>For example, if a password auth provider wants to implement a custom
  7461. login type of <code>com.example.custom_login</code>, where the client is expected
  7462. to pass the fields <code>secret1</code> and <code>secret2</code>, the provider should
  7463. implement this method and return the following dict:</p>
  7464. <pre><code class="language-python">{&quot;com.example.custom_login&quot;: (&quot;secret1&quot;, &quot;secret2&quot;)}
  7465. </code></pre>
  7466. </li>
  7467. <li>
  7468. <p><code>check_auth(self, username, login_type, login_dict)</code></p>
  7469. <p>This method does the real work. If implemented, it
  7470. will be called for each login attempt where the login type matches one
  7471. of the keys returned by <code>get_supported_login_types</code>.</p>
  7472. <p>It is passed the (possibly unqualified) <code>user</code> field provided by the client,
  7473. the login type, and a dictionary of login secrets passed by the
  7474. client.</p>
  7475. <p>The method should return an <code>Awaitable</code> object, which resolves
  7476. to the canonical <code>@localpart:domain</code> user ID if authentication is
  7477. successful, and <code>None</code> if not.</p>
  7478. <p>Alternatively, the <code>Awaitable</code> can resolve to a <code>(str, func)</code> tuple, in
  7479. which case the second field is a callback which will be called with
  7480. the result from the <code>/login</code> call (including <code>access_token</code>,
  7481. <code>device_id</code>, etc.)</p>
  7482. </li>
  7483. <li>
  7484. <p><code>check_3pid_auth(self, medium, address, password)</code></p>
  7485. <p>This method, if implemented, is called when a user attempts to
  7486. register or log in with a third party identifier, such as email. It is
  7487. passed the medium (ex. &quot;email&quot;), an address (ex.
  7488. &quot;<a href="mailto:jdoe@example.com">jdoe@example.com</a>&quot;) and the user's password.</p>
  7489. <p>The method should return an <code>Awaitable</code> object, which resolves
  7490. to a <code>str</code> containing the user's (canonical) User id if
  7491. authentication was successful, and <code>None</code> if not.</p>
  7492. <p>As with <code>check_auth</code>, the <code>Awaitable</code> may alternatively resolve to a
  7493. <code>(user_id, callback)</code> tuple.</p>
  7494. </li>
  7495. <li>
  7496. <p><code>check_password(self, user_id, password)</code></p>
  7497. <p>This method provides a simpler interface than
  7498. <code>get_supported_login_types</code> and <code>check_auth</code> for password auth
  7499. providers that just want to provide a mechanism for validating
  7500. <code>m.login.password</code> logins.</p>
  7501. <p>If implemented, it will be called to check logins with an
  7502. <code>m.login.password</code> login type. It is passed a qualified
  7503. <code>@localpart:domain</code> user id, and the password provided by the user.</p>
  7504. <p>The method should return an <code>Awaitable</code> object, which resolves
  7505. to <code>True</code> if authentication is successful, and <code>False</code> if not.</p>
  7506. </li>
  7507. <li>
  7508. <p><code>on_logged_out(self, user_id, device_id, access_token)</code></p>
  7509. <p>This method, if implemented, is called when a user logs out. It is
  7510. passed the qualified user ID, the ID of the deactivated device (if
  7511. any: access tokens are occasionally created without an associated
  7512. device ID), and the (now deactivated) access token.</p>
  7513. <p>It may return an <code>Awaitable</code> object; the logout request will
  7514. wait for the <code>Awaitable</code> to complete, but the result is ignored.</p>
  7515. </li>
  7516. </ul>
  7517. <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>
  7518. <p>Synapse comes with a non-standard login type to support
  7519. <a href="https://en.wikipedia.org/wiki/JSON_Web_Token">JSON Web Tokens</a>. In general the
  7520. documentation for
  7521. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#login">the login endpoint</a>
  7522. is still valid (and the mechanism works similarly to the
  7523. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#token-based">token based login</a>).</p>
  7524. <p>To log in using a JSON Web Token, clients should submit a <code>/login</code> request as
  7525. follows:</p>
  7526. <pre><code class="language-json">{
  7527. &quot;type&quot;: &quot;org.matrix.login.jwt&quot;,
  7528. &quot;token&quot;: &quot;&lt;jwt&gt;&quot;
  7529. }
  7530. </code></pre>
  7531. <p>The <code>token</code> field should include the JSON web token with the following claims:</p>
  7532. <ul>
  7533. <li>A claim that encodes the local part of the user ID is required. By default,
  7534. the <code>sub</code> (subject) claim is used, or a custom claim can be set in the
  7535. configuration file.</li>
  7536. <li>The expiration time (<code>exp</code>), not before time (<code>nbf</code>), and issued at (<code>iat</code>)
  7537. claims are optional, but validated if present.</li>
  7538. <li>The issuer (<code>iss</code>) claim is optional, but required and validated if configured.</li>
  7539. <li>The audience (<code>aud</code>) claim is optional, but required and validated if configured.
  7540. Providing the audience claim when not configured will cause validation to fail.</li>
  7541. </ul>
  7542. <p>In the case that the token is not valid, the homeserver must respond with
  7543. <code>403 Forbidden</code> and an error code of <code>M_FORBIDDEN</code>.</p>
  7544. <p>As with other login types, there are additional fields (e.g. <code>device_id</code> and
  7545. <code>initial_device_display_name</code>) which can be included in the above request.</p>
  7546. <h2 id="preparing-synapse-1"><a class="header" href="#preparing-synapse-1">Preparing Synapse</a></h2>
  7547. <p>The JSON Web Token integration in Synapse uses the
  7548. <a href="https://docs.authlib.org/en/latest/index.html"><code>Authlib</code></a> library, which must be installed
  7549. as follows:</p>
  7550. <ul>
  7551. <li>
  7552. <p>The relevant libraries are included in the Docker images and Debian packages
  7553. provided by <code>matrix.org</code> so no further action is needed.</p>
  7554. </li>
  7555. <li>
  7556. <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>
  7557. </li>
  7558. <li>
  7559. <p>For other installation mechanisms, see the documentation provided by the
  7560. maintainer.</p>
  7561. </li>
  7562. </ul>
  7563. <p>To enable the JSON web token integration, you should then add a <code>jwt_config</code> section
  7564. to your configuration file (or uncomment the <code>enabled: true</code> line in the
  7565. existing section). See <a href="./sample_config.yaml">sample_config.yaml</a> for some
  7566. sample settings.</p>
  7567. <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>
  7568. <p>Although JSON Web Tokens are typically generated from an external server, the
  7569. example below uses a locally generated JWT.</p>
  7570. <ol>
  7571. <li>
  7572. <p>Configure Synapse with JWT logins, note that this example uses a pre-shared
  7573. secret and an algorithm of HS256:</p>
  7574. <pre><code class="language-yaml">jwt_config:
  7575. enabled: true
  7576. secret: &quot;my-secret-token&quot;
  7577. algorithm: &quot;HS256&quot;
  7578. </code></pre>
  7579. </li>
  7580. <li>
  7581. <p>Generate a JSON web token:</p>
  7582. <p>You can use the following short Python snippet to generate a JWT
  7583. protected by an HMAC.
  7584. Take care that the <code>secret</code> and the algorithm given in the <code>header</code> match
  7585. the entries from <code>jwt_config</code> above.</p>
  7586. <pre><code class="language-python">from authlib.jose import jwt
  7587. header = {&quot;alg&quot;: &quot;HS256&quot;}
  7588. payload = {&quot;sub&quot;: &quot;user1&quot;, &quot;aud&quot;: [&quot;audience&quot;]}
  7589. secret = &quot;my-secret-token&quot;
  7590. result = jwt.encode(header, payload, secret)
  7591. print(result.decode(&quot;ascii&quot;))
  7592. </code></pre>
  7593. </li>
  7594. <li>
  7595. <p>Query for the login types and ensure <code>org.matrix.login.jwt</code> is there:</p>
  7596. <pre><code class="language-bash">curl http://localhost:8080/_matrix/client/r0/login
  7597. </code></pre>
  7598. </li>
  7599. <li>
  7600. <p>Login used the generated JSON web token from above:</p>
  7601. <pre><code class="language-bash">$ curl http://localhost:8082/_matrix/client/r0/login -X POST \
  7602. --data '{&quot;type&quot;:&quot;org.matrix.login.jwt&quot;,&quot;token&quot;:&quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.Ag71GT8v01UO3w80aqRPTeuVPBIBZkYhNTJJ-_-zQIc&quot;}'
  7603. {
  7604. &quot;access_token&quot;: &quot;&lt;access token&gt;&quot;,
  7605. &quot;device_id&quot;: &quot;ACBDEFGHI&quot;,
  7606. &quot;home_server&quot;: &quot;localhost:8080&quot;,
  7607. &quot;user_id&quot;: &quot;@test-user:localhost:8480&quot;
  7608. }
  7609. </code></pre>
  7610. </li>
  7611. </ol>
  7612. <p>You should now be able to use the returned access token to query the client API.</p>
  7613. <div style="break-before: page; page-break-before: always;"></div><h1 id="refresh-tokens"><a class="header" href="#refresh-tokens">Refresh Tokens</a></h1>
  7614. <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>
  7615. <h2 id="background-and-motivation"><a class="header" href="#background-and-motivation">Background and motivation</a></h2>
  7616. <p>Synapse users' sessions are identified by <strong>access tokens</strong>; access tokens are
  7617. issued to users on login. Each session gets a unique access token which identifies
  7618. it; the access token must be kept secret as it grants access to the user's account.</p>
  7619. <p>Traditionally, these access tokens were eternally valid (at least until the user
  7620. explicitly chose to log out).</p>
  7621. <p>In some cases, it may be desirable for these access tokens to expire so that the
  7622. potential damage caused by leaking an access token is reduced.
  7623. On the other hand, forcing a user to re-authenticate (log in again) often might
  7624. be too much of an inconvenience.</p>
  7625. <p><strong>Refresh tokens</strong> are a mechanism to avoid some of this inconvenience whilst
  7626. still getting most of the benefits of short access token lifetimes.
  7627. Refresh tokens are also a concept present in OAuth 2 — further reading is available
  7628. <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.5">here</a>.</p>
  7629. <p>When refresh tokens are in use, both an access token and a refresh token will be
  7630. issued to users on login. The access token will expire after a predetermined amount
  7631. of time, but otherwise works in the same way as before. When the access token is
  7632. close to expiring (or has expired), the user's client should present the homeserver
  7633. (Synapse) with the refresh token.</p>
  7634. <p>The homeserver will then generate a new access token and refresh token for the user
  7635. and return them. The old refresh token is invalidated and can not be used again*.</p>
  7636. <p>Finally, refresh tokens also make it possible for sessions to be logged out if they
  7637. are inactive for too long, before the session naturally ends; see the configuration
  7638. guide below.</p>
  7639. <p>*To prevent issues if clients lose connection half-way through refreshing a token,
  7640. the refresh token is only invalidated once the new access token has been used at
  7641. least once. For all intents and purposes, the above simplification is sufficient.</p>
  7642. <h2 id="caveats"><a class="header" href="#caveats">Caveats</a></h2>
  7643. <p>There are some caveats:</p>
  7644. <ul>
  7645. <li>If a third party gets both your access token and refresh token, they will be able to
  7646. continue to enjoy access to your session.
  7647. <ul>
  7648. <li>This is still an improvement because you (the user) will notice when <em>your</em>
  7649. session expires and you're not able to use your refresh token.
  7650. That would be a giveaway that someone else has compromised your session.
  7651. You would be able to log in again and terminate that session.
  7652. Previously (with long-lived access tokens), a third party that has your access
  7653. token could go undetected for a very long time.</li>
  7654. </ul>
  7655. </li>
  7656. <li>Clients need to implement support for refresh tokens in order for them to be a
  7657. useful mechanism.
  7658. <ul>
  7659. <li>It is up to homeserver administrators if they want to issue long-lived access
  7660. tokens to clients not implementing refresh tokens.
  7661. <ul>
  7662. <li>For compatibility, it is likely that they should, at least until client support
  7663. is widespread.
  7664. <ul>
  7665. <li>Users with clients that support refresh tokens will still benefit from the
  7666. added security; it's not possible to downgrade a session to using long-lived
  7667. access tokens so this effectively gives users the choice.</li>
  7668. </ul>
  7669. </li>
  7670. <li>In a closed environment where all users use known clients, this may not be
  7671. an issue as the homeserver administrator can know if the clients have refresh
  7672. token support. In that case, the non-refreshable access token lifetime
  7673. may be set to a short duration so that a similar level of security is provided.</li>
  7674. </ul>
  7675. </li>
  7676. </ul>
  7677. </li>
  7678. </ul>
  7679. <h2 id="configuration-guide"><a class="header" href="#configuration-guide">Configuration Guide</a></h2>
  7680. <p>The following configuration options, in the <code>registration</code> section, are related:</p>
  7681. <ul>
  7682. <li><code>session_lifetime</code>: maximum length of a session, even if it's refreshed.
  7683. In other words, the client must log in again after this time period.
  7684. In most cases, this can be unset (infinite) or set to a long time (years or months).</li>
  7685. <li><code>refreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  7686. by clients supporting refresh tokens.
  7687. This should be short; a good value might be 5 minutes (<code>5m</code>).</li>
  7688. <li><code>nonrefreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  7689. by clients which don't support refresh tokens.
  7690. Make this short if you want to effectively force use of refresh tokens.
  7691. Make this long if you don't want to inconvenience users of clients which don't
  7692. support refresh tokens (by forcing them to frequently re-authenticate using
  7693. login credentials).</li>
  7694. <li><code>refresh_token_lifetime</code>: lifetime of refresh tokens.
  7695. In other words, the client must refresh within this time period to maintain its session.
  7696. Unless you want to log inactive sessions out, it is often fine to use a long
  7697. value here or even leave it unset (infinite).
  7698. Beware that making it too short will inconvenience clients that do not connect
  7699. very often, including mobile clients and clients of infrequent users (by making
  7700. it more difficult for them to refresh in time, which may force them to need to
  7701. re-authenticate using login credentials).</li>
  7702. </ul>
  7703. <p><strong>Note:</strong> All four options above only apply when tokens are created (by logging in or refreshing).
  7704. Changes to these settings do not apply retroactively.</p>
  7705. <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>
  7706. <p>If you'd like to force sessions to be logged out upon inactivity, you can enable
  7707. refreshable access token expiry and refresh token expiry.</p>
  7708. <p>This works because a client must refresh at least once within a period of
  7709. <code>refresh_token_lifetime</code> in order to maintain valid credentials to access the
  7710. account.</p>
  7711. <p>(It's suggested that <code>refresh_token_lifetime</code> should be longer than
  7712. <code>refreshable_access_token_lifetime</code> and this section assumes that to be the case
  7713. for simplicity.)</p>
  7714. <p>Note: this will only affect sessions using refresh tokens. You may wish to
  7715. set a short <code>nonrefreshable_access_token_lifetime</code> to prevent this being bypassed
  7716. by clients that do not support refresh tokens.</p>
  7717. <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>
  7718. <p>It may be desirable to permit some short periods of inactivity, for example to
  7719. accommodate brief outages in client connectivity.</p>
  7720. <p>The following model aims to provide guidance for choosing <code>refresh_token_lifetime</code>
  7721. and <code>refreshable_access_token_lifetime</code> to satisfy requirements of the form:</p>
  7722. <ol>
  7723. <li>inactivity longer than <code>L</code> <strong>MUST</strong> cause the session to be logged out; and</li>
  7724. <li>inactivity shorter than <code>S</code> <strong>MUST NOT</strong> cause the session to be logged out.</li>
  7725. </ol>
  7726. <p>This model makes the weakest assumption that all active clients will refresh as
  7727. needed to maintain an active access token, but no sooner.
  7728. <em>In reality, clients may refresh more often than this model assumes, but the
  7729. above requirements will still hold.</em></p>
  7730. <p>To satisfy the above model,</p>
  7731. <ul>
  7732. <li><code>refresh_token_lifetime</code> should be set to <code>L</code>; and</li>
  7733. <li><code>refreshable_access_token_lifetime</code> should be set to <code>L - S</code>.</li>
  7734. </ul>
  7735. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-2"><a class="header" href="#overview-2">Overview</a></h1>
  7736. <p>A captcha can be enabled on your homeserver to help prevent bots from registering
  7737. accounts. Synapse currently uses Google's reCAPTCHA service which requires API keys
  7738. from Google.</p>
  7739. <h2 id="getting-api-keys"><a class="header" href="#getting-api-keys">Getting API keys</a></h2>
  7740. <ol>
  7741. <li>Create a new site at <a href="https://www.google.com/recaptcha/admin/create">https://www.google.com/recaptcha/admin/create</a></li>
  7742. <li>Set the label to anything you want</li>
  7743. <li>Set the type to reCAPTCHA v2 using the &quot;I'm not a robot&quot; Checkbox option.
  7744. This is the only type of captcha that works with Synapse.</li>
  7745. <li>Add the public hostname for your server, as set in <code>public_baseurl</code>
  7746. in <code>homeserver.yaml</code>, to the list of authorized domains. If you have not set
  7747. <code>public_baseurl</code>, use <code>server_name</code>.</li>
  7748. <li>Agree to the terms of service and submit.</li>
  7749. <li>Copy your site key and secret key and add them to your <code>homeserver.yaml</code>
  7750. configuration file
  7751. <pre><code class="language-yaml">recaptcha_public_key: YOUR_SITE_KEY
  7752. recaptcha_private_key: YOUR_SECRET_KEY
  7753. </code></pre>
  7754. </li>
  7755. <li>Enable the CAPTCHA for new registrations
  7756. <pre><code class="language-yaml">enable_registration_captcha: true
  7757. </code></pre>
  7758. </li>
  7759. <li>Go to the settings page for the CAPTCHA you just created</li>
  7760. <li>Uncheck the &quot;Verify the origin of reCAPTCHA solutions&quot; checkbox so that the
  7761. captcha can be displayed in any client. If you do not disable this option then you
  7762. must specify the domains of every client that is allowed to display the CAPTCHA.</li>
  7763. </ol>
  7764. <h2 id="configuring-ip-used-for-auth"><a class="header" href="#configuring-ip-used-for-auth">Configuring IP used for auth</a></h2>
  7765. <p>The reCAPTCHA API requires that the IP address of the user who solved the
  7766. CAPTCHA is sent. If the client is connecting through a proxy or load balancer,
  7767. it may be required to use the <code>X-Forwarded-For</code> (XFF) header instead of the origin
  7768. IP address. This can be configured using the <code>x_forwarded</code> directive in the
  7769. listeners section of the <code>homeserver.yaml</code> configuration file.</p>
  7770. <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>
  7771. <p>The registration of new application services depends on the homeserver used.
  7772. In synapse, you need to create a new configuration file for your AS and add it
  7773. to the list specified under the <code>app_service_config_files</code> config
  7774. option in your synapse config.</p>
  7775. <p>For example:</p>
  7776. <pre><code class="language-yaml">app_service_config_files:
  7777. - /home/matrix/.synapse/&lt;your-AS&gt;.yaml
  7778. </code></pre>
  7779. <p>The format of the AS configuration file is as follows:</p>
  7780. <pre><code class="language-yaml">url: &lt;base url of AS&gt;
  7781. as_token: &lt;token AS will add to requests to HS&gt;
  7782. hs_token: &lt;token HS will add to requests to AS&gt;
  7783. sender_localpart: &lt;localpart of AS user&gt;
  7784. namespaces:
  7785. users: # List of users we're interested in
  7786. - exclusive: &lt;bool&gt;
  7787. regex: &lt;regex&gt;
  7788. group_id: &lt;group&gt;
  7789. - ...
  7790. aliases: [] # List of aliases we're interested in
  7791. rooms: [] # List of room ids we're interested in
  7792. </code></pre>
  7793. <p><code>exclusive</code>: If enabled, only this application service is allowed to register users in its namespace(s).
  7794. <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>
  7795. <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>
  7796. <div style="break-before: page; page-break-before: always;"></div><h1 id="server-notices"><a class="header" href="#server-notices">Server Notices</a></h1>
  7797. <p>'Server Notices' are a new feature introduced in Synapse 0.30. They provide a
  7798. channel whereby server administrators can send messages to users on the server.</p>
  7799. <p>They are used as part of communication of the server polices (see
  7800. <a href="consent_tracking.html">Consent Tracking</a>), however the intention is that
  7801. they may also find a use for features such as &quot;Message of the day&quot;.</p>
  7802. <p>This is a feature specific to Synapse, but it uses standard Matrix
  7803. communication mechanisms, so should work with any Matrix client.</p>
  7804. <h2 id="user-experience"><a class="header" href="#user-experience">User experience</a></h2>
  7805. <p>When the user is first sent a server notice, they will get an invitation to a
  7806. room (typically called 'Server Notices', though this is configurable in
  7807. <code>homeserver.yaml</code>). They will be <strong>unable to reject</strong> this invitation -
  7808. attempts to do so will receive an error.</p>
  7809. <p>Once they accept the invitation, they will see the notice message in the room
  7810. history; it will appear to have come from the 'server notices user' (see
  7811. below).</p>
  7812. <p>The user is prevented from sending any messages in this room by the power
  7813. levels.</p>
  7814. <p>Having joined the room, the user can leave the room if they want. Subsequent
  7815. server notices will then cause a new room to be created.</p>
  7816. <h2 id="synapse-configuration"><a class="header" href="#synapse-configuration">Synapse configuration</a></h2>
  7817. <p>Server notices come from a specific user id on the server. Server
  7818. administrators are free to choose the user id - something like <code>server</code> is
  7819. suggested, meaning the notices will come from
  7820. <code>@server:&lt;your_server_name&gt;</code>. Once the Server Notices user is configured, that
  7821. user id becomes a special, privileged user, so administrators should ensure
  7822. that <strong>it is not already allocated</strong>.</p>
  7823. <p>In order to support server notices, it is necessary to add some configuration
  7824. to the <code>homeserver.yaml</code> file. In particular, you should add a <code>server_notices</code>
  7825. section, which should look like this:</p>
  7826. <pre><code class="language-yaml">server_notices:
  7827. system_mxid_localpart: server
  7828. system_mxid_display_name: &quot;Server Notices&quot;
  7829. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  7830. room_name: &quot;Server Notices&quot;
  7831. </code></pre>
  7832. <p>The only compulsory setting is <code>system_mxid_localpart</code>, which defines the user
  7833. id of the Server Notices user, as above. <code>room_name</code> defines the name of the
  7834. room which will be created.</p>
  7835. <p><code>system_mxid_display_name</code> and <code>system_mxid_avatar_url</code> can be used to set the
  7836. displayname and avatar of the Server Notices user.</p>
  7837. <h2 id="sending-notices"><a class="header" href="#sending-notices">Sending notices</a></h2>
  7838. <p>To send server notices to users you can use the
  7839. <a href="admin_api/server_notices.html">admin_api</a>.</p>
  7840. <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>
  7841. <p>Synapse 0.30 introduces support for tracking whether users have agreed to the
  7842. terms and conditions set by the administrator of a server - and blocking access
  7843. to the server until they have.</p>
  7844. <p>There are several parts to this functionality; each requires some specific
  7845. configuration in <code>homeserver.yaml</code> to be enabled.</p>
  7846. <p>Note that various parts of the configuation and this document refer to the
  7847. &quot;privacy policy&quot;: agreement with a privacy policy is one particular use of this
  7848. feature, but of course adminstrators can specify other terms and conditions
  7849. unrelated to &quot;privacy&quot; per se.</p>
  7850. <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>
  7851. <p>Synapse can be configured to serve the user a simple policy form with an
  7852. &quot;accept&quot; button. Clicking &quot;Accept&quot; records the user's acceptance in the
  7853. database and shows a success page.</p>
  7854. <p>To enable this, first create templates for the policy and success pages.
  7855. These should be stored on the local filesystem.</p>
  7856. <p>These templates use the <a href="http://jinja.pocoo.org">Jinja2</a> templating language,
  7857. and <a href="https://github.com/matrix-org/synapse/tree/develop/docs/privacy_policy_templates/">docs/privacy_policy_templates</a>
  7858. gives examples of the sort of thing that can be done.</p>
  7859. <p>Note that the templates must be stored under a name giving the language of the
  7860. template - currently this must always be <code>en</code> (for &quot;English&quot;);
  7861. internationalisation support is intended for the future.</p>
  7862. <p>The template for the policy itself should be versioned and named according to
  7863. the version: for example <code>1.0.html</code>. The version of the policy which the user
  7864. has agreed to is stored in the database.</p>
  7865. <p>Once the templates are in place, make the following changes to <code>homeserver.yaml</code>:</p>
  7866. <ol>
  7867. <li>
  7868. <p>Add a <code>user_consent</code> section, which should look like:</p>
  7869. <pre><code class="language-yaml">user_consent:
  7870. template_dir: privacy_policy_templates
  7871. version: 1.0
  7872. </code></pre>
  7873. <p><code>template_dir</code> points to the directory containing the policy
  7874. templates. <code>version</code> defines the version of the policy which will be served
  7875. to the user. In the example above, Synapse will serve
  7876. <code>privacy_policy_templates/en/1.0.html</code>.</p>
  7877. </li>
  7878. <li>
  7879. <p>Add a <code>form_secret</code> setting at the top level:</p>
  7880. <pre><code class="language-yaml">form_secret: &quot;&lt;unique secret&gt;&quot;
  7881. </code></pre>
  7882. <p>This should be set to an arbitrary secret string (try <code>pwgen -y 30</code> to
  7883. generate suitable secrets).</p>
  7884. <p>More on what this is used for below.</p>
  7885. </li>
  7886. <li>
  7887. <p>Add <code>consent</code> wherever the <code>client</code> resource is currently enabled in the
  7888. <code>listeners</code> configuration. For example:</p>
  7889. <pre><code class="language-yaml">listeners:
  7890. - port: 8008
  7891. resources:
  7892. - names:
  7893. - client
  7894. - consent
  7895. </code></pre>
  7896. </li>
  7897. </ol>
  7898. <p>Finally, ensure that <code>jinja2</code> is installed. If you are using a virtualenv, this
  7899. should be a matter of <code>pip install Jinja2</code>. On debian, try <code>apt-get install python-jinja2</code>.</p>
  7900. <p>Once this is complete, and the server has been restarted, try visiting
  7901. <code>https://&lt;server&gt;/_matrix/consent</code>. If correctly configured, this should give
  7902. an error &quot;Missing string query parameter 'u'&quot;. It is now possible to manually
  7903. construct URIs where users can give their consent.</p>
  7904. <h3 id="enabling-consent-tracking-at-registration"><a class="header" href="#enabling-consent-tracking-at-registration">Enabling consent tracking at registration</a></h3>
  7905. <ol>
  7906. <li>
  7907. <p>Add the following to your configuration:</p>
  7908. <pre><code class="language-yaml">user_consent:
  7909. require_at_registration: true
  7910. policy_name: &quot;Privacy Policy&quot; # or whatever you'd like to call the policy
  7911. </code></pre>
  7912. </li>
  7913. <li>
  7914. <p>In your consent templates, make use of the <code>public_version</code> variable to
  7915. see if an unauthenticated user is viewing the page. This is typically
  7916. wrapped around the form that would be used to actually agree to the document:</p>
  7917. <pre><code class="language-html">{% if not public_version %}
  7918. &lt;!-- The variables used here are only provided when the 'u' param is given to the homeserver --&gt;
  7919. &lt;form method=&quot;post&quot; action=&quot;consent&quot;&gt;
  7920. &lt;input type=&quot;hidden&quot; name=&quot;v&quot; value=&quot;{{version}}&quot;/&gt;
  7921. &lt;input type=&quot;hidden&quot; name=&quot;u&quot; value=&quot;{{user}}&quot;/&gt;
  7922. &lt;input type=&quot;hidden&quot; name=&quot;h&quot; value=&quot;{{userhmac}}&quot;/&gt;
  7923. &lt;input type=&quot;submit&quot; value=&quot;Sure thing!&quot;/&gt;
  7924. &lt;/form&gt;
  7925. {% endif %}
  7926. </code></pre>
  7927. </li>
  7928. <li>
  7929. <p>Restart Synapse to apply the changes.</p>
  7930. </li>
  7931. </ol>
  7932. <p>Visiting <code>https://&lt;server&gt;/_matrix/consent</code> should now give you a view of the privacy
  7933. document. This is what users will be able to see when registering for accounts.</p>
  7934. <h3 id="constructing-the-consent-uri"><a class="header" href="#constructing-the-consent-uri">Constructing the consent URI</a></h3>
  7935. <p>It may be useful to manually construct the &quot;consent URI&quot; for a given user - for
  7936. instance, in order to send them an email asking them to consent. To do this,
  7937. take the base <code>https://&lt;server&gt;/_matrix/consent</code> URL and add the following
  7938. query parameters:</p>
  7939. <ul>
  7940. <li>
  7941. <p><code>u</code>: the user id of the user. This can either be a full MXID
  7942. (<code>@user:server.com</code>) or just the localpart (<code>user</code>).</p>
  7943. </li>
  7944. <li>
  7945. <p><code>h</code>: hex-encoded HMAC-SHA256 of <code>u</code> using the <code>form_secret</code> as a key. It is
  7946. possible to calculate this on the commandline with something like:</p>
  7947. <pre><code class="language-bash">echo -n '&lt;user&gt;' | openssl sha256 -hmac '&lt;form_secret&gt;'
  7948. </code></pre>
  7949. <p>This should result in a URI which looks something like:
  7950. <code>https://&lt;server&gt;/_matrix/consent?u=&lt;user&gt;&amp;h=68a152465a4d...</code>.</p>
  7951. </li>
  7952. </ul>
  7953. <p>Note that not providing a <code>u</code> parameter will be interpreted as wanting to view
  7954. the document from an unauthenticated perspective, such as prior to registration.
  7955. Therefore, the <code>h</code> parameter is not required in this scenario. To enable this
  7956. behaviour, set <code>require_at_registration</code> to <code>true</code> in your <code>user_consent</code> config.</p>
  7957. <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>
  7958. <p>It is possible to configure Synapse to send a <a href="server_notices.html">server
  7959. notice</a> to anybody who has not yet agreed to the current
  7960. version of the policy. To do so:</p>
  7961. <ul>
  7962. <li>
  7963. <p>ensure that the consent resource is configured, as in the previous section</p>
  7964. </li>
  7965. <li>
  7966. <p>ensure that server notices are configured, as in <a href="server_notices.html">the server notice documentation</a>.</p>
  7967. </li>
  7968. <li>
  7969. <p>Add <code>server_notice_content</code> under <code>user_consent</code> in <code>homeserver.yaml</code>. For
  7970. example:</p>
  7971. <pre><code class="language-yaml">user_consent:
  7972. server_notice_content:
  7973. msgtype: m.text
  7974. body: &gt;-
  7975. Please give your consent to the privacy policy at %(consent_uri)s.
  7976. </code></pre>
  7977. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  7978. consent uri for that user.</p>
  7979. </li>
  7980. <li>
  7981. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  7982. URI that clients use to connect to the server. (It is used to construct
  7983. <code>consent_uri</code> in the server notice.)</p>
  7984. </li>
  7985. </ul>
  7986. <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>
  7987. <p>Synapse can be configured to block any attempts to join rooms or send messages
  7988. until the user has given their agreement to the policy. (Joining the server
  7989. notices room is exempted from this).</p>
  7990. <p>To enable this, add <code>block_events_error</code> under <code>user_consent</code>. For example:</p>
  7991. <pre><code class="language-yaml">user_consent:
  7992. block_events_error: &gt;-
  7993. You can't send any messages until you consent to the privacy policy at
  7994. %(consent_uri)s.
  7995. </code></pre>
  7996. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  7997. consent uri for that user.</p>
  7998. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  7999. URI that clients use to connect to the server. (It is used to construct
  8000. <code>consent_uri</code> in the error.)</p>
  8001. <div style="break-before: page; page-break-before: always;"></div><h1 id="url-previews-1"><a class="header" href="#url-previews-1">URL Previews</a></h1>
  8002. <p>The <code>GET /_matrix/media/r0/preview_url</code> endpoint provides a generic preview API
  8003. for URLs which outputs <a href="https://ogp.me/">Open Graph</a> responses (with some Matrix
  8004. specific additions).</p>
  8005. <p>This does have trade-offs compared to other designs:</p>
  8006. <ul>
  8007. <li>Pros:
  8008. <ul>
  8009. <li>Simple and flexible; can be used by any clients at any point</li>
  8010. </ul>
  8011. </li>
  8012. <li>Cons:
  8013. <ul>
  8014. <li>If each homeserver provides one of these independently, all the HSes in a
  8015. room may needlessly DoS the target URI</li>
  8016. <li>The URL metadata must be stored somewhere, rather than just using Matrix
  8017. itself to store the media.</li>
  8018. <li>Matrix cannot be used to distribute the metadata between homeservers.</li>
  8019. </ul>
  8020. </li>
  8021. </ul>
  8022. <p>When Synapse is asked to preview a URL it does the following:</p>
  8023. <ol>
  8024. <li>Checks against a URL blacklist (defined as <code>url_preview_url_blacklist</code> in the
  8025. config).</li>
  8026. <li>Checks the in-memory cache by URLs and returns the result if it exists. (This
  8027. is also used to de-duplicate processing of multiple in-flight requests at once.)</li>
  8028. <li>Kicks off a background process to generate a preview:
  8029. <ol>
  8030. <li>Checks the database cache by URL and timestamp and returns the result if it
  8031. has not expired and was successful (a 2xx return code).</li>
  8032. <li>Checks if the URL matches an <a href="https://oembed.com/">oEmbed</a> pattern. If it
  8033. does, update the URL to download.</li>
  8034. <li>Downloads the URL and stores it into a file via the media storage provider
  8035. and saves the local media metadata.</li>
  8036. <li>If the media is an image:
  8037. <ol>
  8038. <li>Generates thumbnails.</li>
  8039. <li>Generates an Open Graph response based on image properties.</li>
  8040. </ol>
  8041. </li>
  8042. <li>If the media is HTML:
  8043. <ol>
  8044. <li>Decodes the HTML via the stored file.</li>
  8045. <li>Generates an Open Graph response from the HTML.</li>
  8046. <li>If a JSON oEmbed URL was found in the HTML via autodiscovery:
  8047. <ol>
  8048. <li>Downloads the URL and stores it into a file via the media storage provider
  8049. and saves the local media metadata.</li>
  8050. <li>Convert the oEmbed response to an Open Graph response.</li>
  8051. <li>Override any Open Graph data from the HTML with data from oEmbed.</li>
  8052. </ol>
  8053. </li>
  8054. <li>If an image exists in the Open Graph response:
  8055. <ol>
  8056. <li>Downloads the URL and stores it into a file via the media storage
  8057. provider and saves the local media metadata.</li>
  8058. <li>Generates thumbnails.</li>
  8059. <li>Updates the Open Graph response based on image properties.</li>
  8060. </ol>
  8061. </li>
  8062. </ol>
  8063. </li>
  8064. <li>If the media is JSON and an oEmbed URL was found:
  8065. <ol>
  8066. <li>Convert the oEmbed response to an Open Graph response.</li>
  8067. <li>If a thumbnail or image is in the oEmbed response:
  8068. <ol>
  8069. <li>Downloads the URL and stores it into a file via the media storage
  8070. provider and saves the local media metadata.</li>
  8071. <li>Generates thumbnails.</li>
  8072. <li>Updates the Open Graph response based on image properties.</li>
  8073. </ol>
  8074. </li>
  8075. </ol>
  8076. </li>
  8077. <li>Stores the result in the database cache.</li>
  8078. </ol>
  8079. </li>
  8080. <li>Returns the result.</li>
  8081. </ol>
  8082. <p>The in-memory cache expires after 1 hour.</p>
  8083. <p>Expired entries in the database cache (and their associated media files) are
  8084. deleted every 10 seconds. The default expiration time is 1 hour from download.</p>
  8085. <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>
  8086. <p>The user directory is currently maintained based on the 'visible' users
  8087. on this particular server - i.e. ones which your account shares a room with, or
  8088. who are present in a publicly viewable room present on the server.</p>
  8089. <p>The directory info is stored in various tables, which can (typically after
  8090. DB corruption) get stale or out of sync. If this happens, for now the
  8091. solution to fix it is to use the <a href="usage/administration/admin_api/background_updates.html#run">admin API</a>
  8092. and execute the job <code>regenerate_directory</code>. This should then start a background task to
  8093. flush the current tables and regenerate the directory.</p>
  8094. <h2 id="data-model"><a class="header" href="#data-model">Data model</a></h2>
  8095. <p>There are five relevant tables that collectively form the &quot;user directory&quot;.
  8096. Three of them track a master list of all the users we could search for.
  8097. The last two (collectively called the &quot;search tables&quot;) track who can
  8098. see who.</p>
  8099. <p>From all of these tables we exclude three types of local user:</p>
  8100. <ul>
  8101. <li>support users</li>
  8102. <li>appservice users</li>
  8103. <li>deactivated users</li>
  8104. </ul>
  8105. <ul>
  8106. <li>
  8107. <p><code>user_directory</code>. This contains the user_id, display name and avatar we'll
  8108. return when you search the directory.</p>
  8109. <ul>
  8110. <li>Because there's only one directory entry per user, it's important that we only
  8111. ever put publicly visible names here. Otherwise we might leak a private
  8112. nickname or avatar used in a private room.</li>
  8113. <li>Indexed on rooms. Indexed on users.</li>
  8114. </ul>
  8115. </li>
  8116. <li>
  8117. <p><code>user_directory_search</code>. To be joined to <code>user_directory</code>. It contains an extra
  8118. column that enables full text search based on user ids and display names.
  8119. Different schemas for SQLite and Postgres with different code paths to match.</p>
  8120. <ul>
  8121. <li>Indexed on the full text search data. Indexed on users.</li>
  8122. </ul>
  8123. </li>
  8124. <li>
  8125. <p><code>user_directory_stream_pos</code>. When the initial background update to populate
  8126. the directory is complete, we record a stream position here. This indicates
  8127. that synapse should now listen for room changes and incrementally update
  8128. the directory where necessary.</p>
  8129. </li>
  8130. <li>
  8131. <p><code>users_in_public_rooms</code>. Contains associations between users and the public rooms they're in.
  8132. Used to determine which users are in public rooms and should be publicly visible in the directory.</p>
  8133. </li>
  8134. <li>
  8135. <p><code>users_who_share_private_rooms</code>. Rows are triples <code>(L, M, room id)</code> where <code>L</code>
  8136. is a local user and <code>M</code> is a local or remote user. <code>L</code> and <code>M</code> should be
  8137. different, but this isn't enforced by a constraint.</p>
  8138. </li>
  8139. </ul>
  8140. <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>
  8141. <p>Synapse admins can enable support for message retention policies on
  8142. their homeserver. Message retention policies exist at a room level,
  8143. follow the semantics described in
  8144. <a href="https://github.com/matrix-org/matrix-doc/blob/matthew/msc1763/proposals/1763-configurable-retention-periods.md">MSC1763</a>,
  8145. and allow server and room admins to configure how long messages should
  8146. be kept in a homeserver's database before being purged from it.
  8147. <strong>Please note that, as this feature isn't part of the Matrix
  8148. specification yet, this implementation is to be considered as
  8149. experimental.</strong> </p>
  8150. <p>A message retention policy is mainly defined by its <code>max_lifetime</code>
  8151. parameter, which defines how long a message can be kept around after
  8152. it was sent to the room. If a room doesn't have a message retention
  8153. policy, and there's no default one for a given server, then no message
  8154. sent in that room is ever purged on that server.</p>
  8155. <p>MSC1763 also specifies semantics for a <code>min_lifetime</code> parameter which
  8156. defines the amount of time after which an event <em>can</em> get purged (after
  8157. it was sent to the room), but Synapse doesn't currently support it
  8158. beyond registering it.</p>
  8159. <p>Both <code>max_lifetime</code> and <code>min_lifetime</code> are optional parameters.</p>
  8160. <p>Note that message retention policies don't apply to state events.</p>
  8161. <p>Once an event reaches its expiry date (defined as the time it was sent
  8162. plus the value for <code>max_lifetime</code> in the room), two things happen:</p>
  8163. <ul>
  8164. <li>Synapse stops serving the event to clients via any endpoint.</li>
  8165. <li>The message gets picked up by the next purge job (see the &quot;Purge jobs&quot;
  8166. section) and is removed from Synapse's database.</li>
  8167. </ul>
  8168. <p>Since purge jobs don't run continuously, this means that an event might
  8169. stay in a server's database for longer than the value for <code>max_lifetime</code>
  8170. in the room would allow, though hidden from clients.</p>
  8171. <p>Similarly, if a server (with support for message retention policies
  8172. enabled) receives from another server an event that should have been
  8173. purged according to its room's policy, then the receiving server will
  8174. process and store that event until it's picked up by the next purge job,
  8175. though it will always hide it from clients.</p>
  8176. <p>Synapse requires at least one message in each room, so it will never
  8177. delete the last message in a room. It will, however, hide it from
  8178. clients.</p>
  8179. <h2 id="server-configuration"><a class="header" href="#server-configuration">Server configuration</a></h2>
  8180. <p>Support for this feature can be enabled and configured in the
  8181. <code>retention</code> section of the Synapse configuration file (see the
  8182. <a href="https://github.com/matrix-org/synapse/blob/v1.36.0/docs/sample_config.yaml#L451-L518">sample file</a>).</p>
  8183. <p>To enable support for message retention policies, set the setting
  8184. <code>enabled</code> in this section to <code>true</code>.</p>
  8185. <h3 id="default-policy"><a class="header" href="#default-policy">Default policy</a></h3>
  8186. <p>A default message retention policy is a policy defined in Synapse's
  8187. configuration that is used by Synapse for every room that doesn't have a
  8188. message retention policy configured in its state. This allows server
  8189. admins to ensure that messages are never kept indefinitely in a server's
  8190. database. </p>
  8191. <p>A default policy can be defined as such, in the <code>retention</code> section of
  8192. the configuration file:</p>
  8193. <pre><code class="language-yaml">default_policy:
  8194. min_lifetime: 1d
  8195. max_lifetime: 1y
  8196. </code></pre>
  8197. <p>Here, <code>min_lifetime</code> and <code>max_lifetime</code> have the same meaning and level
  8198. of support as previously described. They can be expressed either as a
  8199. duration (using the units <code>s</code> (seconds), <code>m</code> (minutes), <code>h</code> (hours),
  8200. <code>d</code> (days), <code>w</code> (weeks) and <code>y</code> (years)) or as a number of milliseconds.</p>
  8201. <h3 id="purge-jobs"><a class="header" href="#purge-jobs">Purge jobs</a></h3>
  8202. <p>Purge jobs are the jobs that Synapse runs in the background to purge
  8203. expired events from the database. They are only run if support for
  8204. message retention policies is enabled in the server's configuration. If
  8205. no configuration for purge jobs is configured by the server admin,
  8206. Synapse will use a default configuration, which is described in the
  8207. <a href="https://github.com/matrix-org/synapse/blob/v1.36.0/docs/sample_config.yaml#L451-L518">sample configuration file</a>.</p>
  8208. <p>Some server admins might want a finer control on when events are removed
  8209. depending on an event's room's policy. This can be done by setting the
  8210. <code>purge_jobs</code> sub-section in the <code>retention</code> section of the configuration
  8211. file. An example of such configuration could be:</p>
  8212. <pre><code class="language-yaml">purge_jobs:
  8213. - longest_max_lifetime: 3d
  8214. interval: 12h
  8215. - shortest_max_lifetime: 3d
  8216. longest_max_lifetime: 1w
  8217. interval: 1d
  8218. - shortest_max_lifetime: 1w
  8219. interval: 2d
  8220. </code></pre>
  8221. <p>In this example, we define three jobs:</p>
  8222. <ul>
  8223. <li>one that runs twice a day (every 12 hours) and purges events in rooms
  8224. which policy's <code>max_lifetime</code> is lower or equal to 3 days.</li>
  8225. <li>one that runs once a day and purges events in rooms which policy's
  8226. <code>max_lifetime</code> is between 3 days and a week.</li>
  8227. <li>one that runs once every 2 days and purges events in rooms which
  8228. policy's <code>max_lifetime</code> is greater than a week.</li>
  8229. </ul>
  8230. <p>Note that this example is tailored to show different configurations and
  8231. features slightly more jobs than it's probably necessary (in practice, a
  8232. server admin would probably consider it better to replace the two last
  8233. jobs with one that runs once a day and handles rooms which
  8234. policy's <code>max_lifetime</code> is greater than 3 days).</p>
  8235. <p>Keep in mind, when configuring these jobs, that a purge job can become
  8236. quite heavy on the server if it targets many rooms, therefore prefer
  8237. having jobs with a low interval that target a limited set of rooms. Also
  8238. make sure to include a job with no minimum and one with no maximum to
  8239. make sure your configuration handles every policy.</p>
  8240. <p>As previously mentioned in this documentation, while a purge job that
  8241. runs e.g. every day means that an expired event might stay in the
  8242. database for up to a day after its expiry, Synapse hides expired events
  8243. from clients as soon as they expire, so the event is not visible to
  8244. local users between its expiry date and the moment it gets purged from
  8245. the server's database.</p>
  8246. <h3 id="lifetime-limits"><a class="header" href="#lifetime-limits">Lifetime limits</a></h3>
  8247. <p>Server admins can set limits on the values of <code>max_lifetime</code> to use when
  8248. purging old events in a room. These limits can be defined as such in the
  8249. <code>retention</code> section of the configuration file:</p>
  8250. <pre><code class="language-yaml">allowed_lifetime_min: 1d
  8251. allowed_lifetime_max: 1y
  8252. </code></pre>
  8253. <p>The limits are considered when running purge jobs. If necessary, the
  8254. effective value of <code>max_lifetime</code> will be brought between
  8255. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> (inclusive).
  8256. This means that, if the value of <code>max_lifetime</code> defined in the room's state
  8257. is lower than <code>allowed_lifetime_min</code>, the value of <code>allowed_lifetime_min</code>
  8258. will be used instead. Likewise, if the value of <code>max_lifetime</code> is higher
  8259. than <code>allowed_lifetime_max</code>, the value of <code>allowed_lifetime_max</code> will be
  8260. used instead.</p>
  8261. <p>In the example above, we ensure Synapse never deletes events that are less
  8262. than one day old, and that it always deletes events that are over a year
  8263. old.</p>
  8264. <p>If a default policy is set, and its <code>max_lifetime</code> value is lower than
  8265. <code>allowed_lifetime_min</code> or higher than <code>allowed_lifetime_max</code>, the same
  8266. process applies.</p>
  8267. <p>Both parameters are optional; if one is omitted Synapse won't use it to
  8268. adjust the effective value of <code>max_lifetime</code>.</p>
  8269. <p>Like other settings in this section, these parameters can be expressed
  8270. either as a duration or as a number of milliseconds.</p>
  8271. <h2 id="room-configuration"><a class="header" href="#room-configuration">Room configuration</a></h2>
  8272. <p>To configure a room's message retention policy, a room's admin or
  8273. moderator needs to send a state event in that room with the type
  8274. <code>m.room.retention</code> and the following content:</p>
  8275. <pre><code class="language-json">{
  8276. &quot;max_lifetime&quot;: ...
  8277. }
  8278. </code></pre>
  8279. <p>In this event's content, the <code>max_lifetime</code> parameter has the same
  8280. meaning as previously described, and needs to be expressed in
  8281. milliseconds. The event's content can also include a <code>min_lifetime</code>
  8282. parameter, which has the same meaning and limited support as previously
  8283. described.</p>
  8284. <p>Note that over every server in the room, only the ones with support for
  8285. message retention policies will actually remove expired events. This
  8286. support is currently not enabled by default in Synapse.</p>
  8287. <h2 id="note-on-reclaiming-disk-space"><a class="header" href="#note-on-reclaiming-disk-space">Note on reclaiming disk space</a></h2>
  8288. <p>While purge jobs actually delete data from the database, the disk space
  8289. used by the database might not decrease immediately on the database's
  8290. host. However, even though the database engine won't free up the disk
  8291. space, it will start writing new data into where the purged data was.</p>
  8292. <p>If you want to reclaim the freed disk space anyway and return it to the
  8293. operating system, the server admin needs to run <code>VACUUM FULL;</code> (or
  8294. <code>VACUUM;</code> for SQLite databases) on Synapse's database (see the related
  8295. <a href="https://www.postgresql.org/docs/current/sql-vacuum.html">PostgreSQL documentation</a>).</p>
  8296. <div style="break-before: page; page-break-before: always;"></div><h1 id="modules-2"><a class="header" href="#modules-2">Modules</a></h1>
  8297. <p>Synapse supports extending its functionality by configuring external modules.</p>
  8298. <p><strong>Note</strong>: When using third-party modules, you effectively allow someone else to run
  8299. custom code on your Synapse homeserver. Server admins are encouraged to verify the
  8300. provenance of the modules they use on their homeserver and make sure the modules aren't
  8301. running malicious code on their instance.</p>
  8302. <h2 id="using-modules"><a class="header" href="#using-modules">Using modules</a></h2>
  8303. <p>To use a module on Synapse, add it to the <code>modules</code> section of the configuration file:</p>
  8304. <pre><code class="language-yaml">modules:
  8305. - module: my_super_module.MySuperClass
  8306. config:
  8307. do_thing: true
  8308. - module: my_other_super_module.SomeClass
  8309. config: {}
  8310. </code></pre>
  8311. <p>Each module is defined by a path to a Python class as well as a configuration. This
  8312. information for a given module should be available in the module's own documentation.</p>
  8313. <h2 id="using-multiple-modules"><a class="header" href="#using-multiple-modules">Using multiple modules</a></h2>
  8314. <p>The order in which modules are listed in this section is important. When processing an
  8315. action that can be handled by several modules, Synapse will always prioritise the module
  8316. that appears first (i.e. is the highest in the list). This means:</p>
  8317. <ul>
  8318. <li>If several modules register the same callback, the callback registered by the module
  8319. that appears first is used.</li>
  8320. <li>If several modules try to register a handler for the same HTTP path, only the handler
  8321. registered by the module that appears first is used. Handlers registered by the other
  8322. module(s) are ignored and Synapse will log a warning message about them.</li>
  8323. </ul>
  8324. <p>Note that Synapse doesn't allow multiple modules implementing authentication checkers via
  8325. the password auth provider feature for the same login type with different fields. If this
  8326. happens, Synapse will refuse to start.</p>
  8327. <h2 id="current-status"><a class="header" href="#current-status">Current status</a></h2>
  8328. <p>We are currently in the process of migrating module interfaces to this system. While some
  8329. interfaces might be compatible with it, others still require configuring modules in
  8330. another part of Synapse's configuration file.</p>
  8331. <p>Currently, only the following pre-existing interfaces are compatible with this new system:</p>
  8332. <ul>
  8333. <li>spam checker</li>
  8334. <li>third-party rules</li>
  8335. <li>presence router</li>
  8336. <li>password auth providers</li>
  8337. </ul>
  8338. <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>
  8339. <p>A module is a Python class that uses Synapse's module API to interact with the
  8340. homeserver. It can register callbacks that Synapse will call on specific operations, as
  8341. well as web resources to attach to Synapse's web server.</p>
  8342. <p>When instantiated, a module is given its parsed configuration as well as an instance of
  8343. the <code>synapse.module_api.ModuleApi</code> class. The configuration is a dictionary, and is
  8344. either the output of the module's <code>parse_config</code> static method (see below), or the
  8345. configuration associated with the module in Synapse's configuration file.</p>
  8346. <p>See the documentation for the <code>ModuleApi</code> class
  8347. <a href="https://github.com/matrix-org/synapse/blob/master/synapse/module_api/__init__.py">here</a>.</p>
  8348. <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>
  8349. <p>If Synapse is running with other modules configured, the order each module appears in
  8350. within the <code>modules</code> section of the Synapse configuration file might restrict what it can
  8351. or cannot register. See <a href="modules/index.html#using-multiple-modules">this section</a> for more
  8352. information.</p>
  8353. <p>On top of the rules listed in the link above, if a callback returns a value that should
  8354. cause the current operation to fail (e.g. if a callback checking an event returns with a
  8355. value that should cause the event to be denied), Synapse will fail the operation and
  8356. ignore any subsequent callbacks that should have been run after this one.</p>
  8357. <p>The documentation for each callback mentions how Synapse behaves when
  8358. multiple modules implement it.</p>
  8359. <h2 id="handling-the-modules-configuration"><a class="header" href="#handling-the-modules-configuration">Handling the module's configuration</a></h2>
  8360. <p>A module can implement the following static method:</p>
  8361. <pre><code class="language-python">@staticmethod
  8362. def parse_config(config: dict) -&gt; Any
  8363. </code></pre>
  8364. <p>This method is given a dictionary resulting from parsing the YAML configuration for the
  8365. module. It may modify it (for example by parsing durations expressed as strings (e.g.
  8366. &quot;5d&quot;) into milliseconds, etc.), and return the modified dictionary. It may also verify
  8367. that the configuration is correct, and raise an instance of
  8368. <code>synapse.module_api.errors.ConfigError</code> if not.</p>
  8369. <h2 id="registering-a-web-resource"><a class="header" href="#registering-a-web-resource">Registering a web resource</a></h2>
  8370. <p>Modules can register web resources onto Synapse's web server using the following module
  8371. API method:</p>
  8372. <pre><code class="language-python">def ModuleApi.register_web_resource(path: str, resource: IResource) -&gt; None
  8373. </code></pre>
  8374. <p>The path is the full absolute path to register the resource at. For example, if you
  8375. register a resource for the path <code>/_synapse/client/my_super_module/say_hello</code>, Synapse
  8376. will serve it at <code>http(s)://[HS_URL]/_synapse/client/my_super_module/say_hello</code>. Note
  8377. that Synapse does not allow registering resources for several sub-paths in the <code>/_matrix</code>
  8378. namespace (such as anything under <code>/_matrix/client</code> for example). It is strongly
  8379. recommended that modules register their web resources under the <code>/_synapse/client</code>
  8380. namespace.</p>
  8381. <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>
  8382. interface (such as <a href="https://twistedmatrix.com/documents/current/api/twisted.web.resource.Resource.html">Resource</a>).</p>
  8383. <p>Only one resource can be registered for a given path. If several modules attempt to
  8384. register a resource for the same path, the module that appears first in Synapse's
  8385. configuration file takes priority.</p>
  8386. <p>Modules <strong>must</strong> register their web resources in their <code>__init__</code> method.</p>
  8387. <h2 id="registering-a-callback"><a class="header" href="#registering-a-callback">Registering a callback</a></h2>
  8388. <p>Modules can use Synapse's module API to register callbacks. Callbacks are functions that
  8389. Synapse will call when performing specific actions. Callbacks must be asynchronous (unless
  8390. specified otherwise), and are split in categories. A single module may implement callbacks
  8391. from multiple categories, and is under no obligation to implement all callbacks from the
  8392. categories it registers callbacks for.</p>
  8393. <p>Modules can register callbacks using one of the module API's <code>register_[...]_callbacks</code>
  8394. methods. The callback functions are passed to these methods as keyword arguments, with
  8395. the callback name as the argument name and the function as its value. A
  8396. <code>register_[...]_callbacks</code> method exists for each category.</p>
  8397. <p>Callbacks for each category can be found on their respective page of the
  8398. <a href="https://matrix-org.github.io/synapse">Synapse documentation website</a>.</p>
  8399. <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>
  8400. <p>Spam checker callbacks allow module developers to implement spam mitigation actions for
  8401. Synapse instances. Spam checker callbacks can be registered using the module API's
  8402. <code>register_spam_checker_callbacks</code> method.</p>
  8403. <h2 id="callbacks"><a class="header" href="#callbacks">Callbacks</a></h2>
  8404. <p>The available spam checker callbacks are:</p>
  8405. <h3 id="check_event_for_spam"><a class="header" href="#check_event_for_spam"><code>check_event_for_spam</code></a></h3>
  8406. <p><em>First introduced in Synapse v1.37.0</em></p>
  8407. <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>
  8408. <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]
  8409. </code></pre>
  8410. <p>Called when receiving an event from a client or via federation. The callback must return one of:</p>
  8411. <ul>
  8412. <li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8413. decide to reject it.</li>
  8414. <li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8415. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
  8416. <li>(deprecated) a non-<code>Codes</code> <code>str</code> to reject the operation and specify an error message. Note that clients
  8417. typically will not localize the error message to the user's preferred locale.</li>
  8418. <li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
  8419. <li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
  8420. </ul>
  8421. <p>If multiple modules implement this callback, they will be considered in order. If a
  8422. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8423. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8424. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8425. this callback.</p>
  8426. <h3 id="user_may_join_room"><a class="header" href="#user_may_join_room"><code>user_may_join_room</code></a></h3>
  8427. <p><em>First introduced in Synapse v1.37.0</em></p>
  8428. <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>
  8429. <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]
  8430. </code></pre>
  8431. <p>Called when a user is trying to join a room. The user is represented by their Matrix user ID (e.g.
  8432. <code>@alice:example.com</code>) and the room is represented by its Matrix ID (e.g.
  8433. <code>!room:example.com</code>). The module is also given a boolean to indicate whether the user
  8434. currently has a pending invite in the room.</p>
  8435. <p>This callback isn't called if the join is performed by a server administrator, or in the
  8436. context of a room creation.</p>
  8437. <p>The callback must return one of:</p>
  8438. <ul>
  8439. <li><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8440. decide to reject it.</li>
  8441. <li><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8442. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</li>
  8443. <li>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</li>
  8444. <li>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</li>
  8445. </ul>
  8446. <p>If multiple modules implement this callback, they will be considered in order. If a
  8447. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8448. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8449. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8450. this callback.</p>
  8451. <h3 id="user_may_invite"><a class="header" href="#user_may_invite"><code>user_may_invite</code></a></h3>
  8452. <p><em>First introduced in Synapse v1.37.0</em></p>
  8453. <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>
  8454. <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]
  8455. </code></pre>
  8456. <p>Called when processing an invitation. Both inviter and invitee are
  8457. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  8458. <p>The callback must return one of:</p>
  8459. <ul>
  8460. <li>
  8461. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8462. decide to reject it.</p>
  8463. </li>
  8464. <li>
  8465. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8466. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8467. </li>
  8468. <li>
  8469. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8470. </li>
  8471. <li>
  8472. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8473. </li>
  8474. </ul>
  8475. <p>If multiple modules implement this callback, they will be considered in order. If a
  8476. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8477. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8478. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8479. this callback.</p>
  8480. <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>
  8481. <p><em>First introduced in Synapse v1.45.0</em></p>
  8482. <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>
  8483. <pre><code class="language-python">async def user_may_send_3pid_invite(
  8484. inviter: str,
  8485. medium: str,
  8486. address: str,
  8487. room_id: str,
  8488. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
  8489. </code></pre>
  8490. <p>Called when processing an invitation using a third-party identifier (also called a 3PID,
  8491. e.g. an email address or a phone number). </p>
  8492. <p>The inviter is represented by their Matrix user ID (e.g. <code>@alice:example.com</code>), and the
  8493. invitee is represented by its medium (e.g. &quot;email&quot;) and its address
  8494. (e.g. <code>alice@example.com</code>). See <a href="https://matrix.org/docs/spec/appendices#pid-types">the Matrix specification</a>
  8495. for more information regarding third-party identifiers.</p>
  8496. <p>For example, a call to this callback to send an invitation to the email address
  8497. <code>alice@example.com</code> would look like this:</p>
  8498. <pre><code class="language-python">await user_may_send_3pid_invite(
  8499. &quot;@bob:example.com&quot;, # The inviter's user ID
  8500. &quot;email&quot;, # The medium of the 3PID to invite
  8501. &quot;alice@example.com&quot;, # The address of the 3PID to invite
  8502. &quot;!some_room:example.com&quot;, # The ID of the room to send the invite into
  8503. )
  8504. </code></pre>
  8505. <p><strong>Note</strong>: If the third-party identifier is already associated with a matrix user ID,
  8506. <a href="modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a> will be used instead.</p>
  8507. <p>The callback must return one of:</p>
  8508. <ul>
  8509. <li>
  8510. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8511. decide to reject it.</p>
  8512. </li>
  8513. <li>
  8514. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8515. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8516. </li>
  8517. <li>
  8518. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8519. </li>
  8520. <li>
  8521. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8522. </li>
  8523. </ul>
  8524. <p>If multiple modules implement this callback, they will be considered in order. If a
  8525. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8526. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8527. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8528. this callback.</p>
  8529. <h3 id="user_may_create_room"><a class="header" href="#user_may_create_room"><code>user_may_create_room</code></a></h3>
  8530. <p><em>First introduced in Synapse v1.37.0</em></p>
  8531. <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>
  8532. <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]
  8533. </code></pre>
  8534. <p>Called when processing a room creation request.</p>
  8535. <p>The callback must return one of:</p>
  8536. <ul>
  8537. <li>
  8538. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8539. decide to reject it.</p>
  8540. </li>
  8541. <li>
  8542. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8543. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8544. </li>
  8545. <li>
  8546. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8547. </li>
  8548. <li>
  8549. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8550. </li>
  8551. </ul>
  8552. <p>If multiple modules implement this callback, they will be considered in order. If a
  8553. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8554. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8555. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8556. this callback.</p>
  8557. <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>
  8558. <p><em>First introduced in Synapse v1.37.0</em></p>
  8559. <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>
  8560. <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]
  8561. </code></pre>
  8562. <p>Called when trying to associate an alias with an existing room.</p>
  8563. <p>The callback must return one of:</p>
  8564. <ul>
  8565. <li>
  8566. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8567. decide to reject it.</p>
  8568. </li>
  8569. <li>
  8570. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8571. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8572. </li>
  8573. <li>
  8574. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8575. </li>
  8576. <li>
  8577. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8578. </li>
  8579. </ul>
  8580. <p>If multiple modules implement this callback, they will be considered in order. If a
  8581. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8582. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8583. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8584. this callback.</p>
  8585. <h3 id="user_may_publish_room"><a class="header" href="#user_may_publish_room"><code>user_may_publish_room</code></a></h3>
  8586. <p><em>First introduced in Synapse v1.37.0</em></p>
  8587. <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>
  8588. <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]
  8589. </code></pre>
  8590. <p>Called when trying to publish a room to the homeserver's public rooms directory.</p>
  8591. <p>The callback must return one of:</p>
  8592. <ul>
  8593. <li>
  8594. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8595. decide to reject it.</p>
  8596. </li>
  8597. <li>
  8598. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8599. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8600. </li>
  8601. <li>
  8602. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8603. </li>
  8604. <li>
  8605. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8606. </li>
  8607. </ul>
  8608. <p>If multiple modules implement this callback, they will be considered in order. If a
  8609. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8610. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8611. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8612. this callback.</p>
  8613. <h3 id="check_username_for_spam"><a class="header" href="#check_username_for_spam"><code>check_username_for_spam</code></a></h3>
  8614. <p><em>First introduced in Synapse v1.37.0</em></p>
  8615. <pre><code class="language-python">async def check_username_for_spam(user_profile: synapse.module_api.UserProfile) -&gt; bool
  8616. </code></pre>
  8617. <p>Called when computing search results in the user directory. The module must return a
  8618. <code>bool</code> indicating whether the given user should be excluded from user directory
  8619. searches. Return <code>True</code> to indicate that the user is spammy and exclude them from
  8620. search results; otherwise return <code>False</code>.</p>
  8621. <p>The profile is represented as a dictionary with the following keys:</p>
  8622. <ul>
  8623. <li><code>user_id: str</code>. The Matrix ID for this user.</li>
  8624. <li><code>display_name: Optional[str]</code>. The user's display name, or <code>None</code> if this user
  8625. has not set a display name.</li>
  8626. <li><code>avatar_url: Optional[str]</code>. The <code>mxc://</code> URL to the user's avatar, or <code>None</code>
  8627. if this user has not set an avatar.</li>
  8628. </ul>
  8629. <p>The module is given a copy of the original dictionary, so modifying it from within the
  8630. module cannot modify a user's profile when included in user directory search results.</p>
  8631. <p>If multiple modules implement this callback, they will be considered in order. If a
  8632. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  8633. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  8634. any of the subsequent implementations of this callback.</p>
  8635. <h3 id="check_registration_for_spam"><a class="header" href="#check_registration_for_spam"><code>check_registration_for_spam</code></a></h3>
  8636. <p><em>First introduced in Synapse v1.37.0</em></p>
  8637. <pre><code class="language-python">async def check_registration_for_spam(
  8638. email_threepid: Optional[dict],
  8639. username: Optional[str],
  8640. request_info: Collection[Tuple[str, str]],
  8641. auth_provider_id: Optional[str] = None,
  8642. ) -&gt; &quot;synapse.spam_checker_api.RegistrationBehaviour&quot;
  8643. </code></pre>
  8644. <p>Called when registering a new user. The module must return a <code>RegistrationBehaviour</code>
  8645. indicating whether the registration can go through or must be denied, or whether the user
  8646. may be allowed to register but will be shadow banned.</p>
  8647. <p>The arguments passed to this callback are:</p>
  8648. <ul>
  8649. <li><code>email_threepid</code>: The email address used for registering, if any.</li>
  8650. <li><code>username</code>: The username the user would like to register. Can be <code>None</code>, meaning that
  8651. Synapse will generate one later.</li>
  8652. <li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
  8653. second item is an IP address. These user agents and IP addresses are the ones that were
  8654. used during the registration process.</li>
  8655. <li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
  8656. </ul>
  8657. <p>If multiple modules implement this callback, they will be considered in order. If a
  8658. callback returns <code>RegistrationBehaviour.ALLOW</code>, Synapse falls through to the next one.
  8659. The value of the first callback that does not return <code>RegistrationBehaviour.ALLOW</code> will
  8660. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8661. this callback.</p>
  8662. <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>
  8663. <p><em>First introduced in Synapse v1.37.0</em></p>
  8664. <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>
  8665. <pre><code class="language-python">async def check_media_file_for_spam(
  8666. file_wrapper: &quot;synapse.rest.media.v1.media_storage.ReadableFileWrapper&quot;,
  8667. file_info: &quot;synapse.rest.media.v1._base.FileInfo&quot;,
  8668. ) -&gt; Union[&quot;synapse.module_api.NOT_SPAM&quot;, &quot;synapse.module_api.errors.Codes&quot;, bool]
  8669. </code></pre>
  8670. <p>Called when storing a local or remote file.</p>
  8671. <p>The callback must return one of:</p>
  8672. <ul>
  8673. <li>
  8674. <p><code>synapse.module_api.NOT_SPAM</code>, to allow the operation. Other callbacks may still
  8675. decide to reject it.</p>
  8676. </li>
  8677. <li>
  8678. <p><code>synapse.module_api.errors.Codes</code> to reject the operation with an error code. In case
  8679. of doubt, <code>synapse.module_api.errors.Codes.FORBIDDEN</code> is a good error code.</p>
  8680. </li>
  8681. <li>
  8682. <p>(deprecated) <code>False</code>, which is the same as returning <code>synapse.module_api.NOT_SPAM</code>.</p>
  8683. </li>
  8684. <li>
  8685. <p>(deprecated) <code>True</code>, which is the same as returning <code>synapse.module_api.errors.Codes.FORBIDDEN</code>.</p>
  8686. </li>
  8687. </ul>
  8688. <p>If multiple modules implement this callback, they will be considered in order. If a
  8689. callback returns <code>synapse.module_api.NOT_SPAM</code>, Synapse falls through to the next one.
  8690. The value of the first callback that does not return <code>synapse.module_api.NOT_SPAM</code> will
  8691. be used. If this happens, Synapse will not call any of the subsequent implementations of
  8692. this callback.</p>
  8693. <h3 id="should_drop_federated_event"><a class="header" href="#should_drop_federated_event"><code>should_drop_federated_event</code></a></h3>
  8694. <p><em>First introduced in Synapse v1.60.0</em></p>
  8695. <pre><code class="language-python">async def should_drop_federated_event(event: &quot;synapse.events.EventBase&quot;) -&gt; bool
  8696. </code></pre>
  8697. <p>Called when checking whether a remote server can federate an event with us. <strong>Returning
  8698. <code>True</code> from this function will silently drop a federated event and split-brain our view
  8699. of a room's DAG, and thus you shouldn't use this callback unless you know what you are
  8700. doing.</strong></p>
  8701. <p>If multiple modules implement this callback, they will be considered in order. If a
  8702. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  8703. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  8704. any of the subsequent implementations of this callback.</p>
  8705. <h2 id="example"><a class="header" href="#example">Example</a></h2>
  8706. <p>The example below is a module that implements the spam checker callback
  8707. <code>check_event_for_spam</code> to deny any message sent by users whose Matrix user IDs are
  8708. mentioned in a configured list, and registers a web resource to the path
  8709. <code>/_synapse/client/list_spam_checker/is_evil</code> that returns a JSON object indicating
  8710. whether the provided user appears in that list.</p>
  8711. <pre><code class="language-python">import json
  8712. from typing import Union
  8713. from twisted.web.resource import Resource
  8714. from twisted.web.server import Request
  8715. from synapse.module_api import ModuleApi
  8716. class IsUserEvilResource(Resource):
  8717. def __init__(self, config):
  8718. super(IsUserEvilResource, self).__init__()
  8719. self.evil_users = config.get(&quot;evil_users&quot;) or []
  8720. def render_GET(self, request: Request):
  8721. user = request.args.get(b&quot;user&quot;)[0].decode()
  8722. request.setHeader(b&quot;Content-Type&quot;, b&quot;application/json&quot;)
  8723. return json.dumps({&quot;evil&quot;: user in self.evil_users}).encode()
  8724. class ListSpamChecker:
  8725. def __init__(self, config: dict, api: ModuleApi):
  8726. self.api = api
  8727. self.evil_users = config.get(&quot;evil_users&quot;) or []
  8728. self.api.register_spam_checker_callbacks(
  8729. check_event_for_spam=self.check_event_for_spam,
  8730. )
  8731. self.api.register_web_resource(
  8732. path=&quot;/_synapse/client/list_spam_checker/is_evil&quot;,
  8733. resource=IsUserEvilResource(config),
  8734. )
  8735. async def check_event_for_spam(self, event: &quot;synapse.events.EventBase&quot;) -&gt; Union[Literal[&quot;NOT_SPAM&quot;], Codes]:
  8736. if event.sender in self.evil_users:
  8737. return Codes.FORBIDDEN
  8738. else:
  8739. return synapse.module_api.NOT_SPAM
  8740. </code></pre>
  8741. <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>
  8742. <p>Third party rules callbacks allow module developers to add extra checks to verify the
  8743. validity of incoming events. Third party event rules callbacks can be registered using
  8744. the module API's <code>register_third_party_rules_callbacks</code> method.</p>
  8745. <h2 id="callbacks-1"><a class="header" href="#callbacks-1">Callbacks</a></h2>
  8746. <p>The available third party rules callbacks are:</p>
  8747. <h3 id="check_event_allowed"><a class="header" href="#check_event_allowed"><code>check_event_allowed</code></a></h3>
  8748. <p><em>First introduced in Synapse v1.39.0</em></p>
  8749. <pre><code class="language-python">async def check_event_allowed(
  8750. event: &quot;synapse.events.EventBase&quot;,
  8751. state_events: &quot;synapse.types.StateMap&quot;,
  8752. ) -&gt; Tuple[bool, Optional[dict]]
  8753. </code></pre>
  8754. <p><strong><span style="color:red">
  8755. This callback is very experimental and can and will break without notice. Module developers
  8756. are encouraged to implement <code>check_event_for_spam</code> from the spam checker category instead.
  8757. </span></strong></p>
  8758. <p>Called when processing any incoming event, with the event and a <code>StateMap</code>
  8759. representing the current state of the room the event is being sent into. A <code>StateMap</code> is
  8760. a dictionary that maps tuples containing an event type and a state key to the
  8761. corresponding state event. For example retrieving the room's <code>m.room.create</code> event from
  8762. the <code>state_events</code> argument would look like this: <code>state_events.get((&quot;m.room.create&quot;, &quot;&quot;))</code>.
  8763. The module must return a boolean indicating whether the event can be allowed.</p>
  8764. <p>Note that this callback function processes incoming events coming via federation
  8765. traffic (on top of client traffic). This means denying an event might cause the local
  8766. copy of the room's history to diverge from that of remote servers. This may cause
  8767. federation issues in the room. It is strongly recommended to only deny events using this
  8768. callback function if the sender is a local user, or in a private federation in which all
  8769. servers are using the same module, with the same configuration.</p>
  8770. <p>If the boolean returned by the module is <code>True</code>, it may also tell Synapse to replace the
  8771. event with new data by returning the new event's data as a dictionary. In order to do
  8772. that, it is recommended the module calls <code>event.get_dict()</code> to get the current event as a
  8773. dictionary, and modify the returned dictionary accordingly.</p>
  8774. <p>If <code>check_event_allowed</code> raises an exception, the module is assumed to have failed.
  8775. The event will not be accepted but is not treated as explicitly rejected, either.
  8776. An HTTP request causing the module check will likely result in a 500 Internal
  8777. Server Error.</p>
  8778. <p>When the boolean returned by the module is <code>False</code>, the event is rejected.
  8779. (Module developers should not use exceptions for rejection.)</p>
  8780. <p>Note that replacing the event only works for events sent by local users, not for events
  8781. received over federation.</p>
  8782. <p>If multiple modules implement this callback, they will be considered in order. If a
  8783. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  8784. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  8785. any of the subsequent implementations of this callback.</p>
  8786. <h3 id="on_create_room"><a class="header" href="#on_create_room"><code>on_create_room</code></a></h3>
  8787. <p><em>First introduced in Synapse v1.39.0</em></p>
  8788. <pre><code class="language-python">async def on_create_room(
  8789. requester: &quot;synapse.types.Requester&quot;,
  8790. request_content: dict,
  8791. is_requester_admin: bool,
  8792. ) -&gt; None
  8793. </code></pre>
  8794. <p>Called when processing a room creation request, with the <code>Requester</code> object for the user
  8795. performing the request, a dictionary representing the room creation request's JSON body
  8796. (see <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom">the spec</a>
  8797. for a list of possible parameters), and a boolean indicating whether the user performing
  8798. the request is a server admin.</p>
  8799. <p>Modules can modify the <code>request_content</code> (by e.g. adding events to its <code>initial_state</code>),
  8800. or deny the room's creation by raising a <code>module_api.errors.SynapseError</code>.</p>
  8801. <p>If multiple modules implement this callback, they will be considered in order. If a
  8802. callback returns without raising an exception, Synapse falls through to the next one. The
  8803. room creation will be forbidden as soon as one of the callbacks raises an exception. If
  8804. this happens, Synapse will not call any of the subsequent implementations of this
  8805. callback.</p>
  8806. <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>
  8807. <p><em>First introduced in Synapse v1.39.0</em></p>
  8808. <pre><code class="language-python">async def check_threepid_can_be_invited(
  8809. medium: str,
  8810. address: str,
  8811. state_events: &quot;synapse.types.StateMap&quot;,
  8812. ) -&gt; bool:
  8813. </code></pre>
  8814. <p>Called when processing an invite via a third-party identifier (i.e. email or phone number).
  8815. The module must return a boolean indicating whether the invite can go through.</p>
  8816. <p>If multiple modules implement this callback, they will be considered in order. If a
  8817. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  8818. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  8819. any of the subsequent implementations of this callback.</p>
  8820. <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>
  8821. <p><em>First introduced in Synapse v1.39.0</em></p>
  8822. <pre><code class="language-python">async def check_visibility_can_be_modified(
  8823. room_id: str,
  8824. state_events: &quot;synapse.types.StateMap&quot;,
  8825. new_visibility: str,
  8826. ) -&gt; bool:
  8827. </code></pre>
  8828. <p>Called when changing the visibility of a room in the local public room directory. The
  8829. visibility is a string that's either &quot;public&quot; or &quot;private&quot;. The module must return a
  8830. boolean indicating whether the change can go through.</p>
  8831. <p>If multiple modules implement this callback, they will be considered in order. If a
  8832. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  8833. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  8834. any of the subsequent implementations of this callback.</p>
  8835. <h3 id="on_new_event"><a class="header" href="#on_new_event"><code>on_new_event</code></a></h3>
  8836. <p><em>First introduced in Synapse v1.47.0</em></p>
  8837. <pre><code class="language-python">async def on_new_event(
  8838. event: &quot;synapse.events.EventBase&quot;,
  8839. state_events: &quot;synapse.types.StateMap&quot;,
  8840. ) -&gt; None:
  8841. </code></pre>
  8842. <p>Called after sending an event into a room. The module is passed the event, as well
  8843. as the state of the room <em>after</em> the event. This means that if the event is a state event,
  8844. it will be included in this state.</p>
  8845. <p>Note that this callback is called when the event has already been processed and stored
  8846. into the room, which means this callback cannot be used to deny persisting the event. To
  8847. 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>
  8848. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  8849. <h3 id="check_can_shutdown_room"><a class="header" href="#check_can_shutdown_room"><code>check_can_shutdown_room</code></a></h3>
  8850. <p><em>First introduced in Synapse v1.55.0</em></p>
  8851. <pre><code class="language-python">async def check_can_shutdown_room(
  8852. user_id: str, room_id: str,
  8853. ) -&gt; bool:
  8854. </code></pre>
  8855. <p>Called when an admin user requests the shutdown of a room. The module must return a
  8856. boolean indicating whether the shutdown can go through. If the callback returns <code>False</code>,
  8857. the shutdown will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
  8858. <p>If multiple modules implement this callback, they will be considered in order. If a
  8859. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  8860. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  8861. any of the subsequent implementations of this callback.</p>
  8862. <h3 id="check_can_deactivate_user"><a class="header" href="#check_can_deactivate_user"><code>check_can_deactivate_user</code></a></h3>
  8863. <p><em>First introduced in Synapse v1.55.0</em></p>
  8864. <pre><code class="language-python">async def check_can_deactivate_user(
  8865. user_id: str, by_admin: bool,
  8866. ) -&gt; bool:
  8867. </code></pre>
  8868. <p>Called when the deactivation of a user is requested. User deactivation can be
  8869. performed by an admin or the user themselves, so developers are encouraged to check the
  8870. requester when implementing this callback. The module must return a
  8871. boolean indicating whether the deactivation can go through. If the callback returns <code>False</code>,
  8872. the deactivation will not proceed and the caller will see a <code>M_FORBIDDEN</code> error.</p>
  8873. <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>
  8874. <p>If multiple modules implement this callback, they will be considered in order. If a
  8875. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  8876. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  8877. any of the subsequent implementations of this callback.</p>
  8878. <h3 id="on_profile_update"><a class="header" href="#on_profile_update"><code>on_profile_update</code></a></h3>
  8879. <p><em>First introduced in Synapse v1.54.0</em></p>
  8880. <pre><code class="language-python">async def on_profile_update(
  8881. user_id: str,
  8882. new_profile: &quot;synapse.module_api.ProfileInfo&quot;,
  8883. by_admin: bool,
  8884. deactivation: bool,
  8885. ) -&gt; None:
  8886. </code></pre>
  8887. <p>Called after updating a local user's profile. The update can be triggered either by the
  8888. user themselves or a server admin. The update can also be triggered by a user being
  8889. deactivated (in which case their display name is set to an empty string (<code>&quot;&quot;</code>) and the
  8890. avatar URL is set to <code>None</code>). The module is passed the Matrix ID of the user whose profile
  8891. has been updated, their new profile, as well as a <code>by_admin</code> boolean that is <code>True</code> if the
  8892. update was triggered by a server admin (and <code>False</code> otherwise), and a <code>deactivated</code>
  8893. boolean that is <code>True</code> if the update is a result of the user being deactivated.</p>
  8894. <p>Note that the <code>by_admin</code> boolean is also <code>True</code> if the profile change happens as a result
  8895. of the user logging in through Single Sign-On, or if a server admin updates their own
  8896. profile.</p>
  8897. <p>Per-room profile changes do not trigger this callback to be called. Synapse administrators
  8898. wishing this callback to be called on every profile change are encouraged to disable
  8899. per-room profiles globally using the <code>allow_per_room_profiles</code> configuration setting in
  8900. Synapse's configuration file.
  8901. This callback is not called when registering a user, even when setting it through the
  8902. <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>
  8903. module callback.</p>
  8904. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  8905. <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>
  8906. <p><em>First introduced in Synapse v1.54.0</em></p>
  8907. <pre><code class="language-python">async def on_user_deactivation_status_changed(
  8908. user_id: str, deactivated: bool, by_admin: bool
  8909. ) -&gt; None:
  8910. </code></pre>
  8911. <p>Called after deactivating a local user, or reactivating them through the admin API. The
  8912. deactivation can be triggered either by the user themselves or a server admin. The module
  8913. is passed the Matrix ID of the user whose status is changed, as well as a <code>deactivated</code>
  8914. boolean that is <code>True</code> if the user is being deactivated and <code>False</code> if they're being
  8915. reactivated, and a <code>by_admin</code> boolean that is <code>True</code> if the deactivation was triggered by
  8916. a server admin (and <code>False</code> otherwise). This latter <code>by_admin</code> boolean is always <code>True</code>
  8917. if the user is being reactivated, as this operation can only be performed through the
  8918. admin API.</p>
  8919. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  8920. <h3 id="on_threepid_bind"><a class="header" href="#on_threepid_bind"><code>on_threepid_bind</code></a></h3>
  8921. <p><em>First introduced in Synapse v1.56.0</em></p>
  8922. <pre><code class="language-python">async def on_threepid_bind(user_id: str, medium: str, address: str) -&gt; None:
  8923. </code></pre>
  8924. <p>Called after creating an association between a local user and a third-party identifier
  8925. (email address, phone number). The module is given the Matrix ID of the user the
  8926. association is for, as well as the medium (<code>email</code> or <code>msisdn</code>) and address of the
  8927. third-party identifier.</p>
  8928. <p>Note that this callback is <em>not</em> called after a successful association on an <em>identity
  8929. server</em>.</p>
  8930. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  8931. <h2 id="example-1"><a class="header" href="#example-1">Example</a></h2>
  8932. <p>The example below is a module that implements the third-party rules callback
  8933. <code>check_event_allowed</code> to censor incoming messages as dictated by a third-party service.</p>
  8934. <pre><code class="language-python">from typing import Optional, Tuple
  8935. from synapse.module_api import ModuleApi
  8936. _DEFAULT_CENSOR_ENDPOINT = &quot;https://my-internal-service.local/censor-event&quot;
  8937. class EventCensorer:
  8938. def __init__(self, config: dict, api: ModuleApi):
  8939. self.api = api
  8940. self._endpoint = config.get(&quot;endpoint&quot;, _DEFAULT_CENSOR_ENDPOINT)
  8941. self.api.register_third_party_rules_callbacks(
  8942. check_event_allowed=self.check_event_allowed,
  8943. )
  8944. async def check_event_allowed(
  8945. self,
  8946. event: &quot;synapse.events.EventBase&quot;,
  8947. state_events: &quot;synapse.types.StateMap&quot;,
  8948. ) -&gt; Tuple[bool, Optional[dict]]:
  8949. event_dict = event.get_dict()
  8950. new_event_content = await self.api.http_client.post_json_get_json(
  8951. uri=self._endpoint, post_json=event_dict,
  8952. )
  8953. event_dict[&quot;content&quot;] = new_event_content
  8954. return event_dict
  8955. </code></pre>
  8956. <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>
  8957. <p>Presence router callbacks allow module developers to specify additional users (local or remote)
  8958. to receive certain presence updates from local users. Presence router callbacks can be
  8959. registered using the module API's <code>register_presence_router_callbacks</code> method.</p>
  8960. <h2 id="callbacks-2"><a class="header" href="#callbacks-2">Callbacks</a></h2>
  8961. <p>The available presence router callbacks are:</p>
  8962. <h3 id="get_users_for_states"><a class="header" href="#get_users_for_states"><code>get_users_for_states</code></a></h3>
  8963. <p><em>First introduced in Synapse v1.42.0</em></p>
  8964. <pre><code class="language-python">async def get_users_for_states(
  8965. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  8966. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]
  8967. </code></pre>
  8968. <p><strong>Requires</strong> <code>get_interested_users</code> to also be registered</p>
  8969. <p>Called when processing updates to the presence state of one or more users. This callback can
  8970. be used to instruct the server to forward that presence state to specific users. The module
  8971. must return a dictionary that maps from Matrix user IDs (which can be local or remote) to the
  8972. <code>UserPresenceState</code> changes that they should be forwarded.</p>
  8973. <p>Synapse will then attempt to send the specified presence updates to each user when possible.</p>
  8974. <p>If multiple modules implement this callback, Synapse merges all the dictionaries returned
  8975. by the callbacks. If multiple callbacks return a dictionary containing the same key,
  8976. Synapse concatenates the sets associated with this key from each dictionary. </p>
  8977. <h3 id="get_interested_users"><a class="header" href="#get_interested_users"><code>get_interested_users</code></a></h3>
  8978. <p><em>First introduced in Synapse v1.42.0</em></p>
  8979. <pre><code class="language-python">async def get_interested_users(
  8980. user_id: str
  8981. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]
  8982. </code></pre>
  8983. <p><strong>Requires</strong> <code>get_users_for_states</code> to also be registered</p>
  8984. <p>Called when determining which users someone should be able to see the presence state of. This
  8985. callback should return complementary results to <code>get_users_for_state</code> or the presence information
  8986. may not be properly forwarded.</p>
  8987. <p>The callback is given the Matrix user ID for a local user that is requesting presence data and
  8988. should return the Matrix user IDs of the users whose presence state they are allowed to
  8989. query. The returned users can be local or remote. </p>
  8990. <p>Alternatively the callback can return <code>synapse.module_api.PRESENCE_ALL_USERS</code>
  8991. to indicate that the user should receive updates from all known users.</p>
  8992. <p>If multiple modules implement this callback, they will be considered in order. Synapse
  8993. calls each callback one by one, and use a concatenation of all the <code>set</code>s returned by the
  8994. callbacks. If one callback returns <code>synapse.module_api.PRESENCE_ALL_USERS</code>, Synapse uses
  8995. this value instead. If this happens, Synapse does not call any of the subsequent
  8996. implementations of this callback.</p>
  8997. <h2 id="example-2"><a class="header" href="#example-2">Example</a></h2>
  8998. <p>The example below is a module that implements both presence router callbacks, and ensures
  8999. that <code>@alice:example.org</code> receives all presence updates from <code>@bob:example.com</code> and
  9000. <code>@charlie:somewhere.org</code>, regardless of whether Alice shares a room with any of them.</p>
  9001. <pre><code class="language-python">from typing import Dict, Iterable, Set, Union
  9002. from synapse.module_api import ModuleApi
  9003. class CustomPresenceRouter:
  9004. def __init__(self, config: dict, api: ModuleApi):
  9005. self.api = api
  9006. self.api.register_presence_router_callbacks(
  9007. get_users_for_states=self.get_users_for_states,
  9008. get_interested_users=self.get_interested_users,
  9009. )
  9010. async def get_users_for_states(
  9011. self,
  9012. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  9013. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]:
  9014. res = {}
  9015. for update in state_updates:
  9016. if (
  9017. update.user_id == &quot;@bob:example.com&quot;
  9018. or update.user_id == &quot;@charlie:somewhere.org&quot;
  9019. ):
  9020. res.setdefault(&quot;@alice:example.com&quot;, set()).add(update)
  9021. return res
  9022. async def get_interested_users(
  9023. self,
  9024. user_id: str,
  9025. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]:
  9026. if user_id == &quot;@alice:example.com&quot;:
  9027. return {&quot;@bob:example.com&quot;, &quot;@charlie:somewhere.org&quot;}
  9028. return set()
  9029. </code></pre>
  9030. <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>
  9031. <p>Account validity callbacks allow module developers to add extra steps to verify the
  9032. validity on an account, i.e. see if a user can be granted access to their account on the
  9033. Synapse instance. Account validity callbacks can be registered using the module API's
  9034. <code>register_account_validity_callbacks</code> method.</p>
  9035. <p>The available account validity callbacks are:</p>
  9036. <h3 id="is_user_expired"><a class="header" href="#is_user_expired"><code>is_user_expired</code></a></h3>
  9037. <p><em>First introduced in Synapse v1.39.0</em></p>
  9038. <pre><code class="language-python">async def is_user_expired(user: str) -&gt; Optional[bool]
  9039. </code></pre>
  9040. <p>Called when processing any authenticated request (except for logout requests). The module
  9041. can return a <code>bool</code> to indicate whether the user has expired and should be locked out of
  9042. their account, or <code>None</code> if the module wasn't able to figure it out. The user is
  9043. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  9044. <p>If the module returns <code>True</code>, the current request will be denied with the error code
  9045. <code>ORG_MATRIX_EXPIRED_ACCOUNT</code> and the HTTP status code 403. Note that this doesn't
  9046. invalidate the user's access token.</p>
  9047. <p>If multiple modules implement this callback, they will be considered in order. If a
  9048. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  9049. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  9050. any of the subsequent implementations of this callback.</p>
  9051. <h3 id="on_user_registration"><a class="header" href="#on_user_registration"><code>on_user_registration</code></a></h3>
  9052. <p><em>First introduced in Synapse v1.39.0</em></p>
  9053. <pre><code class="language-python">async def on_user_registration(user: str) -&gt; None
  9054. </code></pre>
  9055. <p>Called after successfully registering a user, in case the module needs to perform extra
  9056. operations to keep track of them. (e.g. add them to a database table). The user is
  9057. represented by their Matrix user ID.</p>
  9058. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9059. <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>
  9060. <p>Password auth providers offer a way for server administrators to integrate
  9061. their Synapse installation with an external authentication system. The callbacks can be
  9062. registered by using the Module API's <code>register_password_auth_provider_callbacks</code> method.</p>
  9063. <h2 id="callbacks-3"><a class="header" href="#callbacks-3">Callbacks</a></h2>
  9064. <h3 id="auth_checkers"><a class="header" href="#auth_checkers"><code>auth_checkers</code></a></h3>
  9065. <p><em>First introduced in Synapse v1.46.0</em></p>
  9066. <pre><code class="language-python">auth_checkers: Dict[Tuple[str, Tuple[str, ...]], Callable]
  9067. </code></pre>
  9068. <p>A dict mapping from tuples of a login type identifier (such as <code>m.login.password</code>) and a
  9069. tuple of field names (such as <code>(&quot;password&quot;, &quot;secret_thing&quot;)</code>) to authentication checking
  9070. callbacks, which should be of the following form:</p>
  9071. <pre><code class="language-python">async def check_auth(
  9072. user: str,
  9073. login_type: str,
  9074. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  9075. ) -&gt; Optional[
  9076. Tuple[
  9077. str,
  9078. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  9079. ]
  9080. ]
  9081. </code></pre>
  9082. <p>The login type and field names should be provided by the user in the
  9083. request to the <code>/login</code> API. <a href="https://matrix.org/docs/spec/client_server/latest#authentication-types">The Matrix specification</a>
  9084. defines some types, however user defined ones are also allowed.</p>
  9085. <p>The callback is passed the <code>user</code> field provided by the client (which might not be in
  9086. <code>@username:server</code> form), the login type, and a dictionary of login secrets passed by
  9087. the client.</p>
  9088. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  9089. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the
  9090. <code>/login</code> request. If the module doesn't wish to return a callback, it must return <code>None</code>
  9091. instead.</p>
  9092. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  9093. <p>If multiple modules register an auth checker for the same login type but with different
  9094. fields, Synapse will refuse to start.</p>
  9095. <p>If multiple modules register an auth checker for the same login type with the same fields,
  9096. then the callbacks will be executed in order, until one returns a Matrix User ID (and
  9097. optionally a callback). In that case, the return value of that callback will be accepted
  9098. and subsequent callbacks will not be fired. If every callback returns <code>None</code>, then the
  9099. authentication fails.</p>
  9100. <h3 id="check_3pid_auth"><a class="header" href="#check_3pid_auth"><code>check_3pid_auth</code></a></h3>
  9101. <p><em>First introduced in Synapse v1.46.0</em></p>
  9102. <pre><code class="language-python">async def check_3pid_auth(
  9103. medium: str,
  9104. address: str,
  9105. password: str,
  9106. ) -&gt; Optional[
  9107. Tuple[
  9108. str,
  9109. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  9110. ]
  9111. ]
  9112. </code></pre>
  9113. <p>Called when a user attempts to register or log in with a third party identifier,
  9114. such as email. It is passed the medium (eg. <code>email</code>), an address (eg. <code>jdoe@example.com</code>)
  9115. and the user's password.</p>
  9116. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  9117. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the <code>/login</code> request.
  9118. If the module doesn't wish to return a callback, it must return None instead.</p>
  9119. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  9120. <p>If multiple modules implement this callback, they will be considered in order. If a
  9121. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  9122. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  9123. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  9124. the authentication is denied.</p>
  9125. <h3 id="on_logged_out"><a class="header" href="#on_logged_out"><code>on_logged_out</code></a></h3>
  9126. <p><em>First introduced in Synapse v1.46.0</em></p>
  9127. <pre><code class="language-python">async def on_logged_out(
  9128. user_id: str,
  9129. device_id: Optional[str],
  9130. access_token: str
  9131. ) -&gt; None
  9132. </code></pre>
  9133. <p>Called during a logout request for a user. It is passed the qualified user ID, the ID of the
  9134. deactivated device (if any: access tokens are occasionally created without an associated
  9135. device ID), and the (now deactivated) access token.</p>
  9136. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9137. <h3 id="get_username_for_registration"><a class="header" href="#get_username_for_registration"><code>get_username_for_registration</code></a></h3>
  9138. <p><em>First introduced in Synapse v1.52.0</em></p>
  9139. <pre><code class="language-python">async def get_username_for_registration(
  9140. uia_results: Dict[str, Any],
  9141. params: Dict[str, Any],
  9142. ) -&gt; Optional[str]
  9143. </code></pre>
  9144. <p>Called when registering a new user. The module can return a username to set for the user
  9145. being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  9146. username for this user. If a username is returned, it will be used as the local part of a
  9147. user's full Matrix ID (e.g. it's <code>alice</code> in <code>@alice:example.com</code>).</p>
  9148. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  9149. has been completed by the user. It is not called when registering a user via SSO. It is
  9150. passed two dictionaries, which include the information that the user has provided during
  9151. the registration process.</p>
  9152. <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>
  9153. flow followed by the user. Its keys are the identifiers of every step involved in the flow,
  9154. associated with either a boolean value indicating whether the step was correctly completed,
  9155. or additional information (e.g. email address, phone number...). A list of most existing
  9156. identifiers can be found in the <a href="https://spec.matrix.org/v1.1/client-server-api/#authentication-types">Matrix specification</a>.
  9157. Here's an example featuring all currently supported keys:</p>
  9158. <pre><code class="language-python">{
  9159. &quot;m.login.dummy&quot;: True, # Dummy authentication
  9160. &quot;m.login.terms&quot;: True, # User has accepted the terms of service for the homeserver
  9161. &quot;m.login.recaptcha&quot;: True, # User has completed the recaptcha challenge
  9162. &quot;m.login.email.identity&quot;: { # User has provided and verified an email address
  9163. &quot;medium&quot;: &quot;email&quot;,
  9164. &quot;address&quot;: &quot;alice@example.com&quot;,
  9165. &quot;validated_at&quot;: 1642701357084,
  9166. },
  9167. &quot;m.login.msisdn&quot;: { # User has provided and verified a phone number
  9168. &quot;medium&quot;: &quot;msisdn&quot;,
  9169. &quot;address&quot;: &quot;33123456789&quot;,
  9170. &quot;validated_at&quot;: 1642701357084,
  9171. },
  9172. &quot;m.login.registration_token&quot;: &quot;sometoken&quot;, # User has registered through a registration token
  9173. }
  9174. </code></pre>
  9175. <p>The second dictionary contains the parameters provided by the user's client in the request
  9176. to <code>/_matrix/client/v3/register</code>. See the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3register">Matrix specification</a>
  9177. for a complete list of these parameters.</p>
  9178. <p>If the module cannot, or does not wish to, generate a username for this user, it must
  9179. return <code>None</code>.</p>
  9180. <p>If multiple modules implement this callback, they will be considered in order. If a
  9181. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  9182. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  9183. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  9184. the username provided by the user is used, if any (otherwise one is automatically
  9185. generated).</p>
  9186. <h3 id="get_displayname_for_registration"><a class="header" href="#get_displayname_for_registration"><code>get_displayname_for_registration</code></a></h3>
  9187. <p><em>First introduced in Synapse v1.54.0</em></p>
  9188. <pre><code class="language-python">async def get_displayname_for_registration(
  9189. uia_results: Dict[str, Any],
  9190. params: Dict[str, Any],
  9191. ) -&gt; Optional[str]
  9192. </code></pre>
  9193. <p>Called when registering a new user. The module can return a display name to set for the
  9194. user being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  9195. display name for this user.</p>
  9196. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  9197. has been completed by the user. It is not called when registering a user via SSO. It is
  9198. passed two dictionaries, which include the information that the user has provided during
  9199. the registration process. These dictionaries are identical to the ones passed to
  9200. <a href="modules/password_auth_provider_callbacks.html#get_username_for_registration"><code>get_username_for_registration</code></a>, so refer to the
  9201. documentation of this callback for more information about them.</p>
  9202. <p>If multiple modules implement this callback, they will be considered in order. If a
  9203. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  9204. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  9205. any of the subsequent implementations of this callback. If every callback returns <code>None</code>,
  9206. the username will be used (e.g. <code>alice</code> if the user being registered is <code>@alice:example.com</code>).</p>
  9207. <h2 id="is_3pid_allowed"><a class="header" href="#is_3pid_allowed"><code>is_3pid_allowed</code></a></h2>
  9208. <p><em>First introduced in Synapse v1.53.0</em></p>
  9209. <pre><code class="language-python">async def is_3pid_allowed(self, medium: str, address: str, registration: bool) -&gt; bool
  9210. </code></pre>
  9211. <p>Called when attempting to bind a third-party identifier (i.e. an email address or a phone
  9212. number). The module is given the medium of the third-party identifier (which is <code>email</code> if
  9213. the identifier is an email address, or <code>msisdn</code> if the identifier is a phone number) and
  9214. its address, as well as a boolean indicating whether the attempt to bind is happening as
  9215. part of registering a new user. The module must return a boolean indicating whether the
  9216. identifier can be allowed to be bound to an account on the local homeserver.</p>
  9217. <p>If multiple modules implement this callback, they will be considered in order. If a
  9218. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  9219. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  9220. any of the subsequent implementations of this callback.</p>
  9221. <h2 id="example-3"><a class="header" href="#example-3">Example</a></h2>
  9222. <p>The example module below implements authentication checkers for two different login types: </p>
  9223. <ul>
  9224. <li><code>my.login.type</code>
  9225. <ul>
  9226. <li>Expects a <code>my_field</code> field to be sent to <code>/login</code></li>
  9227. <li>Is checked by the method: <code>self.check_my_login</code></li>
  9228. </ul>
  9229. </li>
  9230. <li><code>m.login.password</code> (defined in <a href="https://matrix.org/docs/spec/client_server/latest#password-based">the spec</a>)
  9231. <ul>
  9232. <li>Expects a <code>password</code> field to be sent to <code>/login</code></li>
  9233. <li>Is checked by the method: <code>self.check_pass</code></li>
  9234. </ul>
  9235. </li>
  9236. </ul>
  9237. <pre><code class="language-python">from typing import Awaitable, Callable, Optional, Tuple
  9238. import synapse
  9239. from synapse import module_api
  9240. class MyAuthProvider:
  9241. def __init__(self, config: dict, api: module_api):
  9242. self.api = api
  9243. self.credentials = {
  9244. &quot;bob&quot;: &quot;building&quot;,
  9245. &quot;@scoop:matrix.org&quot;: &quot;digging&quot;,
  9246. }
  9247. api.register_password_auth_provider_callbacks(
  9248. auth_checkers={
  9249. (&quot;my.login_type&quot;, (&quot;my_field&quot;,)): self.check_my_login,
  9250. (&quot;m.login.password&quot;, (&quot;password&quot;,)): self.check_pass,
  9251. },
  9252. )
  9253. async def check_my_login(
  9254. self,
  9255. username: str,
  9256. login_type: str,
  9257. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  9258. ) -&gt; Optional[
  9259. Tuple[
  9260. str,
  9261. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  9262. ]
  9263. ]:
  9264. if login_type != &quot;my.login_type&quot;:
  9265. return None
  9266. if self.credentials.get(username) == login_dict.get(&quot;my_field&quot;):
  9267. return self.api.get_qualified_user_id(username)
  9268. async def check_pass(
  9269. self,
  9270. username: str,
  9271. login_type: str,
  9272. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  9273. ) -&gt; Optional[
  9274. Tuple[
  9275. str,
  9276. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  9277. ]
  9278. ]:
  9279. if login_type != &quot;m.login.password&quot;:
  9280. return None
  9281. if self.credentials.get(username) == login_dict.get(&quot;password&quot;):
  9282. return self.api.get_qualified_user_id(username)
  9283. </code></pre>
  9284. <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>
  9285. <p>Background update controller callbacks allow module developers to control (e.g. rate-limit)
  9286. how database background updates are run. A database background update is an operation
  9287. Synapse runs on its database in the background after it starts. It's usually used to run
  9288. database operations that would take too long if they were run at the same time as schema
  9289. updates (which are run on startup) and delay Synapse's startup too much: populating a
  9290. table with a big amount of data, adding an index on a big table, deleting superfluous data,
  9291. etc.</p>
  9292. <p>Background update controller callbacks can be registered using the module API's
  9293. <code>register_background_update_controller_callbacks</code> method. Only the first module (in order
  9294. of appearance in Synapse's configuration file) calling this method can register background
  9295. update controller callbacks, subsequent calls are ignored.</p>
  9296. <p>The available background update controller callbacks are:</p>
  9297. <h3 id="on_update"><a class="header" href="#on_update"><code>on_update</code></a></h3>
  9298. <p><em>First introduced in Synapse v1.49.0</em></p>
  9299. <pre><code class="language-python">def on_update(update_name: str, database_name: str, one_shot: bool) -&gt; AsyncContextManager[int]
  9300. </code></pre>
  9301. <p>Called when about to do an iteration of a background update. The module is given the name
  9302. of the update, the name of the database, and a flag to indicate whether the background
  9303. update will happen in one go and may take a long time (e.g. creating indices). If this last
  9304. argument is set to <code>False</code>, the update will be run in batches.</p>
  9305. <p>The module must return an async context manager. It will be entered before Synapse runs a
  9306. background update; this should return the desired duration of the iteration, in
  9307. milliseconds.</p>
  9308. <p>The context manager will be exited when the iteration completes. Note that the duration
  9309. returned by the context manager is a target, and an iteration may take substantially longer
  9310. or shorter. If the <code>one_shot</code> flag is set to <code>True</code>, the duration returned is ignored.</p>
  9311. <p><strong>Note</strong>: Unlike most module callbacks in Synapse, this one is <em>synchronous</em>. This is
  9312. because asynchronous operations are expected to be run by the async context manager.</p>
  9313. <p>This callback is required when registering any other background update controller callback.</p>
  9314. <h3 id="default_batch_size"><a class="header" href="#default_batch_size"><code>default_batch_size</code></a></h3>
  9315. <p><em>First introduced in Synapse v1.49.0</em></p>
  9316. <pre><code class="language-python">async def default_batch_size(update_name: str, database_name: str) -&gt; int
  9317. </code></pre>
  9318. <p>Called before the first iteration of a background update, with the name of the update and
  9319. of the database. The module must return the number of elements to process in this first
  9320. iteration.</p>
  9321. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  9322. <h3 id="min_batch_size"><a class="header" href="#min_batch_size"><code>min_batch_size</code></a></h3>
  9323. <p><em>First introduced in Synapse v1.49.0</em></p>
  9324. <pre><code class="language-python">async def min_batch_size(update_name: str, database_name: str) -&gt; int
  9325. </code></pre>
  9326. <p>Called before running a new batch for a background update, with the name of the update and
  9327. of the database. The module must return an integer representing the minimum number of
  9328. elements to process in this iteration. This number must be at least 1, and is used to
  9329. ensure that progress is always made.</p>
  9330. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  9331. <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>
  9332. <p>Account data callbacks allow module developers to react to changes of the account data
  9333. of local users. Account data callbacks can be registered using the module API's
  9334. <code>register_account_data_callbacks</code> method.</p>
  9335. <h2 id="callbacks-4"><a class="header" href="#callbacks-4">Callbacks</a></h2>
  9336. <p>The available account data callbacks are:</p>
  9337. <h3 id="on_account_data_updated"><a class="header" href="#on_account_data_updated"><code>on_account_data_updated</code></a></h3>
  9338. <p><em>First introduced in Synapse v1.57.0</em></p>
  9339. <pre><code class="language-python">async def on_account_data_updated(
  9340. user_id: str,
  9341. room_id: Optional[str],
  9342. account_data_type: str,
  9343. content: &quot;synapse.module_api.JsonDict&quot;,
  9344. ) -&gt; None:
  9345. </code></pre>
  9346. <p>Called after user's account data has been updated. The module is given the
  9347. Matrix ID of the user whose account data is changing, the room ID the data is associated
  9348. with, the type associated with the change, as well as the new content. If the account
  9349. data is not associated with a specific room, then the room ID is <code>None</code>.</p>
  9350. <p>This callback is triggered when new account data is added or when the data associated with
  9351. a given type (and optionally room) changes. This includes deletion, since in Matrix,
  9352. deleting account data consists of replacing the data associated with a given type
  9353. (and optionally room) with an empty dictionary (<code>{}</code>).</p>
  9354. <p>Note that this doesn't trigger when changing the tags associated with a room, as these are
  9355. processed separately by Synapse.</p>
  9356. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  9357. <h2 id="example-4"><a class="header" href="#example-4">Example</a></h2>
  9358. <p>The example below is a module that implements the <code>on_account_data_updated</code> callback, and
  9359. sends an event to an audit room when a user changes their account data.</p>
  9360. <pre><code class="language-python">import json
  9361. import attr
  9362. from typing import Any, Dict, Optional
  9363. from synapse.module_api import JsonDict, ModuleApi
  9364. from synapse.module_api.errors import ConfigError
  9365. @attr.s(auto_attribs=True)
  9366. class CustomAccountDataConfig:
  9367. audit_room: str
  9368. sender: str
  9369. class CustomAccountDataModule:
  9370. def __init__(self, config: CustomAccountDataConfig, api: ModuleApi):
  9371. self.api = api
  9372. self.config = config
  9373. self.api.register_account_data_callbacks(
  9374. on_account_data_updated=self.log_new_account_data,
  9375. )
  9376. @staticmethod
  9377. def parse_config(config: Dict[str, Any]) -&gt; CustomAccountDataConfig:
  9378. def check_in_config(param: str):
  9379. if param not in config:
  9380. raise ConfigError(f&quot;'{param}' is required&quot;)
  9381. check_in_config(&quot;audit_room&quot;)
  9382. check_in_config(&quot;sender&quot;)
  9383. return CustomAccountDataConfig(
  9384. audit_room=config[&quot;audit_room&quot;],
  9385. sender=config[&quot;sender&quot;],
  9386. )
  9387. async def log_new_account_data(
  9388. self,
  9389. user_id: str,
  9390. room_id: Optional[str],
  9391. account_data_type: str,
  9392. content: JsonDict,
  9393. ) -&gt; None:
  9394. content_raw = json.dumps(content)
  9395. msg_content = f&quot;{user_id} has changed their account data for type {account_data_type} to: {content_raw}&quot;
  9396. if room_id is not None:
  9397. msg_content += f&quot; (in room {room_id})&quot;
  9398. await self.api.create_and_send_event_into_room(
  9399. {
  9400. &quot;room_id&quot;: self.config.audit_room,
  9401. &quot;sender&quot;: self.config.sender,
  9402. &quot;type&quot;: &quot;m.room.message&quot;,
  9403. &quot;content&quot;: {
  9404. &quot;msgtype&quot;: &quot;m.text&quot;,
  9405. &quot;body&quot;: msg_content
  9406. }
  9407. }
  9408. )
  9409. </code></pre>
  9410. <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>
  9411. <p>In order to port a module that uses Synapse's old module interface, its author needs to:</p>
  9412. <ul>
  9413. <li>ensure the module's callbacks are all asynchronous.</li>
  9414. <li>register their callbacks using one or more of the <code>register_[...]_callbacks</code> methods
  9415. 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>
  9416. for more info).</li>
  9417. </ul>
  9418. <p>Additionally, if the module is packaged with an additional web resource, the module
  9419. should register this resource in its <code>__init__</code> method using the <code>register_web_resource</code>
  9420. method from the <code>ModuleApi</code> class (see <a href="modules/writing_a_module.html#registering-a-web-resource">this section</a> for
  9421. more info).</p>
  9422. <p>There is no longer a <code>get_db_schema_files</code> callback provided for password auth provider modules. Any
  9423. changes to the database should now be made by the module using the module API class.</p>
  9424. <p>The module's author should also update any example in the module's configuration to only
  9425. use the new <code>modules</code> section in Synapse's configuration file (see <a href="modules/index.html#using-modules">this section</a>
  9426. for more info).</p>
  9427. <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>
  9428. <p>For small instances it is recommended to run Synapse in the default monolith mode.
  9429. For larger instances where performance is a concern it can be helpful to split
  9430. out functionality into multiple separate python processes. These processes are
  9431. called 'workers', and are (eventually) intended to scale horizontally
  9432. independently.</p>
  9433. <p>Synapse's worker support is under active development and subject to change as
  9434. we attempt to rapidly scale ever larger Synapse instances. However we are
  9435. documenting it here to help admins needing a highly scalable Synapse instance
  9436. similar to the one running <code>matrix.org</code>.</p>
  9437. <p>All processes continue to share the same database instance, and as such,
  9438. workers only work with PostgreSQL-based Synapse deployments. SQLite should only
  9439. be used for demo purposes and any admin considering workers should already be
  9440. running PostgreSQL.</p>
  9441. <p>See also <a href="https://matrix.org/blog/2020/11/03/how-we-fixed-synapses-scalability">Matrix.org blog post</a>
  9442. for a higher level overview.</p>
  9443. <h2 id="main-processworker-communication"><a class="header" href="#main-processworker-communication">Main process/worker communication</a></h2>
  9444. <p>The processes communicate with each other via a Synapse-specific protocol called
  9445. 'replication' (analogous to MySQL- or Postgres-style database replication) which
  9446. feeds streams of newly written data between processes so they can be kept in
  9447. sync with the database state.</p>
  9448. <p>When configured to do so, Synapse uses a
  9449. <a href="https://redis.io/docs/manual/pubsub/">Redis pub/sub channel</a> to send the replication
  9450. stream between all configured Synapse processes. Additionally, processes may
  9451. make HTTP requests to each other, primarily for operations which need to wait
  9452. for a reply ─ such as sending an event.</p>
  9453. <p>Redis support was added in v1.13.0 with it becoming the recommended method in
  9454. v1.18.0. It replaced the old direct TCP connections (which is deprecated as of
  9455. v1.18.0) to the main process. With Redis, rather than all the workers connecting
  9456. to the main process, all the workers and the main process connect to Redis,
  9457. which relays replication commands between processes. This can give a significant
  9458. cpu saving on the main process and will be a prerequisite for upcoming
  9459. performance improvements.</p>
  9460. <p>If Redis support is enabled Synapse will use it as a shared cache, as well as a
  9461. pub/sub mechanism.</p>
  9462. <p>See the <a href="workers.html#architectural-diagram">Architectural diagram</a> section at the end for
  9463. a visualisation of what this looks like.</p>
  9464. <h2 id="setting-up-workers"><a class="header" href="#setting-up-workers">Setting up workers</a></h2>
  9465. <p>A Redis server is required to manage the communication between the processes.
  9466. The Redis server should be installed following the normal procedure for your
  9467. distribution (e.g. <code>apt install redis-server</code> on Debian). It is safe to use an
  9468. existing Redis deployment if you have one.</p>
  9469. <p>Once installed, check that Redis is running and accessible from the host running
  9470. Synapse, for example by executing <code>echo PING | nc -q1 localhost 6379</code> and seeing
  9471. a response of <code>+PONG</code>.</p>
  9472. <p>The appropriate dependencies must also be installed for Synapse. If using a
  9473. virtualenv, these can be installed with:</p>
  9474. <pre><code class="language-sh">pip install &quot;matrix-synapse[redis]&quot;
  9475. </code></pre>
  9476. <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
  9477. <code>matrix.org</code> and in the docker images at
  9478. https://hub.docker.com/r/matrixdotorg/synapse/.</p>
  9479. <p>To make effective use of the workers, you will need to configure an HTTP
  9480. reverse-proxy such as nginx or haproxy, which will direct incoming requests to
  9481. the correct worker, or to the main synapse instance. See
  9482. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a reverse
  9483. proxy.</p>
  9484. <p>When using workers, each worker process has its own configuration file which
  9485. contains settings specific to that worker, such as the HTTP listener that it
  9486. provides (if any), logging configuration, etc.</p>
  9487. <p>Normally, the worker processes are configured to read from a shared
  9488. configuration file as well as the worker-specific configuration files. This
  9489. makes it easier to keep common configuration settings synchronised across all
  9490. the processes.</p>
  9491. <p>The main process is somewhat special in this respect: it does not normally
  9492. need its own configuration file and can take all of its configuration from the
  9493. shared configuration file.</p>
  9494. <h3 id="shared-configuration"><a class="header" href="#shared-configuration">Shared configuration</a></h3>
  9495. <p>Normally, only a couple of changes are needed to make an existing configuration
  9496. file suitable for use with workers. First, you need to enable an &quot;HTTP replication
  9497. listener&quot; for the main process; and secondly, you need to enable redis-based
  9498. replication. Optionally, a shared secret can be used to authenticate HTTP
  9499. traffic between workers. For example:</p>
  9500. <pre><code class="language-yaml"># extend the existing `listeners` section. This defines the ports that the
  9501. # main process will listen on.
  9502. listeners:
  9503. # The HTTP replication port
  9504. - port: 9093
  9505. bind_address: '127.0.0.1'
  9506. type: http
  9507. resources:
  9508. - names: [replication]
  9509. # Add a random shared secret to authenticate traffic.
  9510. worker_replication_secret: &quot;&quot;
  9511. redis:
  9512. enabled: true
  9513. </code></pre>
  9514. <p>See the sample config for the full documentation of each option.</p>
  9515. <p>Under <strong>no circumstances</strong> should the replication listener be exposed to the
  9516. public internet; it has no authentication and is unencrypted.</p>
  9517. <h3 id="worker-configuration"><a class="header" href="#worker-configuration">Worker configuration</a></h3>
  9518. <p>In the config file for each worker, you must specify the type of worker
  9519. application (<code>worker_app</code>), and you should specify a unique name for the worker
  9520. (<code>worker_name</code>). The currently available worker applications are listed below.
  9521. You must also specify the HTTP replication endpoint that it should talk to on
  9522. the main synapse process. <code>worker_replication_host</code> should specify the host of
  9523. the main synapse and <code>worker_replication_http_port</code> should point to the HTTP
  9524. replication port. If the worker will handle HTTP requests then the
  9525. <code>worker_listeners</code> option should be set with a <code>http</code> listener, in the same way
  9526. as the <code>listeners</code> option in the shared config.</p>
  9527. <p>For example:</p>
  9528. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  9529. worker_name: generic_worker1
  9530. # The replication listener on the main synapse process.
  9531. worker_replication_host: 127.0.0.1
  9532. worker_replication_http_port: 9093
  9533. worker_listeners:
  9534. - type: http
  9535. port: 8083
  9536. resources:
  9537. - names: [client, federation]
  9538. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  9539. </code></pre>
  9540. <p>...is a full configuration for a generic worker instance, which will expose a
  9541. plain HTTP endpoint on port 8083 separately serving various endpoints, e.g.
  9542. <code>/sync</code>, which are listed below.</p>
  9543. <p>Obviously you should configure your reverse-proxy to route the relevant
  9544. endpoints to the worker (<code>localhost:8083</code> in the above example).</p>
  9545. <h3 id="running-synapse-with-workers"><a class="header" href="#running-synapse-with-workers">Running Synapse with workers</a></h3>
  9546. <p>Finally, you need to start your worker processes. This can be done with either
  9547. <code>synctl</code> or your distribution's preferred service manager such as <code>systemd</code>. We
  9548. recommend the use of <code>systemd</code> where available: for information on setting up
  9549. <code>systemd</code> to start synapse workers, see
  9550. <a href="systemd-with-workers">Systemd with Workers</a>. To use <code>synctl</code>, see
  9551. <a href="synctl_workers.html">Using synctl with Workers</a>.</p>
  9552. <h2 id="available-worker-applications"><a class="header" href="#available-worker-applications">Available worker applications</a></h2>
  9553. <h3 id="synapseappgeneric_worker"><a class="header" href="#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a></h3>
  9554. <p>This worker can handle API requests matching the following regular expressions.
  9555. These endpoints can be routed to any worker. If a worker is set up to handle a
  9556. stream then, for maximum efficiency, additional endpoints should be routed to that
  9557. worker: refer to the <a href="workers.html#stream-writers">stream writers</a> section below for further
  9558. information.</p>
  9559. <pre><code># Sync requests
  9560. ^/_matrix/client/(r0|v3)/sync$
  9561. ^/_matrix/client/(api/v1|r0|v3)/events$
  9562. ^/_matrix/client/(api/v1|r0|v3)/initialSync$
  9563. ^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$
  9564. # Federation requests
  9565. ^/_matrix/federation/v1/event/
  9566. ^/_matrix/federation/v1/state/
  9567. ^/_matrix/federation/v1/state_ids/
  9568. ^/_matrix/federation/v1/backfill/
  9569. ^/_matrix/federation/v1/get_missing_events/
  9570. ^/_matrix/federation/v1/publicRooms
  9571. ^/_matrix/federation/v1/query/
  9572. ^/_matrix/federation/v1/make_join/
  9573. ^/_matrix/federation/v1/make_leave/
  9574. ^/_matrix/federation/(v1|v2)/send_join/
  9575. ^/_matrix/federation/(v1|v2)/send_leave/
  9576. ^/_matrix/federation/(v1|v2)/invite/
  9577. ^/_matrix/federation/v1/event_auth/
  9578. ^/_matrix/federation/v1/exchange_third_party_invite/
  9579. ^/_matrix/federation/v1/user/devices/
  9580. ^/_matrix/key/v2/query
  9581. ^/_matrix/federation/v1/hierarchy/
  9582. # Inbound federation transaction request
  9583. ^/_matrix/federation/v1/send/
  9584. # Client API requests
  9585. ^/_matrix/client/(api/v1|r0|v3|unstable)/createRoom$
  9586. ^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$
  9587. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$
  9588. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$
  9589. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$
  9590. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$
  9591. ^/_matrix/client/v1/rooms/.*/hierarchy$
  9592. ^/_matrix/client/unstable/org.matrix.msc2716/rooms/.*/batch_send$
  9593. ^/_matrix/client/unstable/im.nheko.summary/rooms/.*/summary$
  9594. ^/_matrix/client/(r0|v3|unstable)/account/3pid$
  9595. ^/_matrix/client/(r0|v3|unstable)/account/whoami$
  9596. ^/_matrix/client/(r0|v3|unstable)/devices$
  9597. ^/_matrix/client/versions$
  9598. ^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$
  9599. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event/
  9600. ^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms$
  9601. ^/_matrix/client/(api/v1|r0|v3|unstable)/search$
  9602. # Encryption requests
  9603. ^/_matrix/client/(r0|v3|unstable)/keys/query$
  9604. ^/_matrix/client/(r0|v3|unstable)/keys/changes$
  9605. ^/_matrix/client/(r0|v3|unstable)/keys/claim$
  9606. ^/_matrix/client/(r0|v3|unstable)/room_keys/
  9607. # Registration/login requests
  9608. ^/_matrix/client/(api/v1|r0|v3|unstable)/login$
  9609. ^/_matrix/client/(r0|v3|unstable)/register$
  9610. ^/_matrix/client/v1/register/m.login.registration_token/validity$
  9611. # Event sending requests
  9612. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact
  9613. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send
  9614. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state/
  9615. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$
  9616. ^/_matrix/client/(api/v1|r0|v3|unstable)/join/
  9617. ^/_matrix/client/(api/v1|r0|v3|unstable)/profile/
  9618. # Account data requests
  9619. ^/_matrix/client/(r0|v3|unstable)/.*/tags
  9620. ^/_matrix/client/(r0|v3|unstable)/.*/account_data
  9621. # Receipts requests
  9622. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
  9623. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
  9624. # Presence requests
  9625. ^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
  9626. # User directory search requests
  9627. ^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  9628. </code></pre>
  9629. <p>Additionally, the following REST endpoints can be handled for GET requests:</p>
  9630. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/pushrules/
  9631. </code></pre>
  9632. <p>Pagination requests can also be handled, but all requests for a given
  9633. room must be routed to the same instance. Additionally, care must be taken to
  9634. ensure that the purge history admin API is not used while pagination requests
  9635. for the room are in flight:</p>
  9636. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$
  9637. </code></pre>
  9638. <p>Additionally, the following endpoints should be included if Synapse is configured
  9639. to use SSO (you only need to include the ones for whichever SSO provider you're
  9640. using):</p>
  9641. <pre><code># for all SSO providers
  9642. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/sso/redirect
  9643. ^/_synapse/client/pick_idp$
  9644. ^/_synapse/client/pick_username
  9645. ^/_synapse/client/new_user_consent$
  9646. ^/_synapse/client/sso_register$
  9647. # OpenID Connect requests.
  9648. ^/_synapse/client/oidc/callback$
  9649. # SAML requests.
  9650. ^/_synapse/client/saml2/authn_response$
  9651. # CAS requests.
  9652. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/cas/ticket$
  9653. </code></pre>
  9654. <p>Ensure that all SSO logins go to a single process.
  9655. For multiple workers not handling the SSO endpoints properly, see
  9656. <a href="https://github.com/matrix-org/synapse/issues/7530">#7530</a> and
  9657. <a href="https://github.com/matrix-org/synapse/issues/9427">#9427</a>.</p>
  9658. <p>Note that a HTTP listener with <code>client</code> and <code>federation</code> resources must be
  9659. configured in the <code>worker_listeners</code> option in the worker config.</p>
  9660. <h4 id="load-balancing"><a class="header" href="#load-balancing">Load balancing</a></h4>
  9661. <p>It is possible to run multiple instances of this worker app, with incoming requests
  9662. being load-balanced between them by the reverse-proxy. However, different endpoints
  9663. have different characteristics and so admins
  9664. may wish to run multiple groups of workers handling different endpoints so that
  9665. load balancing can be done in different ways.</p>
  9666. <p>For <code>/sync</code> and <code>/initialSync</code> requests it will be more efficient if all
  9667. requests from a particular user are routed to a single instance. Extracting a
  9668. user ID from the access token or <code>Authorization</code> header is currently left as an
  9669. exercise for the reader. Admins may additionally wish to separate out <code>/sync</code>
  9670. requests that have a <code>since</code> query parameter from those that don't (and
  9671. <code>/initialSync</code>), as requests that don't are known as &quot;initial sync&quot; that happens
  9672. when a user logs in on a new device and can be <em>very</em> resource intensive, so
  9673. isolating these requests will stop them from interfering with other users ongoing
  9674. syncs.</p>
  9675. <p>Federation and client requests can be balanced via simple round robin.</p>
  9676. <p>The inbound federation transaction request <code>^/_matrix/federation/v1/send/</code>
  9677. should be balanced by source IP so that transactions from the same remote server
  9678. go to the same process.</p>
  9679. <p>Registration/login requests can be handled separately purely to help ensure that
  9680. unexpected load doesn't affect new logins and sign ups.</p>
  9681. <p>Finally, event sending requests can be balanced by the room ID in the URI (or
  9682. the full URI, or even just round robin), the room ID is the path component after
  9683. <code>/rooms/</code>. If there is a large bridge connected that is sending or may send lots
  9684. of events, then a dedicated set of workers can be provisioned to limit the
  9685. effects of bursts of events from that bridge on events sent by normal users.</p>
  9686. <h4 id="stream-writers"><a class="header" href="#stream-writers">Stream writers</a></h4>
  9687. <p>Additionally, the writing of specific streams (such as events) can be moved off
  9688. of the main process to a particular worker.
  9689. (This is only supported with Redis-based replication.)</p>
  9690. <p>To enable this, the worker must have a HTTP replication listener configured,
  9691. have a <code>worker_name</code> and be listed in the <code>instance_map</code> config. The same worker
  9692. can handle multiple streams, but unless otherwise documented, each stream can only
  9693. have a single writer.</p>
  9694. <p>For example, to move event persistence off to a dedicated worker, the shared
  9695. configuration would include:</p>
  9696. <pre><code class="language-yaml">instance_map:
  9697. event_persister1:
  9698. host: localhost
  9699. port: 8034
  9700. stream_writers:
  9701. events: event_persister1
  9702. </code></pre>
  9703. <p>An example for a stream writer instance:</p>
  9704. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  9705. worker_name: event_persister1
  9706. # The replication listener on the main synapse process.
  9707. worker_replication_host: 127.0.0.1
  9708. worker_replication_http_port: 9093
  9709. worker_listeners:
  9710. - type: http
  9711. port: 8034
  9712. resources:
  9713. - names: [replication]
  9714. # Enable listener if this stream writer handles endpoints for the `typing` or
  9715. # `to_device` streams. Uses a different port to the `replication` listener to
  9716. # avoid exposing the `replication` listener publicly.
  9717. #
  9718. #- type: http
  9719. # port: 8035
  9720. # resources:
  9721. # - names: [client]
  9722. worker_log_config: /etc/matrix-synapse/event-persister-log.yaml
  9723. </code></pre>
  9724. <p>Some of the streams have associated endpoints which, for maximum efficiency, should
  9725. be routed to the workers handling that stream. See below for the currently supported
  9726. streams and the endpoints associated with them:</p>
  9727. <h5 id="the-events-stream"><a class="header" href="#the-events-stream">The <code>events</code> stream</a></h5>
  9728. <p>The <code>events</code> stream experimentally supports having multiple writers, where work
  9729. is sharded between them by room ID. Note that you <em>must</em> restart all worker
  9730. instances when adding or removing event persisters. An example <code>stream_writers</code>
  9731. configuration with multiple writers:</p>
  9732. <pre><code class="language-yaml">stream_writers:
  9733. events:
  9734. - event_persister1
  9735. - event_persister2
  9736. </code></pre>
  9737. <h5 id="the-typing-stream"><a class="header" href="#the-typing-stream">The <code>typing</code> stream</a></h5>
  9738. <p>The following endpoints should be routed directly to the worker configured as
  9739. the stream writer for the <code>typing</code> stream:</p>
  9740. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/typing
  9741. </code></pre>
  9742. <h5 id="the-to_device-stream"><a class="header" href="#the-to_device-stream">The <code>to_device</code> stream</a></h5>
  9743. <p>The following endpoints should be routed directly to the worker configured as
  9744. the stream writer for the <code>to_device</code> stream:</p>
  9745. <pre><code>^/_matrix/client/(r0|v3|unstable)/sendToDevice/
  9746. </code></pre>
  9747. <h5 id="the-account_data-stream"><a class="header" href="#the-account_data-stream">The <code>account_data</code> stream</a></h5>
  9748. <p>The following endpoints should be routed directly to the worker configured as
  9749. the stream writer for the <code>account_data</code> stream:</p>
  9750. <pre><code>^/_matrix/client/(r0|v3|unstable)/.*/tags
  9751. ^/_matrix/client/(r0|v3|unstable)/.*/account_data
  9752. </code></pre>
  9753. <h5 id="the-receipts-stream"><a class="header" href="#the-receipts-stream">The <code>receipts</code> stream</a></h5>
  9754. <p>The following endpoints should be routed directly to the worker configured as
  9755. the stream writer for the <code>receipts</code> stream:</p>
  9756. <pre><code>^/_matrix/client/(r0|v3|unstable)/rooms/.*/receipt
  9757. ^/_matrix/client/(r0|v3|unstable)/rooms/.*/read_markers
  9758. </code></pre>
  9759. <h5 id="the-presence-stream"><a class="header" href="#the-presence-stream">The <code>presence</code> stream</a></h5>
  9760. <p>The following endpoints should be routed directly to the worker configured as
  9761. the stream writer for the <code>presence</code> stream:</p>
  9762. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/presence/
  9763. </code></pre>
  9764. <h4 id="background-tasks"><a class="header" href="#background-tasks">Background tasks</a></h4>
  9765. <p>There is also support for moving background tasks to a separate
  9766. worker. Background tasks are run periodically or started via replication. Exactly
  9767. which tasks are configured to run depends on your Synapse configuration (e.g. if
  9768. stats is enabled).</p>
  9769. <p>To enable this, the worker must have a <code>worker_name</code> and can be configured to run
  9770. background tasks. For example, to move background tasks to a dedicated worker,
  9771. the shared configuration would include:</p>
  9772. <pre><code class="language-yaml">run_background_tasks_on: background_worker
  9773. </code></pre>
  9774. <p>You might also wish to investigate the <code>update_user_directory_from_worker</code> and
  9775. <code>media_instance_running_background_jobs</code> settings.</p>
  9776. <p>An example for a dedicated background worker instance:</p>
  9777. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  9778. worker_name: background_worker
  9779. # The replication listener on the main synapse process.
  9780. worker_replication_host: 127.0.0.1
  9781. worker_replication_http_port: 9093
  9782. worker_log_config: /etc/matrix-synapse/background-worker-log.yaml
  9783. </code></pre>
  9784. <h4 id="updating-the-user-directory"><a class="header" href="#updating-the-user-directory">Updating the User Directory</a></h4>
  9785. <p>You can designate one generic worker to update the user directory.</p>
  9786. <p>Specify its name in the shared configuration as follows:</p>
  9787. <pre><code class="language-yaml">update_user_directory_from_worker: worker_name
  9788. </code></pre>
  9789. <p>This work cannot be load-balanced; please ensure the main process is restarted
  9790. after setting this option in the shared configuration!</p>
  9791. <p>User directory updates allow REST endpoints matching the following regular
  9792. expressions to work:</p>
  9793. <pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  9794. </code></pre>
  9795. <p>The above endpoints can be routed to any worker, though you may choose to route
  9796. it to the chosen user directory worker.</p>
  9797. <p>This style of configuration supersedes the legacy <code>synapse.app.user_dir</code>
  9798. worker application type.</p>
  9799. <h4 id="notifying-application-services"><a class="header" href="#notifying-application-services">Notifying Application Services</a></h4>
  9800. <p>You can designate one generic worker to send output traffic to Application Services.</p>
  9801. <p>Specify its name in the shared configuration as follows:</p>
  9802. <pre><code class="language-yaml">notify_appservices_from_worker: worker_name
  9803. </code></pre>
  9804. <p>This work cannot be load-balanced; please ensure the main process is restarted
  9805. after setting this option in the shared configuration!</p>
  9806. <p>This style of configuration supersedes the legacy <code>synapse.app.appservice</code>
  9807. worker application type.</p>
  9808. <h3 id="synapseapppusher"><a class="header" href="#synapseapppusher"><code>synapse.app.pusher</code></a></h3>
  9809. <p>Handles sending push notifications to sygnal and email. Doesn't handle any
  9810. REST endpoints itself, but you should set <code>start_pushers: False</code> in the
  9811. shared configuration file to stop the main synapse sending push notifications.</p>
  9812. <p>To run multiple instances at once the <code>pusher_instances</code> option should list all
  9813. pusher instances by their worker name, e.g.:</p>
  9814. <pre><code class="language-yaml">pusher_instances:
  9815. - pusher_worker1
  9816. - pusher_worker2
  9817. </code></pre>
  9818. <h3 id="synapseappappservice"><a class="header" href="#synapseappappservice"><code>synapse.app.appservice</code></a></h3>
  9819. <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
  9820. <code>notify_appservices_from_worker</code> option instead.</a></p>
  9821. <p>Handles sending output traffic to Application Services. Doesn't handle any
  9822. REST endpoints itself, but you should set <code>notify_appservices: False</code> in the
  9823. shared configuration file to stop the main synapse sending appservice notifications.</p>
  9824. <p>Note this worker cannot be load-balanced: only one instance should be active.</p>
  9825. <h3 id="synapseappfederation_sender"><a class="header" href="#synapseappfederation_sender"><code>synapse.app.federation_sender</code></a></h3>
  9826. <p>Handles sending federation traffic to other servers. Doesn't handle any
  9827. REST endpoints itself, but you should set <code>send_federation: False</code> in the
  9828. shared configuration file to stop the main synapse sending this traffic.</p>
  9829. <p>If running multiple federation senders then you must list each
  9830. instance in the <code>federation_sender_instances</code> option by their <code>worker_name</code>.
  9831. All instances must be stopped and started when adding or removing instances.
  9832. For example:</p>
  9833. <pre><code class="language-yaml">federation_sender_instances:
  9834. - federation_sender1
  9835. - federation_sender2
  9836. </code></pre>
  9837. <h3 id="synapseappmedia_repository"><a class="header" href="#synapseappmedia_repository"><code>synapse.app.media_repository</code></a></h3>
  9838. <p>Handles the media repository. It can handle all endpoints starting with:</p>
  9839. <pre><code>/_matrix/media/
  9840. </code></pre>
  9841. <p>... and the following regular expressions matching media-specific administration APIs:</p>
  9842. <pre><code>^/_synapse/admin/v1/purge_media_cache$
  9843. ^/_synapse/admin/v1/room/.*/media.*$
  9844. ^/_synapse/admin/v1/user/.*/media.*$
  9845. ^/_synapse/admin/v1/media/.*$
  9846. ^/_synapse/admin/v1/quarantine_media/.*$
  9847. ^/_synapse/admin/v1/users/.*/media$
  9848. </code></pre>
  9849. <p>You should also set <code>enable_media_repo: False</code> in the shared configuration
  9850. file to stop the main synapse running background jobs related to managing the
  9851. media repository. Note that doing so will prevent the main process from being
  9852. able to handle the above endpoints.</p>
  9853. <p>In the <code>media_repository</code> worker configuration file, configure the http listener to
  9854. expose the <code>media</code> resource. For example:</p>
  9855. <pre><code class="language-yaml">worker_listeners:
  9856. - type: http
  9857. port: 8085
  9858. resources:
  9859. - names:
  9860. - media
  9861. </code></pre>
  9862. <p>Note that if running multiple media repositories they must be on the same server
  9863. and you must configure a single instance to run the background tasks, e.g.:</p>
  9864. <pre><code class="language-yaml">media_instance_running_background_jobs: &quot;media-repository-1&quot;
  9865. </code></pre>
  9866. <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>
  9867. <h3 id="synapseappuser_dir"><a class="header" href="#synapseappuser_dir"><code>synapse.app.user_dir</code></a></h3>
  9868. <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
  9869. <code>update_user_directory_from_worker</code> option instead.</a></p>
  9870. <p>Handles searches in the user directory. It can handle REST endpoints matching
  9871. the following regular expressions:</p>
  9872. <pre><code>^/_matrix/client/(r0|v3|unstable)/user_directory/search$
  9873. </code></pre>
  9874. <p>When using this worker you must also set <code>update_user_directory: false</code> in the
  9875. shared configuration file to stop the main synapse running background
  9876. jobs related to updating the user directory.</p>
  9877. <p>Above endpoint is not <em>required</em> to be routed to this worker. By default,
  9878. <code>update_user_directory</code> is set to <code>true</code>, which means the main process
  9879. will handle updates. All workers configured with <code>client</code> can handle the above
  9880. endpoint as long as either this worker or the main process are configured to
  9881. handle it, and are online.</p>
  9882. <p>If <code>update_user_directory</code> is set to <code>false</code>, and this worker is not running,
  9883. the above endpoint may give outdated results.</p>
  9884. <h3 id="synapseappfrontend_proxy"><a class="header" href="#synapseappfrontend_proxy"><code>synapse.app.frontend_proxy</code></a></h3>
  9885. <p>Proxies some frequently-requested client endpoints to add caching and remove
  9886. load from the main synapse. It can handle REST endpoints matching the following
  9887. regular expressions:</p>
  9888. <pre><code>^/_matrix/client/(r0|v3|unstable)/keys/upload
  9889. </code></pre>
  9890. <p>If <code>use_presence</code> is False in the homeserver config, it can also handle REST
  9891. endpoints matching the following regular expressions:</p>
  9892. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/presence/[^/]+/status
  9893. </code></pre>
  9894. <p>This &quot;stub&quot; presence handler will pass through <code>GET</code> request but make the
  9895. <code>PUT</code> effectively a no-op.</p>
  9896. <p>It will proxy any requests it cannot handle to the main synapse instance. It
  9897. must therefore be configured with the location of the main instance, via
  9898. the <code>worker_main_http_uri</code> setting in the <code>frontend_proxy</code> worker configuration
  9899. file. For example:</p>
  9900. <pre><code class="language-yaml">worker_main_http_uri: http://127.0.0.1:8008
  9901. </code></pre>
  9902. <h3 id="historical-apps"><a class="header" href="#historical-apps">Historical apps</a></h3>
  9903. <p><em>Note:</em> Historically there used to be more apps, however they have been
  9904. amalgamated into a single <code>synapse.app.generic_worker</code> app. The remaining apps
  9905. are ones that do specific processing unrelated to requests, e.g. the <code>pusher</code>
  9906. that handles sending out push notifications for new events. The intention is for
  9907. all these to be folded into the <code>generic_worker</code> app and to use config to define
  9908. which processes handle the various proccessing such as push notifications.</p>
  9909. <h2 id="migration-from-old-config"><a class="header" href="#migration-from-old-config">Migration from old config</a></h2>
  9910. <p>There are two main independent changes that have been made: introducing Redis
  9911. support and merging apps into <code>synapse.app.generic_worker</code>. Both these changes
  9912. are backwards compatible and so no changes to the config are required, however
  9913. server admins are encouraged to plan to migrate to Redis as the old style direct
  9914. TCP replication config is deprecated.</p>
  9915. <p>To migrate to Redis add the <code>redis</code> config as above, and optionally remove the
  9916. TCP <code>replication</code> listener from master and <code>worker_replication_port</code> from worker
  9917. config.</p>
  9918. <p>To migrate apps to use <code>synapse.app.generic_worker</code> simply update the
  9919. <code>worker_app</code> option in the worker configs, and where worker are started (e.g.
  9920. in systemd service files, but not required for synctl).</p>
  9921. <h2 id="architectural-diagram"><a class="header" href="#architectural-diagram">Architectural diagram</a></h2>
  9922. <p>The following shows an example setup using Redis and a reverse proxy:</p>
  9923. <pre><code> Clients &amp; Federation
  9924. |
  9925. v
  9926. +-----------+
  9927. | |
  9928. | Reverse |
  9929. | Proxy |
  9930. | |
  9931. +-----------+
  9932. | | |
  9933. | | | HTTP requests
  9934. +-------------------+ | +-----------+
  9935. | +---+ |
  9936. | | |
  9937. v v v
  9938. +--------------+ +--------------+ +--------------+ +--------------+
  9939. | Main | | Generic | | Generic | | Event |
  9940. | Process | | Worker 1 | | Worker 2 | | Persister |
  9941. +--------------+ +--------------+ +--------------+ +--------------+
  9942. ^ ^ | ^ | | ^ | | ^ ^
  9943. | | | | | | | | | | |
  9944. | | | | | HTTP | | | | | |
  9945. | +----------+&lt;--|---|---------+&lt;--|---|---------+ | |
  9946. | | +-------------|--&gt;+-------------+ |
  9947. | | | |
  9948. | | | |
  9949. v v v v
  9950. ======================================================================
  9951. Redis pub/sub channel
  9952. </code></pre>
  9953. <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>
  9954. <p>If you want to use <code>synctl</code> to manage your synapse processes, you will need to
  9955. create an an additional configuration file for the main synapse process. That
  9956. configuration should look like this:</p>
  9957. <pre><code class="language-yaml">worker_app: synapse.app.homeserver
  9958. </code></pre>
  9959. <p>Additionally, each worker app must be configured with the name of a &quot;pid file&quot;,
  9960. to which it will write its process ID when it starts. For example, for a
  9961. synchrotron, you might write:</p>
  9962. <pre><code class="language-yaml">worker_pid_file: /home/matrix/synapse/worker1.pid
  9963. </code></pre>
  9964. <p>Finally, to actually run your worker-based synapse, you must pass synctl the <code>-a</code>
  9965. commandline option to tell it to operate on all the worker configurations found
  9966. in the given directory, e.g.:</p>
  9967. <pre><code class="language-sh">synctl -a $CONFIG/workers start
  9968. </code></pre>
  9969. <p>Currently one should always restart all workers when restarting or upgrading
  9970. synapse, unless you explicitly know it's safe not to. For instance, restarting
  9971. synapse without restarting all the synchrotrons may result in broken typing
  9972. notifications.</p>
  9973. <p>To manipulate a specific worker, you pass the -w option to synctl:</p>
  9974. <pre><code class="language-sh">synctl -w $CONFIG/workers/worker1.yaml restart
  9975. </code></pre>
  9976. <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>
  9977. <p>This is a setup for managing synapse with systemd, including support for
  9978. managing workers. It provides a <code>matrix-synapse</code> service for the master, as
  9979. well as a <code>matrix-synapse-worker@</code> service template for any workers you
  9980. require. Additionally, to group the required services, it sets up a
  9981. <code>matrix-synapse.target</code>.</p>
  9982. <p>See the folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/system/">system</a>
  9983. for the systemd unit files.</p>
  9984. <p>The folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/workers/">workers</a>
  9985. contains an example configuration for the <code>generic_worker</code> worker.</p>
  9986. <h2 id="synapse-configuration-files"><a class="header" href="#synapse-configuration-files">Synapse configuration files</a></h2>
  9987. <p>See <a href="systemd-with-workers/../workers.html">the worker documentation</a> for information on how to set up the
  9988. configuration files and reverse-proxy correctly.
  9989. Below is a sample <code>generic_worker</code> worker configuration file.</p>
  9990. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  9991. worker_name: generic_worker1
  9992. # The replication listener on the main synapse process.
  9993. worker_replication_host: 127.0.0.1
  9994. worker_replication_http_port: 9093
  9995. worker_listeners:
  9996. - type: http
  9997. port: 8083
  9998. resources:
  9999. - names: [client, federation]
  10000. worker_log_config: /etc/matrix-synapse/generic-worker-log.yaml
  10001. </code></pre>
  10002. <p>Systemd manages daemonization itself, so ensure that none of the configuration
  10003. files set either <code>daemonize</code> or <code>worker_daemonize</code>.</p>
  10004. <p>The config files of all workers are expected to be located in
  10005. <code>/etc/matrix-synapse/workers</code>. If you want to use a different location, edit
  10006. the provided <code>*.service</code> files accordingly.</p>
  10007. <p>There is no need for a separate configuration file for the master process.</p>
  10008. <h2 id="set-up"><a class="header" href="#set-up">Set up</a></h2>
  10009. <ol>
  10010. <li>Adjust synapse configuration files as above.</li>
  10011. <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>
  10012. to <code>/etc/systemd/system</code>.</li>
  10013. <li>Run <code>systemctl daemon-reload</code> to tell systemd to load the new unit files.</li>
  10014. <li>Run <code>systemctl enable matrix-synapse.service</code>. This will configure the
  10015. synapse master process to be started as part of the <code>matrix-synapse.target</code>
  10016. target.</li>
  10017. <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
  10018. should be a corresponding configuration file.
  10019. <code>/etc/matrix-synapse/workers/&lt;worker_name&gt;.yaml</code>.</li>
  10020. <li>Start all the synapse processes with <code>systemctl start matrix-synapse.target</code>.</li>
  10021. <li>Tell systemd to start synapse on boot with <code>systemctl enable matrix-synapse.target</code>.</li>
  10022. </ol>
  10023. <h2 id="usage"><a class="header" href="#usage">Usage</a></h2>
  10024. <p>Once the services are correctly set up, you can use the following commands
  10025. to manage your synapse installation:</p>
  10026. <pre><code class="language-sh"># Restart Synapse master and all workers
  10027. systemctl restart matrix-synapse.target
  10028. # Stop Synapse and all workers
  10029. systemctl stop matrix-synapse.target
  10030. # Restart the master alone
  10031. systemctl start matrix-synapse.service
  10032. # Restart a specific worker (eg. generic_worker); the master is
  10033. # unaffected by this.
  10034. systemctl restart matrix-synapse-worker@generic_worker.service
  10035. # Add a new worker (assuming all configs are set up already)
  10036. systemctl enable matrix-synapse-worker@federation_writer.service
  10037. systemctl restart matrix-synapse.target
  10038. </code></pre>
  10039. <h2 id="hardening"><a class="header" href="#hardening">Hardening</a></h2>
  10040. <p><strong>Optional:</strong> If further hardening is desired, the file
  10041. <code>override-hardened.conf</code> may be copied from
  10042. <a href="https://github.com/matrix-org/synapse/tree/develop/contrib/systemd/">contrib/systemd/override-hardened.conf</a>
  10043. in this repository to the location
  10044. <code>/etc/systemd/system/matrix-synapse.service.d/override-hardened.conf</code> (the
  10045. directory may have to be created). It enables certain sandboxing features in
  10046. systemd to further secure the synapse service. You may read the comments to
  10047. understand what the override file is doing. The same file will need to be copied to
  10048. <code>/etc/systemd/system/matrix-synapse-worker@.service.d/override-hardened-worker.conf</code>
  10049. (this directory may also have to be created) in order to apply the same
  10050. hardening options to any worker processes.</p>
  10051. <p>Once these files have been copied to their appropriate locations, simply reload
  10052. systemd's manager config files and restart all Synapse services to apply the hardening options. They will automatically
  10053. be applied at every restart as long as the override files are present at the
  10054. specified locations.</p>
  10055. <pre><code class="language-sh">systemctl daemon-reload
  10056. # Restart services
  10057. systemctl restart matrix-synapse.target
  10058. </code></pre>
  10059. <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
  10060. the changes being applied at a glance.</p>
  10061. <div style="break-before: page; page-break-before: always;"></div><h1 id="administration"><a class="header" href="#administration">Administration</a></h1>
  10062. <p>This section contains information on managing your Synapse homeserver. This includes:</p>
  10063. <ul>
  10064. <li>Managing users, rooms and media via the Admin API.</li>
  10065. <li>Setting up metrics and monitoring to give you insight into your homeserver's health.</li>
  10066. <li>Configuring structured logging.</li>
  10067. </ul>
  10068. <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>
  10069. <h2 id="authenticate-as-a-server-admin"><a class="header" href="#authenticate-as-a-server-admin">Authenticate as a server admin</a></h2>
  10070. <p>Many of the API calls in the admin api will require an <code>access_token</code> for a
  10071. server admin. (Note that a server admin is distinct from a room admin.)</p>
  10072. <p>A user can be marked as a server admin by updating the database directly, e.g.:</p>
  10073. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  10074. </code></pre>
  10075. <p>A new server admin user can also be created using the <code>register_new_matrix_user</code>
  10076. command. This is a script that is distributed as part of synapse. It is possibly
  10077. already on your <code>$PATH</code> depending on how Synapse was installed.</p>
  10078. <p>Finding your user's <code>access_token</code> is client-dependent, but will usually be shown in the client's settings.</p>
  10079. <h2 id="making-an-admin-api-request"><a class="header" href="#making-an-admin-api-request">Making an Admin API request</a></h2>
  10080. <p>Once you have your <code>access_token</code>, you will need to authenticate each request to an Admin API endpoint by
  10081. providing the token as either a query parameter or a request header. To add it as a request header in cURL:</p>
  10082. <pre><code class="language-sh">curl --header &quot;Authorization: Bearer &lt;access_token&gt;&quot; &lt;the_rest_of_your_API_request&gt;
  10083. </code></pre>
  10084. <p>For more details on access tokens in Matrix, please refer to the complete
  10085. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#using-access-tokens">matrix spec documentation</a>.</p>
  10086. <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>
  10087. <p>This API allows a server administrator to manage the validity of an account. To
  10088. use it, you must enable the account validity feature (under
  10089. <code>account_validity</code>) in Synapse's configuration.</p>
  10090. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10091. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10092. <h2 id="renew-account"><a class="header" href="#renew-account">Renew account</a></h2>
  10093. <p>This API extends the validity of an account by as much time as configured in the
  10094. <code>period</code> parameter from the <code>account_validity</code> configuration.</p>
  10095. <p>The API is:</p>
  10096. <pre><code>POST /_synapse/admin/v1/account_validity/validity
  10097. </code></pre>
  10098. <p>with the following body:</p>
  10099. <pre><code class="language-json">{
  10100. &quot;user_id&quot;: &quot;&lt;user ID for the account to renew&gt;&quot;,
  10101. &quot;expiration_ts&quot;: 0,
  10102. &quot;enable_renewal_emails&quot;: true
  10103. }
  10104. </code></pre>
  10105. <p><code>expiration_ts</code> is an optional parameter and overrides the expiration date,
  10106. which otherwise defaults to now + validity period.</p>
  10107. <p><code>enable_renewal_emails</code> is also an optional parameter and enables/disables
  10108. sending renewal emails to the user. Defaults to true.</p>
  10109. <p>The API returns with the new expiration date for this account, as a timestamp in
  10110. milliseconds since epoch:</p>
  10111. <pre><code class="language-json">{
  10112. &quot;expiration_ts&quot;: 0
  10113. }
  10114. </code></pre>
  10115. <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>
  10116. <p>This API allows a server administrator to manage the background updates being
  10117. run against the database.</p>
  10118. <h2 id="status"><a class="header" href="#status">Status</a></h2>
  10119. <p>This API gets the current status of the background updates.</p>
  10120. <p>The API is:</p>
  10121. <pre><code>GET /_synapse/admin/v1/background_updates/status
  10122. </code></pre>
  10123. <p>Returning:</p>
  10124. <pre><code class="language-json">{
  10125. &quot;enabled&quot;: true,
  10126. &quot;current_updates&quot;: {
  10127. &quot;&lt;db_name&gt;&quot;: {
  10128. &quot;name&quot;: &quot;&lt;background_update_name&gt;&quot;,
  10129. &quot;total_item_count&quot;: 50,
  10130. &quot;total_duration_ms&quot;: 10000.0,
  10131. &quot;average_items_per_ms&quot;: 2.2,
  10132. },
  10133. }
  10134. }
  10135. </code></pre>
  10136. <p><code>enabled</code> whether the background updates are enabled or disabled.</p>
  10137. <p><code>db_name</code> the database name (usually Synapse is configured with a single database named 'master').</p>
  10138. <p>For each update:</p>
  10139. <p><code>name</code> the name of the update.
  10140. <code>total_item_count</code> total number of &quot;items&quot; processed (the meaning of 'items' depends on the update in question).
  10141. <code>total_duration_ms</code> how long the background process has been running, not including time spent sleeping.
  10142. <code>average_items_per_ms</code> how many items are processed per millisecond based on an exponential average.</p>
  10143. <h2 id="enabled"><a class="header" href="#enabled">Enabled</a></h2>
  10144. <p>This API allow pausing background updates.</p>
  10145. <p>Background updates should <em>not</em> be paused for significant periods of time, as
  10146. this can affect the performance of Synapse.</p>
  10147. <p><em>Note</em>: This won't persist over restarts.</p>
  10148. <p><em>Note</em>: This won't cancel any update query that is currently running. This is
  10149. usually fine since most queries are short lived, except for <code>CREATE INDEX</code>
  10150. background updates which won't be cancelled once started.</p>
  10151. <p>The API is:</p>
  10152. <pre><code>POST /_synapse/admin/v1/background_updates/enabled
  10153. </code></pre>
  10154. <p>with the following body:</p>
  10155. <pre><code class="language-json">{
  10156. &quot;enabled&quot;: false
  10157. }
  10158. </code></pre>
  10159. <p><code>enabled</code> sets whether the background updates are enabled or disabled.</p>
  10160. <p>The API returns the <code>enabled</code> param.</p>
  10161. <pre><code class="language-json">{
  10162. &quot;enabled&quot;: false
  10163. }
  10164. </code></pre>
  10165. <p>There is also a <code>GET</code> version which returns the <code>enabled</code> state.</p>
  10166. <h2 id="run"><a class="header" href="#run">Run</a></h2>
  10167. <p>This API schedules a specific background update to run. The job starts immediately after calling the API.</p>
  10168. <p>The API is:</p>
  10169. <pre><code>POST /_synapse/admin/v1/background_updates/start_job
  10170. </code></pre>
  10171. <p>with the following body:</p>
  10172. <pre><code class="language-json">{
  10173. &quot;job_name&quot;: &quot;populate_stats_process_rooms&quot;
  10174. }
  10175. </code></pre>
  10176. <p>The following JSON body parameters are available:</p>
  10177. <ul>
  10178. <li><code>job_name</code> - A string which job to run. Valid values are:
  10179. <ul>
  10180. <li><code>populate_stats_process_rooms</code> - Recalculate the stats for all rooms.</li>
  10181. <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>
  10182. </ul>
  10183. </li>
  10184. </ul>
  10185. <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>
  10186. <p>This API returns information about reported events.</p>
  10187. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10188. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10189. <p>The api is:</p>
  10190. <pre><code>GET /_synapse/admin/v1/event_reports?from=0&amp;limit=10
  10191. </code></pre>
  10192. <p>It returns a JSON body like the following:</p>
  10193. <pre><code class="language-json">{
  10194. &quot;event_reports&quot;: [
  10195. {
  10196. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  10197. &quot;id&quot;: 2,
  10198. &quot;reason&quot;: &quot;foo&quot;,
  10199. &quot;score&quot;: -100,
  10200. &quot;received_ts&quot;: 1570897107409,
  10201. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  10202. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  10203. &quot;name&quot;: &quot;Matrix HQ&quot;,
  10204. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  10205. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  10206. },
  10207. {
  10208. &quot;event_id&quot;: &quot;$3IcdZsDaN_En-S1DF4EMCy3v4gNRKeOJs8W5qTOKj4I&quot;,
  10209. &quot;id&quot;: 3,
  10210. &quot;reason&quot;: &quot;bar&quot;,
  10211. &quot;score&quot;: -100,
  10212. &quot;received_ts&quot;: 1598889612059,
  10213. &quot;canonical_alias&quot;: &quot;#alias2:matrix.org&quot;,
  10214. &quot;room_id&quot;: &quot;!eGvUQuTCkHGVwNMOjv:matrix.org&quot;,
  10215. &quot;name&quot;: &quot;Your room name here&quot;,
  10216. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  10217. &quot;user_id&quot;: &quot;@bar:matrix.org&quot;
  10218. }
  10219. ],
  10220. &quot;next_token&quot;: 2,
  10221. &quot;total&quot;: 4
  10222. }
  10223. </code></pre>
  10224. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again with <code>from</code>
  10225. set to the value of <code>next_token</code>. This will return a new page.</p>
  10226. <p>If the endpoint does not return a <code>next_token</code> then there are no more reports to
  10227. paginate through.</p>
  10228. <p><strong>URL parameters:</strong></p>
  10229. <ul>
  10230. <li><code>limit</code>: integer - Is optional but is used for pagination, denoting the maximum number
  10231. of items to return in this call. Defaults to <code>100</code>.</li>
  10232. <li><code>from</code>: integer - Is optional but used for pagination, denoting the offset in the
  10233. returned results. This should be treated as an opaque value and not explicitly set to
  10234. anything other than the return value of <code>next_token</code> from a previous call. Defaults to <code>0</code>.</li>
  10235. <li><code>dir</code>: string - Direction of event report order. Whether to fetch the most recent
  10236. first (<code>b</code>) or the oldest first (<code>f</code>). Defaults to <code>b</code>.</li>
  10237. <li><code>user_id</code>: string - Is optional and filters to only return users with user IDs that
  10238. contain this value. This is the user who reported the event and wrote the reason.</li>
  10239. <li><code>room_id</code>: string - Is optional and filters to only return rooms with room IDs that
  10240. contain this value.</li>
  10241. </ul>
  10242. <p><strong>Response</strong></p>
  10243. <p>The following fields are returned in the JSON response body:</p>
  10244. <ul>
  10245. <li><code>id</code>: integer - ID of event report.</li>
  10246. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  10247. report was sent.</li>
  10248. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  10249. <li><code>name</code>: string - The name of the room.</li>
  10250. <li><code>event_id</code>: string - The ID of the reported event.</li>
  10251. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  10252. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank or <code>null</code>.</li>
  10253. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  10254. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;. May be <code>null</code>.</li>
  10255. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  10256. was reported.</li>
  10257. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  10258. have a canonical alias set.</li>
  10259. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  10260. <li><code>total</code>: integer - Total number of event reports related to the query
  10261. (<code>user_id</code> and <code>room_id</code>).</li>
  10262. </ul>
  10263. <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>
  10264. <p>This API returns information about a specific event report.</p>
  10265. <p>The api is:</p>
  10266. <pre><code>GET /_synapse/admin/v1/event_reports/&lt;report_id&gt;
  10267. </code></pre>
  10268. <p>It returns a JSON body like the following:</p>
  10269. <pre><code class="language-json">{
  10270. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  10271. &quot;event_json&quot;: {
  10272. &quot;auth_events&quot;: [
  10273. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;,
  10274. &quot;$oggsNXxzPFRE3y53SUNd7nsj69-QzKv03a1RucHu-ws&quot;
  10275. ],
  10276. &quot;content&quot;: {
  10277. &quot;body&quot;: &quot;matrix.org: This Week in Matrix&quot;,
  10278. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  10279. &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;,
  10280. &quot;msgtype&quot;: &quot;m.notice&quot;
  10281. },
  10282. &quot;depth&quot;: 546,
  10283. &quot;hashes&quot;: {
  10284. &quot;sha256&quot;: &quot;xK1//xnmvHJIOvbgXlkI8eEqdvoMmihVDJ9J4SNlsAw&quot;
  10285. },
  10286. &quot;origin&quot;: &quot;matrix.org&quot;,
  10287. &quot;origin_server_ts&quot;: 1592291711430,
  10288. &quot;prev_events&quot;: [
  10289. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;
  10290. ],
  10291. &quot;prev_state&quot;: [],
  10292. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  10293. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  10294. &quot;signatures&quot;: {
  10295. &quot;matrix.org&quot;: {
  10296. &quot;ed25519:a_JaEG&quot;: &quot;cs+OUKW/iHx5pEidbWxh0UiNNHwe46Ai9LwNz+Ah16aWDNszVIe2gaAcVZfvNsBhakQTew51tlKmL2kspXk/Dg&quot;
  10297. }
  10298. },
  10299. &quot;type&quot;: &quot;m.room.message&quot;,
  10300. &quot;unsigned&quot;: {
  10301. &quot;age_ts&quot;: 1592291711430
  10302. }
  10303. },
  10304. &quot;id&quot;: &lt;report_id&gt;,
  10305. &quot;reason&quot;: &quot;foo&quot;,
  10306. &quot;score&quot;: -100,
  10307. &quot;received_ts&quot;: 1570897107409,
  10308. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  10309. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  10310. &quot;name&quot;: &quot;Matrix HQ&quot;,
  10311. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  10312. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  10313. }
  10314. </code></pre>
  10315. <p><strong>URL parameters:</strong></p>
  10316. <ul>
  10317. <li><code>report_id</code>: string - The ID of the event report.</li>
  10318. </ul>
  10319. <p><strong>Response</strong></p>
  10320. <p>The following fields are returned in the JSON response body:</p>
  10321. <ul>
  10322. <li><code>id</code>: integer - ID of event report.</li>
  10323. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  10324. report was sent.</li>
  10325. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  10326. <li><code>name</code>: string - The name of the room.</li>
  10327. <li><code>event_id</code>: string - The ID of the reported event.</li>
  10328. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  10329. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank.</li>
  10330. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  10331. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;.</li>
  10332. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  10333. was reported.</li>
  10334. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  10335. have a canonical alias set.</li>
  10336. <li><code>event_json</code>: object - Details of the original event that was reported.</li>
  10337. </ul>
  10338. <div style="break-before: page; page-break-before: always;"></div><h1 id="querying-media"><a class="header" href="#querying-media">Querying media</a></h1>
  10339. <p>These APIs allow extracting media information from the homeserver.</p>
  10340. <p>Details about the format of the <code>media_id</code> and storage of the media in the file system
  10341. are documented under <a href="admin_api/../media_repository.html">media repository</a>.</p>
  10342. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10343. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10344. <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>
  10345. <p>This API gets a list of known media in a room.
  10346. However, it only shows media from unencrypted events or rooms.</p>
  10347. <p>The API is:</p>
  10348. <pre><code>GET /_synapse/admin/v1/room/&lt;room_id&gt;/media
  10349. </code></pre>
  10350. <p>The API returns a JSON body like the following:</p>
  10351. <pre><code class="language-json">{
  10352. &quot;local&quot;: [
  10353. &quot;mxc://localhost/xwvutsrqponmlkjihgfedcba&quot;,
  10354. &quot;mxc://localhost/abcdefghijklmnopqrstuvwx&quot;
  10355. ],
  10356. &quot;remote&quot;: [
  10357. &quot;mxc://matrix.org/xwvutsrqponmlkjihgfedcba&quot;,
  10358. &quot;mxc://matrix.org/abcdefghijklmnopqrstuvwx&quot;
  10359. ]
  10360. }
  10361. </code></pre>
  10362. <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>
  10363. <p>Listing all media that has been uploaded by a local user can be achieved through
  10364. the use of the
  10365. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>
  10366. Admin API.</p>
  10367. <h1 id="quarantine-media"><a class="header" href="#quarantine-media">Quarantine media</a></h1>
  10368. <p>Quarantining media means that it is marked as inaccessible by users. It applies
  10369. to any local media, and any locally-cached copies of remote media.</p>
  10370. <p>The media file itself (and any thumbnails) is not deleted from the server.</p>
  10371. <h2 id="quarantining-media-by-id"><a class="header" href="#quarantining-media-by-id">Quarantining media by ID</a></h2>
  10372. <p>This API quarantines a single piece of local or remote media.</p>
  10373. <p>Request:</p>
  10374. <pre><code>POST /_synapse/admin/v1/media/quarantine/&lt;server_name&gt;/&lt;media_id&gt;
  10375. {}
  10376. </code></pre>
  10377. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  10378. form of <code>abcdefg12345...</code>.</p>
  10379. <p>Response:</p>
  10380. <pre><code class="language-json">{}
  10381. </code></pre>
  10382. <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>
  10383. <p>This API removes a single piece of local or remote media from quarantine.</p>
  10384. <p>Request:</p>
  10385. <pre><code>POST /_synapse/admin/v1/media/unquarantine/&lt;server_name&gt;/&lt;media_id&gt;
  10386. {}
  10387. </code></pre>
  10388. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  10389. form of <code>abcdefg12345...</code>.</p>
  10390. <p>Response:</p>
  10391. <pre><code class="language-json">{}
  10392. </code></pre>
  10393. <h2 id="quarantining-media-in-a-room"><a class="header" href="#quarantining-media-in-a-room">Quarantining media in a room</a></h2>
  10394. <p>This API quarantines all local and remote media in a room.</p>
  10395. <p>Request:</p>
  10396. <pre><code>POST /_synapse/admin/v1/room/&lt;room_id&gt;/media/quarantine
  10397. {}
  10398. </code></pre>
  10399. <p>Where <code>room_id</code> is in the form of <code>!roomid12345:example.org</code>.</p>
  10400. <p>Response:</p>
  10401. <pre><code class="language-json">{
  10402. &quot;num_quarantined&quot;: 10
  10403. }
  10404. </code></pre>
  10405. <p>The following fields are returned in the JSON response body:</p>
  10406. <ul>
  10407. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  10408. </ul>
  10409. <p>Note that there is a legacy endpoint, <code>POST /_synapse/admin/v1/quarantine_media/&lt;room_id&gt;</code>, that operates the same.
  10410. However, it is deprecated and may be removed in a future release.</p>
  10411. <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>
  10412. <p>This API quarantines all <em>local</em> media that a <em>local</em> user has uploaded. That is to say, if
  10413. you would like to quarantine media uploaded by a user on a remote homeserver, you should
  10414. instead use one of the other APIs.</p>
  10415. <p>Request:</p>
  10416. <pre><code>POST /_synapse/admin/v1/user/&lt;user_id&gt;/media/quarantine
  10417. {}
  10418. </code></pre>
  10419. <p>URL Parameters</p>
  10420. <ul>
  10421. <li><code>user_id</code>: string - User ID in the form of <code>@bob:example.org</code></li>
  10422. </ul>
  10423. <p>Response:</p>
  10424. <pre><code class="language-json">{
  10425. &quot;num_quarantined&quot;: 10
  10426. }
  10427. </code></pre>
  10428. <p>The following fields are returned in the JSON response body:</p>
  10429. <ul>
  10430. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  10431. </ul>
  10432. <h2 id="protecting-media-from-being-quarantined"><a class="header" href="#protecting-media-from-being-quarantined">Protecting media from being quarantined</a></h2>
  10433. <p>This API protects a single piece of local media from being quarantined using the
  10434. above APIs. This is useful for sticker packs and other shared media which you do
  10435. not want to get quarantined, especially when
  10436. <a href="admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantining media in a room</a>.</p>
  10437. <p>Request:</p>
  10438. <pre><code>POST /_synapse/admin/v1/media/protect/&lt;media_id&gt;
  10439. {}
  10440. </code></pre>
  10441. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  10442. <p>Response:</p>
  10443. <pre><code class="language-json">{}
  10444. </code></pre>
  10445. <h2 id="unprotecting-media-from-being-quarantined"><a class="header" href="#unprotecting-media-from-being-quarantined">Unprotecting media from being quarantined</a></h2>
  10446. <p>This API reverts the protection of a media.</p>
  10447. <p>Request:</p>
  10448. <pre><code>POST /_synapse/admin/v1/media/unprotect/&lt;media_id&gt;
  10449. {}
  10450. </code></pre>
  10451. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  10452. <p>Response:</p>
  10453. <pre><code class="language-json">{}
  10454. </code></pre>
  10455. <h1 id="delete-local-media"><a class="header" href="#delete-local-media">Delete local media</a></h1>
  10456. <p>This API deletes the <em>local</em> media from the disk of your own server.
  10457. This includes any local thumbnails and copies of media downloaded from
  10458. remote homeservers.
  10459. This API will not affect media that has been uploaded to external
  10460. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).
  10461. See also <a href="admin_api/media_admin_api.html#purge-remote-media-api">Purge Remote Media API</a>.</p>
  10462. <h2 id="delete-a-specific-local-media"><a class="header" href="#delete-a-specific-local-media">Delete a specific local media</a></h2>
  10463. <p>Delete a specific <code>media_id</code>.</p>
  10464. <p>Request:</p>
  10465. <pre><code>DELETE /_synapse/admin/v1/media/&lt;server_name&gt;/&lt;media_id&gt;
  10466. {}
  10467. </code></pre>
  10468. <p>URL Parameters</p>
  10469. <ul>
  10470. <li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>)</li>
  10471. <li><code>media_id</code>: string - The ID of the media (e.g <code>abcdefghijklmnopqrstuvwx</code>)</li>
  10472. </ul>
  10473. <p>Response:</p>
  10474. <pre><code class="language-json">{
  10475. &quot;deleted_media&quot;: [
  10476. &quot;abcdefghijklmnopqrstuvwx&quot;
  10477. ],
  10478. &quot;total&quot;: 1
  10479. }
  10480. </code></pre>
  10481. <p>The following fields are returned in the JSON response body:</p>
  10482. <ul>
  10483. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  10484. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  10485. </ul>
  10486. <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>
  10487. <p>Request:</p>
  10488. <pre><code>POST /_synapse/admin/v1/media/&lt;server_name&gt;/delete?before_ts=&lt;before_ts&gt;
  10489. {}
  10490. </code></pre>
  10491. <p>URL Parameters</p>
  10492. <ul>
  10493. <li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>).</li>
  10494. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  10495. Files that were last used before this timestamp will be deleted. It is the timestamp of
  10496. last access, not the timestamp when the file was created.</li>
  10497. <li><code>size_gt</code>: Optional - string representing a positive integer - Size of the media in bytes.
  10498. Files that are larger will be deleted. Defaults to <code>0</code>.</li>
  10499. <li><code>keep_profiles</code>: Optional - string representing a boolean - Switch to also delete files
  10500. that are still used in image data (e.g user profile, room avatar).
  10501. If <code>false</code> these files will be deleted. Defaults to <code>true</code>.</li>
  10502. </ul>
  10503. <p>Response:</p>
  10504. <pre><code class="language-json">{
  10505. &quot;deleted_media&quot;: [
  10506. &quot;abcdefghijklmnopqrstuvwx&quot;,
  10507. &quot;abcdefghijklmnopqrstuvwz&quot;
  10508. ],
  10509. &quot;total&quot;: 2
  10510. }
  10511. </code></pre>
  10512. <p>The following fields are returned in the JSON response body:</p>
  10513. <ul>
  10514. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  10515. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  10516. </ul>
  10517. <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>
  10518. <p>You can find details of how to delete multiple media uploaded by a user in
  10519. <a href="admin_api/user_admin_api.html#delete-media-uploaded-by-a-user">User Admin API</a>.</p>
  10520. <h1 id="purge-remote-media-api"><a class="header" href="#purge-remote-media-api">Purge Remote Media API</a></h1>
  10521. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  10522. <p>The API is:</p>
  10523. <pre><code>POST /_synapse/admin/v1/purge_media_cache?before_ts=&lt;unix_timestamp_in_ms&gt;
  10524. {}
  10525. </code></pre>
  10526. <p>URL Parameters</p>
  10527. <ul>
  10528. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  10529. All cached media that was last accessed before this timestamp will be removed.</li>
  10530. </ul>
  10531. <p>Response:</p>
  10532. <pre><code class="language-json">{
  10533. &quot;deleted&quot;: 10
  10534. }
  10535. </code></pre>
  10536. <p>The following fields are returned in the JSON response body:</p>
  10537. <ul>
  10538. <li><code>deleted</code>: integer - The number of media items successfully deleted</li>
  10539. </ul>
  10540. <p>If the user re-requests purged remote media, synapse will re-request the media
  10541. from the originating server.</p>
  10542. <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>
  10543. <p>The purge history API allows server admins to purge historic events from their
  10544. database, reclaiming disk space.</p>
  10545. <p>Depending on the amount of history being purged a call to the API may take
  10546. several minutes or longer. During this period users will not be able to
  10547. paginate further back in the room from the point being purged from.</p>
  10548. <p>Note that Synapse requires at least one message in each room, so it will never
  10549. delete the last message in a room.</p>
  10550. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10551. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10552. <p>The API is:</p>
  10553. <pre><code>POST /_synapse/admin/v1/purge_history/&lt;room_id&gt;[/&lt;event_id&gt;]
  10554. </code></pre>
  10555. <p>By default, events sent by local users are not deleted, as they may represent
  10556. the only copies of this content in existence. (Events sent by remote users are
  10557. deleted.)</p>
  10558. <p>Room state data (such as joins, leaves, topic) is always preserved.</p>
  10559. <p>To delete local message events as well, set <code>delete_local_events</code> in the body:</p>
  10560. <pre><code class="language-json">{
  10561. &quot;delete_local_events&quot;: true
  10562. }
  10563. </code></pre>
  10564. <p>The caller must specify the point in the room to purge up to. This can be
  10565. specified by including an event_id in the URI, or by setting a
  10566. <code>purge_up_to_event_id</code> or <code>purge_up_to_ts</code> in the request body. If an event
  10567. id is given, that event (and others at the same graph depth) will be retained.
  10568. If <code>purge_up_to_ts</code> is given, it should be a timestamp since the unix epoch,
  10569. in milliseconds.</p>
  10570. <p>The API starts the purge running, and returns immediately with a JSON body with
  10571. a purge id:</p>
  10572. <pre><code class="language-json">{
  10573. &quot;purge_id&quot;: &quot;&lt;opaque id&gt;&quot;
  10574. }
  10575. </code></pre>
  10576. <h2 id="purge-status-query"><a class="header" href="#purge-status-query">Purge status query</a></h2>
  10577. <p>It is possible to poll for updates on recent purges with a second API;</p>
  10578. <pre><code>GET /_synapse/admin/v1/purge_history_status/&lt;purge_id&gt;
  10579. </code></pre>
  10580. <p>This API returns a JSON body like the following:</p>
  10581. <pre><code class="language-json">{
  10582. &quot;status&quot;: &quot;active&quot;
  10583. }
  10584. </code></pre>
  10585. <p>The status will be one of <code>active</code>, <code>complete</code>, or <code>failed</code>.</p>
  10586. <p>If <code>status</code> is <code>failed</code> there will be a string <code>error</code> with the error message.</p>
  10587. <h2 id="reclaim-disk-space-postgres"><a class="header" href="#reclaim-disk-space-postgres">Reclaim disk space (Postgres)</a></h2>
  10588. <p>To reclaim the disk space and return it to the operating system, you need to run
  10589. <code>VACUUM FULL;</code> on the database.</p>
  10590. <p><a href="https://www.postgresql.org/docs/current/sql-vacuum.html">https://www.postgresql.org/docs/current/sql-vacuum.html</a></p>
  10591. <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>
  10592. <p>This API allows for the creation of users in an administrative and
  10593. non-interactive way. This is generally used for bootstrapping a Synapse
  10594. instance with administrator accounts.</p>
  10595. <p>To authenticate yourself to the server, you will need both the shared secret
  10596. (<code>registration_shared_secret</code> in the homeserver configuration), and a
  10597. one-time nonce. If the registration shared secret is not configured, this API
  10598. is not enabled.</p>
  10599. <p>To fetch the nonce, you need to request one from the API:</p>
  10600. <pre><code>&gt; GET /_synapse/admin/v1/register
  10601. &lt; {&quot;nonce&quot;: &quot;thisisanonce&quot;}
  10602. </code></pre>
  10603. <p>Once you have the nonce, you can make a <code>POST</code> to the same URL with a JSON
  10604. body containing the nonce, username, password, whether they are an admin
  10605. (optional, False by default), and a HMAC digest of the content. Also you can
  10606. set the displayname (optional, <code>username</code> by default).</p>
  10607. <p>As an example:</p>
  10608. <pre><code>&gt; POST /_synapse/admin/v1/register
  10609. &gt; {
  10610. &quot;nonce&quot;: &quot;thisisanonce&quot;,
  10611. &quot;username&quot;: &quot;pepper_roni&quot;,
  10612. &quot;displayname&quot;: &quot;Pepper Roni&quot;,
  10613. &quot;password&quot;: &quot;pizza&quot;,
  10614. &quot;admin&quot;: true,
  10615. &quot;mac&quot;: &quot;mac_digest_here&quot;
  10616. }
  10617. &lt; {
  10618. &quot;access_token&quot;: &quot;token_here&quot;,
  10619. &quot;user_id&quot;: &quot;@pepper_roni:localhost&quot;,
  10620. &quot;home_server&quot;: &quot;test&quot;,
  10621. &quot;device_id&quot;: &quot;device_id_here&quot;
  10622. }
  10623. </code></pre>
  10624. <p>The MAC is the hex digest output of the HMAC-SHA1 algorithm, with the key being
  10625. the shared secret and the content being the nonce, user, password, either the
  10626. string &quot;admin&quot; or &quot;notadmin&quot;, and optionally the user_type
  10627. each separated by NULs. For an example of generation in Python:</p>
  10628. <pre><code class="language-python">import hmac, hashlib
  10629. def generate_mac(nonce, user, password, admin=False, user_type=None):
  10630. mac = hmac.new(
  10631. key=shared_secret,
  10632. digestmod=hashlib.sha1,
  10633. )
  10634. mac.update(nonce.encode('utf8'))
  10635. mac.update(b&quot;\x00&quot;)
  10636. mac.update(user.encode('utf8'))
  10637. mac.update(b&quot;\x00&quot;)
  10638. mac.update(password.encode('utf8'))
  10639. mac.update(b&quot;\x00&quot;)
  10640. mac.update(b&quot;admin&quot; if admin else b&quot;notadmin&quot;)
  10641. if user_type:
  10642. mac.update(b&quot;\x00&quot;)
  10643. mac.update(user_type.encode('utf8'))
  10644. return mac.hexdigest()
  10645. </code></pre>
  10646. <div style="break-before: page; page-break-before: always;"></div><h1 id="registration-tokens"><a class="header" href="#registration-tokens">Registration Tokens</a></h1>
  10647. <p>This API allows you to manage tokens which can be used to authenticate
  10648. registration requests, as proposed in
  10649. <a href="https://github.com/matrix-org/matrix-doc/blob/main/proposals/3231-token-authenticated-registration.md">MSC3231</a>.
  10650. To use it, you will need to enable the <code>registration_requires_token</code> config
  10651. option, and authenticate by providing an <code>access_token</code> for a server admin:
  10652. see <a href="usage/administration/admin_api/../../usage/administration/admin_api">Admin API</a>.
  10653. Note that this API is still experimental; not all clients may support it yet.</p>
  10654. <h2 id="registration-token-objects"><a class="header" href="#registration-token-objects">Registration token objects</a></h2>
  10655. <p>Most endpoints make use of JSON objects that contain details about tokens.
  10656. These objects have the following fields:</p>
  10657. <ul>
  10658. <li><code>token</code>: The token which can be used to authenticate registration.</li>
  10659. <li><code>uses_allowed</code>: The number of times the token can be used to complete a
  10660. registration before it becomes invalid.</li>
  10661. <li><code>pending</code>: The number of pending uses the token has. When someone uses
  10662. the token to authenticate themselves, the pending counter is incremented
  10663. so that the token is not used more than the permitted number of times.
  10664. When the person completes registration the pending counter is decremented,
  10665. and the completed counter is incremented.</li>
  10666. <li><code>completed</code>: The number of times the token has been used to successfully
  10667. complete a registration.</li>
  10668. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  10669. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  10670. To convert this into a human-readable form you can remove the milliseconds
  10671. and use the <code>date</code> command. For example, <code>date -d '@1625394937'</code>.</li>
  10672. </ul>
  10673. <h2 id="list-all-tokens"><a class="header" href="#list-all-tokens">List all tokens</a></h2>
  10674. <p>Lists all tokens and details about them. If the request is successful, the top
  10675. level JSON object will have a <code>registration_tokens</code> key which is an array of
  10676. registration token objects.</p>
  10677. <pre><code>GET /_synapse/admin/v1/registration_tokens
  10678. </code></pre>
  10679. <p>Optional query parameters:</p>
  10680. <ul>
  10681. <li><code>valid</code>: <code>true</code> or <code>false</code>. If <code>true</code>, only valid tokens are returned.
  10682. If <code>false</code>, only tokens that have expired or have had all uses exhausted are
  10683. returned. If omitted, all tokens are returned regardless of validity.</li>
  10684. </ul>
  10685. <p>Example:</p>
  10686. <pre><code>GET /_synapse/admin/v1/registration_tokens
  10687. </code></pre>
  10688. <pre><code>200 OK
  10689. {
  10690. &quot;registration_tokens&quot;: [
  10691. {
  10692. &quot;token&quot;: &quot;abcd&quot;,
  10693. &quot;uses_allowed&quot;: 3,
  10694. &quot;pending&quot;: 0,
  10695. &quot;completed&quot;: 1,
  10696. &quot;expiry_time&quot;: null
  10697. },
  10698. {
  10699. &quot;token&quot;: &quot;pqrs&quot;,
  10700. &quot;uses_allowed&quot;: 2,
  10701. &quot;pending&quot;: 1,
  10702. &quot;completed&quot;: 1,
  10703. &quot;expiry_time&quot;: null
  10704. },
  10705. {
  10706. &quot;token&quot;: &quot;wxyz&quot;,
  10707. &quot;uses_allowed&quot;: null,
  10708. &quot;pending&quot;: 0,
  10709. &quot;completed&quot;: 9,
  10710. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  10711. }
  10712. ]
  10713. }
  10714. </code></pre>
  10715. <p>Example using the <code>valid</code> query parameter:</p>
  10716. <pre><code>GET /_synapse/admin/v1/registration_tokens?valid=false
  10717. </code></pre>
  10718. <pre><code>200 OK
  10719. {
  10720. &quot;registration_tokens&quot;: [
  10721. {
  10722. &quot;token&quot;: &quot;pqrs&quot;,
  10723. &quot;uses_allowed&quot;: 2,
  10724. &quot;pending&quot;: 1,
  10725. &quot;completed&quot;: 1,
  10726. &quot;expiry_time&quot;: null
  10727. },
  10728. {
  10729. &quot;token&quot;: &quot;wxyz&quot;,
  10730. &quot;uses_allowed&quot;: null,
  10731. &quot;pending&quot;: 0,
  10732. &quot;completed&quot;: 9,
  10733. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  10734. }
  10735. ]
  10736. }
  10737. </code></pre>
  10738. <h2 id="get-one-token"><a class="header" href="#get-one-token">Get one token</a></h2>
  10739. <p>Get details about a single token. If the request is successful, the response
  10740. body will be a registration token object.</p>
  10741. <pre><code>GET /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  10742. </code></pre>
  10743. <p>Path parameters:</p>
  10744. <ul>
  10745. <li><code>token</code>: The registration token to return details of.</li>
  10746. </ul>
  10747. <p>Example:</p>
  10748. <pre><code>GET /_synapse/admin/v1/registration_tokens/abcd
  10749. </code></pre>
  10750. <pre><code>200 OK
  10751. {
  10752. &quot;token&quot;: &quot;abcd&quot;,
  10753. &quot;uses_allowed&quot;: 3,
  10754. &quot;pending&quot;: 0,
  10755. &quot;completed&quot;: 1,
  10756. &quot;expiry_time&quot;: null
  10757. }
  10758. </code></pre>
  10759. <h2 id="create-token"><a class="header" href="#create-token">Create token</a></h2>
  10760. <p>Create a new registration token. If the request is successful, the newly created
  10761. token will be returned as a registration token object in the response body.</p>
  10762. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  10763. </code></pre>
  10764. <p>The request body must be a JSON object and can contain the following fields:</p>
  10765. <ul>
  10766. <li><code>token</code>: The registration token. A string of no more than 64 characters that
  10767. consists only of characters matched by the regex <code>[A-Za-z0-9._~-]</code>.
  10768. Default: randomly generated.</li>
  10769. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  10770. a registration before it becomes invalid.
  10771. Default: <code>null</code> (unlimited uses).</li>
  10772. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  10773. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  10774. You could use, for example, <code>date '+%s000' -d 'tomorrow'</code>.
  10775. Default: <code>null</code> (token does not expire).</li>
  10776. <li><code>length</code>: The length of the token randomly generated if <code>token</code> is not
  10777. specified. Must be between 1 and 64 inclusive. Default: <code>16</code>.</li>
  10778. </ul>
  10779. <p>If a field is omitted the default is used.</p>
  10780. <p>Example using defaults:</p>
  10781. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  10782. {}
  10783. </code></pre>
  10784. <pre><code>200 OK
  10785. {
  10786. &quot;token&quot;: &quot;0M-9jbkf2t_Tgiw1&quot;,
  10787. &quot;uses_allowed&quot;: null,
  10788. &quot;pending&quot;: 0,
  10789. &quot;completed&quot;: 0,
  10790. &quot;expiry_time&quot;: null
  10791. }
  10792. </code></pre>
  10793. <p>Example specifying some fields:</p>
  10794. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  10795. {
  10796. &quot;token&quot;: &quot;defg&quot;,
  10797. &quot;uses_allowed&quot;: 1
  10798. }
  10799. </code></pre>
  10800. <pre><code>200 OK
  10801. {
  10802. &quot;token&quot;: &quot;defg&quot;,
  10803. &quot;uses_allowed&quot;: 1,
  10804. &quot;pending&quot;: 0,
  10805. &quot;completed&quot;: 0,
  10806. &quot;expiry_time&quot;: null
  10807. }
  10808. </code></pre>
  10809. <h2 id="update-token"><a class="header" href="#update-token">Update token</a></h2>
  10810. <p>Update the number of allowed uses or expiry time of a token. If the request is
  10811. successful, the updated token will be returned as a registration token object
  10812. in the response body.</p>
  10813. <pre><code>PUT /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  10814. </code></pre>
  10815. <p>Path parameters:</p>
  10816. <ul>
  10817. <li><code>token</code>: The registration token to update.</li>
  10818. </ul>
  10819. <p>The request body must be a JSON object and can contain the following fields:</p>
  10820. <ul>
  10821. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  10822. a registration before it becomes invalid. By setting <code>uses_allowed</code> to <code>0</code>
  10823. the token can be easily made invalid without deleting it.
  10824. If <code>null</code> the token will have an unlimited number of uses.</li>
  10825. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  10826. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  10827. If <code>null</code> the token will not expire.</li>
  10828. </ul>
  10829. <p>If a field is omitted its value is not modified.</p>
  10830. <p>Example:</p>
  10831. <pre><code>PUT /_synapse/admin/v1/registration_tokens/defg
  10832. {
  10833. &quot;expiry_time&quot;: 4781243146000 // 2121-07-06 11:05:46 UTC
  10834. }
  10835. </code></pre>
  10836. <pre><code>200 OK
  10837. {
  10838. &quot;token&quot;: &quot;defg&quot;,
  10839. &quot;uses_allowed&quot;: 1,
  10840. &quot;pending&quot;: 0,
  10841. &quot;completed&quot;: 0,
  10842. &quot;expiry_time&quot;: 4781243146000
  10843. }
  10844. </code></pre>
  10845. <h2 id="delete-token"><a class="header" href="#delete-token">Delete token</a></h2>
  10846. <p>Delete a registration token. If the request is successful, the response body
  10847. will be an empty JSON object.</p>
  10848. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  10849. </code></pre>
  10850. <p>Path parameters:</p>
  10851. <ul>
  10852. <li><code>token</code>: The registration token to delete.</li>
  10853. </ul>
  10854. <p>Example:</p>
  10855. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/wxyz
  10856. </code></pre>
  10857. <pre><code>200 OK
  10858. {}
  10859. </code></pre>
  10860. <h2 id="errors"><a class="header" href="#errors">Errors</a></h2>
  10861. <p>If a request fails a &quot;standard error response&quot; will be returned as defined in
  10862. the <a href="https://matrix.org/docs/spec/client_server/r0.6.1#api-standards">Matrix Client-Server API specification</a>.</p>
  10863. <p>For example, if the token specified in a path parameter does not exist a
  10864. <code>404 Not Found</code> error will be returned.</p>
  10865. <pre><code>GET /_synapse/admin/v1/registration_tokens/1234
  10866. </code></pre>
  10867. <pre><code>404 Not Found
  10868. {
  10869. &quot;errcode&quot;: &quot;M_NOT_FOUND&quot;,
  10870. &quot;error&quot;: &quot;No such registration token: 1234&quot;
  10871. }
  10872. </code></pre>
  10873. <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>
  10874. <p>This API allows an administrator to join an user account with a given <code>user_id</code>
  10875. to a room with a given <code>room_id_or_alias</code>. You can only modify the membership of
  10876. local users. The server administrator must be in the room and have permission to
  10877. invite users.</p>
  10878. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10879. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10880. <h2 id="parameters"><a class="header" href="#parameters">Parameters</a></h2>
  10881. <p>The following parameters are available:</p>
  10882. <ul>
  10883. <li><code>user_id</code> - Fully qualified user: for example, <code>@user:server.com</code>.</li>
  10884. <li><code>room_id_or_alias</code> - The room identifier or alias to join: for example,
  10885. <code>!636q39766251:server.com</code>.</li>
  10886. </ul>
  10887. <h2 id="usage-1"><a class="header" href="#usage-1">Usage</a></h2>
  10888. <pre><code>POST /_synapse/admin/v1/join/&lt;room_id_or_alias&gt;
  10889. {
  10890. &quot;user_id&quot;: &quot;@user:server.com&quot;
  10891. }
  10892. </code></pre>
  10893. <p>Response:</p>
  10894. <pre><code class="language-json">{
  10895. &quot;room_id&quot;: &quot;!636q39766251:server.com&quot;
  10896. }
  10897. </code></pre>
  10898. <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>
  10899. <p>The List Room admin API allows server admins to get a list of rooms on their
  10900. server. There are various parameters available that allow for filtering and
  10901. sorting the returned list. This API supports pagination.</p>
  10902. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10903. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10904. <p><strong>Parameters</strong></p>
  10905. <p>The following query parameters are available:</p>
  10906. <ul>
  10907. <li>
  10908. <p><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</p>
  10909. </li>
  10910. <li>
  10911. <p><code>limit</code> - Maximum amount of rooms to return. Defaults to <code>100</code>.</p>
  10912. </li>
  10913. <li>
  10914. <p><code>order_by</code> - The method in which to sort the returned list of rooms. Valid values are:</p>
  10915. <ul>
  10916. <li><code>alphabetical</code> - Same as <code>name</code>. This is deprecated.</li>
  10917. <li><code>size</code> - Same as <code>joined_members</code>. This is deprecated.</li>
  10918. <li><code>name</code> - Rooms are ordered alphabetically by room name. This is the default.</li>
  10919. <li><code>canonical_alias</code> - Rooms are ordered alphabetically by main alias address of the room.</li>
  10920. <li><code>joined_members</code> - Rooms are ordered by the number of members. Largest to smallest.</li>
  10921. <li><code>joined_local_members</code> - Rooms are ordered by the number of local members. Largest to smallest.</li>
  10922. <li><code>version</code> - Rooms are ordered by room version. Largest to smallest.</li>
  10923. <li><code>creator</code> - Rooms are ordered alphabetically by creator of the room.</li>
  10924. <li><code>encryption</code> - Rooms are ordered alphabetically by the end-to-end encryption algorithm.</li>
  10925. <li><code>federatable</code> - Rooms are ordered by whether the room is federatable.</li>
  10926. <li><code>public</code> - Rooms are ordered by visibility in room list.</li>
  10927. <li><code>join_rules</code> - Rooms are ordered alphabetically by join rules of the room.</li>
  10928. <li><code>guest_access</code> - Rooms are ordered alphabetically by guest access option of the room.</li>
  10929. <li><code>history_visibility</code> - Rooms are ordered alphabetically by visibility of history of the room.</li>
  10930. <li><code>state_events</code> - Rooms are ordered by number of state events. Largest to smallest.</li>
  10931. </ul>
  10932. </li>
  10933. <li>
  10934. <p><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  10935. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  10936. </li>
  10937. <li>
  10938. <p><code>search_term</code> - Filter rooms by their room name, canonical alias and room id.
  10939. Specifically, rooms are selected if the search term is contained in</p>
  10940. <ul>
  10941. <li>the room's name,</li>
  10942. <li>the local part of the room's canonical alias, or</li>
  10943. <li>the complete (local and server part) room's id (case sensitive).</li>
  10944. </ul>
  10945. <p>Defaults to no filtering.</p>
  10946. </li>
  10947. </ul>
  10948. <p><strong>Response</strong></p>
  10949. <p>The following fields are possible in the JSON response body:</p>
  10950. <ul>
  10951. <li><code>rooms</code> - An array of objects, each containing information about a room.
  10952. <ul>
  10953. <li>Room objects contain the following fields:
  10954. <ul>
  10955. <li><code>room_id</code> - The ID of the room.</li>
  10956. <li><code>name</code> - The name of the room.</li>
  10957. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  10958. <li><code>joined_members</code> - How many users are currently in the room.</li>
  10959. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  10960. <li><code>version</code> - The version of the room as a string.</li>
  10961. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  10962. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  10963. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  10964. <li><code>public</code> - Whether the room is visible in room directory.</li>
  10965. <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>
  10966. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  10967. <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>
  10968. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  10969. </ul>
  10970. </li>
  10971. </ul>
  10972. </li>
  10973. <li><code>offset</code> - The current pagination offset in rooms. This parameter should be
  10974. used instead of <code>next_token</code> for room offset as <code>next_token</code> is
  10975. not intended to be parsed.</li>
  10976. <li><code>total_rooms</code> - The total number of rooms this query can return. Using this
  10977. and <code>offset</code>, you have enough information to know the current
  10978. progression through the list.</li>
  10979. <li><code>next_batch</code> - If this field is present, we know that there are potentially
  10980. more rooms on the server that did not all fit into this response.
  10981. We can use <code>next_batch</code> to get the &quot;next page&quot; of results. To do
  10982. so, simply repeat your request, setting the <code>from</code> parameter to
  10983. the value of <code>next_batch</code>.</li>
  10984. <li><code>prev_batch</code> - If this field is present, it is possible to paginate backwards.
  10985. Use <code>prev_batch</code> for the <code>from</code> value in the next request to
  10986. get the &quot;previous page&quot; of results.</li>
  10987. </ul>
  10988. <p>The API is:</p>
  10989. <p>A standard request with no filtering:</p>
  10990. <pre><code>GET /_synapse/admin/v1/rooms
  10991. </code></pre>
  10992. <p>A response body like the following is returned:</p>
  10993. <pre><code class="language-json">{
  10994. &quot;rooms&quot;: [
  10995. {
  10996. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  10997. &quot;name&quot;: &quot;Matrix HQ&quot;,
  10998. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  10999. &quot;joined_members&quot;: 8326,
  11000. &quot;joined_local_members&quot;: 2,
  11001. &quot;version&quot;: &quot;1&quot;,
  11002. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11003. &quot;encryption&quot;: null,
  11004. &quot;federatable&quot;: true,
  11005. &quot;public&quot;: true,
  11006. &quot;join_rules&quot;: &quot;invite&quot;,
  11007. &quot;guest_access&quot;: null,
  11008. &quot;history_visibility&quot;: &quot;shared&quot;,
  11009. &quot;state_events&quot;: 93534
  11010. },
  11011. ... (8 hidden items) ...
  11012. {
  11013. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  11014. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  11015. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  11016. &quot;joined_members&quot;: 314,
  11017. &quot;joined_local_members&quot;: 20,
  11018. &quot;version&quot;: &quot;4&quot;,
  11019. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11020. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  11021. &quot;federatable&quot;: true,
  11022. &quot;public&quot;: false,
  11023. &quot;join_rules&quot;: &quot;invite&quot;,
  11024. &quot;guest_access&quot;: null,
  11025. &quot;history_visibility&quot;: &quot;shared&quot;,
  11026. &quot;state_events&quot;: 8345
  11027. }
  11028. ],
  11029. &quot;offset&quot;: 0,
  11030. &quot;total_rooms&quot;: 10
  11031. }
  11032. </code></pre>
  11033. <p>Filtering by room name:</p>
  11034. <pre><code>GET /_synapse/admin/v1/rooms?search_term=TWIM
  11035. </code></pre>
  11036. <p>A response body like the following is returned:</p>
  11037. <pre><code class="language-json">{
  11038. &quot;rooms&quot;: [
  11039. {
  11040. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  11041. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  11042. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  11043. &quot;joined_members&quot;: 314,
  11044. &quot;joined_local_members&quot;: 20,
  11045. &quot;version&quot;: &quot;4&quot;,
  11046. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11047. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  11048. &quot;federatable&quot;: true,
  11049. &quot;public&quot;: false,
  11050. &quot;join_rules&quot;: &quot;invite&quot;,
  11051. &quot;guest_access&quot;: null,
  11052. &quot;history_visibility&quot;: &quot;shared&quot;,
  11053. &quot;state_events&quot;: 8
  11054. }
  11055. ],
  11056. &quot;offset&quot;: 0,
  11057. &quot;total_rooms&quot;: 1
  11058. }
  11059. </code></pre>
  11060. <p>Paginating through a list of rooms:</p>
  11061. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size
  11062. </code></pre>
  11063. <p>A response body like the following is returned:</p>
  11064. <pre><code class="language-json">{
  11065. &quot;rooms&quot;: [
  11066. {
  11067. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  11068. &quot;name&quot;: &quot;Matrix HQ&quot;,
  11069. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  11070. &quot;joined_members&quot;: 8326,
  11071. &quot;joined_local_members&quot;: 2,
  11072. &quot;version&quot;: &quot;1&quot;,
  11073. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11074. &quot;encryption&quot;: null,
  11075. &quot;federatable&quot;: true,
  11076. &quot;public&quot;: true,
  11077. &quot;join_rules&quot;: &quot;invite&quot;,
  11078. &quot;guest_access&quot;: null,
  11079. &quot;history_visibility&quot;: &quot;shared&quot;,
  11080. &quot;state_events&quot;: 93534
  11081. },
  11082. ... (98 hidden items) ...
  11083. {
  11084. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  11085. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  11086. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  11087. &quot;joined_members&quot;: 314,
  11088. &quot;joined_local_members&quot;: 20,
  11089. &quot;version&quot;: &quot;4&quot;,
  11090. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11091. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  11092. &quot;federatable&quot;: true,
  11093. &quot;public&quot;: false,
  11094. &quot;join_rules&quot;: &quot;invite&quot;,
  11095. &quot;guest_access&quot;: null,
  11096. &quot;history_visibility&quot;: &quot;shared&quot;,
  11097. &quot;state_events&quot;: 8345
  11098. }
  11099. ],
  11100. &quot;offset&quot;: 0,
  11101. &quot;total_rooms&quot;: 150,
  11102. &quot;next_token&quot;: 100
  11103. }
  11104. </code></pre>
  11105. <p>The presence of the <code>next_token</code> parameter tells us that there are more rooms
  11106. than returned in this request, and we need to make another request to get them.
  11107. To get the next batch of room results, we repeat our request, setting the <code>from</code>
  11108. parameter to the value of <code>next_token</code>.</p>
  11109. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size&amp;from=100
  11110. </code></pre>
  11111. <p>A response body like the following is returned:</p>
  11112. <pre><code class="language-json">{
  11113. &quot;rooms&quot;: [
  11114. {
  11115. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  11116. &quot;name&quot;: &quot;Music Theory&quot;,
  11117. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  11118. &quot;joined_members&quot;: 127,
  11119. &quot;joined_local_members&quot;: 2,
  11120. &quot;version&quot;: &quot;1&quot;,
  11121. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11122. &quot;encryption&quot;: null,
  11123. &quot;federatable&quot;: true,
  11124. &quot;public&quot;: true,
  11125. &quot;join_rules&quot;: &quot;invite&quot;,
  11126. &quot;guest_access&quot;: null,
  11127. &quot;history_visibility&quot;: &quot;shared&quot;,
  11128. &quot;state_events&quot;: 93534
  11129. },
  11130. ... (48 hidden items) ...
  11131. {
  11132. &quot;room_id&quot;: &quot;!twcBhHVdZlQWuuxBhN:termina.org.uk&quot;,
  11133. &quot;name&quot;: &quot;weechat-matrix&quot;,
  11134. &quot;canonical_alias&quot;: &quot;#weechat-matrix:termina.org.uk&quot;,
  11135. &quot;joined_members&quot;: 137,
  11136. &quot;joined_local_members&quot;: 20,
  11137. &quot;version&quot;: &quot;4&quot;,
  11138. &quot;creator&quot;: &quot;@foo:termina.org.uk&quot;,
  11139. &quot;encryption&quot;: null,
  11140. &quot;federatable&quot;: true,
  11141. &quot;public&quot;: true,
  11142. &quot;join_rules&quot;: &quot;invite&quot;,
  11143. &quot;guest_access&quot;: null,
  11144. &quot;history_visibility&quot;: &quot;shared&quot;,
  11145. &quot;state_events&quot;: 8345
  11146. }
  11147. ],
  11148. &quot;offset&quot;: 100,
  11149. &quot;prev_batch&quot;: 0,
  11150. &quot;total_rooms&quot;: 150
  11151. }
  11152. </code></pre>
  11153. <p>Once the <code>next_token</code> parameter is no longer present, we know we've reached the
  11154. end of the list.</p>
  11155. <h1 id="room-details-api"><a class="header" href="#room-details-api">Room Details API</a></h1>
  11156. <p>The Room Details admin API allows server admins to get all details of a room.</p>
  11157. <p>The following fields are possible in the JSON response body:</p>
  11158. <ul>
  11159. <li><code>room_id</code> - The ID of the room.</li>
  11160. <li><code>name</code> - The name of the room.</li>
  11161. <li><code>topic</code> - The topic of the room.</li>
  11162. <li><code>avatar</code> - The <code>mxc</code> URI to the avatar of the room.</li>
  11163. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  11164. <li><code>joined_members</code> - How many users are currently in the room.</li>
  11165. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  11166. <li><code>joined_local_devices</code> - How many local devices are currently in the room.</li>
  11167. <li><code>version</code> - The version of the room as a string.</li>
  11168. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  11169. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  11170. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  11171. <li><code>public</code> - Whether the room is visible in room directory.</li>
  11172. <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>
  11173. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  11174. <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>
  11175. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  11176. </ul>
  11177. <p>The API is:</p>
  11178. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;
  11179. </code></pre>
  11180. <p>A response body like the following is returned:</p>
  11181. <pre><code class="language-json">{
  11182. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  11183. &quot;name&quot;: &quot;Music Theory&quot;,
  11184. &quot;avatar&quot;: &quot;mxc://matrix.org/AQDaVFlbkQoErdOgqWRgiGSV&quot;,
  11185. &quot;topic&quot;: &quot;Theory, Composition, Notation, Analysis&quot;,
  11186. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  11187. &quot;joined_members&quot;: 127,
  11188. &quot;joined_local_members&quot;: 2,
  11189. &quot;joined_local_devices&quot;: 2,
  11190. &quot;version&quot;: &quot;1&quot;,
  11191. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  11192. &quot;encryption&quot;: null,
  11193. &quot;federatable&quot;: true,
  11194. &quot;public&quot;: true,
  11195. &quot;join_rules&quot;: &quot;invite&quot;,
  11196. &quot;guest_access&quot;: null,
  11197. &quot;history_visibility&quot;: &quot;shared&quot;,
  11198. &quot;state_events&quot;: 93534
  11199. }
  11200. </code></pre>
  11201. <h1 id="room-members-api"><a class="header" href="#room-members-api">Room Members API</a></h1>
  11202. <p>The Room Members admin API allows server admins to get a list of all members of a room.</p>
  11203. <p>The response includes the following fields:</p>
  11204. <ul>
  11205. <li><code>members</code> - A list of all the members that are present in the room, represented by their ids.</li>
  11206. <li><code>total</code> - Total number of members in the room.</li>
  11207. </ul>
  11208. <p>The API is:</p>
  11209. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/members
  11210. </code></pre>
  11211. <p>A response body like the following is returned:</p>
  11212. <pre><code class="language-json">{
  11213. &quot;members&quot;: [
  11214. &quot;@foo:matrix.org&quot;,
  11215. &quot;@bar:matrix.org&quot;,
  11216. &quot;@foobar:matrix.org&quot;
  11217. ],
  11218. &quot;total&quot;: 3
  11219. }
  11220. </code></pre>
  11221. <h1 id="room-state-api"><a class="header" href="#room-state-api">Room State API</a></h1>
  11222. <p>The Room State admin API allows server admins to get a list of all state events in a room.</p>
  11223. <p>The response includes the following fields:</p>
  11224. <ul>
  11225. <li><code>state</code> - The current state of the room at the time of request.</li>
  11226. </ul>
  11227. <p>The API is:</p>
  11228. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/state
  11229. </code></pre>
  11230. <p>A response body like the following is returned:</p>
  11231. <pre><code class="language-json">{
  11232. &quot;state&quot;: [
  11233. {&quot;type&quot;: &quot;m.room.create&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  11234. {&quot;type&quot;: &quot;m.room.power_levels&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  11235. {&quot;type&quot;: &quot;m.room.name&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true}
  11236. ]
  11237. }
  11238. </code></pre>
  11239. <h1 id="block-room-api"><a class="header" href="#block-room-api">Block Room API</a></h1>
  11240. <p>The Block Room admin API allows server admins to block and unblock rooms,
  11241. and query to see if a given room is blocked.
  11242. This API can be used to pre-emptively block a room, even if it's unknown to this
  11243. homeserver. Users will be prevented from joining a blocked room.</p>
  11244. <h2 id="block-or-unblock-a-room"><a class="header" href="#block-or-unblock-a-room">Block or unblock a room</a></h2>
  11245. <p>The API is:</p>
  11246. <pre><code>PUT /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  11247. </code></pre>
  11248. <p>with a body of:</p>
  11249. <pre><code class="language-json">{
  11250. &quot;block&quot;: true
  11251. }
  11252. </code></pre>
  11253. <p>A response body like the following is returned:</p>
  11254. <pre><code class="language-json">{
  11255. &quot;block&quot;: true
  11256. }
  11257. </code></pre>
  11258. <p><strong>Parameters</strong></p>
  11259. <p>The following parameters should be set in the URL:</p>
  11260. <ul>
  11261. <li><code>room_id</code> - The ID of the room.</li>
  11262. </ul>
  11263. <p>The following JSON body parameters are available:</p>
  11264. <ul>
  11265. <li><code>block</code> - If <code>true</code> the room will be blocked and if <code>false</code> the room will be unblocked.</li>
  11266. </ul>
  11267. <p><strong>Response</strong></p>
  11268. <p>The following fields are possible in the JSON response body:</p>
  11269. <ul>
  11270. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  11271. </ul>
  11272. <h2 id="get-block-status"><a class="header" href="#get-block-status">Get block status</a></h2>
  11273. <p>The API is:</p>
  11274. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  11275. </code></pre>
  11276. <p>A response body like the following is returned:</p>
  11277. <pre><code class="language-json">{
  11278. &quot;block&quot;: true,
  11279. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  11280. }
  11281. </code></pre>
  11282. <p><strong>Parameters</strong></p>
  11283. <p>The following parameters should be set in the URL:</p>
  11284. <ul>
  11285. <li><code>room_id</code> - The ID of the room.</li>
  11286. </ul>
  11287. <p><strong>Response</strong></p>
  11288. <p>The following fields are possible in the JSON response body:</p>
  11289. <ul>
  11290. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  11291. <li><code>user_id</code> - An optional string. If the room is blocked (<code>block</code> is <code>true</code>) shows
  11292. the user who has add the room to blocking list. Otherwise it is not displayed.</li>
  11293. </ul>
  11294. <h1 id="delete-room-api"><a class="header" href="#delete-room-api">Delete Room API</a></h1>
  11295. <p>The Delete Room admin API allows server admins to remove rooms from the server
  11296. and block these rooms.</p>
  11297. <p>Shuts down a room. Moves all local users and room aliases automatically to a
  11298. new room if <code>new_room_user_id</code> is set. Otherwise local users only
  11299. leave the room without any information.</p>
  11300. <p>The new room will be created with the user specified by the <code>new_room_user_id</code> parameter
  11301. as room administrator and will contain a message explaining what happened. Users invited
  11302. to the new room will have power level <code>-10</code> by default, and thus be unable to speak.</p>
  11303. <p>If <code>block</code> is <code>true</code>, users will be prevented from joining the old room.
  11304. This option can in <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> also be used to pre-emptively
  11305. block a room, even if it's unknown to this homeserver. In this case, the room will be
  11306. blocked, and no further action will be taken. If <code>block</code> is <code>false</code>, attempting to
  11307. delete an unknown room is invalid and will be rejected as a bad request.</p>
  11308. <p>This API will remove all trace of the old room from your database after removing
  11309. all local users. If <code>purge</code> is <code>true</code> (the default), all traces of the old room will
  11310. be removed from your database after removing all local users. If you do not want
  11311. this to happen, set <code>purge</code> to <code>false</code>.
  11312. Depending on the amount of history being purged, a call to the API may take
  11313. several minutes or longer.</p>
  11314. <p>The local server will only have the power to move local user and room aliases to
  11315. the new room. Users on other servers will be unaffected.</p>
  11316. <h2 id="version-1-old-version"><a class="header" href="#version-1-old-version">Version 1 (old version)</a></h2>
  11317. <p>This version works synchronously. That means you only get the response once the server has
  11318. finished the action, which may take a long time. If you request the same action
  11319. a second time, and the server has not finished the first one, the second request will block.
  11320. This is fixed in version 2 of this API. The parameters are the same in both APIs.
  11321. This API will become deprecated in the future.</p>
  11322. <p>The API is:</p>
  11323. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id&gt;
  11324. </code></pre>
  11325. <p>with a body of:</p>
  11326. <pre><code class="language-json">{
  11327. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  11328. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  11329. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  11330. &quot;block&quot;: true,
  11331. &quot;purge&quot;: true
  11332. }
  11333. </code></pre>
  11334. <p>A response body like the following is returned:</p>
  11335. <pre><code class="language-json">{
  11336. &quot;kicked_users&quot;: [
  11337. &quot;@foobar:example.com&quot;
  11338. ],
  11339. &quot;failed_to_kick_users&quot;: [],
  11340. &quot;local_aliases&quot;: [
  11341. &quot;#badroom:example.com&quot;,
  11342. &quot;#evilsaloon:example.com&quot;
  11343. ],
  11344. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  11345. }
  11346. </code></pre>
  11347. <p>The parameters and response values have the same format as
  11348. <a href="admin_api/rooms.html#version-2-new-version">version 2</a> of the API.</p>
  11349. <h2 id="version-2-new-version"><a class="header" href="#version-2-new-version">Version 2 (new version)</a></h2>
  11350. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  11351. <p>This version works asynchronously, meaning you get the response from server immediately
  11352. while the server works on that task in background. You can then request the status of the action
  11353. to check if it has completed.</p>
  11354. <p>The API is:</p>
  11355. <pre><code>DELETE /_synapse/admin/v2/rooms/&lt;room_id&gt;
  11356. </code></pre>
  11357. <p>with a body of:</p>
  11358. <pre><code class="language-json">{
  11359. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  11360. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  11361. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  11362. &quot;block&quot;: true,
  11363. &quot;purge&quot;: true
  11364. }
  11365. </code></pre>
  11366. <p>The API starts the shut down and purge running, and returns immediately with a JSON body with
  11367. a purge id:</p>
  11368. <pre><code class="language-json">{
  11369. &quot;delete_id&quot;: &quot;&lt;opaque id&gt;&quot;
  11370. }
  11371. </code></pre>
  11372. <p><strong>Parameters</strong></p>
  11373. <p>The following parameters should be set in the URL:</p>
  11374. <ul>
  11375. <li><code>room_id</code> - The ID of the room.</li>
  11376. </ul>
  11377. <p>The following JSON body parameters are available:</p>
  11378. <ul>
  11379. <li><code>new_room_user_id</code> - Optional. If set, a new room will be created with this user ID
  11380. as the creator and admin, and all users in the old room will be moved into that
  11381. room. If not set, no new room will be created and the users will just be removed
  11382. from the old room. The user ID must be on the local server, but does not necessarily
  11383. have to belong to a registered user.</li>
  11384. <li><code>room_name</code> - Optional. A string representing the name of the room that new users will be
  11385. invited to. Defaults to <code>Content Violation Notification</code></li>
  11386. <li><code>message</code> - Optional. A string containing the first message that will be sent as
  11387. <code>new_room_user_id</code> in the new room. Ideally this will clearly convey why the
  11388. 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>
  11389. <li><code>block</code> - Optional. If set to <code>true</code>, this room will be added to a blocking list,
  11390. preventing future attempts to join the room. Rooms can be blocked
  11391. even if they're not yet known to the homeserver (only with
  11392. <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> of the API). Defaults to <code>false</code>.</li>
  11393. <li><code>purge</code> - Optional. If set to <code>true</code>, it will remove all traces of the room from your database.
  11394. Defaults to <code>true</code>.</li>
  11395. <li><code>force_purge</code> - Optional, and ignored unless <code>purge</code> is <code>true</code>. If set to <code>true</code>, it
  11396. will force a purge to go ahead even if there are local users still in the room. Do not
  11397. use this unless a regular <code>purge</code> operation fails, as it could leave those users'
  11398. clients in a confused state.</li>
  11399. </ul>
  11400. <p>The JSON body must not be empty. The body must be at least <code>{}</code>.</p>
  11401. <h2 id="status-of-deleting-rooms"><a class="header" href="#status-of-deleting-rooms">Status of deleting rooms</a></h2>
  11402. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  11403. <p>It is possible to query the status of the background task for deleting rooms.
  11404. The status can be queried up to 24 hours after completion of the task,
  11405. or until Synapse is restarted (whichever happens first).</p>
  11406. <h3 id="query-by-room_id"><a class="header" href="#query-by-room_id">Query by <code>room_id</code></a></h3>
  11407. <p>With this API you can get the status of all active deletion tasks, and all those completed in the last 24h,
  11408. for the given <code>room_id</code>.</p>
  11409. <p>The API is:</p>
  11410. <pre><code>GET /_synapse/admin/v2/rooms/&lt;room_id&gt;/delete_status
  11411. </code></pre>
  11412. <p>A response body like the following is returned:</p>
  11413. <pre><code class="language-json">{
  11414. &quot;results&quot;: [
  11415. {
  11416. &quot;delete_id&quot;: &quot;delete_id1&quot;,
  11417. &quot;status&quot;: &quot;failed&quot;,
  11418. &quot;error&quot;: &quot;error message&quot;,
  11419. &quot;shutdown_room&quot;: {
  11420. &quot;kicked_users&quot;: [],
  11421. &quot;failed_to_kick_users&quot;: [],
  11422. &quot;local_aliases&quot;: [],
  11423. &quot;new_room_id&quot;: null
  11424. }
  11425. }, {
  11426. &quot;delete_id&quot;: &quot;delete_id2&quot;,
  11427. &quot;status&quot;: &quot;purging&quot;,
  11428. &quot;shutdown_room&quot;: {
  11429. &quot;kicked_users&quot;: [
  11430. &quot;@foobar:example.com&quot;
  11431. ],
  11432. &quot;failed_to_kick_users&quot;: [],
  11433. &quot;local_aliases&quot;: [
  11434. &quot;#badroom:example.com&quot;,
  11435. &quot;#evilsaloon:example.com&quot;
  11436. ],
  11437. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  11438. }
  11439. }
  11440. ]
  11441. }
  11442. </code></pre>
  11443. <p><strong>Parameters</strong></p>
  11444. <p>The following parameters should be set in the URL:</p>
  11445. <ul>
  11446. <li><code>room_id</code> - The ID of the room.</li>
  11447. </ul>
  11448. <h3 id="query-by-delete_id"><a class="header" href="#query-by-delete_id">Query by <code>delete_id</code></a></h3>
  11449. <p>With this API you can get the status of one specific task by <code>delete_id</code>.</p>
  11450. <p>The API is:</p>
  11451. <pre><code>GET /_synapse/admin/v2/rooms/delete_status/&lt;delete_id&gt;
  11452. </code></pre>
  11453. <p>A response body like the following is returned:</p>
  11454. <pre><code class="language-json">{
  11455. &quot;status&quot;: &quot;purging&quot;,
  11456. &quot;shutdown_room&quot;: {
  11457. &quot;kicked_users&quot;: [
  11458. &quot;@foobar:example.com&quot;
  11459. ],
  11460. &quot;failed_to_kick_users&quot;: [],
  11461. &quot;local_aliases&quot;: [
  11462. &quot;#badroom:example.com&quot;,
  11463. &quot;#evilsaloon:example.com&quot;
  11464. ],
  11465. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  11466. }
  11467. }
  11468. </code></pre>
  11469. <p><strong>Parameters</strong></p>
  11470. <p>The following parameters should be set in the URL:</p>
  11471. <ul>
  11472. <li><code>delete_id</code> - The ID for this delete.</li>
  11473. </ul>
  11474. <h3 id="response"><a class="header" href="#response">Response</a></h3>
  11475. <p>The following fields are returned in the JSON response body:</p>
  11476. <ul>
  11477. <li><code>results</code> - An array of objects, each containing information about one task.
  11478. This field is omitted from the result when you query by <code>delete_id</code>.
  11479. Task objects contain the following fields:
  11480. <ul>
  11481. <li><code>delete_id</code> - The ID for this purge if you query by <code>room_id</code>.</li>
  11482. <li><code>status</code> - The status will be one of:
  11483. <ul>
  11484. <li><code>shutting_down</code> - The process is removing users from the room.</li>
  11485. <li><code>purging</code> - The process is purging the room and event data from database.</li>
  11486. <li><code>complete</code> - The process has completed successfully.</li>
  11487. <li><code>failed</code> - The process is aborted, an error has occurred.</li>
  11488. </ul>
  11489. </li>
  11490. <li><code>error</code> - A string that shows an error message if <code>status</code> is <code>failed</code>.
  11491. Otherwise this field is hidden.</li>
  11492. <li><code>shutdown_room</code> - An object containing information about the result of shutting down the room.
  11493. <em>Note:</em> The result is shown after removing the room members.
  11494. The delete process can still be running. Please pay attention to the <code>status</code>.
  11495. <ul>
  11496. <li><code>kicked_users</code> - An array of users (<code>user_id</code>) that were kicked.</li>
  11497. <li><code>failed_to_kick_users</code> - An array of users (<code>user_id</code>) that that were not kicked.</li>
  11498. <li><code>local_aliases</code> - An array of strings representing the local aliases that were
  11499. migrated from the old room to the new.</li>
  11500. <li><code>new_room_id</code> - A string representing the room ID of the new room, or <code>null</code> if
  11501. no such room was created.</li>
  11502. </ul>
  11503. </li>
  11504. </ul>
  11505. </li>
  11506. </ul>
  11507. <h2 id="undoing-room-deletions"><a class="header" href="#undoing-room-deletions">Undoing room deletions</a></h2>
  11508. <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,
  11509. the structure can and does change without notice.</p>
  11510. <p>First, it's important to understand that a room deletion is very destructive. Undoing a deletion is not as simple as pretending it
  11511. 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
  11512. to recover at all:</p>
  11513. <ul>
  11514. <li>If the room was invite-only, your users will need to be re-invited.</li>
  11515. <li>If the room no longer has any members at all, it'll be impossible to rejoin.</li>
  11516. <li>The first user to rejoin will have to do so via an alias on a different
  11517. server (or receive an invite from a user on a different server).</li>
  11518. </ul>
  11519. <p>With all that being said, if you still want to try and recover the room:</p>
  11520. <ol>
  11521. <li>
  11522. <p>If the room was <code>block</code>ed, you must unblock it on your server. This can be
  11523. accomplished as follows:</p>
  11524. <ol>
  11525. <li>For safety reasons, shut down Synapse.</li>
  11526. <li>In the database, run <code>DELETE FROM blocked_rooms WHERE room_id = '!example:example.org';</code>
  11527. <ul>
  11528. <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>
  11529. <li>The room ID is the same one supplied to the delete room API, not the Content Violation room.</li>
  11530. </ul>
  11531. </li>
  11532. <li>Restart Synapse.</li>
  11533. </ol>
  11534. <p>This step is unnecessary if <code>block</code> was not set.</p>
  11535. </li>
  11536. <li>
  11537. <p>Any room aliases on your server that pointed to the deleted room may have
  11538. been deleted, or redirected to the Content Violation room. These will need
  11539. to be restored manually.</p>
  11540. </li>
  11541. <li>
  11542. <p>Users on your server that were in the deleted room will have been kicked
  11543. from the room. Consider whether you want to update their membership
  11544. (possibly via the <a href="admin_api/room_membership.html">Edit Room Membership API</a>) or let
  11545. them handle rejoining themselves.</p>
  11546. </li>
  11547. <li>
  11548. <p>If <code>new_room_user_id</code> was given, a 'Content Violation' will have been
  11549. created. Consider whether you want to delete that roomm.</p>
  11550. </li>
  11551. </ol>
  11552. <h1 id="make-room-admin-api"><a class="header" href="#make-room-admin-api">Make Room Admin API</a></h1>
  11553. <p>Grants another user the highest power available to a local user who is in the room.
  11554. If the user is not in the room, and it is not publicly joinable, then invite the user.</p>
  11555. <p>By default the server admin (the caller) is granted power, but another user can
  11556. optionally be specified, e.g.:</p>
  11557. <pre><code>POST /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/make_room_admin
  11558. {
  11559. &quot;user_id&quot;: &quot;@foo:example.com&quot;
  11560. }
  11561. </code></pre>
  11562. <h1 id="forward-extremities-admin-api"><a class="header" href="#forward-extremities-admin-api">Forward Extremities Admin API</a></h1>
  11563. <p>Enables querying and deleting forward extremities from rooms. When a lot of forward
  11564. extremities accumulate in a room, performance can become degraded. For details, see
  11565. <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.</p>
  11566. <h2 id="check-for-forward-extremities"><a class="header" href="#check-for-forward-extremities">Check for forward extremities</a></h2>
  11567. <p>To check the status of forward extremities for a room:</p>
  11568. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  11569. </code></pre>
  11570. <p>A response as follows will be returned:</p>
  11571. <pre><code class="language-json">{
  11572. &quot;count&quot;: 1,
  11573. &quot;results&quot;: [
  11574. {
  11575. &quot;event_id&quot;: &quot;$M5SP266vsnxctfwFgFLNceaCo3ujhRtg_NiiHabcdefgh&quot;,
  11576. &quot;state_group&quot;: 439,
  11577. &quot;depth&quot;: 123,
  11578. &quot;received_ts&quot;: 1611263016761
  11579. }
  11580. ]
  11581. }
  11582. </code></pre>
  11583. <h2 id="deleting-forward-extremities"><a class="header" href="#deleting-forward-extremities">Deleting forward extremities</a></h2>
  11584. <p><strong>WARNING</strong>: Please ensure you know what you're doing and have read
  11585. the related issue <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.
  11586. Under no situations should this API be executed as an automated maintenance task!</p>
  11587. <p>If a room has lots of forward extremities, the extra can be
  11588. deleted as follows:</p>
  11589. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  11590. </code></pre>
  11591. <p>A response as follows will be returned, indicating the amount of forward extremities
  11592. that were deleted.</p>
  11593. <pre><code class="language-json">{
  11594. &quot;deleted&quot;: 1
  11595. }
  11596. </code></pre>
  11597. <h1 id="event-context-api"><a class="header" href="#event-context-api">Event Context API</a></h1>
  11598. <p>This API lets a client find the context of an event. This is designed primarily to investigate abuse reports.</p>
  11599. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/context/&lt;event_id&gt;
  11600. </code></pre>
  11601. <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>
  11602. <p>Example response:</p>
  11603. <pre><code class="language-json">{
  11604. &quot;end&quot;: &quot;t29-57_2_0_2&quot;,
  11605. &quot;events_after&quot;: [
  11606. {
  11607. &quot;content&quot;: {
  11608. &quot;body&quot;: &quot;This is an example text message&quot;,
  11609. &quot;msgtype&quot;: &quot;m.text&quot;,
  11610. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  11611. &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;
  11612. },
  11613. &quot;type&quot;: &quot;m.room.message&quot;,
  11614. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  11615. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11616. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11617. &quot;origin_server_ts&quot;: 1432735824653,
  11618. &quot;unsigned&quot;: {
  11619. &quot;age&quot;: 1234
  11620. }
  11621. }
  11622. ],
  11623. &quot;event&quot;: {
  11624. &quot;content&quot;: {
  11625. &quot;body&quot;: &quot;filename.jpg&quot;,
  11626. &quot;info&quot;: {
  11627. &quot;h&quot;: 398,
  11628. &quot;w&quot;: 394,
  11629. &quot;mimetype&quot;: &quot;image/jpeg&quot;,
  11630. &quot;size&quot;: 31037
  11631. },
  11632. &quot;url&quot;: &quot;mxc://example.org/JWEIFJgwEIhweiWJE&quot;,
  11633. &quot;msgtype&quot;: &quot;m.image&quot;
  11634. },
  11635. &quot;type&quot;: &quot;m.room.message&quot;,
  11636. &quot;event_id&quot;: &quot;$f3h4d129462ha:example.com&quot;,
  11637. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11638. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11639. &quot;origin_server_ts&quot;: 1432735824653,
  11640. &quot;unsigned&quot;: {
  11641. &quot;age&quot;: 1234
  11642. }
  11643. },
  11644. &quot;events_before&quot;: [
  11645. {
  11646. &quot;content&quot;: {
  11647. &quot;body&quot;: &quot;something-important.doc&quot;,
  11648. &quot;filename&quot;: &quot;something-important.doc&quot;,
  11649. &quot;info&quot;: {
  11650. &quot;mimetype&quot;: &quot;application/msword&quot;,
  11651. &quot;size&quot;: 46144
  11652. },
  11653. &quot;msgtype&quot;: &quot;m.file&quot;,
  11654. &quot;url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;
  11655. },
  11656. &quot;type&quot;: &quot;m.room.message&quot;,
  11657. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  11658. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11659. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11660. &quot;origin_server_ts&quot;: 1432735824653,
  11661. &quot;unsigned&quot;: {
  11662. &quot;age&quot;: 1234
  11663. }
  11664. }
  11665. ],
  11666. &quot;start&quot;: &quot;t27-54_2_0_2&quot;,
  11667. &quot;state&quot;: [
  11668. {
  11669. &quot;content&quot;: {
  11670. &quot;creator&quot;: &quot;@example:example.org&quot;,
  11671. &quot;room_version&quot;: &quot;1&quot;,
  11672. &quot;m.federate&quot;: true,
  11673. &quot;predecessor&quot;: {
  11674. &quot;event_id&quot;: &quot;$something:example.org&quot;,
  11675. &quot;room_id&quot;: &quot;!oldroom:example.org&quot;
  11676. }
  11677. },
  11678. &quot;type&quot;: &quot;m.room.create&quot;,
  11679. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  11680. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11681. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11682. &quot;origin_server_ts&quot;: 1432735824653,
  11683. &quot;unsigned&quot;: {
  11684. &quot;age&quot;: 1234
  11685. },
  11686. &quot;state_key&quot;: &quot;&quot;
  11687. },
  11688. {
  11689. &quot;content&quot;: {
  11690. &quot;membership&quot;: &quot;join&quot;,
  11691. &quot;avatar_url&quot;: &quot;mxc://example.org/SEsfnsuifSDFSSEF&quot;,
  11692. &quot;displayname&quot;: &quot;Alice Margatroid&quot;
  11693. },
  11694. &quot;type&quot;: &quot;m.room.member&quot;,
  11695. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  11696. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  11697. &quot;sender&quot;: &quot;@example:example.org&quot;,
  11698. &quot;origin_server_ts&quot;: 1432735824653,
  11699. &quot;unsigned&quot;: {
  11700. &quot;age&quot;: 1234
  11701. },
  11702. &quot;state_key&quot;: &quot;@alice:example.org&quot;
  11703. }
  11704. ]
  11705. }
  11706. </code></pre>
  11707. <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>
  11708. <p>The API to send notices is as follows:</p>
  11709. <pre><code>POST /_synapse/admin/v1/send_server_notice
  11710. </code></pre>
  11711. <p>or:</p>
  11712. <pre><code>PUT /_synapse/admin/v1/send_server_notice/{txnId}
  11713. </code></pre>
  11714. <p>You will need to authenticate with an access token for an admin user.</p>
  11715. <p>When using the <code>PUT</code> form, retransmissions with the same transaction ID will be
  11716. ignored in the same way as with <code>PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}</code>.</p>
  11717. <p>The request body should look something like the following:</p>
  11718. <pre><code class="language-json">{
  11719. &quot;user_id&quot;: &quot;@target_user:server_name&quot;,
  11720. &quot;content&quot;: {
  11721. &quot;msgtype&quot;: &quot;m.text&quot;,
  11722. &quot;body&quot;: &quot;This is my message&quot;
  11723. }
  11724. }
  11725. </code></pre>
  11726. <p>You can optionally include the following additional parameters:</p>
  11727. <ul>
  11728. <li><code>type</code>: the type of event. Defaults to <code>m.room.message</code>.</li>
  11729. <li><code>state_key</code>: Setting this will result in a state event being sent.</li>
  11730. </ul>
  11731. <p>Once the notice has been sent, the API will return the following response:</p>
  11732. <pre><code class="language-json">{
  11733. &quot;event_id&quot;: &quot;&lt;event_id&gt;&quot;
  11734. }
  11735. </code></pre>
  11736. <p>Note that server notices must be enabled in <code>homeserver.yaml</code> before this API
  11737. can be used. See <a href="admin_api/../server_notices.html">the server notices documentation</a> for more information.</p>
  11738. <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>
  11739. <p>Returns information about all local media usage of users. Gives the
  11740. possibility to filter them by time and user.</p>
  11741. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11742. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  11743. <p>The API is:</p>
  11744. <pre><code>GET /_synapse/admin/v1/statistics/users/media
  11745. </code></pre>
  11746. <p>A response body like the following is returned:</p>
  11747. <pre><code class="language-json">{
  11748. &quot;users&quot;: [
  11749. {
  11750. &quot;displayname&quot;: &quot;foo_user_0&quot;,
  11751. &quot;media_count&quot;: 2,
  11752. &quot;media_length&quot;: 134,
  11753. &quot;user_id&quot;: &quot;@foo_user_0:test&quot;
  11754. },
  11755. {
  11756. &quot;displayname&quot;: &quot;foo_user_1&quot;,
  11757. &quot;media_count&quot;: 2,
  11758. &quot;media_length&quot;: 134,
  11759. &quot;user_id&quot;: &quot;@foo_user_1:test&quot;
  11760. }
  11761. ],
  11762. &quot;next_token&quot;: 3,
  11763. &quot;total&quot;: 10
  11764. }
  11765. </code></pre>
  11766. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint
  11767. again with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  11768. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  11769. reports to paginate through.</p>
  11770. <p><strong>Parameters</strong></p>
  11771. <p>The following parameters should be set in the URL:</p>
  11772. <ul>
  11773. <li><code>limit</code>: string representing a positive integer - Is optional but is
  11774. used for pagination, denoting the maximum number of items to return
  11775. in this call. Defaults to <code>100</code>.</li>
  11776. <li><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  11777. denoting the offset in the returned results. This should be treated as an opaque value
  11778. and not explicitly set to anything other than the return value of <code>next_token</code> from a
  11779. previous call. Defaults to <code>0</code>.</li>
  11780. <li><code>order_by</code> - string - The method in which to sort the returned list of users. Valid values are:
  11781. <ul>
  11782. <li><code>user_id</code> - Users are ordered alphabetically by <code>user_id</code>. This is the default.</li>
  11783. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  11784. <li><code>media_length</code> - Users are ordered by the total size of uploaded media in bytes.
  11785. Smallest to largest.</li>
  11786. <li><code>media_count</code> - Users are ordered by number of uploaded media. Smallest to largest.</li>
  11787. </ul>
  11788. </li>
  11789. <li><code>from_ts</code> - string representing a positive integer - Considers only
  11790. files created at this timestamp or later. Unix timestamp in ms.</li>
  11791. <li><code>until_ts</code> - string representing a positive integer - Considers only
  11792. files created at this timestamp or earlier. Unix timestamp in ms.</li>
  11793. <li><code>search_term</code> - string - Filter users by their user ID localpart <strong>or</strong> displayname.
  11794. The search term can be found in any part of the string.
  11795. Defaults to no filtering.</li>
  11796. <li><code>dir</code> - string - Direction of order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  11797. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  11798. </ul>
  11799. <p><strong>Response</strong></p>
  11800. <p>The following fields are returned in the JSON response body:</p>
  11801. <ul>
  11802. <li><code>users</code> - An array of objects, each containing information
  11803. about the user and their local media. Objects contain the following fields:
  11804. <ul>
  11805. <li><code>displayname</code> - string - Displayname of this user.</li>
  11806. <li><code>media_count</code> - integer - Number of uploaded media by this user.</li>
  11807. <li><code>media_length</code> - integer - Size of uploaded media in bytes by this user.</li>
  11808. <li><code>user_id</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  11809. </ul>
  11810. </li>
  11811. <li><code>next_token</code> - integer - Opaque value used for pagination. See above.</li>
  11812. <li><code>total</code> - integer - Total number of users after filtering.</li>
  11813. </ul>
  11814. <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>
  11815. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  11816. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  11817. <h2 id="query-user-account"><a class="header" href="#query-user-account">Query User Account</a></h2>
  11818. <p>This API returns information about a specific user account.</p>
  11819. <p>The api is:</p>
  11820. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;
  11821. </code></pre>
  11822. <p>It returns a JSON body like the following:</p>
  11823. <pre><code class="language-jsonc">{
  11824. &quot;name&quot;: &quot;@user:example.com&quot;,
  11825. &quot;displayname&quot;: &quot;User&quot;, // can be null if not set
  11826. &quot;threepids&quot;: [
  11827. {
  11828. &quot;medium&quot;: &quot;email&quot;,
  11829. &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;,
  11830. &quot;added_at&quot;: 1586458409743,
  11831. &quot;validated_at&quot;: 1586458409743
  11832. },
  11833. {
  11834. &quot;medium&quot;: &quot;email&quot;,
  11835. &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;,
  11836. &quot;added_at&quot;: 1586458409743,
  11837. &quot;validated_at&quot;: 1586458409743
  11838. }
  11839. ],
  11840. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;, // can be null if not set
  11841. &quot;is_guest&quot;: 0,
  11842. &quot;admin&quot;: 0,
  11843. &quot;deactivated&quot;: 0,
  11844. &quot;shadow_banned&quot;: 0,
  11845. &quot;creation_ts&quot;: 1560432506,
  11846. &quot;appservice_id&quot;: null,
  11847. &quot;consent_server_notice_sent&quot;: null,
  11848. &quot;consent_version&quot;: null,
  11849. &quot;external_ids&quot;: [
  11850. {
  11851. &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
  11852. &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
  11853. },
  11854. {
  11855. &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
  11856. &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
  11857. }
  11858. ],
  11859. &quot;user_type&quot;: null
  11860. }
  11861. </code></pre>
  11862. <p>URL parameters:</p>
  11863. <ul>
  11864. <li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
  11865. </ul>
  11866. <h2 id="create-or-modify-account"><a class="header" href="#create-or-modify-account">Create or modify Account</a></h2>
  11867. <p>This API allows an administrator to create or modify a user account with a
  11868. specific <code>user_id</code>.</p>
  11869. <p>This api is:</p>
  11870. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;
  11871. </code></pre>
  11872. <p>with a body of:</p>
  11873. <pre><code class="language-json">{
  11874. &quot;password&quot;: &quot;user_password&quot;,
  11875. &quot;displayname&quot;: &quot;User&quot;,
  11876. &quot;threepids&quot;: [
  11877. {
  11878. &quot;medium&quot;: &quot;email&quot;,
  11879. &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;
  11880. },
  11881. {
  11882. &quot;medium&quot;: &quot;email&quot;,
  11883. &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;
  11884. }
  11885. ],
  11886. &quot;external_ids&quot;: [
  11887. {
  11888. &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
  11889. &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
  11890. },
  11891. {
  11892. &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
  11893. &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
  11894. }
  11895. ],
  11896. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
  11897. &quot;admin&quot;: false,
  11898. &quot;deactivated&quot;: false,
  11899. &quot;user_type&quot;: null
  11900. }
  11901. </code></pre>
  11902. <p>Returns HTTP status code:</p>
  11903. <ul>
  11904. <li><code>201</code> - When a new user object was created.</li>
  11905. <li><code>200</code> - When a user was modified.</li>
  11906. </ul>
  11907. <p>URL parameters:</p>
  11908. <ul>
  11909. <li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
  11910. </ul>
  11911. <p>Body parameters:</p>
  11912. <ul>
  11913. <li><code>password</code> - string, optional. If provided, the user's password is updated and all
  11914. devices are logged out, unless <code>logout_devices</code> is set to <code>false</code>.</li>
  11915. <li><code>logout_devices</code> - bool, optional, defaults to <code>true</code>. If set to false, devices aren't
  11916. logged out even when <code>password</code> is provided.</li>
  11917. <li><code>displayname</code> - string, optional, defaults to the value of <code>user_id</code>.</li>
  11918. <li><code>threepids</code> - array, optional, allows setting the third-party IDs (email, msisdn)
  11919. <ul>
  11920. <li><code>medium</code> - string. Kind of third-party ID, either <code>email</code> or <code>msisdn</code>.</li>
  11921. <li><code>address</code> - string. Value of third-party ID.
  11922. belonging to a user.</li>
  11923. </ul>
  11924. </li>
  11925. <li><code>external_ids</code> - array, optional. Allow setting the identifier of the external identity
  11926. provider for SSO (Single sign-on). Details in
  11927. <a href="admin_api/../usage/configuration/homeserver_sample_config.html">Sample Configuration File</a>
  11928. section <code>sso</code> and <code>oidc_providers</code>.
  11929. <ul>
  11930. <li><code>auth_provider</code> - string. ID of the external identity provider. Value of <code>idp_id</code>
  11931. in the homeserver configuration. Note that no error is raised if the provided
  11932. value is not in the homeserver configuration.</li>
  11933. <li><code>external_id</code> - string, user ID in the external identity provider.</li>
  11934. </ul>
  11935. </li>
  11936. <li><code>avatar_url</code> - string, optional, must be a
  11937. <a href="https://matrix.org/docs/spec/client_server/r0.6.0#matrix-content-mxc-uris">MXC URI</a>.</li>
  11938. <li><code>admin</code> - bool, optional, defaults to <code>false</code>.</li>
  11939. <li><code>deactivated</code> - bool, optional. If unspecified, deactivation state will be left
  11940. unchanged on existing accounts and set to <code>false</code> for new accounts.
  11941. A user cannot be erased by deactivating with this API. For details on
  11942. deactivating users see <a href="admin_api/user_admin_api.html#deactivate-account">Deactivate Account</a>.</li>
  11943. <li><code>user_type</code> - string or null, optional. If provided, the user type will be
  11944. adjusted. If <code>null</code> given, the user type will be cleared. Other
  11945. allowed options are: <code>bot</code> and <code>support</code>.</li>
  11946. </ul>
  11947. <p>If the user already exists then optional parameters default to the current value.</p>
  11948. <p>In order to re-activate an account <code>deactivated</code> must be set to <code>false</code>. If
  11949. users do not login via single-sign-on, a new <code>password</code> must be provided.</p>
  11950. <h2 id="list-accounts"><a class="header" href="#list-accounts">List Accounts</a></h2>
  11951. <p>This API returns all local user accounts.
  11952. By default, the response is ordered by ascending user ID.</p>
  11953. <pre><code>GET /_synapse/admin/v2/users?from=0&amp;limit=10&amp;guests=false
  11954. </code></pre>
  11955. <p>A response body like the following is returned:</p>
  11956. <pre><code class="language-json">{
  11957. &quot;users&quot;: [
  11958. {
  11959. &quot;name&quot;: &quot;&lt;user_id1&gt;&quot;,
  11960. &quot;is_guest&quot;: 0,
  11961. &quot;admin&quot;: 0,
  11962. &quot;user_type&quot;: null,
  11963. &quot;deactivated&quot;: 0,
  11964. &quot;shadow_banned&quot;: 0,
  11965. &quot;displayname&quot;: &quot;&lt;User One&gt;&quot;,
  11966. &quot;avatar_url&quot;: null,
  11967. &quot;creation_ts&quot;: 1560432668000
  11968. }, {
  11969. &quot;name&quot;: &quot;&lt;user_id2&gt;&quot;,
  11970. &quot;is_guest&quot;: 0,
  11971. &quot;admin&quot;: 1,
  11972. &quot;user_type&quot;: null,
  11973. &quot;deactivated&quot;: 0,
  11974. &quot;shadow_banned&quot;: 0,
  11975. &quot;displayname&quot;: &quot;&lt;User Two&gt;&quot;,
  11976. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
  11977. &quot;creation_ts&quot;: 1561550621000
  11978. }
  11979. ],
  11980. &quot;next_token&quot;: &quot;100&quot;,
  11981. &quot;total&quot;: 200
  11982. }
  11983. </code></pre>
  11984. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  11985. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  11986. <p>If the endpoint does not return a <code>next_token</code> then there are no more users
  11987. to paginate through.</p>
  11988. <p><strong>Parameters</strong></p>
  11989. <p>The following parameters should be set in the URL:</p>
  11990. <ul>
  11991. <li>
  11992. <p><code>user_id</code> - Is optional and filters to only return users with user IDs
  11993. that contain this value. This parameter is ignored when using the <code>name</code> parameter.</p>
  11994. </li>
  11995. <li>
  11996. <p><code>name</code> - Is optional and filters to only return users with user ID localparts
  11997. <strong>or</strong> displaynames that contain this value.</p>
  11998. </li>
  11999. <li>
  12000. <p><code>guests</code> - string representing a bool - Is optional and if <code>false</code> will <strong>exclude</strong> guest users.
  12001. Defaults to <code>true</code> to include guest users.</p>
  12002. </li>
  12003. <li>
  12004. <p><code>deactivated</code> - string representing a bool - Is optional and if <code>true</code> will <strong>include</strong> deactivated users.
  12005. Defaults to <code>false</code> to exclude deactivated users.</p>
  12006. </li>
  12007. <li>
  12008. <p><code>limit</code> - string representing a positive integer - Is optional but is used for pagination,
  12009. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  12010. </li>
  12011. <li>
  12012. <p><code>from</code> - string representing a positive integer - Is optional but used for pagination,
  12013. denoting the offset in the returned results. This should be treated as an opaque value and
  12014. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  12015. Defaults to <code>0</code>.</p>
  12016. </li>
  12017. <li>
  12018. <p><code>order_by</code> - The method by which to sort the returned list of users.
  12019. If the ordered field has duplicates, the second order is always by ascending <code>name</code>,
  12020. which guarantees a stable ordering. Valid values are:</p>
  12021. <ul>
  12022. <li><code>name</code> - Users are ordered alphabetically by <code>name</code>. This is the default.</li>
  12023. <li><code>is_guest</code> - Users are ordered by <code>is_guest</code> status.</li>
  12024. <li><code>admin</code> - Users are ordered by <code>admin</code> status.</li>
  12025. <li><code>user_type</code> - Users are ordered alphabetically by <code>user_type</code>.</li>
  12026. <li><code>deactivated</code> - Users are ordered by <code>deactivated</code> status.</li>
  12027. <li><code>shadow_banned</code> - Users are ordered by <code>shadow_banned</code> status.</li>
  12028. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  12029. <li><code>avatar_url</code> - Users are ordered alphabetically by avatar URL.</li>
  12030. <li><code>creation_ts</code> - Users are ordered by when the users was created in ms.</li>
  12031. </ul>
  12032. </li>
  12033. <li>
  12034. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  12035. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  12036. </li>
  12037. </ul>
  12038. <p>Caution. The database only has indexes on the columns <code>name</code> and <code>creation_ts</code>.
  12039. This means that if a different sort order is used (<code>is_guest</code>, <code>admin</code>,
  12040. <code>user_type</code>, <code>deactivated</code>, <code>shadow_banned</code>, <code>avatar_url</code> or <code>displayname</code>),
  12041. this can cause a large load on the database, especially for large environments.</p>
  12042. <p><strong>Response</strong></p>
  12043. <p>The following fields are returned in the JSON response body:</p>
  12044. <ul>
  12045. <li>
  12046. <p><code>users</code> - An array of objects, each containing information about an user.
  12047. User objects contain the following fields:</p>
  12048. <ul>
  12049. <li><code>name</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  12050. <li><code>is_guest</code> - bool - Status if that user is a guest account.</li>
  12051. <li><code>admin</code> - bool - Status if that user is a server administrator.</li>
  12052. <li><code>user_type</code> - string - Type of the user. Normal users are type <code>None</code>.
  12053. This allows user type specific behaviour. There are also types <code>support</code> and <code>bot</code>. </li>
  12054. <li><code>deactivated</code> - bool - Status if that user has been marked as deactivated.</li>
  12055. <li><code>shadow_banned</code> - bool - Status if that user has been marked as shadow banned.</li>
  12056. <li><code>displayname</code> - string - The user's display name if they have set one.</li>
  12057. <li><code>avatar_url</code> - string - The user's avatar URL if they have set one.</li>
  12058. <li><code>creation_ts</code> - integer - The user's creation timestamp in ms.</li>
  12059. </ul>
  12060. </li>
  12061. <li>
  12062. <p><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</p>
  12063. </li>
  12064. <li>
  12065. <p><code>total</code> - integer - Total number of media.</p>
  12066. </li>
  12067. </ul>
  12068. <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>
  12069. <p>This API returns information about the active sessions for a specific user.</p>
  12070. <p>The endpoints are:</p>
  12071. <pre><code>GET /_synapse/admin/v1/whois/&lt;user_id&gt;
  12072. </code></pre>
  12073. <p>and:</p>
  12074. <pre><code>GET /_matrix/client/r0/admin/whois/&lt;userId&gt;
  12075. </code></pre>
  12076. <p>See also: <a href="https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-admin-whois-userid">Client Server
  12077. API Whois</a>.</p>
  12078. <p>It returns a JSON body like the following:</p>
  12079. <pre><code class="language-json">{
  12080. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;,
  12081. &quot;devices&quot;: {
  12082. &quot;&quot;: {
  12083. &quot;sessions&quot;: [
  12084. {
  12085. &quot;connections&quot;: [
  12086. {
  12087. &quot;ip&quot;: &quot;1.2.3.4&quot;,
  12088. &quot;last_seen&quot;: 1417222374433,
  12089. &quot;user_agent&quot;: &quot;Mozilla/5.0 ...&quot;
  12090. },
  12091. {
  12092. &quot;ip&quot;: &quot;1.2.3.10&quot;,
  12093. &quot;last_seen&quot;: 1417222374500,
  12094. &quot;user_agent&quot;: &quot;Dalvik/2.1.0 ...&quot;
  12095. }
  12096. ]
  12097. }
  12098. ]
  12099. }
  12100. }
  12101. }
  12102. </code></pre>
  12103. <p><code>last_seen</code> is measured in milliseconds since the Unix epoch.</p>
  12104. <h2 id="deactivate-account"><a class="header" href="#deactivate-account">Deactivate Account</a></h2>
  12105. <p>This API deactivates an account. It removes active access tokens, resets the
  12106. password, and deletes third-party IDs (to prevent the user requesting a
  12107. password reset).</p>
  12108. <p>It can also mark the user as GDPR-erased. This means messages sent by the
  12109. user will still be visible by anyone that was in the room when these messages
  12110. were sent, but hidden from users joining the room afterwards.</p>
  12111. <p>The api is:</p>
  12112. <pre><code>POST /_synapse/admin/v1/deactivate/&lt;user_id&gt;
  12113. </code></pre>
  12114. <p>with a body of:</p>
  12115. <pre><code class="language-json">{
  12116. &quot;erase&quot;: true
  12117. }
  12118. </code></pre>
  12119. <p>The erase parameter is optional and defaults to <code>false</code>.
  12120. An empty body may be passed for backwards compatibility.</p>
  12121. <p>The following actions are performed when deactivating an user:</p>
  12122. <ul>
  12123. <li>Try to unbind 3PIDs from the identity server</li>
  12124. <li>Remove all 3PIDs from the homeserver</li>
  12125. <li>Delete all devices and E2EE keys</li>
  12126. <li>Delete all access tokens</li>
  12127. <li>Delete all pushers</li>
  12128. <li>Delete the password hash</li>
  12129. <li>Removal from all rooms the user is a member of</li>
  12130. <li>Remove the user from the user directory</li>
  12131. <li>Reject all pending invites</li>
  12132. <li>Remove all account validity information related to the user</li>
  12133. <li>Remove the arbitrary data store known as <em>account data</em>. For example, this includes:
  12134. <ul>
  12135. <li>list of ignored users;</li>
  12136. <li>push rules;</li>
  12137. <li>secret storage keys; and</li>
  12138. <li>cross-signing keys.</li>
  12139. </ul>
  12140. </li>
  12141. </ul>
  12142. <p>The following additional actions are performed during deactivation if <code>erase</code>
  12143. is set to <code>true</code>:</p>
  12144. <ul>
  12145. <li>Remove the user's display name</li>
  12146. <li>Remove the user's avatar URL</li>
  12147. <li>Mark the user as erased</li>
  12148. </ul>
  12149. <p>The following actions are <strong>NOT</strong> performed. The list may be incomplete.</p>
  12150. <ul>
  12151. <li>Remove mappings of SSO IDs</li>
  12152. <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>
  12153. <li>Delete sent and received messages</li>
  12154. <li>Remove the user's creation (registration) timestamp</li>
  12155. <li><a href="admin_api/user_admin_api.html#override-ratelimiting-for-users">Remove rate limit overrides</a></li>
  12156. <li>Remove from monthly active users</li>
  12157. </ul>
  12158. <h2 id="reset-password"><a class="header" href="#reset-password">Reset password</a></h2>
  12159. <p>Changes the password of another user. This will automatically log the user out of all their devices.</p>
  12160. <p>The api is:</p>
  12161. <pre><code>POST /_synapse/admin/v1/reset_password/&lt;user_id&gt;
  12162. </code></pre>
  12163. <p>with a body of:</p>
  12164. <pre><code class="language-json">{
  12165. &quot;new_password&quot;: &quot;&lt;secret&gt;&quot;,
  12166. &quot;logout_devices&quot;: true
  12167. }
  12168. </code></pre>
  12169. <p>The parameter <code>new_password</code> is required.
  12170. The parameter <code>logout_devices</code> is optional and defaults to <code>true</code>.</p>
  12171. <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>
  12172. <p>The api is:</p>
  12173. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  12174. </code></pre>
  12175. <p>A response body like the following is returned:</p>
  12176. <pre><code class="language-json">{
  12177. &quot;admin&quot;: true
  12178. }
  12179. </code></pre>
  12180. <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>
  12181. <p>Note that you cannot demote yourself.</p>
  12182. <p>The api is:</p>
  12183. <pre><code>PUT /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  12184. </code></pre>
  12185. <p>with a body of:</p>
  12186. <pre><code class="language-json">{
  12187. &quot;admin&quot;: true
  12188. }
  12189. </code></pre>
  12190. <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>
  12191. <p>Gets a list of all <code>room_id</code> that a specific <code>user_id</code> is member.</p>
  12192. <p>The API is:</p>
  12193. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/joined_rooms
  12194. </code></pre>
  12195. <p>A response body like the following is returned:</p>
  12196. <pre><code class="language-json"> {
  12197. &quot;joined_rooms&quot;: [
  12198. &quot;!DuGcnbhHGaSZQoNQR:matrix.org&quot;,
  12199. &quot;!ZtSaPCawyWtxfWiIy:matrix.org&quot;
  12200. ],
  12201. &quot;total&quot;: 2
  12202. }
  12203. </code></pre>
  12204. <p>The server returns the list of rooms of which the user and the server
  12205. are member. If the user is local, all the rooms of which the user is
  12206. member are returned.</p>
  12207. <p><strong>Parameters</strong></p>
  12208. <p>The following parameters should be set in the URL:</p>
  12209. <ul>
  12210. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12211. </ul>
  12212. <p><strong>Response</strong></p>
  12213. <p>The following fields are returned in the JSON response body:</p>
  12214. <ul>
  12215. <li><code>joined_rooms</code> - An array of <code>room_id</code>.</li>
  12216. <li><code>total</code> - Number of rooms.</li>
  12217. </ul>
  12218. <h2 id="account-data"><a class="header" href="#account-data">Account Data</a></h2>
  12219. <p>Gets information about account data for a specific <code>user_id</code>.</p>
  12220. <p>The API is:</p>
  12221. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/accountdata
  12222. </code></pre>
  12223. <p>A response body like the following is returned:</p>
  12224. <pre><code class="language-json">{
  12225. &quot;account_data&quot;: {
  12226. &quot;global&quot;: {
  12227. &quot;m.secret_storage.key.LmIGHTg5W&quot;: {
  12228. &quot;algorithm&quot;: &quot;m.secret_storage.v1.aes-hmac-sha2&quot;,
  12229. &quot;iv&quot;: &quot;fwjNZatxg==&quot;,
  12230. &quot;mac&quot;: &quot;eWh9kNnLWZUNOgnc=&quot;
  12231. },
  12232. &quot;im.vector.hide_profile&quot;: {
  12233. &quot;hide_profile&quot;: true
  12234. },
  12235. &quot;org.matrix.preview_urls&quot;: {
  12236. &quot;disable&quot;: false
  12237. },
  12238. &quot;im.vector.riot.breadcrumb_rooms&quot;: {
  12239. &quot;rooms&quot;: [
  12240. &quot;!LxcBDAsDUVAfJDEo:matrix.org&quot;,
  12241. &quot;!MAhRxqasbItjOqxu:matrix.org&quot;
  12242. ]
  12243. },
  12244. &quot;m.accepted_terms&quot;: {
  12245. &quot;accepted&quot;: [
  12246. &quot;https://example.org/somewhere/privacy-1.2-en.html&quot;,
  12247. &quot;https://example.org/somewhere/terms-2.0-en.html&quot;
  12248. ]
  12249. },
  12250. &quot;im.vector.setting.breadcrumbs&quot;: {
  12251. &quot;recent_rooms&quot;: [
  12252. &quot;!MAhRxqasbItqxuEt:matrix.org&quot;,
  12253. &quot;!ZtSaPCawyWtxiImy:matrix.org&quot;
  12254. ]
  12255. }
  12256. },
  12257. &quot;rooms&quot;: {
  12258. &quot;!GUdfZSHUJibpiVqHYd:matrix.org&quot;: {
  12259. &quot;m.fully_read&quot;: {
  12260. &quot;event_id&quot;: &quot;$156334540fYIhZ:matrix.org&quot;
  12261. }
  12262. },
  12263. &quot;!tOZwOOiqwCYQkLhV:matrix.org&quot;: {
  12264. &quot;m.fully_read&quot;: {
  12265. &quot;event_id&quot;: &quot;$xjsIyp4_NaVl2yPvIZs_k1Jl8tsC_Sp23wjqXPno&quot;
  12266. }
  12267. }
  12268. }
  12269. }
  12270. }
  12271. </code></pre>
  12272. <p><strong>Parameters</strong></p>
  12273. <p>The following parameters should be set in the URL:</p>
  12274. <ul>
  12275. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12276. </ul>
  12277. <p><strong>Response</strong></p>
  12278. <p>The following fields are returned in the JSON response body:</p>
  12279. <ul>
  12280. <li><code>account_data</code> - A map containing the account data for the user
  12281. <ul>
  12282. <li><code>global</code> - A map containing the global account data for the user</li>
  12283. <li><code>rooms</code> - A map containing the account data per room for the user</li>
  12284. </ul>
  12285. </li>
  12286. </ul>
  12287. <h2 id="user-media"><a class="header" href="#user-media">User media</a></h2>
  12288. <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>
  12289. <p>Gets a list of all local media that a specific <code>user_id</code> has created.
  12290. These are media that the user has uploaded themselves
  12291. (<a href="admin_api/../media_repository.html#local-media">local media</a>), as well as
  12292. <a href="admin_api/../media_repository.html#url-previews">URL preview images</a> requested by the user if the
  12293. <a href="admin_api/../development/url_previews.html">feature is enabled</a>.</p>
  12294. <p>By default, the response is ordered by descending creation date and ascending media ID.
  12295. The newest media is on top. You can change the order with parameters
  12296. <code>order_by</code> and <code>dir</code>.</p>
  12297. <p>The API is:</p>
  12298. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/media
  12299. </code></pre>
  12300. <p>A response body like the following is returned:</p>
  12301. <pre><code class="language-json">{
  12302. &quot;media&quot;: [
  12303. {
  12304. &quot;created_ts&quot;: 100400,
  12305. &quot;last_access_ts&quot;: null,
  12306. &quot;media_id&quot;: &quot;qXhyRzulkwLsNHTbpHreuEgo&quot;,
  12307. &quot;media_length&quot;: 67,
  12308. &quot;media_type&quot;: &quot;image/png&quot;,
  12309. &quot;quarantined_by&quot;: null,
  12310. &quot;safe_from_quarantine&quot;: false,
  12311. &quot;upload_name&quot;: &quot;test1.png&quot;
  12312. },
  12313. {
  12314. &quot;created_ts&quot;: 200400,
  12315. &quot;last_access_ts&quot;: null,
  12316. &quot;media_id&quot;: &quot;FHfiSnzoINDatrXHQIXBtahw&quot;,
  12317. &quot;media_length&quot;: 67,
  12318. &quot;media_type&quot;: &quot;image/png&quot;,
  12319. &quot;quarantined_by&quot;: null,
  12320. &quot;safe_from_quarantine&quot;: false,
  12321. &quot;upload_name&quot;: &quot;test2.png&quot;
  12322. }
  12323. ],
  12324. &quot;next_token&quot;: 3,
  12325. &quot;total&quot;: 2
  12326. }
  12327. </code></pre>
  12328. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  12329. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  12330. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  12331. reports to paginate through.</p>
  12332. <p><strong>Parameters</strong></p>
  12333. <p>The following parameters should be set in the URL:</p>
  12334. <ul>
  12335. <li>
  12336. <p><code>user_id</code> - string - fully qualified: for example, <code>@user:server.com</code>.</p>
  12337. </li>
  12338. <li>
  12339. <p><code>limit</code>: string representing a positive integer - Is optional but is used for pagination,
  12340. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  12341. </li>
  12342. <li>
  12343. <p><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  12344. denoting the offset in the returned results. This should be treated as an opaque value and
  12345. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  12346. Defaults to <code>0</code>.</p>
  12347. </li>
  12348. <li>
  12349. <p><code>order_by</code> - The method by which to sort the returned list of media.
  12350. If the ordered field has duplicates, the second order is always by ascending <code>media_id</code>,
  12351. which guarantees a stable ordering. Valid values are:</p>
  12352. <ul>
  12353. <li><code>media_id</code> - Media are ordered alphabetically by <code>media_id</code>.</li>
  12354. <li><code>upload_name</code> - Media are ordered alphabetically by name the media was uploaded with.</li>
  12355. <li><code>created_ts</code> - Media are ordered by when the content was uploaded in ms.
  12356. Smallest to largest. This is the default.</li>
  12357. <li><code>last_access_ts</code> - Media are ordered by when the content was last accessed in ms.
  12358. Smallest to largest.</li>
  12359. <li><code>media_length</code> - Media are ordered by length of the media in bytes.
  12360. Smallest to largest.</li>
  12361. <li><code>media_type</code> - Media are ordered alphabetically by MIME-type.</li>
  12362. <li><code>quarantined_by</code> - Media are ordered alphabetically by the user ID that
  12363. initiated the quarantine request for this media.</li>
  12364. <li><code>safe_from_quarantine</code> - Media are ordered by the status if this media is safe
  12365. from quarantining.</li>
  12366. </ul>
  12367. </li>
  12368. <li>
  12369. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  12370. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  12371. </li>
  12372. </ul>
  12373. <p>If neither <code>order_by</code> nor <code>dir</code> is set, the default order is newest media on top
  12374. (corresponds to <code>order_by</code> = <code>created_ts</code> and <code>dir</code> = <code>b</code>).</p>
  12375. <p>Caution. The database only has indexes on the columns <code>media_id</code>,
  12376. <code>user_id</code> and <code>created_ts</code>. This means that if a different sort order is used
  12377. (<code>upload_name</code>, <code>last_access_ts</code>, <code>media_length</code>, <code>media_type</code>,
  12378. <code>quarantined_by</code> or <code>safe_from_quarantine</code>), this can cause a large load on the
  12379. database, especially for large environments.</p>
  12380. <p><strong>Response</strong></p>
  12381. <p>The following fields are returned in the JSON response body:</p>
  12382. <ul>
  12383. <li><code>media</code> - An array of objects, each containing information about a media.
  12384. Media objects contain the following fields:
  12385. <ul>
  12386. <li><code>created_ts</code> - integer - Timestamp when the content was uploaded in ms.</li>
  12387. <li><code>last_access_ts</code> - integer - Timestamp when the content was last accessed in ms.</li>
  12388. <li><code>media_id</code> - string - The id used to refer to the media. Details about the format
  12389. are documented under
  12390. <a href="admin_api/../media_repository.html">media repository</a>.</li>
  12391. <li><code>media_length</code> - integer - Length of the media in bytes.</li>
  12392. <li><code>media_type</code> - string - The MIME-type of the media.</li>
  12393. <li><code>quarantined_by</code> - string - The user ID that initiated the quarantine request
  12394. for this media.</li>
  12395. <li><code>safe_from_quarantine</code> - bool - Status if this media is safe from quarantining.</li>
  12396. <li><code>upload_name</code> - string - The name the media was uploaded with.</li>
  12397. </ul>
  12398. </li>
  12399. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  12400. <li><code>total</code> - integer - Total number of media.</li>
  12401. </ul>
  12402. <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>
  12403. <p>This API deletes the <em>local</em> media from the disk of your own server
  12404. that a specific <code>user_id</code> has created. This includes any local thumbnails.</p>
  12405. <p>This API will not affect media that has been uploaded to external
  12406. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).</p>
  12407. <p>By default, the API deletes media ordered by descending creation date and ascending media ID.
  12408. The newest media is deleted first. You can change the order with parameters
  12409. <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>
  12410. <p>The API is:</p>
  12411. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/media
  12412. </code></pre>
  12413. <p>A response body like the following is returned:</p>
  12414. <pre><code class="language-json">{
  12415. &quot;deleted_media&quot;: [
  12416. &quot;abcdefghijklmnopqrstuvwx&quot;
  12417. ],
  12418. &quot;total&quot;: 1
  12419. }
  12420. </code></pre>
  12421. <p>The following fields are returned in the JSON response body:</p>
  12422. <ul>
  12423. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  12424. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  12425. </ul>
  12426. <p><strong>Note</strong>: There is no <code>next_token</code>. This is not useful for deleting media, because
  12427. after deleting media the remaining media have a new order.</p>
  12428. <p><strong>Parameters</strong></p>
  12429. <p>This API has the same parameters as
  12430. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>.
  12431. With the parameters you can for example limit the number of files to delete at once or
  12432. delete largest/smallest or newest/oldest files first.</p>
  12433. <h2 id="login-as-a-user"><a class="header" href="#login-as-a-user">Login as a user</a></h2>
  12434. <p>Get an access token that can be used to authenticate as that user. Useful for
  12435. when admins wish to do actions on behalf of a user.</p>
  12436. <p>The API is:</p>
  12437. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/login
  12438. {}
  12439. </code></pre>
  12440. <p>An optional <code>valid_until_ms</code> field can be specified in the request body as an
  12441. integer timestamp that specifies when the token should expire. By default tokens
  12442. do not expire.</p>
  12443. <p>A response body like the following is returned:</p>
  12444. <pre><code class="language-json">{
  12445. &quot;access_token&quot;: &quot;&lt;opaque_access_token_string&gt;&quot;
  12446. }
  12447. </code></pre>
  12448. <p>This API does <em>not</em> generate a new device for the user, and so will not appear
  12449. their <code>/devices</code> list, and in general the target user should not be able to
  12450. tell they have been logged in as.</p>
  12451. <p>To expire the token call the standard <code>/logout</code> API with the token.</p>
  12452. <p>Note: The token will expire if the <em>admin</em> user calls <code>/logout/all</code> from any
  12453. of their devices, but the token will <em>not</em> expire if the target user does the
  12454. same.</p>
  12455. <h2 id="user-devices"><a class="header" href="#user-devices">User devices</a></h2>
  12456. <h3 id="list-all-devices"><a class="header" href="#list-all-devices">List all devices</a></h3>
  12457. <p>Gets information about all devices for a specific <code>user_id</code>.</p>
  12458. <p>The API is:</p>
  12459. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices
  12460. </code></pre>
  12461. <p>A response body like the following is returned:</p>
  12462. <pre><code class="language-json">{
  12463. &quot;devices&quot;: [
  12464. {
  12465. &quot;device_id&quot;: &quot;QBUAZIFURK&quot;,
  12466. &quot;display_name&quot;: &quot;android&quot;,
  12467. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  12468. &quot;last_seen_ts&quot;: 1474491775024,
  12469. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  12470. },
  12471. {
  12472. &quot;device_id&quot;: &quot;AUIECTSRND&quot;,
  12473. &quot;display_name&quot;: &quot;ios&quot;,
  12474. &quot;last_seen_ip&quot;: &quot;1.2.3.5&quot;,
  12475. &quot;last_seen_ts&quot;: 1474491775025,
  12476. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  12477. }
  12478. ],
  12479. &quot;total&quot;: 2
  12480. }
  12481. </code></pre>
  12482. <p><strong>Parameters</strong></p>
  12483. <p>The following parameters should be set in the URL:</p>
  12484. <ul>
  12485. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12486. </ul>
  12487. <p><strong>Response</strong></p>
  12488. <p>The following fields are returned in the JSON response body:</p>
  12489. <ul>
  12490. <li>
  12491. <p><code>devices</code> - An array of objects, each containing information about a device.
  12492. Device objects contain the following fields:</p>
  12493. <ul>
  12494. <li><code>device_id</code> - Identifier of device.</li>
  12495. <li><code>display_name</code> - Display name set by the user for this device.
  12496. Absent if no name has been set.</li>
  12497. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  12498. (May be a few minutes out of date, for efficiency reasons).</li>
  12499. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  12500. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  12501. <li><code>user_id</code> - Owner of device.</li>
  12502. </ul>
  12503. </li>
  12504. <li>
  12505. <p><code>total</code> - Total number of user's devices.</p>
  12506. </li>
  12507. </ul>
  12508. <h3 id="delete-multiple-devices"><a class="header" href="#delete-multiple-devices">Delete multiple devices</a></h3>
  12509. <p>Deletes the given devices for a specific <code>user_id</code>, and invalidates
  12510. any access token associated with them.</p>
  12511. <p>The API is:</p>
  12512. <pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/delete_devices
  12513. {
  12514. &quot;devices&quot;: [
  12515. &quot;QBUAZIFURK&quot;,
  12516. &quot;AUIECTSRND&quot;
  12517. ]
  12518. }
  12519. </code></pre>
  12520. <p>An empty JSON dict is returned.</p>
  12521. <p><strong>Parameters</strong></p>
  12522. <p>The following parameters should be set in the URL:</p>
  12523. <ul>
  12524. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12525. </ul>
  12526. <p>The following fields are required in the JSON request body:</p>
  12527. <ul>
  12528. <li><code>devices</code> - The list of device IDs to delete.</li>
  12529. </ul>
  12530. <h3 id="show-a-device"><a class="header" href="#show-a-device">Show a device</a></h3>
  12531. <p>Gets information on a single device, by <code>device_id</code> for a specific <code>user_id</code>.</p>
  12532. <p>The API is:</p>
  12533. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  12534. </code></pre>
  12535. <p>A response body like the following is returned:</p>
  12536. <pre><code class="language-json">{
  12537. &quot;device_id&quot;: &quot;&lt;device_id&gt;&quot;,
  12538. &quot;display_name&quot;: &quot;android&quot;,
  12539. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  12540. &quot;last_seen_ts&quot;: 1474491775024,
  12541. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  12542. }
  12543. </code></pre>
  12544. <p><strong>Parameters</strong></p>
  12545. <p>The following parameters should be set in the URL:</p>
  12546. <ul>
  12547. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12548. <li><code>device_id</code> - The device to retrieve.</li>
  12549. </ul>
  12550. <p><strong>Response</strong></p>
  12551. <p>The following fields are returned in the JSON response body:</p>
  12552. <ul>
  12553. <li><code>device_id</code> - Identifier of device.</li>
  12554. <li><code>display_name</code> - Display name set by the user for this device.
  12555. Absent if no name has been set.</li>
  12556. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  12557. (May be a few minutes out of date, for efficiency reasons).</li>
  12558. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  12559. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  12560. <li><code>user_id</code> - Owner of device.</li>
  12561. </ul>
  12562. <h3 id="update-a-device"><a class="header" href="#update-a-device">Update a device</a></h3>
  12563. <p>Updates the metadata on the given <code>device_id</code> for a specific <code>user_id</code>.</p>
  12564. <p>The API is:</p>
  12565. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  12566. {
  12567. &quot;display_name&quot;: &quot;My other phone&quot;
  12568. }
  12569. </code></pre>
  12570. <p>An empty JSON dict is returned.</p>
  12571. <p><strong>Parameters</strong></p>
  12572. <p>The following parameters should be set in the URL:</p>
  12573. <ul>
  12574. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12575. <li><code>device_id</code> - The device to update.</li>
  12576. </ul>
  12577. <p>The following fields are required in the JSON request body:</p>
  12578. <ul>
  12579. <li><code>display_name</code> - The new display name for this device. If not given,
  12580. the display name is unchanged.</li>
  12581. </ul>
  12582. <h3 id="delete-a-device"><a class="header" href="#delete-a-device">Delete a device</a></h3>
  12583. <p>Deletes the given <code>device_id</code> for a specific <code>user_id</code>,
  12584. and invalidates any access token associated with it.</p>
  12585. <p>The API is:</p>
  12586. <pre><code>DELETE /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  12587. {}
  12588. </code></pre>
  12589. <p>An empty JSON dict is returned.</p>
  12590. <p><strong>Parameters</strong></p>
  12591. <p>The following parameters should be set in the URL:</p>
  12592. <ul>
  12593. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12594. <li><code>device_id</code> - The device to delete.</li>
  12595. </ul>
  12596. <h2 id="list-all-pushers"><a class="header" href="#list-all-pushers">List all pushers</a></h2>
  12597. <p>Gets information about all pushers for a specific <code>user_id</code>.</p>
  12598. <p>The API is:</p>
  12599. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/pushers
  12600. </code></pre>
  12601. <p>A response body like the following is returned:</p>
  12602. <pre><code class="language-json">{
  12603. &quot;pushers&quot;: [
  12604. {
  12605. &quot;app_display_name&quot;:&quot;HTTP Push Notifications&quot;,
  12606. &quot;app_id&quot;:&quot;m.http&quot;,
  12607. &quot;data&quot;: {
  12608. &quot;url&quot;:&quot;example.com&quot;
  12609. },
  12610. &quot;device_display_name&quot;:&quot;pushy push&quot;,
  12611. &quot;kind&quot;:&quot;http&quot;,
  12612. &quot;lang&quot;:&quot;None&quot;,
  12613. &quot;profile_tag&quot;:&quot;&quot;,
  12614. &quot;pushkey&quot;:&quot;a@example.com&quot;
  12615. }
  12616. ],
  12617. &quot;total&quot;: 1
  12618. }
  12619. </code></pre>
  12620. <p><strong>Parameters</strong></p>
  12621. <p>The following parameters should be set in the URL:</p>
  12622. <ul>
  12623. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  12624. </ul>
  12625. <p><strong>Response</strong></p>
  12626. <p>The following fields are returned in the JSON response body:</p>
  12627. <ul>
  12628. <li>
  12629. <p><code>pushers</code> - An array containing the current pushers for the user</p>
  12630. <ul>
  12631. <li>
  12632. <p><code>app_display_name</code> - string - A string that will allow the user to identify
  12633. what application owns this pusher.</p>
  12634. </li>
  12635. <li>
  12636. <p><code>app_id</code> - string - This is a reverse-DNS style identifier for the application.
  12637. Max length, 64 chars.</p>
  12638. </li>
  12639. <li>
  12640. <p><code>data</code> - A dictionary of information for the pusher implementation itself.</p>
  12641. <ul>
  12642. <li>
  12643. <p><code>url</code> - string - Required if <code>kind</code> is <code>http</code>. The URL to use to send
  12644. notifications to.</p>
  12645. </li>
  12646. <li>
  12647. <p><code>format</code> - string - The format to use when sending notifications to the
  12648. Push Gateway.</p>
  12649. </li>
  12650. </ul>
  12651. </li>
  12652. <li>
  12653. <p><code>device_display_name</code> - string - A string that will allow the user to identify
  12654. what device owns this pusher.</p>
  12655. </li>
  12656. <li>
  12657. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  12658. this pusher executes.</p>
  12659. </li>
  12660. <li>
  12661. <p><code>kind</code> - string - The kind of pusher. &quot;http&quot; is a pusher that sends HTTP pokes.</p>
  12662. </li>
  12663. <li>
  12664. <p><code>lang</code> - string - The preferred language for receiving notifications
  12665. (e.g. 'en' or 'en-US')</p>
  12666. </li>
  12667. <li>
  12668. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  12669. this pusher executes.</p>
  12670. </li>
  12671. <li>
  12672. <p><code>pushkey</code> - string - This is a unique identifier for this pusher.
  12673. Max length, 512 bytes.</p>
  12674. </li>
  12675. </ul>
  12676. </li>
  12677. <li>
  12678. <p><code>total</code> - integer - Number of pushers.</p>
  12679. </li>
  12680. </ul>
  12681. <p>See also the
  12682. <a href="https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-pushers">Client-Server API Spec on pushers</a>.</p>
  12683. <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>
  12684. <p>Shadow-banning is a useful tool for moderating malicious or egregiously abusive users.
  12685. A shadow-banned users receives successful responses to their client-server API requests,
  12686. but the events are not propagated into rooms. This can be an effective tool as it
  12687. (hopefully) takes longer for the user to realise they are being moderated before
  12688. pivoting to another account.</p>
  12689. <p>Shadow-banning a user should be used as a tool of last resort and may lead to confusing
  12690. or broken behaviour for the client. A shadow-banned user will not receive any
  12691. notification and it is generally more appropriate to ban or kick abusive users.
  12692. A shadow-banned user will be unable to contact anyone on the server.</p>
  12693. <p>To shadow-ban a user the API is:</p>
  12694. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  12695. </code></pre>
  12696. <p>To un-shadow-ban a user the API is:</p>
  12697. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  12698. </code></pre>
  12699. <p>An empty JSON dict is returned in both cases.</p>
  12700. <p><strong>Parameters</strong></p>
  12701. <p>The following parameters should be set in the URL:</p>
  12702. <ul>
  12703. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  12704. be local.</li>
  12705. </ul>
  12706. <h2 id="override-ratelimiting-for-users"><a class="header" href="#override-ratelimiting-for-users">Override ratelimiting for users</a></h2>
  12707. <p>This API allows to override or disable ratelimiting for a specific user.
  12708. There are specific APIs to set, get and delete a ratelimit.</p>
  12709. <h3 id="get-status-of-ratelimit"><a class="header" href="#get-status-of-ratelimit">Get status of ratelimit</a></h3>
  12710. <p>The API is:</p>
  12711. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  12712. </code></pre>
  12713. <p>A response body like the following is returned:</p>
  12714. <pre><code class="language-json">{
  12715. &quot;messages_per_second&quot;: 0,
  12716. &quot;burst_count&quot;: 0
  12717. }
  12718. </code></pre>
  12719. <p><strong>Parameters</strong></p>
  12720. <p>The following parameters should be set in the URL:</p>
  12721. <ul>
  12722. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  12723. be local.</li>
  12724. </ul>
  12725. <p><strong>Response</strong></p>
  12726. <p>The following fields are returned in the JSON response body:</p>
  12727. <ul>
  12728. <li><code>messages_per_second</code> - integer - The number of actions that can
  12729. be performed in a second. <code>0</code> mean that ratelimiting is disabled for this user.</li>
  12730. <li><code>burst_count</code> - integer - How many actions that can be performed before
  12731. being limited.</li>
  12732. </ul>
  12733. <p>If <strong>no</strong> custom ratelimit is set, an empty JSON dict is returned.</p>
  12734. <pre><code class="language-json">{}
  12735. </code></pre>
  12736. <h3 id="set-ratelimit"><a class="header" href="#set-ratelimit">Set ratelimit</a></h3>
  12737. <p>The API is:</p>
  12738. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  12739. </code></pre>
  12740. <p>A response body like the following is returned:</p>
  12741. <pre><code class="language-json">{
  12742. &quot;messages_per_second&quot;: 0,
  12743. &quot;burst_count&quot;: 0
  12744. }
  12745. </code></pre>
  12746. <p><strong>Parameters</strong></p>
  12747. <p>The following parameters should be set in the URL:</p>
  12748. <ul>
  12749. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  12750. be local.</li>
  12751. </ul>
  12752. <p>Body parameters:</p>
  12753. <ul>
  12754. <li><code>messages_per_second</code> - positive integer, optional. The number of actions that can
  12755. be performed in a second. Defaults to <code>0</code>.</li>
  12756. <li><code>burst_count</code> - positive integer, optional. How many actions that can be performed
  12757. before being limited. Defaults to <code>0</code>.</li>
  12758. </ul>
  12759. <p>To disable users' ratelimit set both values to <code>0</code>.</p>
  12760. <p><strong>Response</strong></p>
  12761. <p>The following fields are returned in the JSON response body:</p>
  12762. <ul>
  12763. <li><code>messages_per_second</code> - integer - The number of actions that can
  12764. be performed in a second.</li>
  12765. <li><code>burst_count</code> - integer - How many actions that can be performed before
  12766. being limited.</li>
  12767. </ul>
  12768. <h3 id="delete-ratelimit"><a class="header" href="#delete-ratelimit">Delete ratelimit</a></h3>
  12769. <p>The API is:</p>
  12770. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  12771. </code></pre>
  12772. <p>An empty JSON dict is returned.</p>
  12773. <pre><code class="language-json">{}
  12774. </code></pre>
  12775. <p><strong>Parameters</strong></p>
  12776. <p>The following parameters should be set in the URL:</p>
  12777. <ul>
  12778. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  12779. be local.</li>
  12780. </ul>
  12781. <h3 id="check-username-availability"><a class="header" href="#check-username-availability">Check username availability</a></h3>
  12782. <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
  12783. API</a>
  12784. for more information.</p>
  12785. <p>This endpoint will work even if registration is disabled on the server, unlike
  12786. <code>/_matrix/client/r0/register/available</code>.</p>
  12787. <p>The API is:</p>
  12788. <pre><code>GET /_synapse/admin/v1/username_available?username=$localpart
  12789. </code></pre>
  12790. <p>The request and response format is the same as the
  12791. <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>
  12792. <div style="break-before: page; page-break-before: always;"></div><h1 id="version-api"><a class="header" href="#version-api">Version API</a></h1>
  12793. <p>This API returns the running Synapse version and the Python version
  12794. on which Synapse is being run. This is useful when a Synapse instance
  12795. is behind a proxy that does not forward the 'Server' header (which also
  12796. contains Synapse version information).</p>
  12797. <p>The api is:</p>
  12798. <pre><code>GET /_synapse/admin/v1/server_version
  12799. </code></pre>
  12800. <p>It returns a JSON body like the following:</p>
  12801. <pre><code class="language-json">{
  12802. &quot;server_version&quot;: &quot;0.99.2rc1 (b=develop, abcdef123)&quot;,
  12803. &quot;python_version&quot;: &quot;3.7.8&quot;
  12804. }
  12805. </code></pre>
  12806. <div style="break-before: page; page-break-before: always;"></div><h1 id="federation-api"><a class="header" href="#federation-api">Federation API</a></h1>
  12807. <p>This API allows a server administrator to manage Synapse's federation with other homeservers.</p>
  12808. <p>Note: This API is new, experimental and &quot;subject to change&quot;.</p>
  12809. <h2 id="list-of-destinations"><a class="header" href="#list-of-destinations">List of destinations</a></h2>
  12810. <p>This API gets the current destination retry timing info for all remote servers.</p>
  12811. <p>The list contains all the servers with which the server federates,
  12812. regardless of whether an error occurred or not.
  12813. If an error occurs, it may take up to 20 minutes for the error to be displayed here,
  12814. as a complete retry must have failed.</p>
  12815. <p>The API is:</p>
  12816. <p>A standard request with no filtering:</p>
  12817. <pre><code>GET /_synapse/admin/v1/federation/destinations
  12818. </code></pre>
  12819. <p>A response body like the following is returned:</p>
  12820. <pre><code class="language-json">{
  12821. &quot;destinations&quot;:[
  12822. {
  12823. &quot;destination&quot;: &quot;matrix.org&quot;,
  12824. &quot;retry_last_ts&quot;: 1557332397936,
  12825. &quot;retry_interval&quot;: 3000000,
  12826. &quot;failure_ts&quot;: 1557329397936,
  12827. &quot;last_successful_stream_ordering&quot;: null
  12828. }
  12829. ],
  12830. &quot;total&quot;: 1
  12831. }
  12832. </code></pre>
  12833. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  12834. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  12835. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  12836. to paginate through.</p>
  12837. <p><strong>Parameters</strong></p>
  12838. <p>The following query parameters are available:</p>
  12839. <ul>
  12840. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  12841. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  12842. <li><code>order_by</code> - The method in which to sort the returned list of destinations.
  12843. Valid values are:
  12844. <ul>
  12845. <li><code>destination</code> - Destinations are ordered alphabetically by remote server name.
  12846. This is the default.</li>
  12847. <li><code>retry_last_ts</code> - Destinations are ordered by time of last retry attempt in ms.</li>
  12848. <li><code>retry_interval</code> - Destinations are ordered by how long until next retry in ms.</li>
  12849. <li><code>failure_ts</code> - Destinations are ordered by when the server started failing in ms.</li>
  12850. <li><code>last_successful_stream_ordering</code> - Destinations are ordered by the stream ordering
  12851. of the most recent successfully-sent PDU.</li>
  12852. </ul>
  12853. </li>
  12854. <li><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  12855. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  12856. </ul>
  12857. <p><em>Caution:</em> The database only has an index on the column <code>destination</code>.
  12858. This means that if a different sort order is used,
  12859. this can cause a large load on the database, especially for large environments.</p>
  12860. <p><strong>Response</strong></p>
  12861. <p>The following fields are returned in the JSON response body:</p>
  12862. <ul>
  12863. <li><code>destinations</code> - An array of objects, each containing information about a destination.
  12864. Destination objects contain the following fields:
  12865. <ul>
  12866. <li><code>destination</code> - string - Name of the remote server to federate.</li>
  12867. <li><code>retry_last_ts</code> - integer - The last time Synapse tried and failed to reach the
  12868. remote server, in ms. This is <code>0</code> if the last attempt to communicate with the
  12869. remote server was successful.</li>
  12870. <li><code>retry_interval</code> - integer - How long since the last time Synapse tried to reach
  12871. the remote server before trying again, in ms. This is <code>0</code> if no further retrying occuring.</li>
  12872. <li><code>failure_ts</code> - nullable integer - The first time Synapse tried and failed to reach the
  12873. remote server, in ms. This is <code>null</code> if communication with the remote server has never failed.</li>
  12874. <li><code>last_successful_stream_ordering</code> - nullable integer - The stream ordering of the most
  12875. recent successfully-sent <a href="usage/administration/admin_api/understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  12876. to this destination, or <code>null</code> if this information has not been tracked yet.</li>
  12877. </ul>
  12878. </li>
  12879. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  12880. <li><code>total</code> - integer - Total number of destinations.</li>
  12881. </ul>
  12882. <h2 id="destination-details-api"><a class="header" href="#destination-details-api">Destination Details API</a></h2>
  12883. <p>This API gets the retry timing info for a specific remote server.</p>
  12884. <p>The API is:</p>
  12885. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;
  12886. </code></pre>
  12887. <p>A response body like the following is returned:</p>
  12888. <pre><code class="language-json">{
  12889. &quot;destination&quot;: &quot;matrix.org&quot;,
  12890. &quot;retry_last_ts&quot;: 1557332397936,
  12891. &quot;retry_interval&quot;: 3000000,
  12892. &quot;failure_ts&quot;: 1557329397936,
  12893. &quot;last_successful_stream_ordering&quot;: null
  12894. }
  12895. </code></pre>
  12896. <p><strong>Parameters</strong></p>
  12897. <p>The following parameters should be set in the URL:</p>
  12898. <ul>
  12899. <li><code>destination</code> - Name of the remote server.</li>
  12900. </ul>
  12901. <p><strong>Response</strong></p>
  12902. <p>The response fields are the same like in the <code>destinations</code> array in
  12903. <a href="usage/administration/admin_api/federation.html#list-of-destinations">List of destinations</a> response.</p>
  12904. <h2 id="destination-rooms"><a class="header" href="#destination-rooms">Destination rooms</a></h2>
  12905. <p>This API gets the rooms that federate with a specific remote server.</p>
  12906. <p>The API is:</p>
  12907. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/rooms
  12908. </code></pre>
  12909. <p>A response body like the following is returned:</p>
  12910. <pre><code class="language-json">{
  12911. &quot;rooms&quot;:[
  12912. {
  12913. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  12914. &quot;stream_ordering&quot;: 8326
  12915. },
  12916. {
  12917. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  12918. &quot;stream_ordering&quot;: 93534
  12919. }
  12920. ],
  12921. &quot;total&quot;: 2
  12922. }
  12923. </code></pre>
  12924. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  12925. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  12926. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  12927. to paginate through.</p>
  12928. <p><strong>Parameters</strong></p>
  12929. <p>The following parameters should be set in the URL:</p>
  12930. <ul>
  12931. <li><code>destination</code> - Name of the remote server.</li>
  12932. </ul>
  12933. <p>The following query parameters are available:</p>
  12934. <ul>
  12935. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  12936. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  12937. <li><code>dir</code> - Direction of room order by <code>room_id</code>. Either <code>f</code> for forwards or <code>b</code> for
  12938. backwards. Defaults to <code>f</code>.</li>
  12939. </ul>
  12940. <p><strong>Response</strong></p>
  12941. <p>The following fields are returned in the JSON response body:</p>
  12942. <ul>
  12943. <li><code>rooms</code> - An array of objects, each containing information about a room.
  12944. Room objects contain the following fields:
  12945. <ul>
  12946. <li><code>room_id</code> - string - The ID of the room.</li>
  12947. <li><code>stream_ordering</code> - integer - The stream ordering of the most recent
  12948. successfully-sent <a href="usage/administration/admin_api/understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  12949. to this destination in this room.</li>
  12950. </ul>
  12951. </li>
  12952. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  12953. <li><code>total</code> - integer - Total number of destinations.</li>
  12954. </ul>
  12955. <h2 id="reset-connection-timeout"><a class="header" href="#reset-connection-timeout">Reset connection timeout</a></h2>
  12956. <p>Synapse makes federation requests to other homeservers. If a federation request fails,
  12957. Synapse will mark the destination homeserver as offline, preventing any future requests
  12958. to that server for a &quot;cooldown&quot; period. This period grows over time if the server
  12959. continues to fail its responses
  12960. (<a href="https://en.wikipedia.org/wiki/Exponential_backoff">exponential backoff</a>).</p>
  12961. <p>Admins can cancel the cooldown period with this API.</p>
  12962. <p>This API resets the retry timing for a specific remote server and tries to connect to
  12963. the remote server again. It does not wait for the next <code>retry_interval</code>.
  12964. The connection must have previously run into an error and <code>retry_last_ts</code>
  12965. (<a href="usage/administration/admin_api/federation.html#destination-details-api">Destination Details API</a>) must not be equal to <code>0</code>.</p>
  12966. <p>The connection attempt is carried out in the background and can take a while
  12967. even if the API already returns the http status 200.</p>
  12968. <p>The API is:</p>
  12969. <pre><code>POST /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/reset_connection
  12970. {}
  12971. </code></pre>
  12972. <p><strong>Parameters</strong></p>
  12973. <p>The following parameters should be set in the URL:</p>
  12974. <ul>
  12975. <li><code>destination</code> - Name of the remote server.</li>
  12976. </ul>
  12977. <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>
  12978. <p>The &quot;manhole&quot; allows server administrators to access a Python shell on a running
  12979. Synapse installation. This is a very powerful mechanism for administration and
  12980. debugging.</p>
  12981. <p><strong><em>Security Warning</em></strong></p>
  12982. <p>Note that this will give administrative access to synapse to <strong>all users</strong> with
  12983. shell access to the server. It should therefore <strong>not</strong> be enabled in
  12984. environments where untrusted users have shell access.</p>
  12985. <h2 id="configuring-the-manhole"><a class="header" href="#configuring-the-manhole">Configuring the manhole</a></h2>
  12986. <p>To enable it, first uncomment the <code>manhole</code> listener configuration in
  12987. <code>homeserver.yaml</code>. The configuration is slightly different if you're using docker.</p>
  12988. <h4 id="docker-config"><a class="header" href="#docker-config">Docker config</a></h4>
  12989. <p>If you are using Docker, set <code>bind_addresses</code> to <code>['0.0.0.0']</code> as shown:</p>
  12990. <pre><code class="language-yaml">listeners:
  12991. - port: 9000
  12992. bind_addresses: ['0.0.0.0']
  12993. type: manhole
  12994. </code></pre>
  12995. <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
  12996. <code>manhole</code> port forwarding. The <code>-p 127.0.0.1:9000:9000</code> below is important: it
  12997. ensures that access to the <code>manhole</code> is only possible for local users.</p>
  12998. <pre><code class="language-bash">docker run -d --name synapse \
  12999. --mount type=volume,src=synapse-data,dst=/data \
  13000. -p 8008:8008 \
  13001. -p 127.0.0.1:9000:9000 \
  13002. matrixdotorg/synapse:latest
  13003. </code></pre>
  13004. <h4 id="native-config"><a class="header" href="#native-config">Native config</a></h4>
  13005. <p>If you are not using docker, set <code>bind_addresses</code> to <code>['::1', '127.0.0.1']</code> as shown.
  13006. The <code>bind_addresses</code> in the example below is important: it ensures that access to the
  13007. <code>manhole</code> is only possible for local users).</p>
  13008. <pre><code class="language-yaml">listeners:
  13009. - port: 9000
  13010. bind_addresses: ['::1', '127.0.0.1']
  13011. type: manhole
  13012. </code></pre>
  13013. <h3 id="security-settings"><a class="header" href="#security-settings">Security settings</a></h3>
  13014. <p>The following config options are available:</p>
  13015. <ul>
  13016. <li><code>username</code> - The username for the manhole (defaults to <code>matrix</code>)</li>
  13017. <li><code>password</code> - The password for the manhole (defaults to <code>rabbithole</code>)</li>
  13018. <li><code>ssh_priv_key</code> - The path to a private SSH key (defaults to a hardcoded value)</li>
  13019. <li><code>ssh_pub_key</code> - The path to a public SSH key (defaults to a hardcoded value)</li>
  13020. </ul>
  13021. <p>For example:</p>
  13022. <pre><code class="language-yaml">manhole_settings:
  13023. username: manhole
  13024. password: mypassword
  13025. ssh_priv_key: &quot;/home/synapse/manhole_keys/id_rsa&quot;
  13026. ssh_pub_key: &quot;/home/synapse/manhole_keys/id_rsa.pub&quot;
  13027. </code></pre>
  13028. <h2 id="accessing-synapse-manhole"><a class="header" href="#accessing-synapse-manhole">Accessing synapse manhole</a></h2>
  13029. <p>Then restart synapse, and point an ssh client at port 9000 on localhost, using
  13030. the username and password configured in <code>homeserver.yaml</code> - with the default
  13031. configuration, this would be:</p>
  13032. <pre><code class="language-bash">ssh -p9000 matrix@localhost
  13033. </code></pre>
  13034. <p>Then enter the password when prompted (the default is <code>rabbithole</code>).</p>
  13035. <p>This gives a Python REPL in which <code>hs</code> gives access to the
  13036. <code>synapse.server.HomeServer</code> object - which in turn gives access to many other
  13037. parts of the process.</p>
  13038. <p>Note that, prior to Synapse 1.41, any call which returns a coroutine will need to be wrapped in <code>ensureDeferred</code>.</p>
  13039. <p>As a simple example, retrieving an event from the database:</p>
  13040. <pre><code class="language-pycon">&gt;&gt;&gt; from twisted.internet import defer
  13041. &gt;&gt;&gt; defer.ensureDeferred(hs.get_datastores().main.get_event('$1416420717069yeQaw:matrix.org'))
  13042. &lt;Deferred at 0x7ff253fc6998 current result: &lt;FrozenEvent event_id='$1416420717069yeQaw:matrix.org', type='m.room.create', state_key=''&gt;&gt;
  13043. </code></pre>
  13044. <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>
  13045. <ol>
  13046. <li>
  13047. <p>Install Prometheus:</p>
  13048. <p>Follow instructions at
  13049. <a href="http://prometheus.io/docs/introduction/install/">http://prometheus.io/docs/introduction/install/</a></p>
  13050. </li>
  13051. <li>
  13052. <p>Enable Synapse metrics:</p>
  13053. <p>There are two methods of enabling metrics in Synapse.</p>
  13054. <p>The first serves the metrics as a part of the usual web server and
  13055. can be enabled by adding the &quot;metrics&quot; resource to the existing
  13056. listener as such:</p>
  13057. <pre><code class="language-yaml"> resources:
  13058. - names:
  13059. - client
  13060. - metrics
  13061. </code></pre>
  13062. <p>This provides a simple way of adding metrics to your Synapse
  13063. installation, and serves under <code>/_synapse/metrics</code>. If you do not
  13064. wish your metrics be publicly exposed, you will need to either
  13065. filter it out at your load balancer, or use the second method.</p>
  13066. <p>The second method runs the metrics server on a different port, in a
  13067. different thread to Synapse. This can make it more resilient to
  13068. heavy load meaning metrics cannot be retrieved, and can be exposed
  13069. to just internal networks easier. The served metrics are available
  13070. over HTTP only, and will be available at <code>/_synapse/metrics</code>.</p>
  13071. <p>Add a new listener to homeserver.yaml:</p>
  13072. <pre><code class="language-yaml"> listeners:
  13073. - type: metrics
  13074. port: 9000
  13075. bind_addresses:
  13076. - '0.0.0.0'
  13077. </code></pre>
  13078. <p>For both options, you will need to ensure that <code>enable_metrics</code> is
  13079. set to <code>True</code>.</p>
  13080. </li>
  13081. <li>
  13082. <p>Restart Synapse.</p>
  13083. </li>
  13084. <li>
  13085. <p>Add a Prometheus target for Synapse.</p>
  13086. <p>It needs to set the <code>metrics_path</code> to a non-default value (under
  13087. <code>scrape_configs</code>):</p>
  13088. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  13089. scrape_interval: 15s
  13090. metrics_path: &quot;/_synapse/metrics&quot;
  13091. static_configs:
  13092. - targets: [&quot;my.server.here:port&quot;]
  13093. </code></pre>
  13094. <p>where <code>my.server.here</code> is the IP address of Synapse, and <code>port</code> is
  13095. the listener port configured with the <code>metrics</code> resource.</p>
  13096. <p>If your prometheus is older than 1.5.2, you will need to replace
  13097. <code>static_configs</code> in the above with <code>target_groups</code>.</p>
  13098. </li>
  13099. <li>
  13100. <p>Restart Prometheus.</p>
  13101. </li>
  13102. <li>
  13103. <p>Consider using the <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana/">grafana dashboard</a>
  13104. and required <a href="https://github.com/matrix-org/synapse/tree/master/contrib/prometheus/">recording rules</a> </p>
  13105. </li>
  13106. </ol>
  13107. <h2 id="monitoring-workers"><a class="header" href="#monitoring-workers">Monitoring workers</a></h2>
  13108. <p>To monitor a Synapse installation using <a href="workers.html">workers</a>,
  13109. every worker needs to be monitored independently, in addition to
  13110. the main homeserver process. This is because workers don't send
  13111. their metrics to the main homeserver process, but expose them
  13112. directly (if they are configured to do so).</p>
  13113. <p>To allow collecting metrics from a worker, you need to add a
  13114. <code>metrics</code> listener to its configuration, by adding the following
  13115. under <code>worker_listeners</code>:</p>
  13116. <pre><code class="language-yaml"> - type: metrics
  13117. bind_address: ''
  13118. port: 9101
  13119. </code></pre>
  13120. <p>The <code>bind_address</code> and <code>port</code> parameters should be set so that
  13121. the resulting listener can be reached by prometheus, and they
  13122. don't clash with an existing worker.
  13123. With this example, the worker's metrics would then be available
  13124. on <code>http://127.0.0.1:9101</code>.</p>
  13125. <p>Example Prometheus target for Synapse with workers:</p>
  13126. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  13127. scrape_interval: 15s
  13128. metrics_path: &quot;/_synapse/metrics&quot;
  13129. static_configs:
  13130. - targets: [&quot;my.server.here:port&quot;]
  13131. labels:
  13132. instance: &quot;my.server&quot;
  13133. job: &quot;master&quot;
  13134. index: 1
  13135. - targets: [&quot;my.workerserver.here:port&quot;]
  13136. labels:
  13137. instance: &quot;my.server&quot;
  13138. job: &quot;generic_worker&quot;
  13139. index: 1
  13140. - targets: [&quot;my.workerserver.here:port&quot;]
  13141. labels:
  13142. instance: &quot;my.server&quot;
  13143. job: &quot;generic_worker&quot;
  13144. index: 2
  13145. - targets: [&quot;my.workerserver.here:port&quot;]
  13146. labels:
  13147. instance: &quot;my.server&quot;
  13148. job: &quot;media_repository&quot;
  13149. index: 1
  13150. </code></pre>
  13151. <p>Labels (<code>instance</code>, <code>job</code>, <code>index</code>) can be defined as anything.
  13152. The labels are used to group graphs in grafana.</p>
  13153. <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>
  13154. <p>Synapse 1.2 updates the Prometheus metrics to match the naming
  13155. convention of the upstream <code>prometheus_client</code>. The old names are
  13156. considered deprecated and will be removed in a future version of
  13157. Synapse.</p>
  13158. <table><thead><tr><th>New Name</th><th>Old Name</th></tr></thead><tbody>
  13159. <tr><td>python_gc_objects_collected_total</td><td>python_gc_objects_collected</td></tr>
  13160. <tr><td>python_gc_objects_uncollectable_total</td><td>python_gc_objects_uncollectable</td></tr>
  13161. <tr><td>python_gc_collections_total</td><td>python_gc_collections</td></tr>
  13162. <tr><td>process_cpu_seconds_total</td><td>process_cpu_seconds</td></tr>
  13163. <tr><td>synapse_federation_client_sent_transactions_total</td><td>synapse_federation_client_sent_transactions</td></tr>
  13164. <tr><td>synapse_federation_client_events_processed_total</td><td>synapse_federation_client_events_processed</td></tr>
  13165. <tr><td>synapse_event_processing_loop_count_total</td><td>synapse_event_processing_loop_count</td></tr>
  13166. <tr><td>synapse_event_processing_loop_room_count_total</td><td>synapse_event_processing_loop_room_count</td></tr>
  13167. <tr><td>synapse_util_metrics_block_count_total</td><td>synapse_util_metrics_block_count</td></tr>
  13168. <tr><td>synapse_util_metrics_block_time_seconds_total</td><td>synapse_util_metrics_block_time_seconds</td></tr>
  13169. <tr><td>synapse_util_metrics_block_ru_utime_seconds_total</td><td>synapse_util_metrics_block_ru_utime_seconds</td></tr>
  13170. <tr><td>synapse_util_metrics_block_ru_stime_seconds_total</td><td>synapse_util_metrics_block_ru_stime_seconds</td></tr>
  13171. <tr><td>synapse_util_metrics_block_db_txn_count_total</td><td>synapse_util_metrics_block_db_txn_count</td></tr>
  13172. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds_total</td><td>synapse_util_metrics_block_db_txn_duration_seconds</td></tr>
  13173. <tr><td>synapse_util_metrics_block_db_sched_duration_seconds_total</td><td>synapse_util_metrics_block_db_sched_duration_seconds</td></tr>
  13174. <tr><td>synapse_background_process_start_count_total</td><td>synapse_background_process_start_count</td></tr>
  13175. <tr><td>synapse_background_process_ru_utime_seconds_total</td><td>synapse_background_process_ru_utime_seconds</td></tr>
  13176. <tr><td>synapse_background_process_ru_stime_seconds_total</td><td>synapse_background_process_ru_stime_seconds</td></tr>
  13177. <tr><td>synapse_background_process_db_txn_count_total</td><td>synapse_background_process_db_txn_count</td></tr>
  13178. <tr><td>synapse_background_process_db_txn_duration_seconds_total</td><td>synapse_background_process_db_txn_duration_seconds</td></tr>
  13179. <tr><td>synapse_background_process_db_sched_duration_seconds_total</td><td>synapse_background_process_db_sched_duration_seconds</td></tr>
  13180. <tr><td>synapse_storage_events_persisted_events_total</td><td>synapse_storage_events_persisted_events</td></tr>
  13181. <tr><td>synapse_storage_events_persisted_events_sep_total</td><td>synapse_storage_events_persisted_events_sep</td></tr>
  13182. <tr><td>synapse_storage_events_state_delta_total</td><td>synapse_storage_events_state_delta</td></tr>
  13183. <tr><td>synapse_storage_events_state_delta_single_event_total</td><td>synapse_storage_events_state_delta_single_event</td></tr>
  13184. <tr><td>synapse_storage_events_state_delta_reuse_delta_total</td><td>synapse_storage_events_state_delta_reuse_delta</td></tr>
  13185. <tr><td>synapse_federation_server_received_pdus_total</td><td>synapse_federation_server_received_pdus</td></tr>
  13186. <tr><td>synapse_federation_server_received_edus_total</td><td>synapse_federation_server_received_edus</td></tr>
  13187. <tr><td>synapse_handler_presence_notified_presence_total</td><td>synapse_handler_presence_notified_presence</td></tr>
  13188. <tr><td>synapse_handler_presence_federation_presence_out_total</td><td>synapse_handler_presence_federation_presence_out</td></tr>
  13189. <tr><td>synapse_handler_presence_presence_updates_total</td><td>synapse_handler_presence_presence_updates</td></tr>
  13190. <tr><td>synapse_handler_presence_timers_fired_total</td><td>synapse_handler_presence_timers_fired</td></tr>
  13191. <tr><td>synapse_handler_presence_federation_presence_total</td><td>synapse_handler_presence_federation_presence</td></tr>
  13192. <tr><td>synapse_handler_presence_bump_active_time_total</td><td>synapse_handler_presence_bump_active_time</td></tr>
  13193. <tr><td>synapse_federation_client_sent_edus_total</td><td>synapse_federation_client_sent_edus</td></tr>
  13194. <tr><td>synapse_federation_client_sent_pdu_destinations_count_total</td><td>synapse_federation_client_sent_pdu_destinations:count</td></tr>
  13195. <tr><td>synapse_federation_client_sent_pdu_destinations_total</td><td>synapse_federation_client_sent_pdu_destinations:total</td></tr>
  13196. <tr><td>synapse_handlers_appservice_events_processed_total</td><td>synapse_handlers_appservice_events_processed</td></tr>
  13197. <tr><td>synapse_notifier_notified_events_total</td><td>synapse_notifier_notified_events</td></tr>
  13198. <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>
  13199. <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>
  13200. <tr><td>synapse_http_httppusher_http_pushes_processed_total</td><td>synapse_http_httppusher_http_pushes_processed</td></tr>
  13201. <tr><td>synapse_http_httppusher_http_pushes_failed_total</td><td>synapse_http_httppusher_http_pushes_failed</td></tr>
  13202. <tr><td>synapse_http_httppusher_badge_updates_processed_total</td><td>synapse_http_httppusher_badge_updates_processed</td></tr>
  13203. <tr><td>synapse_http_httppusher_badge_updates_failed_total</td><td>synapse_http_httppusher_badge_updates_failed</td></tr>
  13204. </tbody></table>
  13205. <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>
  13206. <p>The duplicated metrics deprecated in Synapse 0.27.0 have been removed.</p>
  13207. <p>All time duration-based metrics have been changed to be seconds. This
  13208. affects:</p>
  13209. <table><thead><tr><th>msec -&gt; sec metrics</th></tr></thead><tbody>
  13210. <tr><td>python_gc_time</td></tr>
  13211. <tr><td>python_twisted_reactor_tick_time</td></tr>
  13212. <tr><td>synapse_storage_query_time</td></tr>
  13213. <tr><td>synapse_storage_schedule_time</td></tr>
  13214. <tr><td>synapse_storage_transaction_time</td></tr>
  13215. </tbody></table>
  13216. <p>Several metrics have been changed to be histograms, which sort entries
  13217. into buckets and allow better analysis. The following metrics are now
  13218. histograms:</p>
  13219. <table><thead><tr><th>Altered metrics</th></tr></thead><tbody>
  13220. <tr><td>python_gc_time</td></tr>
  13221. <tr><td>python_twisted_reactor_pending_calls</td></tr>
  13222. <tr><td>python_twisted_reactor_tick_time</td></tr>
  13223. <tr><td>synapse_http_server_response_time_seconds</td></tr>
  13224. <tr><td>synapse_storage_query_time</td></tr>
  13225. <tr><td>synapse_storage_schedule_time</td></tr>
  13226. <tr><td>synapse_storage_transaction_time</td></tr>
  13227. </tbody></table>
  13228. <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>
  13229. <p>Synapse 0.27.0 begins the process of rationalising the duplicate
  13230. <code>*:count</code> metrics reported for the resource tracking for code blocks and
  13231. HTTP requests.</p>
  13232. <p>At the same time, the corresponding <code>*:total</code> metrics are being renamed,
  13233. as the <code>:total</code> suffix no longer makes sense in the absence of a
  13234. corresponding <code>:count</code> metric.</p>
  13235. <p>To enable a graceful migration path, this release just adds new names
  13236. for the metrics being renamed. A future release will remove the old
  13237. ones.</p>
  13238. <p>The following table shows the new metrics, and the old metrics which
  13239. they are replacing.</p>
  13240. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  13241. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_timer:count</td></tr>
  13242. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_utime:count</td></tr>
  13243. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_stime:count</td></tr>
  13244. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_count:count</td></tr>
  13245. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_duration:count</td></tr>
  13246. <tr><td>synapse_util_metrics_block_time_seconds</td><td>synapse_util_metrics_block_timer:total</td></tr>
  13247. <tr><td>synapse_util_metrics_block_ru_utime_seconds</td><td>synapse_util_metrics_block_ru_utime:total</td></tr>
  13248. <tr><td>synapse_util_metrics_block_ru_stime_seconds</td><td>synapse_util_metrics_block_ru_stime:total</td></tr>
  13249. <tr><td>synapse_util_metrics_block_db_txn_count</td><td>synapse_util_metrics_block_db_txn_count:total</td></tr>
  13250. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds</td><td>synapse_util_metrics_block_db_txn_duration:total</td></tr>
  13251. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_requests</td></tr>
  13252. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_time:count</td></tr>
  13253. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_utime:count</td></tr>
  13254. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_stime:count</td></tr>
  13255. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_count:count</td></tr>
  13256. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_duration:count</td></tr>
  13257. <tr><td>synapse_http_server_response_time_seconds</td><td>synapse_http_server_response_time:total</td></tr>
  13258. <tr><td>synapse_http_server_response_ru_utime_seconds</td><td>synapse_http_server_response_ru_utime:total</td></tr>
  13259. <tr><td>synapse_http_server_response_ru_stime_seconds</td><td>synapse_http_server_response_ru_stime:total</td></tr>
  13260. <tr><td>synapse_http_server_response_db_txn_count</td><td>synapse_http_server_response_db_txn_count:total</td></tr>
  13261. <tr><td>synapse_http_server_response_db_txn_duration_seconds</td><td>synapse_http_server_response_db_txn_duration:total</td></tr>
  13262. </tbody></table>
  13263. <h2 id="standard-metric-names"><a class="header" href="#standard-metric-names">Standard Metric Names</a></h2>
  13264. <p>As of synapse version 0.18.2, the format of the process-wide metrics has
  13265. been changed to fit prometheus standard naming conventions. Additionally
  13266. the units have been changed to seconds, from miliseconds.</p>
  13267. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  13268. <tr><td>process_cpu_user_seconds_total</td><td>process_resource_utime / 1000</td></tr>
  13269. <tr><td>process_cpu_system_seconds_total</td><td>process_resource_stime / 1000</td></tr>
  13270. <tr><td>process_open_fds (no 'type' label)</td><td>process_fds</td></tr>
  13271. </tbody></table>
  13272. <p>The python-specific counts of garbage collector performance have been
  13273. renamed.</p>
  13274. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  13275. <tr><td>python_gc_time</td><td>reactor_gc_time</td></tr>
  13276. <tr><td>python_gc_unreachable_total</td><td>reactor_gc_unreachable</td></tr>
  13277. <tr><td>python_gc_counts</td><td>reactor_gc_counts</td></tr>
  13278. </tbody></table>
  13279. <p>The twisted-specific reactor metrics have been renamed.</p>
  13280. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  13281. <tr><td>python_twisted_reactor_pending_calls</td><td>reactor_pending_calls</td></tr>
  13282. <tr><td>python_twisted_reactor_tick_time</td><td>reactor_tick_time</td></tr>
  13283. </tbody></table>
  13284. <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>
  13285. <p>It is possible to monitor much of the internal state of Synapse using <a href="https://prometheus.io">Prometheus</a>
  13286. metrics and <a href="https://grafana.com/">Grafana</a>.
  13287. A guide for configuring Synapse to provide metrics is available <a href="usage/administration/../../metrics-howto.html">here</a>
  13288. and information on setting up Grafana is <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana">here</a>.
  13289. In this setup, Prometheus will periodically scrape the information Synapse provides and
  13290. store a record of it over time. Grafana is then used as an interface to query and
  13291. present this information through a series of pretty graphs.</p>
  13292. <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>
  13293. <h2 id="message-event-send-time"><a class="header" href="#message-event-send-time">Message Event Send Time</a></h2>
  13294. <p><img src="https://user-images.githubusercontent.com/1342360/82239409-a1c8e900-9930-11ea-8081-e4614e0c63f4.png" alt="image" /></p>
  13295. <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>
  13296. <h2 id="transaction-count-and-transaction-duration"><a class="header" href="#transaction-count-and-transaction-duration">Transaction Count and Transaction Duration</a></h2>
  13297. <p><img src="https://user-images.githubusercontent.com/1342360/82239985-8d392080-9931-11ea-80d0-843ab2f22e1e.png" alt="image" /></p>
  13298. <p><img src="https://user-images.githubusercontent.com/1342360/82240050-ab068580-9931-11ea-98f1-f94671cbac9a.png" alt="image" /></p>
  13299. <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>
  13300. <p><img src="https://user-images.githubusercontent.com/1342360/82240192-e86b1300-9931-11ea-9aac-3e2c9bfa6fdc.png" alt="image" /></p>
  13301. <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>
  13302. <p><img src="https://user-images.githubusercontent.com/1342360/82240467-62030100-9932-11ea-8db9-917f2d977fe1.png" alt="image" /></p>
  13303. <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>
  13304. <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>
  13305. <h2 id="federation-1"><a class="header" href="#federation-1">Federation</a></h2>
  13306. <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>
  13307. <ul>
  13308. <li>PDU (Persistent Data Unit) - room events: messages, state events (join/leave), etc. These are permanently stored in the database.</li>
  13309. <li>EDU (Ephemeral Data Unit) - other data, which need not be stored permanently, such as read receipts, typing notifications.</li>
  13310. </ul>
  13311. <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>
  13312. <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>
  13313. <h2 id="caches"><a class="header" href="#caches">Caches</a></h2>
  13314. <p><img src="https://user-images.githubusercontent.com/1342360/82240572-8b239180-9932-11ea-96ff-6b5f0e57ebe5.png" alt="image" /></p>
  13315. <p><img src="https://user-images.githubusercontent.com/1342360/82240666-b8703f80-9932-11ea-86af-9f663988d8da.png" alt="image" /></p>
  13316. <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>
  13317. <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>
  13318. <p><img src="https://user-images.githubusercontent.com/1342360/82240766-de95df80-9932-11ea-8c15-5acfc57c48da.png" alt="image" /></p>
  13319. <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>
  13320. <h2 id="forward-extremities"><a class="header" href="#forward-extremities">Forward Extremities</a></h2>
  13321. <p><img src="https://user-images.githubusercontent.com/1342360/82241440-13566680-9934-11ea-8b88-ba468db937ed.png" alt="image" /></p>
  13322. <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>
  13323. <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>
  13324. <h2 id="garbage-collection"><a class="header" href="#garbage-collection">Garbage Collection</a></h2>
  13325. <p><img src="https://user-images.githubusercontent.com/1342360/82241911-da6ac180-9934-11ea-9a0d-a311fe22acd0.png" alt="image" /></p>
  13326. <p>Large spikes in garbage collection times (bigger than shown here, I'm talking in the
  13327. multiple seconds range), can cause lots of problems in Synapse performance. It's more an
  13328. indicator of problems, and a symptom of other problems though, so check other graphs for what might be causing it.</p>
  13329. <h2 id="final-thoughts"><a class="header" href="#final-thoughts">Final Thoughts</a></h2>
  13330. <p>If you're still having performance problems with your Synapse instance and you've
  13331. tried everything you can, it may just be a lack of system resources. Consider adding
  13332. more CPU and RAM, and make use of <a href="usage/administration/../../workers.html">worker mode</a>
  13333. to make use of multiple CPU cores / multiple machines for your homeserver.</p>
  13334. <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>
  13335. <h2 id="size-of-full-matrix-db"><a class="header" href="#size-of-full-matrix-db">Size of full matrix db</a></h2>
  13336. <pre><code class="language-sql">SELECT pg_size_pretty( pg_database_size( 'matrix' ) );
  13337. </code></pre>
  13338. <h3 id="result-example"><a class="header" href="#result-example">Result example:</a></h3>
  13339. <pre><code>pg_size_pretty
  13340. ----------------
  13341. 6420 MB
  13342. (1 row)
  13343. </code></pre>
  13344. <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>
  13345. <pre><code class="language-sql">SELECT relname, n_live_tup AS &quot;rows&quot;
  13346. FROM pg_stat_user_tables
  13347. ORDER BY n_live_tup DESC
  13348. LIMIT 20;
  13349. </code></pre>
  13350. <p>This query is quick, but may be very approximate, for exact number of rows use:</p>
  13351. <pre><code class="language-sql">SELECT COUNT(*) FROM &lt;table_name&gt;;
  13352. </code></pre>
  13353. <h3 id="result-example-1"><a class="header" href="#result-example-1">Result example:</a></h3>
  13354. <pre><code>state_groups_state - 161687170
  13355. event_auth - 8584785
  13356. event_edges - 6995633
  13357. event_json - 6585916
  13358. event_reference_hashes - 6580990
  13359. events - 6578879
  13360. received_transactions - 5713989
  13361. event_to_state_groups - 4873377
  13362. stream_ordering_to_exterm - 4136285
  13363. current_state_delta_stream - 3770972
  13364. event_search - 3670521
  13365. state_events - 2845082
  13366. room_memberships - 2785854
  13367. cache_invalidation_stream - 2448218
  13368. state_groups - 1255467
  13369. state_group_edges - 1229849
  13370. current_state_events - 1222905
  13371. users_in_public_rooms - 364059
  13372. device_lists_stream - 326903
  13373. user_directory_search - 316433
  13374. </code></pre>
  13375. <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>
  13376. <pre><code class="language-sql">SELECT nspname || '.' || relname AS &quot;relation&quot;,
  13377. pg_size_pretty(pg_total_relation_size(c.oid)) AS &quot;total_size&quot;
  13378. FROM pg_class c
  13379. LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
  13380. WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  13381. AND c.relkind &lt;&gt; 'i'
  13382. AND nspname !~ '^pg_toast'
  13383. ORDER BY pg_total_relation_size(c.oid) DESC
  13384. LIMIT 20;
  13385. </code></pre>
  13386. <h3 id="result-example-2"><a class="header" href="#result-example-2">Result example:</a></h3>
  13387. <pre><code>public.state_groups_state - 27 GB
  13388. public.event_json - 9855 MB
  13389. public.events - 3675 MB
  13390. public.event_edges - 3404 MB
  13391. public.received_transactions - 2745 MB
  13392. public.event_reference_hashes - 1864 MB
  13393. public.event_auth - 1775 MB
  13394. public.stream_ordering_to_exterm - 1663 MB
  13395. public.event_search - 1370 MB
  13396. public.room_memberships - 1050 MB
  13397. public.event_to_state_groups - 948 MB
  13398. public.current_state_delta_stream - 711 MB
  13399. public.state_events - 611 MB
  13400. public.presence_stream - 530 MB
  13401. public.current_state_events - 525 MB
  13402. public.cache_invalidation_stream - 466 MB
  13403. public.receipts_linearized - 279 MB
  13404. public.state_groups - 160 MB
  13405. public.device_lists_remote_cache - 124 MB
  13406. public.state_group_edges - 122 MB
  13407. </code></pre>
  13408. <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>
  13409. <p>You get the same information when you use the
  13410. <a href="usage/administration/../../admin_api/rooms.html#list-room-api">admin API</a>
  13411. and set parameter <code>order_by=state_events</code>.</p>
  13412. <pre><code class="language-sql">SELECT r.name, s.room_id, s.current_state_events
  13413. FROM room_stats_current s
  13414. LEFT JOIN room_stats_state r USING (room_id)
  13415. ORDER BY current_state_events DESC
  13416. LIMIT 20;
  13417. </code></pre>
  13418. <p>and by state_group_events count:</p>
  13419. <pre><code class="language-sql">SELECT rss.name, s.room_id, COUNT(s.room_id)
  13420. FROM state_groups_state s
  13421. LEFT JOIN room_stats_state rss USING (room_id)
  13422. GROUP BY s.room_id, rss.name
  13423. ORDER BY COUNT(s.room_id) DESC
  13424. LIMIT 20;
  13425. </code></pre>
  13426. <p>plus same, but with join removed for performance reasons:</p>
  13427. <pre><code class="language-sql">SELECT s.room_id, COUNT(s.room_id)
  13428. FROM state_groups_state s
  13429. GROUP BY s.room_id
  13430. ORDER BY COUNT(s.room_id) DESC
  13431. LIMIT 20;
  13432. </code></pre>
  13433. <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>
  13434. <pre><code class="language-sql">SELECT e.room_id, r.name, COUNT(e.event_id) cnt
  13435. FROM events e
  13436. LEFT JOIN room_stats_state r USING (room_id)
  13437. WHERE e.origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 day') * 1000
  13438. GROUP BY e.room_id, r.name
  13439. ORDER BY cnt DESC
  13440. LIMIT 20;
  13441. </code></pre>
  13442. <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>
  13443. <p>Caution. This query does not use any indexes, can be slow and create load on the database.</p>
  13444. <pre><code class="language-sql">SELECT COUNT(*), sender
  13445. FROM events
  13446. WHERE (type = 'm.room.encrypted' OR type = 'm.room.message')
  13447. AND origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 month') * 1000
  13448. GROUP BY sender
  13449. ORDER BY COUNT(*) DESC
  13450. LIMIT 20;
  13451. </code></pre>
  13452. <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>
  13453. <pre><code class="language-sql">SELECT e.room_id, r.name, e.event_id, e.type, e.content, j.json
  13454. FROM events e
  13455. LEFT JOIN event_json j USING (room_id)
  13456. LEFT JOIN room_stats_state r USING (room_id)
  13457. WHERE sender = '@LOGIN:example.com'
  13458. AND e.type = 'm.room.message'
  13459. ORDER BY stream_ordering DESC
  13460. LIMIT 100;
  13461. </code></pre>
  13462. <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>
  13463. <p><strong>Sort and order with bash</strong></p>
  13464. <pre><code class="language-bash">echo &quot;SELECT event_json.room_id, room_stats_state.name FROM event_json, room_stats_state \
  13465. WHERE room_stats_state.room_id = event_json.room_id&quot; | psql -d synapse -h localhost -U synapse_user -t \
  13466. | sort | uniq -c | sort -n
  13467. </code></pre>
  13468. <p>Documentation for <code>psql</code> command line parameters: https://www.postgresql.org/docs/current/app-psql.html</p>
  13469. <p><strong>Sort and order with SQL</strong></p>
  13470. <pre><code class="language-sql">SELECT COUNT(*), event_json.room_id, room_stats_state.name
  13471. FROM event_json, room_stats_state
  13472. WHERE room_stats_state.room_id = event_json.room_id
  13473. GROUP BY event_json.room_id, room_stats_state.name
  13474. ORDER BY COUNT(*) DESC
  13475. LIMIT 50;
  13476. </code></pre>
  13477. <h3 id="result-example-3"><a class="header" href="#result-example-3">Result example:</a></h3>
  13478. <pre><code> 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix
  13479. 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix (TWIM)
  13480. 17799 !iDIOImbmXxwNngznsa:matrix.org | Linux in Russian
  13481. 18739 !GnEEPYXUhoaHbkFBNX:matrix.org | Riot Android
  13482. 23373 !QtykxKocfZaZOUrTwp:matrix.org | Matrix HQ
  13483. 39504 !gTQfWzbYncrtNrvEkB:matrix.org | ru.[matrix]
  13484. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot
  13485. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot Web/Desktop
  13486. </code></pre>
  13487. <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>
  13488. <p>You get the same information when you use the
  13489. <a href="usage/administration/../../admin_api/rooms.html#room-details-api">admin API</a>.</p>
  13490. <pre><code class="language-sql">SELECT rss.room_id, rss.name, rss.canonical_alias, rss.topic, rss.encryption,
  13491. rsc.joined_members, rsc.local_users_in_room, rss.join_rules
  13492. FROM room_stats_state rss
  13493. LEFT JOIN room_stats_current rsc USING (room_id)
  13494. WHERE room_id IN ( WHERE room_id IN (
  13495. '!OGEhHVWSdvArJzumhm:matrix.org',
  13496. '!YTvKGNlinIzlkMTVRl:matrix.org'
  13497. );
  13498. </code></pre>
  13499. <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>
  13500. <pre><code class="language-sql">SELECT user_id, device_id, user_agent, TO_TIMESTAMP(last_seen / 1000) AS &quot;last_seen&quot;
  13501. FROM devices
  13502. WHERE last_seen &lt; DATE_PART('epoch', NOW() - INTERVAL '3 month') * 1000;
  13503. </code></pre>
  13504. <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>
  13505. <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>
  13506. <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>
  13507. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  13508. <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>
  13509. <p>This API deletes the <em>local</em> media from the disk of your own server.</p>
  13510. <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>
  13511. <p>The purge history API allows server admins to purge historic events from their database, reclaiming disk space.</p>
  13512. <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>
  13513. <p>Tool for compressing (deduplicating) <code>state_groups_state</code> table.</p>
  13514. <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>
  13515. <p>Some easy SQL that reports useful stats about your Synapse database.</p>
  13516. <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>
  13517. <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>
  13518. <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>
  13519. <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>
  13520. <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>
  13521. <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>
  13522. <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>
  13523. <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>
  13524. <p>A full state group just records the event id for each piece of state in the room at that point.</p>
  13525. <h2 id="known-bugs-with-state-groups"><a class="header" href="#known-bugs-with-state-groups">Known bugs with state groups</a></h2>
  13526. <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>
  13527. <h2 id="compression-tool"><a class="header" href="#compression-tool">Compression tool</a></h2>
  13528. <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>
  13529. <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>
  13530. <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>
  13531. <p>See the following for how to decode the dense data available from the default logging configuration.</p>
  13532. <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]
  13533. -AAAAAAAAAAAAAAAAAAAAA- -BBBBBBBBBBBBBBBBBBBBBB- -C- -DD- -EEEEEE- -FFFFFFFFF- -GG- -HHHHHHHHHHHHHHHHHHHHHHH- -IIIIII- -JJJJJJJ- -KKKKKK-, -LLLLLL- -MMMMMMM- -NNNNNN- O -P- -QQ- -RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR- -SSSSSSSSSSSS- -TTTTTT-
  13534. </code></pre>
  13535. <table><thead><tr><th>Part</th><th>Explanation</th></tr></thead><tbody>
  13536. <tr><td>AAAA</td><td>Timestamp request was logged (not recieved)</td></tr>
  13537. <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>
  13538. <tr><td>CCCC</td><td>Line number in code</td></tr>
  13539. <tr><td>DDDD</td><td>Log Level</td></tr>
  13540. <tr><td>EEEE</td><td>Request Identifier (This identifier is shared by related log lines)</td></tr>
  13541. <tr><td>FFFF</td><td>Source IP (Or X-Forwarded-For if enabled)</td></tr>
  13542. <tr><td>GGGG</td><td>Server Port</td></tr>
  13543. <tr><td>HHHH</td><td>Federated Server or Local User making request (blank if unauthenticated or not supplied)</td></tr>
  13544. <tr><td>IIII</td><td>Total Time to process the request</td></tr>
  13545. <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>
  13546. <tr><td>KKKK</td><td>Userland CPU time</td></tr>
  13547. <tr><td>LLLL</td><td>System CPU time</td></tr>
  13548. <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>
  13549. <tr><td>NNNN</td><td>Total time waiting for response to DB queries across all parallel DB work from this request</td></tr>
  13550. <tr><td>OOOO</td><td>Count of DB transactions performed</td></tr>
  13551. <tr><td>PPPP</td><td>Response body size</td></tr>
  13552. <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>
  13553. <tr><td>RRRR</td><td>Request</td></tr>
  13554. <tr><td>SSSS</td><td>User-agent</td></tr>
  13555. <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>
  13556. </tbody></table>
  13557. <p>MMMM / NNNN can be greater than IIII if there are multiple slow database queries
  13558. running in parallel.</p>
  13559. <p>Some actions can result in multiple identical http requests, which will return
  13560. the same data, but only the first request will report time/transactions in
  13561. <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
  13562. response and will simultaneously return with the first request, but with very
  13563. small processing times.</p>
  13564. <div style="break-before: page; page-break-before: always;"></div><h2 id="admin-faq"><a class="header" href="#admin-faq">Admin FAQ</a></h2>
  13565. <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>
  13566. <p>If your server already has an admin account you should use the user admin API to promote other accounts to become admins. See <a href="usage/administration/../../admin_api/user_admin_api.html#Change-whether-a-user-is-a-server-administrator-or-not">User Admin API</a></p>
  13567. <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>
  13568. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  13569. </code></pre>
  13570. <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>
  13571. <p>Run this sql query on your db:</p>
  13572. <pre><code class="language-sql">SELECT * FROM destinations;
  13573. </code></pre>
  13574. <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>
  13575. <p>Run this sql query on your db:</p>
  13576. <pre><code class="language-sql">SELECT DISTINCT split_part(state_key, ':', 2)
  13577. FROM current_state_events AS c
  13578. INNER JOIN room_memberships AS m USING (room_id, event_id)
  13579. WHERE room_id = '!cURbafjkfsMDVwdRDQ:matrix.org' AND membership = 'join';
  13580. </code></pre>
  13581. <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>
  13582. <pre><code class="language-sql">SELECT NAME from users;
  13583. </code></pre>
  13584. <h2 id="manually-resetting-passwords"><a class="header" href="#manually-resetting-passwords">Manually resetting passwords:</a></h2>
  13585. <p>See https://github.com/matrix-org/synapse/blob/master/README.rst#password-reset</p>
  13586. <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>
  13587. <p>Deleting your database is unlikely to make anything better. </p>
  13588. <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>
  13589. <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>
  13590. <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>
  13591. <p>There are two exceptions when it might be sensible to delete your database and start again:</p>
  13592. <ul>
  13593. <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>
  13594. <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.
  13595. (In both cases you probably also want to clear out the media_store.)</li>
  13596. </ul>
  13597. <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>
  13598. <p>Using the following curl command:</p>
  13599. <pre><code>curl -H 'Authorization: Bearer &lt;access-token&gt;' -X DELETE https://matrix.org/_matrix/client/r0/directory/room/&lt;room-alias&gt;
  13600. </code></pre>
  13601. <p><code>&lt;access-token&gt;</code> - can be obtained in riot by looking in the riot settings, down the bottom is:
  13602. Access Token:&lt;click to reveal&gt; </p>
  13603. <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>
  13604. <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>
  13605. <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>
  13606. <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;
  13607. </code></pre>
  13608. <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>
  13609. <pre><code>grep 'GET-37' homeserver.log
  13610. </code></pre>
  13611. <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>
  13612. <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>
  13613. <p>See <a href="usage/administration/request_log.html">Request log format</a>.</p>
  13614. <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>
  13615. <pre><code class="language-sql">SELECT s.canonical_alias, g.room_id, count(*) AS num_rows
  13616. FROM
  13617. state_groups_state AS g,
  13618. room_stats_state AS s
  13619. WHERE g.room_id = s.room_id
  13620. GROUP BY s.canonical_alias, g.room_id
  13621. ORDER BY num_rows desc
  13622. LIMIT 10;
  13623. </code></pre>
  13624. <p>You can also use the <a href="usage/administration/../../admin_api/rooms.html#list-room-api">List Room API</a>
  13625. and <code>order_by</code> <code>state_events</code>.</p>
  13626. <div style="break-before: page; page-break-before: always;"></div><h1 id="contributing"><a class="header" href="#contributing">Contributing</a></h1>
  13627. <p>This document aims to get you started with contributing to Synapse!</p>
  13628. <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>
  13629. <p>Everyone is welcome to contribute code to <a href="https://github.com/matrix-org">matrix.org
  13630. projects</a>, provided that they are willing to
  13631. license their contributions under the same license as the project itself. We
  13632. follow a simple 'inbound=outbound' model for contributions: the act of
  13633. submitting an 'inbound' contribution means that the contributor agrees to
  13634. license the code under the same terms as the project's overall 'outbound'
  13635. license - in our case, this is almost always Apache Software License v2 (see
  13636. <a href="https://github.com/matrix-org/synapse/blob/develop/LICENSE">LICENSE</a>).</p>
  13637. <h1 id="2-what-do-i-need"><a class="header" href="#2-what-do-i-need">2. What do I need?</a></h1>
  13638. <p>If you are running Windows, the Windows Subsystem for Linux (WSL) is strongly
  13639. recommended for development. More information about WSL can be found at
  13640. <a href="https://docs.microsoft.com/en-us/windows/wsl/install">https://docs.microsoft.com/en-us/windows/wsl/install</a>. Running Synapse natively
  13641. on Windows is not officially supported.</p>
  13642. <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>
  13643. <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>
  13644. <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>
  13645. <p>For some tests, you will need <a href="https://docs.docker.com/get-docker/">a recent version of Docker</a>.</p>
  13646. <h1 id="3-get-the-source"><a class="header" href="#3-get-the-source">3. Get the source.</a></h1>
  13647. <p>The preferred and easiest way to contribute changes is to fork the relevant
  13648. 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
  13649. changes into our repo.</p>
  13650. <p>Please base your changes on the <code>develop</code> branch.</p>
  13651. <pre><code class="language-sh">git clone git@github.com:YOUR_GITHUB_USER_NAME/synapse.git
  13652. git checkout develop
  13653. </code></pre>
  13654. <p>If you need help getting started with git, this is beyond the scope of the document, but you
  13655. can find many good git tutorials on the web.</p>
  13656. <h1 id="4-install-the-dependencies"><a class="header" href="#4-install-the-dependencies">4. Install the dependencies</a></h1>
  13657. <p>Synapse uses the <a href="https://python-poetry.org/">poetry</a> project to manage its dependencies
  13658. and development environment. Once you have installed Python 3 and added the
  13659. source, you should install <code>poetry</code>.
  13660. Of their installation methods, we recommend
  13661. <a href="https://python-poetry.org/docs/#installing-with-pipx">installing <code>poetry</code> using <code>pipx</code></a>,</p>
  13662. <pre><code class="language-shell">pip install --user pipx
  13663. pipx install poetry
  13664. </code></pre>
  13665. <p>but see poetry's <a href="https://python-poetry.org/docs/#installation">installation instructions</a>
  13666. for other installation methods.</p>
  13667. <p>Next, open a terminal and install dependencies as follows:</p>
  13668. <pre><code class="language-sh">cd path/where/you/have/cloned/the/repository
  13669. poetry install --extras all
  13670. </code></pre>
  13671. <p>This will install the runtime and developer dependencies for the project.</p>
  13672. <h1 id="5-get-in-touch"><a class="header" href="#5-get-in-touch">5. Get in touch.</a></h1>
  13673. <p>Join our developer community on Matrix: <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>!</p>
  13674. <h1 id="6-pick-an-issue"><a class="header" href="#6-pick-an-issue">6. Pick an issue.</a></h1>
  13675. <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>
  13676. to work on.</p>
  13677. <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>
  13678. <p>There is a growing amount of documentation located in the
  13679. <a href="https://github.com/matrix-org/synapse/tree/develop/docs"><code>docs</code></a>
  13680. directory, with a rendered version <a href="https://matrix-org.github.io/synapse">available online</a>.
  13681. This documentation is intended primarily for sysadmins running their
  13682. own Synapse instance, as well as developers interacting externally with
  13683. Synapse.
  13684. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/development"><code>docs/development</code></a>
  13685. exists primarily to house documentation for
  13686. Synapse developers.
  13687. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/admin_api"><code>docs/admin_api</code></a> houses documentation
  13688. regarding Synapse's Admin API, which is used mostly by sysadmins and external
  13689. service developers.</p>
  13690. <p>Synapse's code style is documented <a href="development/../code_style.html">here</a>. Please follow
  13691. it, including the conventions for the <a href="development/../code_style.html#configuration-file-format">sample configuration
  13692. file</a>.</p>
  13693. <p>We welcome improvements and additions to our documentation itself! When
  13694. writing new pages, please
  13695. <a href="https://github.com/matrix-org/synapse/tree/develop/docs#adding-to-the-documentation">build <code>docs</code> to a book</a>
  13696. to check that your contributions render correctly. The docs are written in
  13697. <a href="https://guides.github.com/features/mastering-markdown/">GitHub-Flavoured Markdown</a>.</p>
  13698. <p>Some documentation also exists in <a href="https://github.com/matrix-org/synapse/wiki">Synapse's GitHub
  13699. Wiki</a>, although this is primarily
  13700. contributed to by community authors.</p>
  13701. <h1 id="8-test-test-test"><a class="header" href="#8-test-test-test">8. Test, test, test!</a></h1>
  13702. <p><a name="test-test-test"></a></p>
  13703. <p>While you're developing and before submitting a patch, you'll
  13704. want to test your code.</p>
  13705. <h2 id="run-the-linters"><a class="header" href="#run-the-linters">Run the linters.</a></h2>
  13706. <p>The linters look at your code and do two things:</p>
  13707. <ul>
  13708. <li>ensure that your code follows the coding style adopted by the project;</li>
  13709. <li>catch a number of errors in your code.</li>
  13710. </ul>
  13711. <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>
  13712. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh
  13713. </code></pre>
  13714. <p>Note that this script <em>will modify your files</em> to fix styling errors.
  13715. Make sure that you have saved all your files.</p>
  13716. <p>If you wish to restrict the linters to only the files changed since the last commit
  13717. (much faster!), you can instead run:</p>
  13718. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh -d
  13719. </code></pre>
  13720. <p>Or if you know exactly which files you wish to lint, you can instead run:</p>
  13721. <pre><code class="language-sh">poetry run ./scripts-dev/lint.sh path/to/file1.py path/to/file2.py path/to/folder
  13722. </code></pre>
  13723. <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>
  13724. <p>The unit tests run parts of Synapse, including your changes, to see if anything
  13725. was broken. They are slower than the linters but will typically catch more errors.</p>
  13726. <pre><code class="language-sh">poetry run trial tests
  13727. </code></pre>
  13728. <p>If you wish to only run <em>some</em> unit tests, you may specify
  13729. another module instead of <code>tests</code> - or a test class or a method:</p>
  13730. <pre><code class="language-sh">poetry run trial tests.rest.admin.test_room tests.handlers.test_admin.ExfiltrateData.test_invite
  13731. </code></pre>
  13732. <p>If your tests fail, you may wish to look at the logs (the default log level is <code>ERROR</code>):</p>
  13733. <pre><code class="language-sh">less _trial_temp/test.log
  13734. </code></pre>
  13735. <p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>:</p>
  13736. <pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG poetry run trial tests
  13737. </code></pre>
  13738. <p>By default, tests will use an in-memory SQLite database for test data. For additional
  13739. help with debugging, one can use an on-disk SQLite database file instead, in order to
  13740. review database state during and after running tests. This can be done by setting
  13741. the <code>SYNAPSE_TEST_PERSIST_SQLITE_DB</code> environment variable. Doing so will cause the
  13742. database state to be stored in a file named <code>test.db</code> under the trial process'
  13743. working directory. Typically, this ends up being <code>_trial_temp/test.db</code>. For example:</p>
  13744. <pre><code class="language-sh">SYNAPSE_TEST_PERSIST_SQLITE_DB=1 poetry run trial tests
  13745. </code></pre>
  13746. <p>The database file can then be inspected with:</p>
  13747. <pre><code class="language-sh">sqlite3 _trial_temp/test.db
  13748. </code></pre>
  13749. <p>Note that the database file is cleared at the beginning of each test run. Thus it
  13750. will always only contain the data generated by the <em>last run test</em>. Though generally
  13751. when debugging, one is only running a single test anyway.</p>
  13752. <h3 id="running-tests-under-postgresql"><a class="header" href="#running-tests-under-postgresql">Running tests under PostgreSQL</a></h3>
  13753. <p>Invoking <code>trial</code> as above will use an in-memory SQLite database. This is great for
  13754. quick development and testing. However, we recommend using a PostgreSQL database
  13755. in production (and indeed, we have some code paths specific to each database).
  13756. This means that we need to run our unit tests against PostgreSQL too. Our CI does
  13757. this automatically for pull requests and release candidates, but it's sometimes
  13758. useful to reproduce this locally.</p>
  13759. <h4 id="using-docker"><a class="header" href="#using-docker">Using Docker</a></h4>
  13760. <p>The easiest way to do so is to run Postgres via a docker container. In one
  13761. terminal:</p>
  13762. <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
  13763. </code></pre>
  13764. <p>If you see an error like</p>
  13765. <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.
  13766. </code></pre>
  13767. <p>then something is already bound to port 5432. You're probably already running postgres locally.</p>
  13768. <p>Once you have a postgres server running, invoke <code>trial</code> in a second terminal:</p>
  13769. <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
  13770. </code></pre>
  13771. <h4 id="using-an-existing-postgres-installation"><a class="header" href="#using-an-existing-postgres-installation">Using an existing Postgres installation</a></h4>
  13772. <p>If you have postgres already installed on your system, you can run <code>trial</code> with the
  13773. following environment variables matching your configuration:</p>
  13774. <ul>
  13775. <li><code>SYNAPSE_POSTGRES</code> to anything nonempty</li>
  13776. <li><code>SYNAPSE_POSTGRES_HOST</code> (optional if it's the default: UNIX socket)</li>
  13777. <li><code>SYNAPSE_POSTGRES_PORT</code> (optional if it's the default: 5432)</li>
  13778. <li><code>SYNAPSE_POSTGRES_USER</code> (optional if using a UNIX socket)</li>
  13779. <li><code>SYNAPSE_POSTGRES_PASSWORD</code> (optional if using a UNIX socket)</li>
  13780. </ul>
  13781. <p>For example:</p>
  13782. <pre><code class="language-shell">export SYNAPSE_POSTGRES=1
  13783. export SYNAPSE_POSTGRES_HOST=localhost
  13784. export SYNAPSE_POSTGRES_USER=postgres
  13785. export SYNAPSE_POSTGRES_PASSWORD=mydevenvpassword
  13786. trial
  13787. </code></pre>
  13788. <p>You don't need to specify the host, user, port or password if your Postgres
  13789. server is set to authenticate you over the UNIX socket (i.e. if the <code>psql</code> command
  13790. works without further arguments).</p>
  13791. <p>Your Postgres account needs to be able to create databases; see the postgres
  13792. docs for <a href="https://www.postgresql.org/docs/current/sql-alterrole.html"><code>ALTER ROLE</code></a>.</p>
  13793. <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>
  13794. <p>The integration tests are a more comprehensive suite of tests. They
  13795. run a full version of Synapse, including your changes, to check if
  13796. anything was broken. They are slower than the unit tests but will
  13797. typically catch more errors.</p>
  13798. <p>The following command will let you run the integration test with the most common
  13799. configuration:</p>
  13800. <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
  13801. </code></pre>
  13802. <p>(Note that the paths must be full paths! You could also write <code>$(realpath relative/path)</code> if needed.)</p>
  13803. <p>This configuration should generally cover your needs.</p>
  13804. <ul>
  13805. <li>To run with Postgres, supply the <code>-e POSTGRES=1 -e MULTI_POSTGRES=1</code> environment flags.</li>
  13806. <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>
  13807. </ul>
  13808. <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>
  13809. <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>
  13810. <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>
  13811. <p>It's often nice to develop on Synapse and write Complement tests at the same time.
  13812. Here is how to run your local Synapse checkout against your local Complement checkout.</p>
  13813. <p>(checkout <a href="https://github.com/matrix-org/complement"><code>complement</code></a> alongside your <code>synapse</code> checkout)</p>
  13814. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh
  13815. </code></pre>
  13816. <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>
  13817. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages
  13818. </code></pre>
  13819. <p>To run a specific test, you can specify the whole name structure:</p>
  13820. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -run TestImportHistoricalMessages/parallel/Historical_events_resolve_in_the_correct_order
  13821. </code></pre>
  13822. <p>The above will run a monolithic (single-process) Synapse with SQLite as the database. For other configurations, try:</p>
  13823. <ul>
  13824. <li>Passing <code>POSTGRES=1</code> as an environment variable to use the Postgres database instead.</li>
  13825. <li>Passing <code>WORKERS=1</code> as an environment variable to use a workerised setup instead. This option implies the use of Postgres.</li>
  13826. </ul>
  13827. <h3 id="prettier-formatting-with-gotestfmt"><a class="header" href="#prettier-formatting-with-gotestfmt">Prettier formatting with <code>gotestfmt</code></a></h3>
  13828. <p>If you want to format the output of the tests the same way as it looks in CI,
  13829. install <a href="https://github.com/haveyoudebuggedit/gotestfmt">gotestfmt</a>.</p>
  13830. <p>You can then use this incantation to format the tests appropriately:</p>
  13831. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh -json | gotestfmt -hide successful-tests
  13832. </code></pre>
  13833. <p>(Remove <code>-hide successful-tests</code> if you don't want to hide successful tests.)</p>
  13834. <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>
  13835. <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>
  13836. <ol>
  13837. <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>
  13838. <li>Start the Complement tests</li>
  13839. <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>
  13840. <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>
  13841. <li>Install sqlite (database driver), <code>apt-get update &amp;&amp; apt-get install -y sqlite3</code></li>
  13842. <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>
  13843. </ol>
  13844. <h1 id="9-submit-your-patch"><a class="header" href="#9-submit-your-patch">9. Submit your patch.</a></h1>
  13845. <p>Once you're happy with your patch, it's time to prepare a Pull Request.</p>
  13846. <p>To prepare a Pull Request, please:</p>
  13847. <ol>
  13848. <li>verify that <a href="development/contributing_guide.html#test-test-test">all the tests pass</a>, including the coding style;</li>
  13849. <li><a href="development/contributing_guide.html#sign-off">sign off</a> your contribution;</li>
  13850. <li><code>git push</code> your commit to your fork of Synapse;</li>
  13851. <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>
  13852. <li>add a <a href="development/contributing_guide.html#changelog">changelog entry</a> and push it to your Pull Request;</li>
  13853. <li>for most contributors, that's all - however, if you are a member of the organization <code>matrix-org</code>, on GitHub, please request a review from <code>matrix.org / Synapse Core</code>.</li>
  13854. <li>if you need to update your PR, please avoid rebasing and just add new commits to your branch.</li>
  13855. </ol>
  13856. <h2 id="changelog"><a class="header" href="#changelog">Changelog</a></h2>
  13857. <p>All changes, even minor ones, need a corresponding changelog / newsfragment
  13858. entry. These are managed by <a href="https://github.com/hawkowl/towncrier">Towncrier</a>.</p>
  13859. <p>To create a changelog entry, make a new file in the <code>changelog.d</code> directory named
  13860. in the format of <code>PRnumber.type</code>. The type can be one of the following:</p>
  13861. <ul>
  13862. <li><code>feature</code></li>
  13863. <li><code>bugfix</code></li>
  13864. <li><code>docker</code> (for updates to the Docker image)</li>
  13865. <li><code>doc</code> (for updates to the documentation)</li>
  13866. <li><code>removal</code> (also used for deprecations)</li>
  13867. <li><code>misc</code> (for internal-only changes)</li>
  13868. </ul>
  13869. <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
  13870. release, so the content of the file should be a short description of your
  13871. change in the same style as the rest of the changelog. The file can contain Markdown
  13872. formatting, and should end with a full stop (.) or an exclamation mark (!) for
  13873. consistency.</p>
  13874. <p>Adding credits to the changelog is encouraged, we value your
  13875. contributions and would like to have you shouted out in the release notes!</p>
  13876. <p>For example, a fix in PR #1234 would have its changelog entry in
  13877. <code>changelog.d/1234.bugfix</code>, and contain content like:</p>
  13878. <blockquote>
  13879. <p>The security levels of Florbs are now validated when received
  13880. via the <code>/federation/florb</code> endpoint. Contributed by Jane Matrix.</p>
  13881. </blockquote>
  13882. <p>If there are multiple pull requests involved in a single bugfix/feature/etc,
  13883. then the content for each <code>changelog.d</code> file should be the same. Towncrier will
  13884. merge the matching files together into a single changelog entry when we come to
  13885. release.</p>
  13886. <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>
  13887. <p>Obviously, you don't know if you should call your newsfile
  13888. <code>1234.bugfix</code> or <code>5678.bugfix</code> until you create the PR, which leads to a
  13889. chicken-and-egg problem.</p>
  13890. <p>There are two options for solving this:</p>
  13891. <ol>
  13892. <li>
  13893. <p>Open the PR without a changelog file, see what number you got, and <em>then</em>
  13894. add the changelog file to your branch (see <a href="development/contributing_guide.html#updating-your-pull-request">Updating your pull
  13895. request</a>), or:</p>
  13896. </li>
  13897. <li>
  13898. <p>Look at the <a href="https://github.com/matrix-org/synapse/issues?q=">list of all
  13899. issues/PRs</a>, add one to the
  13900. highest number you see, and quickly open the PR before somebody else claims
  13901. your number.</p>
  13902. <p><a href="https://github.com/richvdh/scripts/blob/master/next_github_number.sh">This
  13903. script</a>
  13904. might be helpful if you find yourself doing this a lot.</p>
  13905. </li>
  13906. </ol>
  13907. <p>Sorry, we know it's a bit fiddly, but it's <em>really</em> helpful for us when we come
  13908. to put together a release!</p>
  13909. <h3 id="debian-changelog"><a class="header" href="#debian-changelog">Debian changelog</a></h3>
  13910. <p>Changes which affect the debian packaging files (in <code>debian</code>) are an
  13911. exception to the rule that all changes require a <code>changelog.d</code> file.</p>
  13912. <p>In this case, you will need to add an entry to the debian changelog for the
  13913. next release. For this, run the following command:</p>
  13914. <pre><code>dch
  13915. </code></pre>
  13916. <p>This will make up a new version number (if there isn't already an unreleased
  13917. version in flight), and open an editor where you can add a new changelog entry.
  13918. (Our release process will ensure that the version number and maintainer name is
  13919. corrected for the release.)</p>
  13920. <p>If your change affects both the debian packaging <em>and</em> files outside the debian
  13921. directory, you will need both a regular newsfragment <em>and</em> an entry in the
  13922. debian changelog. (Though typically such changes should be submitted as two
  13923. separate pull requests.)</p>
  13924. <h2 id="sign-off"><a class="header" href="#sign-off">Sign off</a></h2>
  13925. <p>In order to have a concrete record that your contribution is intentional
  13926. and you agree to license it under the same terms as the project's license, we've adopted the
  13927. same lightweight approach that the Linux Kernel
  13928. <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>,
  13929. <a href="https://github.com/docker/docker/blob/master/CONTRIBUTING.md">Docker</a>, and many other
  13930. projects use: the DCO (<a href="http://developercertificate.org/">Developer Certificate of Origin</a>).
  13931. This is a simple declaration that you wrote
  13932. the contribution or otherwise have the right to contribute it to Matrix:</p>
  13933. <pre><code>Developer Certificate of Origin
  13934. Version 1.1
  13935. Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
  13936. 660 York Street, Suite 102,
  13937. San Francisco, CA 94110 USA
  13938. Everyone is permitted to copy and distribute verbatim copies of this
  13939. license document, but changing it is not allowed.
  13940. Developer's Certificate of Origin 1.1
  13941. By making a contribution to this project, I certify that:
  13942. (a) The contribution was created in whole or in part by me and I
  13943. have the right to submit it under the open source license
  13944. indicated in the file; or
  13945. (b) The contribution is based upon previous work that, to the best
  13946. of my knowledge, is covered under an appropriate open source
  13947. license and I have the right under that license to submit that
  13948. work with modifications, whether created in whole or in part
  13949. by me, under the same open source license (unless I am
  13950. permitted to submit under a different license), as indicated
  13951. in the file; or
  13952. (c) The contribution was provided directly to me by some other
  13953. person who certified (a), (b) or (c) and I have not modified
  13954. it.
  13955. (d) I understand and agree that this project and the contribution
  13956. are public and that a record of the contribution (including all
  13957. personal information I submit with it, including my sign-off) is
  13958. maintained indefinitely and may be redistributed consistent with
  13959. this project or the open source license(s) involved.
  13960. </code></pre>
  13961. <p>If you agree to this for your contribution, then all that's needed is to
  13962. include the line in your commit or pull request comment:</p>
  13963. <pre><code>Signed-off-by: Your Name &lt;your@email.example.org&gt;
  13964. </code></pre>
  13965. <p>We accept contributions under a legally identifiable name, such as
  13966. your name on government documentation or common-law names (names
  13967. claimed by legitimate usage or repute). Unfortunately, we cannot
  13968. accept anonymous contributions at this time.</p>
  13969. <p>Git allows you to add this signoff automatically when using the <code>-s</code>
  13970. flag to <code>git commit</code>, which uses the name and email set in your
  13971. <code>user.name</code> and <code>user.email</code> git configs.</p>
  13972. <h3 id="private-sign-off"><a class="header" href="#private-sign-off">Private Sign off</a></h3>
  13973. <p>If you would like to provide your legal name privately to the Matrix.org
  13974. Foundation (instead of in a public commit or comment), you can do so
  13975. by emailing your legal name and a link to the pull request to
  13976. <a href="mailto:dco@matrix.org?subject=Private%20sign%20off">dco@matrix.org</a>.
  13977. It helps to include &quot;sign off&quot; or similar in the subject line. You will then
  13978. be instructed further.</p>
  13979. <p>Once private sign off is complete, doing so for future contributions will not
  13980. be required.</p>
  13981. <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>
  13982. <p>Once the Pull Request is opened, you will see a few things:</p>
  13983. <ol>
  13984. <li>our automated CI (Continuous Integration) pipeline will run (again) the linters, the unit tests, the integration tests and more;</li>
  13985. <li>one or more of the developers will take a look at your Pull Request and offer feedback.</li>
  13986. </ol>
  13987. <p>From this point, you should:</p>
  13988. <ol>
  13989. <li>Look at the results of the CI pipeline.
  13990. <ul>
  13991. <li>If there is any error, fix the error.</li>
  13992. </ul>
  13993. </li>
  13994. <li>If a developer has requested changes, make these changes and let us know if it is ready for a developer to review again.</li>
  13995. <li>Create a new commit with the changes.
  13996. <ul>
  13997. <li>Please do NOT overwrite the history. New commits make the reviewer's life easier.</li>
  13998. <li>Push this commits to your Pull Request.</li>
  13999. </ul>
  14000. </li>
  14001. <li>Back to 1.</li>
  14002. </ol>
  14003. <p>Once both the CI and the developers are happy, the patch will be merged into Synapse and released shortly!</p>
  14004. <h1 id="11-find-a-new-issue"><a class="header" href="#11-find-a-new-issue">11. Find a new issue.</a></h1>
  14005. <p>By now, you know the drill!</p>
  14006. <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>
  14007. <p>There are some notes for those with commit access to the project on how we
  14008. manage git <a href="development/git.html">here</a>.</p>
  14009. <h1 id="conclusion"><a class="header" href="#conclusion">Conclusion</a></h1>
  14010. <p>That's it! Matrix is a very open and collaborative project as you might expect
  14011. given our obsession with open communication. If we're going to successfully
  14012. matrix together all the fragmented communication technologies out there we are
  14013. reliant on contributions and collaboration from the community to do so. So
  14014. please get involved - and we hope you have as much fun hacking on Matrix as we
  14015. do!</p>
  14016. <div style="break-before: page; page-break-before: always;"></div><h1 id="code-style"><a class="header" href="#code-style">Code Style</a></h1>
  14017. <h2 id="formatting-tools"><a class="header" href="#formatting-tools">Formatting tools</a></h2>
  14018. <p>The Synapse codebase uses a number of code formatting tools in order to
  14019. quickly and automatically check for formatting (and sometimes logical)
  14020. errors in code.</p>
  14021. <p>The necessary tools are:</p>
  14022. <ul>
  14023. <li><a href="https://black.readthedocs.io/en/stable/">black</a>, a source code formatter;</li>
  14024. <li><a href="https://pycqa.github.io/isort/">isort</a>, which organises each file's imports;</li>
  14025. <li><a href="https://flake8.pycqa.org/en/latest/">flake8</a>, which can spot common errors; and</li>
  14026. <li><a href="https://mypy.readthedocs.io/en/stable/">mypy</a>, a type checker.</li>
  14027. </ul>
  14028. <p>Install them with:</p>
  14029. <pre><code class="language-sh">pip install -e &quot;.[lint,mypy]&quot;
  14030. </code></pre>
  14031. <p>The easiest way to run the lints is to invoke the linter script as follows.</p>
  14032. <pre><code class="language-sh">scripts-dev/lint.sh
  14033. </code></pre>
  14034. <p>It's worth noting that modern IDEs and text editors can run these tools
  14035. automatically on save. It may be worth looking into whether this
  14036. functionality is supported in your editor for a more convenient
  14037. development workflow. It is not, however, recommended to run <code>flake8</code> or <code>mypy</code>
  14038. on save as they take a while and can be very resource intensive.</p>
  14039. <h2 id="general-rules"><a class="header" href="#general-rules">General rules</a></h2>
  14040. <ul>
  14041. <li><strong>Naming</strong>:
  14042. <ul>
  14043. <li>Use <code>CamelCase</code> for class and type names</li>
  14044. <li>Use underscores for <code>function_names</code> and <code>variable_names</code>.</li>
  14045. </ul>
  14046. </li>
  14047. <li><strong>Docstrings</strong>: should follow the <a href="https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings">google code
  14048. style</a>.
  14049. See the
  14050. <a href="http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html">examples</a>
  14051. in the sphinx documentation.</li>
  14052. <li><strong>Imports</strong>:
  14053. <ul>
  14054. <li>
  14055. <p>Imports should be sorted by <code>isort</code> as described above.</p>
  14056. </li>
  14057. <li>
  14058. <p>Prefer to import classes and functions rather than packages or
  14059. modules.</p>
  14060. <p>Example:</p>
  14061. <pre><code class="language-python">from synapse.types import UserID
  14062. ...
  14063. user_id = UserID(local, server)
  14064. </code></pre>
  14065. <p>is preferred over:</p>
  14066. <pre><code class="language-python">from synapse import types
  14067. ...
  14068. user_id = types.UserID(local, server)
  14069. </code></pre>
  14070. <p>(or any other variant).</p>
  14071. <p>This goes against the advice in the Google style guide, but it
  14072. means that errors in the name are caught early (at import time).</p>
  14073. </li>
  14074. <li>
  14075. <p>Avoid wildcard imports (<code>from synapse.types import *</code>) and
  14076. relative imports (<code>from .types import UserID</code>).</p>
  14077. </li>
  14078. </ul>
  14079. </li>
  14080. </ul>
  14081. <h2 id="configuration-file-format"><a class="header" href="#configuration-file-format">Configuration file format</a></h2>
  14082. <p>The <a href="./sample_config.yaml">sample configuration file</a> acts as a
  14083. reference to Synapse's configuration options for server administrators.
  14084. Remember that many readers will be unfamiliar with YAML and server
  14085. administration in general, so that it is important that the file be as
  14086. easy to understand as possible, which includes following a consistent
  14087. format.</p>
  14088. <p>Some guidelines follow:</p>
  14089. <ul>
  14090. <li>
  14091. <p>Sections should be separated with a heading consisting of a single
  14092. line prefixed and suffixed with <code>##</code>. There should be <strong>two</strong> blank
  14093. lines before the section header, and <strong>one</strong> after.</p>
  14094. </li>
  14095. <li>
  14096. <p>Each option should be listed in the file with the following format:</p>
  14097. <ul>
  14098. <li>
  14099. <p>A comment describing the setting. Each line of this comment
  14100. should be prefixed with a hash (<code>#</code>) and a space.</p>
  14101. <p>The comment should describe the default behaviour (ie, what
  14102. happens if the setting is omitted), as well as what the effect
  14103. will be if the setting is changed.</p>
  14104. <p>Often, the comment end with something like &quot;uncomment the
  14105. following to <do action>&quot;.</p>
  14106. </li>
  14107. <li>
  14108. <p>A line consisting of only <code>#</code>.</p>
  14109. </li>
  14110. <li>
  14111. <p>A commented-out example setting, prefixed with only <code>#</code>.</p>
  14112. <p>For boolean (on/off) options, convention is that this example
  14113. should be the <em>opposite</em> to the default (so the comment will end
  14114. with &quot;Uncomment the following to enable [or disable]
  14115. <feature>.&quot; For other options, the example should give some
  14116. non-default value which is likely to be useful to the reader.</p>
  14117. </li>
  14118. </ul>
  14119. </li>
  14120. <li>
  14121. <p>There should be a blank line between each option.</p>
  14122. </li>
  14123. <li>
  14124. <p>Where several settings are grouped into a single dict, <em>avoid</em> the
  14125. convention where the whole block is commented out, resulting in
  14126. comment lines starting <code># #</code>, as this is hard to read and confusing
  14127. to edit. Instead, leave the top-level config option uncommented, and
  14128. follow the conventions above for sub-options. Ensure that your code
  14129. correctly handles the top-level option being set to <code>None</code> (as it
  14130. will be if no sub-options are enabled).</p>
  14131. </li>
  14132. <li>
  14133. <p>Lines should be wrapped at 80 characters.</p>
  14134. </li>
  14135. <li>
  14136. <p>Use two-space indents.</p>
  14137. </li>
  14138. <li>
  14139. <p><code>true</code> and <code>false</code> are spelt thus (as opposed to <code>True</code>, etc.)</p>
  14140. </li>
  14141. <li>
  14142. <p>Use single quotes (<code>'</code>) rather than double-quotes (<code>&quot;</code>) or backticks
  14143. (<code>`</code>) to refer to configuration options.</p>
  14144. </li>
  14145. </ul>
  14146. <p>Example:</p>
  14147. <pre><code class="language-yaml">## Frobnication ##
  14148. # The frobnicator will ensure that all requests are fully frobnicated.
  14149. # To enable it, uncomment the following.
  14150. #
  14151. #frobnicator_enabled: true
  14152. # By default, the frobnicator will frobnicate with the default frobber.
  14153. # The following will make it use an alternative frobber.
  14154. #
  14155. #frobincator_frobber: special_frobber
  14156. # Settings for the frobber
  14157. #
  14158. frobber:
  14159. # frobbing speed. Defaults to 1.
  14160. #
  14161. #speed: 10
  14162. # frobbing distance. Defaults to 1000.
  14163. #
  14164. #distance: 100
  14165. </code></pre>
  14166. <p>Note that the sample configuration is generated from the synapse code
  14167. and is maintained by a script, <code>scripts-dev/generate_sample_config.sh</code>.
  14168. Making sure that the output from this script matches the desired format
  14169. is left as an exercise for the reader!</p>
  14170. <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>
  14171. <p>Releases of Synapse follow a two week release cycle with new releases usually
  14172. occurring on Tuesdays:</p>
  14173. <ul>
  14174. <li>Day 0: Synapse <code>N - 1</code> is released.</li>
  14175. <li>Day 7: Synapse <code>N</code> release candidate 1 is released.</li>
  14176. <li>Days 7 - 13: Synapse <code>N</code> release candidates 2+ are released, if bugs are found.</li>
  14177. <li>Day 14: Synapse <code>N</code> is released.</li>
  14178. </ul>
  14179. <p>Note that this schedule might be modified depending on the availability of the
  14180. Synapse team, e.g. releases may be skipped to avoid holidays.</p>
  14181. <p>Release announcements can be found in the
  14182. <a href="https://matrix.org/blog/category/releases">release category of the Matrix blog</a>.</p>
  14183. <h2 id="bugfix-releases"><a class="header" href="#bugfix-releases">Bugfix releases</a></h2>
  14184. <p>If a bug is found after release that is deemed severe enough (by a combination
  14185. of the impacted users and the impact on those users) then a bugfix release may
  14186. be issued. This may be at any point in the release cycle.</p>
  14187. <h2 id="security-releases"><a class="header" href="#security-releases">Security releases</a></h2>
  14188. <p>Security will sometimes be backported to the previous version and released
  14189. immediately before the next release candidate. An example of this might be:</p>
  14190. <ul>
  14191. <li>Day 0: Synapse N - 1 is released.</li>
  14192. <li>Day 7: Synapse (N - 1).1 is released as Synapse N - 1 + the security fix.</li>
  14193. <li>Day 7: Synapse N release candidate 1 is released (including the security fix).</li>
  14194. </ul>
  14195. <p>Depending on the impact and complexity of security fixes, multiple fixes might
  14196. be held to be released together.</p>
  14197. <p>In some cases, a pre-disclosure of a security release will be issued as a notice
  14198. to Synapse operators that there is an upcoming security release. These can be
  14199. found in the <a href="https://matrix.org/blog/category/security">security category of the Matrix blog</a>.</p>
  14200. <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>
  14201. <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>
  14202. <p>In an ideal world, our git commit history would be a linear progression of
  14203. commits each of which contains a single change building on what came
  14204. before. Here, by way of an arbitrary example, is the top of <code>git log --graph b2dba0607</code>:</p>
  14205. <img src="development/img/git/clean.png" alt="clean git graph" width="500px">
  14206. <p>Note how the commit comment explains clearly what is changing and why. Also
  14207. note the <em>absence</em> of merge commits, as well as the absence of commits called
  14208. things like (to pick a few culprits):
  14209. <a href="https://github.com/matrix-org/synapse/commit/84691da6c">“pep8”</a>, <a href="https://github.com/matrix-org/synapse/commit/474810d9d">“fix broken
  14210. test”</a>,
  14211. <a href="https://github.com/matrix-org/synapse/commit/c9d72e457">“oops”</a>,
  14212. <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
  14213. the president?”</a>.</p>
  14214. <p>There are a number of reasons why keeping a clean commit history is a good
  14215. thing:</p>
  14216. <ul>
  14217. <li>
  14218. <p>From time to time, after a change lands, it turns out to be necessary to
  14219. revert it, or to backport it to a release branch. Those operations are
  14220. <em>much</em> easier when the change is contained in a single commit.</p>
  14221. </li>
  14222. <li>
  14223. <p>Similarly, it's much easier to answer questions like “is the fix for
  14224. <code>/publicRooms</code> on the release branch?” if that change consists of a single
  14225. commit.</p>
  14226. </li>
  14227. <li>
  14228. <p>Likewise: “what has changed on this branch in the last week?” is much
  14229. clearer without merges and “pep8” commits everywhere.</p>
  14230. </li>
  14231. <li>
  14232. <p>Sometimes we need to figure out where a bug got introduced, or some
  14233. behaviour changed. One way of doing that is with <code>git bisect</code>: pick an
  14234. arbitrary commit between the known good point and the known bad point, and
  14235. see how the code behaves. However, that strategy fails if the commit you
  14236. chose is the middle of someone's epic branch in which they broke the world
  14237. before putting it back together again.</p>
  14238. </li>
  14239. </ul>
  14240. <p>One counterargument is that it is sometimes useful to see how a PR evolved as
  14241. it went through review cycles. This is true, but that information is always
  14242. 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
  14243. namespace</a>).</p>
  14244. <p>Of course, in reality, things are more complicated than that. We have release
  14245. branches as well as <code>develop</code> and <code>master</code>, and we deliberately merge changes
  14246. between them. Bugs often slip through and have to be fixed later. That's all
  14247. fine: this not a cast-iron rule which must be obeyed, but an ideal to aim
  14248. towards.</p>
  14249. <h2 id="merges-squashes-rebases-wtf"><a class="header" href="#merges-squashes-rebases-wtf">Merges, squashes, rebases: wtf?</a></h2>
  14250. <p>Ok, so that's what we'd like to achieve. How do we achieve it?</p>
  14251. <p>The TL;DR is: when you come to merge a pull request, you <em>probably</em> want to
  14252. “squash and merge”:</p>
  14253. <p><img src="development/img/git/squash.png" alt="squash and merge" />.</p>
  14254. <p>(This applies whether you are merging your own PR, or that of another
  14255. contributor.)</p>
  14256. <p>“Squash and merge”<sup id="a1"><a href="development/git.html#f1">1</a></sup> takes all of the changes in the
  14257. PR, and bundles them into a single commit. GitHub gives you the opportunity to
  14258. edit the commit message before you confirm, and normally you should do so,
  14259. because the default will be useless (again: <code>* woops typo</code> is not a useful
  14260. thing to keep in the historical record).</p>
  14261. <p>The main problem with this approach comes when you have a series of pull
  14262. requests which build on top of one another: as soon as you squash-merge the
  14263. first PR, you'll end up with a stack of conflicts to resolve in all of the
  14264. others. In general, it's best to avoid this situation in the first place by
  14265. trying not to have multiple related PRs in flight at the same time. Still,
  14266. sometimes that's not possible and doing a regular merge is the lesser evil.</p>
  14267. <p>Another occasion in which a regular merge makes more sense is a PR where you've
  14268. deliberately created a series of commits each of which makes sense in its own
  14269. right. For example: <a href="https://github.com/matrix-org/synapse/pull/6837">a PR which gradually propagates a refactoring operation
  14270. through the codebase</a>, or <a href="https://github.com/matrix-org/synapse/pull/5987">a
  14271. PR which is the culmination of several other
  14272. PRs</a>. In this case the ability
  14273. to figure out when a particular change/bug was introduced could be very useful.</p>
  14274. <p>Ultimately: <strong>this is not a hard-and-fast-rule</strong>. If in doubt, ask yourself “do
  14275. each of the commits I am about to merge make sense in their own right”, but
  14276. remember that we're just doing our best to balance “keeping the commit history
  14277. clean” with other factors.</p>
  14278. <h2 id="git-branching-model"><a class="header" href="#git-branching-model">Git branching model</a></h2>
  14279. <p>A <a href="https://nvie.com/posts/a-successful-git-branching-model/">lot</a>
  14280. <a href="http://scottchacon.com/2011/08/31/github-flow.html">of</a>
  14281. <a href="https://www.endoflineblog.com/gitflow-considered-harmful">words</a> have been
  14282. written in the past about git branching models (no really, <a href="https://martinfowler.com/articles/branching-patterns.html">a
  14283. lot</a>). I tend to
  14284. think the whole thing is overblown. Fundamentally, it's not that
  14285. complicated. Here's how we do it.</p>
  14286. <p>Let's start with a picture:</p>
  14287. <p><img src="development/img/git/branches.jpg" alt="branching model" /></p>
  14288. <p>It looks complicated, but it's really not. There's one basic rule: <em>anyone</em> is
  14289. free to merge from <em>any</em> more-stable branch to <em>any</em> less-stable branch at
  14290. <em>any</em> time<sup id="a2"><a href="development/git.html#f2">2</a></sup>. (The principle behind this is that if a
  14291. change is good enough for the more-stable branch, then it's also good enough go
  14292. put in a less-stable branch.)</p>
  14293. <p>Meanwhile, merging (or squashing, as per the above) from a less-stable to a
  14294. more-stable branch is a deliberate action in which you want to publish a change
  14295. or a set of changes to (some subset of) the world: for example, this happens
  14296. when a PR is landed, or as part of our release process.</p>
  14297. <p>So, what counts as a more- or less-stable branch? A little reflection will show
  14298. that our active branches are ordered thus, from more-stable to less-stable:</p>
  14299. <ul>
  14300. <li><code>master</code> (tracks our last release).</li>
  14301. <li><code>release-vX.Y</code> (the branch where we prepare the next release)<sup
  14302. id="a3"><a href="development/git.html#f3">3</a></sup>.</li>
  14303. <li>PR branches which are targeting the release.</li>
  14304. <li><code>develop</code> (our &quot;mainline&quot; branch containing our bleeding-edge).</li>
  14305. <li>regular PR branches.</li>
  14306. </ul>
  14307. <p>The corollary is: if you have a bugfix that needs to land in both
  14308. <code>release-vX.Y</code> <em>and</em> <code>develop</code>, then you should base your PR on
  14309. <code>release-vX.Y</code>, get it merged there, and then merge from <code>release-vX.Y</code> to
  14310. <code>develop</code>. (If a fix lands in <code>develop</code> and we later need it in a
  14311. release-branch, we can of course cherry-pick it, but landing it in the release
  14312. branch first helps reduce the chance of annoying conflicts.)</p>
  14313. <hr />
  14314. <p><b id="f1">[1]</b>: “Squash and merge” is GitHub's term for this
  14315. operation. Given that there is no merge involved, I'm not convinced it's the
  14316. most intuitive name. <a href="development/git.html#a1">^</a></p>
  14317. <p><b id="f2">[2]</b>: Well, anyone with commit access.<a href="development/git.html#a2">^</a></p>
  14318. <p><b id="f3">[3]</b>: Very, very occasionally (I think this has happened once in
  14319. the history of Synapse), we've had two releases in flight at once. Obviously,
  14320. <code>release-v1.2</code> is more-stable than <code>release-v1.3</code>. <a href="development/git.html#a3">^</a></p>
  14321. <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>
  14322. <p><strong>DO NOT USE THESE DEMO SERVERS IN PRODUCTION</strong></p>
  14323. <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>
  14324. <p>The demo setup allows running three federation Synapse servers, with server
  14325. names <code>localhost:8480</code>, <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
  14326. <p>You can access them via any Matrix client over HTTP at <code>localhost:8080</code>,
  14327. <code>localhost:8081</code>, and <code>localhost:8082</code> or over HTTPS at <code>localhost:8480</code>,
  14328. <code>localhost:8481</code>, and <code>localhost:8482</code>.</p>
  14329. <p>To enable the servers to communicate, self-signed SSL certificates are generated
  14330. and the servers are configured in a highly insecure way, including:</p>
  14331. <ul>
  14332. <li>Not checking certificates over federation.</li>
  14333. <li>Not verifying keys.</li>
  14334. </ul>
  14335. <p>The servers are configured to store their data under <code>demo/8080</code>, <code>demo/8081</code>, and
  14336. <code>demo/8082</code>. This includes configuration, logs, SQLite databases, and media.</p>
  14337. <p>Note that when joining a public room on a different homeserver via &quot;#foo:bar.net&quot;,
  14338. then you are (in the current implementation) joining a room with room_id &quot;foo&quot;.
  14339. This means that it won't work if your homeserver already has a room with that
  14340. name.</p>
  14341. <h2 id="using-the-demo-scripts"><a class="header" href="#using-the-demo-scripts">Using the demo scripts</a></h2>
  14342. <p>There's three main scripts with straightforward purposes:</p>
  14343. <ul>
  14344. <li><code>start.sh</code> will start the Synapse servers, generating any missing configuration.
  14345. <ul>
  14346. <li>This accepts a single parameter <code>--no-rate-limit</code> to &quot;disable&quot; rate limits
  14347. (they actually still exist, but are very high).</li>
  14348. </ul>
  14349. </li>
  14350. <li><code>stop.sh</code> will stop the Synapse servers.</li>
  14351. <li><code>clean.sh</code> will delete the configuration, databases, log files, etc.</li>
  14352. </ul>
  14353. <p>To start a completely new set of servers, run:</p>
  14354. <pre><code class="language-sh">./demo/stop.sh; ./demo/clean.sh &amp;&amp; ./demo/start.sh
  14355. </code></pre>
  14356. <div style="break-before: page; page-break-before: always;"></div><h1 id="opentracing-2"><a class="header" href="#opentracing-2">OpenTracing</a></h1>
  14357. <h2 id="background"><a class="header" href="#background">Background</a></h2>
  14358. <p>OpenTracing is a semi-standard being adopted by a number of distributed
  14359. tracing platforms. It is a common api for facilitating vendor-agnostic
  14360. tracing instrumentation. That is, we can use the OpenTracing api and
  14361. select one of a number of tracer implementations to do the heavy lifting
  14362. in the background. Our current selected implementation is Jaeger.</p>
  14363. <p>OpenTracing is a tool which gives an insight into the causal
  14364. relationship of work done in and between servers. The servers each track
  14365. events and report them to a centralised server - in Synapse's case:
  14366. Jaeger. The basic unit used to represent events is the span. The span
  14367. roughly represents a single piece of work that was done and the time at
  14368. which it occurred. A span can have child spans, meaning that the work of
  14369. the child had to be completed for the parent span to complete, or it can
  14370. have follow-on spans which represent work that is undertaken as a result
  14371. of the parent but is not depended on by the parent to in order to
  14372. finish.</p>
  14373. <p>Since this is undertaken in a distributed environment a request to
  14374. another server, such as an RPC or a simple GET, can be considered a span
  14375. (a unit or work) for the local server. This causal link is what
  14376. OpenTracing aims to capture and visualise. In order to do this metadata
  14377. about the local server's span, i.e the 'span context', needs to be
  14378. included with the request to the remote.</p>
  14379. <p>It is up to the remote server to decide what it does with the spans it
  14380. creates. This is called the sampling policy and it can be configured
  14381. through Jaeger's settings.</p>
  14382. <p>For OpenTracing concepts see
  14383. <a href="https://opentracing.io/docs/overview/what-is-tracing/">https://opentracing.io/docs/overview/what-is-tracing/</a>.</p>
  14384. <p>For more information about Jaeger's implementation see
  14385. <a href="https://www.jaegertracing.io/docs/">https://www.jaegertracing.io/docs/</a></p>
  14386. <h2 id="setting-up-opentracing"><a class="header" href="#setting-up-opentracing">Setting up OpenTracing</a></h2>
  14387. <p>To receive OpenTracing spans, start up a Jaeger server. This can be done
  14388. using docker like so:</p>
  14389. <pre><code class="language-sh">docker run -d --name jaeger \
  14390. -p 6831:6831/udp \
  14391. -p 6832:6832/udp \
  14392. -p 5778:5778 \
  14393. -p 16686:16686 \
  14394. -p 14268:14268 \
  14395. jaegertracing/all-in-one:1
  14396. </code></pre>
  14397. <p>Latest documentation is probably at
  14398. https://www.jaegertracing.io/docs/latest/getting-started.</p>
  14399. <h2 id="enable-opentracing-in-synapse"><a class="header" href="#enable-opentracing-in-synapse">Enable OpenTracing in Synapse</a></h2>
  14400. <p>OpenTracing is not enabled by default. It must be enabled in the
  14401. homeserver config by adding the <code>opentracing</code> option to your config file. You can find
  14402. documentation about how to do this in the <a href="usage/configuration/config_documentation.html#opentracing">config manual under the header 'Opentracing'</a>.
  14403. See below for an example Opentracing configuration: </p>
  14404. <pre><code class="language-yaml">opentracing:
  14405. enabled: true
  14406. homeserver_whitelist:
  14407. - &quot;mytrustedhomeserver.org&quot;
  14408. - &quot;*.myotherhomeservers.com&quot;
  14409. </code></pre>
  14410. <h2 id="homeserver-whitelisting"><a class="header" href="#homeserver-whitelisting">Homeserver whitelisting</a></h2>
  14411. <p>The homeserver whitelist is configured using regular expressions. A list
  14412. of regular expressions can be given and their union will be compared
  14413. when propagating any spans contexts to another homeserver.</p>
  14414. <p>Though it's mostly safe to send and receive span contexts to and from
  14415. untrusted users since span contexts are usually opaque ids it can lead
  14416. to two problems, namely:</p>
  14417. <ul>
  14418. <li>If the span context is marked as sampled by the sending homeserver
  14419. the receiver will sample it. Therefore two homeservers with wildly
  14420. different sampling policies could incur higher sampling counts than
  14421. intended.</li>
  14422. <li>Sending servers can attach arbitrary data to spans, known as
  14423. 'baggage'. For safety this has been disabled in Synapse but that
  14424. doesn't prevent another server sending you baggage which will be
  14425. logged to OpenTracing's logs.</li>
  14426. </ul>
  14427. <h2 id="configuring-jaeger"><a class="header" href="#configuring-jaeger">Configuring Jaeger</a></h2>
  14428. <p>Sampling strategies can be set as in this document:
  14429. <a href="https://www.jaegertracing.io/docs/latest/sampling/">https://www.jaegertracing.io/docs/latest/sampling/</a>.</p>
  14430. <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>
  14431. <p>Synapse's database schema is stored in the <code>synapse.storage.schema</code> module.</p>
  14432. <h2 id="logical-databases"><a class="header" href="#logical-databases">Logical databases</a></h2>
  14433. <p>Synapse supports splitting its datastore across multiple physical databases (which can
  14434. be useful for large installations), and the schema files are therefore split according
  14435. to the logical database they apply to.</p>
  14436. <p>At the time of writing, the following &quot;logical&quot; databases are supported:</p>
  14437. <ul>
  14438. <li><code>state</code> - used to store Matrix room state (more specifically, <code>state_groups</code>,
  14439. their relationships and contents).</li>
  14440. <li><code>main</code> - stores everything else.</li>
  14441. </ul>
  14442. <p>Additionally, the <code>common</code> directory contains schema files for tables which must be
  14443. present on <em>all</em> physical databases.</p>
  14444. <h2 id="synapse-schema-versions"><a class="header" href="#synapse-schema-versions">Synapse schema versions</a></h2>
  14445. <p>Synapse manages its database schema via &quot;schema versions&quot;. These are mainly used to
  14446. help avoid confusion if the Synapse codebase is rolled back after the database is
  14447. updated. They work as follows:</p>
  14448. <ul>
  14449. <li>
  14450. <p>The Synapse codebase defines a constant <code>synapse.storage.schema.SCHEMA_VERSION</code>
  14451. which represents the expectations made about the database by that version. For
  14452. example, as of Synapse v1.36, this is <code>59</code>.</p>
  14453. </li>
  14454. <li>
  14455. <p>The database stores a &quot;compatibility version&quot; in
  14456. <code>schema_compat_version.compat_version</code> which defines the <code>SCHEMA_VERSION</code> of the
  14457. oldest version of Synapse which will work with the database. On startup, if
  14458. <code>compat_version</code> is found to be newer than <code>SCHEMA_VERSION</code>, Synapse will refuse to
  14459. start.</p>
  14460. <p>Synapse automatically updates this field from
  14461. <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code>.</p>
  14462. </li>
  14463. <li>
  14464. <p>Whenever a backwards-incompatible change is made to the database format (normally
  14465. via a <code>delta</code> file), <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code> is also updated
  14466. so that administrators can not accidentally roll back to a too-old version of Synapse.</p>
  14467. </li>
  14468. </ul>
  14469. <p>Generally, the goal is to maintain compatibility with at least one or two previous
  14470. releases of Synapse, so any substantial change tends to require multiple releases and a
  14471. bit of forward-planning to get right.</p>
  14472. <p>As a worked example: we want to remove the <code>room_stats_historical</code> table. Here is how it
  14473. might pan out.</p>
  14474. <ol>
  14475. <li>
  14476. <p>Replace any code that <em>reads</em> from <code>room_stats_historical</code> with alternative
  14477. implementations, but keep writing to it in case of rollback to an earlier version.
  14478. Also, increase <code>synapse.storage.schema.SCHEMA_VERSION</code>. In this
  14479. instance, there is no existing code which reads from <code>room_stats_historical</code>, so
  14480. our starting point is:</p>
  14481. <p>v1.36.0: <code>SCHEMA_VERSION=59</code>, <code>SCHEMA_COMPAT_VERSION=59</code></p>
  14482. </li>
  14483. <li>
  14484. <p>Next (say in Synapse v1.37.0): remove the code that <em>writes</em> to
  14485. <code>room_stats_historical</code>, but don’t yet remove the table in case of rollback to
  14486. v1.36.0. Again, we increase <code>synapse.storage.schema.SCHEMA_VERSION</code>, but
  14487. because we have not broken compatibility with v1.36, we do not yet update
  14488. <code>SCHEMA_COMPAT_VERSION</code>. We now have:</p>
  14489. <p>v1.37.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=59</code>.</p>
  14490. </li>
  14491. <li>
  14492. <p>Later (say in Synapse v1.38.0): we can remove the table altogether. This will
  14493. break compatibility with v1.36.0, so we must update <code>SCHEMA_COMPAT_VERSION</code> accordingly.
  14494. There is no need to update <code>synapse.storage.schema.SCHEMA_VERSION</code>, since there is no
  14495. change to the Synapse codebase here. So we end up with:</p>
  14496. <p>v1.38.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=60</code>.</p>
  14497. </li>
  14498. </ol>
  14499. <p>If in doubt about whether to update <code>SCHEMA_VERSION</code> or not, it is generally best to
  14500. lean towards doing so.</p>
  14501. <h2 id="full-schema-dumps"><a class="header" href="#full-schema-dumps">Full schema dumps</a></h2>
  14502. <p>In the <code>full_schemas</code> directories, only the most recently-numbered snapshot is used
  14503. (<code>54</code> at the time of writing). Older snapshots (eg, <code>16</code>) are present for historical
  14504. reference only.</p>
  14505. <h3 id="building-full-schema-dumps"><a class="header" href="#building-full-schema-dumps">Building full schema dumps</a></h3>
  14506. <p>If you want to recreate these schemas, they need to be made from a database that
  14507. has had all background updates run.</p>
  14508. <p>To do so, use <code>scripts-dev/make_full_schema.sh</code>. This will produce new
  14509. <code>full.sql.postgres</code> and <code>full.sql.sqlite</code> files.</p>
  14510. <p>Ensure postgres is installed, then run:</p>
  14511. <pre><code class="language-sh">./scripts-dev/make_full_schema.sh -p postgres_username -o output_dir/
  14512. </code></pre>
  14513. <p>NB at the time of writing, this script predates the split into separate <code>state</code>/<code>main</code>
  14514. databases so will require updates to handle that correctly.</p>
  14515. <h2 id="delta-files"><a class="header" href="#delta-files">Delta files</a></h2>
  14516. <p>Delta files define the steps required to upgrade the database from an earlier version.
  14517. They can be written as either a file containing a series of SQL statements, or a Python
  14518. module.</p>
  14519. <p>Synapse remembers which delta files it has applied to a database (they are stored in the
  14520. <code>applied_schema_deltas</code> table) and will not re-apply them (even if a given file is
  14521. subsequently updated).</p>
  14522. <p>Delta files should be placed in a directory named <code>synapse/storage/schema/&lt;database&gt;/delta/&lt;version&gt;/</code>.
  14523. They are applied in alphanumeric order, so by convention the first two characters
  14524. of the filename should be an integer such as <code>01</code>, to put the file in the right order.</p>
  14525. <h3 id="sql-delta-files"><a class="header" href="#sql-delta-files">SQL delta files</a></h3>
  14526. <p>These should be named <code>*.sql</code>, or — for changes which should only be applied for a
  14527. given database engine — <code>*.sql.posgres</code> or <code>*.sql.sqlite</code>. For example, a delta which
  14528. adds a new column to the <code>foo</code> table might be called <code>01add_bar_to_foo.sql</code>.</p>
  14529. <p>Note that our SQL parser is a bit simple - it understands comments (<code>--</code> and <code>/*...*/</code>),
  14530. 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>
  14531. <h3 id="python-delta-files"><a class="header" href="#python-delta-files">Python delta files</a></h3>
  14532. <p>For more flexibility, a delta file can take the form of a python module. These should
  14533. be named <code>*.py</code>. Note that database-engine-specific modules are not supported here –
  14534. instead you can write <code>if isinstance(database_engine, PostgresEngine)</code> or similar.</p>
  14535. <p>A Python delta module should define either or both of the following functions:</p>
  14536. <pre><code class="language-python">import synapse.config.homeserver
  14537. import synapse.storage.engines
  14538. import synapse.storage.types
  14539. def run_create(
  14540. cur: synapse.storage.types.Cursor,
  14541. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  14542. ) -&gt; None:
  14543. &quot;&quot;&quot;Called whenever an existing or new database is to be upgraded&quot;&quot;&quot;
  14544. ...
  14545. def run_upgrade(
  14546. cur: synapse.storage.types.Cursor,
  14547. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  14548. config: synapse.config.homeserver.HomeServerConfig,
  14549. ) -&gt; None:
  14550. &quot;&quot;&quot;Called whenever an existing database is to be upgraded.&quot;&quot;&quot;
  14551. ...
  14552. </code></pre>
  14553. <h2 id="boolean-columns"><a class="header" href="#boolean-columns">Boolean columns</a></h2>
  14554. <p>Boolean columns require special treatment, since SQLite treats booleans the
  14555. same as integers.</p>
  14556. <p>There are three separate aspects to this:</p>
  14557. <ul>
  14558. <li>
  14559. <p>Any new boolean column must be added to the <code>BOOLEAN_COLUMNS</code> list in
  14560. <code>synapse/_scripts/synapse_port_db.py</code>. This tells the port script to cast
  14561. the integer value from SQLite to a boolean before writing the value to the
  14562. postgres database.</p>
  14563. </li>
  14564. <li>
  14565. <p>Before SQLite 3.23, <code>TRUE</code> and <code>FALSE</code> were not recognised as constants by
  14566. SQLite, and the <code>IS [NOT] TRUE</code>/<code>IS [NOT] FALSE</code> operators were not
  14567. supported. This makes it necessary to avoid using <code>TRUE</code> and <code>FALSE</code>
  14568. constants in SQL commands.</p>
  14569. <p>For example, to insert a <code>TRUE</code> value into the database, write:</p>
  14570. <pre><code class="language-python">txn.execute(&quot;INSERT INTO tbl(col) VALUES (?)&quot;, (True, ))
  14571. </code></pre>
  14572. </li>
  14573. <li>
  14574. <p>Default values for new boolean columns present a particular
  14575. difficulty. Generally it is best to create separate schema files for
  14576. Postgres and SQLite. For example:</p>
  14577. <pre><code class="language-sql"># in 00delta.sql.postgres:
  14578. ALTER TABLE tbl ADD COLUMN col BOOLEAN DEFAULT FALSE;
  14579. </code></pre>
  14580. <pre><code class="language-sql"># in 00delta.sql.sqlite:
  14581. ALTER TABLE tbl ADD COLUMN col BOOLEAN DEFAULT 0;
  14582. </code></pre>
  14583. <p>Note that there is a particularly insidious failure mode here: the Postgres
  14584. flavour will be accepted by SQLite 3.22, but will give a column whose
  14585. default value is the <strong>string</strong> <code>&quot;FALSE&quot;</code> - which, when cast back to a boolean
  14586. in Python, evaluates to <code>True</code>.</p>
  14587. </li>
  14588. </ul>
  14589. <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>
  14590. <p>It can be desirable to implement &quot;experimental&quot; features which are disabled by
  14591. default and must be explicitly enabled via the Synapse configuration. This is
  14592. applicable for features which:</p>
  14593. <ul>
  14594. <li>Are unstable in the Matrix spec (e.g. those defined by an MSC that has not yet been merged).</li>
  14595. <li>Developers are not confident in their use by general Synapse administrators/users
  14596. (e.g. a feature is incomplete, buggy, performs poorly, or needs further testing).</li>
  14597. </ul>
  14598. <p>Note that this only really applies to features which are expected to be desirable
  14599. to a broad audience. The <a href="development/../modules/index.html">module infrastructure</a> should
  14600. instead be investigated for non-standard features.</p>
  14601. <p>Guarding experimental features behind configuration flags should help with some
  14602. of the following scenarios:</p>
  14603. <ul>
  14604. <li>Ensure that clients do not assume that unstable features exist (failing
  14605. gracefully if they do not).</li>
  14606. <li>Unstable features do not become de-facto standards and can be removed
  14607. aggressively (since only those who have opted-in will be affected).</li>
  14608. <li>Ease finding the implementation of unstable features in Synapse (for future
  14609. removal or stabilization).</li>
  14610. <li>Ease testing a feature (or removal of feature) due to enabling/disabling without
  14611. code changes. It also becomes possible to ask for wider testing, if desired.</li>
  14612. </ul>
  14613. <p>Experimental configuration flags should be disabled by default (requiring Synapse
  14614. administrators to explicitly opt-in), although there are situations where it makes
  14615. sense (from a product point-of-view) to enable features by default. This is
  14616. expected and not an issue.</p>
  14617. <p>It is not a requirement for experimental features to be behind a configuration flag,
  14618. but one should be used if unsure.</p>
  14619. <p>New experimental configuration flags should be added under the <code>experimental</code>
  14620. configuration key (see the <code>synapse.config.experimental</code> file) and either explain
  14621. (briefly) what is being enabled, or include the MSC number.</p>
  14622. <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>
  14623. <p>This is a quick cheat sheet for developers on how to use <a href="https://python-poetry.org/"><code>poetry</code></a>.</p>
  14624. <h1 id="background-1"><a class="header" href="#background-1">Background</a></h1>
  14625. <p>Synapse uses a variety of third-party Python packages to function as a homeserver.
  14626. Some of these are direct dependencies, listed in <code>pyproject.toml</code> under the
  14627. <code>[tool.poetry.dependencies]</code> section. The rest are transitive dependencies (the
  14628. things that our direct dependencies themselves depend on, and so on recursively.)</p>
  14629. <p>We maintain a locked list of all our dependencies (transitive included) so that
  14630. we can track exactly which version of each dependency appears in a given release.
  14631. See <a href="https://github.com/matrix-org/synapse/issues/11537#issue-1074469665">here</a>
  14632. for discussion of why we wanted this for Synapse. We chose to use
  14633. <a href="https://python-poetry.org/"><code>poetry</code></a> to manage this locked list; see
  14634. <a href="https://github.com/matrix-org/synapse/issues/11537#issuecomment-1015975819">this comment</a>
  14635. for the reasoning.</p>
  14636. <p>The locked dependencies get included in our &quot;self-contained&quot; releases: namely,
  14637. our docker images and our debian packages. We also use the locked dependencies
  14638. in development and our continuous integration.</p>
  14639. <p>Separately, our &quot;broad&quot; dependencies—the version ranges specified in
  14640. <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
  14641. to PyPI</a>. Installing from PyPI or from
  14642. the Synapse source tree directly will <em>not</em> use the locked dependencies; instead,
  14643. they'll pull in the latest version of each package available at install time.</p>
  14644. <h2 id="example-dependency"><a class="header" href="#example-dependency">Example dependency</a></h2>
  14645. <p>An example may help. We have a broad dependency on
  14646. <a href="https://pypi.org/project/phonenumbers/"><code>phonenumbers</code></a>, as declared in
  14647. 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>
  14648. <pre><code class="language-toml">[tool.poetry.dependencies]
  14649. # ...
  14650. phonenumbers = &quot;&gt;=8.2.0&quot;
  14651. </code></pre>
  14652. <p>In our lockfile this is
  14653. <a href="https://github.com/matrix-org/synapse/blob/dfc7646504cef3e4ff396c36089e1c6f1b1634de/poetry.lock#L679-L685">pinned</a>
  14654. to version 8.12.44, even though
  14655. <a href="https://pypi.org/project/phonenumbers/#history">newer versions are available</a>.</p>
  14656. <pre><code class="language-toml">[[package]]
  14657. name = &quot;phonenumbers&quot;
  14658. version = &quot;8.12.44&quot;
  14659. description = &quot;Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.&quot;
  14660. category = &quot;main&quot;
  14661. optional = false
  14662. python-versions = &quot;*&quot;
  14663. </code></pre>
  14664. <p>The lockfile also includes a
  14665. <a href="https://github.com/matrix-org/synapse/blob/release-v1.57/poetry.lock#L2178-L2181">cryptographic checksum</a>
  14666. of the sdists and wheels provided for this version of <code>phonenumbers</code>.</p>
  14667. <pre><code class="language-toml">[metadata.files]
  14668. # ...
  14669. phonenumbers = [
  14670. {file = &quot;phonenumbers-8.12.44-py2.py3-none-any.whl&quot;, hash = &quot;sha256:cc1299cf37b309ecab6214297663ab86cb3d64ae37fd5b88e904fe7983a874a6&quot;},
  14671. {file = &quot;phonenumbers-8.12.44.tar.gz&quot;, hash = &quot;sha256:26cfd0257d1704fe2f88caff2caabb70d16a877b1e65b6aae51f9fbbe10aa8ce&quot;},
  14672. ]
  14673. </code></pre>
  14674. <p>We can see this pinned version inside the docker image for that release:</p>
  14675. <pre><code>$ docker pull matrixdotorg/synapse:v1.57.0
  14676. ...
  14677. $ docker run --entrypoint pip matrixdotorg/synapse:v1.57.0 show phonenumbers
  14678. Name: phonenumbers
  14679. Version: 8.12.44
  14680. Summary: Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.
  14681. Home-page: https://github.com/daviddrysdale/python-phonenumbers
  14682. Author: David Drysdale
  14683. Author-email: dmd@lurklurk.org
  14684. License: Apache License 2.0
  14685. Location: /usr/local/lib/python3.9/site-packages
  14686. Requires:
  14687. Required-by: matrix-synapse
  14688. </code></pre>
  14689. <p>Whereas the wheel metadata just contains the broad dependencies:</p>
  14690. <pre><code>$ cd /tmp
  14691. $ wget https://files.pythonhosted.org/packages/ca/5e/d722d572cc5b3092402b783d6b7185901b444427633bd8a6b00ea0dd41b7/matrix_synapse-1.57.0rc1-py3-none-any.whl
  14692. ...
  14693. $ unzip -c matrix_synapse-1.57.0rc1-py3-none-any.whl matrix_synapse-1.57.0rc1.dist-info/METADATA | grep phonenumbers
  14694. Requires-Dist: phonenumbers (&gt;=8.2.0)
  14695. </code></pre>
  14696. <h1 id="tooling-recommendation-direnv"><a class="header" href="#tooling-recommendation-direnv">Tooling recommendation: direnv</a></h1>
  14697. <p><a href="https://direnv.net/"><code>direnv</code></a> is a tool for activating environments in your
  14698. shell inside a given directory. Its support for poetry is unofficial (a
  14699. community wiki recipe only), but works solidly in our experience. We thoroughly
  14700. recommend it for daily use. To use it:</p>
  14701. <ol>
  14702. <li><a href="https://direnv.net/docs/installation.html">Install <code>direnv</code></a> - it's likely
  14703. packaged for your system already.</li>
  14704. <li>Teach direnv about poetry. The <a href="https://github.com/direnv/direnv/wiki/Python#poetry">shell config here</a>
  14705. needs to be added to <code>~/.config/direnv/direnvrc</code> (or more generally <code>$XDG_CONFIG_HOME/direnv/direnvrc</code>).</li>
  14706. <li>Mark the synapse checkout as a poetry project: <code>echo layout poetry &gt; .envrc</code>.</li>
  14707. <li>Convince yourself that you trust this <code>.envrc</code> configuration and project.
  14708. Then formally confirm this to <code>direnv</code> by running <code>direnv allow</code>.</li>
  14709. </ol>
  14710. <p>Then whenever you navigate to the synapse checkout, you should be able to run
  14711. e.g. <code>mypy</code> instead of <code>poetry run mypy</code>; <code>python</code> instead of
  14712. <code>poetry run python</code>; and your shell commands will automatically run in the
  14713. context of poetry's venv, without having to run <code>poetry shell</code> beforehand.</p>
  14714. <h1 id="how-do-i"><a class="header" href="#how-do-i">How do I...</a></h1>
  14715. <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>
  14716. <pre><code class="language-shell">poetry install --extras all --remove-untracked
  14717. </code></pre>
  14718. <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>
  14719. <p>Use <code>poetry run cmd args</code> when you need the python virtualenv context.
  14720. To avoid typing <code>poetry run</code> all the time, you can run <code>poetry shell</code>
  14721. to start a new shell in the poetry virtualenv context. Within <code>poetry shell</code>,
  14722. <code>python</code>, <code>pip</code>, <code>mypy</code>, <code>trial</code>, etc. are all run inside the project virtualenv
  14723. and isolated from the rest o the system.</p>
  14724. <p>Roughly speaking, the translation from a traditional virtualenv is:</p>
  14725. <ul>
  14726. <li><code>env/bin/activate</code> -&gt; <code>poetry shell</code>, and</li>
  14727. <li><code>deactivate</code> -&gt; close the terminal (Ctrl-D, <code>exit</code>, etc.)</li>
  14728. </ul>
  14729. <p>See also the direnv recommendation above, which makes <code>poetry run</code> and
  14730. <code>poetry shell</code> unnecessary.</p>
  14731. <h2 id="inspect-the-poetry-virtualenv"><a class="header" href="#inspect-the-poetry-virtualenv">...inspect the <code>poetry</code> virtualenv?</a></h2>
  14732. <p>Some suggestions:</p>
  14733. <pre><code class="language-shell"># Current env only
  14734. poetry env info
  14735. # All envs: this allows you to have e.g. a poetry managed venv for Python 3.7,
  14736. # and another for Python 3.10.
  14737. poetry env list --full-path
  14738. poetry run pip list
  14739. </code></pre>
  14740. <p>Note that <code>poetry show</code> describes the abstract <em>lock file</em> rather than your
  14741. on-disk environment. With that said, <code>poetry show --tree</code> can sometimes be
  14742. useful.</p>
  14743. <h2 id="add-a-new-dependency"><a class="header" href="#add-a-new-dependency">...add a new dependency?</a></h2>
  14744. <p>Either:</p>
  14745. <ul>
  14746. <li>manually update <code>pyproject.toml</code>; then <code>poetry lock --no-update</code>; or else</li>
  14747. <li><code>poetry add packagename</code>. See <code>poetry add --help</code>; note the <code>--dev</code>,
  14748. <code>--extras</code> and <code>--optional</code> flags in particular.
  14749. <ul>
  14750. <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>
  14751. </ul>
  14752. </li>
  14753. </ul>
  14754. <p>Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> files in your commit.</p>
  14755. <h2 id="remove-a-dependency"><a class="header" href="#remove-a-dependency">...remove a dependency?</a></h2>
  14756. <p>This is not done often and is untested, but</p>
  14757. <pre><code class="language-shell">poetry remove packagename
  14758. </code></pre>
  14759. <p>ought to do the trick. Alternatively, manually update <code>pyproject.toml</code> and
  14760. <code>poetry lock --no-update</code>. Include the updated <code>pyproject.toml</code> and poetry.lock`
  14761. files in your commit.</p>
  14762. <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>
  14763. <p>Best done by manually editing <code>pyproject.toml</code>, then <code>poetry lock --no-update</code>.
  14764. Include the updated <code>pyproject.toml</code> and <code>poetry.lock</code> in your commit.</p>
  14765. <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>
  14766. <p>Use</p>
  14767. <pre><code class="language-shell">poetry update packagename
  14768. </code></pre>
  14769. <p>to use the latest version of <code>packagename</code> in the locked environment, without
  14770. affecting the broad dependencies listed in the wheel.</p>
  14771. <p>There doesn't seem to be a way to do this whilst locking a <em>specific</em> version of
  14772. <code>packagename</code>. We can workaround this (crudely) as follows:</p>
  14773. <pre><code class="language-shell">poetry add packagename==1.2.3
  14774. # This should update pyproject.lock.
  14775. # Now undo the changes to pyproject.toml. For example
  14776. # git restore pyproject.toml
  14777. # Get poetry to recompute the content-hash of pyproject.toml without changing
  14778. # the locked package versions.
  14779. poetry lock --no-update
  14780. </code></pre>
  14781. <p>Either way, include the updated <code>poetry.lock</code> file in your commit.</p>
  14782. <h2 id="export-a-requirementstxt-file"><a class="header" href="#export-a-requirementstxt-file">...export a <code>requirements.txt</code> file?</a></h2>
  14783. <pre><code class="language-shell">poetry export --extras all
  14784. </code></pre>
  14785. <p>Be wary of bugs in <code>poetry export</code> and <code>pip install -r requirements.txt</code>.</p>
  14786. <p>Note: <code>poetry export</code> will be made a plugin in Poetry 1.2. Additional config may
  14787. be required.</p>
  14788. <h2 id="build-a-test-wheel"><a class="header" href="#build-a-test-wheel">...build a test wheel?</a></h2>
  14789. <p>I usually use</p>
  14790. <pre><code class="language-shell">poetry run pip install build &amp;&amp; poetry run python -m build
  14791. </code></pre>
  14792. <p>because <a href="https://github.com/pypa/build"><code>build</code></a> is a standardish tool which
  14793. doesn't require poetry. (It's what we use in CI too). However, you could try
  14794. <code>poetry build</code> too.</p>
  14795. <div style="break-before: page; page-break-before: always;"></div><h1 id="cancellation"><a class="header" href="#cancellation">Cancellation</a></h1>
  14796. <p>Sometimes, requests take a long time to service and clients disconnect
  14797. before Synapse produces a response. To avoid wasting resources, Synapse
  14798. can cancel request processing for select endpoints marked with the
  14799. <code>@cancellable</code> decorator.</p>
  14800. <p>Synapse makes use of Twisted's <code>Deferred.cancel()</code> feature to make
  14801. cancellation work. The <code>@cancellable</code> decorator does nothing by itself
  14802. and merely acts as a flag, signalling to developers and other code alike
  14803. that a method can be cancelled.</p>
  14804. <h2 id="enabling-cancellation-for-an-endpoint"><a class="header" href="#enabling-cancellation-for-an-endpoint">Enabling cancellation for an endpoint</a></h2>
  14805. <ol>
  14806. <li>Check that the endpoint method, and any <code>async</code> functions in its call
  14807. tree handle cancellation correctly. See
  14808. <a href="development/synapse_architecture/cancellation.html#handling-cancellation-correctly">Handling cancellation correctly</a>
  14809. for a list of things to look out for.</li>
  14810. <li>Add the <code>@cancellable</code> decorator to the <code>on_GET/POST/PUT/DELETE</code>
  14811. method. It's not recommended to make non-<code>GET</code> methods cancellable,
  14812. since cancellation midway through some database updates is less
  14813. likely to be handled correctly.</li>
  14814. </ol>
  14815. <h2 id="mechanics"><a class="header" href="#mechanics">Mechanics</a></h2>
  14816. <p>There are two stages to cancellation: downward propagation of a
  14817. <code>cancel()</code> call, followed by upwards propagation of a <code>CancelledError</code>
  14818. out of a blocked <code>await</code>.
  14819. Both Twisted and asyncio have a cancellation mechanism.</p>
  14820. <table><thead><tr><th></th><th>Method</th><th>Exception</th><th>Exception inherits from</th></tr></thead><tbody>
  14821. <tr><td>Twisted</td><td><code>Deferred.cancel()</code></td><td><code>twisted.internet.defer.CancelledError</code></td><td><code>Exception</code> (!)</td></tr>
  14822. <tr><td>asyncio</td><td><code>Task.cancel()</code></td><td><code>asyncio.CancelledError</code></td><td><code>BaseException</code></td></tr>
  14823. </tbody></table>
  14824. <h3 id="deferredcancel"><a class="header" href="#deferredcancel">Deferred.cancel()</a></h3>
  14825. <p>When Synapse starts handling a request, it runs the async method
  14826. responsible for handling it using <code>defer.ensureDeferred</code>, which returns
  14827. a <code>Deferred</code>. For example:</p>
  14828. <pre><code class="language-python">def do_something() -&gt; Deferred[None]:
  14829. ...
  14830. @cancellable
  14831. async def on_GET() -&gt; Tuple[int, JsonDict]:
  14832. d = make_deferred_yieldable(do_something())
  14833. await d
  14834. return 200, {}
  14835. request = defer.ensureDeferred(on_GET())
  14836. </code></pre>
  14837. <p>When a client disconnects early, Synapse checks for the presence of the
  14838. <code>@cancellable</code> decorator on <code>on_GET</code>. Since <code>on_GET</code> is cancellable,
  14839. <code>Deferred.cancel()</code> is called on the <code>Deferred</code> from
  14840. <code>defer.ensureDeferred</code>, ie. <code>request</code>. Twisted knows which <code>Deferred</code>
  14841. <code>request</code> is waiting on and passes the <code>cancel()</code> call on to <code>d</code>.</p>
  14842. <p>The <code>Deferred</code> being waited on, <code>d</code>, may have its own handling for
  14843. <code>cancel()</code> and pass the call on to other <code>Deferred</code>s.</p>
  14844. <p>Eventually, a <code>Deferred</code> handles the <code>cancel()</code> call by resolving itself
  14845. with a <code>CancelledError</code>.</p>
  14846. <h3 id="cancellederror"><a class="header" href="#cancellederror">CancelledError</a></h3>
  14847. <p>The <code>CancelledError</code> gets raised out of the <code>await</code> and bubbles up, as
  14848. per normal Python exception handling.</p>
  14849. <h2 id="handling-cancellation-correctly"><a class="header" href="#handling-cancellation-correctly">Handling cancellation correctly</a></h2>
  14850. <p>In general, when writing code that might be subject to cancellation, two
  14851. things must be considered:</p>
  14852. <ul>
  14853. <li>The effect of <code>CancelledError</code>s raised out of <code>await</code>s.</li>
  14854. <li>The effect of <code>Deferred</code>s being <code>cancel()</code>ed.</li>
  14855. </ul>
  14856. <p>Examples of code that handles cancellation incorrectly include:</p>
  14857. <ul>
  14858. <li><code>try-except</code> blocks which swallow <code>CancelledError</code>s.</li>
  14859. <li>Code that shares the same <code>Deferred</code>, which may be cancelled, between
  14860. multiple requests.</li>
  14861. <li>Code that starts some processing that's exempt from cancellation, but
  14862. uses a logging context from cancellable code. The logging context
  14863. will be finished upon cancellation, while the uncancelled processing
  14864. is still using it.</li>
  14865. </ul>
  14866. <p>Some common patterns are listed below in more detail.</p>
  14867. <h3 id="async-function-calls"><a class="header" href="#async-function-calls"><code>async</code> function calls</a></h3>
  14868. <p>Most functions in Synapse are relatively straightforward from a
  14869. cancellation standpoint: they don't do anything with <code>Deferred</code>s and
  14870. purely call and <code>await</code> other <code>async</code> functions.</p>
  14871. <p>An <code>async</code> function handles cancellation correctly if its own code
  14872. handles cancellation correctly and all the async function it calls
  14873. handle cancellation correctly. For example:</p>
  14874. <pre><code class="language-python">async def do_two_things() -&gt; None:
  14875. check_something()
  14876. await do_something()
  14877. await do_something_else()
  14878. </code></pre>
  14879. <p><code>do_two_things</code> handles cancellation correctly if <code>do_something</code> and
  14880. <code>do_something_else</code> handle cancellation correctly.</p>
  14881. <p>That is, when checking whether a function handles cancellation
  14882. correctly, its implementation and all its <code>async</code> function calls need to
  14883. be checked, recursively.</p>
  14884. <p>As <code>check_something</code> is not <code>async</code>, it does not need to be checked.</p>
  14885. <h3 id="cancellederrors"><a class="header" href="#cancellederrors">CancelledErrors</a></h3>
  14886. <p>Because Twisted's <code>CancelledError</code>s are <code>Exception</code>s, it's easy to
  14887. accidentally catch and suppress them. Care must be taken to ensure that
  14888. <code>CancelledError</code>s are allowed to propagate upwards.</p>
  14889. <table width="100%">
  14890. <tr>
  14891. <td width="50%" valign="top">
  14892. <p><strong>Bad</strong>:</p>
  14893. <pre><code class="language-python">try:
  14894. await do_something()
  14895. except Exception:
  14896. # `CancelledError` gets swallowed here.
  14897. logger.info(...)
  14898. </code></pre>
  14899. </td>
  14900. <td width="50%" valign="top">
  14901. <p><strong>Good</strong>:</p>
  14902. <pre><code class="language-python">try:
  14903. await do_something()
  14904. except CancelledError:
  14905. raise
  14906. except Exception:
  14907. logger.info(...)
  14908. </code></pre>
  14909. </td>
  14910. </tr>
  14911. <tr>
  14912. <td width="50%" valign="top">
  14913. <p><strong>OK</strong>:</p>
  14914. <pre><code class="language-python">try:
  14915. check_something()
  14916. # A `CancelledError` won't ever be raised here.
  14917. except Exception:
  14918. logger.info(...)
  14919. </code></pre>
  14920. </td>
  14921. <td width="50%" valign="top">
  14922. <p><strong>Good</strong>:</p>
  14923. <pre><code class="language-python">try:
  14924. await do_something()
  14925. except ValueError:
  14926. logger.info(...)
  14927. </code></pre>
  14928. </td>
  14929. </tr>
  14930. </table>
  14931. <h4 id="defergatherresults"><a class="header" href="#defergatherresults">defer.gatherResults</a></h4>
  14932. <p><code>defer.gatherResults</code> produces a <code>Deferred</code> which:</p>
  14933. <ul>
  14934. <li>broadcasts <code>cancel()</code> calls to every <code>Deferred</code> being waited on.</li>
  14935. <li>wraps the first exception it sees in a <code>FirstError</code>.</li>
  14936. </ul>
  14937. <p>Together, this means that <code>CancelledError</code>s will be wrapped in
  14938. a <code>FirstError</code> unless unwrapped. Such <code>FirstError</code>s are liable to be
  14939. swallowed, so they must be unwrapped.</p>
  14940. <table width="100%">
  14941. <tr>
  14942. <td width="50%" valign="top">
  14943. <p><strong>Bad</strong>:</p>
  14944. <pre><code class="language-python">async def do_something() -&gt; None:
  14945. await make_deferred_yieldable(
  14946. defer.gatherResults([...], consumeErrors=True)
  14947. )
  14948. try:
  14949. await do_something()
  14950. except CancelledError:
  14951. raise
  14952. except Exception:
  14953. # `FirstError(CancelledError)` gets swallowed here.
  14954. logger.info(...)
  14955. </code></pre>
  14956. </td>
  14957. <td width="50%" valign="top">
  14958. <p><strong>Good</strong>:</p>
  14959. <pre><code class="language-python">async def do_something() -&gt; None:
  14960. await make_deferred_yieldable(
  14961. defer.gatherResults([...], consumeErrors=True)
  14962. ).addErrback(unwrapFirstError)
  14963. try:
  14964. await do_something()
  14965. except CancelledError:
  14966. raise
  14967. except Exception:
  14968. logger.info(...)
  14969. </code></pre>
  14970. </td>
  14971. </tr>
  14972. </table>
  14973. <h3 id="creation-of-deferreds"><a class="header" href="#creation-of-deferreds">Creation of <code>Deferred</code>s</a></h3>
  14974. <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>
  14975. <table width="100%">
  14976. <tr>
  14977. <td width="50%" valign="top">
  14978. <p><strong>Bad</strong>:</p>
  14979. <pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}
  14980. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  14981. deferred = cache.get(room_id)
  14982. if deferred is None:
  14983. deferred = Deferred()
  14984. cache[room_id] = deferred
  14985. # `deferred` can have multiple waiters.
  14986. # All of them will observe a `CancelledError`
  14987. # if any one of them is cancelled.
  14988. return make_deferred_yieldable(deferred)
  14989. # Request 1
  14990. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  14991. # Request 2
  14992. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  14993. </code></pre>
  14994. </td>
  14995. <td width="50%" valign="top">
  14996. <p><strong>Good</strong>:</p>
  14997. <pre><code class="language-python">cache: Dict[str, Deferred[None]] = {}
  14998. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  14999. deferred = cache.get(room_id)
  15000. if deferred is None:
  15001. deferred = Deferred()
  15002. cache[room_id] = deferred
  15003. # `deferred` will never be cancelled now.
  15004. # A `CancelledError` will still come out of
  15005. # the `await`.
  15006. # `delay_cancellation` may also be used.
  15007. return make_deferred_yieldable(stop_cancellation(deferred))
  15008. # Request 1
  15009. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15010. # Request 2
  15011. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15012. </code></pre>
  15013. </td>
  15014. </tr>
  15015. <tr>
  15016. <td width="50%" valign="top">
  15017. </td>
  15018. <td width="50%" valign="top">
  15019. <p><strong>Good</strong>:</p>
  15020. <pre><code class="language-python">cache: Dict[str, List[Deferred[None]]] = {}
  15021. def wait_for_room(room_id: str) -&gt; Deferred[None]:
  15022. if room_id not in cache:
  15023. cache[room_id] = []
  15024. # Each request gets its own `Deferred` to wait on.
  15025. deferred = Deferred()
  15026. cache[room_id]].append(deferred)
  15027. return make_deferred_yieldable(deferred)
  15028. # Request 1
  15029. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15030. # Request 2
  15031. await wait_for_room(&quot;!aAAaaAaaaAAAaAaAA:matrix.org&quot;)
  15032. </code></pre>
  15033. </td>
  15034. </table>
  15035. <h3 id="uncancelled-processing"><a class="header" href="#uncancelled-processing">Uncancelled processing</a></h3>
  15036. <p>Some <code>async</code> functions may kick off some <code>async</code> processing which is
  15037. intentionally protected from cancellation, by <code>stop_cancellation</code> or
  15038. other means. If the <code>async</code> processing inherits the logcontext of the
  15039. request which initiated it, care must be taken to ensure that the
  15040. logcontext is not finished before the <code>async</code> processing completes.</p>
  15041. <table width="100%">
  15042. <tr>
  15043. <td width="50%" valign="top">
  15044. <p><strong>Bad</strong>:</p>
  15045. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  15046. async def do_something_else(
  15047. to_resolve: Deferred[None]
  15048. ) -&gt; None:
  15049. await ...
  15050. logger.info(&quot;done!&quot;)
  15051. to_resolve.callback(None)
  15052. async def do_something() -&gt; None:
  15053. if not cache:
  15054. to_resolve = Deferred()
  15055. cache = ObservableDeferred(to_resolve)
  15056. # `do_something_else` will never be cancelled and
  15057. # can outlive the `request-1` logging context.
  15058. run_in_background(do_something_else, to_resolve)
  15059. await make_deferred_yieldable(cache.observe())
  15060. with LoggingContext(&quot;request-1&quot;):
  15061. await do_something()
  15062. </code></pre>
  15063. </td>
  15064. <td width="50%" valign="top">
  15065. <p><strong>Good</strong>:</p>
  15066. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  15067. async def do_something_else(
  15068. to_resolve: Deferred[None]
  15069. ) -&gt; None:
  15070. await ...
  15071. logger.info(&quot;done!&quot;)
  15072. to_resolve.callback(None)
  15073. async def do_something() -&gt; None:
  15074. if not cache:
  15075. to_resolve = Deferred()
  15076. cache = ObservableDeferred(to_resolve)
  15077. run_in_background(do_something_else, to_resolve)
  15078. # We'll wait until `do_something_else` is
  15079. # done before raising a `CancelledError`.
  15080. await make_deferred_yieldable(
  15081. delay_cancellation(cache.observe())
  15082. )
  15083. else:
  15084. await make_deferred_yieldable(cache.observe())
  15085. with LoggingContext(&quot;request-1&quot;):
  15086. await do_something()
  15087. </code></pre>
  15088. </td>
  15089. </tr>
  15090. <tr>
  15091. <td width="50%">
  15092. <p><strong>OK</strong>:</p>
  15093. <pre><code class="language-python">cache: Optional[ObservableDeferred[None]] = None
  15094. async def do_something_else(
  15095. to_resolve: Deferred[None]
  15096. ) -&gt; None:
  15097. await ...
  15098. logger.info(&quot;done!&quot;)
  15099. to_resolve.callback(None)
  15100. async def do_something() -&gt; None:
  15101. if not cache:
  15102. to_resolve = Deferred()
  15103. cache = ObservableDeferred(to_resolve)
  15104. # `do_something_else` will get its own independent
  15105. # logging context. `request-1` will not count any
  15106. # metrics from `do_something_else`.
  15107. run_as_background_process(
  15108. &quot;do_something_else&quot;,
  15109. do_something_else,
  15110. to_resolve,
  15111. )
  15112. await make_deferred_yieldable(cache.observe())
  15113. with LoggingContext(&quot;request-1&quot;):
  15114. await do_something()
  15115. </code></pre>
  15116. </td>
  15117. <td width="50%">
  15118. </td>
  15119. </tr>
  15120. </table>
  15121. <div style="break-before: page; page-break-before: always;"></div><h1 id="log-contexts"><a class="header" href="#log-contexts">Log Contexts</a></h1>
  15122. <p>To help track the processing of individual requests, synapse uses a
  15123. '<code>log context</code>' to track which request it is handling at any given
  15124. moment. This is done via a thread-local variable; a <code>logging.Filter</code> is
  15125. then used to fish the information back out of the thread-local variable
  15126. and add it to each log record.</p>
  15127. <p>Logcontexts are also used for CPU and database accounting, so that we
  15128. can track which requests were responsible for high CPU use or database
  15129. activity.</p>
  15130. <p>The <code>synapse.logging.context</code> module provides facilities for managing
  15131. the current log context (as well as providing the <code>LoggingContextFilter</code>
  15132. class).</p>
  15133. <p>Asynchronous functions make the whole thing complicated, so this document describes
  15134. how it all works, and how to write code which follows the rules.</p>
  15135. <p>In this document, &quot;awaitable&quot; refers to any object which can be <code>await</code>ed. In the context of
  15136. Synapse, that normally means either a coroutine or a Twisted
  15137. <a href="https://twistedmatrix.com/documents/current/api/twisted.internet.defer.Deferred.html"><code>Deferred</code></a>.</p>
  15138. <h2 id="logcontexts-without-asynchronous-code"><a class="header" href="#logcontexts-without-asynchronous-code">Logcontexts without asynchronous code</a></h2>
  15139. <p>In the absence of any asynchronous voodoo, things are simple enough. As with
  15140. any code of this nature, the rule is that our function should leave
  15141. things as it found them:</p>
  15142. <pre><code class="language-python">from synapse.logging import context # omitted from future snippets
  15143. def handle_request(request_id):
  15144. request_context = context.LoggingContext()
  15145. calling_context = context.set_current_context(request_context)
  15146. try:
  15147. request_context.request = request_id
  15148. do_request_handling()
  15149. logger.debug(&quot;finished&quot;)
  15150. finally:
  15151. context.set_current_context(calling_context)
  15152. def do_request_handling():
  15153. logger.debug(&quot;phew&quot;) # this will be logged against request_id
  15154. </code></pre>
  15155. <p>LoggingContext implements the context management methods, so the above
  15156. can be written much more succinctly as:</p>
  15157. <pre><code class="language-python">def handle_request(request_id):
  15158. with context.LoggingContext() as request_context:
  15159. request_context.request = request_id
  15160. do_request_handling()
  15161. logger.debug(&quot;finished&quot;)
  15162. def do_request_handling():
  15163. logger.debug(&quot;phew&quot;)
  15164. </code></pre>
  15165. <h2 id="using-logcontexts-with-awaitables"><a class="header" href="#using-logcontexts-with-awaitables">Using logcontexts with awaitables</a></h2>
  15166. <p>Awaitables break the linear flow of code so that there is no longer a single entry point
  15167. where we should set the logcontext and a single exit point where we should remove it.</p>
  15168. <p>Consider the example above, where <code>do_request_handling</code> needs to do some
  15169. blocking operation, and returns an awaitable:</p>
  15170. <pre><code class="language-python">async def handle_request(request_id):
  15171. with context.LoggingContext() as request_context:
  15172. request_context.request = request_id
  15173. await do_request_handling()
  15174. logger.debug(&quot;finished&quot;)
  15175. </code></pre>
  15176. <p>In the above flow:</p>
  15177. <ul>
  15178. <li>The logcontext is set</li>
  15179. <li><code>do_request_handling</code> is called, and returns an awaitable</li>
  15180. <li><code>handle_request</code> awaits the awaitable</li>
  15181. <li>Execution of <code>handle_request</code> is suspended</li>
  15182. </ul>
  15183. <p>So we have stopped processing the request (and will probably go on to
  15184. start processing the next), without clearing the logcontext.</p>
  15185. <p>To circumvent this problem, synapse code assumes that, wherever you have
  15186. an awaitable, you will want to <code>await</code> it. To that end, whereever
  15187. functions return awaitables, we adopt the following conventions:</p>
  15188. <p><strong>Rules for functions returning awaitables:</strong></p>
  15189. <blockquote>
  15190. <ul>
  15191. <li>If the awaitable is already complete, the function returns with the
  15192. same logcontext it started with.</li>
  15193. <li>If the awaitable is incomplete, the function clears the logcontext
  15194. before returning; when the awaitable completes, it restores the
  15195. logcontext before running any callbacks.</li>
  15196. </ul>
  15197. </blockquote>
  15198. <p>That sounds complicated, but actually it means a lot of code (including
  15199. the example above) &quot;just works&quot;. There are two cases:</p>
  15200. <ul>
  15201. <li>
  15202. <p>If <code>do_request_handling</code> returns a completed awaitable, then the
  15203. logcontext will still be in place. In this case, execution will
  15204. continue immediately after the <code>await</code>; the &quot;finished&quot; line will
  15205. be logged against the right context, and the <code>with</code> block restores
  15206. the original context before we return to the caller.</p>
  15207. </li>
  15208. <li>
  15209. <p>If the returned awaitable is incomplete, <code>do_request_handling</code> clears
  15210. the logcontext before returning. The logcontext is therefore clear
  15211. when <code>handle_request</code> <code>await</code>s the awaitable.</p>
  15212. <p>Once <code>do_request_handling</code>'s awaitable completes, it will reinstate
  15213. the logcontext, before running the second half of <code>handle_request</code>,
  15214. so again the &quot;finished&quot; line will be logged against the right context,
  15215. and the <code>with</code> block restores the original context.</p>
  15216. </li>
  15217. </ul>
  15218. <p>As an aside, it's worth noting that <code>handle_request</code> follows our rules</p>
  15219. <ul>
  15220. <li>though that only matters if the caller has its own logcontext which it
  15221. cares about.</li>
  15222. </ul>
  15223. <p>The following sections describe pitfalls and helpful patterns when
  15224. implementing these rules.</p>
  15225. <h2 id="always-await-your-awaitables"><a class="header" href="#always-await-your-awaitables">Always await your awaitables</a></h2>
  15226. <p>Whenever you get an awaitable back from a function, you should <code>await</code> on
  15227. it as soon as possible. Do not pass go; do not do any logging; do not
  15228. call any other functions.</p>
  15229. <pre><code class="language-python">async def fun():
  15230. logger.debug(&quot;starting&quot;)
  15231. await do_some_stuff() # just like this
  15232. coro = more_stuff()
  15233. result = await coro # also fine, of course
  15234. return result
  15235. </code></pre>
  15236. <p>Provided this pattern is followed all the way back up to the callchain
  15237. to where the logcontext was set, this will make things work out ok:
  15238. provided <code>do_some_stuff</code> and <code>more_stuff</code> follow the rules above, then
  15239. so will <code>fun</code>.</p>
  15240. <p>It's all too easy to forget to <code>await</code>: for instance if we forgot that
  15241. <code>do_some_stuff</code> returned an awaitable, we might plough on regardless. This
  15242. leads to a mess; it will probably work itself out eventually, but not
  15243. before a load of stuff has been logged against the wrong context.
  15244. (Normally, other things will break, more obviously, if you forget to
  15245. <code>await</code>, so this tends not to be a major problem in practice.)</p>
  15246. <p>Of course sometimes you need to do something a bit fancier with your
  15247. awaitable - not all code follows the linear A-then-B-then-C pattern.
  15248. Notes on implementing more complex patterns are in later sections.</p>
  15249. <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>
  15250. <p>Most of the time, an awaitable comes from another synapse function.
  15251. Sometimes, though, we need to make up a new awaitable, or we get an awaitable
  15252. back from external code. We need to make it follow our rules.</p>
  15253. <p>The easy way to do it is by using <code>context.make_deferred_yieldable</code>. Suppose we want to implement
  15254. <code>sleep</code>, which returns a deferred which will run its callbacks after a
  15255. given number of seconds. That might look like:</p>
  15256. <pre><code class="language-python"># not a logcontext-rules-compliant function
  15257. def get_sleep_deferred(seconds):
  15258. d = defer.Deferred()
  15259. reactor.callLater(seconds, d.callback, None)
  15260. return d
  15261. </code></pre>
  15262. <p>That doesn't follow the rules, but we can fix it by calling it through
  15263. <code>context.make_deferred_yieldable</code>:</p>
  15264. <pre><code class="language-python">async def sleep(seconds):
  15265. return await context.make_deferred_yieldable(get_sleep_deferred(seconds))
  15266. </code></pre>
  15267. <h2 id="fire-and-forget"><a class="header" href="#fire-and-forget">Fire-and-forget</a></h2>
  15268. <p>Sometimes you want to fire off a chain of execution, but not wait for
  15269. its result. That might look a bit like this:</p>
  15270. <pre><code class="language-python">async def do_request_handling():
  15271. await foreground_operation()
  15272. # *don't* do this
  15273. background_operation()
  15274. logger.debug(&quot;Request handling complete&quot;)
  15275. async def background_operation():
  15276. await first_background_step()
  15277. logger.debug(&quot;Completed first step&quot;)
  15278. await second_background_step()
  15279. logger.debug(&quot;Completed second step&quot;)
  15280. </code></pre>
  15281. <p>The above code does a couple of steps in the background after
  15282. <code>do_request_handling</code> has finished. The log lines are still logged
  15283. against the <code>request_context</code> logcontext, which may or may not be
  15284. desirable. There are two big problems with the above, however. The first
  15285. problem is that, if <code>background_operation</code> returns an incomplete
  15286. awaitable, it will expect its caller to <code>await</code> immediately, so will have
  15287. cleared the logcontext. In this example, that means that 'Request
  15288. handling complete' will be logged without any context.</p>
  15289. <p>The second problem, which is potentially even worse, is that when the
  15290. awaitable returned by <code>background_operation</code> completes, it will restore
  15291. the original logcontext. There is nothing waiting on that awaitable, so
  15292. the logcontext will leak into the reactor and possibly get attached to
  15293. some arbitrary future operation.</p>
  15294. <p>There are two potential solutions to this.</p>
  15295. <p>One option is to surround the call to <code>background_operation</code> with a
  15296. <code>PreserveLoggingContext</code> call. That will reset the logcontext before
  15297. starting <code>background_operation</code> (so the context restored when the
  15298. deferred completes will be the empty logcontext), and will restore the
  15299. current logcontext before continuing the foreground process:</p>
  15300. <pre><code class="language-python">async def do_request_handling():
  15301. await foreground_operation()
  15302. # start background_operation off in the empty logcontext, to
  15303. # avoid leaking the current context into the reactor.
  15304. with PreserveLoggingContext():
  15305. background_operation()
  15306. # this will now be logged against the request context
  15307. logger.debug(&quot;Request handling complete&quot;)
  15308. </code></pre>
  15309. <p>Obviously that option means that the operations done in
  15310. <code>background_operation</code> would be not be logged against a logcontext
  15311. (though that might be fixed by setting a different logcontext via a
  15312. <code>with LoggingContext(...)</code> in <code>background_operation</code>).</p>
  15313. <p>The second option is to use <code>context.run_in_background</code>, which wraps a
  15314. function so that it doesn't reset the logcontext even when it returns
  15315. an incomplete awaitable, and adds a callback to the returned awaitable to
  15316. reset the logcontext. In other words, it turns a function that follows
  15317. the Synapse rules about logcontexts and awaitables into one which behaves
  15318. more like an external function --- the opposite operation to that
  15319. described in the previous section. It can be used like this:</p>
  15320. <pre><code class="language-python">async def do_request_handling():
  15321. await foreground_operation()
  15322. context.run_in_background(background_operation)
  15323. # this will now be logged against the request context
  15324. logger.debug(&quot;Request handling complete&quot;)
  15325. </code></pre>
  15326. <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>
  15327. <p>A typical example of this is where we want to collect together two or
  15328. more awaitables via <code>defer.gatherResults</code>:</p>
  15329. <pre><code class="language-python">a1 = operation1()
  15330. a2 = operation2()
  15331. a3 = defer.gatherResults([a1, a2])
  15332. </code></pre>
  15333. <p>This is really a variation of the fire-and-forget problem above, in that
  15334. we are firing off <code>a1</code> and <code>a2</code> without awaiting on them. The difference
  15335. is that we now have third-party code attached to their callbacks. Anyway
  15336. either technique given in the <a href="log_contexts.html#fire-and-forget">Fire-and-forget</a>
  15337. section will work.</p>
  15338. <p>Of course, the new awaitable returned by <code>gather</code> needs to be
  15339. wrapped in order to make it follow the logcontext rules before we can
  15340. 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
  15341. follow the
  15342. rules</a>.</p>
  15343. <p>So, option one: reset the logcontext before starting the operations to
  15344. be gathered:</p>
  15345. <pre><code class="language-python">async def do_request_handling():
  15346. with PreserveLoggingContext():
  15347. a1 = operation1()
  15348. a2 = operation2()
  15349. result = await defer.gatherResults([a1, a2])
  15350. </code></pre>
  15351. <p>In this case particularly, though, option two, of using
  15352. <code>context.run_in_background</code> almost certainly makes more sense, so that
  15353. <code>operation1</code> and <code>operation2</code> are both logged against the original
  15354. logcontext. This looks like:</p>
  15355. <pre><code class="language-python">async def do_request_handling():
  15356. a1 = context.run_in_background(operation1)
  15357. a2 = context.run_in_background(operation2)
  15358. result = await make_deferred_yieldable(defer.gatherResults([a1, a2]))
  15359. </code></pre>
  15360. <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>
  15361. <p>It turns out that our logcontext rules do not play nicely with awaitable
  15362. chains which get orphaned and garbage-collected.</p>
  15363. <p>Imagine we have some code that looks like this:</p>
  15364. <pre><code class="language-python">listener_queue = []
  15365. def on_something_interesting():
  15366. for d in listener_queue:
  15367. d.callback(&quot;foo&quot;)
  15368. async def await_something_interesting():
  15369. new_awaitable = defer.Deferred()
  15370. listener_queue.append(new_awaitable)
  15371. with PreserveLoggingContext():
  15372. await new_awaitable
  15373. </code></pre>
  15374. <p>Obviously, the idea here is that we have a bunch of things which are
  15375. waiting for an event. (It's just an example of the problem here, but a
  15376. relatively common one.)</p>
  15377. <p>Now let's imagine two further things happen. First of all, whatever was
  15378. waiting for the interesting thing goes away. (Perhaps the request times
  15379. out, or something <em>even more</em> interesting happens.)</p>
  15380. <p>Secondly, let's suppose that we decide that the interesting thing is
  15381. never going to happen, and we reset the listener queue:</p>
  15382. <pre><code class="language-python">def reset_listener_queue():
  15383. listener_queue.clear()
  15384. </code></pre>
  15385. <p>So, both ends of the awaitable chain have now dropped their references,
  15386. and the awaitable chain is now orphaned, and will be garbage-collected at
  15387. some point. Note that <code>await_something_interesting</code> is a coroutine,
  15388. which Python implements as a generator function. When Python
  15389. garbage-collects generator functions, it gives them a chance to
  15390. clean up by making the <code>await</code> (or <code>yield</code>) raise a <code>GeneratorExit</code>
  15391. exception. In our case, that means that the <code>__exit__</code> handler of
  15392. <code>PreserveLoggingContext</code> will carefully restore the request context, but
  15393. there is now nothing waiting for its return, so the request context is
  15394. never cleared.</p>
  15395. <p>To reiterate, this problem only arises when <em>both</em> ends of a awaitable
  15396. chain are dropped. Dropping the the reference to an awaitable you're
  15397. supposed to be awaiting is bad practice, so this doesn't
  15398. actually happen too much. Unfortunately, when it does happen, it will
  15399. lead to leaked logcontexts which are incredibly hard to track down.</p>
  15400. <div style="break-before: page; page-break-before: always;"></div><h1 id="replication-architecture"><a class="header" href="#replication-architecture">Replication Architecture</a></h1>
  15401. <h2 id="motivation"><a class="header" href="#motivation">Motivation</a></h2>
  15402. <p>We'd like to be able to split some of the work that synapse does into
  15403. multiple python processes. In theory multiple synapse processes could
  15404. share a single postgresql database and we'd scale up by running more
  15405. synapse processes. However much of synapse assumes that only one process
  15406. is interacting with the database, both for assigning unique identifiers
  15407. when inserting into tables, notifying components about new updates, and
  15408. for invalidating its caches.</p>
  15409. <p>So running multiple copies of the current code isn't an option. One way
  15410. to run multiple processes would be to have a single writer process and
  15411. multiple reader processes connected to the same database. In order to do
  15412. this we'd need a way for the reader process to invalidate its in-memory
  15413. caches when an update happens on the writer. One way to do this is for
  15414. the writer to present an append-only log of updates which the readers
  15415. can consume to invalidate their caches and to push updates to listening
  15416. clients or pushers.</p>
  15417. <p>Synapse already stores much of its data as an append-only log so that it
  15418. can correctly respond to <code>/sync</code> requests so the amount of code changes
  15419. needed to expose the append-only log to the readers should be fairly
  15420. minimal.</p>
  15421. <h2 id="architecture"><a class="header" href="#architecture">Architecture</a></h2>
  15422. <h3 id="the-replication-protocol"><a class="header" href="#the-replication-protocol">The Replication Protocol</a></h3>
  15423. <p>See <a href="tcp_replication.html">the TCP replication documentation</a>.</p>
  15424. <h3 id="the-slaved-datastore"><a class="header" href="#the-slaved-datastore">The Slaved DataStore</a></h3>
  15425. <p>There are read-only version of the synapse storage layer in
  15426. <code>synapse/replication/slave/storage</code> that use the response of the
  15427. replication API to invalidate their caches.</p>
  15428. <h3 id="the-tcp-replication-module"><a class="header" href="#the-tcp-replication-module">The TCP Replication Module</a></h3>
  15429. <p>Information about how the tcp replication module is structured, including how
  15430. the classes interact, can be found in
  15431. <code>synapse/replication/tcp/__init__.py</code></p>
  15432. <div style="break-before: page; page-break-before: always;"></div><h1 id="tcp-replication"><a class="header" href="#tcp-replication">TCP Replication</a></h1>
  15433. <h2 id="motivation-1"><a class="header" href="#motivation-1">Motivation</a></h2>
  15434. <p>Previously the workers used an HTTP long poll mechanism to get updates
  15435. from the master, which had the problem of causing a lot of duplicate
  15436. work on the server. This TCP protocol replaces those APIs with the aim
  15437. of increased efficiency.</p>
  15438. <h2 id="overview-3"><a class="header" href="#overview-3">Overview</a></h2>
  15439. <p>The protocol is based on fire and forget, line based commands. An
  15440. example flow would be (where '&gt;' indicates master to worker and
  15441. '&lt;' worker to master flows):</p>
  15442. <pre><code>&gt; SERVER example.com
  15443. &lt; REPLICATE
  15444. &gt; POSITION events master 53 53
  15445. &gt; RDATA events master 54 [&quot;$foo1:bar.com&quot;, ...]
  15446. &gt; RDATA events master 55 [&quot;$foo4:bar.com&quot;, ...]
  15447. </code></pre>
  15448. <p>The example shows the server accepting a new connection and sending its identity
  15449. with the <code>SERVER</code> command, followed by the client server to respond with the
  15450. position of all streams. The server then periodically sends <code>RDATA</code> commands
  15451. which have the format <code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row&gt;</code>, where
  15452. the format of <code>&lt;row&gt;</code> is defined by the individual streams. The
  15453. <code>&lt;instance_name&gt;</code> is the name of the Synapse process that generated the data
  15454. (usually &quot;master&quot;).</p>
  15455. <p>Error reporting happens by either the client or server sending an ERROR
  15456. command, and usually the connection will be closed.</p>
  15457. <p>Since the protocol is a simple line based, its possible to manually
  15458. connect to the server using a tool like netcat. A few things should be
  15459. noted when manually using the protocol:</p>
  15460. <ul>
  15461. <li>The federation stream is only available if federation sending has
  15462. been disabled on the main process.</li>
  15463. <li>The server will only time connections out that have sent a <code>PING</code>
  15464. command. If a ping is sent then the connection will be closed if no
  15465. further commands are receieved within 15s. Both the client and
  15466. server protocol implementations will send an initial PING on
  15467. connection and ensure at least one command every 5s is sent (not
  15468. necessarily <code>PING</code>).</li>
  15469. <li><code>RDATA</code> commands <em>usually</em> include a numeric token, however if the
  15470. stream has multiple rows to replicate per token the server will send
  15471. multiple <code>RDATA</code> commands, with all but the last having a token of
  15472. <code>batch</code>. See the documentation on <code>commands.RdataCommand</code> for
  15473. further details.</li>
  15474. </ul>
  15475. <h2 id="architecture-1"><a class="header" href="#architecture-1">Architecture</a></h2>
  15476. <p>The basic structure of the protocol is line based, where the initial
  15477. word of each line specifies the command. The rest of the line is parsed
  15478. based on the command. For example, the RDATA command is defined as:</p>
  15479. <pre><code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row_json&gt;
  15480. </code></pre>
  15481. <p>(Note that &lt;row_json&gt; may contains spaces, but cannot contain
  15482. newlines.)</p>
  15483. <p>Blank lines are ignored.</p>
  15484. <h3 id="keep-alives"><a class="header" href="#keep-alives">Keep alives</a></h3>
  15485. <p>Both sides are expected to send at least one command every 5s or so, and
  15486. should send a <code>PING</code> command if necessary. If either side do not receive
  15487. a command within e.g. 15s then the connection should be closed.</p>
  15488. <p>Because the server may be connected to manually using e.g. netcat, the
  15489. timeouts aren't enabled until an initial <code>PING</code> command is seen. Both
  15490. the client and server implementations below send a <code>PING</code> command
  15491. immediately on connection to ensure the timeouts are enabled.</p>
  15492. <p>This ensures that both sides can quickly realize if the tcp connection
  15493. has gone and handle the situation appropriately.</p>
  15494. <h3 id="start-up"><a class="header" href="#start-up">Start up</a></h3>
  15495. <p>When a new connection is made, the server:</p>
  15496. <ul>
  15497. <li>Sends a <code>SERVER</code> command, which includes the identity of the server,
  15498. allowing the client to detect if its connected to the expected
  15499. server</li>
  15500. <li>Sends a <code>PING</code> command as above, to enable the client to time out
  15501. connections promptly.</li>
  15502. </ul>
  15503. <p>The client:</p>
  15504. <ul>
  15505. <li>Sends a <code>NAME</code> command, allowing the server to associate a human
  15506. friendly name with the connection. This is optional.</li>
  15507. <li>Sends a <code>PING</code> as above</li>
  15508. <li>Sends a <code>REPLICATE</code> to get the current position of all streams.</li>
  15509. <li>On receipt of a <code>SERVER</code> command, checks that the server name
  15510. matches the expected server name.</li>
  15511. </ul>
  15512. <h3 id="error-handling"><a class="header" href="#error-handling">Error handling</a></h3>
  15513. <p>If either side detects an error it can send an <code>ERROR</code> command and close
  15514. the connection.</p>
  15515. <p>If the client side loses the connection to the server it should
  15516. reconnect, following the steps above.</p>
  15517. <h3 id="congestion"><a class="header" href="#congestion">Congestion</a></h3>
  15518. <p>If the server sends messages faster than the client can consume them the
  15519. server will first buffer a (fairly large) number of commands and then
  15520. disconnect the client. This ensures that we don't queue up an unbounded
  15521. number of commands in memory and gives us a potential oppurtunity to
  15522. squawk loudly. When/if the client recovers it can reconnect to the
  15523. server and ask for missed messages.</p>
  15524. <h3 id="reliability"><a class="header" href="#reliability">Reliability</a></h3>
  15525. <p>In general the replication stream should be considered an unreliable
  15526. transport since e.g. commands are not resent if the connection
  15527. disappears.</p>
  15528. <p>The exception to that are the replication streams, i.e. RDATA commands,
  15529. since these include tokens which can be used to restart the stream on
  15530. connection errors.</p>
  15531. <p>The client should keep track of the token in the last RDATA command
  15532. received for each stream so that on reconneciton it can start streaming
  15533. from the correct place. Note: not all RDATA have valid tokens due to
  15534. batching. See <code>RdataCommand</code> for more details.</p>
  15535. <h3 id="example-5"><a class="header" href="#example-5">Example</a></h3>
  15536. <p>An example iteraction is shown below. Each line is prefixed with '&gt;'
  15537. or '&lt;' to indicate which side is sending, these are <em>not</em> included on
  15538. the wire:</p>
  15539. <pre><code>* connection established *
  15540. &gt; SERVER localhost:8823
  15541. &gt; PING 1490197665618
  15542. &lt; NAME synapse.app.appservice
  15543. &lt; PING 1490197665618
  15544. &lt; REPLICATE
  15545. &gt; POSITION events master 1 1
  15546. &gt; POSITION backfill master 1 1
  15547. &gt; POSITION caches master 1 1
  15548. &gt; RDATA caches master 2 [&quot;get_user_by_id&quot;,[&quot;@01register-user:localhost:8823&quot;],1490197670513]
  15549. &gt; RDATA events master 14 [&quot;$149019767112vOHxz:localhost:8823&quot;,
  15550. &quot;!AFDCvgApUmpdfVjIXm:localhost:8823&quot;,&quot;m.room.guest_access&quot;,&quot;&quot;,null]
  15551. &lt; PING 1490197675618
  15552. &gt; ERROR server stopping
  15553. * connection closed by server *
  15554. </code></pre>
  15555. <p>The <code>POSITION</code> command sent by the server is used to set the clients
  15556. position without needing to send data with the <code>RDATA</code> command.</p>
  15557. <p>An example of a batched set of <code>RDATA</code> is:</p>
  15558. <pre><code>&gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test:localhost:8823&quot;],1490197670513]
  15559. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test2:localhost:8823&quot;],1490197670513]
  15560. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test3:localhost:8823&quot;],1490197670513]
  15561. &gt; RDATA caches master 54 [&quot;get_user_by_id&quot;,[&quot;@test4:localhost:8823&quot;],1490197670513]
  15562. </code></pre>
  15563. <p>In this case the client shouldn't advance their caches token until it
  15564. sees the the last <code>RDATA</code>.</p>
  15565. <h3 id="list-of-commands"><a class="header" href="#list-of-commands">List of commands</a></h3>
  15566. <p>The list of valid commands, with which side can send it: server (S) or
  15567. client (C):</p>
  15568. <h4 id="server-s"><a class="header" href="#server-s">SERVER (S)</a></h4>
  15569. <p>Sent at the start to identify which server the client is talking to</p>
  15570. <h4 id="rdata-s"><a class="header" href="#rdata-s">RDATA (S)</a></h4>
  15571. <p>A single update in a stream</p>
  15572. <h4 id="position-s"><a class="header" href="#position-s">POSITION (S)</a></h4>
  15573. <p>On receipt of a POSITION command clients should check if they have missed any
  15574. updates, and if so then fetch them out of band. Sent in response to a
  15575. REPLICATE command (but can happen at any time).</p>
  15576. <p>The POSITION command includes the source of the stream. Currently all streams
  15577. are written by a single process (usually &quot;master&quot;). If fetching missing
  15578. updates via HTTP API, rather than via the DB, then processes should make the
  15579. request to the appropriate process.</p>
  15580. <p>Two positions are included, the &quot;new&quot; position and the last position sent respectively.
  15581. This allows servers to tell instances that the positions have advanced but no
  15582. data has been written, without clients needlessly checking to see if they
  15583. have missed any updates.</p>
  15584. <h4 id="error-s-c"><a class="header" href="#error-s-c">ERROR (S, C)</a></h4>
  15585. <p>There was an error</p>
  15586. <h4 id="ping-s-c"><a class="header" href="#ping-s-c">PING (S, C)</a></h4>
  15587. <p>Sent periodically to ensure the connection is still alive</p>
  15588. <h4 id="name-c"><a class="header" href="#name-c">NAME (C)</a></h4>
  15589. <p>Sent at the start by client to inform the server who they are</p>
  15590. <h4 id="replicate-c"><a class="header" href="#replicate-c">REPLICATE (C)</a></h4>
  15591. <p>Asks the server for the current position of all streams.</p>
  15592. <h4 id="user_sync-c"><a class="header" href="#user_sync-c">USER_SYNC (C)</a></h4>
  15593. <p>A user has started or stopped syncing on this process.</p>
  15594. <h4 id="clear_user_sync-c"><a class="header" href="#clear_user_sync-c">CLEAR_USER_SYNC (C)</a></h4>
  15595. <p>The server should clear all associated user sync data from the worker.</p>
  15596. <p>This is used when a worker is shutting down.</p>
  15597. <h4 id="federation_ack-c"><a class="header" href="#federation_ack-c">FEDERATION_ACK (C)</a></h4>
  15598. <p>Acknowledge receipt of some federation data</p>
  15599. <h3 id="remote_server_up-s-c"><a class="header" href="#remote_server_up-s-c">REMOTE_SERVER_UP (S, C)</a></h3>
  15600. <p>Inform other processes that a remote server may have come back online.</p>
  15601. <p>See <code>synapse/replication/tcp/commands.py</code> for a detailed description and
  15602. the format of each command.</p>
  15603. <h3 id="cache-invalidation-stream"><a class="header" href="#cache-invalidation-stream">Cache Invalidation Stream</a></h3>
  15604. <p>The cache invalidation stream is used to inform workers when they need
  15605. to invalidate any of their caches in the data store. This is done by
  15606. streaming all cache invalidations done on master down to the workers,
  15607. assuming that any caches on the workers also exist on the master.</p>
  15608. <p>Each individual cache invalidation results in a row being sent down
  15609. replication, which includes the cache name (the name of the function)
  15610. and they key to invalidate. For example:</p>
  15611. <pre><code>&gt; RDATA caches master 550953771 [&quot;get_user_by_id&quot;, [&quot;@bob:example.com&quot;], 1550574873251]
  15612. </code></pre>
  15613. <p>Alternatively, an entire cache can be invalidated by sending down a <code>null</code>
  15614. instead of the key. For example:</p>
  15615. <pre><code>&gt; RDATA caches master 550953772 [&quot;get_user_by_id&quot;, null, 1550574873252]
  15616. </code></pre>
  15617. <p>However, there are times when a number of caches need to be invalidated
  15618. at the same time with the same key. To reduce traffic we batch those
  15619. invalidations into a single poke by defining a special cache name that
  15620. workers understand to mean to expand to invalidate the correct caches.</p>
  15621. <p>Currently the special cache names are declared in
  15622. <code>synapse/storage/_base.py</code> and are:</p>
  15623. <ol>
  15624. <li><code>cs_cache_fake</code> ─ invalidates caches that depend on the current
  15625. state</li>
  15626. </ol>
  15627. <div style="break-before: page; page-break-before: always;"></div><h1 id="internal-documentation"><a class="header" href="#internal-documentation">Internal Documentation</a></h1>
  15628. <p>This section covers implementation documentation for various parts of Synapse.</p>
  15629. <p>If a developer is planning to make a change to a feature of Synapse, it can be useful for
  15630. general documentation of how that feature is implemented to be available. This saves the
  15631. developer time in place of needing to understand how the feature works by reading the
  15632. code.</p>
  15633. <p>Documentation that would be more useful for the perspective of a system administrator,
  15634. rather than a developer who's intending to change to code, should instead be placed
  15635. under the Usage section of the documentation.</p>
  15636. <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>
  15637. <p>https://fujifish.github.io/samling/samling.html (https://github.com/fujifish/samling) is a great resource for being able to tinker with the
  15638. SAML options within Synapse without needing to deploy and configure a complicated software stack.</p>
  15639. <p>To make Synapse (and therefore Element) use it:</p>
  15640. <ol>
  15641. <li>Use the samling.html URL above or deploy your own and visit the IdP Metadata tab.</li>
  15642. <li>Copy the XML to your clipboard.</li>
  15643. <li>On your Synapse server, create a new file <code>samling.xml</code> next to your <code>homeserver.yaml</code> with
  15644. the XML from step 2 as the contents.</li>
  15645. <li>Edit your <code>homeserver.yaml</code> to include:
  15646. <pre><code class="language-yaml">saml2_config:
  15647. sp_config:
  15648. allow_unknown_attributes: true # Works around a bug with AVA Hashes: https://github.com/IdentityPython/pysaml2/issues/388
  15649. metadata:
  15650. local: [&quot;samling.xml&quot;]
  15651. </code></pre>
  15652. </li>
  15653. <li>Ensure that your <code>homeserver.yaml</code> has a setting for <code>public_baseurl</code>:
  15654. <pre><code class="language-yaml">public_baseurl: http://localhost:8080/
  15655. </code></pre>
  15656. </li>
  15657. <li>Run <code>apt-get install xmlsec1</code> and <code>pip install --upgrade --force 'pysaml2&gt;=4.5.0'</code> to ensure
  15658. the dependencies are installed and ready to go.</li>
  15659. <li>Restart Synapse.</li>
  15660. </ol>
  15661. <p>Then in Element:</p>
  15662. <ol>
  15663. <li>Visit the login page and point Element towards your homeserver using the <code>public_baseurl</code> above.</li>
  15664. <li>Click the Single Sign-On button.</li>
  15665. <li>On the samling page, enter a Name Identifier and add a SAML Attribute for <code>uid=your_localpart</code>.
  15666. The response must also be signed.</li>
  15667. <li>Click &quot;Next&quot;.</li>
  15668. <li>Click &quot;Post Response&quot; (change nothing).</li>
  15669. <li>You should be logged in.</li>
  15670. </ol>
  15671. <p>If you try and repeat this process, you may be automatically logged in using the information you
  15672. gave previously. To fix this, open your developer console (<code>F12</code> or <code>Ctrl+Shift+I</code>) while on the
  15673. samling page and clear the site data. In Chrome, this will be a button on the Application tab.</p>
  15674. <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>
  15675. <p>The <a href="https://github.com/jbittel/django-mama-cas">django-mama-cas</a> project is an
  15676. easy to run CAS implementation built on top of Django.</p>
  15677. <h2 id="prerequisites"><a class="header" href="#prerequisites">Prerequisites</a></h2>
  15678. <ol>
  15679. <li>Create a new virtualenv: <code>python3 -m venv &lt;your virtualenv&gt;</code></li>
  15680. <li>Activate your virtualenv: <code>source /path/to/your/virtualenv/bin/activate</code></li>
  15681. <li>Install Django and django-mama-cas:
  15682. <pre><code class="language-sh">python -m pip install &quot;django&lt;3&quot; &quot;django-mama-cas==2.4.0&quot;
  15683. </code></pre>
  15684. </li>
  15685. <li>Create a Django project in the current directory:
  15686. <pre><code class="language-sh">django-admin startproject cas_test .
  15687. </code></pre>
  15688. </li>
  15689. <li>Follow the <a href="https://django-mama-cas.readthedocs.io/en/latest/installation.html#configuring">install directions</a> for django-mama-cas</li>
  15690. <li>Setup the SQLite database: <code>python manage.py migrate</code></li>
  15691. <li>Create a user:
  15692. <pre><code class="language-sh">python manage.py createsuperuser
  15693. </code></pre>
  15694. <ol>
  15695. <li>Use whatever you want as the username and password.</li>
  15696. <li>Leave the other fields blank.</li>
  15697. </ol>
  15698. </li>
  15699. <li>Use the built-in Django test server to serve the CAS endpoints on port 8000:
  15700. <pre><code class="language-sh">python manage.py runserver
  15701. </code></pre>
  15702. </li>
  15703. </ol>
  15704. <p>You should now have a Django project configured to serve CAS authentication with
  15705. a single user created.</p>
  15706. <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>
  15707. <ol>
  15708. <li>Modify your <code>homeserver.yaml</code> to enable CAS and point it to your locally
  15709. running Django test server:
  15710. <pre><code class="language-yaml">cas_config:
  15711. enabled: true
  15712. server_url: &quot;http://localhost:8000&quot;
  15713. service_url: &quot;http://localhost:8081&quot;
  15714. #displayname_attribute: name
  15715. #required_attributes:
  15716. # name: value
  15717. </code></pre>
  15718. </li>
  15719. <li>Restart Synapse.</li>
  15720. </ol>
  15721. <p>Note that the above configuration assumes the homeserver is running on port 8081
  15722. and that the CAS server is on port 8000, both on localhost.</p>
  15723. <h2 id="testing-the-configuration"><a class="header" href="#testing-the-configuration">Testing the configuration</a></h2>
  15724. <p>Then in Element:</p>
  15725. <ol>
  15726. <li>Visit the login page with a Element pointing at your homeserver.</li>
  15727. <li>Click the Single Sign-On button.</li>
  15728. <li>Login using the credentials created with <code>createsuperuser</code>.</li>
  15729. <li>You should be logged in.</li>
  15730. </ol>
  15731. <p>If you want to repeat this process you'll need to manually logout first:</p>
  15732. <ol>
  15733. <li>http://localhost:8000/admin/</li>
  15734. <li>Click &quot;logout&quot; in the top right.</li>
  15735. </ol>
  15736. <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>
  15737. <h2 id="edges"><a class="header" href="#edges">Edges</a></h2>
  15738. <p>The word &quot;edge&quot; comes from graph theory lingo. An edge is just a connection
  15739. between two events. In Synapse, we connect events by specifying their
  15740. <code>prev_events</code>. A subsequent event points back at a previous event.</p>
  15741. <pre><code>A (oldest) &lt;---- B &lt;---- C (most recent)
  15742. </code></pre>
  15743. <h2 id="depth-and-stream-ordering"><a class="header" href="#depth-and-stream-ordering">Depth and stream ordering</a></h2>
  15744. <p>Events are normally sorted by <code>(topological_ordering, stream_ordering)</code> where
  15745. <code>topological_ordering</code> is just <code>depth</code>. In other words, we first sort by <code>depth</code>
  15746. and then tie-break based on <code>stream_ordering</code>. <code>depth</code> is incremented as new
  15747. messages are added to the DAG. Normally, <code>stream_ordering</code> is an auto
  15748. incrementing integer, but backfilled events start with <code>stream_ordering=-1</code> and decrement.</p>
  15749. <hr />
  15750. <ul>
  15751. <li><code>/sync</code> returns things in the order they arrive at the server (<code>stream_ordering</code>).</li>
  15752. <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>
  15753. </ul>
  15754. <p>The general idea is that, if you're following a room in real-time (i.e.
  15755. <code>/sync</code>), you probably want to see the messages as they arrive at your server,
  15756. rather than skipping any that arrived late; whereas if you're looking at a
  15757. historical section of timeline (i.e. <code>/messages</code>), you want to see the best
  15758. representation of the state of the room as others were seeing it at the time.</p>
  15759. <h2 id="outliers"><a class="header" href="#outliers">Outliers</a></h2>
  15760. <p>We mark an event as an <code>outlier</code> when we haven't figured out the state for the
  15761. room at that point in the DAG yet. They are &quot;floating&quot; events that we haven't
  15762. yet correlated to the DAG.</p>
  15763. <p>Outliers typically arise when we fetch the auth chain or state for a given
  15764. event. When that happens, we just grab the events in the state/auth chain,
  15765. without calculating the state at those events, or backfilling their
  15766. <code>prev_events</code>. Since we don't have the state at any events fetched in that
  15767. way, we mark them as outliers.</p>
  15768. <p>So, typically, we won't have the <code>prev_events</code> of an <code>outlier</code> in the database,
  15769. (though it's entirely possible that we <em>might</em> have them for some other
  15770. reason). Other things that make outliers different from regular events:</p>
  15771. <ul>
  15772. <li>
  15773. <p>We don't have state for them, so there should be no entry in
  15774. <code>event_to_state_groups</code> for an outlier. (In practice this isn't always
  15775. the case, though I'm not sure why: see https://github.com/matrix-org/synapse/issues/12201).</p>
  15776. </li>
  15777. <li>
  15778. <p>We don't record entries for them in the <code>event_edges</code>,
  15779. <code>event_forward_extremeties</code> or <code>event_backward_extremities</code> tables.</p>
  15780. </li>
  15781. </ul>
  15782. <p>Since outliers are not tied into the DAG, they do not normally form part of the
  15783. timeline sent down to clients via <code>/sync</code> or <code>/messages</code>; however there is an
  15784. exception:</p>
  15785. <h3 id="out-of-band-membership-events"><a class="header" href="#out-of-band-membership-events">Out-of-band membership events</a></h3>
  15786. <p>A special case of outlier events are some membership events for federated rooms
  15787. that we aren't full members of. For example:</p>
  15788. <ul>
  15789. <li>invites received over federation, before we join the room</li>
  15790. <li><em>rejections</em> for said invites</li>
  15791. <li>knock events for rooms that we would like to join but have not yet joined.</li>
  15792. </ul>
  15793. <p>In all the above cases, we don't have the state for the room, which is why they
  15794. are treated as outliers. They are a bit special though, in that they are
  15795. proactively sent to clients via <code>/sync</code>.</p>
  15796. <h2 id="forward-extremity"><a class="header" href="#forward-extremity">Forward extremity</a></h2>
  15797. <p>Most-recent-in-time events in the DAG which are not referenced by any other
  15798. events' <code>prev_events</code> yet. (In this definition, outliers, rejected events, and
  15799. soft-failed events don't count.)</p>
  15800. <p>The forward extremities of a room (or at least, a subset of them, if there are
  15801. more than ten) are used as the <code>prev_events</code> when the next event is sent.</p>
  15802. <p>The &quot;current state&quot; of a room (ie: the state which would be used if we
  15803. generated a new event) is, therefore, the resolution of the room states
  15804. at each of the forward extremities.</p>
  15805. <h2 id="backward-extremity"><a class="header" href="#backward-extremity">Backward extremity</a></h2>
  15806. <p>The current marker of where we have backfilled up to and will generally be the
  15807. <code>prev_events</code> of the oldest-in-time events we have in the DAG. This gives a starting point when
  15808. backfilling history.</p>
  15809. <p>Note that, unlike forward extremities, we typically don't have any backward
  15810. extremity events themselves in the database - or, if we do, they will be &quot;outliers&quot; (see
  15811. above). Either way, we don't expect to have the room state at a backward extremity.</p>
  15812. <p>When we persist a non-outlier event, if it was previously a backward extremity,
  15813. we clear it as a backward extremity and set all of its <code>prev_events</code> as the new
  15814. backward extremities if they aren't already persisted as non-outliers. This
  15815. therefore keeps the backward extremities up-to-date.</p>
  15816. <h2 id="state-groups"><a class="header" href="#state-groups">State groups</a></h2>
  15817. <p>For every non-outlier event we need to know the state at that event. Instead of
  15818. storing the full state for each event in the DB (i.e. a <code>event_id -&gt; state</code>
  15819. mapping), which is <em>very</em> space inefficient when state doesn't change, we
  15820. instead assign each different set of state a &quot;state group&quot; and then have
  15821. mappings of <code>event_id -&gt; state_group</code> and <code>state_group -&gt; state</code>.</p>
  15822. <h3 id="stage-group-edges"><a class="header" href="#stage-group-edges">Stage group edges</a></h3>
  15823. <p>TODO: <code>state_group_edges</code> is a further optimization...
  15824. notes from @Azrenbeth, https://pastebin.com/seUGVGeT</p>
  15825. <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>
  15826. <p>The auth chain difference algorithm is used by V2 state resolution, where a
  15827. naive implementation can be a significant source of CPU and DB usage.</p>
  15828. <h3 id="definitions"><a class="header" href="#definitions">Definitions</a></h3>
  15829. <p>A <em>state set</em> is a set of state events; e.g. the input of a state resolution
  15830. algorithm is a collection of state sets.</p>
  15831. <p>The <em>auth chain</em> of a set of events are all the events' auth events and <em>their</em>
  15832. auth events, recursively (i.e. the events reachable by walking the graph induced
  15833. by an event's auth events links).</p>
  15834. <p>The <em>auth chain difference</em> of a collection of state sets is the union minus the
  15835. intersection of the sets of auth chains corresponding to the state sets, i.e an
  15836. event is in the auth chain difference if it is reachable by walking the auth
  15837. event graph from at least one of the state sets but not from <em>all</em> of the state
  15838. sets.</p>
  15839. <h2 id="breadth-first-walk-algorithm"><a class="header" href="#breadth-first-walk-algorithm">Breadth First Walk Algorithm</a></h2>
  15840. <p>A way of calculating the auth chain difference without calculating the full auth
  15841. chains for each state set is to do a parallel breadth first walk (ordered by
  15842. depth) of each state set's auth chain. By tracking which events are reachable
  15843. from each state set we can finish early if every pending event is reachable from
  15844. every state set.</p>
  15845. <p>This can work well for state sets that have a small auth chain difference, but
  15846. can be very inefficient for larger differences. However, this algorithm is still
  15847. used if we don't have a chain cover index for the room (e.g. because we're in
  15848. the process of indexing it).</p>
  15849. <h2 id="chain-cover-index"><a class="header" href="#chain-cover-index">Chain Cover Index</a></h2>
  15850. <p>Synapse computes auth chain differences by pre-computing a &quot;chain cover&quot; index
  15851. for the auth chain in a room, allowing efficient reachability queries like &quot;is
  15852. event A in the auth chain of event B&quot;. This is done by assigning every event a
  15853. <em>chain ID</em> and <em>sequence number</em> (e.g. <code>(5,3)</code>), and having a map of <em>links</em>
  15854. between chains (e.g. <code>(5,3) -&gt; (2,4)</code>) such that A is reachable by B (i.e. <code>A</code>
  15855. is in the auth chain of <code>B</code>) if and only if either:</p>
  15856. <ol>
  15857. <li>A and B have the same chain ID and <code>A</code>'s sequence number is less than <code>B</code>'s
  15858. sequence number; or</li>
  15859. <li>there is a link <code>L</code> between <code>B</code>'s chain ID and <code>A</code>'s chain ID such that
  15860. <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>
  15861. </ol>
  15862. <p>There are actually two potential implementations, one where we store links from
  15863. each chain to every other reachable chain (the transitive closure of the links
  15864. graph), and one where we remove redundant links (the transitive reduction of the
  15865. links graph) e.g. if we have chains <code>C3 -&gt; C2 -&gt; C1</code> then the link <code>C3 -&gt; C1</code>
  15866. would not be stored. Synapse uses the former implementations so that it doesn't
  15867. need to recurse to test reachability between chains.</p>
  15868. <h3 id="example-6"><a class="header" href="#example-6">Example</a></h3>
  15869. <p>An example auth graph would look like the following, where chains have been
  15870. formed based on type/state_key and are denoted by colour and are labelled with
  15871. <code>(chain ID, sequence number)</code>. Links are denoted by the arrows (links in grey
  15872. are those that would be remove in the second implementation described above).</p>
  15873. <p><img src="auth_chain_diff.dot.png" alt="Example" /></p>
  15874. <p>Note that we don't include all links between events and their auth events, as
  15875. most of those links would be redundant. For example, all events point to the
  15876. create event, but each chain only needs the one link from it's base to the
  15877. create event.</p>
  15878. <h2 id="using-the-index"><a class="header" href="#using-the-index">Using the Index</a></h2>
  15879. <p>This index can be used to calculate the auth chain difference of the state sets
  15880. by looking at the chain ID and sequence numbers reachable from each state set:</p>
  15881. <ol>
  15882. <li>For every state set lookup the chain ID/sequence numbers of each state event</li>
  15883. <li>Use the index to find all chains and the maximum sequence number reachable
  15884. from each state set.</li>
  15885. <li>The auth chain difference is then all events in each chain that have sequence
  15886. numbers between the maximum sequence number reachable from <em>any</em> state set and
  15887. the minimum reachable by <em>all</em> state sets (if any).</li>
  15888. </ol>
  15889. <p>Note that steps 2 is effectively calculating the auth chain for each state set
  15890. (in terms of chain IDs and sequence numbers), and step 3 is calculating the
  15891. difference between the union and intersection of the auth chains.</p>
  15892. <h3 id="worked-example"><a class="header" href="#worked-example">Worked Example</a></h3>
  15893. <p>For example, given the above graph, we can calculate the difference between
  15894. state sets consisting of:</p>
  15895. <ol>
  15896. <li><code>S1</code>: Alice's invite <code>(4,1)</code> and Bob's second join <code>(2,2)</code>; and</li>
  15897. <li><code>S2</code>: Alice's second join <code>(4,3)</code> and Bob's first join <code>(2,1)</code>.</li>
  15898. </ol>
  15899. <p>Using the index we see that the following auth chains are reachable from each
  15900. state set:</p>
  15901. <ol>
  15902. <li><code>S1</code>: <code>(1,1)</code>, <code>(2,2)</code>, <code>(3,1)</code> &amp; <code>(4,1)</code></li>
  15903. <li><code>S2</code>: <code>(1,1)</code>, <code>(2,1)</code>, <code>(3,2)</code> &amp; <code>(4,3)</code></li>
  15904. </ol>
  15905. <p>And so, for each the ranges that are in the auth chain difference:</p>
  15906. <ol>
  15907. <li>Chain 1: None, (since everything can reach the create event).</li>
  15908. <li>Chain 2: The range <code>(1, 2]</code> (i.e. just <code>2</code>), as <code>1</code> is reachable by all state
  15909. sets and the maximum reachable is <code>2</code> (corresponding to Bob's second join).</li>
  15910. <li>Chain 3: Similarly the range <code>(1, 2]</code> (corresponding to the second power
  15911. level).</li>
  15912. <li>Chain 4: The range <code>(1, 3]</code> (corresponding to both of Alice's joins).</li>
  15913. </ol>
  15914. <p>So the final result is: Bob's second join <code>(2,2)</code>, the second power level
  15915. <code>(3,2)</code> and both of Alice's joins <code>(4,2)</code> &amp; <code>(4,3)</code>.</p>
  15916. <div style="break-before: page; page-break-before: always;"></div><h1 id="media-repository"><a class="header" href="#media-repository">Media Repository</a></h1>
  15917. <p><em>Synapse implementation-specific details for the media repository</em></p>
  15918. <p>The media repository</p>
  15919. <ul>
  15920. <li>stores avatars, attachments and their thumbnails for media uploaded by local
  15921. users.</li>
  15922. <li>caches avatars, attachments and their thumbnails for media uploaded by remote
  15923. users.</li>
  15924. <li>caches resources and thumbnails used for
  15925. <a href="development/url_previews.html">URL previews</a>.</li>
  15926. </ul>
  15927. <p>All media in Matrix can be identified by a unique
  15928. <a href="https://spec.matrix.org/latest/client-server-api/#matrix-content-mxc-uris">MXC URI</a>,
  15929. consisting of a server name and media ID:</p>
  15930. <pre><code>mxc://&lt;server-name&gt;/&lt;media-id&gt;
  15931. </code></pre>
  15932. <h2 id="local-media"><a class="header" href="#local-media">Local Media</a></h2>
  15933. <p>Synapse generates 24 character media IDs for content uploaded by local users.
  15934. These media IDs consist of upper and lowercase letters and are case-sensitive.
  15935. Other homeserver implementations may generate media IDs differently.</p>
  15936. <p>Local media is recorded in the <code>local_media_repository</code> table, which includes
  15937. metadata such as MIME types, upload times and file sizes.
  15938. Note that this table is shared by the URL cache, which has a different media ID
  15939. scheme.</p>
  15940. <h3 id="paths"><a class="header" href="#paths">Paths</a></h3>
  15941. <p>A file with media ID <code>aabbcccccccccccccccccccc</code> and its <code>128x96</code> <code>image/jpeg</code>
  15942. thumbnail, created by scaling, would be stored at:</p>
  15943. <pre><code>local_content/aa/bb/cccccccccccccccccccc
  15944. local_thumbnails/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  15945. </code></pre>
  15946. <h2 id="remote-media"><a class="header" href="#remote-media">Remote Media</a></h2>
  15947. <p>When media from a remote homeserver is requested from Synapse, it is assigned
  15948. a local <code>filesystem_id</code>, with the same format as locally-generated media IDs,
  15949. as described above.</p>
  15950. <p>A record of remote media is stored in the <code>remote_media_cache</code> table, which
  15951. can be used to map remote MXC URIs (server names and media IDs) to local
  15952. <code>filesystem_id</code>s.</p>
  15953. <h3 id="paths-1"><a class="header" href="#paths-1">Paths</a></h3>
  15954. <p>A file from <code>matrix.org</code> with <code>filesystem_id</code> <code>aabbcccccccccccccccccccc</code> and its
  15955. <code>128x96</code> <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  15956. <pre><code>remote_content/matrix.org/aa/bb/cccccccccccccccccccc
  15957. remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  15958. </code></pre>
  15959. <p>Older thumbnails may omit the thumbnailing method:</p>
  15960. <pre><code>remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg
  15961. </code></pre>
  15962. <p>Note that <code>remote_thumbnail/</code> does not have an <code>s</code>.</p>
  15963. <h2 id="url-previews-2"><a class="header" href="#url-previews-2">URL Previews</a></h2>
  15964. <p>See <a href="development/url_previews.html">URL Previews</a> for documentation on the URL preview
  15965. process.</p>
  15966. <p>When generating previews for URLs, Synapse may download and cache various
  15967. resources, including images. These resources are assigned temporary media IDs
  15968. of the form <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code>, where <code>yyyy-mm-dd</code> is the current
  15969. date and <code>aaaaaaaaaaaaaaaa</code> is a random sequence of 16 case-sensitive letters.</p>
  15970. <p>The metadata for these cached resources is stored in the
  15971. <code>local_media_repository</code> and <code>local_media_repository_url_cache</code> tables.</p>
  15972. <p>Resources for URL previews are deleted after a few days.</p>
  15973. <h3 id="paths-2"><a class="header" href="#paths-2">Paths</a></h3>
  15974. <p>The file with media ID <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code> and its <code>128x96</code>
  15975. <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  15976. <pre><code>url_cache/yyyy-mm-dd/aaaaaaaaaaaaaaaa
  15977. url_cache_thumbnails/yyyy-mm-dd/aaaaaaaaaaaaaaaa/128-96-image-jpeg-scale
  15978. </code></pre>
  15979. <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>
  15980. <p>Synapse maintains room and user statistics in various tables. These can be used
  15981. for administrative purposes but are also used when generating the public room
  15982. directory.</p>
  15983. <h1 id="synapse-developer-documentation"><a class="header" href="#synapse-developer-documentation">Synapse Developer Documentation</a></h1>
  15984. <h2 id="high-level-concepts"><a class="header" href="#high-level-concepts">High-Level Concepts</a></h2>
  15985. <h3 id="definitions-1"><a class="header" href="#definitions-1">Definitions</a></h3>
  15986. <ul>
  15987. <li><strong>subject</strong>: Something we are tracking stats about – currently a room or user.</li>
  15988. <li><strong>current row</strong>: An entry for a subject in the appropriate current statistics
  15989. table. Each subject can have only one.</li>
  15990. </ul>
  15991. <h3 id="overview-4"><a class="header" href="#overview-4">Overview</a></h3>
  15992. <p>Stats correspond to the present values. Current rows contain the most up-to-date
  15993. statistics for a room. Each subject can only have one entry.</p>
  15994. <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>
  15995. <p>Synapse has a number of platform dependencies, including Python and PostgreSQL.
  15996. This document outlines the policy towards which versions we support, and when we
  15997. drop support for versions in the future.</p>
  15998. <h2 id="policy"><a class="header" href="#policy">Policy</a></h2>
  15999. <p>Synapse follows the upstream support life cycles for Python and PostgreSQL,
  16000. i.e. when a version reaches End of Life Synapse will withdraw support for that
  16001. version in future releases.</p>
  16002. <p>Details on the upstream support life cycles for Python and PostgreSQL are
  16003. documented at <a href="https://endoflife.date/python">https://endoflife.date/python</a> and
  16004. <a href="https://endoflife.date/postgresql">https://endoflife.date/postgresql</a>.</p>
  16005. <h2 id="context"><a class="header" href="#context">Context</a></h2>
  16006. <p>It is important for system admins to have a clear understanding of the platform
  16007. requirements of Synapse and its deprecation policies so that they can
  16008. effectively plan upgrading their infrastructure ahead of time. This is
  16009. especially important in contexts where upgrading the infrastructure requires
  16010. auditing and approval from a security team, or where otherwise upgrading is a
  16011. long process.</p>
  16012. <p>By following the upstream support life cycles Synapse can ensure that its
  16013. dependencies continue to get security patches, while not requiring system admins
  16014. to constantly update their platform dependencies to the latest versions.</p>
  16015. <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>
  16016. <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>
  16017. <ul>
  16018. <li><strong>Platform</strong>: 2x1GHz armhf 2GiB ram <a href="https://wiki.debian.org/CheapServerBoxHardware">Single-board computers</a>, SSD, postgres.</li>
  16019. </ul>
  16020. <h3 id="presence-1"><a class="header" href="#presence-1">Presence</a></h3>
  16021. <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>
  16022. <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>
  16023. <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>
  16024. <h3 id="joining"><a class="header" href="#joining">Joining</a></h3>
  16025. <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>
  16026. <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>
  16027. <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>
  16028. <h3 id="sessions"><a class="header" href="#sessions">Sessions</a></h3>
  16029. <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>
  16030. <h3 id="recommended-configuration"><a class="header" href="#recommended-configuration">Recommended configuration</a></h3>
  16031. <p>Put the below in a new file at /etc/matrix-synapse/conf.d/sbc.yaml to override the defaults in homeserver.yaml.</p>
  16032. <pre><code># Disable presence tracking, which is currently fairly resource intensive
  16033. # More info: https://github.com/matrix-org/synapse/issues/9478
  16034. use_presence: false
  16035. # Set a small complexity limit, preventing users from joining large rooms
  16036. # which may be resource-intensive to remain a part of.
  16037. #
  16038. # Note that this will not prevent users from joining smaller rooms that
  16039. # eventually become complex.
  16040. limit_remote_rooms:
  16041. enabled: true
  16042. complexity: 3.0
  16043. # Database configuration
  16044. database:
  16045. # Use postgres for the best performance
  16046. name: psycopg2
  16047. args:
  16048. user: matrix-synapse
  16049. # Generate a long, secure password using a password manager
  16050. password: hunter2
  16051. database: matrix-synapse
  16052. host: localhost
  16053. </code></pre>
  16054. <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>
  16055. <pre><code>admin@homeserver:~$ zgrep '/client/r0/join/' /var/log/matrix-synapse/homeserver.log* | awk '{print $18, $25}' | sort --human-numeric-sort
  16056. 29.922sec/-0.002sec /_matrix/client/r0/join/%23debian-fasttrack%3Apoddery.com
  16057. 182.088sec/0.003sec /_matrix/client/r0/join/%23decentralizedweb-general%3Amatrix.org
  16058. 911.625sec/-570.847sec /_matrix/client/r0/join/%23synapse%3Amatrix.org
  16059. 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'
  16060. canonical_alias | joined_members | current_state_events
  16061. -------------------------------+----------------+----------------------
  16062. #_oftc_#debian:matrix.org | 871 | 52355
  16063. #matrix:matrix.org | 6379 | 10684
  16064. #irc:matrix.org | 461 | 3751
  16065. #decentralizedweb-general:matrix.org | 997 | 1509
  16066. #whatsapp:maunium.net | 554 | 854
  16067. </code></pre>
  16068. </main>
  16069. <nav class="nav-wrapper" aria-label="Page navigation">
  16070. <!-- Mobile navigation buttons -->
  16071. <div style="clear: both"></div>
  16072. </nav>
  16073. </div>
  16074. </div>
  16075. <nav class="nav-wide-wrapper" aria-label="Page navigation">
  16076. </nav>
  16077. </div>
  16078. <script type="text/javascript">
  16079. window.playground_copyable = true;
  16080. </script>
  16081. <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
  16082. <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
  16083. <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
  16084. <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
  16085. <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
  16086. <script src="book.js" type="text/javascript" charset="utf-8"></script>
  16087. <!-- Custom JS scripts -->
  16088. <script type="text/javascript" src="docs/website_files/table-of-contents.js"></script>
  16089. <script type="text/javascript" src="docs/website_files/version-picker.js"></script>
  16090. <script type="text/javascript" src="docs/website_files/version.js"></script>
  16091. <script type="text/javascript">
  16092. window.addEventListener('load', function() {
  16093. window.setTimeout(window.print, 100);
  16094. });
  16095. </script>
  16096. </body>
  16097. </html>