print.html 787 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690
  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/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/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/delete_group.html">Delete Group</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 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 "><div>Synapse Architecture</div></li><li><ol class="section"><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>maintainence</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/index.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. supportor 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>We do not recommend using the packages from the default Debian <code>buster</code>
  294. repository at this time, as they are old and suffer from known security
  295. vulnerabilities. You can install the latest version of Synapse from
  296. <a href="setup/installation.html#matrixorg-packages">our repository</a> or from <code>buster-backports</code>. Please
  297. see the <a href="https://backports.debian.org/Instructions/">Debian documentation</a>
  298. for information on how to use backports.</p>
  299. <p>If you are using Debian <code>sid</code> or testing, Synapse is available in the default
  300. repositories and it should be possible to install it simply with:</p>
  301. <pre><code class="language-sh">sudo apt install matrix-synapse
  302. </code></pre>
  303. <h5 id="downstream-ubuntu-packages"><a class="header" href="#downstream-ubuntu-packages">Downstream Ubuntu packages</a></h5>
  304. <p>We do not recommend using the packages in the default Ubuntu repository
  305. at this time, as they are old and suffer from known security vulnerabilities.
  306. The latest version of Synapse can be installed from <a href="setup/installation.html#matrixorg-packages">our repository</a>.</p>
  307. <h4 id="fedora"><a class="header" href="#fedora">Fedora</a></h4>
  308. <p>Synapse is in the Fedora repositories as <code>matrix-synapse</code>:</p>
  309. <pre><code class="language-sh">sudo dnf install matrix-synapse
  310. </code></pre>
  311. <p>Oleg Girko provides Fedora RPMs at
  312. <a href="https://obs.infoserver.lv/project/monitor/matrix-synapse">https://obs.infoserver.lv/project/monitor/matrix-synapse</a></p>
  313. <h4 id="opensuse"><a class="header" href="#opensuse">OpenSUSE</a></h4>
  314. <p>Synapse is in the OpenSUSE repositories as <code>matrix-synapse</code>:</p>
  315. <pre><code class="language-sh">sudo zypper install matrix-synapse
  316. </code></pre>
  317. <h4 id="suse-linux-enterprise-server"><a class="header" href="#suse-linux-enterprise-server">SUSE Linux Enterprise Server</a></h4>
  318. <p>Unofficial package are built for SLES 15 in the openSUSE:Backports:SLE-15 repository at
  319. <a href="https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/">https://download.opensuse.org/repositories/openSUSE:/Backports:/SLE-15/standard/</a></p>
  320. <h4 id="archlinux"><a class="header" href="#archlinux">ArchLinux</a></h4>
  321. <p>The quickest way to get up and running with ArchLinux is probably with the community package
  322. <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
  323. the necessary dependencies.</p>
  324. <p>pip may be outdated (6.0.7-1 and needs to be upgraded to 6.0.8-1 ):</p>
  325. <pre><code class="language-sh">sudo pip install --upgrade pip
  326. </code></pre>
  327. <p>If you encounter an error with lib bcrypt causing an Wrong ELF Class:
  328. ELFCLASS32 (x64 Systems), you may need to reinstall py-bcrypt to correctly
  329. compile it under the right architecture. (This should not be needed if
  330. installing under virtualenv):</p>
  331. <pre><code class="language-sh">sudo pip uninstall py-bcrypt
  332. sudo pip install py-bcrypt
  333. </code></pre>
  334. <h4 id="void-linux"><a class="header" href="#void-linux">Void Linux</a></h4>
  335. <p>Synapse can be found in the void repositories as 'synapse':</p>
  336. <pre><code class="language-sh">xbps-install -Su
  337. xbps-install -S synapse
  338. </code></pre>
  339. <h4 id="freebsd"><a class="header" href="#freebsd">FreeBSD</a></h4>
  340. <p>Synapse can be installed via FreeBSD Ports or Packages contributed by Brendan Molloy from:</p>
  341. <ul>
  342. <li>Ports: <code>cd /usr/ports/net-im/py-matrix-synapse &amp;&amp; make install clean</code></li>
  343. <li>Packages: <code>pkg install py38-matrix-synapse</code></li>
  344. </ul>
  345. <h4 id="openbsd"><a class="header" href="#openbsd">OpenBSD</a></h4>
  346. <p>As of OpenBSD 6.7 Synapse is available as a pre-compiled binary. The filesystem
  347. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  348. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  349. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  350. <p>Installing Synapse:</p>
  351. <pre><code class="language-sh">doas pkg_add synapse
  352. </code></pre>
  353. <h4 id="nixos"><a class="header" href="#nixos">NixOS</a></h4>
  354. <p>Robin Lambertz has packaged Synapse for NixOS at:
  355. <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>
  356. <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>
  357. <p>It's also possible to install Synapse as a Python module from PyPI.</p>
  358. <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>
  359. <p>System requirements:</p>
  360. <ul>
  361. <li>POSIX-compliant system (tested on Linux &amp; OS X)</li>
  362. <li>Python 3.7 or later, up to Python 3.10.</li>
  363. <li>At least 1GB of free RAM if you want to join large public rooms like #matrix:matrix.org</li>
  364. </ul>
  365. <p>To install the Synapse homeserver run:</p>
  366. <pre><code class="language-sh">mkdir -p ~/synapse
  367. virtualenv -p python3 ~/synapse/env
  368. source ~/synapse/env/bin/activate
  369. pip install --upgrade pip
  370. pip install --upgrade setuptools
  371. pip install matrix-synapse
  372. </code></pre>
  373. <p>This will download Synapse from <a href="https://pypi.org/project/matrix-synapse">PyPI</a>
  374. and install it, along with the python libraries it uses, into a virtual environment
  375. under <code>~/synapse/env</code>. Feel free to pick a different directory if you
  376. prefer.</p>
  377. <p>This Synapse installation can then be later upgraded by using pip again with the
  378. update flag:</p>
  379. <pre><code class="language-sh">source ~/synapse/env/bin/activate
  380. pip install -U matrix-synapse
  381. </code></pre>
  382. <p>Before you can start Synapse, you will need to generate a configuration
  383. file. To do this, run (in your virtualenv, as before):</p>
  384. <pre><code class="language-sh">cd ~/synapse
  385. python -m synapse.app.homeserver \
  386. --server-name my.domain.name \
  387. --config-path homeserver.yaml \
  388. --generate-config \
  389. --report-stats=[yes|no]
  390. </code></pre>
  391. <p>... substituting an appropriate value for <code>--server-name</code>.</p>
  392. <p>This command will generate you a config file that you can then customise, but it will
  393. also generate a set of keys for you. These keys will allow your homeserver to
  394. identify itself to other homeserver, so don't lose or delete them. It would be
  395. wise to back them up somewhere safe. (If, for whatever reason, you do need to
  396. change your homeserver's keys, you may find that other homeserver have the
  397. old key cached. If you update the signing key, you should change the name of the
  398. key in the <code>&lt;server name&gt;.signing.key</code> file (the second word) to something
  399. 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>
  400. <p>To actually run your new homeserver, pick a working directory for Synapse to
  401. run (e.g. <code>~/synapse</code>), and:</p>
  402. <pre><code class="language-sh">cd ~/synapse
  403. source env/bin/activate
  404. synctl start
  405. </code></pre>
  406. <h4 id="platform-specific-prerequisites"><a class="header" href="#platform-specific-prerequisites">Platform-specific prerequisites</a></h4>
  407. <p>Synapse is written in Python but some of the libraries it uses are written in
  408. C. So before we can install Synapse itself we need a working C compiler and the
  409. header files for Python C extensions.</p>
  410. <h5 id="debianubunturaspbian"><a class="header" href="#debianubunturaspbian">Debian/Ubuntu/Raspbian</a></h5>
  411. <p>Installing prerequisites on Ubuntu or Debian:</p>
  412. <pre><code class="language-sh">sudo apt install build-essential python3-dev libffi-dev \
  413. python3-pip python3-setuptools sqlite3 \
  414. libssl-dev virtualenv libjpeg-dev libxslt1-dev
  415. </code></pre>
  416. <h5 id="archlinux-1"><a class="header" href="#archlinux-1">ArchLinux</a></h5>
  417. <p>Installing prerequisites on ArchLinux:</p>
  418. <pre><code class="language-sh">sudo pacman -S base-devel python python-pip \
  419. python-setuptools python-virtualenv sqlite3
  420. </code></pre>
  421. <h5 id="centosfedora"><a class="header" href="#centosfedora">CentOS/Fedora</a></h5>
  422. <p>Installing prerequisites on CentOS or Fedora Linux:</p>
  423. <pre><code class="language-sh">sudo dnf install libtiff-devel libjpeg-devel libzip-devel freetype-devel \
  424. libwebp-devel libxml2-devel libxslt-devel libpq-devel \
  425. python3-virtualenv libffi-devel openssl-devel python3-devel
  426. sudo dnf groupinstall &quot;Development Tools&quot;
  427. </code></pre>
  428. <h5 id="macos"><a class="header" href="#macos">macOS</a></h5>
  429. <p>Installing prerequisites on macOS:</p>
  430. <p>You may need to install the latest Xcode developer tools:</p>
  431. <pre><code class="language-sh">xcode-select --install
  432. </code></pre>
  433. <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>
  434. <pre><code class="language-sh"> brew install jpeg
  435. </code></pre>
  436. <p>On macOS Catalina (10.15) you may need to explicitly install OpenSSL
  437. via brew and inform <code>pip</code> about it so that <code>psycopg2</code> builds:</p>
  438. <pre><code class="language-sh">brew install openssl@1.1
  439. export LDFLAGS=&quot;-L/usr/local/opt/openssl/lib&quot;
  440. export CPPFLAGS=&quot;-I/usr/local/opt/openssl/include&quot;
  441. </code></pre>
  442. <h5 id="opensuse-1"><a class="header" href="#opensuse-1">OpenSUSE</a></h5>
  443. <p>Installing prerequisites on openSUSE:</p>
  444. <pre><code class="language-sh">sudo zypper in -t pattern devel_basis
  445. sudo zypper in python-pip python-setuptools sqlite3 python-virtualenv \
  446. python-devel libffi-devel libopenssl-devel libjpeg62-devel
  447. </code></pre>
  448. <h5 id="openbsd-1"><a class="header" href="#openbsd-1">OpenBSD</a></h5>
  449. <p>A port of Synapse is available under <code>net/synapse</code>. The filesystem
  450. underlying the homeserver directory (defaults to <code>/var/synapse</code>) has to be
  451. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>), so creating a separate filesystem
  452. and mounting it to <code>/var/synapse</code> should be taken into consideration.</p>
  453. <p>To be able to build Synapse's dependency on python the <code>WRKOBJDIR</code>
  454. (cf. <code>bsd.port.mk(5)</code>) for building python, too, needs to be on a filesystem
  455. mounted with <code>wxallowed</code> (cf. <code>mount(8)</code>).</p>
  456. <p>Creating a <code>WRKOBJDIR</code> for building python under <code>/usr/local</code> (which on a
  457. default OpenBSD installation is mounted with <code>wxallowed</code>):</p>
  458. <pre><code class="language-sh">doas mkdir /usr/local/pobj_wxallowed
  459. </code></pre>
  460. <p>Assuming <code>PORTS_PRIVSEP=Yes</code> (cf. <code>bsd.port.mk(5)</code>) and <code>SUDO=doas</code> are
  461. configured in <code>/etc/mk.conf</code>:</p>
  462. <pre><code class="language-sh">doas chown _pbuild:_pbuild /usr/local/pobj_wxallowed
  463. </code></pre>
  464. <p>Setting the <code>WRKOBJDIR</code> for building python:</p>
  465. <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
  466. </code></pre>
  467. <p>Building Synapse:</p>
  468. <pre><code class="language-sh">cd /usr/ports/net/synapse
  469. make install
  470. </code></pre>
  471. <h5 id="windows"><a class="header" href="#windows">Windows</a></h5>
  472. <p>Running Synapse natively on Windows is not officially supported.</p>
  473. <p>If you wish to run or develop Synapse on Windows, the Windows Subsystem for
  474. Linux provides a Linux environment which is capable of using the Debian, Fedora,
  475. or source installation methods. More information about WSL can be found at
  476. <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
  477. <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
  478. Windows Server.</p>
  479. <h2 id="setting-up-synapse"><a class="header" href="#setting-up-synapse">Setting up Synapse</a></h2>
  480. <p>Once you have installed synapse as above, you will need to configure it.</p>
  481. <h3 id="using-postgresql"><a class="header" href="#using-postgresql">Using PostgreSQL</a></h3>
  482. <p>By default Synapse uses an <a href="https://sqlite.org/">SQLite</a> database and in doing so trades
  483. performance for convenience. Almost all installations should opt to use <a href="https://www.postgresql.org">PostgreSQL</a>
  484. instead. Advantages include:</p>
  485. <ul>
  486. <li>significant performance improvements due to the superior threading and
  487. caching model, smarter query optimiser</li>
  488. <li>allowing the DB to be run on separate hardware</li>
  489. </ul>
  490. <p>For information on how to install and use PostgreSQL in Synapse, please see
  491. <a href="setup/../postgres.html">Using Postgres</a></p>
  492. <p>SQLite is only acceptable for testing purposes. SQLite should not be used in
  493. a production server. Synapse will perform poorly when using
  494. SQLite, especially when participating in large rooms.</p>
  495. <h3 id="tls-certificates"><a class="header" href="#tls-certificates">TLS certificates</a></h3>
  496. <p>The default configuration exposes a single HTTP port on the local
  497. interface: <code>http://localhost:8008</code>. It is suitable for local testing,
  498. but for any practical use, you will need Synapse's APIs to be served
  499. over HTTPS.</p>
  500. <p>The recommended way to do so is to set up a reverse proxy on port
  501. <code>8448</code>. You can find documentation on doing so in
  502. <a href="setup/../reverse_proxy.html">the reverse proxy documentation</a>.</p>
  503. <p>Alternatively, you can configure Synapse to expose an HTTPS port. To do
  504. so, you will need to edit <code>homeserver.yaml</code>, as follows:</p>
  505. <ul>
  506. <li>First, under the <code>listeners</code> section, uncomment the configuration for the
  507. TLS-enabled listener. (Remove the hash sign (<code>#</code>) at the start of
  508. each line). The relevant lines are like this:</li>
  509. </ul>
  510. <pre><code class="language-yaml"> - port: 8448
  511. type: http
  512. tls: true
  513. resources:
  514. - names: [client, federation]
  515. </code></pre>
  516. <ul>
  517. <li>
  518. <p>You will also need to uncomment the <code>tls_certificate_path</code> and
  519. <code>tls_private_key_path</code> lines under the <code>TLS</code> section. You will need to manage
  520. provisioning of these certificates yourself.</p>
  521. <p>If you are using your own certificate, be sure to use a <code>.pem</code> file that
  522. includes the full certificate chain including any intermediate certificates
  523. (for instance, if using certbot, use <code>fullchain.pem</code> as your certificate, not
  524. <code>cert.pem</code>).</p>
  525. </li>
  526. </ul>
  527. <p>For a more detailed guide to configuring your server for federation, see
  528. <a href="setup/../federate.html">Federation</a>.</p>
  529. <h3 id="client-well-known-uri"><a class="header" href="#client-well-known-uri">Client Well-Known URI</a></h3>
  530. <p>Setting up the client Well-Known URI is optional but if you set it up, it will
  531. allow users to enter their full username (e.g. <code>@user:&lt;server_name&gt;</code>) into clients
  532. which support well-known lookup to automatically configure the homeserver and
  533. identity server URLs. This is useful so that users don't have to memorize or think
  534. about the actual homeserver URL you are using.</p>
  535. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/client</code> should return JSON in
  536. the following format.</p>
  537. <pre><code class="language-json">{
  538. &quot;m.homeserver&quot;: {
  539. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  540. }
  541. }
  542. </code></pre>
  543. <p>It can optionally contain identity server information as well.</p>
  544. <pre><code class="language-json">{
  545. &quot;m.homeserver&quot;: {
  546. &quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;
  547. },
  548. &quot;m.identity_server&quot;: {
  549. &quot;base_url&quot;: &quot;https://&lt;identity.example.com&gt;&quot;
  550. }
  551. }
  552. </code></pre>
  553. <p>To work in browser based clients, the file must be served with the appropriate
  554. Cross-Origin Resource Sharing (CORS) headers. A recommended value would be
  555. <code>Access-Control-Allow-Origin: *</code> which would allow all browser based clients to
  556. view it.</p>
  557. <p>In nginx this would be something like:</p>
  558. <pre><code class="language-nginx">location /.well-known/matrix/client {
  559. return 200 '{&quot;m.homeserver&quot;: {&quot;base_url&quot;: &quot;https://&lt;matrix.example.com&gt;&quot;}}';
  560. default_type application/json;
  561. add_header Access-Control-Allow-Origin *;
  562. }
  563. </code></pre>
  564. <p>You should also ensure the <code>public_baseurl</code> option in <code>homeserver.yaml</code> is set
  565. correctly. <code>public_baseurl</code> should be set to the URL that clients will use to
  566. connect to your server. This is the same URL you put for the <code>m.homeserver</code>
  567. <code>base_url</code> above.</p>
  568. <pre><code class="language-yaml">public_baseurl: &quot;https://&lt;matrix.example.com&gt;&quot;
  569. </code></pre>
  570. <h3 id="email"><a class="header" href="#email">Email</a></h3>
  571. <p>It is desirable for Synapse to have the capability to send email. This allows
  572. Synapse to send password reset emails, send verifications when an email address
  573. is added to a user's account, and send email notifications to users when they
  574. receive new messages.</p>
  575. <p>To configure an SMTP server for Synapse, modify the configuration section
  576. headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>, <code>smtp_port</code>
  577. and <code>notif_from</code> fields filled out. You may also need to set <code>smtp_user</code>,
  578. <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  579. <p>If email is not configured, password reset, registration and notifications via
  580. email will be disabled.</p>
  581. <h3 id="registering-a-user"><a class="header" href="#registering-a-user">Registering a user</a></h3>
  582. <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>
  583. <p>Alternatively, you can do so from the command line. This can be done as follows:</p>
  584. <ol>
  585. <li>If synapse was installed via pip, activate the virtualenv as follows (if Synapse was
  586. installed via a prebuilt package, <code>register_new_matrix_user</code> should already be
  587. on the search path):
  588. <pre><code class="language-sh">cd ~/synapse
  589. source env/bin/activate
  590. synctl start # if not already running
  591. </code></pre>
  592. </li>
  593. <li>Run the following command:
  594. <pre><code class="language-sh">register_new_matrix_user -c homeserver.yaml http://localhost:8008
  595. </code></pre>
  596. </li>
  597. </ol>
  598. <p>This will prompt you to add details for the new user, and will then connect to
  599. the running Synapse to create the new user. For example:</p>
  600. <pre><code>New user localpart: erikj
  601. Password:
  602. Confirm password:
  603. Make admin [no]:
  604. Success!
  605. </code></pre>
  606. <p>This process uses a setting <code>registration_shared_secret</code> in
  607. <code>homeserver.yaml</code>, which is shared between Synapse itself and the
  608. <code>register_new_matrix_user</code> script. It doesn't matter what it is (a random
  609. value is generated by <code>--generate-config</code>), but it should be kept secret, as
  610. anyone with knowledge of it can register users, including admin accounts,
  611. on your server even if <code>enable_registration</code> is <code>false</code>.</p>
  612. <h3 id="setting-up-a-turn-server"><a class="header" href="#setting-up-a-turn-server">Setting up a TURN server</a></h3>
  613. <p>For reliable VoIP calls to be routed via this homeserver, you MUST configure
  614. a TURN server. See <a href="setup/../turn-howto.html">TURN setup</a> for details.</p>
  615. <h3 id="url-previews"><a class="header" href="#url-previews">URL previews</a></h3>
  616. <p>Synapse includes support for previewing URLs, which is disabled by default. To
  617. turn it on you must enable the <code>url_preview_enabled: True</code> config parameter
  618. and explicitly specify the IP ranges that Synapse is not allowed to spider for
  619. previewing in the <code>url_preview_ip_range_blacklist</code> configuration parameter.
  620. This is critical from a security perspective to stop arbitrary Matrix users
  621. spidering 'internal' URLs on your network. At the very least we recommend that
  622. your loopback and RFC1918 IP addresses are blacklisted.</p>
  623. <p>This also requires the optional <code>lxml</code> python dependency to be installed. This
  624. in turn requires the <code>libxml2</code> library to be available - on Debian/Ubuntu this
  625. means <code>apt-get install libxml2-dev</code>, or equivalent for your OS.</p>
  626. <h3 id="troubleshooting-installation"><a class="header" href="#troubleshooting-installation">Troubleshooting Installation</a></h3>
  627. <p><code>pip</code> seems to leak <em>lots</em> of memory during installation. For instance, a Linux
  628. host with 512MB of RAM may run out of memory whilst installing Twisted. If this
  629. happens, you will have to individually install the dependencies which are
  630. failing, e.g.:</p>
  631. <pre><code class="language-sh">pip install twisted
  632. </code></pre>
  633. <p>If you have any other problems, feel free to ask in
  634. <a href="https://matrix.to/#/#synapse:matrix.org">#synapse:matrix.org</a>.</p>
  635. <div style="break-before: page; page-break-before: always;"></div><h1 id="using-postgres"><a class="header" href="#using-postgres">Using Postgres</a></h1>
  636. <p>Synapse supports PostgreSQL versions 10 or later.</p>
  637. <h2 id="install-postgres-client-libraries"><a class="header" href="#install-postgres-client-libraries">Install postgres client libraries</a></h2>
  638. <p>Synapse will require the python postgres client library in order to
  639. connect to a postgres database.</p>
  640. <ul>
  641. <li>
  642. <p>If you are using the <a href="setup/installation.html#matrixorg-packages">matrix.org debian/ubuntu
  643. packages</a>, the necessary python
  644. library will already be installed, but you will need to ensure the
  645. low-level postgres library is installed, which you can do with
  646. <code>apt install libpq5</code>.</p>
  647. </li>
  648. <li>
  649. <p>For other pre-built packages, please consult the documentation from
  650. the relevant package.</p>
  651. </li>
  652. <li>
  653. <p>If you installed synapse <a href="setup/installation.html#installing-from-source">in a
  654. virtualenv</a>, you can install
  655. the library with:</p>
  656. <pre><code>~/synapse/env/bin/pip install &quot;matrix-synapse[postgres]&quot;
  657. </code></pre>
  658. <p>(substituting the path to your virtualenv for <code>~/synapse/env</code>, if
  659. you used a different path). You will require the postgres
  660. development files. These are in the <code>libpq-dev</code> package on
  661. Debian-derived distributions.</p>
  662. </li>
  663. </ul>
  664. <h2 id="set-up-database"><a class="header" href="#set-up-database">Set up database</a></h2>
  665. <p>Assuming your PostgreSQL database user is called <code>postgres</code>, first authenticate as the database user with:</p>
  666. <pre><code class="language-sh">su - postgres
  667. # Or, if your system uses sudo to get administrative rights
  668. sudo -u postgres bash
  669. </code></pre>
  670. <p>Then, create a postgres user and a database with:</p>
  671. <pre><code class="language-sh"># this will prompt for a password for the new user
  672. createuser --pwprompt synapse_user
  673. createdb --encoding=UTF8 --locale=C --template=template0 --owner=synapse_user synapse
  674. </code></pre>
  675. <p>The above will create a user called <code>synapse_user</code>, and a database called
  676. <code>synapse</code>.</p>
  677. <p>Note that the PostgreSQL database <em>must</em> have the correct encoding set
  678. (as shown above), otherwise it will not be able to store UTF8 strings.</p>
  679. <p>You may need to enable password authentication so <code>synapse_user</code> can
  680. connect to the database. See
  681. <a href="https://www.postgresql.org/docs/current/auth-pg-hba-conf.html">https://www.postgresql.org/docs/current/auth-pg-hba-conf.html</a>.</p>
  682. <h2 id="synapse-config"><a class="header" href="#synapse-config">Synapse config</a></h2>
  683. <p>When you are ready to start using PostgreSQL, edit the <code>database</code>
  684. section in your config file to match the following lines:</p>
  685. <pre><code class="language-yaml">database:
  686. name: psycopg2
  687. args:
  688. user: &lt;user&gt;
  689. password: &lt;pass&gt;
  690. database: &lt;db&gt;
  691. host: &lt;host&gt;
  692. cp_min: 5
  693. cp_max: 10
  694. </code></pre>
  695. <p>All key, values in <code>args</code> are passed to the <code>psycopg2.connect(..)</code>
  696. function, except keys beginning with <code>cp_</code>, which are consumed by the
  697. twisted adbapi connection pool. See the <a href="https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS">libpq
  698. documentation</a>
  699. for a list of options which can be passed.</p>
  700. <p>You should consider tuning the <code>args.keepalives_*</code> options if there is any danger of
  701. the connection between your homeserver and database dropping, otherwise Synapse
  702. may block for an extended period while it waits for a response from the
  703. database server. Example values might be:</p>
  704. <pre><code class="language-yaml">database:
  705. args:
  706. # ... as above
  707. # seconds of inactivity after which TCP should send a keepalive message to the server
  708. keepalives_idle: 10
  709. # the number of seconds after which a TCP keepalive message that is not
  710. # acknowledged by the server should be retransmitted
  711. keepalives_interval: 10
  712. # the number of TCP keepalives that can be lost before the client's connection
  713. # to the server is considered dead
  714. keepalives_count: 3
  715. </code></pre>
  716. <h2 id="tuning-postgres"><a class="header" href="#tuning-postgres">Tuning Postgres</a></h2>
  717. <p>The default settings should be fine for most deployments. For larger
  718. scale deployments tuning some of the settings is recommended, details of
  719. which can be found at
  720. <a href="https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server">https://wiki.postgresql.org/wiki/Tuning_Your_PostgreSQL_Server</a>.</p>
  721. <p>In particular, we've found tuning the following values helpful for
  722. performance:</p>
  723. <ul>
  724. <li><code>shared_buffers</code></li>
  725. <li><code>effective_cache_size</code></li>
  726. <li><code>work_mem</code></li>
  727. <li><code>maintenance_work_mem</code></li>
  728. <li><code>autovacuum_work_mem</code></li>
  729. </ul>
  730. <p>Note that the appropriate values for those fields depend on the amount
  731. of free memory the database host has available.</p>
  732. <p>Additionally, admins of large deployments might want to consider using huge pages
  733. to help manage memory, especially when using large values of <code>shared_buffers</code>. You
  734. can read more about that <a href="https://www.postgresql.org/docs/10/kernel-resources.html#LINUX-HUGE-PAGES">here</a>.</p>
  735. <h2 id="porting-from-sqlite"><a class="header" href="#porting-from-sqlite">Porting from SQLite</a></h2>
  736. <h3 id="overview"><a class="header" href="#overview">Overview</a></h3>
  737. <p>The script <code>synapse_port_db</code> allows porting an existing synapse server
  738. backed by SQLite to using PostgreSQL. This is done in as a two phase
  739. process:</p>
  740. <ol>
  741. <li>Copy the existing SQLite database to a separate location and run
  742. the port script against that offline database.</li>
  743. <li>Shut down the server. Rerun the port script to port any data that
  744. has come in since taking the first snapshot. Restart server against
  745. the PostgreSQL database.</li>
  746. </ol>
  747. <p>The port script is designed to be run repeatedly against newer snapshots
  748. of the SQLite database file. This makes it safe to repeat step 1 if
  749. there was a delay between taking the previous snapshot and being ready
  750. to do step 2.</p>
  751. <p>It is safe to at any time kill the port script and restart it.</p>
  752. <p>Note that the database may take up significantly more (25% - 100% more)
  753. space on disk after porting to Postgres.</p>
  754. <h3 id="using-the-port-script"><a class="header" href="#using-the-port-script">Using the port script</a></h3>
  755. <p>Firstly, shut down the currently running synapse server and copy its
  756. database file (typically <code>homeserver.db</code>) to another location. Once the
  757. copy is complete, restart synapse. For instance:</p>
  758. <pre><code class="language-sh">./synctl stop
  759. cp homeserver.db homeserver.db.snapshot
  760. ./synctl start
  761. </code></pre>
  762. <p>Copy the old config file into a new config file:</p>
  763. <pre><code class="language-sh">cp homeserver.yaml homeserver-postgres.yaml
  764. </code></pre>
  765. <p>Edit the database section as described in the section <em>Synapse config</em>
  766. above and with the SQLite snapshot located at <code>homeserver.db.snapshot</code>
  767. simply run:</p>
  768. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db.snapshot \
  769. --postgres-config homeserver-postgres.yaml
  770. </code></pre>
  771. <p>The flag <code>--curses</code> displays a coloured curses progress UI.</p>
  772. <p>If the script took a long time to complete, or time has otherwise passed
  773. since the original snapshot was taken, repeat the previous steps with a
  774. newer snapshot.</p>
  775. <p>To complete the conversion shut down the synapse server and run the port
  776. script one last time, e.g. if the SQLite database is at <code>homeserver.db</code>
  777. run:</p>
  778. <pre><code class="language-sh">synapse_port_db --sqlite-database homeserver.db \
  779. --postgres-config homeserver-postgres.yaml
  780. </code></pre>
  781. <p>Once that has completed, change the synapse config to point at the
  782. PostgreSQL database configuration file <code>homeserver-postgres.yaml</code>:</p>
  783. <pre><code class="language-sh">./synctl stop
  784. mv homeserver.yaml homeserver-old-sqlite.yaml
  785. mv homeserver-postgres.yaml homeserver.yaml
  786. ./synctl start
  787. </code></pre>
  788. <p>Synapse should now be running against PostgreSQL.</p>
  789. <h2 id="troubleshooting"><a class="header" href="#troubleshooting">Troubleshooting</a></h2>
  790. <h3 id="alternative-auth-methods"><a class="header" href="#alternative-auth-methods">Alternative auth methods</a></h3>
  791. <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
  792. <code>ident</code>:</p>
  793. <ul>
  794. <li>
  795. <p>If the <code>synapse_user</code> user has a password, add the password to the <code>database:</code>
  796. section of <code>homeserver.yaml</code>. Then add the following to <code>pg_hba.conf</code>:</p>
  797. <pre><code>host synapse synapse_user ::1/128 md5 # or `scram-sha-256` instead of `md5` if you use that
  798. </code></pre>
  799. </li>
  800. <li>
  801. <p>If the <code>synapse_user</code> user does not have a password, then a password doesn't
  802. have to be added to <code>homeserver.yaml</code>. But the following does need to be added
  803. to <code>pg_hba.conf</code>:</p>
  804. <pre><code>host synapse synapse_user ::1/128 trust
  805. </code></pre>
  806. </li>
  807. </ul>
  808. <p>Note that line order matters in <code>pg_hba.conf</code>, so make sure that if you do add a
  809. new line, it is inserted before:</p>
  810. <pre><code>host all all ::1/128 ident
  811. </code></pre>
  812. <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>
  813. <p>Synapse will refuse to set up a new database if it has the wrong values of
  814. <code>COLLATE</code> and <code>CTYPE</code> set, and will log warnings on existing databases. Using
  815. different locales can cause issues if the locale library is updated from
  816. underneath the database, or if a different version of the locale is used on any
  817. replicas.</p>
  818. <p>The safest way to fix the issue is to dump the database and recreate it with
  819. the correct locale parameter (as shown above). It is also possible to change the
  820. parameters on a live database and run a <code>REINDEX</code> on the entire database,
  821. however extreme care must be taken to avoid database corruption.</p>
  822. <p>Note that the above may fail with an error about duplicate rows if corruption
  823. has already occurred, and such duplicate rows will need to be manually removed.</p>
  824. <h3 id="fixing-inconsistent-sequences-error"><a class="header" href="#fixing-inconsistent-sequences-error">Fixing inconsistent sequences error</a></h3>
  825. <p>Synapse uses Postgres sequences to generate IDs for various tables. A sequence
  826. and associated table can get out of sync if, for example, Synapse has been
  827. downgraded and then upgraded again.</p>
  828. <p>To fix the issue shut down Synapse (including any and all workers) and run the
  829. SQL command included in the error message. Once done Synapse should start
  830. successfully.</p>
  831. <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>
  832. <p>It is recommended to put a reverse proxy such as
  833. <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html">nginx</a>,
  834. <a href="https://httpd.apache.org/docs/current/mod/mod_proxy_http.html">Apache</a>,
  835. <a href="https://caddyserver.com/docs/quick-starts/reverse-proxy">Caddy</a>,
  836. <a href="https://www.haproxy.org/">HAProxy</a> or
  837. <a href="https://man.openbsd.org/relayd.8">relayd</a> in front of Synapse. One advantage
  838. of doing so is that it means that you can expose the default https port
  839. (443) to Matrix clients without needing to run Synapse with root
  840. privileges.</p>
  841. <p>You should configure your reverse proxy to forward requests to <code>/_matrix</code> or
  842. <code>/_synapse/client</code> to Synapse, and have it set the <code>X-Forwarded-For</code> and
  843. <code>X-Forwarded-Proto</code> request headers.</p>
  844. <p>You should remember that Matrix clients and other Matrix servers do not
  845. necessarily need to connect to your server via the same server name or
  846. port. Indeed, clients will use port 443 by default, whereas servers default to
  847. port 8448. Where these are different, we refer to the 'client port' and the
  848. 'federation port'. See <a href="https://matrix.org/docs/spec/server_server/latest#resolving-server-names">the Matrix
  849. specification</a>
  850. for more details of the algorithm used for federation connections, and
  851. <a href="delegate.html">Delegation</a> for instructions on setting up delegation.</p>
  852. <p><strong>NOTE</strong>: Your reverse proxy must not <code>canonicalise</code> or <code>normalise</code>
  853. the requested URI in any way (for example, by decoding <code>%xx</code> escapes).
  854. Beware that Apache <em>will</em> canonicalise URIs unless you specify
  855. <code>nocanon</code>.</p>
  856. <p>Let's assume that we expect clients to connect to our server at
  857. <code>https://matrix.example.com</code>, and other servers to connect at
  858. <code>https://example.com:8448</code>. The following sections detail the configuration of
  859. the reverse proxy and the homeserver.</p>
  860. <h2 id="homeserver-configuration"><a class="header" href="#homeserver-configuration">Homeserver Configuration</a></h2>
  861. <p>The HTTP configuration will need to be updated for Synapse to correctly record
  862. client IP addresses and generate redirect URLs while behind a reverse proxy. </p>
  863. <p>In <code>homeserver.yaml</code> set <code>x_forwarded: true</code> in the port 8008 section and
  864. consider setting <code>bind_addresses: ['127.0.0.1']</code> so that the server only
  865. listens to traffic on localhost. (Do not change <code>bind_addresses</code> to <code>127.0.0.1</code>
  866. when using a containerized Synapse, as that will prevent it from responding
  867. to proxied traffic.)</p>
  868. <h2 id="reverse-proxy-configuration-examples"><a class="header" href="#reverse-proxy-configuration-examples">Reverse-proxy configuration examples</a></h2>
  869. <p><strong>NOTE</strong>: You only need one of these.</p>
  870. <h3 id="nginx"><a class="header" href="#nginx">nginx</a></h3>
  871. <pre><code class="language-nginx">server {
  872. listen 443 ssl http2;
  873. listen [::]:443 ssl http2;
  874. # For the federation port
  875. listen 8448 ssl http2 default_server;
  876. listen [::]:8448 ssl http2 default_server;
  877. server_name matrix.example.com;
  878. location ~ ^(/_matrix|/_synapse/client) {
  879. # note: do not add a path (even a single /) after the port in `proxy_pass`,
  880. # otherwise nginx will canonicalise the URI and cause signature verification
  881. # errors.
  882. proxy_pass http://localhost:8008;
  883. proxy_set_header X-Forwarded-For $remote_addr;
  884. proxy_set_header X-Forwarded-Proto $scheme;
  885. proxy_set_header Host $host;
  886. # Nginx by default only allows file uploads up to 1M in size
  887. # Increase client_max_body_size to match max_upload_size defined in homeserver.yaml
  888. client_max_body_size 50M;
  889. }
  890. }
  891. </code></pre>
  892. <h3 id="caddy-v1"><a class="header" href="#caddy-v1">Caddy v1</a></h3>
  893. <pre><code>matrix.example.com {
  894. proxy /_matrix http://localhost:8008 {
  895. transparent
  896. }
  897. proxy /_synapse/client http://localhost:8008 {
  898. transparent
  899. }
  900. }
  901. example.com:8448 {
  902. proxy / http://localhost:8008 {
  903. transparent
  904. }
  905. }
  906. </code></pre>
  907. <h3 id="caddy-v2"><a class="header" href="#caddy-v2">Caddy v2</a></h3>
  908. <pre><code>matrix.example.com {
  909. reverse_proxy /_matrix/* http://localhost:8008
  910. reverse_proxy /_synapse/client/* http://localhost:8008
  911. }
  912. example.com:8448 {
  913. reverse_proxy http://localhost:8008
  914. }
  915. </code></pre>
  916. <p><a href="delegate.html">Delegation</a> example:</p>
  917. <pre><code>(matrix-well-known-header) {
  918. # Headers
  919. header Access-Control-Allow-Origin &quot;*&quot;
  920. header Access-Control-Allow-Methods &quot;GET, POST, PUT, DELETE, OPTIONS&quot;
  921. header Access-Control-Allow-Headers &quot;Origin, X-Requested-With, Content-Type, Accept, Authorization&quot;
  922. header Content-Type &quot;application/json&quot;
  923. }
  924. example.com {
  925. handle /.well-known/matrix/server {
  926. import matrix-well-known-header
  927. respond `{&quot;m.server&quot;:&quot;matrix.example.com:443&quot;}`
  928. }
  929. handle /.well-known/matrix/client {
  930. import matrix-well-known-header
  931. 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;}}`
  932. }
  933. }
  934. matrix.example.com {
  935. reverse_proxy /_matrix/* http://localhost:8008
  936. reverse_proxy /_synapse/client/* http://localhost:8008
  937. }
  938. </code></pre>
  939. <h3 id="apache"><a class="header" href="#apache">Apache</a></h3>
  940. <pre><code class="language-apache">&lt;VirtualHost *:443&gt;
  941. SSLEngine on
  942. ServerName matrix.example.com
  943. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  944. AllowEncodedSlashes NoDecode
  945. ProxyPreserveHost on
  946. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  947. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  948. ProxyPass /_synapse/client http://127.0.0.1:8008/_synapse/client nocanon
  949. ProxyPassReverse /_synapse/client http://127.0.0.1:8008/_synapse/client
  950. &lt;/VirtualHost&gt;
  951. &lt;VirtualHost *:8448&gt;
  952. SSLEngine on
  953. ServerName example.com
  954. RequestHeader set &quot;X-Forwarded-Proto&quot; expr=%{REQUEST_SCHEME}
  955. AllowEncodedSlashes NoDecode
  956. ProxyPass /_matrix http://127.0.0.1:8008/_matrix nocanon
  957. ProxyPassReverse /_matrix http://127.0.0.1:8008/_matrix
  958. &lt;/VirtualHost&gt;
  959. </code></pre>
  960. <p><strong>NOTE</strong>: ensure the <code>nocanon</code> options are included.</p>
  961. <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>
  962. <pre><code class="language-apache">&lt;IfModule security2_module&gt;
  963. SecRuleEngine off
  964. &lt;/IfModule&gt;
  965. </code></pre>
  966. <p><strong>NOTE 3</strong>: Missing <code>ProxyPreserveHost on</code> can lead to a redirect loop.</p>
  967. <h3 id="haproxy"><a class="header" href="#haproxy">HAProxy</a></h3>
  968. <pre><code>frontend https
  969. bind :::443 v4v6 ssl crt /etc/ssl/haproxy/ strict-sni alpn h2,http/1.1
  970. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  971. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  972. http-request set-header X-Forwarded-For %[src]
  973. # Matrix client traffic
  974. acl matrix-host hdr(host) -i matrix.example.com matrix.example.com:443
  975. acl matrix-path path_beg /_matrix
  976. acl matrix-path path_beg /_synapse/client
  977. use_backend matrix if matrix-host matrix-path
  978. frontend matrix-federation
  979. bind :::8448 v4v6 ssl crt /etc/ssl/haproxy/synapse.pem alpn h2,http/1.1
  980. http-request set-header X-Forwarded-Proto https if { ssl_fc }
  981. http-request set-header X-Forwarded-Proto http if !{ ssl_fc }
  982. http-request set-header X-Forwarded-For %[src]
  983. default_backend matrix
  984. backend matrix
  985. server matrix 127.0.0.1:8008
  986. </code></pre>
  987. <h3 id="relayd"><a class="header" href="#relayd">Relayd</a></h3>
  988. <pre><code>table &lt;webserver&gt; { 127.0.0.1 }
  989. table &lt;matrixserver&gt; { 127.0.0.1 }
  990. http protocol &quot;https&quot; {
  991. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  992. tls keypair &quot;example.com&quot;
  993. match header set &quot;X-Forwarded-For&quot; value &quot;$REMOTE_ADDR&quot;
  994. match header set &quot;X-Forwarded-Proto&quot; value &quot;https&quot;
  995. # set CORS header for .well-known/matrix/server, .well-known/matrix/client
  996. # httpd does not support setting headers, so do it here
  997. match request path &quot;/.well-known/matrix/*&quot; tag &quot;matrix-cors&quot;
  998. match response tagged &quot;matrix-cors&quot; header set &quot;Access-Control-Allow-Origin&quot; value &quot;*&quot;
  999. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1000. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1001. # pass on non-matrix traffic to webserver
  1002. pass forward to &lt;webserver&gt;
  1003. }
  1004. relay &quot;https_traffic&quot; {
  1005. listen on egress port 443 tls
  1006. protocol &quot;https&quot;
  1007. forward to &lt;matrixserver&gt; port 8008 check tcp
  1008. forward to &lt;webserver&gt; port 8080 check tcp
  1009. }
  1010. http protocol &quot;matrix&quot; {
  1011. tls { no tlsv1.0, ciphers &quot;HIGH&quot; }
  1012. tls keypair &quot;example.com&quot;
  1013. block
  1014. pass quick path &quot;/_matrix/*&quot; forward to &lt;matrixserver&gt;
  1015. pass quick path &quot;/_synapse/client/*&quot; forward to &lt;matrixserver&gt;
  1016. }
  1017. relay &quot;matrix_federation&quot; {
  1018. listen on egress port 8448 tls
  1019. protocol &quot;matrix&quot;
  1020. forward to &lt;matrixserver&gt; port 8008 check tcp
  1021. }
  1022. </code></pre>
  1023. <h2 id="health-check-endpoint"><a class="header" href="#health-check-endpoint">Health check endpoint</a></h2>
  1024. <p>Synapse exposes a health check endpoint for use by reverse proxies.
  1025. Each configured HTTP listener has a <code>/health</code> endpoint which always returns
  1026. 200 OK (and doesn't get logged).</p>
  1027. <h2 id="synapse-administration-endpoints"><a class="header" href="#synapse-administration-endpoints">Synapse administration endpoints</a></h2>
  1028. <p>Endpoints for administering your Synapse instance are placed under
  1029. <code>/_synapse/admin</code>. These require authentication through an access token of an
  1030. admin user. However as access to these endpoints grants the caller a lot of power,
  1031. we do not recommend exposing them to the public internet without good reason.</p>
  1032. <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>
  1033. <p>You can use Synapse with a forward or outbound proxy. An example of when
  1034. this is necessary is in corporate environments behind a DMZ (demilitarized zone).
  1035. Synapse supports routing outbound HTTP(S) requests via a proxy. Only HTTP(S)
  1036. proxy is supported, not SOCKS proxy or anything else.</p>
  1037. <h2 id="configure"><a class="header" href="#configure">Configure</a></h2>
  1038. <p>The <code>http_proxy</code>, <code>https_proxy</code>, <code>no_proxy</code> environment variables are used to
  1039. specify proxy settings. The environment variable is not case sensitive.</p>
  1040. <ul>
  1041. <li><code>http_proxy</code>: Proxy server to use for HTTP requests.</li>
  1042. <li><code>https_proxy</code>: Proxy server to use for HTTPS requests.</li>
  1043. <li><code>no_proxy</code>: Comma-separated list of hosts, IP addresses, or IP ranges in CIDR
  1044. format which should not use the proxy. Synapse will directly connect to these hosts.</li>
  1045. </ul>
  1046. <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>
  1047. <ul>
  1048. <li>
  1049. <p>Supported schemes are <code>http://</code> and <code>https://</code>. The default scheme is <code>http://</code>
  1050. for compatibility reasons; it is recommended to set a scheme. If scheme is set
  1051. to <code>https://</code> the connection uses TLS between Synapse and the proxy.</p>
  1052. <p><strong>NOTE</strong>: Synapse validates the certificates. If the certificate is not
  1053. valid, then the connection is dropped.</p>
  1054. </li>
  1055. <li>
  1056. <p>Default port if not given is <code>1080</code>.</p>
  1057. </li>
  1058. <li>
  1059. <p>Username and password are optional and will be used to authenticate against
  1060. the proxy.</p>
  1061. </li>
  1062. </ul>
  1063. <p><strong>Examples</strong></p>
  1064. <ul>
  1065. <li>HTTP_PROXY=http://USERNAME:PASSWORD@10.0.1.1:8080/</li>
  1066. <li>HTTPS_PROXY=http://USERNAME:PASSWORD@proxy.example.com:8080/</li>
  1067. <li>NO_PROXY=master.hostname.example.com,10.1.0.0/16,172.30.0.0/16</li>
  1068. </ul>
  1069. <p><strong>NOTE</strong>:
  1070. Synapse does not apply the IP blacklist to connections through the proxy (since
  1071. the DNS resolution is done by the proxy). It is expected that the proxy or firewall
  1072. will apply blacklisting of IP addresses.</p>
  1073. <h2 id="connection-types"><a class="header" href="#connection-types">Connection types</a></h2>
  1074. <p>The proxy will be <strong>used</strong> for:</p>
  1075. <ul>
  1076. <li>push</li>
  1077. <li>url previews</li>
  1078. <li>phone-home stats</li>
  1079. <li>recaptcha validation</li>
  1080. <li>CAS auth validation</li>
  1081. <li>OpenID Connect</li>
  1082. <li>Outbound federation</li>
  1083. <li>Federation (checking public key revocation)</li>
  1084. <li>Fetching public keys of other servers</li>
  1085. <li>Downloading remote media</li>
  1086. </ul>
  1087. <p>It will <strong>not be used</strong> for:</p>
  1088. <ul>
  1089. <li>Application Services</li>
  1090. <li>Identity servers</li>
  1091. <li>In worker configurations
  1092. <ul>
  1093. <li>connections between workers</li>
  1094. <li>connections from workers to Redis</li>
  1095. </ul>
  1096. </li>
  1097. </ul>
  1098. <h2 id="troubleshooting-1"><a class="header" href="#troubleshooting-1">Troubleshooting</a></h2>
  1099. <p>If a proxy server is used with TLS (HTTPS) and no connections are established,
  1100. it is most likely due to the proxy's certificates. To test this, the validation
  1101. in Synapse can be deactivated.</p>
  1102. <p><strong>NOTE</strong>: This has an impact on security and is for testing purposes only!</p>
  1103. <p>To deactivate the certificate validation, the following setting must be made in
  1104. <a href="setup/../usage/configuration/homeserver_sample_config.html">homserver.yaml</a>.</p>
  1105. <pre><code class="language-yaml">use_insecure_ssl_client_just_for_testing_do_not_use: true
  1106. </code></pre>
  1107. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-1"><a class="header" href="#overview-1">Overview</a></h1>
  1108. <p>This document explains how to enable VoIP relaying on your homeserver with
  1109. TURN.</p>
  1110. <p>The synapse Matrix homeserver supports integration with TURN server via the
  1111. <a href="https://tools.ietf.org/html/draft-uberti-behave-turn-rest-00">TURN server REST API</a>. This
  1112. allows the homeserver to generate credentials that are valid for use on the
  1113. TURN server through the use of a secret shared between the homeserver and the
  1114. TURN server.</p>
  1115. <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>
  1116. <h2 id="requirements"><a class="header" href="#requirements">Requirements</a></h2>
  1117. <p>For TURN relaying with <code>coturn</code> to work, it must be hosted on a server/endpoint with a public IP.</p>
  1118. <p>Hosting TURN behind NAT requires port forwaring and for the NAT gateway to have a public IP.
  1119. However, even with appropriate configuration, NAT is known to cause issues and to often not work.</p>
  1120. <h2 id="coturn-setup"><a class="header" href="#coturn-setup"><code>coturn</code> setup</a></h2>
  1121. <h3 id="initial-installation"><a class="header" href="#initial-installation">Initial installation</a></h3>
  1122. <p>The TURN daemon <code>coturn</code> is available from a variety of sources such as native package managers, or installation from source.</p>
  1123. <h4 id="debian-installation"><a class="header" href="#debian-installation">Debian installation</a></h4>
  1124. <p>Just install the debian package:</p>
  1125. <pre><code class="language-sh">apt install coturn
  1126. </code></pre>
  1127. <p>This will install and start a systemd service called <code>coturn</code>.</p>
  1128. <h4 id="source-installation"><a class="header" href="#source-installation">Source installation</a></h4>
  1129. <ol>
  1130. <li>
  1131. <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>
  1132. </li>
  1133. <li>
  1134. <p>Configure it:</p>
  1135. <pre><code class="language-sh">./configure
  1136. </code></pre>
  1137. <p>You may need to install <code>libevent2</code>: if so, you should do so in
  1138. the way recommended by your operating system. You can ignore
  1139. warnings about lack of database support: a database is unnecessary
  1140. for this purpose.</p>
  1141. </li>
  1142. <li>
  1143. <p>Build and install it:</p>
  1144. <pre><code class="language-sh">make
  1145. make install
  1146. </code></pre>
  1147. </li>
  1148. </ol>
  1149. <h3 id="configuration"><a class="header" href="#configuration">Configuration</a></h3>
  1150. <ol>
  1151. <li>
  1152. <p>Create or edit the config file in <code>/etc/turnserver.conf</code>. The relevant
  1153. lines, with example values, are:</p>
  1154. <pre><code>use-auth-secret
  1155. static-auth-secret=[your secret key here]
  1156. realm=turn.myserver.org
  1157. </code></pre>
  1158. <p>See <code>turnserver.conf</code> for explanations of the options. One way to generate
  1159. the <code>static-auth-secret</code> is with <code>pwgen</code>:</p>
  1160. <pre><code class="language-sh">pwgen -s 64 1
  1161. </code></pre>
  1162. <p>A <code>realm</code> must be specified, but its value is somewhat arbitrary. (It is
  1163. sent to clients as part of the authentication flow.) It is conventional to
  1164. set it to be your server name.</p>
  1165. </li>
  1166. <li>
  1167. <p>You will most likely want to configure coturn to write logs somewhere. The
  1168. easiest way is normally to send them to the syslog:</p>
  1169. <pre><code class="language-sh">syslog
  1170. </code></pre>
  1171. <p>(in which case, the logs will be available via <code>journalctl -u coturn</code> on a
  1172. systemd system). Alternatively, coturn can be configured to write to a
  1173. logfile - check the example config file supplied with coturn.</p>
  1174. </li>
  1175. <li>
  1176. <p>Consider your security settings. TURN lets users request a relay which will
  1177. connect to arbitrary IP addresses and ports. The following configuration is
  1178. suggested as a minimum starting point:</p>
  1179. <pre><code># VoIP traffic is all UDP. There is no reason to let users connect to arbitrary TCP endpoints via the relay.
  1180. no-tcp-relay
  1181. # don't let the relay ever try to connect to private IP address ranges within your network (if any)
  1182. # given the turn server is likely behind your firewall, remember to include any privileged public IPs too.
  1183. denied-peer-ip=10.0.0.0-10.255.255.255
  1184. denied-peer-ip=192.168.0.0-192.168.255.255
  1185. denied-peer-ip=172.16.0.0-172.31.255.255
  1186. # recommended additional local peers to block, to mitigate external access to internal services.
  1187. # https://www.rtcsec.com/article/slack-webrtc-turn-compromise-and-bug-bounty/#how-to-fix-an-open-turn-relay-to-address-this-vulnerability
  1188. no-multicast-peers
  1189. denied-peer-ip=0.0.0.0-0.255.255.255
  1190. denied-peer-ip=100.64.0.0-100.127.255.255
  1191. denied-peer-ip=127.0.0.0-127.255.255.255
  1192. denied-peer-ip=169.254.0.0-169.254.255.255
  1193. denied-peer-ip=192.0.0.0-192.0.0.255
  1194. denied-peer-ip=192.0.2.0-192.0.2.255
  1195. denied-peer-ip=192.88.99.0-192.88.99.255
  1196. denied-peer-ip=198.18.0.0-198.19.255.255
  1197. denied-peer-ip=198.51.100.0-198.51.100.255
  1198. denied-peer-ip=203.0.113.0-203.0.113.255
  1199. denied-peer-ip=240.0.0.0-255.255.255.255
  1200. # special case the turn server itself so that client-&gt;TURN-&gt;TURN-&gt;client flows work
  1201. # this should be one of the turn server's listening IPs
  1202. allowed-peer-ip=10.0.0.1
  1203. # consider whether you want to limit the quota of relayed streams per user (or total) to avoid risk of DoS.
  1204. user-quota=12 # 4 streams per video call, so 12 streams = 3 simultaneous relayed calls per user.
  1205. total-quota=1200
  1206. </code></pre>
  1207. </li>
  1208. <li>
  1209. <p>Also consider supporting TLS/DTLS. To do this, add the following settings
  1210. to <code>turnserver.conf</code>:</p>
  1211. <pre><code># TLS certificates, including intermediate certs.
  1212. # For Let's Encrypt certificates, use `fullchain.pem` here.
  1213. cert=/path/to/fullchain.pem
  1214. # TLS private key file
  1215. pkey=/path/to/privkey.pem
  1216. # Ensure the configuration lines that disable TLS/DTLS are commented-out or removed
  1217. #no-tls
  1218. #no-dtls
  1219. </code></pre>
  1220. <p>In this case, replace the <code>turn:</code> schemes in the <code>turn_uris</code> settings below
  1221. with <code>turns:</code>.</p>
  1222. <p>We recommend that you only try to set up TLS/DTLS once you have set up a
  1223. basic installation and got it working.</p>
  1224. <p>NB: If your TLS certificate was provided by Let's Encrypt, TLS/DTLS will
  1225. not work with any Matrix client that uses Chromium's WebRTC library. This
  1226. currently includes Element Android &amp; iOS; for more details, see their
  1227. <a href="https://github.com/vector-im/element-android/issues/1533">respective</a>
  1228. <a href="https://github.com/vector-im/element-ios/issues/2712">issues</a> as well as the underlying
  1229. <a href="https://bugs.chromium.org/p/webrtc/issues/detail?id=11710">WebRTC issue</a>.
  1230. Consider using a ZeroSSL certificate for your TURN server as a working alternative.</p>
  1231. </li>
  1232. <li>
  1233. <p>Ensure your firewall allows traffic into the TURN server on the ports
  1234. you've configured it to listen on (By default: 3478 and 5349 for TURN
  1235. traffic (remember to allow both TCP and UDP traffic), and ports 49152-65535
  1236. for the UDP relay.)</p>
  1237. </li>
  1238. <li>
  1239. <p>If your TURN server is behind NAT, the NAT gateway must have an external,
  1240. publicly-reachable IP address. You must configure coturn to advertise that
  1241. address to connecting clients:</p>
  1242. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1243. </code></pre>
  1244. <p>You may optionally limit the TURN server to listen only on the local
  1245. address that is mapped by NAT to the external address:</p>
  1246. <pre><code>listening-ip=INTERNAL_TURNSERVER_IPv4_ADDRESS
  1247. </code></pre>
  1248. <p>If your NAT gateway is reachable over both IPv4 and IPv6, you may
  1249. configure coturn to advertise each available address:</p>
  1250. <pre><code>external-ip=EXTERNAL_NAT_IPv4_ADDRESS
  1251. external-ip=EXTERNAL_NAT_IPv6_ADDRESS
  1252. </code></pre>
  1253. <p>When advertising an external IPv6 address, ensure that the firewall and
  1254. network settings of the system running your TURN server are configured to
  1255. accept IPv6 traffic, and that the TURN server is listening on the local
  1256. IPv6 address that is mapped by NAT to the external IPv6 address.</p>
  1257. </li>
  1258. <li>
  1259. <p>(Re)start the turn server:</p>
  1260. <ul>
  1261. <li>
  1262. <p>If you used the Debian package (or have set up a systemd unit yourself):</p>
  1263. <pre><code class="language-sh">systemctl restart coturn
  1264. </code></pre>
  1265. </li>
  1266. <li>
  1267. <p>If you installed from source:</p>
  1268. <pre><code class="language-sh">bin/turnserver -o
  1269. </code></pre>
  1270. </li>
  1271. </ul>
  1272. </li>
  1273. </ol>
  1274. <h2 id="synapse-setup"><a class="header" href="#synapse-setup">Synapse setup</a></h2>
  1275. <p>Your homeserver configuration file needs the following extra keys:</p>
  1276. <ol>
  1277. <li>&quot;<code>turn_uris</code>&quot;: This needs to be a yaml list of public-facing URIs
  1278. for your TURN server to be given out to your clients. Add separate
  1279. entries for each transport your TURN server supports.</li>
  1280. <li>&quot;<code>turn_shared_secret</code>&quot;: This is the secret shared between your
  1281. homeserver and your TURN server, so you should set it to the same
  1282. string you used in turnserver.conf.</li>
  1283. <li>&quot;<code>turn_user_lifetime</code>&quot;: This is the amount of time credentials
  1284. generated by your homeserver are valid for (in milliseconds).
  1285. Shorter times offer less potential for abuse at the expense of
  1286. increased traffic between web clients and your homeserver to
  1287. refresh credentials. The TURN REST API specification recommends
  1288. one day (86400000).</li>
  1289. <li>&quot;<code>turn_allow_guests</code>&quot;: Whether to allow guest users to use the
  1290. TURN server. This is enabled by default, as otherwise VoIP will
  1291. not work reliably for guests. However, it does introduce a
  1292. security risk as it lets guests connect to arbitrary endpoints
  1293. without having gone through a CAPTCHA or similar to register a
  1294. real account.</li>
  1295. </ol>
  1296. <p>As an example, here is the relevant section of the config file for <code>matrix.org</code>. The
  1297. <code>turn_uris</code> are appropriate for TURN servers listening on the default ports, with no TLS.</p>
  1298. <pre><code>turn_uris: [ &quot;turn:turn.matrix.org?transport=udp&quot;, &quot;turn:turn.matrix.org?transport=tcp&quot; ]
  1299. turn_shared_secret: &quot;n0t4ctuAllymatr1Xd0TorgSshar3d5ecret4obvIousreAsons&quot;
  1300. turn_user_lifetime: 86400000
  1301. turn_allow_guests: True
  1302. </code></pre>
  1303. <p>After updating the homeserver configuration, you must restart synapse:</p>
  1304. <ul>
  1305. <li>If you use synctl:
  1306. <pre><code class="language-sh">cd /where/you/run/synapse
  1307. ./synctl restart
  1308. </code></pre>
  1309. </li>
  1310. <li>If you use systemd:
  1311. <pre><code class="language-sh">systemctl restart matrix-synapse.service
  1312. </code></pre>
  1313. </li>
  1314. </ul>
  1315. <p>... and then reload any clients (or wait an hour for them to refresh their
  1316. settings).</p>
  1317. <h2 id="troubleshooting-2"><a class="header" href="#troubleshooting-2">Troubleshooting</a></h2>
  1318. <p>The normal symptoms of a misconfigured TURN server are that calls between
  1319. devices on different networks ring, but get stuck at &quot;call
  1320. connecting&quot;. Unfortunately, troubleshooting this can be tricky.</p>
  1321. <p>Here are a few things to try:</p>
  1322. <ul>
  1323. <li>
  1324. <p>Check that you have opened your firewall to allow TCP and UDP traffic to the
  1325. TURN ports (normally 3478 and 5349).</p>
  1326. </li>
  1327. <li>
  1328. <p>Check that you have opened your firewall to allow UDP traffic to the UDP
  1329. relay ports (49152-65535 by default).</p>
  1330. </li>
  1331. <li>
  1332. <p>Try disabling <code>coturn</code>'s TLS/DTLS listeners and enable only its (unencrypted)
  1333. TCP/UDP listeners. (This will only leave signaling traffic unencrypted;
  1334. voice &amp; video WebRTC traffic is always encrypted.)</p>
  1335. </li>
  1336. <li>
  1337. <p>Some WebRTC implementations (notably, that of Google Chrome) appear to get
  1338. confused by TURN servers which are reachable over IPv6 (this appears to be
  1339. an unexpected side-effect of its handling of multiple IP addresses as
  1340. defined by
  1341. <a href="https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12"><code>draft-ietf-rtcweb-ip-handling</code></a>).</p>
  1342. <p>Try removing any AAAA records for your TURN server, so that it is only
  1343. reachable over IPv4.</p>
  1344. </li>
  1345. <li>
  1346. <p>If your TURN server is behind NAT:</p>
  1347. <ul>
  1348. <li>
  1349. <p>double-check that your NAT gateway is correctly forwarding all TURN
  1350. ports (normally 3478 &amp; 5349 for TCP &amp; UDP TURN traffic, and 49152-65535 for the UDP
  1351. relay) to the NAT-internal address of your TURN server. If advertising
  1352. both IPv4 and IPv6 external addresses via the <code>external-ip</code> option, ensure
  1353. that the NAT is forwarding both IPv4 and IPv6 traffic to the IPv4 and IPv6
  1354. internal addresses of your TURN server. When in doubt, remove AAAA records
  1355. for your TURN server and specify only an IPv4 address as your <code>external-ip</code>.</p>
  1356. </li>
  1357. <li>
  1358. <p>ensure that your TURN server uses the NAT gateway as its default route.</p>
  1359. </li>
  1360. </ul>
  1361. </li>
  1362. <li>
  1363. <p>Enable more verbose logging in coturn via the <code>verbose</code> setting:</p>
  1364. <pre><code>verbose
  1365. </code></pre>
  1366. <p>... and then see if there are any clues in its logs.</p>
  1367. </li>
  1368. <li>
  1369. <p>If you are using a browser-based client under Chrome, check
  1370. <code>chrome://webrtc-internals/</code> for insights into the internals of the
  1371. negotiation. On Firefox, check the &quot;Connection Log&quot; on <code>about:webrtc</code>.</p>
  1372. <p>(Understanding the output is beyond the scope of this document!)</p>
  1373. </li>
  1374. <li>
  1375. <p>You can test your Matrix homeserver TURN setup with https://test.voip.librepush.net/.
  1376. Note that this test is not fully reliable yet, so don't be discouraged if
  1377. the test fails.
  1378. <a href="https://github.com/matrix-org/voip-tester">Here</a> is the github repo of the
  1379. source of the tester, where you can file bug reports.</p>
  1380. </li>
  1381. <li>
  1382. <p>There is a WebRTC test tool at
  1383. https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/. To
  1384. use it, you will need a username/password for your TURN server. You can
  1385. either:</p>
  1386. <ul>
  1387. <li>
  1388. <p>look for the <code>GET /_matrix/client/r0/voip/turnServer</code> request made by a
  1389. matrix client to your homeserver in your browser's network inspector. In
  1390. the response you should see <code>username</code> and <code>password</code>. Or:</p>
  1391. </li>
  1392. <li>
  1393. <p>Use the following shell commands:</p>
  1394. <pre><code class="language-sh">secret=staticAuthSecretHere
  1395. u=$((`date +%s` + 3600)):test
  1396. p=$(echo -n $u | openssl dgst -hmac $secret -sha1 -binary | base64)
  1397. echo -e &quot;username: $u\npassword: $p&quot;
  1398. </code></pre>
  1399. <p>Or:</p>
  1400. </li>
  1401. <li>
  1402. <p>Temporarily configure coturn to accept a static username/password. To do
  1403. this, comment out <code>use-auth-secret</code> and <code>static-auth-secret</code> and add the
  1404. following:</p>
  1405. <pre><code>lt-cred-mech
  1406. user=username:password
  1407. </code></pre>
  1408. <p><strong>Note</strong>: these settings will not take effect unless <code>use-auth-secret</code>
  1409. and <code>static-auth-secret</code> are disabled.</p>
  1410. <p>Restart coturn after changing the configuration file.</p>
  1411. <p>Remember to restore the original settings to go back to testing with
  1412. Matrix clients!</p>
  1413. </li>
  1414. </ul>
  1415. <p>If the TURN server is working correctly, you should see at least one <code>relay</code>
  1416. entry in the results.</p>
  1417. </li>
  1418. </ul>
  1419. <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>
  1420. <p>In the following documentation, we use the term <code>server_name</code> to refer to that setting
  1421. in your homeserver configuration file. It appears at the ends of user ids, and tells
  1422. other homeservers where they can find your server.</p>
  1423. <p>By default, other homeservers will expect to be able to reach yours via
  1424. your <code>server_name</code>, on port 8448. For example, if you set your <code>server_name</code>
  1425. to <code>example.com</code> (so that your user names look like <code>@user:example.com</code>),
  1426. other servers will try to connect to yours at <code>https://example.com:8448/</code>.</p>
  1427. <p>Delegation is a Matrix feature allowing a homeserver admin to retain a
  1428. <code>server_name</code> of <code>example.com</code> so that user IDs, room aliases, etc continue
  1429. to look like <code>*:example.com</code>, whilst having federation traffic routed
  1430. to a different server and/or port (e.g. <code>synapse.example.com:443</code>).</p>
  1431. <h2 id="well-known-delegation"><a class="header" href="#well-known-delegation">.well-known delegation</a></h2>
  1432. <p>To use this method, you need to be able to configure the server at
  1433. <code>https://&lt;server_name&gt;</code> to serve a file at
  1434. <code>https://&lt;server_name&gt;/.well-known/matrix/server</code>. There are two ways to do this, shown below.</p>
  1435. <p>Note that the <code>.well-known</code> file is hosted on the default port for <code>https</code> (port 443).</p>
  1436. <h3 id="external-server"><a class="header" href="#external-server">External server</a></h3>
  1437. <p>For maximum flexibility, you need to configure an external server such as nginx, Apache
  1438. or HAProxy to serve the <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> file. Setting
  1439. up such a server is out of the scope of this documentation, but note that it is often
  1440. possible to configure your <a href="reverse_proxy.html">reverse proxy</a> for this.</p>
  1441. <p>The URL <code>https://&lt;server_name&gt;/.well-known/matrix/server</code> should be configured
  1442. return a JSON structure containing the key <code>m.server</code> like this:</p>
  1443. <pre><code class="language-json">{
  1444. &quot;m.server&quot;: &quot;&lt;synapse.server.name&gt;[:&lt;yourport&gt;]&quot;
  1445. }
  1446. </code></pre>
  1447. <p>In our example (where we want federation traffic to be routed to
  1448. <code>https://synapse.example.com</code>, on port 443), this would mean that
  1449. <code>https://example.com/.well-known/matrix/server</code> should return:</p>
  1450. <pre><code class="language-json">{
  1451. &quot;m.server&quot;: &quot;synapse.example.com:443&quot;
  1452. }
  1453. </code></pre>
  1454. <p>Note, specifying a port is optional. If no port is specified, then it defaults
  1455. to 8448.</p>
  1456. <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>
  1457. <p>If you are able to set up your domain so that <code>https://&lt;server_name&gt;</code> is routed to
  1458. Synapse (i.e., the only change needed is to direct federation traffic to port 443
  1459. instead of port 8448), then it is possible to configure Synapse to serve a suitable
  1460. <code>.well-known/matrix/server</code> file. To do so, add the following to your <code>homeserver.yaml</code>
  1461. file:</p>
  1462. <pre><code class="language-yaml">serve_server_wellknown: true
  1463. </code></pre>
  1464. <p><strong>Note</strong>: this <em>only</em> works if <code>https://&lt;server_name&gt;</code> is routed to Synapse, so is
  1465. generally not suitable if Synapse is hosted at a subdomain such as
  1466. <code>https://synapse.example.com</code>.</p>
  1467. <h2 id="srv-dns-record-delegation"><a class="header" href="#srv-dns-record-delegation">SRV DNS record delegation</a></h2>
  1468. <p>It is also possible to do delegation using a SRV DNS record. However, that is generally
  1469. not recommended, as it can be difficult to configure the TLS certificates correctly in
  1470. this case, and it offers little advantage over <code>.well-known</code> delegation.</p>
  1471. <p>However, if you really need it, you can find some documentation on what such a
  1472. 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
  1473. specification</a>.</p>
  1474. <h2 id="delegation-faq"><a class="header" href="#delegation-faq">Delegation FAQ</a></h2>
  1475. <h3 id="when-do-i-need-delegation"><a class="header" href="#when-do-i-need-delegation">When do I need delegation?</a></h3>
  1476. <p>If your homeserver's APIs are accessible on the default federation port (8448)
  1477. and the domain your <code>server_name</code> points to, you do not need any delegation.</p>
  1478. <p>For instance, if you registered <code>example.com</code> and pointed its DNS A record at a
  1479. fresh server, you could install Synapse on that host, giving it a <code>server_name</code>
  1480. of <code>example.com</code>, and once a reverse proxy has been set up to proxy all requests
  1481. sent to the port <code>8448</code> and serve TLS certificates for <code>example.com</code>, you
  1482. wouldn't need any delegation set up.</p>
  1483. <p><strong>However</strong>, if your homeserver's APIs aren't accessible on port 8448 and on the
  1484. domain <code>server_name</code> points to, you will need to let other servers know how to
  1485. find it using delegation.</p>
  1486. <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>
  1487. <p>Generally, using a reverse proxy for both the federation and client traffic is a good
  1488. idea, since it saves handling TLS traffic in Synapse. See
  1489. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a
  1490. reverse proxy.</p>
  1491. <div style="break-before: page; page-break-before: always;"></div><h1 id="upgrading-synapse"><a class="header" href="#upgrading-synapse">Upgrading Synapse</a></h1>
  1492. <p>Before upgrading check if any special steps are required to upgrade from
  1493. the version you currently have installed to the current version of
  1494. Synapse. The extra instructions that may be required are listed later in
  1495. this document.</p>
  1496. <ul>
  1497. <li>
  1498. <p>Check that your versions of Python and PostgreSQL are still
  1499. supported.</p>
  1500. <p>Synapse follows upstream lifecycles for <a href="https://endoflife.date/python">Python</a> and
  1501. <a href="https://endoflife.date/postgresql">PostgreSQL</a>, and removes support for versions
  1502. which are no longer maintained.</p>
  1503. <p>The website <a href="https://endoflife.date">https://endoflife.date</a> also offers convenient
  1504. summaries.</p>
  1505. </li>
  1506. <li>
  1507. <p>If Synapse was installed using <a href="setup/installation.html#prebuilt-packages">prebuilt
  1508. packages</a>, you will need to follow the
  1509. normal process for upgrading those packages.</p>
  1510. </li>
  1511. <li>
  1512. <p>If Synapse was installed from source, then:</p>
  1513. <ol>
  1514. <li>
  1515. <p>Activate the virtualenv before upgrading. For example, if
  1516. Synapse is installed in a virtualenv in <code>~/synapse/env</code> then
  1517. run:</p>
  1518. <pre><code class="language-bash">source ~/synapse/env/bin/activate
  1519. </code></pre>
  1520. </li>
  1521. <li>
  1522. <p>If Synapse was installed using pip then upgrade to the latest
  1523. version by running:</p>
  1524. <pre><code class="language-bash">pip install --upgrade matrix-synapse
  1525. </code></pre>
  1526. <p>If Synapse was installed using git then upgrade to the latest
  1527. version by running:</p>
  1528. <pre><code class="language-bash">git pull
  1529. pip install --upgrade .
  1530. </code></pre>
  1531. </li>
  1532. <li>
  1533. <p>Restart Synapse:</p>
  1534. <pre><code class="language-bash">./synctl restart
  1535. </code></pre>
  1536. </li>
  1537. </ol>
  1538. </li>
  1539. </ul>
  1540. <p>To check whether your update was successful, you can check the running
  1541. server version with:</p>
  1542. <pre><code class="language-bash"># you may need to replace 'localhost:8008' if synapse is not configured
  1543. # to listen on port 8008.
  1544. curl http://localhost:8008/_synapse/admin/v1/server_version
  1545. </code></pre>
  1546. <h2 id="rolling-back-to-older-versions"><a class="header" href="#rolling-back-to-older-versions">Rolling back to older versions</a></h2>
  1547. <p>Rolling back to previous releases can be difficult, due to database
  1548. schema changes between releases. Where we have been able to test the
  1549. rollback process, this will be noted below.</p>
  1550. <p>In general, you will need to undo any changes made during the upgrade
  1551. process, for example:</p>
  1552. <ul>
  1553. <li>
  1554. <p>pip:</p>
  1555. <pre><code class="language-bash">source env/bin/activate
  1556. # replace `1.3.0` accordingly:
  1557. pip install matrix-synapse==1.3.0
  1558. </code></pre>
  1559. </li>
  1560. <li>
  1561. <p>Debian:</p>
  1562. <pre><code class="language-bash"># replace `1.3.0` and `stretch` accordingly:
  1563. wget https://packages.matrix.org/debian/pool/main/m/matrix-synapse-py3/matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1564. dpkg -i matrix-synapse-py3_1.3.0+stretch1_amd64.deb
  1565. </code></pre>
  1566. </li>
  1567. </ul>
  1568. <h1 id="upgrading-to-v1530"><a class="header" href="#upgrading-to-v1530">Upgrading to v1.53.0</a></h1>
  1569. <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>
  1570. <p>Per the deprecation notice in Synapse v1.51.0, listeners of type <code>webclient</code>
  1571. are no longer supported and configuring them is a now a configuration error.</p>
  1572. <p>Configuring a non-HTTP(S) <code>web_client_location</code> configuration is is now a
  1573. configuration error. Since the <code>webclient</code> listener is no longer supported, this
  1574. setting only applies to the root path <code>/</code> of Synapse's web server and no longer
  1575. the <code>/_matrix/client/</code> path.</p>
  1576. <h2 id="stablisation-of-msc3231"><a class="header" href="#stablisation-of-msc3231">Stablisation of MSC3231</a></h2>
  1577. <p>The unstable validity-check endpoint for the
  1578. <a href="https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv1registermloginregistration_tokenvalidity">Registration Tokens</a>
  1579. feature has been stabilised and moved from:</p>
  1580. <p><code>/_matrix/client/unstable/org.matrix.msc3231/register/org.matrix.msc3231.login.registration_token/validity</code></p>
  1581. <p>to:</p>
  1582. <p><code>/_matrix/client/v1/register/m.login.registration_token/validity</code></p>
  1583. <p>Please update any relevant reverse proxy or firewall configurations appropriately.</p>
  1584. <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>
  1585. <p>Formerly, entries in the cache were not evicted regardless of whether they were accessed after storing.
  1586. This behavior has now changed. By default entries in the cache are now evicted after 30m of not being accessed.
  1587. To change the default behavior, go to the <code>caches</code> section of the config and change the <code>expire_caches</code> and
  1588. <code>cache_entry_ttl</code> flags as necessary. Please note that these flags replace the <code>expiry_time</code> flag in the config.<br />
  1589. The <code>expiry_time</code> flag will still continue to work, but it has been deprecated and will be removed in the future.</p>
  1590. <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>
  1591. <p>The <code>capabilities</code> of MSC3283 from the REST API <code>/_matrix/client/r0/capabilities</code>
  1592. becomes stable.</p>
  1593. <p>The old <code>capabilities</code></p>
  1594. <ul>
  1595. <li><code>org.matrix.msc3283.set_displayname</code>,</li>
  1596. <li><code>org.matrix.msc3283.set_avatar_url</code> and</li>
  1597. <li><code>org.matrix.msc3283.3pid_changes</code></li>
  1598. </ul>
  1599. <p>are deprecated and scheduled to be removed in Synapse v1.54.0.</p>
  1600. <p>The new <code>capabilities</code></p>
  1601. <ul>
  1602. <li><code>m.set_displayname</code>,</li>
  1603. <li><code>m.set_avatar_url</code> and</li>
  1604. <li><code>m.3pid_changes</code></li>
  1605. </ul>
  1606. <p>are now active by default.</p>
  1607. <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>
  1608. <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>,
  1609. the deprecated <code>user_may_create_room_with_invites</code> module callback has been removed.</p>
  1610. <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>
  1611. 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>
  1612. 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>
  1613. 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>
  1614. <h1 id="upgrading-to-v1520"><a class="header" href="#upgrading-to-v1520">Upgrading to v1.52.0</a></h1>
  1615. <h2 id="twisted-security-release"><a class="header" href="#twisted-security-release">Twisted security release</a></h2>
  1616. <p>Note that <a href="https://github.com/twisted/twisted/releases/tag/twisted-22.1.0">Twisted 22.1.0</a>
  1617. has recently been released, which fixes a <a href="https://github.com/twisted/twisted/security/advisories/GHSA-92x2-jw7w-xvvx">security issue</a>
  1618. within the Twisted library. We do not believe Synapse is affected by this vulnerability,
  1619. though we advise server administrators who installed Synapse via pip to upgrade Twisted
  1620. with <code>pip install --upgrade Twisted</code> as a matter of good practice. The Docker image
  1621. <code>matrixdotorg/synapse</code> and the Debian packages from <code>packages.matrix.org</code> are using the
  1622. updated library.</p>
  1623. <h1 id="upgrading-to-v1510"><a class="header" href="#upgrading-to-v1510">Upgrading to v1.51.0</a></h1>
  1624. <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>
  1625. <p>Listeners of type <code>webclient</code> are deprecated and scheduled to be removed in
  1626. Synapse v1.53.0.</p>
  1627. <p>Similarly, a non-HTTP(S) <code>web_client_location</code> configuration is deprecated and
  1628. will become a configuration error in Synapse v1.53.0.</p>
  1629. <h1 id="upgrading-to-v1500"><a class="header" href="#upgrading-to-v1500">Upgrading to v1.50.0</a></h1>
  1630. <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>
  1631. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  1632. we've dropped support for Python 3.6 and PostgreSQL 9.6, as they are no
  1633. longer supported upstream.</p>
  1634. <p>This release of Synapse requires Python 3.7+ and PostgreSQL 10+.</p>
  1635. <h1 id="upgrading-to-v1470"><a class="header" href="#upgrading-to-v1470">Upgrading to v1.47.0</a></h1>
  1636. <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>
  1637. <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>
  1638. (released on 2021-05-17) and have now been removed:</p>
  1639. <ul>
  1640. <li><code>POST /_synapse/admin/v1/&lt;room_id&gt;/delete</code></li>
  1641. </ul>
  1642. <p>Any scripts still using the above APIs should be converted to use the
  1643. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  1644. <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>
  1645. <p>The <code>user_may_create_room_with_invites</code> is deprecated and will be removed in a future
  1646. version of Synapse. Modules implementing this callback can instead implement
  1647. <a href="https://matrix-org.github.io/synapse/latest/modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a>
  1648. 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>
  1649. module API method to infer whether the invite is happening in the context of creating a
  1650. room.</p>
  1651. <p>We plan to remove this callback in January 2022.</p>
  1652. <h1 id="upgrading-to-v1450"><a class="header" href="#upgrading-to-v1450">Upgrading to v1.45.0</a></h1>
  1653. <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>
  1654. <p>Media storage provider modules that read from the Synapse configuration object (i.e. that
  1655. read the value of <code>hs.config.[...]</code>) now need to specify the configuration section they're
  1656. reading from. This means that if a module reads the value of e.g. <code>hs.config.media_store_path</code>,
  1657. it needs to replace it with <code>hs.config.media.media_store_path</code>.</p>
  1658. <h1 id="upgrading-to-v1440"><a class="header" href="#upgrading-to-v1440">Upgrading to v1.44.0</a></h1>
  1659. <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>
  1660. <p>The <code>url_cache/</code> and <code>url_cache_thumbnails/</code> directories in the media store are
  1661. no longer mirrored to storage providers. These two directories can be safely
  1662. deleted from any configured storage providers to reclaim space.</p>
  1663. <h1 id="upgrading-to-v1430"><a class="header" href="#upgrading-to-v1430">Upgrading to v1.43.0</a></h1>
  1664. <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>
  1665. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#available-worker-applications">available worker applications documentation</a>
  1666. has been updated to reflect that calls to the <code>/spaces</code>, <code>/hierarchy</code>, and
  1667. <code>/summary</code> endpoints can now be routed to workers for both client API and
  1668. federation requests.</p>
  1669. <h1 id="upgrading-to-v1420"><a class="header" href="#upgrading-to-v1420">Upgrading to v1.42.0</a></h1>
  1670. <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>
  1671. <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>
  1672. (released on 2021-01-13) and have now been removed:</p>
  1673. <ul>
  1674. <li><code>POST /_synapse/admin/v1/purge_room</code></li>
  1675. <li><code>POST /_synapse/admin/v1/shutdown_room/&lt;room_id&gt;</code></li>
  1676. </ul>
  1677. <p>Any scripts still using the above APIs should be converted to use the
  1678. <a href="https://matrix-org.github.io/synapse/latest/admin_api/rooms.html#delete-room-api">Delete Room API</a>.</p>
  1679. <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>
  1680. <p>This may affect you if you make use of custom HTML templates for the
  1681. <a href="../synapse/res/templates/recaptcha.html">reCAPTCHA</a> or
  1682. <a href="../synapse/res/templates/terms.html">terms</a> fallback pages.</p>
  1683. <p>The template is now provided an <code>error</code> variable if the authentication
  1684. process failed. See the default templates linked above for an example.</p>
  1685. <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>
  1686. <p>Users will stop receiving message updates via email for addresses that were
  1687. once, but not still, linked to their account.</p>
  1688. <h1 id="upgrading-to-v1410"><a class="header" href="#upgrading-to-v1410">Upgrading to v1.41.0</a></h1>
  1689. <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>
  1690. <p>Since Synapse 1.6.0 (2019-11-26) you can set a proxy for outbound HTTP requests via
  1691. http_proxy/https_proxy environment variables. This proxy was set for:</p>
  1692. <ul>
  1693. <li>push</li>
  1694. <li>url previews</li>
  1695. <li>phone-home stats</li>
  1696. <li>recaptcha validation</li>
  1697. <li>CAS auth validation</li>
  1698. <li>OpenID Connect</li>
  1699. <li>Federation (checking public key revocation)</li>
  1700. </ul>
  1701. <p>In this version we have added support for outbound requests for:</p>
  1702. <ul>
  1703. <li>Outbound federation</li>
  1704. <li>Downloading remote media</li>
  1705. <li>Fetching public keys of other servers</li>
  1706. </ul>
  1707. <p>These requests use the same proxy configuration. If you have a proxy configuration we
  1708. recommend to verify the configuration. It may be necessary to adjust the <code>no_proxy</code>
  1709. environment variable.</p>
  1710. <p>See <a href="setup/forward_proxy.html">using a forward proxy with Synapse documentation</a> for
  1711. details.</p>
  1712. <h2 id="deprecation-of-template_dir"><a class="header" href="#deprecation-of-template_dir">Deprecation of <code>template_dir</code></a></h2>
  1713. <p>The <code>template_dir</code> settings in the <code>sso</code>, <code>account_validity</code> and <code>email</code> sections of the
  1714. configuration file are now deprecated. Server admins should use the new
  1715. <code>templates.custom_template_directory</code> setting in the configuration file and use one single
  1716. custom template directory for all aforementioned features. Template file names remain
  1717. unchanged. See <a href="https://matrix-org.github.io/synapse/latest/templates.html">the related documentation</a>
  1718. for more information and examples.</p>
  1719. <p>We plan to remove support for these settings in October 2021.</p>
  1720. <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>
  1721. <p>The <a href="https://matrix-org.github.io/synapse/latest/workers.html#synapseappmedia_repository">media repository worker documentation</a>
  1722. has been updated to reflect that calls to <code>/_synapse/admin/v1/users/{userId}/media</code>
  1723. must now be handled by media repository workers. This is due to the new <code>DELETE</code> method
  1724. of this endpoint modifying the media store.</p>
  1725. <h1 id="upgrading-to-v1390"><a class="header" href="#upgrading-to-v1390">Upgrading to v1.39.0</a></h1>
  1726. <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>
  1727. <p>The current third-party rules module interface is deprecated in favour of the new generic
  1728. modules system introduced in Synapse v1.37.0. Authors of third-party rules modules can refer
  1729. to <a href="modules/porting_legacy_module.html">this documentation</a>
  1730. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this documentation</a>
  1731. to update their configuration once the modules they are using have been updated.</p>
  1732. <p>We plan to remove support for the current third-party rules interface in September 2021.</p>
  1733. <h1 id="upgrading-to-v1380"><a class="header" href="#upgrading-to-v1380">Upgrading to v1.38.0</a></h1>
  1734. <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>
  1735. <p>This release includes a database schema update which requires re-indexing one of
  1736. the larger tables in the database, <code>events</code>. This could result in increased
  1737. disk I/O for several hours or days after upgrading while the migration
  1738. completes. Furthermore, because we have to keep the old indexes until the new
  1739. indexes are ready, it could result in a significant, temporary, increase in
  1740. disk space.</p>
  1741. <p>To get a rough idea of the disk space required, check the current size of one
  1742. of the indexes. For example, from a <code>psql</code> shell, run the following sql:</p>
  1743. <pre><code class="language-sql">SELECT pg_size_pretty(pg_relation_size('events_order_room'));
  1744. </code></pre>
  1745. <p>We need to rebuild <strong>four</strong> indexes, so you will need to multiply this result
  1746. by four to give an estimate of the disk space required. For example, on one
  1747. particular server:</p>
  1748. <pre><code>synapse=# select pg_size_pretty(pg_relation_size('events_order_room'));
  1749. pg_size_pretty
  1750. ----------------
  1751. 288 MB
  1752. (1 row)
  1753. </code></pre>
  1754. <p>On this server, it would be wise to ensure that at least 1152MB are free.</p>
  1755. <p>The additional disk space will be freed once the migration completes.</p>
  1756. <p>SQLite databases are unaffected by this change.</p>
  1757. <h1 id="upgrading-to-v1370"><a class="header" href="#upgrading-to-v1370">Upgrading to v1.37.0</a></h1>
  1758. <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>
  1759. <p>The current spam checker interface is deprecated in favour of a new generic modules system.
  1760. Authors of spam checker modules can refer to [this
  1761. documentation](modules/porting_legacy_module.md
  1762. to update their modules. Synapse administrators can refer to <a href="modules/index.html">this
  1763. documentation</a>
  1764. to update their configuration once the modules they are using have been updated.</p>
  1765. <p>We plan to remove support for the current spam checker interface in August 2021.</p>
  1766. <p>More module interfaces will be ported over to this new generic system in future versions
  1767. of Synapse.</p>
  1768. <h1 id="upgrading-to-v1340"><a class="header" href="#upgrading-to-v1340">Upgrading to v1.34.0</a></h1>
  1769. <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>
  1770. <p>The <code>room_invite_state_types</code> configuration setting has been deprecated
  1771. 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
  1772. file</a>.</p>
  1773. <p>If you have set <code>room_invite_state_types</code> to the default value you
  1774. should simply remove it from your configuration file. The default value
  1775. used to be:</p>
  1776. <pre><code class="language-yaml">room_invite_state_types:
  1777. - &quot;m.room.join_rules&quot;
  1778. - &quot;m.room.canonical_alias&quot;
  1779. - &quot;m.room.avatar&quot;
  1780. - &quot;m.room.encryption&quot;
  1781. - &quot;m.room.name&quot;
  1782. </code></pre>
  1783. <p>If you have customised this value, you should remove
  1784. <code>room_invite_state_types</code> and configure <code>room_prejoin_state</code> instead.</p>
  1785. <h1 id="upgrading-to-v1330"><a class="header" href="#upgrading-to-v1330">Upgrading to v1.33.0</a></h1>
  1786. <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>
  1787. <p>This may affect you if you have enabled the account validity feature,
  1788. and have made use of a custom HTML template specified by the
  1789. <code>account_validity.template_dir</code> or
  1790. <code>account_validity.account_renewed_html_path</code> Synapse config options.</p>
  1791. <p>The template can now accept an <code>expiration_ts</code> variable, which
  1792. represents the unix timestamp in milliseconds for the future date of
  1793. 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
  1794. template</a>
  1795. for an example of usage.</p>
  1796. <p>ALso note that a new HTML template, <code>account_previously_renewed.html</code>,
  1797. has been added. This is is shown to users when they attempt to renew
  1798. their account with a valid renewal token that has already been used
  1799. before. The default template contents can been found
  1800. <a href="https://github.com/matrix-org/synapse/blob/release-v1.33.0/synapse/res/templates/account_previously_renewed.html">here</a>,
  1801. and can also accept an <code>expiration_ts</code> variable. This template replaces
  1802. the error message users would previously see upon attempting to use a
  1803. valid renewal token more than once.</p>
  1804. <h1 id="upgrading-to-v1320"><a class="header" href="#upgrading-to-v1320">Upgrading to v1.32.0</a></h1>
  1805. <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>
  1806. <p>This release introduces <a href="https://github.com/matrix-org/synapse/issues/9853">a
  1807. regression</a> that can
  1808. overwhelm connected Prometheus instances. This issue is not present in
  1809. Synapse v1.32.0rc1.</p>
  1810. <p>If you have been affected, please downgrade to 1.31.0. You then may need
  1811. to remove excess writeahead logs in order for Prometheus to recover.
  1812. Instructions for doing so are provided
  1813. <a href="https://github.com/matrix-org/synapse/pull/9854#issuecomment-823472183">here</a>.</p>
  1814. <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>
  1815. <p>In line with our <a href="deprecation_policy.html">deprecation policy</a>,
  1816. we've dropped support for Python 3.5 and PostgreSQL 9.5, as they are no
  1817. longer supported upstream.</p>
  1818. <p>This release of Synapse requires Python 3.6+ and PostgresSQL 9.6+ or
  1819. SQLite 3.22+.</p>
  1820. <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>
  1821. <p>The deprecated v1 &quot;list accounts&quot; admin API
  1822. (<code>GET /_synapse/admin/v1/users/&lt;user_id&gt;</code>) has been removed in this
  1823. version.</p>
  1824. <p>The <a href="admin_api/user_admin_api.html#list-accounts">v2 list accounts API</a>
  1825. has been available since Synapse 1.7.0 (2019-12-13), and is accessible
  1826. under <code>GET /_synapse/admin/v2/users</code>.</p>
  1827. <p>The deprecation of the old endpoint was announced with Synapse 1.28.0
  1828. (released on 2021-02-25).</p>
  1829. <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>
  1830. <p>In compliance with the <a href="https://matrix.org/docs/spec/application_service/r0.1.2#server-admin-style-permissions">Application Service
  1831. spec</a>,
  1832. Application Services are now required to use the
  1833. <code>m.login.application_service</code> type when registering users via the
  1834. <code>/_matrix/client/r0/register</code> endpoint. This behaviour was deprecated in
  1835. Synapse v1.30.0.</p>
  1836. <p>Please ensure your Application Services are up to date.</p>
  1837. <h1 id="upgrading-to-v1290"><a class="header" href="#upgrading-to-v1290">Upgrading to v1.29.0</a></h1>
  1838. <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>
  1839. <p>When using Synapse with a reverse proxy (in particular, when using the
  1840. <code>x_forwarded</code> option on an HTTP listener), Synapse now
  1841. expects to receive an <code>X-Forwarded-Proto</code> header on incoming
  1842. HTTP requests. If it is not set, Synapse will log a warning on each
  1843. received request.</p>
  1844. <p>To avoid the warning, administrators using a reverse proxy should ensure
  1845. that the reverse proxy sets <code>X-Forwarded-Proto</code> header to
  1846. <code>https</code> or <code>http</code> to indicate the protocol used
  1847. by the client.</p>
  1848. <p>Synapse also requires the <code>Host</code> header to be preserved.</p>
  1849. <p>See the <a href="reverse_proxy.html">reverse proxy documentation</a>, where the
  1850. example configurations have been updated to show how to set these
  1851. headers.</p>
  1852. <p>(Users of <a href="https://caddyserver.com/">Caddy</a> are unaffected, since we
  1853. believe it sets <code>X-Forwarded-Proto</code> by default.)</p>
  1854. <h1 id="upgrading-to-v1270"><a class="header" href="#upgrading-to-v1270">Upgrading to v1.27.0</a></h1>
  1855. <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>
  1856. <p>This version changes the URI used for callbacks from OAuth2 and SAML2
  1857. identity providers:</p>
  1858. <ul>
  1859. <li>
  1860. <p>If your server is configured for single sign-on via an OpenID
  1861. Connect or OAuth2 identity provider, you will need to add
  1862. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> to the list
  1863. of permitted &quot;redirect URIs&quot; at the identity provider.</p>
  1864. <p>See the <a href="openid.html">OpenID docs</a> for more information on setting
  1865. up OpenID Connect.</p>
  1866. </li>
  1867. <li>
  1868. <p>If your server is configured for single sign-on via a SAML2 identity
  1869. provider, you will need to add
  1870. <code>[synapse public baseurl]/_synapse/client/saml2/authn_response</code> as a
  1871. permitted &quot;ACS location&quot; (also known as &quot;allowed callback URLs&quot;)
  1872. at the identity provider.</p>
  1873. <p>The &quot;Issuer&quot; in the &quot;AuthnRequest&quot; to the SAML2 identity
  1874. provider is also updated to
  1875. <code>[synapse public baseurl]/_synapse/client/saml2/metadata.xml</code>. If
  1876. your SAML2 identity provider uses this property to validate or
  1877. otherwise identify Synapse, its configuration will need to be
  1878. updated to use the new URL. Alternatively you could create a new,
  1879. separate &quot;EntityDescriptor&quot; in your SAML2 identity provider with
  1880. the new URLs and leave the URLs in the existing &quot;EntityDescriptor&quot;
  1881. as they were.</p>
  1882. </li>
  1883. </ul>
  1884. <h2 id="changes-to-html-templates"><a class="header" href="#changes-to-html-templates">Changes to HTML templates</a></h2>
  1885. <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
  1886. autoescape</a>
  1887. enabled for files ending in <code>.html</code>, <code>.htm</code>, and <code>.xml</code>. If you have
  1888. customised these templates and see issues when viewing them you might
  1889. need to update them. It is expected that most configurations will need
  1890. no changes.</p>
  1891. <p>If you have customised the templates <em>names</em> for these templates, it is
  1892. recommended to verify they end in <code>.html</code> to ensure autoescape is
  1893. enabled.</p>
  1894. <p>The above applies to the following templates:</p>
  1895. <ul>
  1896. <li><code>add_threepid.html</code></li>
  1897. <li><code>add_threepid_failure.html</code></li>
  1898. <li><code>add_threepid_success.html</code></li>
  1899. <li><code>notice_expiry.html</code></li>
  1900. <li><code>notice_expiry.html</code></li>
  1901. <li><code>notif_mail.html</code> (which, by default, includes <code>room.html</code> and
  1902. <code>notif.html</code>)</li>
  1903. <li><code>password_reset.html</code></li>
  1904. <li><code>password_reset_confirmation.html</code></li>
  1905. <li><code>password_reset_failure.html</code></li>
  1906. <li><code>password_reset_success.html</code></li>
  1907. <li><code>registration.html</code></li>
  1908. <li><code>registration_failure.html</code></li>
  1909. <li><code>registration_success.html</code></li>
  1910. <li><code>sso_account_deactivated.html</code></li>
  1911. <li><code>sso_auth_bad_user.html</code></li>
  1912. <li><code>sso_auth_confirm.html</code></li>
  1913. <li><code>sso_auth_success.html</code></li>
  1914. <li><code>sso_error.html</code></li>
  1915. <li><code>sso_login_idp_picker.html</code></li>
  1916. <li><code>sso_redirect_confirm.html</code></li>
  1917. </ul>
  1918. <h1 id="upgrading-to-v1260"><a class="header" href="#upgrading-to-v1260">Upgrading to v1.26.0</a></h1>
  1919. <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>
  1920. <p>v1.26.0 includes a lot of large changes. If something problematic
  1921. occurs, you may want to roll-back to a previous version of Synapse.
  1922. Because v1.26.0 also includes a new database schema version, reverting
  1923. that version is also required alongside the generic rollback
  1924. instructions mentioned above. In short, to roll back to v1.25.0 you need
  1925. to:</p>
  1926. <ol>
  1927. <li>
  1928. <p>Stop the server</p>
  1929. </li>
  1930. <li>
  1931. <p>Decrease the schema version in the database:</p>
  1932. <pre><code class="language-sql">UPDATE schema_version SET version = 58;
  1933. </code></pre>
  1934. </li>
  1935. <li>
  1936. <p>Delete the ignored users &amp; chain cover data:</p>
  1937. <pre><code class="language-sql">DROP TABLE IF EXISTS ignored_users;
  1938. UPDATE rooms SET has_auth_chain_index = false;
  1939. </code></pre>
  1940. <p>For PostgreSQL run:</p>
  1941. <pre><code class="language-sql">TRUNCATE event_auth_chain_links;
  1942. TRUNCATE event_auth_chains;
  1943. </code></pre>
  1944. <p>For SQLite run:</p>
  1945. <pre><code class="language-sql">DELETE FROM event_auth_chain_links;
  1946. DELETE FROM event_auth_chains;
  1947. </code></pre>
  1948. </li>
  1949. <li>
  1950. <p>Mark the deltas as not run (so they will re-run on upgrade).</p>
  1951. <pre><code class="language-sql">DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/01ignored_user.py&quot;;
  1952. DELETE FROM applied_schema_deltas WHERE version = 59 AND file = &quot;59/06chain_cover_index.sql&quot;;
  1953. </code></pre>
  1954. </li>
  1955. <li>
  1956. <p>Downgrade Synapse by following the instructions for your
  1957. installation method in the &quot;Rolling back to older versions&quot;
  1958. section above.</p>
  1959. </li>
  1960. </ol>
  1961. <h1 id="upgrading-to-v1250"><a class="header" href="#upgrading-to-v1250">Upgrading to v1.25.0</a></h1>
  1962. <h2 id="last-release-supporting-python-35"><a class="header" href="#last-release-supporting-python-35">Last release supporting Python 3.5</a></h2>
  1963. <p>This is the last release of Synapse which guarantees support with Python
  1964. 3.5, which passed its upstream End of Life date several months ago.</p>
  1965. <p>We will attempt to maintain support through March 2021, but without
  1966. guarantees.</p>
  1967. <p>In the future, Synapse will follow upstream schedules for ending support
  1968. of older versions of Python and PostgreSQL. Please upgrade to at least
  1969. Python 3.6 and PostgreSQL 9.6 as soon as possible.</p>
  1970. <h2 id="blacklisting-ip-ranges"><a class="header" href="#blacklisting-ip-ranges">Blacklisting IP ranges</a></h2>
  1971. <p>Synapse v1.25.0 includes new settings, <code>ip_range_blacklist</code> and
  1972. <code>ip_range_whitelist</code>, for controlling outgoing requests from Synapse for
  1973. federation, identity servers, push, and for checking key validity for
  1974. third-party invite events. The previous setting,
  1975. <code>federation_ip_range_blacklist</code>, is deprecated. The new
  1976. <code>ip_range_blacklist</code> defaults to private IP ranges if it is not defined.</p>
  1977. <p>If you have never customised <code>federation_ip_range_blacklist</code> it is
  1978. recommended that you remove that setting.</p>
  1979. <p>If you have customised <code>federation_ip_range_blacklist</code> you should update
  1980. the setting name to <code>ip_range_blacklist</code>.</p>
  1981. <p>If you have a custom push server that is reached via private IP space
  1982. you may need to customise <code>ip_range_blacklist</code> or <code>ip_range_whitelist</code>.</p>
  1983. <h1 id="upgrading-to-v1240"><a class="header" href="#upgrading-to-v1240">Upgrading to v1.24.0</a></h1>
  1984. <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>
  1985. <p>This release allows the OpenID Connect mapping provider to perform
  1986. normalisation of the localpart of the Matrix ID. This allows for the
  1987. mapping provider to specify different algorithms, instead of the
  1988. <a href="https://matrix.org/docs/spec/appendices#mapping-from-other-character-sets">default
  1989. way</a>.</p>
  1990. <p>If your Synapse configuration uses a custom mapping provider
  1991. (<code>oidc_config.user_mapping_provider.module</code> is specified and
  1992. not equal to
  1993. <code>synapse.handlers.oidc_handler.JinjaOidcMappingProvider</code>)
  1994. then you <em>must</em> ensure that <code>map_user_attributes</code> of the
  1995. mapping provider performs some normalisation of the
  1996. <code>localpart</code> returned. To match previous behaviour you can
  1997. use the <code>map_username_to_mxid_localpart</code> function provided
  1998. by Synapse. An example is shown below:</p>
  1999. <pre><code class="language-python">from synapse.types import map_username_to_mxid_localpart
  2000. class MyMappingProvider:
  2001. def map_user_attributes(self, userinfo, token):
  2002. # ... your custom logic ...
  2003. sso_user_id = ...
  2004. localpart = map_username_to_mxid_localpart(sso_user_id)
  2005. return {&quot;localpart&quot;: localpart}
  2006. </code></pre>
  2007. <h2 id="removal-historical-synapse-admin-api"><a class="header" href="#removal-historical-synapse-admin-api">Removal historical Synapse Admin API</a></h2>
  2008. <p>Historically, the Synapse Admin API has been accessible under:</p>
  2009. <ul>
  2010. <li><code>/_matrix/client/api/v1/admin</code></li>
  2011. <li><code>/_matrix/client/unstable/admin</code></li>
  2012. <li><code>/_matrix/client/r0/admin</code></li>
  2013. <li><code>/_synapse/admin/v1</code></li>
  2014. </ul>
  2015. <p>The endpoints with <code>/_matrix/client/*</code> prefixes have been removed as of
  2016. v1.24.0. The Admin API is now only accessible under:</p>
  2017. <ul>
  2018. <li><code>/_synapse/admin/v1</code></li>
  2019. </ul>
  2020. <p>The only exception is the <code>/admin/whois</code> endpoint, which is
  2021. <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
  2022. API</a>.</p>
  2023. <p>The deprecation of the old endpoints was announced with Synapse 1.20.0
  2024. (released on 2020-09-22) and makes it easier for homeserver admins to
  2025. lock down external access to the Admin API endpoints.</p>
  2026. <h1 id="upgrading-to-v1230"><a class="header" href="#upgrading-to-v1230">Upgrading to v1.23.0</a></h1>
  2027. <h2 id="structured-logging-configuration-breaking-changes"><a class="header" href="#structured-logging-configuration-breaking-changes">Structured logging configuration breaking changes</a></h2>
  2028. <p>This release deprecates use of the <code>structured: true</code> logging
  2029. configuration for structured logging. If your logging configuration
  2030. contains <code>structured: true</code> then it should be modified based on the
  2031. <a href="structured_logging.html">structured logging documentation</a>.</p>
  2032. <p>The <code>structured</code> and <code>drains</code> logging options are now deprecated and
  2033. should be replaced by standard logging configuration of <code>handlers</code> and
  2034. <code>formatters</code>.</p>
  2035. <p>A future will release of Synapse will make using <code>structured: true</code> an
  2036. error.</p>
  2037. <h1 id="upgrading-to-v1220"><a class="header" href="#upgrading-to-v1220">Upgrading to v1.22.0</a></h1>
  2038. <h2 id="thirdpartyeventrules-breaking-changes"><a class="header" href="#thirdpartyeventrules-breaking-changes">ThirdPartyEventRules breaking changes</a></h2>
  2039. <p>This release introduces a backwards-incompatible change to modules
  2040. making use of <code>ThirdPartyEventRules</code> in Synapse. If you make use of a
  2041. module defined under the <code>third_party_event_rules</code> config option, please
  2042. make sure it is updated to handle the below change:</p>
  2043. <p>The <code>http_client</code> argument is no longer passed to modules as they are
  2044. initialised. Instead, modules are expected to make use of the
  2045. <code>http_client</code> property on the <code>ModuleApi</code> class. Modules are now passed
  2046. a <code>module_api</code> argument during initialisation, which is an instance of
  2047. <code>ModuleApi</code>. <code>ModuleApi</code> instances have a <code>http_client</code> property which
  2048. acts the same as the <code>http_client</code> argument previously passed to
  2049. <code>ThirdPartyEventRules</code> modules.</p>
  2050. <h1 id="upgrading-to-v1210"><a class="header" href="#upgrading-to-v1210">Upgrading to v1.21.0</a></h1>
  2051. <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>
  2052. <p>The <a href="reverse_proxy.html">reverse proxy documentation</a>
  2053. has been updated to include reverse proxy directives for
  2054. <code>/_synapse/client/*</code> endpoints. As the user password reset flow now uses
  2055. endpoints under this prefix, <strong>you must update your reverse proxy
  2056. configurations for user password reset to work</strong>.</p>
  2057. <p>Additionally, note that the <a href="workers.html">Synapse worker documentation</a> has been updated to</p>
  2058. <p>: state that the <code>/_synapse/client/password_reset/email/submit_token</code>
  2059. endpoint can be handled</p>
  2060. <p>by all workers. If you make use of Synapse's worker feature, please
  2061. update your reverse proxy configuration to reflect this change.</p>
  2062. <h2 id="new-html-templates"><a class="header" href="#new-html-templates">New HTML templates</a></h2>
  2063. <p>A new HTML template,
  2064. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/res/templates/password_reset_confirmation.html">password_reset_confirmation.html</a>,
  2065. has been added to the <code>synapse/res/templates</code> directory. If you are
  2066. using a custom template directory, you may want to copy the template
  2067. over and modify it.</p>
  2068. <p>Note that as of v1.20.0, templates do not need to be included in custom
  2069. template directories for Synapse to start. The default templates will be
  2070. used if a custom template cannot be found.</p>
  2071. <p>This page will appear to the user after clicking a password reset link
  2072. that has been emailed to them.</p>
  2073. <p>To complete password reset, the page must include a way to make a
  2074. <code>POST</code> request to
  2075. <code>/_synapse/client/password_reset/{medium}/submit_token</code> with the query
  2076. parameters from the original link, presented as a URL-encoded form. See
  2077. the file itself for more details.</p>
  2078. <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>
  2079. <p>The <code>saml_error.html</code> template was removed from Synapse and replaced
  2080. with the <code>sso_error.html</code> template. If your Synapse is configured to use
  2081. SAML and a custom <code>sso_redirect_confirm_template_dir</code> configuration then
  2082. any customisations of the <code>saml_error.html</code> template will need to be
  2083. merged into the <code>sso_error.html</code> template. These templates are similar,
  2084. but the parameters are slightly different:</p>
  2085. <ul>
  2086. <li>The <code>msg</code> parameter should be renamed to <code>error_description</code>.</li>
  2087. <li>There is no longer a <code>code</code> parameter for the response code.</li>
  2088. <li>A string <code>error</code> parameter is available that includes a short hint
  2089. of why a user is seeing the error page.</li>
  2090. </ul>
  2091. <h1 id="upgrading-to-v1180"><a class="header" href="#upgrading-to-v1180">Upgrading to v1.18.0</a></h1>
  2092. <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>
  2093. <p>From 10th August 2020, we will no longer publish Docker images with the
  2094. <code>-py3</code> tag suffix. The images tagged with the
  2095. <code>-py3</code> suffix have been identical to the non-suffixed tags
  2096. since release 0.99.0, and the suffix is obsolete.</p>
  2097. <p>On 10th August, we will remove the <code>latest-py3</code> tag.
  2098. Existing per-release tags (such as <code>v1.18.0-py3</code> will not
  2099. be removed, but no new <code>-py3</code> tags will be added.</p>
  2100. <p>Scripts relying on the <code>-py3</code> suffix will need to be
  2101. updated.</p>
  2102. <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>
  2103. <p>When setting up worker processes, we now recommend the use of a Redis
  2104. server for replication. <strong>The old direct TCP connection method is
  2105. deprecated and will be removed in a future release.</strong> See
  2106. <a href="workers.html">workers</a> for more details.</p>
  2107. <h1 id="upgrading-to-v1140"><a class="header" href="#upgrading-to-v1140">Upgrading to v1.14.0</a></h1>
  2108. <p>This version includes a database update which is run as part of the
  2109. upgrade, and which may take a couple of minutes in the case of a large
  2110. server. Synapse will not respond to HTTP requests while this update is
  2111. taking place.</p>
  2112. <h1 id="upgrading-to-v1130"><a class="header" href="#upgrading-to-v1130">Upgrading to v1.13.0</a></h1>
  2113. <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>
  2114. <p>A bug was introduced in Synapse 1.4.0 which could cause the room
  2115. directory to be incomplete or empty if Synapse was upgraded directly
  2116. from v1.2.1 or earlier, to versions between v1.4.0 and v1.12.x.</p>
  2117. <p>This will <em>not</em> be a problem for Synapse installations which were:</p>
  2118. <p>: - created at v1.4.0 or later,
  2119. - upgraded via v1.3.x, or
  2120. - upgraded straight from v1.2.1 or earlier to v1.13.0 or later.</p>
  2121. <p>If completeness of the room directory is a concern, installations which
  2122. are affected can be repaired as follows:</p>
  2123. <ol>
  2124. <li>
  2125. <p>Run the following sql from a <code>psql</code> or
  2126. <code>sqlite3</code> console:</p>
  2127. <pre><code class="language-sql">INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2128. ('populate_stats_process_rooms', '{}', 'current_state_events_membership');
  2129. INSERT INTO background_updates (update_name, progress_json, depends_on) VALUES
  2130. ('populate_stats_process_users', '{}', 'populate_stats_process_rooms');
  2131. </code></pre>
  2132. </li>
  2133. <li>
  2134. <p>Restart synapse.</p>
  2135. </li>
  2136. </ol>
  2137. <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>
  2138. <p>New templates (<code>sso_auth_confirm.html</code>, <code>sso_auth_success.html</code>, and
  2139. <code>sso_account_deactivated.html</code>) were added to Synapse. If your Synapse
  2140. is configured to use SSO and a custom
  2141. <code>sso_redirect_confirm_template_dir</code> configuration then these templates
  2142. will need to be copied from
  2143. <a href="synapse/res/templates">synapse/res/templates</a> into that directory.</p>
  2144. <h2 id="synapse-sso-plugins-method-deprecation"><a class="header" href="#synapse-sso-plugins-method-deprecation">Synapse SSO Plugins Method Deprecation</a></h2>
  2145. <p>Plugins using the <code>complete_sso_login</code> method of
  2146. <code>synapse.module_api.ModuleApi</code> should update to using the async/await
  2147. version <code>complete_sso_login_async</code> which includes additional checks. The
  2148. non-async version is considered deprecated.</p>
  2149. <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>
  2150. <p>v1.13.0 includes a lot of large changes. If something problematic
  2151. occurs, you may want to roll-back to a previous version of Synapse.
  2152. Because v1.13.0 also includes a new database schema version, reverting
  2153. that version is also required alongside the generic rollback
  2154. instructions mentioned above. In short, to roll back to v1.12.4 you need
  2155. to:</p>
  2156. <ol>
  2157. <li>
  2158. <p>Stop the server</p>
  2159. </li>
  2160. <li>
  2161. <p>Decrease the schema version in the database:</p>
  2162. <pre><code class="language-sql">UPDATE schema_version SET version = 57;
  2163. </code></pre>
  2164. </li>
  2165. <li>
  2166. <p>Downgrade Synapse by following the instructions for your
  2167. installation method in the &quot;Rolling back to older versions&quot;
  2168. section above.</p>
  2169. </li>
  2170. </ol>
  2171. <h1 id="upgrading-to-v1120"><a class="header" href="#upgrading-to-v1120">Upgrading to v1.12.0</a></h1>
  2172. <p>This version includes a database update which is run as part of the
  2173. upgrade, and which may take some time (several hours in the case of a
  2174. large server). Synapse will not respond to HTTP requests while this
  2175. update is taking place.</p>
  2176. <p>This is only likely to be a problem in the case of a server which is
  2177. participating in many rooms.</p>
  2178. <ol start="0">
  2179. <li>
  2180. <p>As with all upgrades, it is recommended that you have a recent
  2181. backup of your database which can be used for recovery in the event
  2182. of any problems.</p>
  2183. </li>
  2184. <li>
  2185. <p>As an initial check to see if you will be affected, you can try
  2186. running the following query from the <code>psql</code> or
  2187. <code>sqlite3</code> console. It is safe to run it while Synapse is
  2188. still running.</p>
  2189. <pre><code class="language-sql">SELECT MAX(q.v) FROM (
  2190. SELECT (
  2191. SELECT ej.json AS v
  2192. FROM state_events se INNER JOIN event_json ej USING (event_id)
  2193. WHERE se.room_id=rooms.room_id AND se.type='m.room.create' AND se.state_key=''
  2194. LIMIT 1
  2195. ) FROM rooms WHERE rooms.room_version IS NULL
  2196. ) q;
  2197. </code></pre>
  2198. <p>This query will take about the same amount of time as the upgrade
  2199. process: ie, if it takes 5 minutes, then it is likely that Synapse
  2200. will be unresponsive for 5 minutes during the upgrade.</p>
  2201. <p>If you consider an outage of this duration to be acceptable, no
  2202. further action is necessary and you can simply start Synapse 1.12.0.</p>
  2203. <p>If you would prefer to reduce the downtime, continue with the steps
  2204. below.</p>
  2205. </li>
  2206. <li>
  2207. <p>The easiest workaround for this issue is to manually create a new
  2208. index before upgrading. On PostgreSQL, his can be done as follows:</p>
  2209. <pre><code class="language-sql">CREATE INDEX CONCURRENTLY tmp_upgrade_1_12_0_index
  2210. ON state_events(room_id) WHERE type = 'm.room.create';
  2211. </code></pre>
  2212. <p>The above query may take some time, but is also safe to run while
  2213. Synapse is running.</p>
  2214. <p>We assume that no SQLite users have databases large enough to be
  2215. affected. If you <em>are</em> affected, you can run a similar query,
  2216. omitting the <code>CONCURRENTLY</code> keyword. Note however that this
  2217. operation may in itself cause Synapse to stop running for some time.
  2218. Synapse admins are reminded that <a href="postgres.html">SQLite is not recommended for use
  2219. outside a test environment</a>.</p>
  2220. </li>
  2221. <li>
  2222. <p>Once the index has been created, the <code>SELECT</code> query in step 1 above
  2223. should complete quickly. It is therefore safe to upgrade to Synapse
  2224. 1.12.0.</p>
  2225. </li>
  2226. <li>
  2227. <p>Once Synapse 1.12.0 has successfully started and is responding to
  2228. HTTP requests, the temporary index can be removed:</p>
  2229. <pre><code class="language-sql">DROP INDEX tmp_upgrade_1_12_0_index;
  2230. </code></pre>
  2231. </li>
  2232. </ol>
  2233. <h1 id="upgrading-to-v1100"><a class="header" href="#upgrading-to-v1100">Upgrading to v1.10.0</a></h1>
  2234. <p>Synapse will now log a warning on start up if used with a PostgreSQL
  2235. database that has a non-recommended locale set.</p>
  2236. <p>See <a href="postgres.html">Postgres</a> for details.</p>
  2237. <h1 id="upgrading-to-v180"><a class="header" href="#upgrading-to-v180">Upgrading to v1.8.0</a></h1>
  2238. <p>Specifying a <code>log_file</code> config option will now cause Synapse to refuse
  2239. to start, and should be replaced by with the <code>log_config</code> option.
  2240. Support for the <code>log_file</code> option was removed in v1.3.0 and has since
  2241. had no effect.</p>
  2242. <h1 id="upgrading-to-v170"><a class="header" href="#upgrading-to-v170">Upgrading to v1.7.0</a></h1>
  2243. <p>In an attempt to configure Synapse in a privacy preserving way, the
  2244. default behaviours of <code>allow_public_rooms_without_auth</code> and
  2245. <code>allow_public_rooms_over_federation</code> have been inverted. This means that
  2246. by default, only authenticated users querying the Client/Server API will
  2247. be able to query the room directory, and relatedly that the server will
  2248. not share room directory information with other servers over federation.</p>
  2249. <p>If your installation does not explicitly set these settings one way or
  2250. the other and you want either setting to be <code>true</code> then it will
  2251. necessary to update your homeserver configuration file accordingly.</p>
  2252. <p>For more details on the surrounding context see our
  2253. <a href="https://matrix.org/blog/2019/11/09/avoiding-unwelcome-visitors-on-private-matrix-servers">explainer</a>.</p>
  2254. <h1 id="upgrading-to-v150"><a class="header" href="#upgrading-to-v150">Upgrading to v1.5.0</a></h1>
  2255. <p>This release includes a database migration which may take several
  2256. minutes to complete if there are a large number (more than a million or
  2257. so) of entries in the <code>devices</code> table. This is only likely to a be a
  2258. problem on very large installations.</p>
  2259. <h1 id="upgrading-to-v140"><a class="header" href="#upgrading-to-v140">Upgrading to v1.4.0</a></h1>
  2260. <h2 id="new-custom-templates"><a class="header" href="#new-custom-templates">New custom templates</a></h2>
  2261. <p>If you have configured a custom template directory with the
  2262. <code>email.template_dir</code> option, be aware that there are new templates
  2263. regarding registration and threepid management (see below) that must be
  2264. included.</p>
  2265. <ul>
  2266. <li><code>registration.html</code> and <code>registration.txt</code></li>
  2267. <li><code>registration_success.html</code> and <code>registration_failure.html</code></li>
  2268. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code></li>
  2269. <li><code>add_threepid_failure.html</code> and <code>add_threepid_success.html</code></li>
  2270. </ul>
  2271. <p>Synapse will expect these files to exist inside the configured template
  2272. directory, and <strong>will fail to start</strong> if they are absent. To view the
  2273. default templates, see
  2274. <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">synapse/res/templates</a>.</p>
  2275. <h2 id="3pid-verification-changes"><a class="header" href="#3pid-verification-changes">3pid verification changes</a></h2>
  2276. <p><strong>Note: As of this release, users will be unable to add phone numbers or
  2277. email addresses to their accounts, without changes to the Synapse
  2278. configuration. This includes adding an email address during
  2279. registration.</strong></p>
  2280. <p>It is possible for a user to associate an email address or phone number
  2281. with their account, for a number of reasons:</p>
  2282. <ul>
  2283. <li>for use when logging in, as an alternative to the user id.</li>
  2284. <li>in the case of email, as an alternative contact to help with account
  2285. recovery.</li>
  2286. <li>in the case of email, to receive notifications of missed messages.</li>
  2287. </ul>
  2288. <p>Before an email address or phone number can be added to a user's
  2289. account, or before such an address is used to carry out a
  2290. password-reset, Synapse must confirm the operation with the owner of the
  2291. email address or phone number. It does this by sending an email or text
  2292. giving the user a link or token to confirm receipt. This process is
  2293. known as '3pid verification'. ('3pid', or 'threepid', stands for
  2294. third-party identifier, and we use it to refer to external identifiers
  2295. such as email addresses and phone numbers.)</p>
  2296. <p>Previous versions of Synapse delegated the task of 3pid verification to
  2297. an identity server by default. In most cases this server is <code>vector.im</code>
  2298. or <code>matrix.org</code>.</p>
  2299. <p>In Synapse 1.4.0, for security and privacy reasons, the homeserver will
  2300. no longer delegate this task to an identity server by default. Instead,
  2301. the server administrator will need to explicitly decide how they would
  2302. like the verification messages to be sent.</p>
  2303. <p>In the medium term, the <code>vector.im</code> and <code>matrix.org</code> identity servers
  2304. will disable support for delegated 3pid verification entirely. However,
  2305. in order to ease the transition, they will retain the capability for a
  2306. limited period. Delegated email verification will be disabled on Monday
  2307. 2nd December 2019 (giving roughly 2 months notice). Disabling delegated
  2308. SMS verification will follow some time after that once SMS verification
  2309. support lands in Synapse.</p>
  2310. <p>Once delegated 3pid verification support has been disabled in the
  2311. <code>vector.im</code> and <code>matrix.org</code> identity servers, all Synapse versions that
  2312. depend on those instances will be unable to verify email and phone
  2313. numbers through them. There are no imminent plans to remove delegated
  2314. 3pid verification from Sydent generally. (Sydent is the identity server
  2315. project that backs the <code>vector.im</code> and <code>matrix.org</code> instances).</p>
  2316. <h3 id="email-1"><a class="header" href="#email-1">Email</a></h3>
  2317. <p>Following upgrade, to continue verifying email (e.g. as part of the
  2318. registration process), admins can either:-</p>
  2319. <ul>
  2320. <li>Configure Synapse to use an email server.</li>
  2321. <li>Run or choose an identity server which allows delegated email
  2322. verification and delegate to it.</li>
  2323. </ul>
  2324. <h4 id="configure-smtp-in-synapse"><a class="header" href="#configure-smtp-in-synapse">Configure SMTP in Synapse</a></h4>
  2325. <p>To configure an SMTP server for Synapse, modify the configuration
  2326. section headed <code>email</code>, and be sure to have at least the
  2327. <code>smtp_host, smtp_port</code> and <code>notif_from</code> fields filled out.</p>
  2328. <p>You may also need to set <code>smtp_user</code>, <code>smtp_pass</code>, and
  2329. <code>require_transport_security</code>.</p>
  2330. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2331. for more details on these settings.</p>
  2332. <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>
  2333. <p>Some admins will wish to continue using email verification as part of
  2334. the registration process, but will not immediately have an appropriate
  2335. SMTP server at hand.</p>
  2336. <p>To this end, we will continue to support email verification delegation
  2337. via the <code>vector.im</code> and <code>matrix.org</code> identity servers for two months.
  2338. Support for delegated email verification will be disabled on Monday 2nd
  2339. December.</p>
  2340. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  2341. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  2342. server</a>) to handle
  2343. sending confirmation messages via email and SMS.</p>
  2344. <p>So to delegate email verification, in <code>homeserver.yaml</code>, set
  2345. <code>account_threepid_delegates.email</code> to the base URL of an identity
  2346. server. For example:</p>
  2347. <pre><code class="language-yaml">account_threepid_delegates:
  2348. email: https://example.com # Delegate email sending to example.com
  2349. </code></pre>
  2350. <p>Note that <code>account_threepid_delegates.email</code> replaces the deprecated
  2351. <code>email.trust_identity_server_for_password_resets</code>: if
  2352. <code>email.trust_identity_server_for_password_resets</code> is set to <code>true</code>, and
  2353. <code>account_threepid_delegates.email</code> is not set, then the first entry in
  2354. <code>trusted_third_party_id_servers</code> will be used as the
  2355. <code>account_threepid_delegate</code> for email. This is to ensure compatibility
  2356. with existing Synapse installs that set up external server handling for
  2357. these tasks before v1.4.0. If
  2358. <code>email.trust_identity_server_for_password_resets</code> is <code>true</code> and no
  2359. trusted identity server domains are configured, Synapse will report an
  2360. error and refuse to start.</p>
  2361. <p>If <code>email.trust_identity_server_for_password_resets</code> is <code>false</code> or
  2362. absent and no <code>email</code> delegate is configured in
  2363. <code>account_threepid_delegates</code>, then Synapse will send email verification
  2364. messages itself, using the configured SMTP server (see above). that
  2365. type.</p>
  2366. <h3 id="phone-numbers"><a class="header" href="#phone-numbers">Phone numbers</a></h3>
  2367. <p>Synapse does not support phone-number verification itself, so the only
  2368. way to maintain the ability for users to add phone numbers to their
  2369. accounts will be by continuing to delegate phone number verification to
  2370. the <code>matrix.org</code> and <code>vector.im</code> identity servers (or another identity
  2371. server that supports SMS sending).</p>
  2372. <p>The <code>account_threepid_delegates</code> dictionary defines whether the
  2373. homeserver should delegate an external server (typically an <a href="https://matrix.org/docs/spec/identity_service/r0.2.1">identity
  2374. server</a>) to handle
  2375. sending confirmation messages via email and SMS.</p>
  2376. <p>So to delegate phone number verification, in <code>homeserver.yaml</code>, set
  2377. <code>account_threepid_delegates.msisdn</code> to the base URL of an identity
  2378. server. For example:</p>
  2379. <pre><code class="language-yaml">account_threepid_delegates:
  2380. msisdn: https://example.com # Delegate sms sending to example.com
  2381. </code></pre>
  2382. <p>The <code>matrix.org</code> and <code>vector.im</code> identity servers will continue to
  2383. support delegated phone number verification via SMS until such time as
  2384. it is possible for admins to configure their servers to perform phone
  2385. number verification directly. More details will follow in a future
  2386. release.</p>
  2387. <h2 id="rolling-back-to-v131"><a class="header" href="#rolling-back-to-v131">Rolling back to v1.3.1</a></h2>
  2388. <p>If you encounter problems with v1.4.0, it should be possible to roll
  2389. back to v1.3.1, subject to the following:</p>
  2390. <ul>
  2391. <li>
  2392. <p>The 'room statistics' engine was heavily reworked in this release
  2393. (see <a href="https://github.com/matrix-org/synapse/pull/5971">#5971</a>),
  2394. including significant changes to the database schema, which are not
  2395. easily reverted. This will cause the room statistics engine to stop
  2396. updating when you downgrade.</p>
  2397. <p>The room statistics are essentially unused in v1.3.1 (in future
  2398. versions of Synapse, they will be used to populate the room
  2399. directory), so there should be no loss of functionality. However,
  2400. the statistics engine will write errors to the logs, which can be
  2401. avoided by setting the following in <code>homeserver.yaml</code>:</p>
  2402. <pre><code class="language-yaml">stats:
  2403. enabled: false
  2404. </code></pre>
  2405. <p>Don't forget to re-enable it when you upgrade again, in preparation
  2406. for its use in the room directory!</p>
  2407. </li>
  2408. </ul>
  2409. <h1 id="upgrading-to-v120"><a class="header" href="#upgrading-to-v120">Upgrading to v1.2.0</a></h1>
  2410. <p>Some counter metrics have been renamed, with the old names deprecated.
  2411. See <a href="metrics-howto.html#renaming-of-metrics--deprecation-of-old-names-in-12">the metrics
  2412. documentation</a>
  2413. for details.</p>
  2414. <h1 id="upgrading-to-v110"><a class="header" href="#upgrading-to-v110">Upgrading to v1.1.0</a></h1>
  2415. <p>Synapse v1.1.0 removes support for older Python and PostgreSQL versions,
  2416. as outlined in <a href="https://matrix.org/blog/2019/04/08/synapse-deprecating-postgres-9-4-and-python-2-x">our deprecation
  2417. notice</a>.</p>
  2418. <h2 id="minimum-python-version"><a class="header" href="#minimum-python-version">Minimum Python Version</a></h2>
  2419. <p>Synapse v1.1.0 has a minimum Python requirement of Python 3.5. Python
  2420. 3.6 or Python 3.7 are recommended as they have improved internal string
  2421. handling, significantly reducing memory usage.</p>
  2422. <p>If you use current versions of the Matrix.org-distributed Debian
  2423. packages or Docker images, action is not required.</p>
  2424. <p>If you install Synapse in a Python virtual environment, please see
  2425. &quot;Upgrading to v0.34.0&quot; for notes on setting up a new virtualenv under
  2426. Python 3.</p>
  2427. <h2 id="minimum-postgresql-version"><a class="header" href="#minimum-postgresql-version">Minimum PostgreSQL Version</a></h2>
  2428. <p>If using PostgreSQL under Synapse, you will need to use PostgreSQL 9.5
  2429. or above. Please see the <a href="https://www.postgresql.org/docs/11/upgrading.html">PostgreSQL
  2430. documentation</a> for
  2431. more details on upgrading your database.</p>
  2432. <h1 id="upgrading-to-v10"><a class="header" href="#upgrading-to-v10">Upgrading to v1.0</a></h1>
  2433. <h2 id="validation-of-tls-certificates"><a class="header" href="#validation-of-tls-certificates">Validation of TLS certificates</a></h2>
  2434. <p>Synapse v1.0 is the first release to enforce validation of TLS
  2435. certificates for the federation API. It is therefore essential that your
  2436. certificates are correctly configured.</p>
  2437. <p>Note, v1.0 installations will also no longer be able to federate with
  2438. servers that have not correctly configured their certificates.</p>
  2439. <p>In rare cases, it may be desirable to disable certificate checking: for
  2440. example, it might be essential to be able to federate with a given
  2441. legacy server in a closed federation. This can be done in one of two
  2442. ways:-</p>
  2443. <ul>
  2444. <li>Configure the global switch <code>federation_verify_certificates</code> to
  2445. <code>false</code>.</li>
  2446. <li>Configure a whitelist of server domains to trust via
  2447. <code>federation_certificate_verification_whitelist</code>.</li>
  2448. </ul>
  2449. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2450. for more details on these settings.</p>
  2451. <h2 id="email-2"><a class="header" href="#email-2">Email</a></h2>
  2452. <p>When a user requests a password reset, Synapse will send an email to the
  2453. user to confirm the request.</p>
  2454. <p>Previous versions of Synapse delegated the job of sending this email to
  2455. an identity server. If the identity server was somehow malicious or
  2456. became compromised, it would be theoretically possible to hijack an
  2457. account through this means.</p>
  2458. <p>Therefore, by default, Synapse v1.0 will send the confirmation email
  2459. itself. If Synapse is not configured with an SMTP server, password reset
  2460. via email will be disabled.</p>
  2461. <p>To configure an SMTP server for Synapse, modify the configuration
  2462. section headed <code>email</code>, and be sure to have at least the <code>smtp_host</code>,
  2463. <code>smtp_port</code> and <code>notif_from</code> fields filled out. You may also need to set
  2464. <code>smtp_user</code>, <code>smtp_pass</code>, and <code>require_transport_security</code>.</p>
  2465. <p>If you are absolutely certain that you wish to continue using an
  2466. identity server for password resets, set
  2467. <code>trust_identity_server_for_password_resets</code> to <code>true</code>.</p>
  2468. <p>See the <a href="usage/configuration/homeserver_sample_config.html">sample configuration file</a>
  2469. for more details on these settings.</p>
  2470. <h2 id="new-email-templates"><a class="header" href="#new-email-templates">New email templates</a></h2>
  2471. <p>Some new templates have been added to the default template directory for the purpose of
  2472. the homeserver sending its own password reset emails. If you have configured a
  2473. custom <code>template_dir</code> in your Synapse config, these files will need to be added.</p>
  2474. <p><code>password_reset.html</code> and <code>password_reset.txt</code> are HTML and plain text
  2475. templates respectively that contain the contents of what will be emailed
  2476. to the user upon attempting to reset their password via email.
  2477. <code>password_reset_success.html</code> and <code>password_reset_failure.html</code> are HTML
  2478. files that the content of which (assuming no redirect URL is set) will
  2479. be shown to the user after they attempt to click the link in the email
  2480. sent to them.</p>
  2481. <h1 id="upgrading-to-v0990"><a class="header" href="#upgrading-to-v0990">Upgrading to v0.99.0</a></h1>
  2482. <p>Please be aware that, before Synapse v1.0 is released around March 2019,
  2483. you will need to replace any self-signed certificates with those
  2484. verified by a root CA. Information on how to do so can be found at the
  2485. ACME docs.</p>
  2486. <h1 id="upgrading-to-v0340"><a class="header" href="#upgrading-to-v0340">Upgrading to v0.34.0</a></h1>
  2487. <ol>
  2488. <li>
  2489. <p>This release is the first to fully support Python 3. Synapse will
  2490. now run on Python versions 3.5, or 3.6 (as well as 2.7). We
  2491. recommend switching to Python 3, as it has been shown to give
  2492. performance improvements.</p>
  2493. <p>For users who have installed Synapse into a virtualenv, we recommend
  2494. doing this by creating a new virtualenv. For example:</p>
  2495. <pre><code class="language-sh">virtualenv -p python3 ~/synapse/env3
  2496. source ~/synapse/env3/bin/activate
  2497. pip install matrix-synapse
  2498. </code></pre>
  2499. <p>You can then start synapse as normal, having activated the new
  2500. virtualenv:</p>
  2501. <pre><code class="language-sh">cd ~/synapse
  2502. source env3/bin/activate
  2503. synctl start
  2504. </code></pre>
  2505. <p>Users who have installed from distribution packages should see the
  2506. relevant package documentation. See below for notes on Debian
  2507. packages.</p>
  2508. <ul>
  2509. <li>
  2510. <p>When upgrading to Python 3, you <strong>must</strong> make sure that your log
  2511. files are configured as UTF-8, by adding <code>encoding: utf8</code> to the
  2512. <code>RotatingFileHandler</code> configuration (if you have one) in your
  2513. <code>&lt;server&gt;.log.config</code> file. For example, if your <code>log.config</code>
  2514. file contains:</p>
  2515. <pre><code class="language-yaml">handlers:
  2516. file:
  2517. class: logging.handlers.RotatingFileHandler
  2518. formatter: precise
  2519. filename: homeserver.log
  2520. maxBytes: 104857600
  2521. backupCount: 10
  2522. filters: [context]
  2523. console:
  2524. class: logging.StreamHandler
  2525. formatter: precise
  2526. filters: [context]
  2527. </code></pre>
  2528. <p>Then you should update this to be:</p>
  2529. <pre><code class="language-yaml">handlers:
  2530. file:
  2531. class: logging.handlers.RotatingFileHandler
  2532. formatter: precise
  2533. filename: homeserver.log
  2534. maxBytes: 104857600
  2535. backupCount: 10
  2536. filters: [context]
  2537. encoding: utf8
  2538. console:
  2539. class: logging.StreamHandler
  2540. formatter: precise
  2541. filters: [context]
  2542. </code></pre>
  2543. <p>There is no need to revert this change if downgrading to
  2544. Python 2.</p>
  2545. </li>
  2546. </ul>
  2547. <p>We are also making available Debian packages which will run Synapse
  2548. on Python 3. You can switch to these packages with
  2549. <code>apt-get install matrix-synapse-py3</code>, however, please read
  2550. <a href="https://github.com/matrix-org/synapse/blob/release-v0.34.0/debian/NEWS">debian/NEWS</a>
  2551. before doing so. The existing <code>matrix-synapse</code> packages will
  2552. continue to use Python 2 for the time being.</p>
  2553. </li>
  2554. <li>
  2555. <p>This release removes the <code>riot.im</code> from the default list of trusted
  2556. identity servers.</p>
  2557. <p>If <code>riot.im</code> is in your homeserver's list of
  2558. <code>trusted_third_party_id_servers</code>, you should remove it. It was added
  2559. in case a hypothetical future identity server was put there. If you
  2560. don't remove it, users may be unable to deactivate their accounts.</p>
  2561. </li>
  2562. <li>
  2563. <p>This release no longer installs the (unmaintained) Matrix Console
  2564. web client as part of the default installation. It is possible to
  2565. re-enable it by installing it separately and setting the
  2566. <code>web_client_location</code> config option, but please consider switching
  2567. to another client.</p>
  2568. </li>
  2569. </ol>
  2570. <h1 id="upgrading-to-v0337"><a class="header" href="#upgrading-to-v0337">Upgrading to v0.33.7</a></h1>
  2571. <p>This release removes the example email notification templates from
  2572. <code>res/templates</code> (they are now internal to the python package). This
  2573. should only affect you if you (a) deploy your Synapse instance from a
  2574. git checkout or a github snapshot URL, and (b) have email notifications
  2575. enabled.</p>
  2576. <p>If you have email notifications enabled, you should ensure that
  2577. <code>email.template_dir</code> is either configured to point at a directory where
  2578. you have installed customised templates, or leave it unset to use the
  2579. default templates.</p>
  2580. <h1 id="upgrading-to-v0273"><a class="header" href="#upgrading-to-v0273">Upgrading to v0.27.3</a></h1>
  2581. <p>This release expands the anonymous usage stats sent if the opt-in
  2582. <code>report_stats</code> configuration is set to <code>true</code>. We now capture RSS memory
  2583. and cpu use at a very coarse level. This requires administrators to
  2584. install the optional <code>psutil</code> python module.</p>
  2585. <p>We would appreciate it if you could assist by ensuring this module is
  2586. available and <code>report_stats</code> is enabled. This will let us see if
  2587. performance changes to synapse are having an impact to the general
  2588. community.</p>
  2589. <h1 id="upgrading-to-v0150"><a class="header" href="#upgrading-to-v0150">Upgrading to v0.15.0</a></h1>
  2590. <p>If you want to use the new URL previewing API
  2591. (<code>/_matrix/media/r0/preview_url</code>) then you have to explicitly enable it
  2592. in the config and update your dependencies dependencies. See README.rst
  2593. for details.</p>
  2594. <h1 id="upgrading-to-v0110"><a class="header" href="#upgrading-to-v0110">Upgrading to v0.11.0</a></h1>
  2595. <p>This release includes the option to send anonymous usage stats to
  2596. matrix.org, and requires that administrators explictly opt in or out by
  2597. setting the <code>report_stats</code> option to either <code>true</code> or <code>false</code>.</p>
  2598. <p>We would really appreciate it if you could help our project out by
  2599. reporting anonymized usage statistics from your homeserver. Only very
  2600. basic aggregate data (e.g. number of users) will be reported, but it
  2601. helps us to track the growth of the Matrix community, and helps us to
  2602. make Matrix a success, as well as to convince other networks that they
  2603. should peer with us.</p>
  2604. <h1 id="upgrading-to-v090"><a class="header" href="#upgrading-to-v090">Upgrading to v0.9.0</a></h1>
  2605. <p>Application services have had a breaking API change in this version.</p>
  2606. <p>They can no longer register themselves with a home server using the AS
  2607. HTTP API. This decision was made because a compromised application
  2608. service with free reign to register any regex in effect grants full
  2609. read/write access to the home server if a regex of <code>.*</code> is used. An
  2610. attack where a compromised AS re-registers itself with <code>.*</code> was deemed
  2611. too big of a security risk to ignore, and so the ability to register
  2612. with the HS remotely has been removed.</p>
  2613. <p>It has been replaced by specifying a list of application service
  2614. registrations in <code>homeserver.yaml</code>:</p>
  2615. <pre><code class="language-yaml">app_service_config_files: [&quot;registration-01.yaml&quot;, &quot;registration-02.yaml&quot;]
  2616. </code></pre>
  2617. <p>Where <code>registration-01.yaml</code> looks like:</p>
  2618. <pre><code class="language-yaml">url: &lt;String&gt; # e.g. &quot;https://my.application.service.com&quot;
  2619. as_token: &lt;String&gt;
  2620. hs_token: &lt;String&gt;
  2621. sender_localpart: &lt;String&gt; # This is a new field which denotes the user_id localpart when using the AS token
  2622. namespaces:
  2623. users:
  2624. - exclusive: &lt;Boolean&gt;
  2625. regex: &lt;String&gt; # e.g. &quot;@prefix_.*&quot;
  2626. aliases:
  2627. - exclusive: &lt;Boolean&gt;
  2628. regex: &lt;String&gt;
  2629. rooms:
  2630. - exclusive: &lt;Boolean&gt;
  2631. regex: &lt;String&gt;
  2632. </code></pre>
  2633. <h1 id="upgrading-to-v080"><a class="header" href="#upgrading-to-v080">Upgrading to v0.8.0</a></h1>
  2634. <p>Servers which use captchas will need to add their public key to:</p>
  2635. <pre><code>static/client/register/register_config.js
  2636. window.matrixRegistrationConfig = {
  2637. recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  2638. };
  2639. </code></pre>
  2640. <p>This is required in order to support registration fallback (typically
  2641. used on mobile devices).</p>
  2642. <h1 id="upgrading-to-v070"><a class="header" href="#upgrading-to-v070">Upgrading to v0.7.0</a></h1>
  2643. <p>New dependencies are:</p>
  2644. <ul>
  2645. <li>pydenticon</li>
  2646. <li>simplejson</li>
  2647. <li>syutil</li>
  2648. <li>matrix-angular-sdk</li>
  2649. </ul>
  2650. <p>To pull in these dependencies in a virtual env, run:</p>
  2651. <pre><code>python synapse/python_dependencies.py | xargs -n 1 pip install
  2652. </code></pre>
  2653. <h1 id="upgrading-to-v060"><a class="header" href="#upgrading-to-v060">Upgrading to v0.6.0</a></h1>
  2654. <p>To pull in new dependencies, run:</p>
  2655. <pre><code>python setup.py develop --user
  2656. </code></pre>
  2657. <p>This update includes a change to the database schema. To upgrade you
  2658. first need to upgrade the database by running:</p>
  2659. <pre><code>python scripts/upgrade_db_to_v0.6.0.py &lt;db&gt; &lt;server_name&gt; &lt;signing_key&gt;
  2660. </code></pre>
  2661. <p>Where <code>&lt;db&gt;</code> is the location of the database,
  2662. <code>&lt;server_name&gt;</code> is the server name as specified in the
  2663. synapse configuration, and <code>&lt;signing_key&gt;</code> is the location
  2664. of the signing key as specified in the synapse configuration.</p>
  2665. <p>This may take some time to complete. Failures of signatures and content
  2666. hashes can safely be ignored.</p>
  2667. <h1 id="upgrading-to-v051"><a class="header" href="#upgrading-to-v051">Upgrading to v0.5.1</a></h1>
  2668. <p>Depending on precisely when you installed v0.5.0 you may have ended up
  2669. with a stale release of the reference matrix webclient installed as a
  2670. python module. To uninstall it and ensure you are depending on the
  2671. latest module, please run:</p>
  2672. <pre><code>$ pip uninstall syweb
  2673. </code></pre>
  2674. <h1 id="upgrading-to-v050"><a class="header" href="#upgrading-to-v050">Upgrading to v0.5.0</a></h1>
  2675. <p>The webclient has been split out into a seperate repository/pacakage in
  2676. this release. Before you restart your homeserver you will need to pull
  2677. in the webclient package by running:</p>
  2678. <pre><code>python setup.py develop --user
  2679. </code></pre>
  2680. <p>This release completely changes the database schema and so requires
  2681. upgrading it before starting the new version of the homeserver.</p>
  2682. <p>The script &quot;database-prepare-for-0.5.0.sh&quot; should be used to upgrade
  2683. the database. This will save all user information, such as logins and
  2684. profiles, but will otherwise purge the database. This includes messages,
  2685. which rooms the home server was a member of and room alias mappings.</p>
  2686. <p>If you would like to keep your history, please take a copy of your
  2687. database file and ask for help in #matrix:matrix.org. The upgrade
  2688. process is, unfortunately, non trivial and requires human intervention
  2689. to resolve any resulting conflicts during the upgrade process.</p>
  2690. <p>Before running the command the homeserver should be first completely
  2691. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  2692. <blockquote>
  2693. <p>./scripts/database-prepare-for-0.5.0.sh &quot;homeserver.db&quot;</p>
  2694. </blockquote>
  2695. <p>Once this has successfully completed it will be safe to restart the
  2696. homeserver. You may notice that the homeserver takes a few seconds
  2697. longer to restart than usual as it reinitializes the database.</p>
  2698. <p>On startup of the new version, users can either rejoin remote rooms
  2699. using room aliases or by being reinvited. Alternatively, if any other
  2700. homeserver sends a message to a room that the homeserver was previously
  2701. in the local HS will automatically rejoin the room.</p>
  2702. <h1 id="upgrading-to-v040"><a class="header" href="#upgrading-to-v040">Upgrading to v0.4.0</a></h1>
  2703. <p>This release needs an updated syutil version. Run:</p>
  2704. <pre><code>python setup.py develop
  2705. </code></pre>
  2706. <p>You will also need to upgrade your configuration as the signing key
  2707. format has changed. Run:</p>
  2708. <pre><code>python -m synapse.app.homeserver --config-path &lt;CONFIG&gt; --generate-config
  2709. </code></pre>
  2710. <h1 id="upgrading-to-v030"><a class="header" href="#upgrading-to-v030">Upgrading to v0.3.0</a></h1>
  2711. <p>This registration API now closely matches the login API. This introduces
  2712. a bit more backwards and forwards between the HS and the client, but
  2713. this improves the overall flexibility of the API. You can now GET on
  2714. /register to retrieve a list of valid registration flows. Upon choosing
  2715. one, they are submitted in the same way as login, e.g:</p>
  2716. <pre><code>{
  2717. type: m.login.password,
  2718. user: foo,
  2719. password: bar
  2720. }
  2721. </code></pre>
  2722. <p>The default HS supports 2 flows, with and without Identity Server email
  2723. authentication. Enabling captcha on the HS will add in an extra step to
  2724. all flows: <code>m.login.recaptcha</code> which must be completed before you can
  2725. transition to the next stage. There is a new login type:
  2726. <code>m.login.email.identity</code> which contains the <code>threepidCreds</code> key which
  2727. were previously sent in the original register request. For more
  2728. information on this, see the specification.</p>
  2729. <h2 id="web-client"><a class="header" href="#web-client">Web Client</a></h2>
  2730. <p>The VoIP specification has changed between v0.2.0 and v0.3.0. Users
  2731. should refresh any browser tabs to get the latest web client code. Users
  2732. on v0.2.0 of the web client will not be able to call those on v0.3.0 and
  2733. vice versa.</p>
  2734. <h1 id="upgrading-to-v020"><a class="header" href="#upgrading-to-v020">Upgrading to v0.2.0</a></h1>
  2735. <p>The home server now requires setting up of SSL config before it can run.
  2736. To automatically generate default config use:</p>
  2737. <pre><code>$ python synapse/app/homeserver.py \
  2738. --server-name machine.my.domain.name \
  2739. --bind-port 8448 \
  2740. --config-path homeserver.config \
  2741. --generate-config
  2742. </code></pre>
  2743. <p>This config can be edited if desired, for example to specify a different
  2744. SSL certificate to use. Once done you can run the home server using:</p>
  2745. <pre><code>$ python synapse/app/homeserver.py --config-path homeserver.config
  2746. </code></pre>
  2747. <p>See the README.rst for more information.</p>
  2748. <p>Also note that some config options have been renamed, including:</p>
  2749. <ul>
  2750. <li>&quot;host&quot; to &quot;server-name&quot;</li>
  2751. <li>&quot;database&quot; to &quot;database-path&quot;</li>
  2752. <li>&quot;port&quot; to &quot;bind-port&quot; and &quot;unsecure-port&quot;</li>
  2753. </ul>
  2754. <h1 id="upgrading-to-v001"><a class="header" href="#upgrading-to-v001">Upgrading to v0.0.1</a></h1>
  2755. <p>This release completely changes the database schema and so requires
  2756. upgrading it before starting the new version of the homeserver.</p>
  2757. <p>The script &quot;database-prepare-for-0.0.1.sh&quot; should be used to upgrade
  2758. the database. This will save all user information, such as logins and
  2759. profiles, but will otherwise purge the database. This includes messages,
  2760. which rooms the home server was a member of and room alias mappings.</p>
  2761. <p>Before running the command the homeserver should be first completely
  2762. shutdown. To run it, simply specify the location of the database, e.g.:</p>
  2763. <blockquote>
  2764. <p>./scripts/database-prepare-for-0.0.1.sh &quot;homeserver.db&quot;</p>
  2765. </blockquote>
  2766. <p>Once this has successfully completed it will be safe to restart the
  2767. homeserver. You may notice that the homeserver takes a few seconds
  2768. longer to restart than usual as it reinitializes the database.</p>
  2769. <p>On startup of the new version, users can either rejoin remote rooms
  2770. using room aliases or by being reinvited. Alternatively, if any other
  2771. homeserver sends a message to a room that the homeserver was previously
  2772. in the local HS will automatically rejoin the room.</p>
  2773. <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>
  2774. <p>Federation is the process by which users on different servers can participate
  2775. in the same room. For this to work, those other servers must be able to contact
  2776. yours to send messages.</p>
  2777. <p>The <code>server_name</code> configured in the Synapse configuration file (often
  2778. <code>homeserver.yaml</code>) defines how resources (users, rooms, etc.) will be
  2779. identified (eg: <code>@user:example.com</code>, <code>#room:example.com</code>). By default,
  2780. it is also the domain that other servers will use to try to reach your
  2781. server (via port 8448). This is easy to set up and will work provided
  2782. you set the <code>server_name</code> to match your machine's public DNS hostname.</p>
  2783. <p>For this default configuration to work, you will need to listen for TLS
  2784. connections on port 8448. The preferred way to do that is by using a
  2785. reverse proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions
  2786. on how to correctly set one up.</p>
  2787. <p>In some cases you might not want to run Synapse on the machine that has
  2788. the <code>server_name</code> as its public DNS hostname, or you might want federation
  2789. traffic to use a different port than 8448. For example, you might want to
  2790. have your user names look like <code>@user:example.com</code>, but you want to run
  2791. Synapse on <code>synapse.example.com</code> on port 443. This can be done using
  2792. delegation, which allows an admin to control where federation traffic should
  2793. be sent. See <a href="delegate.html">the delegation documentation</a> for instructions on how to set this up.</p>
  2794. <p>Once federation has been configured, you should be able to join a room over
  2795. federation. A good place to start is <code>#synapse:matrix.org</code> - a room for
  2796. Synapse admins.</p>
  2797. <h2 id="troubleshooting-3"><a class="header" href="#troubleshooting-3">Troubleshooting</a></h2>
  2798. <p>You can use the <a href="https://matrix.org/federationtester">federation tester</a>
  2799. to check if your homeserver is configured correctly. Alternatively try the
  2800. <a href="https://matrix.org/federationtester/api/report?server_name=DOMAIN">JSON API used by the federation tester</a>.
  2801. Note that you'll have to modify this URL to replace <code>DOMAIN</code> with your
  2802. <code>server_name</code>. Hitting the API directly provides extra detail.</p>
  2803. <p>The typical failure mode for federation is that when the server tries to join
  2804. a room, it is rejected with &quot;401: Unauthorized&quot;. Generally this means that other
  2805. servers in the room could not access yours. (Joining a room over federation is
  2806. a complicated dance which requires connections in both directions).</p>
  2807. <p>Another common problem is that people on other servers can't join rooms that
  2808. you invite them to. This can be caused by an incorrectly-configured reverse
  2809. proxy: see <a href="reverse_proxy.html">the reverse proxy documentation</a> for instructions on how
  2810. to correctly configure a reverse proxy.</p>
  2811. <h3 id="known-issues"><a class="header" href="#known-issues">Known issues</a></h3>
  2812. <p><strong>HTTP <code>308 Permanent Redirect</code> redirects are not followed</strong>: Due to missing features
  2813. in the HTTP library used by Synapse, 308 redirects are currently not followed by
  2814. federating servers, which can cause <code>M_UNKNOWN</code> or <code>401 Unauthorized</code> errors. This
  2815. may affect users who are redirecting apex-to-www (e.g. <code>example.com</code> -&gt; <code>www.example.com</code>),
  2816. and especially users of the Kubernetes <em>Nginx Ingress</em> module, which uses 308 redirect
  2817. codes by default. For those Kubernetes users, <a href="https://stackoverflow.com/a/52617528/5096871">this Stackoverflow post</a>
  2818. might be helpful. For other users, switching to a <code>301 Moved Permanently</code> code may be
  2819. an option. 308 redirect codes will be supported properly in a future
  2820. release of Synapse.</p>
  2821. <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>
  2822. <p>If you want to get up and running quickly with a trio of homeservers in a
  2823. private federation, there is a script in the <code>demo</code> directory. This is mainly
  2824. useful just for development purposes. See <a href="https://github.com/matrix-org/synapse/tree/develop/demo/">demo/README</a>.</p>
  2825. <div style="break-before: page; page-break-before: always;"></div><h1 id="configuration-1"><a class="header" href="#configuration-1">Configuration</a></h1>
  2826. <p>This section contains information on tweaking Synapse via the various options in the configuration file. A configuration
  2827. file should have been generated when you <a href="usage/configuration/../../setup/installation.html">installed Synapse</a>.</p>
  2828. <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>
  2829. <p>Below is a sample homeserver configuration file. The homeserver configuration file
  2830. can be tweaked to change the behaviour of your homeserver. A restart of the server is
  2831. generally required to apply any changes made to this file.</p>
  2832. <p>Note that the contents below are <em>not</em> intended to be copied and used as the basis for
  2833. a real homeserver.yaml. Instead, if you are starting from scratch, please generate
  2834. a fresh config using Synapse by following the instructions in
  2835. <a href="usage/configuration/../../setup/installation.html">Installation</a>.</p>
  2836. <pre><code class="language-yaml"># This file is maintained as an up-to-date snapshot of the default
  2837. # homeserver.yaml configuration generated by Synapse.
  2838. #
  2839. # It is intended to act as a reference for the default configuration,
  2840. # helping admins keep track of new options and other changes, and compare
  2841. # their configs with the current default. As such, many of the actual
  2842. # config values shown are placeholders.
  2843. #
  2844. # It is *not* intended to be copied and used as the basis for a real
  2845. # homeserver.yaml. Instead, if you are starting from scratch, please generate
  2846. # a fresh config using Synapse by following the instructions in
  2847. # https://matrix-org.github.io/synapse/latest/setup/installation.html.
  2848. # Configuration options that take a time period can be set using a number
  2849. # followed by a letter. Letters have the following meanings:
  2850. # s = second
  2851. # m = minute
  2852. # h = hour
  2853. # d = day
  2854. # w = week
  2855. # y = year
  2856. # For example, setting redaction_retention_period: 5m would remove redacted
  2857. # messages from the database after 5 minutes, rather than 5 months.
  2858. ################################################################################
  2859. # Configuration file for Synapse.
  2860. #
  2861. # This is a YAML file: see [1] for a quick introduction. Note in particular
  2862. # that *indentation is important*: all the elements of a list or dictionary
  2863. # should have the same indentation.
  2864. #
  2865. # [1] https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
  2866. ## Modules ##
  2867. # Server admins can expand Synapse's functionality with external modules.
  2868. #
  2869. # See https://matrix-org.github.io/synapse/latest/modules/index.html for more
  2870. # documentation on how to configure or create custom modules for Synapse.
  2871. #
  2872. modules:
  2873. #- module: my_super_module.MySuperClass
  2874. # config:
  2875. # do_thing: true
  2876. #- module: my_other_super_module.SomeClass
  2877. # config: {}
  2878. ## Server ##
  2879. # The public-facing domain of the server
  2880. #
  2881. # The server_name name will appear at the end of usernames and room addresses
  2882. # created on this server. For example if the server_name was example.com,
  2883. # usernames on this server would be in the format @user:example.com
  2884. #
  2885. # In most cases you should avoid using a matrix specific subdomain such as
  2886. # matrix.example.com or synapse.example.com as the server_name for the same
  2887. # reasons you wouldn't use user@email.example.com as your email address.
  2888. # See https://matrix-org.github.io/synapse/latest/delegate.html
  2889. # for information on how to host Synapse on a subdomain while preserving
  2890. # a clean server_name.
  2891. #
  2892. # The server_name cannot be changed later so it is important to
  2893. # configure this correctly before you start Synapse. It should be all
  2894. # lowercase and may contain an explicit port.
  2895. # Examples: matrix.org, localhost:8080
  2896. #
  2897. server_name: &quot;SERVERNAME&quot;
  2898. # When running as a daemon, the file to store the pid in
  2899. #
  2900. pid_file: DATADIR/homeserver.pid
  2901. # The absolute URL to the web client which / will redirect to.
  2902. #
  2903. #web_client_location: https://riot.example.com/
  2904. # The public-facing base URL that clients use to access this Homeserver (not
  2905. # including _matrix/...). This is the same URL a user might enter into the
  2906. # 'Custom Homeserver URL' field on their client. If you use Synapse with a
  2907. # reverse proxy, this should be the URL to reach Synapse via the proxy.
  2908. # Otherwise, it should be the URL to reach Synapse's client HTTP listener (see
  2909. # 'listeners' below).
  2910. #
  2911. # Defaults to 'https://&lt;server_name&gt;/'.
  2912. #
  2913. #public_baseurl: https://example.com/
  2914. # Uncomment the following to tell other servers to send federation traffic on
  2915. # port 443.
  2916. #
  2917. # By default, other servers will try to reach our server on port 8448, which can
  2918. # be inconvenient in some environments.
  2919. #
  2920. # Provided 'https://&lt;server_name&gt;/' on port 443 is routed to Synapse, this
  2921. # option configures Synapse to serve a file at
  2922. # 'https://&lt;server_name&gt;/.well-known/matrix/server'. This will tell other
  2923. # servers to send traffic to port 443 instead.
  2924. #
  2925. # See https://matrix-org.github.io/synapse/latest/delegate.html for more
  2926. # information.
  2927. #
  2928. # Defaults to 'false'.
  2929. #
  2930. #serve_server_wellknown: true
  2931. # Set the soft limit on the number of file descriptors synapse can use
  2932. # Zero is used to indicate synapse should set the soft limit to the
  2933. # hard limit.
  2934. #
  2935. #soft_file_limit: 0
  2936. # Presence tracking allows users to see the state (e.g online/offline)
  2937. # of other local and remote users.
  2938. #
  2939. presence:
  2940. # Uncomment to disable presence tracking on this homeserver. This option
  2941. # replaces the previous top-level 'use_presence' option.
  2942. #
  2943. #enabled: false
  2944. # Whether to require authentication to retrieve profile data (avatars,
  2945. # display names) of other users through the client API. Defaults to
  2946. # 'false'. Note that profile data is also available via the federation
  2947. # API, unless allow_profile_lookup_over_federation is set to false.
  2948. #
  2949. #require_auth_for_profile_requests: true
  2950. # Uncomment to require a user to share a room with another user in order
  2951. # to retrieve their profile information. Only checked on Client-Server
  2952. # requests. Profile requests from other servers should be checked by the
  2953. # requesting server. Defaults to 'false'.
  2954. #
  2955. #limit_profile_requests_to_users_who_share_rooms: true
  2956. # Uncomment to prevent a user's profile data from being retrieved and
  2957. # displayed in a room until they have joined it. By default, a user's
  2958. # profile data is included in an invite event, regardless of the values
  2959. # of the above two settings, and whether or not the users share a server.
  2960. # Defaults to 'true'.
  2961. #
  2962. #include_profile_data_on_invite: false
  2963. # If set to 'true', removes the need for authentication to access the server's
  2964. # public rooms directory through the client API, meaning that anyone can
  2965. # query the room directory. Defaults to 'false'.
  2966. #
  2967. #allow_public_rooms_without_auth: true
  2968. # If set to 'true', allows any other homeserver to fetch the server's public
  2969. # rooms directory via federation. Defaults to 'false'.
  2970. #
  2971. #allow_public_rooms_over_federation: true
  2972. # The default room version for newly created rooms.
  2973. #
  2974. # Known room versions are listed here:
  2975. # https://spec.matrix.org/latest/rooms/#complete-list-of-room-versions
  2976. #
  2977. # For example, for room version 1, default_room_version should be set
  2978. # to &quot;1&quot;.
  2979. #
  2980. #default_room_version: &quot;6&quot;
  2981. # The GC threshold parameters to pass to `gc.set_threshold`, if defined
  2982. #
  2983. #gc_thresholds: [700, 10, 10]
  2984. # The minimum time in seconds between each GC for a generation, regardless of
  2985. # the GC thresholds. This ensures that we don't do GC too frequently.
  2986. #
  2987. # A value of `[1s, 10s, 30s]` indicates that a second must pass between consecutive
  2988. # generation 0 GCs, etc.
  2989. #
  2990. # Defaults to `[1s, 10s, 30s]`.
  2991. #
  2992. #gc_min_interval: [0.5s, 30s, 1m]
  2993. # Set the limit on the returned events in the timeline in the get
  2994. # and sync operations. The default value is 100. -1 means no upper limit.
  2995. #
  2996. # Uncomment the following to increase the limit to 5000.
  2997. #
  2998. #filter_timeline_limit: 5000
  2999. # Whether room invites to users on this server should be blocked
  3000. # (except those sent by local server admins). The default is False.
  3001. #
  3002. #block_non_admin_invites: true
  3003. # Room searching
  3004. #
  3005. # If disabled, new messages will not be indexed for searching and users
  3006. # will receive errors when searching for messages. Defaults to enabled.
  3007. #
  3008. #enable_search: false
  3009. # Prevent outgoing requests from being sent to the following blacklisted IP address
  3010. # CIDR ranges. If this option is not specified then it defaults to private IP
  3011. # address ranges (see the example below).
  3012. #
  3013. # The blacklist applies to the outbound requests for federation, identity servers,
  3014. # push servers, and for checking key validity for third-party invite events.
  3015. #
  3016. # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  3017. # listed here, since they correspond to unroutable addresses.)
  3018. #
  3019. # This option replaces federation_ip_range_blacklist in Synapse v1.25.0.
  3020. #
  3021. # Note: The value is ignored when an HTTP proxy is in use
  3022. #
  3023. #ip_range_blacklist:
  3024. # - '127.0.0.0/8'
  3025. # - '10.0.0.0/8'
  3026. # - '172.16.0.0/12'
  3027. # - '192.168.0.0/16'
  3028. # - '100.64.0.0/10'
  3029. # - '192.0.0.0/24'
  3030. # - '169.254.0.0/16'
  3031. # - '192.88.99.0/24'
  3032. # - '198.18.0.0/15'
  3033. # - '192.0.2.0/24'
  3034. # - '198.51.100.0/24'
  3035. # - '203.0.113.0/24'
  3036. # - '224.0.0.0/4'
  3037. # - '::1/128'
  3038. # - 'fe80::/10'
  3039. # - 'fc00::/7'
  3040. # - '2001:db8::/32'
  3041. # - 'ff00::/8'
  3042. # - 'fec0::/10'
  3043. # List of IP address CIDR ranges that should be allowed for federation,
  3044. # identity servers, push servers, and for checking key validity for
  3045. # third-party invite events. This is useful for specifying exceptions to
  3046. # wide-ranging blacklisted target IP ranges - e.g. for communication with
  3047. # a push server only visible in your network.
  3048. #
  3049. # This whitelist overrides ip_range_blacklist and defaults to an empty
  3050. # list.
  3051. #
  3052. #ip_range_whitelist:
  3053. # - '192.168.1.1'
  3054. # List of ports that Synapse should listen on, their purpose and their
  3055. # configuration.
  3056. #
  3057. # Options for each listener include:
  3058. #
  3059. # port: the TCP port to bind to
  3060. #
  3061. # bind_addresses: a list of local addresses to listen on. The default is
  3062. # 'all local interfaces'.
  3063. #
  3064. # type: the type of listener. Normally 'http', but other valid options are:
  3065. # 'manhole' (see https://matrix-org.github.io/synapse/latest/manhole.html),
  3066. # 'metrics' (see https://matrix-org.github.io/synapse/latest/metrics-howto.html),
  3067. # 'replication' (see https://matrix-org.github.io/synapse/latest/workers.html).
  3068. #
  3069. # tls: set to true to enable TLS for this listener. Will use the TLS
  3070. # key/cert specified in tls_private_key_path / tls_certificate_path.
  3071. #
  3072. # x_forwarded: Only valid for an 'http' listener. Set to true to use the
  3073. # X-Forwarded-For header as the client IP. Useful when Synapse is
  3074. # behind a reverse-proxy.
  3075. #
  3076. # resources: Only valid for an 'http' listener. A list of resources to host
  3077. # on this port. Options for each resource are:
  3078. #
  3079. # names: a list of names of HTTP resources. See below for a list of
  3080. # valid resource names.
  3081. #
  3082. # compress: set to true to enable HTTP compression for this resource.
  3083. #
  3084. # additional_resources: Only valid for an 'http' listener. A map of
  3085. # additional endpoints which should be loaded via dynamic modules.
  3086. #
  3087. # Valid resource names are:
  3088. #
  3089. # client: the client-server API (/_matrix/client), and the synapse admin
  3090. # API (/_synapse/admin). Also implies 'media' and 'static'.
  3091. #
  3092. # consent: user consent forms (/_matrix/consent).
  3093. # See https://matrix-org.github.io/synapse/latest/consent_tracking.html.
  3094. #
  3095. # federation: the server-server API (/_matrix/federation). Also implies
  3096. # 'media', 'keys', 'openid'
  3097. #
  3098. # keys: the key discovery API (/_matrix/keys).
  3099. #
  3100. # media: the media API (/_matrix/media).
  3101. #
  3102. # metrics: the metrics interface.
  3103. # See https://matrix-org.github.io/synapse/latest/metrics-howto.html.
  3104. #
  3105. # openid: OpenID authentication.
  3106. #
  3107. # replication: the HTTP replication API (/_synapse/replication).
  3108. # See https://matrix-org.github.io/synapse/latest/workers.html.
  3109. #
  3110. # static: static resources under synapse/static (/_matrix/static). (Mostly
  3111. # useful for 'fallback authentication'.)
  3112. #
  3113. listeners:
  3114. # TLS-enabled listener: for when matrix traffic is sent directly to synapse.
  3115. #
  3116. # Disabled by default. To enable it, uncomment the following. (Note that you
  3117. # will also need to give Synapse a TLS key and certificate: see the TLS section
  3118. # below.)
  3119. #
  3120. #- port: 8448
  3121. # type: http
  3122. # tls: true
  3123. # resources:
  3124. # - names: [client, federation]
  3125. # Unsecure HTTP listener: for when matrix traffic passes through a reverse proxy
  3126. # that unwraps TLS.
  3127. #
  3128. # If you plan to use a reverse proxy, please see
  3129. # https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  3130. #
  3131. - port: 8008
  3132. tls: false
  3133. type: http
  3134. x_forwarded: true
  3135. bind_addresses: ['::1', '127.0.0.1']
  3136. resources:
  3137. - names: [client, federation]
  3138. compress: false
  3139. # example additional_resources:
  3140. #
  3141. #additional_resources:
  3142. # &quot;/_matrix/my/custom/endpoint&quot;:
  3143. # module: my_module.CustomRequestHandler
  3144. # config: {}
  3145. # Turn on the twisted ssh manhole service on localhost on the given
  3146. # port.
  3147. #
  3148. #- port: 9000
  3149. # bind_addresses: ['::1', '127.0.0.1']
  3150. # type: manhole
  3151. # Connection settings for the manhole
  3152. #
  3153. manhole_settings:
  3154. # The username for the manhole. This defaults to 'matrix'.
  3155. #
  3156. #username: manhole
  3157. # The password for the manhole. This defaults to 'rabbithole'.
  3158. #
  3159. #password: mypassword
  3160. # The private and public SSH key pair used to encrypt the manhole traffic.
  3161. # If these are left unset, then hardcoded and non-secret keys are used,
  3162. # which could allow traffic to be intercepted if sent over a public network.
  3163. #
  3164. #ssh_priv_key_path: CONFDIR/id_rsa
  3165. #ssh_pub_key_path: CONFDIR/id_rsa.pub
  3166. # Forward extremities can build up in a room due to networking delays between
  3167. # homeservers. Once this happens in a large room, calculation of the state of
  3168. # that room can become quite expensive. To mitigate this, once the number of
  3169. # forward extremities reaches a given threshold, Synapse will send an
  3170. # org.matrix.dummy_event event, which will reduce the forward extremities
  3171. # in the room.
  3172. #
  3173. # This setting defines the threshold (i.e. number of forward extremities in the
  3174. # room) at which dummy events are sent. The default value is 10.
  3175. #
  3176. #dummy_events_threshold: 5
  3177. ## Homeserver blocking ##
  3178. # How to reach the server admin, used in ResourceLimitError
  3179. #
  3180. #admin_contact: 'mailto:admin@server.com'
  3181. # Global blocking
  3182. #
  3183. #hs_disabled: false
  3184. #hs_disabled_message: 'Human readable reason for why the HS is blocked'
  3185. # Monthly Active User Blocking
  3186. #
  3187. # Used in cases where the admin or server owner wants to limit to the
  3188. # number of monthly active users.
  3189. #
  3190. # 'limit_usage_by_mau' disables/enables monthly active user blocking. When
  3191. # enabled and a limit is reached the server returns a 'ResourceLimitError'
  3192. # with error type Codes.RESOURCE_LIMIT_EXCEEDED
  3193. #
  3194. # 'max_mau_value' is the hard limit of monthly active users above which
  3195. # the server will start blocking user actions.
  3196. #
  3197. # 'mau_trial_days' is a means to add a grace period for active users. It
  3198. # means that users must be active for this number of days before they
  3199. # can be considered active and guards against the case where lots of users
  3200. # sign up in a short space of time never to return after their initial
  3201. # session.
  3202. #
  3203. # 'mau_limit_alerting' is a means of limiting client side alerting
  3204. # should the mau limit be reached. This is useful for small instances
  3205. # where the admin has 5 mau seats (say) for 5 specific people and no
  3206. # interest increasing the mau limit further. Defaults to True, which
  3207. # means that alerting is enabled
  3208. #
  3209. #limit_usage_by_mau: false
  3210. #max_mau_value: 50
  3211. #mau_trial_days: 2
  3212. #mau_limit_alerting: false
  3213. # If enabled, the metrics for the number of monthly active users will
  3214. # be populated, however no one will be limited. If limit_usage_by_mau
  3215. # is true, this is implied to be true.
  3216. #
  3217. #mau_stats_only: false
  3218. # Sometimes the server admin will want to ensure certain accounts are
  3219. # never blocked by mau checking. These accounts are specified here.
  3220. #
  3221. #mau_limit_reserved_threepids:
  3222. # - medium: 'email'
  3223. # address: 'reserved_user@example.com'
  3224. # Used by phonehome stats to group together related servers.
  3225. #server_context: context
  3226. # Resource-constrained homeserver settings
  3227. #
  3228. # When this is enabled, the room &quot;complexity&quot; will be checked before a user
  3229. # joins a new remote room. If it is above the complexity limit, the server will
  3230. # disallow joining, or will instantly leave.
  3231. #
  3232. # Room complexity is an arbitrary measure based on factors such as the number of
  3233. # users in the room.
  3234. #
  3235. limit_remote_rooms:
  3236. # Uncomment to enable room complexity checking.
  3237. #
  3238. #enabled: true
  3239. # the limit above which rooms cannot be joined. The default is 1.0.
  3240. #
  3241. #complexity: 0.5
  3242. # override the error which is returned when the room is too complex.
  3243. #
  3244. #complexity_error: &quot;This room is too complex.&quot;
  3245. # allow server admins to join complex rooms. Default is false.
  3246. #
  3247. #admins_can_join: true
  3248. # Whether to require a user to be in the room to add an alias to it.
  3249. # Defaults to 'true'.
  3250. #
  3251. #require_membership_for_aliases: false
  3252. # Whether to allow per-room membership profiles through the send of membership
  3253. # events with profile information that differ from the target's global profile.
  3254. # Defaults to 'true'.
  3255. #
  3256. #allow_per_room_profiles: false
  3257. # The largest allowed file size for a user avatar. Defaults to no restriction.
  3258. #
  3259. # Note that user avatar changes will not work if this is set without
  3260. # using Synapse's media repository.
  3261. #
  3262. #max_avatar_size: 10M
  3263. # The MIME types allowed for user avatars. Defaults to no restriction.
  3264. #
  3265. # Note that user avatar changes will not work if this is set without
  3266. # using Synapse's media repository.
  3267. #
  3268. #allowed_avatar_mimetypes: [&quot;image/png&quot;, &quot;image/jpeg&quot;, &quot;image/gif&quot;]
  3269. # How long to keep redacted events in unredacted form in the database. After
  3270. # this period redacted events get replaced with their redacted form in the DB.
  3271. #
  3272. # Defaults to `7d`. Set to `null` to disable.
  3273. #
  3274. #redaction_retention_period: 28d
  3275. # How long to track users' last seen time and IPs in the database.
  3276. #
  3277. # Defaults to `28d`. Set to `null` to disable clearing out of old rows.
  3278. #
  3279. #user_ips_max_age: 14d
  3280. # Inhibits the /requestToken endpoints from returning an error that might leak
  3281. # information about whether an e-mail address is in use or not on this
  3282. # homeserver.
  3283. # Note that for some endpoints the error situation is the e-mail already being
  3284. # used, and for others the error is entering the e-mail being unused.
  3285. # If this option is enabled, instead of returning an error, these endpoints will
  3286. # act as if no error happened and return a fake session ID ('sid') to clients.
  3287. #
  3288. #request_token_inhibit_3pid_errors: true
  3289. # A list of domains that the domain portion of 'next_link' parameters
  3290. # must match.
  3291. #
  3292. # This parameter is optionally provided by clients while requesting
  3293. # validation of an email or phone number, and maps to a link that
  3294. # users will be automatically redirected to after validation
  3295. # succeeds. Clients can make use this parameter to aid the validation
  3296. # process.
  3297. #
  3298. # The whitelist is applied whether the homeserver or an
  3299. # identity server is handling validation.
  3300. #
  3301. # The default value is no whitelist functionality; all domains are
  3302. # allowed. Setting this value to an empty list will instead disallow
  3303. # all domains.
  3304. #
  3305. #next_link_domain_whitelist: [&quot;matrix.org&quot;]
  3306. # Templates to use when generating email or HTML page contents.
  3307. #
  3308. templates:
  3309. # Directory in which Synapse will try to find template files to use to generate
  3310. # email or HTML page contents.
  3311. # If not set, or a file is not found within the template directory, a default
  3312. # template from within the Synapse package will be used.
  3313. #
  3314. # See https://matrix-org.github.io/synapse/latest/templates.html for more
  3315. # information about using custom templates.
  3316. #
  3317. #custom_template_directory: /path/to/custom/templates/
  3318. # Message retention policy at the server level.
  3319. #
  3320. # Room admins and mods can define a retention period for their rooms using the
  3321. # 'm.room.retention' state event, and server admins can cap this period by setting
  3322. # the 'allowed_lifetime_min' and 'allowed_lifetime_max' config options.
  3323. #
  3324. # If this feature is enabled, Synapse will regularly look for and purge events
  3325. # which are older than the room's maximum retention period. Synapse will also
  3326. # filter events received over federation so that events that should have been
  3327. # purged are ignored and not stored again.
  3328. #
  3329. retention:
  3330. # The message retention policies feature is disabled by default. Uncomment the
  3331. # following line to enable it.
  3332. #
  3333. #enabled: true
  3334. # Default retention policy. If set, Synapse will apply it to rooms that lack the
  3335. # 'm.room.retention' state event. Currently, the value of 'min_lifetime' doesn't
  3336. # matter much because Synapse doesn't take it into account yet.
  3337. #
  3338. #default_policy:
  3339. # min_lifetime: 1d
  3340. # max_lifetime: 1y
  3341. # Retention policy limits. If set, and the state of a room contains a
  3342. # 'm.room.retention' event in its state which contains a 'min_lifetime' or a
  3343. # 'max_lifetime' that's out of these bounds, Synapse will cap the room's policy
  3344. # to these limits when running purge jobs.
  3345. #
  3346. #allowed_lifetime_min: 1d
  3347. #allowed_lifetime_max: 1y
  3348. # Server admins can define the settings of the background jobs purging the
  3349. # events which lifetime has expired under the 'purge_jobs' section.
  3350. #
  3351. # If no configuration is provided, a single job will be set up to delete expired
  3352. # events in every room daily.
  3353. #
  3354. # Each job's configuration defines which range of message lifetimes the job
  3355. # takes care of. For example, if 'shortest_max_lifetime' is '2d' and
  3356. # 'longest_max_lifetime' is '3d', the job will handle purging expired events in
  3357. # rooms whose state defines a 'max_lifetime' that's both higher than 2 days, and
  3358. # lower than or equal to 3 days. Both the minimum and the maximum value of a
  3359. # range are optional, e.g. a job with no 'shortest_max_lifetime' and a
  3360. # 'longest_max_lifetime' of '3d' will handle every room with a retention policy
  3361. # which 'max_lifetime' is lower than or equal to three days.
  3362. #
  3363. # The rationale for this per-job configuration is that some rooms might have a
  3364. # retention policy with a low 'max_lifetime', where history needs to be purged
  3365. # of outdated messages on a more frequent basis than for the rest of the rooms
  3366. # (e.g. every 12h), but not want that purge to be performed by a job that's
  3367. # iterating over every room it knows, which could be heavy on the server.
  3368. #
  3369. # If any purge job is configured, it is strongly recommended to have at least
  3370. # a single job with neither 'shortest_max_lifetime' nor 'longest_max_lifetime'
  3371. # set, or one job without 'shortest_max_lifetime' and one job without
  3372. # 'longest_max_lifetime' set. Otherwise some rooms might be ignored, even if
  3373. # 'allowed_lifetime_min' and 'allowed_lifetime_max' are set, because capping a
  3374. # room's policy to these values is done after the policies are retrieved from
  3375. # Synapse's database (which is done using the range specified in a purge job's
  3376. # configuration).
  3377. #
  3378. #purge_jobs:
  3379. # - longest_max_lifetime: 3d
  3380. # interval: 12h
  3381. # - shortest_max_lifetime: 3d
  3382. # interval: 1d
  3383. ## TLS ##
  3384. # PEM-encoded X509 certificate for TLS.
  3385. # This certificate, as of Synapse 1.0, will need to be a valid and verifiable
  3386. # certificate, signed by a recognised Certificate Authority.
  3387. #
  3388. # Be sure to use a `.pem` file that includes the full certificate chain including
  3389. # any intermediate certificates (for instance, if using certbot, use
  3390. # `fullchain.pem` as your certificate, not `cert.pem`).
  3391. #
  3392. #tls_certificate_path: &quot;CONFDIR/SERVERNAME.tls.crt&quot;
  3393. # PEM-encoded private key for TLS
  3394. #
  3395. #tls_private_key_path: &quot;CONFDIR/SERVERNAME.tls.key&quot;
  3396. # Whether to verify TLS server certificates for outbound federation requests.
  3397. #
  3398. # Defaults to `true`. To disable certificate verification, uncomment the
  3399. # following line.
  3400. #
  3401. #federation_verify_certificates: false
  3402. # The minimum TLS version that will be used for outbound federation requests.
  3403. #
  3404. # Defaults to `1`. Configurable to `1`, `1.1`, `1.2`, or `1.3`. Note
  3405. # that setting this value higher than `1.2` will prevent federation to most
  3406. # of the public Matrix network: only configure it to `1.3` if you have an
  3407. # entirely private federation setup and you can ensure TLS 1.3 support.
  3408. #
  3409. #federation_client_minimum_tls_version: 1.2
  3410. # Skip federation certificate verification on the following whitelist
  3411. # of domains.
  3412. #
  3413. # This setting should only be used in very specific cases, such as
  3414. # federation over Tor hidden services and similar. For private networks
  3415. # of homeservers, you likely want to use a private CA instead.
  3416. #
  3417. # Only effective if federation_verify_certicates is `true`.
  3418. #
  3419. #federation_certificate_verification_whitelist:
  3420. # - lon.example.com
  3421. # - &quot;*.domain.com&quot;
  3422. # - &quot;*.onion&quot;
  3423. # List of custom certificate authorities for federation traffic.
  3424. #
  3425. # This setting should only normally be used within a private network of
  3426. # homeservers.
  3427. #
  3428. # Note that this list will replace those that are provided by your
  3429. # operating environment. Certificates must be in PEM format.
  3430. #
  3431. #federation_custom_ca_list:
  3432. # - myCA1.pem
  3433. # - myCA2.pem
  3434. # - myCA3.pem
  3435. ## Federation ##
  3436. # Restrict federation to the following whitelist of domains.
  3437. # N.B. we recommend also firewalling your federation listener to limit
  3438. # inbound federation traffic as early as possible, rather than relying
  3439. # purely on this application-layer restriction. If not specified, the
  3440. # default is to whitelist everything.
  3441. #
  3442. #federation_domain_whitelist:
  3443. # - lon.example.com
  3444. # - nyc.example.com
  3445. # - syd.example.com
  3446. # Report prometheus metrics on the age of PDUs being sent to and received from
  3447. # the following domains. This can be used to give an idea of &quot;delay&quot; on inbound
  3448. # and outbound federation, though be aware that any delay can be due to problems
  3449. # at either end or with the intermediate network.
  3450. #
  3451. # By default, no domains are monitored in this way.
  3452. #
  3453. #federation_metrics_domains:
  3454. # - matrix.org
  3455. # - example.com
  3456. # Uncomment to disable profile lookup over federation. By default, the
  3457. # Federation API allows other homeservers to obtain profile data of any user
  3458. # on this homeserver. Defaults to 'true'.
  3459. #
  3460. #allow_profile_lookup_over_federation: false
  3461. # Uncomment to disable device display name lookup over federation. By default, the
  3462. # Federation API allows other homeservers to obtain device display names of any user
  3463. # on this homeserver. Defaults to 'true'.
  3464. #
  3465. #allow_device_name_lookup_over_federation: false
  3466. ## Caching ##
  3467. # Caching can be configured through the following options.
  3468. #
  3469. # A cache 'factor' is a multiplier that can be applied to each of
  3470. # Synapse's caches in order to increase or decrease the maximum
  3471. # number of entries that can be stored.
  3472. # The number of events to cache in memory. Not affected by
  3473. # caches.global_factor.
  3474. #
  3475. #event_cache_size: 10K
  3476. caches:
  3477. # Controls the global cache factor, which is the default cache factor
  3478. # for all caches if a specific factor for that cache is not otherwise
  3479. # set.
  3480. #
  3481. # This can also be set by the &quot;SYNAPSE_CACHE_FACTOR&quot; environment
  3482. # variable. Setting by environment variable takes priority over
  3483. # setting through the config file.
  3484. #
  3485. # Defaults to 0.5, which will half the size of all caches.
  3486. #
  3487. #global_factor: 1.0
  3488. # A dictionary of cache name to cache factor for that individual
  3489. # cache. Overrides the global cache factor for a given cache.
  3490. #
  3491. # These can also be set through environment variables comprised
  3492. # of &quot;SYNAPSE_CACHE_FACTOR_&quot; + the name of the cache in capital
  3493. # letters and underscores. Setting by environment variable
  3494. # takes priority over setting through the config file.
  3495. # Ex. SYNAPSE_CACHE_FACTOR_GET_USERS_WHO_SHARE_ROOM_WITH_USER=2.0
  3496. #
  3497. # Some caches have '*' and other characters that are not
  3498. # alphanumeric or underscores. These caches can be named with or
  3499. # without the special characters stripped. For example, to specify
  3500. # the cache factor for `*stateGroupCache*` via an environment
  3501. # variable would be `SYNAPSE_CACHE_FACTOR_STATEGROUPCACHE=2.0`.
  3502. #
  3503. per_cache_factors:
  3504. #get_users_who_share_room_with_user: 2.0
  3505. # Controls whether cache entries are evicted after a specified time
  3506. # period. Defaults to true. Uncomment to disable this feature.
  3507. #
  3508. #expire_caches: false
  3509. # If expire_caches is enabled, this flag controls how long an entry can
  3510. # be in a cache without having been accessed before being evicted.
  3511. # Defaults to 30m. Uncomment to set a different time to live for cache entries.
  3512. #
  3513. #cache_entry_ttl: 30m
  3514. # Controls how long the results of a /sync request are cached for after
  3515. # a successful response is returned. A higher duration can help clients with
  3516. # intermittent connections, at the cost of higher memory usage.
  3517. #
  3518. # By default, this is zero, which means that sync responses are not cached
  3519. # at all.
  3520. #
  3521. #sync_response_cache_duration: 2m
  3522. ## Database ##
  3523. # The 'database' setting defines the database that synapse uses to store all of
  3524. # its data.
  3525. #
  3526. # 'name' gives the database engine to use: either 'sqlite3' (for SQLite) or
  3527. # 'psycopg2' (for PostgreSQL).
  3528. #
  3529. # 'txn_limit' gives the maximum number of transactions to run per connection
  3530. # before reconnecting. Defaults to 0, which means no limit.
  3531. #
  3532. # 'args' gives options which are passed through to the database engine,
  3533. # except for options starting 'cp_', which are used to configure the Twisted
  3534. # connection pool. For a reference to valid arguments, see:
  3535. # * for sqlite: https://docs.python.org/3/library/sqlite3.html#sqlite3.connect
  3536. # * for postgres: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
  3537. # * for the connection pool: https://twistedmatrix.com/documents/current/api/twisted.enterprise.adbapi.ConnectionPool.html#__init__
  3538. #
  3539. #
  3540. # Example SQLite configuration:
  3541. #
  3542. #database:
  3543. # name: sqlite3
  3544. # args:
  3545. # database: /path/to/homeserver.db
  3546. #
  3547. #
  3548. # Example Postgres configuration:
  3549. #
  3550. #database:
  3551. # name: psycopg2
  3552. # txn_limit: 10000
  3553. # args:
  3554. # user: synapse_user
  3555. # password: secretpassword
  3556. # database: synapse
  3557. # host: localhost
  3558. # port: 5432
  3559. # cp_min: 5
  3560. # cp_max: 10
  3561. #
  3562. # For more information on using Synapse with Postgres,
  3563. # see https://matrix-org.github.io/synapse/latest/postgres.html.
  3564. #
  3565. database:
  3566. name: sqlite3
  3567. args:
  3568. database: DATADIR/homeserver.db
  3569. ## Logging ##
  3570. # A yaml python logging config file as described by
  3571. # https://docs.python.org/3.7/library/logging.config.html#configuration-dictionary-schema
  3572. #
  3573. log_config: &quot;CONFDIR/SERVERNAME.log.config&quot;
  3574. ## Ratelimiting ##
  3575. # Ratelimiting settings for client actions (registration, login, messaging).
  3576. #
  3577. # Each ratelimiting configuration is made of two parameters:
  3578. # - per_second: number of requests a client can send per second.
  3579. # - burst_count: number of requests a client can send before being throttled.
  3580. #
  3581. # Synapse currently uses the following configurations:
  3582. # - one for messages that ratelimits sending based on the account the client
  3583. # is using
  3584. # - one for registration that ratelimits registration requests based on the
  3585. # client's IP address.
  3586. # - one for checking the validity of registration tokens that ratelimits
  3587. # requests based on the client's IP address.
  3588. # - one for login that ratelimits login requests based on the client's IP
  3589. # address.
  3590. # - one for login that ratelimits login requests based on the account the
  3591. # client is attempting to log into.
  3592. # - one for login that ratelimits login requests based on the account the
  3593. # client is attempting to log into, based on the amount of failed login
  3594. # attempts for this account.
  3595. # - one for ratelimiting redactions by room admins. If this is not explicitly
  3596. # set then it uses the same ratelimiting as per rc_message. This is useful
  3597. # to allow room admins to deal with abuse quickly.
  3598. # - two for ratelimiting number of rooms a user can join, &quot;local&quot; for when
  3599. # users are joining rooms the server is already in (this is cheap) vs
  3600. # &quot;remote&quot; for when users are trying to join rooms not on the server (which
  3601. # can be more expensive)
  3602. # - one for ratelimiting how often a user or IP can attempt to validate a 3PID.
  3603. # - two for ratelimiting how often invites can be sent in a room or to a
  3604. # specific user.
  3605. # - one for ratelimiting 3PID invites (i.e. invites sent to a third-party ID
  3606. # such as an email address or a phone number) based on the account that's
  3607. # sending the invite.
  3608. #
  3609. # The defaults are as shown below.
  3610. #
  3611. #rc_message:
  3612. # per_second: 0.2
  3613. # burst_count: 10
  3614. #
  3615. #rc_registration:
  3616. # per_second: 0.17
  3617. # burst_count: 3
  3618. #
  3619. #rc_registration_token_validity:
  3620. # per_second: 0.1
  3621. # burst_count: 5
  3622. #
  3623. #rc_login:
  3624. # address:
  3625. # per_second: 0.17
  3626. # burst_count: 3
  3627. # account:
  3628. # per_second: 0.17
  3629. # burst_count: 3
  3630. # failed_attempts:
  3631. # per_second: 0.17
  3632. # burst_count: 3
  3633. #
  3634. #rc_admin_redaction:
  3635. # per_second: 1
  3636. # burst_count: 50
  3637. #
  3638. #rc_joins:
  3639. # local:
  3640. # per_second: 0.1
  3641. # burst_count: 10
  3642. # remote:
  3643. # per_second: 0.01
  3644. # burst_count: 10
  3645. #
  3646. #rc_3pid_validation:
  3647. # per_second: 0.003
  3648. # burst_count: 5
  3649. #
  3650. #rc_invites:
  3651. # per_room:
  3652. # per_second: 0.3
  3653. # burst_count: 10
  3654. # per_user:
  3655. # per_second: 0.003
  3656. # burst_count: 5
  3657. #
  3658. #rc_third_party_invite:
  3659. # per_second: 0.2
  3660. # burst_count: 10
  3661. # Ratelimiting settings for incoming federation
  3662. #
  3663. # The rc_federation configuration is made up of the following settings:
  3664. # - window_size: window size in milliseconds
  3665. # - sleep_limit: number of federation requests from a single server in
  3666. # a window before the server will delay processing the request.
  3667. # - sleep_delay: duration in milliseconds to delay processing events
  3668. # from remote servers by if they go over the sleep limit.
  3669. # - reject_limit: maximum number of concurrent federation requests
  3670. # allowed from a single server
  3671. # - concurrent: number of federation requests to concurrently process
  3672. # from a single server
  3673. #
  3674. # The defaults are as shown below.
  3675. #
  3676. #rc_federation:
  3677. # window_size: 1000
  3678. # sleep_limit: 10
  3679. # sleep_delay: 500
  3680. # reject_limit: 50
  3681. # concurrent: 3
  3682. # Target outgoing federation transaction frequency for sending read-receipts,
  3683. # per-room.
  3684. #
  3685. # If we end up trying to send out more read-receipts, they will get buffered up
  3686. # into fewer transactions.
  3687. #
  3688. #federation_rr_transactions_per_room_per_second: 50
  3689. ## Media Store ##
  3690. # Enable the media store service in the Synapse master. Uncomment the
  3691. # following if you are using a separate media store worker.
  3692. #
  3693. #enable_media_repo: false
  3694. # Directory where uploaded images and attachments are stored.
  3695. #
  3696. media_store_path: &quot;DATADIR/media_store&quot;
  3697. # Media storage providers allow media to be stored in different
  3698. # locations.
  3699. #
  3700. #media_storage_providers:
  3701. # - module: file_system
  3702. # # Whether to store newly uploaded local files
  3703. # store_local: false
  3704. # # Whether to store newly downloaded remote files
  3705. # store_remote: false
  3706. # # Whether to wait for successful storage for local uploads
  3707. # store_synchronous: false
  3708. # config:
  3709. # directory: /mnt/some/other/directory
  3710. # The largest allowed upload size in bytes
  3711. #
  3712. # If you are using a reverse proxy you may also need to set this value in
  3713. # your reverse proxy's config. Notably Nginx has a small max body size by default.
  3714. # See https://matrix-org.github.io/synapse/latest/reverse_proxy.html.
  3715. #
  3716. #max_upload_size: 50M
  3717. # Maximum number of pixels that will be thumbnailed
  3718. #
  3719. #max_image_pixels: 32M
  3720. # Whether to generate new thumbnails on the fly to precisely match
  3721. # the resolution requested by the client. If true then whenever
  3722. # a new resolution is requested by the client the server will
  3723. # generate a new thumbnail. If false the server will pick a thumbnail
  3724. # from a precalculated list.
  3725. #
  3726. #dynamic_thumbnails: false
  3727. # List of thumbnails to precalculate when an image is uploaded.
  3728. #
  3729. #thumbnail_sizes:
  3730. # - width: 32
  3731. # height: 32
  3732. # method: crop
  3733. # - width: 96
  3734. # height: 96
  3735. # method: crop
  3736. # - width: 320
  3737. # height: 240
  3738. # method: scale
  3739. # - width: 640
  3740. # height: 480
  3741. # method: scale
  3742. # - width: 800
  3743. # height: 600
  3744. # method: scale
  3745. # Is the preview URL API enabled?
  3746. #
  3747. # 'false' by default: uncomment the following to enable it (and specify a
  3748. # url_preview_ip_range_blacklist blacklist).
  3749. #
  3750. #url_preview_enabled: true
  3751. # List of IP address CIDR ranges that the URL preview spider is denied
  3752. # from accessing. There are no defaults: you must explicitly
  3753. # specify a list for URL previewing to work. You should specify any
  3754. # internal services in your network that you do not want synapse to try
  3755. # to connect to, otherwise anyone in any Matrix room could cause your
  3756. # synapse to issue arbitrary GET requests to your internal services,
  3757. # causing serious security issues.
  3758. #
  3759. # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  3760. # listed here, since they correspond to unroutable addresses.)
  3761. #
  3762. # This must be specified if url_preview_enabled is set. It is recommended that
  3763. # you uncomment the following list as a starting point.
  3764. #
  3765. # Note: The value is ignored when an HTTP proxy is in use
  3766. #
  3767. #url_preview_ip_range_blacklist:
  3768. # - '127.0.0.0/8'
  3769. # - '10.0.0.0/8'
  3770. # - '172.16.0.0/12'
  3771. # - '192.168.0.0/16'
  3772. # - '100.64.0.0/10'
  3773. # - '192.0.0.0/24'
  3774. # - '169.254.0.0/16'
  3775. # - '192.88.99.0/24'
  3776. # - '198.18.0.0/15'
  3777. # - '192.0.2.0/24'
  3778. # - '198.51.100.0/24'
  3779. # - '203.0.113.0/24'
  3780. # - '224.0.0.0/4'
  3781. # - '::1/128'
  3782. # - 'fe80::/10'
  3783. # - 'fc00::/7'
  3784. # - '2001:db8::/32'
  3785. # - 'ff00::/8'
  3786. # - 'fec0::/10'
  3787. # List of IP address CIDR ranges that the URL preview spider is allowed
  3788. # to access even if they are specified in url_preview_ip_range_blacklist.
  3789. # This is useful for specifying exceptions to wide-ranging blacklisted
  3790. # target IP ranges - e.g. for enabling URL previews for a specific private
  3791. # website only visible in your network.
  3792. #
  3793. #url_preview_ip_range_whitelist:
  3794. # - '192.168.1.1'
  3795. # Optional list of URL matches that the URL preview spider is
  3796. # denied from accessing. You should use url_preview_ip_range_blacklist
  3797. # in preference to this, otherwise someone could define a public DNS
  3798. # entry that points to a private IP address and circumvent the blacklist.
  3799. # This is more useful if you know there is an entire shape of URL that
  3800. # you know that will never want synapse to try to spider.
  3801. #
  3802. # Each list entry is a dictionary of url component attributes as returned
  3803. # by urlparse.urlsplit as applied to the absolute form of the URL. See
  3804. # https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit
  3805. # The values of the dictionary are treated as an filename match pattern
  3806. # applied to that component of URLs, unless they start with a ^ in which
  3807. # case they are treated as a regular expression match. If all the
  3808. # specified component matches for a given list item succeed, the URL is
  3809. # blacklisted.
  3810. #
  3811. #url_preview_url_blacklist:
  3812. # # blacklist any URL with a username in its URI
  3813. # - username: '*'
  3814. #
  3815. # # blacklist all *.google.com URLs
  3816. # - netloc: 'google.com'
  3817. # - netloc: '*.google.com'
  3818. #
  3819. # # blacklist all plain HTTP URLs
  3820. # - scheme: 'http'
  3821. #
  3822. # # blacklist http(s)://www.acme.com/foo
  3823. # - netloc: 'www.acme.com'
  3824. # path: '/foo'
  3825. #
  3826. # # blacklist any URL with a literal IPv4 address
  3827. # - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
  3828. # The largest allowed URL preview spidering size in bytes
  3829. #
  3830. #max_spider_size: 10M
  3831. # A list of values for the Accept-Language HTTP header used when
  3832. # downloading webpages during URL preview generation. This allows
  3833. # Synapse to specify the preferred languages that URL previews should
  3834. # be in when communicating with remote servers.
  3835. #
  3836. # Each value is a IETF language tag; a 2-3 letter identifier for a
  3837. # language, optionally followed by subtags separated by '-', specifying
  3838. # a country or region variant.
  3839. #
  3840. # Multiple values can be provided, and a weight can be added to each by
  3841. # using quality value syntax (;q=). '*' translates to any language.
  3842. #
  3843. # Defaults to &quot;en&quot;.
  3844. #
  3845. # Example:
  3846. #
  3847. # url_preview_accept_language:
  3848. # - en-UK
  3849. # - en-US;q=0.9
  3850. # - fr;q=0.8
  3851. # - *;q=0.7
  3852. #
  3853. url_preview_accept_language:
  3854. # - en
  3855. # oEmbed allows for easier embedding content from a website. It can be
  3856. # used for generating URLs previews of services which support it.
  3857. #
  3858. oembed:
  3859. # A default list of oEmbed providers is included with Synapse.
  3860. #
  3861. # Uncomment the following to disable using these default oEmbed URLs.
  3862. # Defaults to 'false'.
  3863. #
  3864. #disable_default_providers: true
  3865. # Additional files with oEmbed configuration (each should be in the
  3866. # form of providers.json).
  3867. #
  3868. # By default, this list is empty (so only the default providers.json
  3869. # is used).
  3870. #
  3871. #additional_providers:
  3872. # - oembed/my_providers.json
  3873. ## Captcha ##
  3874. # See docs/CAPTCHA_SETUP.md for full details of configuring this.
  3875. # This homeserver's ReCAPTCHA public key. Must be specified if
  3876. # enable_registration_captcha is enabled.
  3877. #
  3878. #recaptcha_public_key: &quot;YOUR_PUBLIC_KEY&quot;
  3879. # This homeserver's ReCAPTCHA private key. Must be specified if
  3880. # enable_registration_captcha is enabled.
  3881. #
  3882. #recaptcha_private_key: &quot;YOUR_PRIVATE_KEY&quot;
  3883. # Uncomment to enable ReCaptcha checks when registering, preventing signup
  3884. # unless a captcha is answered. Requires a valid ReCaptcha
  3885. # public/private key. Defaults to 'false'.
  3886. #
  3887. #enable_registration_captcha: true
  3888. # The API endpoint to use for verifying m.login.recaptcha responses.
  3889. # Defaults to &quot;https://www.recaptcha.net/recaptcha/api/siteverify&quot;.
  3890. #
  3891. #recaptcha_siteverify_api: &quot;https://my.recaptcha.site&quot;
  3892. ## TURN ##
  3893. # The public URIs of the TURN server to give to clients
  3894. #
  3895. #turn_uris: []
  3896. # The shared secret used to compute passwords for the TURN server
  3897. #
  3898. #turn_shared_secret: &quot;YOUR_SHARED_SECRET&quot;
  3899. # The Username and password if the TURN server needs them and
  3900. # does not use a token
  3901. #
  3902. #turn_username: &quot;TURNSERVER_USERNAME&quot;
  3903. #turn_password: &quot;TURNSERVER_PASSWORD&quot;
  3904. # How long generated TURN credentials last
  3905. #
  3906. #turn_user_lifetime: 1h
  3907. # Whether guests should be allowed to use the TURN server.
  3908. # This defaults to True, otherwise VoIP will be unreliable for guests.
  3909. # However, it does introduce a slight security risk as it allows users to
  3910. # connect to arbitrary endpoints without having first signed up for a
  3911. # valid account (e.g. by passing a CAPTCHA).
  3912. #
  3913. #turn_allow_guests: true
  3914. ## Registration ##
  3915. #
  3916. # Registration can be rate-limited using the parameters in the &quot;Ratelimiting&quot;
  3917. # section of this file.
  3918. # Enable registration for new users.
  3919. #
  3920. #enable_registration: false
  3921. # Time that a user's session remains valid for, after they log in.
  3922. #
  3923. # Note that this is not currently compatible with guest logins.
  3924. #
  3925. # Note also that this is calculated at login time: changes are not applied
  3926. # retrospectively to users who have already logged in.
  3927. #
  3928. # By default, this is infinite.
  3929. #
  3930. #session_lifetime: 24h
  3931. # Time that an access token remains valid for, if the session is
  3932. # using refresh tokens.
  3933. # For more information about refresh tokens, please see the manual.
  3934. # Note that this only applies to clients which advertise support for
  3935. # refresh tokens.
  3936. #
  3937. # Note also that this is calculated at login time and refresh time:
  3938. # changes are not applied to existing sessions until they are refreshed.
  3939. #
  3940. # By default, this is 5 minutes.
  3941. #
  3942. #refreshable_access_token_lifetime: 5m
  3943. # Time that a refresh token remains valid for (provided that it is not
  3944. # exchanged for another one first).
  3945. # This option can be used to automatically log-out inactive sessions.
  3946. # Please see the manual for more information.
  3947. #
  3948. # Note also that this is calculated at login time and refresh time:
  3949. # changes are not applied to existing sessions until they are refreshed.
  3950. #
  3951. # By default, this is infinite.
  3952. #
  3953. #refresh_token_lifetime: 24h
  3954. # Time that an access token remains valid for, if the session is NOT
  3955. # using refresh tokens.
  3956. # Please note that not all clients support refresh tokens, so setting
  3957. # this to a short value may be inconvenient for some users who will
  3958. # then be logged out frequently.
  3959. #
  3960. # Note also that this is calculated at login time: changes are not applied
  3961. # retrospectively to existing sessions for users that have already logged in.
  3962. #
  3963. # By default, this is infinite.
  3964. #
  3965. #nonrefreshable_access_token_lifetime: 24h
  3966. # The user must provide all of the below types of 3PID when registering.
  3967. #
  3968. #registrations_require_3pid:
  3969. # - email
  3970. # - msisdn
  3971. # Explicitly disable asking for MSISDNs from the registration
  3972. # flow (overrides registrations_require_3pid if MSISDNs are set as required)
  3973. #
  3974. #disable_msisdn_registration: true
  3975. # Mandate that users are only allowed to associate certain formats of
  3976. # 3PIDs with accounts on this server.
  3977. #
  3978. #allowed_local_3pids:
  3979. # - medium: email
  3980. # pattern: '^[^@]+@matrix\.org$'
  3981. # - medium: email
  3982. # pattern: '^[^@]+@vector\.im$'
  3983. # - medium: msisdn
  3984. # pattern: '\+44'
  3985. # Enable 3PIDs lookup requests to identity servers from this server.
  3986. #
  3987. #enable_3pid_lookup: true
  3988. # Require users to submit a token during registration.
  3989. # Tokens can be managed using the admin API:
  3990. # https://matrix-org.github.io/synapse/latest/usage/administration/admin_api/registration_tokens.html
  3991. # Note that `enable_registration` must be set to `true`.
  3992. # Disabling this option will not delete any tokens previously generated.
  3993. # Defaults to false. Uncomment the following to require tokens:
  3994. #
  3995. #registration_requires_token: true
  3996. # If set, allows registration of standard or admin accounts by anyone who
  3997. # has the shared secret, even if registration is otherwise disabled.
  3998. #
  3999. #registration_shared_secret: &lt;PRIVATE STRING&gt;
  4000. # Set the number of bcrypt rounds used to generate password hash.
  4001. # Larger numbers increase the work factor needed to generate the hash.
  4002. # The default number is 12 (which equates to 2^12 rounds).
  4003. # N.B. that increasing this will exponentially increase the time required
  4004. # to register or login - e.g. 24 =&gt; 2^24 rounds which will take &gt;20 mins.
  4005. #
  4006. #bcrypt_rounds: 12
  4007. # Allows users to register as guests without a password/email/etc, and
  4008. # participate in rooms hosted on this server which have been made
  4009. # accessible to anonymous users.
  4010. #
  4011. #allow_guest_access: false
  4012. # The identity server which we suggest that clients should use when users log
  4013. # in on this server.
  4014. #
  4015. # (By default, no suggestion is made, so it is left up to the client.
  4016. # This setting is ignored unless public_baseurl is also explicitly set.)
  4017. #
  4018. #default_identity_server: https://matrix.org
  4019. # Handle threepid (email/phone etc) registration and password resets through a set of
  4020. # *trusted* identity servers. Note that this allows the configured identity server to
  4021. # reset passwords for accounts!
  4022. #
  4023. # Be aware that if `email` is not set, and SMTP options have not been
  4024. # configured in the email config block, registration and user password resets via
  4025. # email will be globally disabled.
  4026. #
  4027. # Additionally, if `msisdn` is not set, registration and password resets via msisdn
  4028. # will be disabled regardless, and users will not be able to associate an msisdn
  4029. # identifier to their account. This is due to Synapse currently not supporting
  4030. # any method of sending SMS messages on its own.
  4031. #
  4032. # To enable using an identity server for operations regarding a particular third-party
  4033. # identifier type, set the value to the URL of that identity server as shown in the
  4034. # examples below.
  4035. #
  4036. # Servers handling the these requests must answer the `/requestToken` endpoints defined
  4037. # by the Matrix Identity Service API specification:
  4038. # https://matrix.org/docs/spec/identity_service/latest
  4039. #
  4040. account_threepid_delegates:
  4041. #email: https://example.com # Delegate email sending to example.com
  4042. #msisdn: http://localhost:8090 # Delegate SMS sending to this local process
  4043. # Whether users are allowed to change their displayname after it has
  4044. # been initially set. Useful when provisioning users based on the
  4045. # contents of a third-party directory.
  4046. #
  4047. # Does not apply to server administrators. Defaults to 'true'
  4048. #
  4049. #enable_set_displayname: false
  4050. # Whether users are allowed to change their avatar after it has been
  4051. # initially set. Useful when provisioning users based on the contents
  4052. # of a third-party directory.
  4053. #
  4054. # Does not apply to server administrators. Defaults to 'true'
  4055. #
  4056. #enable_set_avatar_url: false
  4057. # Whether users can change the 3PIDs associated with their accounts
  4058. # (email address and msisdn).
  4059. #
  4060. # Defaults to 'true'
  4061. #
  4062. #enable_3pid_changes: false
  4063. # Users who register on this homeserver will automatically be joined
  4064. # to these rooms.
  4065. #
  4066. # By default, any room aliases included in this list will be created
  4067. # as a publicly joinable room when the first user registers for the
  4068. # homeserver. This behaviour can be customised with the settings below.
  4069. # If the room already exists, make certain it is a publicly joinable
  4070. # room. The join rule of the room must be set to 'public'.
  4071. #
  4072. #auto_join_rooms:
  4073. # - &quot;#example:example.com&quot;
  4074. # Where auto_join_rooms are specified, setting this flag ensures that the
  4075. # the rooms exist by creating them when the first user on the
  4076. # homeserver registers.
  4077. #
  4078. # By default the auto-created rooms are publicly joinable from any federated
  4079. # server. Use the autocreate_auto_join_rooms_federated and
  4080. # autocreate_auto_join_room_preset settings below to customise this behaviour.
  4081. #
  4082. # Setting to false means that if the rooms are not manually created,
  4083. # users cannot be auto-joined since they do not exist.
  4084. #
  4085. # Defaults to true. Uncomment the following line to disable automatically
  4086. # creating auto-join rooms.
  4087. #
  4088. #autocreate_auto_join_rooms: false
  4089. # Whether the auto_join_rooms that are auto-created are available via
  4090. # federation. Only has an effect if autocreate_auto_join_rooms is true.
  4091. #
  4092. # Note that whether a room is federated cannot be modified after
  4093. # creation.
  4094. #
  4095. # Defaults to true: the room will be joinable from other servers.
  4096. # Uncomment the following to prevent users from other homeservers from
  4097. # joining these rooms.
  4098. #
  4099. #autocreate_auto_join_rooms_federated: false
  4100. # The room preset to use when auto-creating one of auto_join_rooms. Only has an
  4101. # effect if autocreate_auto_join_rooms is true.
  4102. #
  4103. # This can be one of &quot;public_chat&quot;, &quot;private_chat&quot;, or &quot;trusted_private_chat&quot;.
  4104. # If a value of &quot;private_chat&quot; or &quot;trusted_private_chat&quot; is used then
  4105. # auto_join_mxid_localpart must also be configured.
  4106. #
  4107. # Defaults to &quot;public_chat&quot;, meaning that the room is joinable by anyone, including
  4108. # federated servers if autocreate_auto_join_rooms_federated is true (the default).
  4109. # Uncomment the following to require an invitation to join these rooms.
  4110. #
  4111. #autocreate_auto_join_room_preset: private_chat
  4112. # The local part of the user id which is used to create auto_join_rooms if
  4113. # autocreate_auto_join_rooms is true. If this is not provided then the
  4114. # initial user account that registers will be used to create the rooms.
  4115. #
  4116. # The user id is also used to invite new users to any auto-join rooms which
  4117. # are set to invite-only.
  4118. #
  4119. # It *must* be configured if autocreate_auto_join_room_preset is set to
  4120. # &quot;private_chat&quot; or &quot;trusted_private_chat&quot;.
  4121. #
  4122. # Note that this must be specified in order for new users to be correctly
  4123. # invited to any auto-join rooms which have been set to invite-only (either
  4124. # at the time of creation or subsequently).
  4125. #
  4126. # Note that, if the room already exists, this user must be joined and
  4127. # have the appropriate permissions to invite new members.
  4128. #
  4129. #auto_join_mxid_localpart: system
  4130. # When auto_join_rooms is specified, setting this flag to false prevents
  4131. # guest accounts from being automatically joined to the rooms.
  4132. #
  4133. # Defaults to true.
  4134. #
  4135. #auto_join_rooms_for_guests: false
  4136. # Whether to inhibit errors raised when registering a new account if the user ID
  4137. # already exists. If turned on, that requests to /register/available will always
  4138. # show a user ID as available, and Synapse won't raise an error when starting
  4139. # a registration with a user ID that already exists. However, Synapse will still
  4140. # raise an error if the registration completes and the username conflicts.
  4141. #
  4142. # Defaults to false.
  4143. #
  4144. #inhibit_user_in_use_error: true
  4145. ## Metrics ###
  4146. # Enable collection and rendering of performance metrics
  4147. #
  4148. #enable_metrics: false
  4149. # Enable sentry integration
  4150. # NOTE: While attempts are made to ensure that the logs don't contain
  4151. # any sensitive information, this cannot be guaranteed. By enabling
  4152. # this option the sentry server may therefore receive sensitive
  4153. # information, and it in turn may then diseminate sensitive information
  4154. # through insecure notification channels if so configured.
  4155. #
  4156. #sentry:
  4157. # dsn: &quot;...&quot;
  4158. # Flags to enable Prometheus metrics which are not suitable to be
  4159. # enabled by default, either for performance reasons or limited use.
  4160. #
  4161. metrics_flags:
  4162. # Publish synapse_federation_known_servers, a gauge of the number of
  4163. # servers this homeserver knows about, including itself. May cause
  4164. # performance problems on large homeservers.
  4165. #
  4166. #known_servers: true
  4167. # Whether or not to report anonymized homeserver usage statistics.
  4168. #
  4169. #report_stats: true|false
  4170. # The endpoint to report the anonymized homeserver usage statistics to.
  4171. # Defaults to https://matrix.org/report-usage-stats/push
  4172. #
  4173. #report_stats_endpoint: https://example.com/report-usage-stats/push
  4174. ## API Configuration ##
  4175. # Controls for the state that is shared with users who receive an invite
  4176. # to a room
  4177. #
  4178. room_prejoin_state:
  4179. # By default, the following state event types are shared with users who
  4180. # receive invites to the room:
  4181. #
  4182. # - m.room.join_rules
  4183. # - m.room.canonical_alias
  4184. # - m.room.avatar
  4185. # - m.room.encryption
  4186. # - m.room.name
  4187. # - m.room.create
  4188. # - m.room.topic
  4189. #
  4190. # Uncomment the following to disable these defaults (so that only the event
  4191. # types listed in 'additional_event_types' are shared). Defaults to 'false'.
  4192. #
  4193. #disable_default_event_types: true
  4194. # Additional state event types to share with users when they are invited
  4195. # to a room.
  4196. #
  4197. # By default, this list is empty (so only the default event types are shared).
  4198. #
  4199. #additional_event_types:
  4200. # - org.example.custom.event.type
  4201. # We record the IP address of clients used to access the API for various
  4202. # reasons, including displaying it to the user in the &quot;Where you're signed in&quot;
  4203. # dialog.
  4204. #
  4205. # By default, when puppeting another user via the admin API, the client IP
  4206. # address is recorded against the user who created the access token (ie, the
  4207. # admin user), and *not* the puppeted user.
  4208. #
  4209. # Uncomment the following to also record the IP address against the puppeted
  4210. # user. (This also means that the puppeted user will count as an &quot;active&quot; user
  4211. # for the purpose of monthly active user tracking - see 'limit_usage_by_mau' etc
  4212. # above.)
  4213. #
  4214. #track_puppeted_user_ips: true
  4215. # A list of application service config files to use
  4216. #
  4217. #app_service_config_files:
  4218. # - app_service_1.yaml
  4219. # - app_service_2.yaml
  4220. # Uncomment to enable tracking of application service IP addresses. Implicitly
  4221. # enables MAU tracking for application service users.
  4222. #
  4223. #track_appservice_user_ips: true
  4224. # a secret which is used to sign access tokens. If none is specified,
  4225. # the registration_shared_secret is used, if one is given; otherwise,
  4226. # a secret key is derived from the signing key.
  4227. #
  4228. #macaroon_secret_key: &lt;PRIVATE STRING&gt;
  4229. # a secret which is used to calculate HMACs for form values, to stop
  4230. # falsification of values. Must be specified for the User Consent
  4231. # forms to work.
  4232. #
  4233. #form_secret: &lt;PRIVATE STRING&gt;
  4234. ## Signing Keys ##
  4235. # Path to the signing key to sign messages with
  4236. #
  4237. signing_key_path: &quot;CONFDIR/SERVERNAME.signing.key&quot;
  4238. # The keys that the server used to sign messages with but won't use
  4239. # to sign new messages.
  4240. #
  4241. old_signing_keys:
  4242. # For each key, `key` should be the base64-encoded public key, and
  4243. # `expired_ts`should be the time (in milliseconds since the unix epoch) that
  4244. # it was last used.
  4245. #
  4246. # It is possible to build an entry from an old signing.key file using the
  4247. # `export_signing_key` script which is provided with synapse.
  4248. #
  4249. # For example:
  4250. #
  4251. #&quot;ed25519:id&quot;: { key: &quot;base64string&quot;, expired_ts: 123456789123 }
  4252. # How long key response published by this server is valid for.
  4253. # Used to set the valid_until_ts in /key/v2 APIs.
  4254. # Determines how quickly servers will query to check which keys
  4255. # are still valid.
  4256. #
  4257. #key_refresh_interval: 1d
  4258. # The trusted servers to download signing keys from.
  4259. #
  4260. # When we need to fetch a signing key, each server is tried in parallel.
  4261. #
  4262. # Normally, the connection to the key server is validated via TLS certificates.
  4263. # Additional security can be provided by configuring a `verify key`, which
  4264. # will make synapse check that the response is signed by that key.
  4265. #
  4266. # This setting supercedes an older setting named `perspectives`. The old format
  4267. # is still supported for backwards-compatibility, but it is deprecated.
  4268. #
  4269. # 'trusted_key_servers' defaults to matrix.org, but using it will generate a
  4270. # warning on start-up. To suppress this warning, set
  4271. # 'suppress_key_server_warning' to true.
  4272. #
  4273. # Options for each entry in the list include:
  4274. #
  4275. # server_name: the name of the server. required.
  4276. #
  4277. # verify_keys: an optional map from key id to base64-encoded public key.
  4278. # If specified, we will check that the response is signed by at least
  4279. # one of the given keys.
  4280. #
  4281. # accept_keys_insecurely: a boolean. Normally, if `verify_keys` is unset,
  4282. # and federation_verify_certificates is not `true`, synapse will refuse
  4283. # to start, because this would allow anyone who can spoof DNS responses
  4284. # to masquerade as the trusted key server. If you know what you are doing
  4285. # and are sure that your network environment provides a secure connection
  4286. # to the key server, you can set this to `true` to override this
  4287. # behaviour.
  4288. #
  4289. # An example configuration might look like:
  4290. #
  4291. #trusted_key_servers:
  4292. # - server_name: &quot;my_trusted_server.example.com&quot;
  4293. # verify_keys:
  4294. # &quot;ed25519:auto&quot;: &quot;abcdefghijklmnopqrstuvwxyzabcdefghijklmopqr&quot;
  4295. # - server_name: &quot;my_other_trusted_server.example.com&quot;
  4296. #
  4297. trusted_key_servers:
  4298. - server_name: &quot;matrix.org&quot;
  4299. # Uncomment the following to disable the warning that is emitted when the
  4300. # trusted_key_servers include 'matrix.org'. See above.
  4301. #
  4302. #suppress_key_server_warning: true
  4303. # The signing keys to use when acting as a trusted key server. If not specified
  4304. # defaults to the server signing key.
  4305. #
  4306. # Can contain multiple keys, one per line.
  4307. #
  4308. #key_server_signing_keys_path: &quot;key_server_signing_keys.key&quot;
  4309. ## Single sign-on integration ##
  4310. # The following settings can be used to make Synapse use a single sign-on
  4311. # provider for authentication, instead of its internal password database.
  4312. #
  4313. # You will probably also want to set the following options to `false` to
  4314. # disable the regular login/registration flows:
  4315. # * enable_registration
  4316. # * password_config.enabled
  4317. #
  4318. # You will also want to investigate the settings under the &quot;sso&quot; configuration
  4319. # section below.
  4320. # Enable SAML2 for registration and login. Uses pysaml2.
  4321. #
  4322. # At least one of `sp_config` or `config_path` must be set in this section to
  4323. # enable SAML login.
  4324. #
  4325. # Once SAML support is enabled, a metadata file will be exposed at
  4326. # https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/metadata.xml, which you may be able to
  4327. # use to configure your SAML IdP with. Alternatively, you can manually configure
  4328. # the IdP to use an ACS location of
  4329. # https://&lt;server&gt;:&lt;port&gt;/_synapse/client/saml2/authn_response.
  4330. #
  4331. saml2_config:
  4332. # `sp_config` is the configuration for the pysaml2 Service Provider.
  4333. # See pysaml2 docs for format of config.
  4334. #
  4335. # Default values will be used for the 'entityid' and 'service' settings,
  4336. # so it is not normally necessary to specify them unless you need to
  4337. # override them.
  4338. #
  4339. sp_config:
  4340. # Point this to the IdP's metadata. You must provide either a local
  4341. # file via the `local` attribute or (preferably) a URL via the
  4342. # `remote` attribute.
  4343. #
  4344. #metadata:
  4345. # local: [&quot;saml2/idp.xml&quot;]
  4346. # remote:
  4347. # - url: https://our_idp/metadata.xml
  4348. # Allowed clock difference in seconds between the homeserver and IdP.
  4349. #
  4350. # Uncomment the below to increase the accepted time difference from 0 to 3 seconds.
  4351. #
  4352. #accepted_time_diff: 3
  4353. # By default, the user has to go to our login page first. If you'd like
  4354. # to allow IdP-initiated login, set 'allow_unsolicited: true' in a
  4355. # 'service.sp' section:
  4356. #
  4357. #service:
  4358. # sp:
  4359. # allow_unsolicited: true
  4360. # The examples below are just used to generate our metadata xml, and you
  4361. # may well not need them, depending on your setup. Alternatively you
  4362. # may need a whole lot more detail - see the pysaml2 docs!
  4363. #description: [&quot;My awesome SP&quot;, &quot;en&quot;]
  4364. #name: [&quot;Test SP&quot;, &quot;en&quot;]
  4365. #ui_info:
  4366. # display_name:
  4367. # - lang: en
  4368. # text: &quot;Display Name is the descriptive name of your service.&quot;
  4369. # description:
  4370. # - lang: en
  4371. # text: &quot;Description should be a short paragraph explaining the purpose of the service.&quot;
  4372. # information_url:
  4373. # - lang: en
  4374. # text: &quot;https://example.com/terms-of-service&quot;
  4375. # privacy_statement_url:
  4376. # - lang: en
  4377. # text: &quot;https://example.com/privacy-policy&quot;
  4378. # keywords:
  4379. # - lang: en
  4380. # text: [&quot;Matrix&quot;, &quot;Element&quot;]
  4381. # logo:
  4382. # - lang: en
  4383. # text: &quot;https://example.com/logo.svg&quot;
  4384. # width: &quot;200&quot;
  4385. # height: &quot;80&quot;
  4386. #organization:
  4387. # name: Example com
  4388. # display_name:
  4389. # - [&quot;Example co&quot;, &quot;en&quot;]
  4390. # url: &quot;http://example.com&quot;
  4391. #contact_person:
  4392. # - given_name: Bob
  4393. # sur_name: &quot;the Sysadmin&quot;
  4394. # email_address&quot;: [&quot;admin@example.com&quot;]
  4395. # contact_type&quot;: technical
  4396. # Instead of putting the config inline as above, you can specify a
  4397. # separate pysaml2 configuration file:
  4398. #
  4399. #config_path: &quot;CONFDIR/sp_conf.py&quot;
  4400. # The lifetime of a SAML session. This defines how long a user has to
  4401. # complete the authentication process, if allow_unsolicited is unset.
  4402. # The default is 15 minutes.
  4403. #
  4404. #saml_session_lifetime: 5m
  4405. # An external module can be provided here as a custom solution to
  4406. # mapping attributes returned from a saml provider onto a matrix user.
  4407. #
  4408. user_mapping_provider:
  4409. # The custom module's class. Uncomment to use a custom module.
  4410. #
  4411. #module: mapping_provider.SamlMappingProvider
  4412. # Custom configuration values for the module. Below options are
  4413. # intended for the built-in provider, they should be changed if
  4414. # using a custom module. This section will be passed as a Python
  4415. # dictionary to the module's `parse_config` method.
  4416. #
  4417. config:
  4418. # The SAML attribute (after mapping via the attribute maps) to use
  4419. # to derive the Matrix ID from. 'uid' by default.
  4420. #
  4421. # Note: This used to be configured by the
  4422. # saml2_config.mxid_source_attribute option. If that is still
  4423. # defined, its value will be used instead.
  4424. #
  4425. #mxid_source_attribute: displayName
  4426. # The mapping system to use for mapping the saml attribute onto a
  4427. # matrix ID.
  4428. #
  4429. # Options include:
  4430. # * 'hexencode' (which maps unpermitted characters to '=xx')
  4431. # * 'dotreplace' (which replaces unpermitted characters with
  4432. # '.').
  4433. # The default is 'hexencode'.
  4434. #
  4435. # Note: This used to be configured by the
  4436. # saml2_config.mxid_mapping option. If that is still defined, its
  4437. # value will be used instead.
  4438. #
  4439. #mxid_mapping: dotreplace
  4440. # In previous versions of synapse, the mapping from SAML attribute to
  4441. # MXID was always calculated dynamically rather than stored in a
  4442. # table. For backwards- compatibility, we will look for user_ids
  4443. # matching such a pattern before creating a new account.
  4444. #
  4445. # This setting controls the SAML attribute which will be used for this
  4446. # backwards-compatibility lookup. Typically it should be 'uid', but if
  4447. # the attribute maps are changed, it may be necessary to change it.
  4448. #
  4449. # The default is 'uid'.
  4450. #
  4451. #grandfathered_mxid_source_attribute: upn
  4452. # It is possible to configure Synapse to only allow logins if SAML attributes
  4453. # match particular values. The requirements can be listed under
  4454. # `attribute_requirements` as shown below. All of the listed attributes must
  4455. # match for the login to be permitted.
  4456. #
  4457. #attribute_requirements:
  4458. # - attribute: userGroup
  4459. # value: &quot;staff&quot;
  4460. # - attribute: department
  4461. # value: &quot;sales&quot;
  4462. # If the metadata XML contains multiple IdP entities then the `idp_entityid`
  4463. # option must be set to the entity to redirect users to.
  4464. #
  4465. # Most deployments only have a single IdP entity and so should omit this
  4466. # option.
  4467. #
  4468. #idp_entityid: 'https://our_idp/entityid'
  4469. # List of OpenID Connect (OIDC) / OAuth 2.0 identity providers, for registration
  4470. # and login.
  4471. #
  4472. # Options for each entry include:
  4473. #
  4474. # idp_id: a unique identifier for this identity provider. Used internally
  4475. # by Synapse; should be a single word such as 'github'.
  4476. #
  4477. # Note that, if this is changed, users authenticating via that provider
  4478. # will no longer be recognised as the same user!
  4479. #
  4480. # (Use &quot;oidc&quot; here if you are migrating from an old &quot;oidc_config&quot;
  4481. # configuration.)
  4482. #
  4483. # idp_name: A user-facing name for this identity provider, which is used to
  4484. # offer the user a choice of login mechanisms.
  4485. #
  4486. # idp_icon: An optional icon for this identity provider, which is presented
  4487. # by clients and Synapse's own IdP picker page. If given, must be an
  4488. # MXC URI of the format mxc://&lt;server-name&gt;/&lt;media-id&gt;. (An easy way to
  4489. # obtain such an MXC URI is to upload an image to an (unencrypted) room
  4490. # and then copy the &quot;url&quot; from the source of the event.)
  4491. #
  4492. # idp_brand: An optional brand for this identity provider, allowing clients
  4493. # to style the login flow according to the identity provider in question.
  4494. # See the spec for possible options here.
  4495. #
  4496. # discover: set to 'false' to disable the use of the OIDC discovery mechanism
  4497. # to discover endpoints. Defaults to true.
  4498. #
  4499. # issuer: Required. The OIDC issuer. Used to validate tokens and (if discovery
  4500. # is enabled) to discover the provider's endpoints.
  4501. #
  4502. # client_id: Required. oauth2 client id to use.
  4503. #
  4504. # client_secret: oauth2 client secret to use. May be omitted if
  4505. # client_secret_jwt_key is given, or if client_auth_method is 'none'.
  4506. #
  4507. # client_secret_jwt_key: Alternative to client_secret: details of a key used
  4508. # to create a JSON Web Token to be used as an OAuth2 client secret. If
  4509. # given, must be a dictionary with the following properties:
  4510. #
  4511. # key: a pem-encoded signing key. Must be a suitable key for the
  4512. # algorithm specified. Required unless 'key_file' is given.
  4513. #
  4514. # key_file: the path to file containing a pem-encoded signing key file.
  4515. # Required unless 'key' is given.
  4516. #
  4517. # jwt_header: a dictionary giving properties to include in the JWT
  4518. # header. Must include the key 'alg', giving the algorithm used to
  4519. # sign the JWT, such as &quot;ES256&quot;, using the JWA identifiers in
  4520. # RFC7518.
  4521. #
  4522. # jwt_payload: an optional dictionary giving properties to include in
  4523. # the JWT payload. Normally this should include an 'iss' key.
  4524. #
  4525. # client_auth_method: auth method to use when exchanging the token. Valid
  4526. # values are 'client_secret_basic' (default), 'client_secret_post' and
  4527. # 'none'.
  4528. #
  4529. # scopes: list of scopes to request. This should normally include the &quot;openid&quot;
  4530. # scope. Defaults to [&quot;openid&quot;].
  4531. #
  4532. # authorization_endpoint: the oauth2 authorization endpoint. Required if
  4533. # provider discovery is disabled.
  4534. #
  4535. # token_endpoint: the oauth2 token endpoint. Required if provider discovery is
  4536. # disabled.
  4537. #
  4538. # userinfo_endpoint: the OIDC userinfo endpoint. Required if discovery is
  4539. # disabled and the 'openid' scope is not requested.
  4540. #
  4541. # jwks_uri: URI where to fetch the JWKS. Required if discovery is disabled and
  4542. # the 'openid' scope is used.
  4543. #
  4544. # skip_verification: set to 'true' to skip metadata verification. Use this if
  4545. # you are connecting to a provider that is not OpenID Connect compliant.
  4546. # Defaults to false. Avoid this in production.
  4547. #
  4548. # user_profile_method: Whether to fetch the user profile from the userinfo
  4549. # endpoint, or to rely on the data returned in the id_token from the
  4550. # token_endpoint.
  4551. #
  4552. # Valid values are: 'auto' or 'userinfo_endpoint'.
  4553. #
  4554. # Defaults to 'auto', which uses the userinfo endpoint if 'openid' is
  4555. # not included in 'scopes'. Set to 'userinfo_endpoint' to always use the
  4556. # userinfo endpoint.
  4557. #
  4558. # allow_existing_users: set to 'true' to allow a user logging in via OIDC to
  4559. # match a pre-existing account instead of failing. This could be used if
  4560. # switching from password logins to OIDC. Defaults to false.
  4561. #
  4562. # user_mapping_provider: Configuration for how attributes returned from a OIDC
  4563. # provider are mapped onto a matrix user. This setting has the following
  4564. # sub-properties:
  4565. #
  4566. # module: The class name of a custom mapping module. Default is
  4567. # 'synapse.handlers.oidc.JinjaOidcMappingProvider'.
  4568. # See https://matrix-org.github.io/synapse/latest/sso_mapping_providers.html#openid-mapping-providers
  4569. # for information on implementing a custom mapping provider.
  4570. #
  4571. # config: Configuration for the mapping provider module. This section will
  4572. # be passed as a Python dictionary to the user mapping provider
  4573. # module's `parse_config` method.
  4574. #
  4575. # For the default provider, the following settings are available:
  4576. #
  4577. # subject_claim: name of the claim containing a unique identifier
  4578. # for the user. Defaults to 'sub', which OpenID Connect
  4579. # compliant providers should provide.
  4580. #
  4581. # localpart_template: Jinja2 template for the localpart of the MXID.
  4582. # If this is not set, the user will be prompted to choose their
  4583. # own username (see 'sso_auth_account_details.html' in the 'sso'
  4584. # section of this file).
  4585. #
  4586. # display_name_template: Jinja2 template for the display name to set
  4587. # on first login. If unset, no displayname will be set.
  4588. #
  4589. # email_template: Jinja2 template for the email address of the user.
  4590. # If unset, no email address will be added to the account.
  4591. #
  4592. # extra_attributes: a map of Jinja2 templates for extra attributes
  4593. # to send back to the client during login.
  4594. # Note that these are non-standard and clients will ignore them
  4595. # without modifications.
  4596. #
  4597. # When rendering, the Jinja2 templates are given a 'user' variable,
  4598. # which is set to the claims returned by the UserInfo Endpoint and/or
  4599. # in the ID Token.
  4600. #
  4601. # It is possible to configure Synapse to only allow logins if certain attributes
  4602. # match particular values in the OIDC userinfo. The requirements can be listed under
  4603. # `attribute_requirements` as shown below. All of the listed attributes must
  4604. # match for the login to be permitted. Additional attributes can be added to
  4605. # userinfo by expanding the `scopes` section of the OIDC config to retrieve
  4606. # additional information from the OIDC provider.
  4607. #
  4608. # If the OIDC claim is a list, then the attribute must match any value in the list.
  4609. # Otherwise, it must exactly match the value of the claim. Using the example
  4610. # below, the `family_name` claim MUST be &quot;Stephensson&quot;, but the `groups`
  4611. # claim MUST contain &quot;admin&quot;.
  4612. #
  4613. # attribute_requirements:
  4614. # - attribute: family_name
  4615. # value: &quot;Stephensson&quot;
  4616. # - attribute: groups
  4617. # value: &quot;admin&quot;
  4618. #
  4619. # See https://matrix-org.github.io/synapse/latest/openid.html
  4620. # for information on how to configure these options.
  4621. #
  4622. # For backwards compatibility, it is also possible to configure a single OIDC
  4623. # provider via an 'oidc_config' setting. This is now deprecated and admins are
  4624. # advised to migrate to the 'oidc_providers' format. (When doing that migration,
  4625. # use 'oidc' for the idp_id to ensure that existing users continue to be
  4626. # recognised.)
  4627. #
  4628. oidc_providers:
  4629. # Generic example
  4630. #
  4631. #- idp_id: my_idp
  4632. # idp_name: &quot;My OpenID provider&quot;
  4633. # idp_icon: &quot;mxc://example.com/mediaid&quot;
  4634. # discover: false
  4635. # issuer: &quot;https://accounts.example.com/&quot;
  4636. # client_id: &quot;provided-by-your-issuer&quot;
  4637. # client_secret: &quot;provided-by-your-issuer&quot;
  4638. # client_auth_method: client_secret_post
  4639. # scopes: [&quot;openid&quot;, &quot;profile&quot;]
  4640. # authorization_endpoint: &quot;https://accounts.example.com/oauth2/auth&quot;
  4641. # token_endpoint: &quot;https://accounts.example.com/oauth2/token&quot;
  4642. # userinfo_endpoint: &quot;https://accounts.example.com/userinfo&quot;
  4643. # jwks_uri: &quot;https://accounts.example.com/.well-known/jwks.json&quot;
  4644. # skip_verification: true
  4645. # user_mapping_provider:
  4646. # config:
  4647. # subject_claim: &quot;id&quot;
  4648. # localpart_template: &quot;{{ user.login }}&quot;
  4649. # display_name_template: &quot;{{ user.name }}&quot;
  4650. # email_template: &quot;{{ user.email }}&quot;
  4651. # attribute_requirements:
  4652. # - attribute: userGroup
  4653. # value: &quot;synapseUsers&quot;
  4654. # Enable Central Authentication Service (CAS) for registration and login.
  4655. #
  4656. cas_config:
  4657. # Uncomment the following to enable authorization against a CAS server.
  4658. # Defaults to false.
  4659. #
  4660. #enabled: true
  4661. # The URL of the CAS authorization endpoint.
  4662. #
  4663. #server_url: &quot;https://cas-server.com&quot;
  4664. # The attribute of the CAS response to use as the display name.
  4665. #
  4666. # If unset, no displayname will be set.
  4667. #
  4668. #displayname_attribute: name
  4669. # It is possible to configure Synapse to only allow logins if CAS attributes
  4670. # match particular values. All of the keys in the mapping below must exist
  4671. # and the values must match the given value. Alternately if the given value
  4672. # is None then any value is allowed (the attribute just must exist).
  4673. # All of the listed attributes must match for the login to be permitted.
  4674. #
  4675. #required_attributes:
  4676. # userGroup: &quot;staff&quot;
  4677. # department: None
  4678. # Additional settings to use with single-sign on systems such as OpenID Connect,
  4679. # SAML2 and CAS.
  4680. #
  4681. # Server admins can configure custom templates for pages related to SSO. See
  4682. # https://matrix-org.github.io/synapse/latest/templates.html for more information.
  4683. #
  4684. sso:
  4685. # A list of client URLs which are whitelisted so that the user does not
  4686. # have to confirm giving access to their account to the URL. Any client
  4687. # whose URL starts with an entry in the following list will not be subject
  4688. # to an additional confirmation step after the SSO login is completed.
  4689. #
  4690. # WARNING: An entry such as &quot;https://my.client&quot; is insecure, because it
  4691. # will also match &quot;https://my.client.evil.site&quot;, exposing your users to
  4692. # phishing attacks from evil.site. To avoid this, include a slash after the
  4693. # hostname: &quot;https://my.client/&quot;.
  4694. #
  4695. # The login fallback page (used by clients that don't natively support the
  4696. # required login flows) is whitelisted in addition to any URLs in this list.
  4697. #
  4698. # By default, this list contains only the login fallback page.
  4699. #
  4700. #client_whitelist:
  4701. # - https://riot.im/develop
  4702. # - https://my.custom.client/
  4703. # Uncomment to keep a user's profile fields in sync with information from
  4704. # the identity provider. Currently only syncing the displayname is
  4705. # supported. Fields are checked on every SSO login, and are updated
  4706. # if necessary.
  4707. #
  4708. # Note that enabling this option will override user profile information,
  4709. # regardless of whether users have opted-out of syncing that
  4710. # information when first signing in. Defaults to false.
  4711. #
  4712. #update_profile_information: true
  4713. # JSON web token integration. The following settings can be used to make
  4714. # Synapse JSON web tokens for authentication, instead of its internal
  4715. # password database.
  4716. #
  4717. # Each JSON Web Token needs to contain a &quot;sub&quot; (subject) claim, which is
  4718. # used as the localpart of the mxid.
  4719. #
  4720. # Additionally, the expiration time (&quot;exp&quot;), not before time (&quot;nbf&quot;),
  4721. # and issued at (&quot;iat&quot;) claims are validated if present.
  4722. #
  4723. # Note that this is a non-standard login type and client support is
  4724. # expected to be non-existent.
  4725. #
  4726. # See https://matrix-org.github.io/synapse/latest/jwt.html.
  4727. #
  4728. #jwt_config:
  4729. # Uncomment the following to enable authorization using JSON web
  4730. # tokens. Defaults to false.
  4731. #
  4732. #enabled: true
  4733. # This is either the private shared secret or the public key used to
  4734. # decode the contents of the JSON web token.
  4735. #
  4736. # Required if 'enabled' is true.
  4737. #
  4738. #secret: &quot;provided-by-your-issuer&quot;
  4739. # The algorithm used to sign the JSON web token.
  4740. #
  4741. # Supported algorithms are listed at
  4742. # https://pyjwt.readthedocs.io/en/latest/algorithms.html
  4743. #
  4744. # Required if 'enabled' is true.
  4745. #
  4746. #algorithm: &quot;provided-by-your-issuer&quot;
  4747. # Name of the claim containing a unique identifier for the user.
  4748. #
  4749. # Optional, defaults to `sub`.
  4750. #
  4751. #subject_claim: &quot;sub&quot;
  4752. # The issuer to validate the &quot;iss&quot; claim against.
  4753. #
  4754. # Optional, if provided the &quot;iss&quot; claim will be required and
  4755. # validated for all JSON web tokens.
  4756. #
  4757. #issuer: &quot;provided-by-your-issuer&quot;
  4758. # A list of audiences to validate the &quot;aud&quot; claim against.
  4759. #
  4760. # Optional, if provided the &quot;aud&quot; claim will be required and
  4761. # validated for all JSON web tokens.
  4762. #
  4763. # Note that if the &quot;aud&quot; claim is included in a JSON web token then
  4764. # validation will fail without configuring audiences.
  4765. #
  4766. #audiences:
  4767. # - &quot;provided-by-your-issuer&quot;
  4768. password_config:
  4769. # Uncomment to disable password login
  4770. #
  4771. #enabled: false
  4772. # Uncomment to disable authentication against the local password
  4773. # database. This is ignored if `enabled` is false, and is only useful
  4774. # if you have other password_providers.
  4775. #
  4776. #localdb_enabled: false
  4777. # Uncomment and change to a secret random string for extra security.
  4778. # DO NOT CHANGE THIS AFTER INITIAL SETUP!
  4779. #
  4780. #pepper: &quot;EVEN_MORE_SECRET&quot;
  4781. # Define and enforce a password policy. Each parameter is optional.
  4782. # This is an implementation of MSC2000.
  4783. #
  4784. policy:
  4785. # Whether to enforce the password policy.
  4786. # Defaults to 'false'.
  4787. #
  4788. #enabled: true
  4789. # Minimum accepted length for a password.
  4790. # Defaults to 0.
  4791. #
  4792. #minimum_length: 15
  4793. # Whether a password must contain at least one digit.
  4794. # Defaults to 'false'.
  4795. #
  4796. #require_digit: true
  4797. # Whether a password must contain at least one symbol.
  4798. # A symbol is any character that's not a number or a letter.
  4799. # Defaults to 'false'.
  4800. #
  4801. #require_symbol: true
  4802. # Whether a password must contain at least one lowercase letter.
  4803. # Defaults to 'false'.
  4804. #
  4805. #require_lowercase: true
  4806. # Whether a password must contain at least one uppercase letter.
  4807. # Defaults to 'false'.
  4808. #
  4809. #require_uppercase: true
  4810. ui_auth:
  4811. # The amount of time to allow a user-interactive authentication session
  4812. # to be active.
  4813. #
  4814. # This defaults to 0, meaning the user is queried for their credentials
  4815. # before every action, but this can be overridden to allow a single
  4816. # validation to be re-used. This weakens the protections afforded by
  4817. # the user-interactive authentication process, by allowing for multiple
  4818. # (and potentially different) operations to use the same validation session.
  4819. #
  4820. # This is ignored for potentially &quot;dangerous&quot; operations (including
  4821. # deactivating an account, modifying an account password, and
  4822. # adding a 3PID).
  4823. #
  4824. # Uncomment below to allow for credential validation to last for 15
  4825. # seconds.
  4826. #
  4827. #session_timeout: &quot;15s&quot;
  4828. # Configuration for sending emails from Synapse.
  4829. #
  4830. # Server admins can configure custom templates for email content. See
  4831. # https://matrix-org.github.io/synapse/latest/templates.html for more information.
  4832. #
  4833. email:
  4834. # The hostname of the outgoing SMTP server to use. Defaults to 'localhost'.
  4835. #
  4836. #smtp_host: mail.server
  4837. # The port on the mail server for outgoing SMTP. Defaults to 25.
  4838. #
  4839. #smtp_port: 587
  4840. # Username/password for authentication to the SMTP server. By default, no
  4841. # authentication is attempted.
  4842. #
  4843. #smtp_user: &quot;exampleusername&quot;
  4844. #smtp_pass: &quot;examplepassword&quot;
  4845. # Uncomment the following to require TLS transport security for SMTP.
  4846. # By default, Synapse will connect over plain text, and will then switch to
  4847. # TLS via STARTTLS *if the SMTP server supports it*. If this option is set,
  4848. # Synapse will refuse to connect unless the server supports STARTTLS.
  4849. #
  4850. #require_transport_security: true
  4851. # Uncomment the following to disable TLS for SMTP.
  4852. #
  4853. # By default, if the server supports TLS, it will be used, and the server
  4854. # must present a certificate that is valid for 'smtp_host'. If this option
  4855. # is set to false, TLS will not be used.
  4856. #
  4857. #enable_tls: false
  4858. # notif_from defines the &quot;From&quot; address to use when sending emails.
  4859. # It must be set if email sending is enabled.
  4860. #
  4861. # The placeholder '%(app)s' will be replaced by the application name,
  4862. # which is normally 'app_name' (below), but may be overridden by the
  4863. # Matrix client application.
  4864. #
  4865. # Note that the placeholder must be written '%(app)s', including the
  4866. # trailing 's'.
  4867. #
  4868. #notif_from: &quot;Your Friendly %(app)s homeserver &lt;noreply@example.com&gt;&quot;
  4869. # app_name defines the default value for '%(app)s' in notif_from and email
  4870. # subjects. It defaults to 'Matrix'.
  4871. #
  4872. #app_name: my_branded_matrix_server
  4873. # Uncomment the following to enable sending emails for messages that the user
  4874. # has missed. Disabled by default.
  4875. #
  4876. #enable_notifs: true
  4877. # Uncomment the following to disable automatic subscription to email
  4878. # notifications for new users. Enabled by default.
  4879. #
  4880. #notif_for_new_users: false
  4881. # Custom URL for client links within the email notifications. By default
  4882. # links will be based on &quot;https://matrix.to&quot;.
  4883. #
  4884. # (This setting used to be called riot_base_url; the old name is still
  4885. # supported for backwards-compatibility but is now deprecated.)
  4886. #
  4887. #client_base_url: &quot;http://localhost/riot&quot;
  4888. # Configure the time that a validation email will expire after sending.
  4889. # Defaults to 1h.
  4890. #
  4891. #validation_token_lifetime: 15m
  4892. # The web client location to direct users to during an invite. This is passed
  4893. # to the identity server as the org.matrix.web_client_location key. Defaults
  4894. # to unset, giving no guidance to the identity server.
  4895. #
  4896. #invite_client_location: https://app.element.io
  4897. # Subjects to use when sending emails from Synapse.
  4898. #
  4899. # The placeholder '%(app)s' will be replaced with the value of the 'app_name'
  4900. # setting above, or by a value dictated by the Matrix client application.
  4901. #
  4902. # If a subject isn't overridden in this configuration file, the value used as
  4903. # its example will be used.
  4904. #
  4905. #subjects:
  4906. # Subjects for notification emails.
  4907. #
  4908. # On top of the '%(app)s' placeholder, these can use the following
  4909. # placeholders:
  4910. #
  4911. # * '%(person)s', which will be replaced by the display name of the user(s)
  4912. # that sent the message(s), e.g. &quot;Alice and Bob&quot;.
  4913. # * '%(room)s', which will be replaced by the name of the room the
  4914. # message(s) have been sent to, e.g. &quot;My super room&quot;.
  4915. #
  4916. # See the example provided for each setting to see which placeholder can be
  4917. # used and how to use them.
  4918. #
  4919. # Subject to use to notify about one message from one or more user(s) in a
  4920. # room which has a name.
  4921. #message_from_person_in_room: &quot;[%(app)s] You have a message on %(app)s from %(person)s in the %(room)s room...&quot;
  4922. #
  4923. # Subject to use to notify about one message from one or more user(s) in a
  4924. # room which doesn't have a name.
  4925. #message_from_person: &quot;[%(app)s] You have a message on %(app)s from %(person)s...&quot;
  4926. #
  4927. # Subject to use to notify about multiple messages from one or more users in
  4928. # a room which doesn't have a name.
  4929. #messages_from_person: &quot;[%(app)s] You have messages on %(app)s from %(person)s...&quot;
  4930. #
  4931. # Subject to use to notify about multiple messages in a room which has a
  4932. # name.
  4933. #messages_in_room: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room...&quot;
  4934. #
  4935. # Subject to use to notify about multiple messages in multiple rooms.
  4936. #messages_in_room_and_others: &quot;[%(app)s] You have messages on %(app)s in the %(room)s room and others...&quot;
  4937. #
  4938. # Subject to use to notify about multiple messages from multiple persons in
  4939. # multiple rooms. This is similar to the setting above except it's used when
  4940. # the room in which the notification was triggered has no name.
  4941. #messages_from_person_and_others: &quot;[%(app)s] You have messages on %(app)s from %(person)s and others...&quot;
  4942. #
  4943. # Subject to use to notify about an invite to a room which has a name.
  4944. #invite_from_person_to_room: &quot;[%(app)s] %(person)s has invited you to join the %(room)s room on %(app)s...&quot;
  4945. #
  4946. # Subject to use to notify about an invite to a room which doesn't have a
  4947. # name.
  4948. #invite_from_person: &quot;[%(app)s] %(person)s has invited you to chat on %(app)s...&quot;
  4949. # Subject for emails related to account administration.
  4950. #
  4951. # On top of the '%(app)s' placeholder, these one can use the
  4952. # '%(server_name)s' placeholder, which will be replaced by the value of the
  4953. # 'server_name' setting in your Synapse configuration.
  4954. #
  4955. # Subject to use when sending a password reset email.
  4956. #password_reset: &quot;[%(server_name)s] Password reset&quot;
  4957. #
  4958. # Subject to use when sending a verification email to assert an address's
  4959. # ownership.
  4960. #email_validation: &quot;[%(server_name)s] Validate your email&quot;
  4961. ## Push ##
  4962. push:
  4963. # Clients requesting push notifications can either have the body of
  4964. # the message sent in the notification poke along with other details
  4965. # like the sender, or just the event ID and room ID (`event_id_only`).
  4966. # If clients choose the former, this option controls whether the
  4967. # notification request includes the content of the event (other details
  4968. # like the sender are still included). For `event_id_only` push, it
  4969. # has no effect.
  4970. #
  4971. # For modern android devices the notification content will still appear
  4972. # because it is loaded by the app. iPhone, however will send a
  4973. # notification saying only that a message arrived and who it came from.
  4974. #
  4975. # The default value is &quot;true&quot; to include message details. Uncomment to only
  4976. # include the event ID and room ID in push notification payloads.
  4977. #
  4978. #include_content: false
  4979. # When a push notification is received, an unread count is also sent.
  4980. # This number can either be calculated as the number of unread messages
  4981. # for the user, or the number of *rooms* the user has unread messages in.
  4982. #
  4983. # The default value is &quot;true&quot;, meaning push clients will see the number of
  4984. # rooms with unread messages in them. Uncomment to instead send the number
  4985. # of unread messages.
  4986. #
  4987. #group_unread_count_by_room: false
  4988. ## Rooms ##
  4989. # Controls whether locally-created rooms should be end-to-end encrypted by
  4990. # default.
  4991. #
  4992. # Possible options are &quot;all&quot;, &quot;invite&quot;, and &quot;off&quot;. They are defined as:
  4993. #
  4994. # * &quot;all&quot;: any locally-created room
  4995. # * &quot;invite&quot;: any room created with the &quot;private_chat&quot; or &quot;trusted_private_chat&quot;
  4996. # room creation presets
  4997. # * &quot;off&quot;: this option will take no effect
  4998. #
  4999. # The default value is &quot;off&quot;.
  5000. #
  5001. # Note that this option will only affect rooms created after it is set. It
  5002. # will also not affect rooms created by other servers.
  5003. #
  5004. #encryption_enabled_by_default_for_room_type: invite
  5005. # Uncomment to allow non-server-admin users to create groups on this server
  5006. #
  5007. #enable_group_creation: true
  5008. # If enabled, non server admins can only create groups with local parts
  5009. # starting with this prefix
  5010. #
  5011. #group_creation_prefix: &quot;unofficial_&quot;
  5012. # User Directory configuration
  5013. #
  5014. user_directory:
  5015. # Defines whether users can search the user directory. If false then
  5016. # empty responses are returned to all queries. Defaults to true.
  5017. #
  5018. # Uncomment to disable the user directory.
  5019. #
  5020. #enabled: false
  5021. # Defines whether to search all users visible to your HS when searching
  5022. # the user directory. If false, search results will only contain users
  5023. # visible in public rooms and users sharing a room with the requester.
  5024. # Defaults to false.
  5025. #
  5026. # NB. If you set this to true, and the last time the user_directory search
  5027. # indexes were (re)built was before Synapse 1.44, you'll have to
  5028. # rebuild the indexes in order to search through all known users.
  5029. # These indexes are built the first time Synapse starts; admins can
  5030. # manually trigger a rebuild via API following the instructions at
  5031. # https://matrix-org.github.io/synapse/latest/usage/administration/admin_api/background_updates.html#run
  5032. #
  5033. # Uncomment to return search results containing all known users, even if that
  5034. # user does not share a room with the requester.
  5035. #
  5036. #search_all_users: true
  5037. # Defines whether to prefer local users in search query results.
  5038. # If True, local users are more likely to appear above remote users
  5039. # when searching the user directory. Defaults to false.
  5040. #
  5041. # Uncomment to prefer local over remote users in user directory search
  5042. # results.
  5043. #
  5044. #prefer_local_users: true
  5045. # User Consent configuration
  5046. #
  5047. # for detailed instructions, see
  5048. # https://matrix-org.github.io/synapse/latest/consent_tracking.html
  5049. #
  5050. # Parts of this section are required if enabling the 'consent' resource under
  5051. # 'listeners', in particular 'template_dir' and 'version'.
  5052. #
  5053. # 'template_dir' gives the location of the templates for the HTML forms.
  5054. # This directory should contain one subdirectory per language (eg, 'en', 'fr'),
  5055. # and each language directory should contain the policy document (named as
  5056. # '&lt;version&gt;.html') and a success page (success.html).
  5057. #
  5058. # 'version' specifies the 'current' version of the policy document. It defines
  5059. # the version to be served by the consent resource if there is no 'v'
  5060. # parameter.
  5061. #
  5062. # 'server_notice_content', if enabled, will send a user a &quot;Server Notice&quot;
  5063. # asking them to consent to the privacy policy. The 'server_notices' section
  5064. # must also be configured for this to work. Notices will *not* be sent to
  5065. # guest users unless 'send_server_notice_to_guests' is set to true.
  5066. #
  5067. # 'block_events_error', if set, will block any attempts to send events
  5068. # until the user consents to the privacy policy. The value of the setting is
  5069. # used as the text of the error.
  5070. #
  5071. # 'require_at_registration', if enabled, will add a step to the registration
  5072. # process, similar to how captcha works. Users will be required to accept the
  5073. # policy before their account is created.
  5074. #
  5075. # 'policy_name' is the display name of the policy users will see when registering
  5076. # for an account. Has no effect unless `require_at_registration` is enabled.
  5077. # Defaults to &quot;Privacy Policy&quot;.
  5078. #
  5079. #user_consent:
  5080. # template_dir: res/templates/privacy
  5081. # version: 1.0
  5082. # server_notice_content:
  5083. # msgtype: m.text
  5084. # body: &gt;-
  5085. # To continue using this homeserver you must review and agree to the
  5086. # terms and conditions at %(consent_uri)s
  5087. # send_server_notice_to_guests: true
  5088. # block_events_error: &gt;-
  5089. # To continue using this homeserver you must review and agree to the
  5090. # terms and conditions at %(consent_uri)s
  5091. # require_at_registration: false
  5092. # policy_name: Privacy Policy
  5093. #
  5094. # Settings for local room and user statistics collection. See
  5095. # https://matrix-org.github.io/synapse/latest/room_and_user_statistics.html.
  5096. #
  5097. stats:
  5098. # Uncomment the following to disable room and user statistics. Note that doing
  5099. # so may cause certain features (such as the room directory) not to work
  5100. # correctly.
  5101. #
  5102. #enabled: false
  5103. # Server Notices room configuration
  5104. #
  5105. # Uncomment this section to enable a room which can be used to send notices
  5106. # from the server to users. It is a special room which cannot be left; notices
  5107. # come from a special &quot;notices&quot; user id.
  5108. #
  5109. # If you uncomment this section, you *must* define the system_mxid_localpart
  5110. # setting, which defines the id of the user which will be used to send the
  5111. # notices.
  5112. #
  5113. # It's also possible to override the room name, the display name of the
  5114. # &quot;notices&quot; user, and the avatar for the user.
  5115. #
  5116. #server_notices:
  5117. # system_mxid_localpart: notices
  5118. # system_mxid_display_name: &quot;Server Notices&quot;
  5119. # system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  5120. # room_name: &quot;Server Notices&quot;
  5121. # Uncomment to disable searching the public room list. When disabled
  5122. # blocks searching local and remote room lists for local and remote
  5123. # users by always returning an empty list for all queries.
  5124. #
  5125. #enable_room_list_search: false
  5126. # The `alias_creation` option controls who's allowed to create aliases
  5127. # on this server.
  5128. #
  5129. # The format of this option is a list of rules that contain globs that
  5130. # match against user_id, room_id and the new alias (fully qualified with
  5131. # server name). The action in the first rule that matches is taken,
  5132. # which can currently either be &quot;allow&quot; or &quot;deny&quot;.
  5133. #
  5134. # Missing user_id/room_id/alias fields default to &quot;*&quot;.
  5135. #
  5136. # If no rules match the request is denied. An empty list means no one
  5137. # can create aliases.
  5138. #
  5139. # Options for the rules include:
  5140. #
  5141. # user_id: Matches against the creator of the alias
  5142. # alias: Matches against the alias being created
  5143. # room_id: Matches against the room ID the alias is being pointed at
  5144. # action: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches
  5145. #
  5146. # The default is:
  5147. #
  5148. #alias_creation_rules:
  5149. # - user_id: &quot;*&quot;
  5150. # alias: &quot;*&quot;
  5151. # room_id: &quot;*&quot;
  5152. # action: allow
  5153. # The `room_list_publication_rules` option controls who can publish and
  5154. # which rooms can be published in the public room list.
  5155. #
  5156. # The format of this option is the same as that for
  5157. # `alias_creation_rules`.
  5158. #
  5159. # If the room has one or more aliases associated with it, only one of
  5160. # the aliases needs to match the alias rule. If there are no aliases
  5161. # then only rules with `alias: *` match.
  5162. #
  5163. # If no rules match the request is denied. An empty list means no one
  5164. # can publish rooms.
  5165. #
  5166. # Options for the rules include:
  5167. #
  5168. # user_id: Matches against the creator of the alias
  5169. # room_id: Matches against the room ID being published
  5170. # alias: Matches against any current local or canonical aliases
  5171. # associated with the room
  5172. # action: Whether to &quot;allow&quot; or &quot;deny&quot; the request if the rule matches
  5173. #
  5174. # The default is:
  5175. #
  5176. #room_list_publication_rules:
  5177. # - user_id: &quot;*&quot;
  5178. # alias: &quot;*&quot;
  5179. # room_id: &quot;*&quot;
  5180. # action: allow
  5181. ## Opentracing ##
  5182. # These settings enable opentracing, which implements distributed tracing.
  5183. # This allows you to observe the causal chains of events across servers
  5184. # including requests, key lookups etc., across any server running
  5185. # synapse or any other other services which supports opentracing
  5186. # (specifically those implemented with Jaeger).
  5187. #
  5188. opentracing:
  5189. # tracing is disabled by default. Uncomment the following line to enable it.
  5190. #
  5191. #enabled: true
  5192. # The list of homeservers we wish to send and receive span contexts and span baggage.
  5193. # See https://matrix-org.github.io/synapse/latest/opentracing.html.
  5194. #
  5195. # This is a list of regexes which are matched against the server_name of the
  5196. # homeserver.
  5197. #
  5198. # By default, it is empty, so no servers are matched.
  5199. #
  5200. #homeserver_whitelist:
  5201. # - &quot;.*&quot;
  5202. # A list of the matrix IDs of users whose requests will always be traced,
  5203. # even if the tracing system would otherwise drop the traces due to
  5204. # probabilistic sampling.
  5205. #
  5206. # By default, the list is empty.
  5207. #
  5208. #force_tracing_for_users:
  5209. # - &quot;@user1:server_name&quot;
  5210. # - &quot;@user2:server_name&quot;
  5211. # Jaeger can be configured to sample traces at different rates.
  5212. # All configuration options provided by Jaeger can be set here.
  5213. # Jaeger's configuration is mostly related to trace sampling which
  5214. # is documented here:
  5215. # https://www.jaegertracing.io/docs/latest/sampling/.
  5216. #
  5217. #jaeger_config:
  5218. # sampler:
  5219. # type: const
  5220. # param: 1
  5221. # logging:
  5222. # false
  5223. ## Workers ##
  5224. # Disables sending of outbound federation transactions on the main process.
  5225. # Uncomment if using a federation sender worker.
  5226. #
  5227. #send_federation: false
  5228. # It is possible to run multiple federation sender workers, in which case the
  5229. # work is balanced across them.
  5230. #
  5231. # This configuration must be shared between all federation sender workers, and if
  5232. # changed all federation sender workers must be stopped at the same time and then
  5233. # started, to ensure that all instances are running with the same config (otherwise
  5234. # events may be dropped).
  5235. #
  5236. #federation_sender_instances:
  5237. # - federation_sender1
  5238. # When using workers this should be a map from `worker_name` to the
  5239. # HTTP replication listener of the worker, if configured.
  5240. #
  5241. #instance_map:
  5242. # worker1:
  5243. # host: localhost
  5244. # port: 8034
  5245. # Experimental: When using workers you can define which workers should
  5246. # handle event persistence and typing notifications. Any worker
  5247. # specified here must also be in the `instance_map`.
  5248. #
  5249. #stream_writers:
  5250. # events: worker1
  5251. # typing: worker1
  5252. # The worker that is used to run background tasks (e.g. cleaning up expired
  5253. # data). If not provided this defaults to the main process.
  5254. #
  5255. #run_background_tasks_on: worker1
  5256. # A shared secret used by the replication APIs to authenticate HTTP requests
  5257. # from workers.
  5258. #
  5259. # By default this is unused and traffic is not authenticated.
  5260. #
  5261. #worker_replication_secret: &quot;&quot;
  5262. # Configuration for Redis when using workers. This *must* be enabled when
  5263. # using workers (unless using old style direct TCP configuration).
  5264. #
  5265. redis:
  5266. # Uncomment the below to enable Redis support.
  5267. #
  5268. #enabled: true
  5269. # Optional host and port to use to connect to redis. Defaults to
  5270. # localhost and 6379
  5271. #
  5272. #host: localhost
  5273. #port: 6379
  5274. # Optional password if configured on the Redis instance
  5275. #
  5276. #password: &lt;secret_password&gt;
  5277. </code></pre>
  5278. <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>
  5279. <p>Below is a sample logging configuration file. This file can be tweaked to control how your
  5280. homeserver will output logs. A restart of the server is generally required to apply any
  5281. changes made to this file. The value of the <code>log_config</code> option in your homeserver
  5282. config should be the path to this file.</p>
  5283. <p>Note that a default logging configuration (shown below) is created automatically alongside
  5284. the homeserver config when following the <a href="usage/configuration/../../setup/installation.html">installation instructions</a>.
  5285. It should be named <code>&lt;SERVERNAME&gt;.log.config</code> by default.</p>
  5286. <pre><code class="language-yaml"># Log configuration for Synapse.
  5287. #
  5288. # This is a YAML file containing a standard Python logging configuration
  5289. # dictionary. See [1] for details on the valid settings.
  5290. #
  5291. # Synapse also supports structured logging for machine readable logs which can
  5292. # be ingested by ELK stacks. See [2] for details.
  5293. #
  5294. # [1]: https://docs.python.org/3.7/library/logging.config.html#configuration-dictionary-schema
  5295. # [2]: https://matrix-org.github.io/synapse/latest/structured_logging.html
  5296. version: 1
  5297. formatters:
  5298. precise:
  5299. format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s'
  5300. handlers:
  5301. file:
  5302. class: logging.handlers.TimedRotatingFileHandler
  5303. formatter: precise
  5304. filename: /var/log/matrix-synapse/homeserver.log
  5305. when: midnight
  5306. backupCount: 3 # Does not include the current log file.
  5307. encoding: utf8
  5308. # Default to buffering writes to log file for efficiency.
  5309. # WARNING/ERROR logs will still be flushed immediately, but there will be a
  5310. # delay (of up to `period` seconds, or until the buffer is full with
  5311. # `capacity` messages) before INFO/DEBUG logs get written.
  5312. buffer:
  5313. class: synapse.logging.handlers.PeriodicallyFlushingMemoryHandler
  5314. target: file
  5315. # The capacity is the maximum number of log lines that are buffered
  5316. # before being written to disk. Increasing this will lead to better
  5317. # performance, at the expensive of it taking longer for log lines to
  5318. # be written to disk.
  5319. # This parameter is required.
  5320. capacity: 10
  5321. # Logs with a level at or above the flush level will cause the buffer to
  5322. # be flushed immediately.
  5323. # Default value: 40 (ERROR)
  5324. # Other values: 50 (CRITICAL), 30 (WARNING), 20 (INFO), 10 (DEBUG)
  5325. flushLevel: 30 # Flush immediately for WARNING logs and higher
  5326. # The period of time, in seconds, between forced flushes.
  5327. # Messages will not be delayed for longer than this time.
  5328. # Default value: 5 seconds
  5329. period: 5
  5330. # A handler that writes logs to stderr. Unused by default, but can be used
  5331. # instead of &quot;buffer&quot; and &quot;file&quot; in the logger handlers.
  5332. console:
  5333. class: logging.StreamHandler
  5334. formatter: precise
  5335. loggers:
  5336. synapse.storage.SQL:
  5337. # beware: increasing this to DEBUG will make synapse log sensitive
  5338. # information such as access tokens.
  5339. level: INFO
  5340. twisted:
  5341. # We send the twisted logging directly to the file handler,
  5342. # to work around https://github.com/matrix-org/synapse/issues/3471
  5343. # when using &quot;buffer&quot; logger. Use &quot;console&quot; to log to stderr instead.
  5344. handlers: [file]
  5345. propagate: false
  5346. root:
  5347. level: INFO
  5348. # Write logs to the `buffer` handler, which will buffer them together in memory,
  5349. # then write them to a file.
  5350. #
  5351. # Replace &quot;buffer&quot; with &quot;console&quot; to log to stderr instead. (Note that you'll
  5352. # also need to update the configuration for the `twisted` logger above, in
  5353. # this case.)
  5354. #
  5355. handlers: [buffer]
  5356. disable_existing_loggers: false
  5357. </code></pre>
  5358. <div style="break-before: page; page-break-before: always;"></div><h1 id="structured-logging"><a class="header" href="#structured-logging">Structured Logging</a></h1>
  5359. <p>A structured logging system can be useful when your logs are destined for a
  5360. machine to parse and process. By maintaining its machine-readable characteristics,
  5361. it enables more efficient searching and aggregations when consumed by software
  5362. such as the &quot;ELK stack&quot;.</p>
  5363. <p>Synapse's structured logging system is configured via the file that Synapse's
  5364. <code>log_config</code> config option points to. The file should include a formatter which
  5365. uses the <code>synapse.logging.TerseJsonFormatter</code> class included with Synapse and a
  5366. handler which uses the above formatter.</p>
  5367. <p>There is also a <code>synapse.logging.JsonFormatter</code> option which does not include
  5368. a timestamp in the resulting JSON. This is useful if the log ingester adds its
  5369. own timestamp.</p>
  5370. <p>A structured logging configuration looks similar to the following:</p>
  5371. <pre><code class="language-yaml">version: 1
  5372. formatters:
  5373. structured:
  5374. class: synapse.logging.TerseJsonFormatter
  5375. handlers:
  5376. file:
  5377. class: logging.handlers.TimedRotatingFileHandler
  5378. formatter: structured
  5379. filename: /path/to/my/logs/homeserver.log
  5380. when: midnight
  5381. backupCount: 3 # Does not include the current log file.
  5382. encoding: utf8
  5383. loggers:
  5384. synapse:
  5385. level: INFO
  5386. handlers: [remote]
  5387. synapse.storage.SQL:
  5388. level: WARNING
  5389. </code></pre>
  5390. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  5391. with the SQL layer at 'WARNING', and will log to a file, stored as JSON.</p>
  5392. <p>It is also possible to figure Synapse to log to a remote endpoint by using the
  5393. <code>synapse.logging.RemoteHandler</code> class included with Synapse. It takes the
  5394. following arguments:</p>
  5395. <ul>
  5396. <li><code>host</code>: Hostname or IP address of the log aggregator.</li>
  5397. <li><code>port</code>: Numerical port to contact on the host.</li>
  5398. <li><code>maximum_buffer</code>: (Optional, defaults to 1000) The maximum buffer size to allow.</li>
  5399. </ul>
  5400. <p>A remote structured logging configuration looks similar to the following:</p>
  5401. <pre><code class="language-yaml">version: 1
  5402. formatters:
  5403. structured:
  5404. class: synapse.logging.TerseJsonFormatter
  5405. handlers:
  5406. remote:
  5407. class: synapse.logging.RemoteHandler
  5408. formatter: structured
  5409. host: 10.1.2.3
  5410. port: 9999
  5411. loggers:
  5412. synapse:
  5413. level: INFO
  5414. handlers: [remote]
  5415. synapse.storage.SQL:
  5416. level: WARNING
  5417. </code></pre>
  5418. <p>The above logging config will set Synapse as 'INFO' logging level by default,
  5419. with the SQL layer at 'WARNING', and will log JSON formatted messages to a
  5420. remote endpoint at 10.1.2.3:9999.</p>
  5421. <h2 id="upgrading-from-legacy-structured-logging-configuration"><a class="header" href="#upgrading-from-legacy-structured-logging-configuration">Upgrading from legacy structured logging configuration</a></h2>
  5422. <p>Versions of Synapse prior to v1.23.0 included a custom structured logging
  5423. configuration which is deprecated. It used a <code>structured: true</code> flag and
  5424. configured <code>drains</code> instead of <code>handlers</code> and <code>formatters</code>.</p>
  5425. <p>Synapse currently automatically converts the old configuration to the new
  5426. configuration, but this will be removed in a future version of Synapse. The
  5427. following reference can be used to update your configuration. Based on the drain
  5428. <code>type</code>, we can pick a new handler:</p>
  5429. <ol>
  5430. <li>For a type of <code>console</code>, <code>console_json</code>, or <code>console_json_terse</code>: a handler
  5431. with a class of <code>logging.StreamHandler</code> and a <code>stream</code> of <code>ext://sys.stdout</code>
  5432. or <code>ext://sys.stderr</code> should be used.</li>
  5433. <li>For a type of <code>file</code> or <code>file_json</code>: a handler of <code>logging.FileHandler</code> with
  5434. a location of the file path should be used.</li>
  5435. <li>For a type of <code>network_json_terse</code>: a handler of <code>synapse.logging.RemoteHandler</code>
  5436. with the host and port should be used.</li>
  5437. </ol>
  5438. <p>Then based on the drain <code>type</code> we can pick a new formatter:</p>
  5439. <ol>
  5440. <li>For a type of <code>console</code> or <code>file</code> no formatter is necessary.</li>
  5441. <li>For a type of <code>console_json</code> or <code>file_json</code>: a formatter of
  5442. <code>synapse.logging.JsonFormatter</code> should be used.</li>
  5443. <li>For a type of <code>console_json_terse</code> or <code>network_json_terse</code>: a formatter of
  5444. <code>synapse.logging.TerseJsonFormatter</code> should be used.</li>
  5445. </ol>
  5446. <p>For each new handler and formatter they should be added to the logging configuration
  5447. and then assigned to either a logger or the root logger.</p>
  5448. <p>An example legacy configuration:</p>
  5449. <pre><code class="language-yaml">structured: true
  5450. loggers:
  5451. synapse:
  5452. level: INFO
  5453. synapse.storage.SQL:
  5454. level: WARNING
  5455. drains:
  5456. console:
  5457. type: console
  5458. location: stdout
  5459. file:
  5460. type: file_json
  5461. location: homeserver.log
  5462. </code></pre>
  5463. <p>Would be converted into a new configuration:</p>
  5464. <pre><code class="language-yaml">version: 1
  5465. formatters:
  5466. json:
  5467. class: synapse.logging.JsonFormatter
  5468. handlers:
  5469. console:
  5470. class: logging.StreamHandler
  5471. stream: ext://sys.stdout
  5472. file:
  5473. class: logging.FileHandler
  5474. formatter: json
  5475. filename: homeserver.log
  5476. loggers:
  5477. synapse:
  5478. level: INFO
  5479. handlers: [console, file]
  5480. synapse.storage.SQL:
  5481. level: WARNING
  5482. </code></pre>
  5483. <p>The new logging configuration is a bit more verbose, but significantly more
  5484. flexible. It allows for configuration that were not previously possible, such as
  5485. sending plain logs over the network, or using different handlers for different
  5486. modules.</p>
  5487. <div style="break-before: page; page-break-before: always;"></div><h1 id="templates"><a class="header" href="#templates">Templates</a></h1>
  5488. <p>Synapse uses parametrised templates to generate the content of emails it sends and
  5489. webpages it shows to users.</p>
  5490. <p>By default, Synapse will use the templates listed <a href="https://github.com/matrix-org/synapse/tree/master/synapse/res/templates">here</a>.
  5491. Server admins can configure an additional directory for Synapse to look for templates
  5492. in, allowing them to specify custom templates:</p>
  5493. <pre><code class="language-yaml">templates:
  5494. custom_templates_directory: /path/to/custom/templates/
  5495. </code></pre>
  5496. <p>If this setting is not set, or the files named below are not found within the directory,
  5497. default templates from within the Synapse package will be used.</p>
  5498. <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>.
  5499. Templates rendered by Jinja 2 can also access two functions on top of the functions
  5500. already available as part of Jinja 2:</p>
  5501. <pre><code class="language-python">format_ts(value: int, format: str) -&gt; str
  5502. </code></pre>
  5503. <p>Formats a timestamp in milliseconds.</p>
  5504. <p>Example: <code>reason.last_sent_ts|format_ts(&quot;%c&quot;)</code></p>
  5505. <pre><code class="language-python">mxc_to_http(value: str, width: int, height: int, resize_method: str = &quot;crop&quot;) -&gt; str
  5506. </code></pre>
  5507. <p>Turns a <code>mxc://</code> URL for media content into an HTTP(S) one using the homeserver's
  5508. <code>public_baseurl</code> configuration setting as the URL's base.</p>
  5509. <p>Example: <code>message.sender_avatar_url|mxc_to_http(32,32)</code></p>
  5510. <h2 id="email-templates"><a class="header" href="#email-templates">Email templates</a></h2>
  5511. <p>Below are the templates Synapse will look for when generating the content of an email:</p>
  5512. <ul>
  5513. <li><code>notif_mail.html</code> and <code>notif_mail.txt</code>: The contents of email notifications of missed
  5514. events.
  5515. When rendering, this template is given the following variables:
  5516. <ul>
  5517. <li><code>user_display_name</code>: the display name for the user receiving the notification</li>
  5518. <li><code>unsubscribe_link</code>: the link users can click to unsubscribe from email notifications</li>
  5519. <li><code>summary_text</code>: a summary of the notification(s). The text used can be customised
  5520. by configuring the various settings in the <code>email.subjects</code> section of the
  5521. configuration file.</li>
  5522. <li><code>rooms</code>: a list of rooms containing events to include in the email. Each element is
  5523. an object with the following attributes:
  5524. <ul>
  5525. <li><code>title</code>: a human-readable name for the room</li>
  5526. <li><code>hash</code>: a hash of the ID of the room</li>
  5527. <li><code>invite</code>: a boolean, which is <code>True</code> if the room is an invite the user hasn't
  5528. accepted yet, <code>False</code> otherwise</li>
  5529. <li><code>notifs</code>: a list of events, or an empty list if <code>invite</code> is <code>True</code>. Each element
  5530. is an object with the following attributes:
  5531. <ul>
  5532. <li><code>link</code>: a <code>matrix.to</code> link to the event</li>
  5533. <li><code>ts</code>: the time in milliseconds at which the event was received</li>
  5534. <li><code>messages</code>: a list of messages containing one message before the event, the
  5535. message in the event, and one message after the event. Each element is an
  5536. object with the following attributes:
  5537. <ul>
  5538. <li><code>event_type</code>: the type of the event</li>
  5539. <li><code>is_historical</code>: a boolean, which is <code>False</code> if the message is the one
  5540. that triggered the notification, <code>True</code> otherwise</li>
  5541. <li><code>id</code>: the ID of the event</li>
  5542. <li><code>ts</code>: the time in milliseconds at which the event was sent</li>
  5543. <li><code>sender_name</code>: the display name for the event's sender</li>
  5544. <li><code>sender_avatar_url</code>: the avatar URL (as a <code>mxc://</code> URL) for the event's
  5545. sender</li>
  5546. <li><code>sender_hash</code>: a hash of the user ID of the sender</li>
  5547. <li><code>msgtype</code>: the type of the message</li>
  5548. <li><code>body_text_html</code>: html representation of the message</li>
  5549. <li><code>body_text_plain</code>: plaintext representation of the message</li>
  5550. <li><code>image_url</code>: mxc url of an image, when &quot;msgtype&quot; is &quot;m.image&quot;</li>
  5551. </ul>
  5552. </li>
  5553. </ul>
  5554. </li>
  5555. <li><code>link</code>: a <code>matrix.to</code> link to the room</li>
  5556. <li><code>avator_url</code>: url to the room's avator</li>
  5557. </ul>
  5558. </li>
  5559. <li><code>reason</code>: information on the event that triggered the email to be sent. It's an
  5560. object with the following attributes:
  5561. <ul>
  5562. <li><code>room_id</code>: the ID of the room the event was sent in</li>
  5563. <li><code>room_name</code>: a human-readable name for the room the event was sent in</li>
  5564. <li><code>now</code>: the current time in milliseconds</li>
  5565. <li><code>received_at</code>: the time in milliseconds at which the event was received</li>
  5566. <li><code>delay_before_mail_ms</code>: the amount of time in milliseconds Synapse always waits
  5567. before ever emailing about a notification (to give the user a chance to respond
  5568. to other push or notice the window)</li>
  5569. <li><code>last_sent_ts</code>: the time in milliseconds at which a notification was last sent
  5570. for an event in this room</li>
  5571. <li><code>throttle_ms</code>: the minimum amount of time in milliseconds between two
  5572. notifications can be sent for this room</li>
  5573. </ul>
  5574. </li>
  5575. </ul>
  5576. </li>
  5577. <li><code>password_reset.html</code> and <code>password_reset.txt</code>: The contents of password reset emails
  5578. sent by the homeserver.
  5579. When rendering, these templates are given a <code>link</code> variable which contains the link the
  5580. user must click in order to reset their password.</li>
  5581. <li><code>registration.html</code> and <code>registration.txt</code>: The contents of address verification emails
  5582. sent during registration.
  5583. When rendering, these templates are given a <code>link</code> variable which contains the link the
  5584. user must click in order to validate their email address.</li>
  5585. <li><code>add_threepid.html</code> and <code>add_threepid.txt</code>: The contents of address verification emails
  5586. sent when an address is added to a Matrix account.
  5587. When rendering, these templates are given a <code>link</code> variable which contains the link the
  5588. user must click in order to validate their email address.</li>
  5589. </ul>
  5590. <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>
  5591. <p>Below are the templates Synapse will look for when generating pages related to
  5592. registration and password reset:</p>
  5593. <ul>
  5594. <li><code>password_reset_confirmation.html</code>: An HTML page that a user will see when they follow
  5595. the link in the password reset email. The user will be asked to confirm the action
  5596. before their password is reset.
  5597. When rendering, this template is given the following variables:
  5598. <ul>
  5599. <li><code>sid</code>: the session ID for the password reset</li>
  5600. <li><code>token</code>: the token for the password reset</li>
  5601. <li><code>client_secret</code>: the client secret for the password reset</li>
  5602. </ul>
  5603. </li>
  5604. <li><code>password_reset_success.html</code> and <code>password_reset_failure.html</code>: HTML pages for success
  5605. and failure that a user will see when they confirm the password reset flow using the
  5606. page above.
  5607. When rendering, <code>password_reset_success.html</code> is given no variable, and
  5608. <code>password_reset_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  5609. for the password reset failure. </li>
  5610. <li><code>registration_success.html</code> and <code>registration_failure.html</code>: HTML pages for success and
  5611. failure that a user will see when they follow the link in an address verification email
  5612. sent during registration.
  5613. When rendering, <code>registration_success.html</code> is given no variable, and
  5614. <code>registration_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  5615. for the registration failure.</li>
  5616. <li><code>add_threepid_success.html</code> and <code>add_threepid_failure.html</code>: HTML pages for success and
  5617. failure that a user will see when they follow the link in an address verification email
  5618. sent when an address is added to a Matrix account.
  5619. When rendering, <code>add_threepid_success.html</code> is given no variable, and
  5620. <code>add_threepid_failure.html</code> is given a <code>failure_reason</code>, which contains the reason
  5621. for the registration failure.</li>
  5622. </ul>
  5623. <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>
  5624. <p>Below are the templates Synapse will look for when generating pages related to SSO:</p>
  5625. <ul>
  5626. <li><code>sso_login_idp_picker.html</code>: HTML page to prompt the user to choose an
  5627. Identity Provider during login.
  5628. This is only used if multiple SSO Identity Providers are configured.
  5629. When rendering, this template is given the following variables:
  5630. <ul>
  5631. <li><code>redirect_url</code>: the URL that the user will be redirected to after
  5632. login.</li>
  5633. <li><code>server_name</code>: the homeserver's name.</li>
  5634. <li><code>providers</code>: a list of available Identity Providers. Each element is
  5635. an object with the following attributes:
  5636. <ul>
  5637. <li><code>idp_id</code>: unique identifier for the IdP</li>
  5638. <li><code>idp_name</code>: user-facing name for the IdP</li>
  5639. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  5640. for the IdP</li>
  5641. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  5642. for the brand of the IdP
  5643. The rendered HTML page should contain a form which submits its results
  5644. back as a GET request, with the following query parameters:</li>
  5645. </ul>
  5646. </li>
  5647. <li><code>redirectUrl</code>: the client redirect URI (ie, the <code>redirect_url</code> passed
  5648. to the template)</li>
  5649. <li><code>idp</code>: the 'idp_id' of the chosen IDP.</li>
  5650. </ul>
  5651. </li>
  5652. <li><code>sso_auth_account_details.html</code>: HTML page to prompt new users to enter a
  5653. userid and confirm other details. This is only shown if the
  5654. SSO implementation (with any <code>user_mapping_provider</code>) does not return
  5655. a localpart.
  5656. When rendering, this template is given the following variables:
  5657. <ul>
  5658. <li><code>server_name</code>: the homeserver's name.</li>
  5659. <li><code>idp</code>: details of the SSO Identity Provider that the user logged in
  5660. with: an object with the following attributes:
  5661. <ul>
  5662. <li><code>idp_id</code>: unique identifier for the IdP</li>
  5663. <li><code>idp_name</code>: user-facing name for the IdP</li>
  5664. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  5665. for the IdP</li>
  5666. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  5667. for the brand of the IdP</li>
  5668. </ul>
  5669. </li>
  5670. <li><code>user_attributes</code>: an object containing details about the user that
  5671. we received from the IdP. May have the following attributes:
  5672. <ul>
  5673. <li>display_name: the user's display_name</li>
  5674. <li>emails: a list of email addresses
  5675. The template should render a form which submits the following fields:</li>
  5676. </ul>
  5677. </li>
  5678. <li><code>username</code>: the localpart of the user's chosen user id</li>
  5679. </ul>
  5680. </li>
  5681. <li><code>sso_new_user_consent.html</code>: HTML page allowing the user to consent to the
  5682. server's terms and conditions. This is only shown for new users, and only if
  5683. <code>user_consent.require_at_registration</code> is set.
  5684. When rendering, this template is given the following variables:
  5685. <ul>
  5686. <li><code>server_name</code>: the homeserver's name.</li>
  5687. <li><code>user_id</code>: the user's matrix proposed ID.</li>
  5688. <li><code>user_profile.display_name</code>: the user's proposed display name, if any.</li>
  5689. <li>consent_version: the version of the terms that the user will be
  5690. shown</li>
  5691. <li><code>terms_url</code>: a link to the page showing the terms.
  5692. The template should render a form which submits the following fields:</li>
  5693. <li><code>accepted_version</code>: the version of the terms accepted by the user
  5694. (ie, 'consent_version' from the input variables).</li>
  5695. </ul>
  5696. </li>
  5697. <li><code>sso_redirect_confirm.html</code>: HTML page for a confirmation step before redirecting back
  5698. to the client with the login token.
  5699. When rendering, this template is given the following variables:
  5700. <ul>
  5701. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  5702. <li><code>display_url</code>: the same as <code>redirect_url</code>, but with the query
  5703. parameters stripped. The intention is to have a
  5704. human-readable URL to show to users, not to use it as
  5705. the final address to redirect to.</li>
  5706. <li><code>server_name</code>: the homeserver's name.</li>
  5707. <li><code>new_user</code>: a boolean indicating whether this is the user's first time
  5708. logging in.</li>
  5709. <li><code>user_id</code>: the user's matrix ID.</li>
  5710. <li><code>user_profile.avatar_url</code>: an MXC URI for the user's avatar, if any.
  5711. <code>None</code> if the user has not set an avatar.</li>
  5712. <li><code>user_profile.display_name</code>: the user's display name. <code>None</code> if the user
  5713. has not set a display name.</li>
  5714. </ul>
  5715. </li>
  5716. <li><code>sso_auth_confirm.html</code>: HTML page which notifies the user that they are authenticating
  5717. to confirm an operation on their account during the user interactive authentication
  5718. process.
  5719. When rendering, this template is given the following variables:
  5720. <ul>
  5721. <li><code>redirect_url</code>: the URL the user is about to be redirected to.</li>
  5722. <li><code>description</code>: the operation which the user is being asked to confirm</li>
  5723. <li><code>idp</code>: details of the Identity Provider that we will use to confirm
  5724. the user's identity: an object with the following attributes:
  5725. <ul>
  5726. <li><code>idp_id</code>: unique identifier for the IdP</li>
  5727. <li><code>idp_name</code>: user-facing name for the IdP</li>
  5728. <li><code>idp_icon</code>: if specified in the IdP config, an MXC URI for an icon
  5729. for the IdP</li>
  5730. <li><code>idp_brand</code>: if specified in the IdP config, a textual identifier
  5731. for the brand of the IdP</li>
  5732. </ul>
  5733. </li>
  5734. </ul>
  5735. </li>
  5736. <li><code>sso_auth_success.html</code>: HTML page shown after a successful user interactive
  5737. authentication session.
  5738. Note that this page must include the JavaScript which notifies of a successful
  5739. authentication (see https://matrix.org/docs/spec/client_server/r0.6.0#fallback).
  5740. This template has no additional variables.</li>
  5741. <li><code>sso_auth_bad_user.html</code>: HTML page shown after a user-interactive authentication
  5742. session which does not map correctly onto the expected user.
  5743. When rendering, this template is given the following variables:
  5744. <ul>
  5745. <li><code>server_name</code>: the homeserver's name.</li>
  5746. <li><code>user_id_to_verify</code>: the MXID of the user that we are trying to
  5747. validate.</li>
  5748. </ul>
  5749. </li>
  5750. <li><code>sso_account_deactivated.html</code>: HTML page shown during single sign-on if a deactivated
  5751. user (according to Synapse's database) attempts to login.
  5752. This template has no additional variables.</li>
  5753. <li><code>sso_error.html</code>: HTML page to display to users if something goes wrong during the
  5754. OpenID Connect authentication process.
  5755. When rendering, this template is given two variables:
  5756. <ul>
  5757. <li><code>error</code>: the technical name of the error</li>
  5758. <li><code>error_description</code>: a human-readable message for the error</li>
  5759. </ul>
  5760. </li>
  5761. </ul>
  5762. <div style="break-before: page; page-break-before: always;"></div><h1 id="user-authentication"><a class="header" href="#user-authentication">User Authentication</a></h1>
  5763. <p>Synapse supports multiple methods of authenticating users, either out-of-the-box or through custom pluggable
  5764. authentication modules.</p>
  5765. <p>Included in Synapse is support for authenticating users via:</p>
  5766. <ul>
  5767. <li>A username and password.</li>
  5768. <li>An email address and password.</li>
  5769. <li>Single Sign-On through the SAML, Open ID Connect or CAS protocols.</li>
  5770. <li>JSON Web Tokens.</li>
  5771. <li>An administrator's shared secret.</li>
  5772. </ul>
  5773. <p>Synapse can additionally be extended to support custom authentication schemes through optional &quot;password auth provider&quot;
  5774. modules.</p>
  5775. <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>
  5776. <p>Synapse supports single sign-on through the SAML, Open ID Connect or CAS protocols.
  5777. LDAP and other login methods are supported through first and third-party password
  5778. auth provider modules.</p>
  5779. <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>
  5780. <p>Synapse can be configured to use an OpenID Connect Provider (OP) for
  5781. authentication, instead of its own local password database.</p>
  5782. <p>Any OP should work with Synapse, as long as it supports the authorization code
  5783. flow. There are a few options for that:</p>
  5784. <ul>
  5785. <li>
  5786. <p>start a local OP. Synapse has been tested with <a href="https://www.ory.sh/docs/hydra/">Hydra</a> and
  5787. <a href="https://github.com/dexidp/dex">Dex</a>. Note that for an OP to work, it should be served under a
  5788. secure (HTTPS) origin. A certificate signed with a self-signed, locally
  5789. trusted CA should work. In that case, start Synapse with a <code>SSL_CERT_FILE</code>
  5790. environment variable set to the path of the CA.</p>
  5791. </li>
  5792. <li>
  5793. <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
  5794. <a href="https://www.okta.com/">Okta</a>. Synapse has been tested with Auth0 and Google.</p>
  5795. </li>
  5796. </ul>
  5797. <p>It may also be possible to use other OAuth2 providers which provide the
  5798. <a href="https://tools.ietf.org/html/rfc6749#section-4.1">authorization code grant type</a>,
  5799. such as <a href="https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps">Github</a>.</p>
  5800. <h2 id="preparing-synapse"><a class="header" href="#preparing-synapse">Preparing Synapse</a></h2>
  5801. <p>The OpenID integration in Synapse uses the
  5802. <a href="https://pypi.org/project/Authlib/"><code>authlib</code></a> library, which must be installed
  5803. as follows:</p>
  5804. <ul>
  5805. <li>
  5806. <p>The relevant libraries are included in the Docker images and Debian packages
  5807. provided by <code>matrix.org</code> so no further action is needed.</p>
  5808. </li>
  5809. <li>
  5810. <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>
  5811. </li>
  5812. <li>
  5813. <p>For other installation mechanisms, see the documentation provided by the
  5814. maintainer.</p>
  5815. </li>
  5816. </ul>
  5817. <p>To enable the OpenID integration, you should then add a section to the <code>oidc_providers</code>
  5818. setting in your configuration file (or uncomment one of the existing examples).
  5819. See <a href="./sample_config.yaml">sample_config.yaml</a> for some sample settings, as well as
  5820. the text below for example configurations for specific providers.</p>
  5821. <h2 id="sample-configs"><a class="header" href="#sample-configs">Sample configs</a></h2>
  5822. <p>Here are a few configs for providers that should work with Synapse.</p>
  5823. <h3 id="microsoft-azure-active-directory"><a class="header" href="#microsoft-azure-active-directory">Microsoft Azure Active Directory</a></h3>
  5824. <p>Azure AD can act as an OpenID Connect Provider. Register a new application under
  5825. <em>App registrations</em> in the Azure AD management console. The RedirectURI for your
  5826. application should point to your matrix server:
  5827. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  5828. <p>Go to <em>Certificates &amp; secrets</em> and register a new client secret. Make note of your
  5829. Directory (tenant) ID as it will be used in the Azure links.
  5830. Edit your Synapse config file and change the <code>oidc_config</code> section:</p>
  5831. <pre><code class="language-yaml">oidc_providers:
  5832. - idp_id: microsoft
  5833. idp_name: Microsoft
  5834. issuer: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/v2.0&quot;
  5835. client_id: &quot;&lt;client id&gt;&quot;
  5836. client_secret: &quot;&lt;client secret&gt;&quot;
  5837. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  5838. authorization_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/authorize&quot;
  5839. token_endpoint: &quot;https://login.microsoftonline.com/&lt;tenant id&gt;/oauth2/v2.0/token&quot;
  5840. userinfo_endpoint: &quot;https://graph.microsoft.com/oidc/userinfo&quot;
  5841. user_mapping_provider:
  5842. config:
  5843. localpart_template: &quot;{{ user.preferred_username.split('@')[0] }}&quot;
  5844. display_name_template: &quot;{{ user.name }}&quot;
  5845. </code></pre>
  5846. <h3 id="dex"><a class="header" href="#dex">Dex</a></h3>
  5847. <p><a href="https://github.com/dexidp/dex">Dex</a> is a simple, open-source OpenID Connect Provider.
  5848. Although it is designed to help building a full-blown provider with an
  5849. external database, it can be configured with static passwords in a config file.</p>
  5850. <p>Follow the <a href="https://dexidp.io/docs/getting-started/">Getting Started guide</a>
  5851. to install Dex.</p>
  5852. <p>Edit <code>examples/config-dev.yaml</code> config file from the Dex repo to add a client:</p>
  5853. <pre><code class="language-yaml">staticClients:
  5854. - id: synapse
  5855. secret: secret
  5856. redirectURIs:
  5857. - '[synapse public baseurl]/_synapse/client/oidc/callback'
  5858. name: 'Synapse'
  5859. </code></pre>
  5860. <p>Run with <code>dex serve examples/config-dev.yaml</code>.</p>
  5861. <p>Synapse config:</p>
  5862. <pre><code class="language-yaml">oidc_providers:
  5863. - idp_id: dex
  5864. idp_name: &quot;My Dex server&quot;
  5865. skip_verification: true # This is needed as Dex is served on an insecure endpoint
  5866. issuer: &quot;http://127.0.0.1:5556/dex&quot;
  5867. client_id: &quot;synapse&quot;
  5868. client_secret: &quot;secret&quot;
  5869. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  5870. user_mapping_provider:
  5871. config:
  5872. localpart_template: &quot;{{ user.name }}&quot;
  5873. display_name_template: &quot;{{ user.name|capitalize }}&quot;
  5874. </code></pre>
  5875. <h3 id="keycloak"><a class="header" href="#keycloak">Keycloak</a></h3>
  5876. <p><a href="https://www.keycloak.org/docs/latest/server_admin/#sso-protocols">Keycloak</a> is an opensource IdP maintained by Red Hat.</p>
  5877. <p>Follow the <a href="https://www.keycloak.org/getting-started">Getting Started Guide</a> to install Keycloak and set up a realm.</p>
  5878. <ol>
  5879. <li>
  5880. <p>Click <code>Clients</code> in the sidebar and click <code>Create</code></p>
  5881. </li>
  5882. <li>
  5883. <p>Fill in the fields as below:</p>
  5884. </li>
  5885. </ol>
  5886. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  5887. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  5888. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  5889. </tbody></table>
  5890. <ol start="3">
  5891. <li>Click <code>Save</code></li>
  5892. <li>Fill in the fields as below:</li>
  5893. </ol>
  5894. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  5895. <tr><td>Client ID</td><td><code>synapse</code></td></tr>
  5896. <tr><td>Enabled</td><td><code>On</code></td></tr>
  5897. <tr><td>Client Protocol</td><td><code>openid-connect</code></td></tr>
  5898. <tr><td>Access Type</td><td><code>confidential</code></td></tr>
  5899. <tr><td>Valid Redirect URIs</td><td><code>[synapse public baseurl]/_synapse/client/oidc/callback</code></td></tr>
  5900. </tbody></table>
  5901. <ol start="5">
  5902. <li>Click <code>Save</code></li>
  5903. <li>On the Credentials tab, update the fields:</li>
  5904. </ol>
  5905. <table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>
  5906. <tr><td>Client Authenticator</td><td><code>Client ID and Secret</code></td></tr>
  5907. </tbody></table>
  5908. <ol start="7">
  5909. <li>Click <code>Regenerate Secret</code></li>
  5910. <li>Copy Secret</li>
  5911. </ol>
  5912. <pre><code class="language-yaml">oidc_providers:
  5913. - idp_id: keycloak
  5914. idp_name: &quot;My KeyCloak server&quot;
  5915. issuer: &quot;https://127.0.0.1:8443/auth/realms/{realm_name}&quot;
  5916. client_id: &quot;synapse&quot;
  5917. client_secret: &quot;copy secret generated from above&quot;
  5918. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  5919. user_mapping_provider:
  5920. config:
  5921. localpart_template: &quot;{{ user.preferred_username }}&quot;
  5922. display_name_template: &quot;{{ user.name }}&quot;
  5923. </code></pre>
  5924. <h3 id="auth0"><a class="header" href="#auth0">Auth0</a></h3>
  5925. <p><a href="https://auth0.com/">Auth0</a> is a hosted SaaS IdP solution.</p>
  5926. <ol>
  5927. <li>
  5928. <p>Create a regular web application for Synapse</p>
  5929. </li>
  5930. <li>
  5931. <p>Set the Allowed Callback URLs to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></p>
  5932. </li>
  5933. <li>
  5934. <p>Add a rule to add the <code>preferred_username</code> claim.</p>
  5935. <details>
  5936. <summary>Code sample</summary>
  5937. <pre><code class="language-js">function addPersistenceAttribute(user, context, callback) {
  5938. user.user_metadata = user.user_metadata || {};
  5939. user.user_metadata.preferred_username = user.user_metadata.preferred_username || user.user_id;
  5940. context.idToken.preferred_username = user.user_metadata.preferred_username;
  5941. auth0.users.updateUserMetadata(user.user_id, user.user_metadata)
  5942. .then(function(){
  5943. callback(null, user, context);
  5944. })
  5945. .catch(function(err){
  5946. callback(err);
  5947. });
  5948. }
  5949. </code></pre>
  5950. </li>
  5951. </ol>
  5952. </details>
  5953. <p>Synapse config:</p>
  5954. <pre><code class="language-yaml">oidc_providers:
  5955. - idp_id: auth0
  5956. idp_name: Auth0
  5957. issuer: &quot;https://your-tier.eu.auth0.com/&quot; # TO BE FILLED
  5958. client_id: &quot;your-client-id&quot; # TO BE FILLED
  5959. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  5960. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  5961. user_mapping_provider:
  5962. config:
  5963. localpart_template: &quot;{{ user.preferred_username }}&quot;
  5964. display_name_template: &quot;{{ user.name }}&quot;
  5965. </code></pre>
  5966. <h3 id="authentik"><a class="header" href="#authentik">Authentik</a></h3>
  5967. <p><a href="https://goauthentik.io/">Authentik</a> is an open-source IdP solution.</p>
  5968. <ol>
  5969. <li>Create a provider in Authentik, with type OAuth2/OpenID.</li>
  5970. <li>The parameters are:</li>
  5971. </ol>
  5972. <ul>
  5973. <li>Client Type: Confidential</li>
  5974. <li>JWT Algorithm: RS256</li>
  5975. <li>Scopes: OpenID, Email and Profile</li>
  5976. <li>RSA Key: Select any available key</li>
  5977. <li>Redirect URIs: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  5978. </ul>
  5979. <ol start="3">
  5980. <li>Create an application for synapse in Authentik and link it to the provider.</li>
  5981. <li>Note the slug of your application, Client ID and Client Secret.</li>
  5982. </ol>
  5983. <p>Synapse config:</p>
  5984. <pre><code class="language-yaml">oidc_providers:
  5985. - idp_id: authentik
  5986. idp_name: authentik
  5987. discover: true
  5988. issuer: &quot;https://your.authentik.example.org/application/o/your-app-slug/&quot; # TO BE FILLED: domain and slug
  5989. client_id: &quot;your client id&quot; # TO BE FILLED
  5990. client_secret: &quot;your client secret&quot; # TO BE FILLED
  5991. scopes:
  5992. - &quot;openid&quot;
  5993. - &quot;profile&quot;
  5994. - &quot;email&quot;
  5995. user_mapping_provider:
  5996. config:
  5997. localpart_template: &quot;{{ user.preferred_username }}}&quot;
  5998. 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.
  5999. </code></pre>
  6000. <h3 id="lemonldap"><a class="header" href="#lemonldap">LemonLDAP</a></h3>
  6001. <p><a href="https://lemonldap-ng.org/">LemonLDAP::NG</a> is an open-source IdP solution.</p>
  6002. <ol>
  6003. <li>Create an OpenID Connect Relying Parties in LemonLDAP::NG</li>
  6004. <li>The parameters are:</li>
  6005. </ol>
  6006. <ul>
  6007. <li>Client ID under the basic menu of the new Relying Parties (<code>Options &gt; Basic &gt; Client ID</code>)</li>
  6008. <li>Client secret (<code>Options &gt; Basic &gt; Client secret</code>)</li>
  6009. <li>JWT Algorithm: RS256 within the security menu of the new Relying Parties
  6010. (<code>Options &gt; Security &gt; ID Token signature algorithm</code> and <code>Options &gt; Security &gt; Access Token signature algorithm</code>)</li>
  6011. <li>Scopes: OpenID, Email and Profile</li>
  6012. <li>Allowed redirection addresses for login (<code>Options &gt; Basic &gt; Allowed redirection addresses for login</code> ) :
  6013. <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  6014. </ul>
  6015. <p>Synapse config:</p>
  6016. <pre><code class="language-yaml">oidc_providers:
  6017. - idp_id: lemonldap
  6018. idp_name: lemonldap
  6019. discover: true
  6020. issuer: &quot;https://auth.example.org/&quot; # TO BE FILLED: replace with your domain
  6021. client_id: &quot;your client id&quot; # TO BE FILLED
  6022. client_secret: &quot;your client secret&quot; # TO BE FILLED
  6023. scopes:
  6024. - &quot;openid&quot;
  6025. - &quot;profile&quot;
  6026. - &quot;email&quot;
  6027. user_mapping_provider:
  6028. config:
  6029. localpart_template: &quot;{{ user.preferred_username }}}&quot;
  6030. # 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.
  6031. display_name_template: &quot;{{ user.preferred_username|capitalize }}&quot;
  6032. </code></pre>
  6033. <h3 id="github"><a class="header" href="#github">GitHub</a></h3>
  6034. <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
  6035. just a regular OAuth2 provider.</p>
  6036. <p>The <a href="https://developer.github.com/v3/users/#get-the-authenticated-user"><code>/user</code> API endpoint</a>
  6037. can be used to retrieve information on the authenticated user. As the Synapse
  6038. login mechanism needs an attribute to uniquely identify users, and that endpoint
  6039. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  6040. <ol>
  6041. <li>Create a new OAuth application: https://github.com/settings/applications/new.</li>
  6042. <li>Set the callback URL to <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  6043. </ol>
  6044. <p>Synapse config:</p>
  6045. <pre><code class="language-yaml">oidc_providers:
  6046. - idp_id: github
  6047. idp_name: Github
  6048. idp_brand: &quot;github&quot; # optional: styling hint for clients
  6049. discover: false
  6050. issuer: &quot;https://github.com/&quot;
  6051. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6052. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6053. authorization_endpoint: &quot;https://github.com/login/oauth/authorize&quot;
  6054. token_endpoint: &quot;https://github.com/login/oauth/access_token&quot;
  6055. userinfo_endpoint: &quot;https://api.github.com/user&quot;
  6056. scopes: [&quot;read:user&quot;]
  6057. user_mapping_provider:
  6058. config:
  6059. subject_claim: &quot;id&quot;
  6060. localpart_template: &quot;{{ user.login }}&quot;
  6061. display_name_template: &quot;{{ user.name }}&quot;
  6062. </code></pre>
  6063. <h3 id="google"><a class="header" href="#google">Google</a></h3>
  6064. <p><a href="https://developers.google.com/identity/protocols/oauth2/openid-connect">Google</a> is an OpenID certified authentication and authorisation provider.</p>
  6065. <ol>
  6066. <li>Set up a project in the Google API Console (see
  6067. https://developers.google.com/identity/protocols/oauth2/openid-connect#appsetup).</li>
  6068. <li>Add an &quot;OAuth Client ID&quot; for a Web Application under &quot;Credentials&quot;.</li>
  6069. <li>Copy the Client ID and Client Secret, and add the following to your synapse config:
  6070. <pre><code class="language-yaml">oidc_providers:
  6071. - idp_id: google
  6072. idp_name: Google
  6073. idp_brand: &quot;google&quot; # optional: styling hint for clients
  6074. issuer: &quot;https://accounts.google.com/&quot;
  6075. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6076. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6077. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6078. user_mapping_provider:
  6079. config:
  6080. localpart_template: &quot;{{ user.given_name|lower }}&quot;
  6081. display_name_template: &quot;{{ user.name }}&quot;
  6082. </code></pre>
  6083. </li>
  6084. <li>Back in the Google console, add this Authorized redirect URI: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code>.</li>
  6085. </ol>
  6086. <h3 id="twitch"><a class="header" href="#twitch">Twitch</a></h3>
  6087. <ol>
  6088. <li>Setup a developer account on <a href="https://dev.twitch.tv/">Twitch</a></li>
  6089. <li>Obtain the OAuth 2.0 credentials by <a href="https://dev.twitch.tv/console/apps/">creating an app</a></li>
  6090. <li>Add this OAuth Redirect URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  6091. </ol>
  6092. <p>Synapse config:</p>
  6093. <pre><code class="language-yaml">oidc_providers:
  6094. - idp_id: twitch
  6095. idp_name: Twitch
  6096. issuer: &quot;https://id.twitch.tv/oauth2/&quot;
  6097. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6098. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6099. client_auth_method: &quot;client_secret_post&quot;
  6100. user_mapping_provider:
  6101. config:
  6102. localpart_template: &quot;{{ user.preferred_username }}&quot;
  6103. display_name_template: &quot;{{ user.name }}&quot;
  6104. </code></pre>
  6105. <h3 id="gitlab"><a class="header" href="#gitlab">GitLab</a></h3>
  6106. <ol>
  6107. <li>Create a <a href="https://gitlab.com/profile/applications">new application</a>.</li>
  6108. <li>Add the <code>read_user</code> and <code>openid</code> scopes.</li>
  6109. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  6110. </ol>
  6111. <p>Synapse config:</p>
  6112. <pre><code class="language-yaml">oidc_providers:
  6113. - idp_id: gitlab
  6114. idp_name: Gitlab
  6115. idp_brand: &quot;gitlab&quot; # optional: styling hint for clients
  6116. issuer: &quot;https://gitlab.com/&quot;
  6117. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6118. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6119. client_auth_method: &quot;client_secret_post&quot;
  6120. scopes: [&quot;openid&quot;, &quot;read_user&quot;]
  6121. user_profile_method: &quot;userinfo_endpoint&quot;
  6122. user_mapping_provider:
  6123. config:
  6124. localpart_template: '{{ user.nickname }}'
  6125. display_name_template: '{{ user.name }}'
  6126. </code></pre>
  6127. <h3 id="facebook"><a class="header" href="#facebook">Facebook</a></h3>
  6128. <ol start="0">
  6129. <li>You will need a Facebook developer account. You can register for one
  6130. <a href="https://developers.facebook.com/async/registration/">here</a>.</li>
  6131. <li>On the <a href="https://developers.facebook.com/apps/">apps</a> page of the developer
  6132. console, &quot;Create App&quot;, and choose &quot;Build Connected Experiences&quot;.</li>
  6133. <li>Once the app is created, add &quot;Facebook Login&quot; and choose &quot;Web&quot;. You don't
  6134. need to go through the whole form here.</li>
  6135. <li>In the left-hand menu, open &quot;Products&quot;/&quot;Facebook Login&quot;/&quot;Settings&quot;.
  6136. <ul>
  6137. <li>Add <code>[synapse public baseurl]/_synapse/client/oidc/callback</code> as an OAuth Redirect
  6138. URL.</li>
  6139. </ul>
  6140. </li>
  6141. <li>In the left-hand menu, open &quot;Settings/Basic&quot;. Here you can copy the &quot;App ID&quot;
  6142. and &quot;App Secret&quot; for use below.</li>
  6143. </ol>
  6144. <p>Synapse config:</p>
  6145. <pre><code class="language-yaml"> - idp_id: facebook
  6146. idp_name: Facebook
  6147. idp_brand: &quot;facebook&quot; # optional: styling hint for clients
  6148. discover: false
  6149. issuer: &quot;https://www.facebook.com&quot;
  6150. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6151. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6152. scopes: [&quot;openid&quot;, &quot;email&quot;]
  6153. authorization_endpoint: &quot;https://facebook.com/dialog/oauth&quot;
  6154. token_endpoint: &quot;https://graph.facebook.com/v9.0/oauth/access_token&quot;
  6155. jwks_uri: &quot;https://www.facebook.com/.well-known/oauth/openid/jwks/&quot;
  6156. user_mapping_provider:
  6157. config:
  6158. display_name_template: &quot;{{ user.name }}&quot;
  6159. email_template: &quot;{{ '{{ user.email }}' }}&quot;
  6160. </code></pre>
  6161. <p>Relevant documents:</p>
  6162. <ul>
  6163. <li><a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow">Manually Build a Login Flow</a></li>
  6164. <li><a href="https://developers.facebook.com/docs/graph-api/using-graph-api/">Using Facebook's Graph API</a></li>
  6165. <li><a href="https://developers.facebook.com/docs/graph-api/reference/user">Reference to the User endpoint</a></li>
  6166. </ul>
  6167. <p>Facebook do have an <a href="https://www.facebook.com/.well-known/openid-configuration">OIDC discovery endpoint</a>,
  6168. but it has a <code>response_types_supported</code> which excludes &quot;code&quot; (which we rely on, and
  6169. is even mentioned in their <a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#login">documentation</a>),
  6170. so we have to disable discovery and configure the URIs manually.</p>
  6171. <h3 id="gitea"><a class="header" href="#gitea">Gitea</a></h3>
  6172. <p>Gitea is, like Github, not an OpenID provider, but just an OAuth2 provider.</p>
  6173. <p>The <a href="https://try.gitea.io/api/swagger#/user/userGetCurrent"><code>/user</code> API endpoint</a>
  6174. can be used to retrieve information on the authenticated user. As the Synapse
  6175. login mechanism needs an attribute to uniquely identify users, and that endpoint
  6176. does not return a <code>sub</code> property, an alternative <code>subject_claim</code> has to be set.</p>
  6177. <ol>
  6178. <li>Create a new application.</li>
  6179. <li>Add this Callback URL: <code>[synapse public baseurl]/_synapse/client/oidc/callback</code></li>
  6180. </ol>
  6181. <p>Synapse config:</p>
  6182. <pre><code class="language-yaml">oidc_providers:
  6183. - idp_id: gitea
  6184. idp_name: Gitea
  6185. discover: false
  6186. issuer: &quot;https://your-gitea.com/&quot;
  6187. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6188. client_secret: &quot;your-client-secret&quot; # TO BE FILLED
  6189. client_auth_method: client_secret_post
  6190. scopes: [] # Gitea doesn't support Scopes
  6191. authorization_endpoint: &quot;https://your-gitea.com/login/oauth/authorize&quot;
  6192. token_endpoint: &quot;https://your-gitea.com/login/oauth/access_token&quot;
  6193. userinfo_endpoint: &quot;https://your-gitea.com/api/v1/user&quot;
  6194. user_mapping_provider:
  6195. config:
  6196. subject_claim: &quot;id&quot;
  6197. localpart_template: &quot;{{ user.login }}&quot;
  6198. display_name_template: &quot;{{ user.full_name }}&quot;
  6199. </code></pre>
  6200. <h3 id="xwiki"><a class="header" href="#xwiki">XWiki</a></h3>
  6201. <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>
  6202. <p>Synapse config:</p>
  6203. <pre><code class="language-yaml">oidc_providers:
  6204. - idp_id: xwiki
  6205. idp_name: &quot;XWiki&quot;
  6206. issuer: &quot;https://myxwikihost/xwiki/oidc/&quot;
  6207. client_id: &quot;your-client-id&quot; # TO BE FILLED
  6208. client_auth_method: none
  6209. scopes: [&quot;openid&quot;, &quot;profile&quot;]
  6210. user_profile_method: &quot;userinfo_endpoint&quot;
  6211. user_mapping_provider:
  6212. config:
  6213. localpart_template: &quot;{{ user.preferred_username }}&quot;
  6214. display_name_template: &quot;{{ user.name }}&quot;
  6215. </code></pre>
  6216. <h3 id="apple"><a class="header" href="#apple">Apple</a></h3>
  6217. <p>Configuring &quot;Sign in with Apple&quot; (SiWA) requires an Apple Developer account.</p>
  6218. <p>You will need to create a new &quot;Services ID&quot; for SiWA, and create and download a
  6219. private key with &quot;SiWA&quot; enabled.</p>
  6220. <p>As well as the private key file, you will need:</p>
  6221. <ul>
  6222. <li>Client ID: the &quot;identifier&quot; you gave the &quot;Services ID&quot;</li>
  6223. <li>Team ID: a 10-character ID associated with your developer account.</li>
  6224. <li>Key ID: the 10-character identifier for the key.</li>
  6225. </ul>
  6226. <p>https://help.apple.com/developer-account/?lang=en#/dev77c875b7e has more
  6227. documentation on setting up SiWA.</p>
  6228. <p>The synapse config will look like this:</p>
  6229. <pre><code class="language-yaml"> - idp_id: apple
  6230. idp_name: Apple
  6231. issuer: &quot;https://appleid.apple.com&quot;
  6232. client_id: &quot;your-client-id&quot; # Set to the &quot;identifier&quot; for your &quot;ServicesID&quot;
  6233. client_auth_method: &quot;client_secret_post&quot;
  6234. client_secret_jwt_key:
  6235. key_file: &quot;/path/to/AuthKey_KEYIDCODE.p8&quot; # point to your key file
  6236. jwt_header:
  6237. alg: ES256
  6238. kid: &quot;KEYIDCODE&quot; # Set to the 10-char Key ID
  6239. jwt_payload:
  6240. iss: TEAMIDCODE # Set to the 10-char Team ID
  6241. scopes: [&quot;name&quot;, &quot;email&quot;, &quot;openid&quot;]
  6242. authorization_endpoint: https://appleid.apple.com/auth/authorize?response_mode=form_post
  6243. user_mapping_provider:
  6244. config:
  6245. email_template: &quot;{{ user.email }}&quot;
  6246. </code></pre>
  6247. <h3 id="django-oauth-toolkit"><a class="header" href="#django-oauth-toolkit">Django OAuth Toolkit</a></h3>
  6248. <p><a href="https://github.com/jazzband/django-oauth-toolkit">django-oauth-toolkit</a> is a
  6249. Django application providing out of the box all the endpoints, data and logic
  6250. needed to add OAuth2 capabilities to your Django projects. It supports
  6251. <a href="https://django-oauth-toolkit.readthedocs.io/en/latest/oidc.html">OpenID Connect too</a>.</p>
  6252. <p>Configuration on Django's side:</p>
  6253. <ol>
  6254. <li>Add an application: https://example.com/admin/oauth2_provider/application/add/ and choose parameters like this:</li>
  6255. </ol>
  6256. <ul>
  6257. <li><code>Redirect uris</code>: https://synapse.example.com/_synapse/client/oidc/callback</li>
  6258. <li><code>Client type</code>: <code>Confidential</code></li>
  6259. <li><code>Authorization grant type</code>: <code>Authorization code</code></li>
  6260. <li><code>Algorithm</code>: <code>HMAC with SHA-2 256</code></li>
  6261. </ul>
  6262. <ol start="2">
  6263. <li>
  6264. <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>
  6265. <details>
  6266. <summary>Code sample</summary>
  6267. <pre><code class="language-python">class CustomOAuth2Validator(OAuth2Validator):
  6268. def get_additional_claims(self, request):
  6269. return {
  6270. &quot;sub&quot;: request.user.email,
  6271. &quot;email&quot;: request.user.email,
  6272. &quot;first_name&quot;: request.user.first_name,
  6273. &quot;last_name&quot;: request.user.last_name,
  6274. }
  6275. </code></pre>
  6276. </details>
  6277. </li>
  6278. </ol>
  6279. <p>Your synapse config is then:</p>
  6280. <pre><code class="language-yaml">oidc_providers:
  6281. - idp_id: django_example
  6282. idp_name: &quot;Django Example&quot;
  6283. issuer: &quot;https://example.com/o/&quot;
  6284. client_id: &quot;your-client-id&quot; # CHANGE ME
  6285. client_secret: &quot;your-client-secret&quot; # CHANGE ME
  6286. scopes: [&quot;openid&quot;]
  6287. user_profile_method: &quot;userinfo_endpoint&quot; # needed because oauth-toolkit does not include user information in the authorization response
  6288. user_mapping_provider:
  6289. config:
  6290. localpart_template: &quot;{{ user.email.split('@')[0] }}&quot;
  6291. display_name_template: &quot;{{ user.first_name }} {{ user.last_name }}&quot;
  6292. email_template: &quot;{{ user.email }}&quot;
  6293. </code></pre>
  6294. <div style="break-before: page; page-break-before: always;"></div><h1 id="saml"><a class="header" href="#saml">SAML</a></h1>
  6295. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language">Security Assertion
  6296. Markup Language</a>
  6297. (SAML) protocol natively.</p>
  6298. <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
  6299. file</a> for more details.</p>
  6300. <div style="break-before: page; page-break-before: always;"></div><h1 id="cas"><a class="header" href="#cas">CAS</a></h1>
  6301. <p>Synapse supports authenticating users via the <a href="https://en.wikipedia.org/wiki/Central_Authentication_Service">Central Authentication
  6302. Service protocol</a>
  6303. (CAS) natively.</p>
  6304. <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
  6305. file</a> for more details.</p>
  6306. <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>
  6307. <p>A mapping provider is a Python class (loaded via a Python module) that
  6308. works out how to map attributes of a SSO response to Matrix-specific
  6309. user attributes. Details such as user ID localpart, displayname, and even avatar
  6310. URLs are all things that can be mapped from talking to a SSO service.</p>
  6311. <p>As an example, a SSO service may return the email address
  6312. &quot;john.smith@example.com&quot; for a user, whereas Synapse will need to figure out how
  6313. to turn that into a displayname when creating a Matrix user for this individual.
  6314. It may choose <code>John Smith</code>, or <code>Smith, John [Example.com]</code> or any number of
  6315. variations. As each Synapse configuration may want something different, this is
  6316. where SAML mapping providers come into play.</p>
  6317. <p>SSO mapping providers are currently supported for OpenID and SAML SSO
  6318. configurations. Please see the details below for how to implement your own.</p>
  6319. <p>It is up to the mapping provider whether the user should be assigned a predefined
  6320. Matrix ID based on the SSO attributes, or if the user should be allowed to
  6321. choose their own username.</p>
  6322. <p>In the first case - where users are automatically allocated a Matrix ID - it is
  6323. the responsibility of the mapping provider to normalise the SSO attributes and
  6324. map them to a valid Matrix ID. The <a href="https://matrix.org/docs/spec/appendices#user-identifiers">specification for Matrix
  6325. IDs</a> has some
  6326. information about what is considered valid.</p>
  6327. <p>If the mapping provider does not assign a Matrix ID, then Synapse will
  6328. automatically serve an HTML page allowing the user to pick their own username.</p>
  6329. <p>External mapping providers are provided to Synapse in the form of an external
  6330. Python module. You can retrieve this module from <a href="https://pypi.org">PyPI</a> or elsewhere,
  6331. but it must be importable via Synapse (e.g. it must be in the same virtualenv
  6332. as Synapse). The Synapse config is then modified to point to the mapping provider
  6333. (and optionally provide additional configuration for it).</p>
  6334. <h2 id="openid-mapping-providers"><a class="header" href="#openid-mapping-providers">OpenID Mapping Providers</a></h2>
  6335. <p>The OpenID mapping provider can be customized by editing the
  6336. <code>oidc_config.user_mapping_provider.module</code> config option.</p>
  6337. <p><code>oidc_config.user_mapping_provider.config</code> allows you to provide custom
  6338. configuration options to the module. Check with the module's documentation for
  6339. what options it provides (if any). The options listed by default are for the
  6340. user mapping provider built in to Synapse. If using a custom module, you should
  6341. comment these options out and use those specified by the module instead.</p>
  6342. <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>
  6343. <p>A custom mapping provider must specify the following methods:</p>
  6344. <ul>
  6345. <li><code>def __init__(self, parsed_config)</code>
  6346. <ul>
  6347. <li>Arguments:
  6348. <ul>
  6349. <li><code>parsed_config</code> - A configuration object that is the return value of the
  6350. <code>parse_config</code> method. You should set any configuration options needed by
  6351. the module here.</li>
  6352. </ul>
  6353. </li>
  6354. </ul>
  6355. </li>
  6356. <li><code>def parse_config(config)</code>
  6357. <ul>
  6358. <li>This method should have the <code>@staticmethod</code> decoration.</li>
  6359. <li>Arguments:
  6360. <ul>
  6361. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  6362. <code>oidc_config.user_mapping_provider.config</code> homeserver config option.
  6363. Runs on homeserver startup. Providers should extract and validate
  6364. any option values they need here.</li>
  6365. </ul>
  6366. </li>
  6367. <li>Whatever is returned will be passed back to the user mapping provider module's
  6368. <code>__init__</code> method during construction.</li>
  6369. </ul>
  6370. </li>
  6371. <li><code>def get_remote_user_id(self, userinfo)</code>
  6372. <ul>
  6373. <li>Arguments:
  6374. <ul>
  6375. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  6376. information from.</li>
  6377. </ul>
  6378. </li>
  6379. <li>This method must return a string, which is the unique, immutable identifier
  6380. for the user. Commonly the <code>sub</code> claim of the response.</li>
  6381. </ul>
  6382. </li>
  6383. <li><code>async def map_user_attributes(self, userinfo, token, failures)</code>
  6384. <ul>
  6385. <li>This method must be async.</li>
  6386. <li>Arguments:
  6387. <ul>
  6388. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  6389. information from.</li>
  6390. <li><code>token</code> - A dictionary which includes information necessary to make
  6391. further requests to the OpenID provider.</li>
  6392. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  6393. mxid localpart mapping has failed. This should be used
  6394. to create a deduplicated mxid localpart which should be
  6395. returned instead. For example, if this method returns
  6396. <code>john.doe</code> as the value of <code>localpart</code> in the returned
  6397. dict, and that is already taken on the homeserver, this
  6398. method will be called again with the same parameters but
  6399. with failures=1. The method should then return a different
  6400. <code>localpart</code> value, such as <code>john.doe1</code>.</li>
  6401. </ul>
  6402. </li>
  6403. <li>Returns a dictionary with two keys:
  6404. <ul>
  6405. <li><code>localpart</code>: A string, used to generate the Matrix ID. If this is
  6406. <code>None</code>, the user is prompted to pick their own username. This is only used
  6407. during a user's first login. Once a localpart has been associated with a
  6408. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  6409. <li><code>displayname</code>: An optional string, the display name for the user.</li>
  6410. </ul>
  6411. </li>
  6412. </ul>
  6413. </li>
  6414. <li><code>async def get_extra_attributes(self, userinfo, token)</code>
  6415. <ul>
  6416. <li>
  6417. <p>This method must be async.</p>
  6418. </li>
  6419. <li>
  6420. <p>Arguments:</p>
  6421. <ul>
  6422. <li><code>userinfo</code> - A <code>authlib.oidc.core.claims.UserInfo</code> object to extract user
  6423. information from.</li>
  6424. <li><code>token</code> - A dictionary which includes information necessary to make
  6425. further requests to the OpenID provider.</li>
  6426. </ul>
  6427. </li>
  6428. <li>
  6429. <p>Returns a dictionary that is suitable to be serialized to JSON. This
  6430. will be returned as part of the response during a successful login.</p>
  6431. <p>Note that care should be taken to not overwrite any of the parameters
  6432. 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>
  6433. </li>
  6434. </ul>
  6435. </li>
  6436. </ul>
  6437. <h3 id="default-openid-mapping-provider"><a class="header" href="#default-openid-mapping-provider">Default OpenID Mapping Provider</a></h3>
  6438. <p>Synapse has a built-in OpenID mapping provider if a custom provider isn't
  6439. specified in the config. It is located at
  6440. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/oidc.py"><code>synapse.handlers.oidc.JinjaOidcMappingProvider</code></a>.</p>
  6441. <h2 id="saml-mapping-providers"><a class="header" href="#saml-mapping-providers">SAML Mapping Providers</a></h2>
  6442. <p>The SAML mapping provider can be customized by editing the
  6443. <code>saml2_config.user_mapping_provider.module</code> config option.</p>
  6444. <p><code>saml2_config.user_mapping_provider.config</code> allows you to provide custom
  6445. configuration options to the module. Check with the module's documentation for
  6446. what options it provides (if any). The options listed by default are for the
  6447. user mapping provider built in to Synapse. If using a custom module, you should
  6448. comment these options out and use those specified by the module instead.</p>
  6449. <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>
  6450. <p>A custom mapping provider must specify the following methods:</p>
  6451. <ul>
  6452. <li><code>def __init__(self, parsed_config, module_api)</code>
  6453. <ul>
  6454. <li>Arguments:
  6455. <ul>
  6456. <li><code>parsed_config</code> - A configuration object that is the return value of the
  6457. <code>parse_config</code> method. You should set any configuration options needed by
  6458. the module here.</li>
  6459. <li><code>module_api</code> - a <code>synapse.module_api.ModuleApi</code> object which provides the
  6460. stable API available for extension modules.</li>
  6461. </ul>
  6462. </li>
  6463. </ul>
  6464. </li>
  6465. <li><code>def parse_config(config)</code>
  6466. <ul>
  6467. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  6468. <li>Arguments:
  6469. <ul>
  6470. <li><code>config</code> - A <code>dict</code> representing the parsed content of the
  6471. <code>saml_config.user_mapping_provider.config</code> homeserver config option.
  6472. Runs on homeserver startup. Providers should extract and validate
  6473. any option values they need here.</li>
  6474. </ul>
  6475. </li>
  6476. <li>Whatever is returned will be passed back to the user mapping provider module's
  6477. <code>__init__</code> method during construction.</li>
  6478. </ul>
  6479. </li>
  6480. <li><code>def get_saml_attributes(config)</code>
  6481. <ul>
  6482. <li><strong>This method should have the <code>@staticmethod</code> decoration.</strong></li>
  6483. <li>Arguments:
  6484. <ul>
  6485. <li><code>config</code> - A object resulting from a call to <code>parse_config</code>.</li>
  6486. </ul>
  6487. </li>
  6488. <li>Returns a tuple of two sets. The first set equates to the SAML auth
  6489. response attributes that are required for the module to function, whereas
  6490. the second set consists of those attributes which can be used if available,
  6491. but are not necessary.</li>
  6492. </ul>
  6493. </li>
  6494. <li><code>def get_remote_user_id(self, saml_response, client_redirect_url)</code>
  6495. <ul>
  6496. <li>Arguments:
  6497. <ul>
  6498. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  6499. information from.</li>
  6500. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  6501. redirected to.</li>
  6502. </ul>
  6503. </li>
  6504. <li>This method must return a string, which is the unique, immutable identifier
  6505. for the user. Commonly the <code>uid</code> claim of the response.</li>
  6506. </ul>
  6507. </li>
  6508. <li><code>def saml_response_to_user_attributes(self, saml_response, failures, client_redirect_url)</code>
  6509. <ul>
  6510. <li>
  6511. <p>Arguments:</p>
  6512. <ul>
  6513. <li><code>saml_response</code> - A <code>saml2.response.AuthnResponse</code> object to extract user
  6514. information from.</li>
  6515. <li><code>failures</code> - An <code>int</code> that represents the amount of times the returned
  6516. mxid localpart mapping has failed. This should be used
  6517. to create a deduplicated mxid localpart which should be
  6518. returned instead. For example, if this method returns
  6519. <code>john.doe</code> as the value of <code>mxid_localpart</code> in the returned
  6520. dict, and that is already taken on the homeserver, this
  6521. method will be called again with the same parameters but
  6522. with failures=1. The method should then return a different
  6523. <code>mxid_localpart</code> value, such as <code>john.doe1</code>.</li>
  6524. <li><code>client_redirect_url</code> - A string, the URL that the client will be
  6525. redirected to.</li>
  6526. </ul>
  6527. </li>
  6528. <li>
  6529. <p>This method must return a dictionary, which will then be used by Synapse
  6530. to build a new user. The following keys are allowed:</p>
  6531. <ul>
  6532. <li><code>mxid_localpart</code> - A string, the mxid localpart of the new user. If this is
  6533. <code>None</code>, the user is prompted to pick their own username. This is only used
  6534. during a user's first login. Once a localpart has been associated with a
  6535. remote user ID (see <code>get_remote_user_id</code>) it cannot be updated.</li>
  6536. <li><code>displayname</code> - The displayname of the new user. If not provided, will default to
  6537. the value of <code>mxid_localpart</code>.</li>
  6538. <li><code>emails</code> - A list of emails for the new user. If not provided, will
  6539. default to an empty list.</li>
  6540. </ul>
  6541. <p>Alternatively it can raise a <code>synapse.api.errors.RedirectException</code> to
  6542. redirect the user to another page. This is useful to prompt the user for
  6543. additional information, e.g. if you want them to provide their own username.
  6544. It is the responsibility of the mapping provider to either redirect back
  6545. to <code>client_redirect_url</code> (including any additional information) or to
  6546. complete registration using methods from the <code>ModuleApi</code>.</p>
  6547. </li>
  6548. </ul>
  6549. </li>
  6550. </ul>
  6551. <h3 id="default-saml-mapping-provider"><a class="header" href="#default-saml-mapping-provider">Default SAML Mapping Provider</a></h3>
  6552. <p>Synapse has a built-in SAML mapping provider if a custom provider isn't
  6553. specified in the config. It is located at
  6554. <a href="https://github.com/matrix-org/synapse/blob/develop/synapse/handlers/saml.py"><code>synapse.handlers.saml.DefaultSamlMappingProvider</code></a>.</p>
  6555. <div style="break-before: page; page-break-before: always;"></div><h2 style="color:red">
  6556. This page of the Synapse documentation is now deprecated. For up to date
  6557. documentation on setting up or writing a password auth provider module, please see
  6558. <a href="modules/index.html">this page</a>.
  6559. </h2>
  6560. <h1 id="password-auth-provider-modules"><a class="header" href="#password-auth-provider-modules">Password auth provider modules</a></h1>
  6561. <p>Password auth providers offer a way for server administrators to
  6562. integrate their Synapse installation with an existing authentication
  6563. system.</p>
  6564. <p>A password auth provider is a Python class which is dynamically loaded
  6565. into Synapse, and provides a number of methods by which it can integrate
  6566. with the authentication system.</p>
  6567. <p>This document serves as a reference for those looking to implement their
  6568. own password auth providers. Additionally, here is a list of known
  6569. password auth provider module implementations:</p>
  6570. <ul>
  6571. <li><a href="https://github.com/matrix-org/matrix-synapse-ldap3/">matrix-synapse-ldap3</a></li>
  6572. <li><a href="https://github.com/devture/matrix-synapse-shared-secret-auth">matrix-synapse-shared-secret-auth</a></li>
  6573. <li><a href="https://github.com/ma1uta/matrix-synapse-rest-password-provider">matrix-synapse-rest-password-provider</a></li>
  6574. </ul>
  6575. <h2 id="required-methods"><a class="header" href="#required-methods">Required methods</a></h2>
  6576. <p>Password auth provider classes must provide the following methods:</p>
  6577. <ul>
  6578. <li>
  6579. <p><code>parse_config(config)</code>
  6580. This method is passed the <code>config</code> object for this module from the
  6581. homeserver configuration file.</p>
  6582. <p>It should perform any appropriate sanity checks on the provided
  6583. configuration, and return an object which is then passed into
  6584. <code>__init__</code>.</p>
  6585. <p>This method should have the <code>@staticmethod</code> decoration.</p>
  6586. </li>
  6587. <li>
  6588. <p><code>__init__(self, config, account_handler)</code></p>
  6589. <p>The constructor is passed the config object returned by
  6590. <code>parse_config</code>, and a <code>synapse.module_api.ModuleApi</code> object which
  6591. allows the password provider to check if accounts exist and/or create
  6592. new ones.</p>
  6593. </li>
  6594. </ul>
  6595. <h2 id="optional-methods"><a class="header" href="#optional-methods">Optional methods</a></h2>
  6596. <p>Password auth provider classes may optionally provide the following methods:</p>
  6597. <ul>
  6598. <li>
  6599. <p><code>get_db_schema_files(self)</code></p>
  6600. <p>This method, if implemented, should return an Iterable of
  6601. <code>(name, stream)</code> pairs of database schema files. Each file is applied
  6602. in turn at initialisation, and a record is then made in the database
  6603. so that it is not re-applied on the next start.</p>
  6604. </li>
  6605. <li>
  6606. <p><code>get_supported_login_types(self)</code></p>
  6607. <p>This method, if implemented, should return a <code>dict</code> mapping from a
  6608. login type identifier (such as <code>m.login.password</code>) to an iterable
  6609. giving the fields which must be provided by the user in the submission
  6610. to <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-login">the <code>/login</code> API</a>.
  6611. These fields are passed in the <code>login_dict</code> dictionary to <code>check_auth</code>.</p>
  6612. <p>For example, if a password auth provider wants to implement a custom
  6613. login type of <code>com.example.custom_login</code>, where the client is expected
  6614. to pass the fields <code>secret1</code> and <code>secret2</code>, the provider should
  6615. implement this method and return the following dict:</p>
  6616. <pre><code class="language-python">{&quot;com.example.custom_login&quot;: (&quot;secret1&quot;, &quot;secret2&quot;)}
  6617. </code></pre>
  6618. </li>
  6619. <li>
  6620. <p><code>check_auth(self, username, login_type, login_dict)</code></p>
  6621. <p>This method does the real work. If implemented, it
  6622. will be called for each login attempt where the login type matches one
  6623. of the keys returned by <code>get_supported_login_types</code>.</p>
  6624. <p>It is passed the (possibly unqualified) <code>user</code> field provided by the client,
  6625. the login type, and a dictionary of login secrets passed by the
  6626. client.</p>
  6627. <p>The method should return an <code>Awaitable</code> object, which resolves
  6628. to the canonical <code>@localpart:domain</code> user ID if authentication is
  6629. successful, and <code>None</code> if not.</p>
  6630. <p>Alternatively, the <code>Awaitable</code> can resolve to a <code>(str, func)</code> tuple, in
  6631. which case the second field is a callback which will be called with
  6632. the result from the <code>/login</code> call (including <code>access_token</code>,
  6633. <code>device_id</code>, etc.)</p>
  6634. </li>
  6635. <li>
  6636. <p><code>check_3pid_auth(self, medium, address, password)</code></p>
  6637. <p>This method, if implemented, is called when a user attempts to
  6638. register or log in with a third party identifier, such as email. It is
  6639. passed the medium (ex. &quot;email&quot;), an address (ex.
  6640. &quot;<a href="mailto:jdoe@example.com">jdoe@example.com</a>&quot;) and the user's password.</p>
  6641. <p>The method should return an <code>Awaitable</code> object, which resolves
  6642. to a <code>str</code> containing the user's (canonical) User id if
  6643. authentication was successful, and <code>None</code> if not.</p>
  6644. <p>As with <code>check_auth</code>, the <code>Awaitable</code> may alternatively resolve to a
  6645. <code>(user_id, callback)</code> tuple.</p>
  6646. </li>
  6647. <li>
  6648. <p><code>check_password(self, user_id, password)</code></p>
  6649. <p>This method provides a simpler interface than
  6650. <code>get_supported_login_types</code> and <code>check_auth</code> for password auth
  6651. providers that just want to provide a mechanism for validating
  6652. <code>m.login.password</code> logins.</p>
  6653. <p>If implemented, it will be called to check logins with an
  6654. <code>m.login.password</code> login type. It is passed a qualified
  6655. <code>@localpart:domain</code> user id, and the password provided by the user.</p>
  6656. <p>The method should return an <code>Awaitable</code> object, which resolves
  6657. to <code>True</code> if authentication is successful, and <code>False</code> if not.</p>
  6658. </li>
  6659. <li>
  6660. <p><code>on_logged_out(self, user_id, device_id, access_token)</code></p>
  6661. <p>This method, if implemented, is called when a user logs out. It is
  6662. passed the qualified user ID, the ID of the deactivated device (if
  6663. any: access tokens are occasionally created without an associated
  6664. device ID), and the (now deactivated) access token.</p>
  6665. <p>It may return an <code>Awaitable</code> object; the logout request will
  6666. wait for the <code>Awaitable</code> to complete, but the result is ignored.</p>
  6667. </li>
  6668. </ul>
  6669. <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>
  6670. <p>Synapse comes with a non-standard login type to support
  6671. <a href="https://en.wikipedia.org/wiki/JSON_Web_Token">JSON Web Tokens</a>. In general the
  6672. documentation for
  6673. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#login">the login endpoint</a>
  6674. is still valid (and the mechanism works similarly to the
  6675. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#token-based">token based login</a>).</p>
  6676. <p>To log in using a JSON Web Token, clients should submit a <code>/login</code> request as
  6677. follows:</p>
  6678. <pre><code class="language-json">{
  6679. &quot;type&quot;: &quot;org.matrix.login.jwt&quot;,
  6680. &quot;token&quot;: &quot;&lt;jwt&gt;&quot;
  6681. }
  6682. </code></pre>
  6683. <p>Note that the login type of <code>m.login.jwt</code> is supported, but is deprecated. This
  6684. will be removed in a future version of Synapse.</p>
  6685. <p>The <code>token</code> field should include the JSON web token with the following claims:</p>
  6686. <ul>
  6687. <li>A claim that encodes the local part of the user ID is required. By default,
  6688. the <code>sub</code> (subject) claim is used, or a custom claim can be set in the
  6689. configuration file.</li>
  6690. <li>The expiration time (<code>exp</code>), not before time (<code>nbf</code>), and issued at (<code>iat</code>)
  6691. claims are optional, but validated if present.</li>
  6692. <li>The issuer (<code>iss</code>) claim is optional, but required and validated if configured.</li>
  6693. <li>The audience (<code>aud</code>) claim is optional, but required and validated if configured.
  6694. Providing the audience claim when not configured will cause validation to fail.</li>
  6695. </ul>
  6696. <p>In the case that the token is not valid, the homeserver must respond with
  6697. <code>403 Forbidden</code> and an error code of <code>M_FORBIDDEN</code>.</p>
  6698. <p>As with other login types, there are additional fields (e.g. <code>device_id</code> and
  6699. <code>initial_device_display_name</code>) which can be included in the above request.</p>
  6700. <h2 id="preparing-synapse-1"><a class="header" href="#preparing-synapse-1">Preparing Synapse</a></h2>
  6701. <p>The JSON Web Token integration in Synapse uses the
  6702. <a href="https://pypi.org/project/pyjwt/"><code>PyJWT</code></a> library, which must be installed
  6703. as follows:</p>
  6704. <ul>
  6705. <li>
  6706. <p>The relevant libraries are included in the Docker images and Debian packages
  6707. provided by <code>matrix.org</code> so no further action is needed.</p>
  6708. </li>
  6709. <li>
  6710. <p>If you installed Synapse into a virtualenv, run <code>/path/to/env/bin/pip install synapse[pyjwt]</code> to install the necessary dependencies.</p>
  6711. </li>
  6712. <li>
  6713. <p>For other installation mechanisms, see the documentation provided by the
  6714. maintainer.</p>
  6715. </li>
  6716. </ul>
  6717. <p>To enable the JSON web token integration, you should then add an <code>jwt_config</code> section
  6718. to your configuration file (or uncomment the <code>enabled: true</code> line in the
  6719. existing section). See <a href="./sample_config.yaml">sample_config.yaml</a> for some
  6720. sample settings.</p>
  6721. <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>
  6722. <p>Although JSON Web Tokens are typically generated from an external server, the
  6723. examples below use <a href="https://pyjwt.readthedocs.io/en/latest/">PyJWT</a> directly.</p>
  6724. <ol>
  6725. <li>
  6726. <p>Configure Synapse with JWT logins, note that this example uses a pre-shared
  6727. secret and an algorithm of HS256:</p>
  6728. <pre><code class="language-yaml">jwt_config:
  6729. enabled: true
  6730. secret: &quot;my-secret-token&quot;
  6731. algorithm: &quot;HS256&quot;
  6732. </code></pre>
  6733. </li>
  6734. <li>
  6735. <p>Generate a JSON web token:</p>
  6736. <pre><code class="language-bash">$ pyjwt --key=my-secret-token --alg=HS256 encode sub=test-user
  6737. eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.Ag71GT8v01UO3w80aqRPTeuVPBIBZkYhNTJJ-_-zQIc
  6738. </code></pre>
  6739. </li>
  6740. <li>
  6741. <p>Query for the login types and ensure <code>org.matrix.login.jwt</code> is there:</p>
  6742. <pre><code class="language-bash">curl http://localhost:8080/_matrix/client/r0/login
  6743. </code></pre>
  6744. </li>
  6745. <li>
  6746. <p>Login used the generated JSON web token from above:</p>
  6747. <pre><code class="language-bash">$ curl http://localhost:8082/_matrix/client/r0/login -X POST \
  6748. --data '{&quot;type&quot;:&quot;org.matrix.login.jwt&quot;,&quot;token&quot;:&quot;eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXVzZXIifQ.Ag71GT8v01UO3w80aqRPTeuVPBIBZkYhNTJJ-_-zQIc&quot;}'
  6749. {
  6750. &quot;access_token&quot;: &quot;&lt;access token&gt;&quot;,
  6751. &quot;device_id&quot;: &quot;ACBDEFGHI&quot;,
  6752. &quot;home_server&quot;: &quot;localhost:8080&quot;,
  6753. &quot;user_id&quot;: &quot;@test-user:localhost:8480&quot;
  6754. }
  6755. </code></pre>
  6756. </li>
  6757. </ol>
  6758. <p>You should now be able to use the returned access token to query the client API.</p>
  6759. <div style="break-before: page; page-break-before: always;"></div><h1 id="refresh-tokens"><a class="header" href="#refresh-tokens">Refresh Tokens</a></h1>
  6760. <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>
  6761. <h2 id="background-and-motivation"><a class="header" href="#background-and-motivation">Background and motivation</a></h2>
  6762. <p>Synapse users' sessions are identified by <strong>access tokens</strong>; access tokens are
  6763. issued to users on login. Each session gets a unique access token which identifies
  6764. it; the access token must be kept secret as it grants access to the user's account.</p>
  6765. <p>Traditionally, these access tokens were eternally valid (at least until the user
  6766. explicitly chose to log out).</p>
  6767. <p>In some cases, it may be desirable for these access tokens to expire so that the
  6768. potential damage caused by leaking an access token is reduced.
  6769. On the other hand, forcing a user to re-authenticate (log in again) often might
  6770. be too much of an inconvenience.</p>
  6771. <p><strong>Refresh tokens</strong> are a mechanism to avoid some of this inconvenience whilst
  6772. still getting most of the benefits of short access token lifetimes.
  6773. Refresh tokens are also a concept present in OAuth 2 — further reading is available
  6774. <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-1.5">here</a>.</p>
  6775. <p>When refresh tokens are in use, both an access token and a refresh token will be
  6776. issued to users on login. The access token will expire after a predetermined amount
  6777. of time, but otherwise works in the same way as before. When the access token is
  6778. close to expiring (or has expired), the user's client should present the homeserver
  6779. (Synapse) with the refresh token.</p>
  6780. <p>The homeserver will then generate a new access token and refresh token for the user
  6781. and return them. The old refresh token is invalidated and can not be used again*.</p>
  6782. <p>Finally, refresh tokens also make it possible for sessions to be logged out if they
  6783. are inactive for too long, before the session naturally ends; see the configuration
  6784. guide below.</p>
  6785. <p>*To prevent issues if clients lose connection half-way through refreshing a token,
  6786. the refresh token is only invalidated once the new access token has been used at
  6787. least once. For all intents and purposes, the above simplification is sufficient.</p>
  6788. <h2 id="caveats"><a class="header" href="#caveats">Caveats</a></h2>
  6789. <p>There are some caveats:</p>
  6790. <ul>
  6791. <li>If a third party gets both your access token and refresh token, they will be able to
  6792. continue to enjoy access to your session.
  6793. <ul>
  6794. <li>This is still an improvement because you (the user) will notice when <em>your</em>
  6795. session expires and you're not able to use your refresh token.
  6796. That would be a giveaway that someone else has compromised your session.
  6797. You would be able to log in again and terminate that session.
  6798. Previously (with long-lived access tokens), a third party that has your access
  6799. token could go undetected for a very long time.</li>
  6800. </ul>
  6801. </li>
  6802. <li>Clients need to implement support for refresh tokens in order for them to be a
  6803. useful mechanism.
  6804. <ul>
  6805. <li>It is up to homeserver administrators if they want to issue long-lived access
  6806. tokens to clients not implementing refresh tokens.
  6807. <ul>
  6808. <li>For compatibility, it is likely that they should, at least until client support
  6809. is widespread.
  6810. <ul>
  6811. <li>Users with clients that support refresh tokens will still benefit from the
  6812. added security; it's not possible to downgrade a session to using long-lived
  6813. access tokens so this effectively gives users the choice.</li>
  6814. </ul>
  6815. </li>
  6816. <li>In a closed environment where all users use known clients, this may not be
  6817. an issue as the homeserver administrator can know if the clients have refresh
  6818. token support. In that case, the non-refreshable access token lifetime
  6819. may be set to a short duration so that a similar level of security is provided.</li>
  6820. </ul>
  6821. </li>
  6822. </ul>
  6823. </li>
  6824. </ul>
  6825. <h2 id="configuration-guide"><a class="header" href="#configuration-guide">Configuration Guide</a></h2>
  6826. <p>The following configuration options, in the <code>registration</code> section, are related:</p>
  6827. <ul>
  6828. <li><code>session_lifetime</code>: maximum length of a session, even if it's refreshed.
  6829. In other words, the client must log in again after this time period.
  6830. In most cases, this can be unset (infinite) or set to a long time (years or months).</li>
  6831. <li><code>refreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  6832. by clients supporting refresh tokens.
  6833. This should be short; a good value might be 5 minutes (<code>5m</code>).</li>
  6834. <li><code>nonrefreshable_access_token_lifetime</code>: lifetime of access tokens that are created
  6835. by clients which don't support refresh tokens.
  6836. Make this short if you want to effectively force use of refresh tokens.
  6837. Make this long if you don't want to inconvenience users of clients which don't
  6838. support refresh tokens (by forcing them to frequently re-authenticate using
  6839. login credentials).</li>
  6840. <li><code>refresh_token_lifetime</code>: lifetime of refresh tokens.
  6841. In other words, the client must refresh within this time period to maintain its session.
  6842. Unless you want to log inactive sessions out, it is often fine to use a long
  6843. value here or even leave it unset (infinite).
  6844. Beware that making it too short will inconvenience clients that do not connect
  6845. very often, including mobile clients and clients of infrequent users (by making
  6846. it more difficult for them to refresh in time, which may force them to need to
  6847. re-authenticate using login credentials).</li>
  6848. </ul>
  6849. <p><strong>Note:</strong> All four options above only apply when tokens are created (by logging in or refreshing).
  6850. Changes to these settings do not apply retroactively.</p>
  6851. <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>
  6852. <p>If you'd like to force sessions to be logged out upon inactivity, you can enable
  6853. refreshable access token expiry and refresh token expiry.</p>
  6854. <p>This works because a client must refresh at least once within a period of
  6855. <code>refresh_token_lifetime</code> in order to maintain valid credentials to access the
  6856. account.</p>
  6857. <p>(It's suggested that <code>refresh_token_lifetime</code> should be longer than
  6858. <code>refreshable_access_token_lifetime</code> and this section assumes that to be the case
  6859. for simplicity.)</p>
  6860. <p>Note: this will only affect sessions using refresh tokens. You may wish to
  6861. set a short <code>nonrefreshable_access_token_lifetime</code> to prevent this being bypassed
  6862. by clients that do not support refresh tokens.</p>
  6863. <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>
  6864. <p>It may be desirable to permit some short periods of inactivity, for example to
  6865. accommodate brief outages in client connectivity.</p>
  6866. <p>The following model aims to provide guidance for choosing <code>refresh_token_lifetime</code>
  6867. and <code>refreshable_access_token_lifetime</code> to satisfy requirements of the form:</p>
  6868. <ol>
  6869. <li>inactivity longer than <code>L</code> <strong>MUST</strong> cause the session to be logged out; and</li>
  6870. <li>inactivity shorter than <code>S</code> <strong>MUST NOT</strong> cause the session to be logged out.</li>
  6871. </ol>
  6872. <p>This model makes the weakest assumption that all active clients will refresh as
  6873. needed to maintain an active access token, but no sooner.
  6874. <em>In reality, clients may refresh more often than this model assumes, but the
  6875. above requirements will still hold.</em></p>
  6876. <p>To satisfy the above model,</p>
  6877. <ul>
  6878. <li><code>refresh_token_lifetime</code> should be set to <code>L</code>; and</li>
  6879. <li><code>refreshable_access_token_lifetime</code> should be set to <code>L - S</code>.</li>
  6880. </ul>
  6881. <div style="break-before: page; page-break-before: always;"></div><h1 id="overview-2"><a class="header" href="#overview-2">Overview</a></h1>
  6882. <p>A captcha can be enabled on your homeserver to help prevent bots from registering
  6883. accounts. Synapse currently uses Google's reCAPTCHA service which requires API keys
  6884. from Google.</p>
  6885. <h2 id="getting-api-keys"><a class="header" href="#getting-api-keys">Getting API keys</a></h2>
  6886. <ol>
  6887. <li>Create a new site at <a href="https://www.google.com/recaptcha/admin/create">https://www.google.com/recaptcha/admin/create</a></li>
  6888. <li>Set the label to anything you want</li>
  6889. <li>Set the type to reCAPTCHA v2 using the &quot;I'm not a robot&quot; Checkbox option.
  6890. This is the only type of captcha that works with Synapse.</li>
  6891. <li>Add the public hostname for your server, as set in <code>public_baseurl</code>
  6892. in <code>homeserver.yaml</code>, to the list of authorized domains. If you have not set
  6893. <code>public_baseurl</code>, use <code>server_name</code>.</li>
  6894. <li>Agree to the terms of service and submit.</li>
  6895. <li>Copy your site key and secret key and add them to your <code>homeserver.yaml</code>
  6896. configuration file
  6897. <pre><code class="language-yaml">recaptcha_public_key: YOUR_SITE_KEY
  6898. recaptcha_private_key: YOUR_SECRET_KEY
  6899. </code></pre>
  6900. </li>
  6901. <li>Enable the CAPTCHA for new registrations
  6902. <pre><code class="language-yaml">enable_registration_captcha: true
  6903. </code></pre>
  6904. </li>
  6905. <li>Go to the settings page for the CAPTCHA you just created</li>
  6906. <li>Uncheck the &quot;Verify the origin of reCAPTCHA solutions&quot; checkbox so that the
  6907. captcha can be displayed in any client. If you do not disable this option then you
  6908. must specify the domains of every client that is allowed to display the CAPTCHA.</li>
  6909. </ol>
  6910. <h2 id="configuring-ip-used-for-auth"><a class="header" href="#configuring-ip-used-for-auth">Configuring IP used for auth</a></h2>
  6911. <p>The reCAPTCHA API requires that the IP address of the user who solved the
  6912. CAPTCHA is sent. If the client is connecting through a proxy or load balancer,
  6913. it may be required to use the <code>X-Forwarded-For</code> (XFF) header instead of the origin
  6914. IP address. This can be configured using the <code>x_forwarded</code> directive in the
  6915. listeners section of the <code>homeserver.yaml</code> configuration file.</p>
  6916. <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>
  6917. <p>The registration of new application services depends on the homeserver used.
  6918. In synapse, you need to create a new configuration file for your AS and add it
  6919. to the list specified under the <code>app_service_config_files</code> config
  6920. option in your synapse config.</p>
  6921. <p>For example:</p>
  6922. <pre><code class="language-yaml">app_service_config_files:
  6923. - /home/matrix/.synapse/&lt;your-AS&gt;.yaml
  6924. </code></pre>
  6925. <p>The format of the AS configuration file is as follows:</p>
  6926. <pre><code class="language-yaml">url: &lt;base url of AS&gt;
  6927. as_token: &lt;token AS will add to requests to HS&gt;
  6928. hs_token: &lt;token HS will add to requests to AS&gt;
  6929. sender_localpart: &lt;localpart of AS user&gt;
  6930. namespaces:
  6931. users: # List of users we're interested in
  6932. - exclusive: &lt;bool&gt;
  6933. regex: &lt;regex&gt;
  6934. group_id: &lt;group&gt;
  6935. - ...
  6936. aliases: [] # List of aliases we're interested in
  6937. rooms: [] # List of room ids we're interested in
  6938. </code></pre>
  6939. <p><code>exclusive</code>: If enabled, only this application service is allowed to register users in its namespace(s).
  6940. <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>
  6941. <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>
  6942. <div style="break-before: page; page-break-before: always;"></div><h1 id="server-notices"><a class="header" href="#server-notices">Server Notices</a></h1>
  6943. <p>'Server Notices' are a new feature introduced in Synapse 0.30. They provide a
  6944. channel whereby server administrators can send messages to users on the server.</p>
  6945. <p>They are used as part of communication of the server polices (see
  6946. <a href="consent_tracking.html">Consent Tracking</a>), however the intention is that
  6947. they may also find a use for features such as &quot;Message of the day&quot;.</p>
  6948. <p>This is a feature specific to Synapse, but it uses standard Matrix
  6949. communication mechanisms, so should work with any Matrix client.</p>
  6950. <h2 id="user-experience"><a class="header" href="#user-experience">User experience</a></h2>
  6951. <p>When the user is first sent a server notice, they will get an invitation to a
  6952. room (typically called 'Server Notices', though this is configurable in
  6953. <code>homeserver.yaml</code>). They will be <strong>unable to reject</strong> this invitation -
  6954. attempts to do so will receive an error.</p>
  6955. <p>Once they accept the invitation, they will see the notice message in the room
  6956. history; it will appear to have come from the 'server notices user' (see
  6957. below).</p>
  6958. <p>The user is prevented from sending any messages in this room by the power
  6959. levels.</p>
  6960. <p>Having joined the room, the user can leave the room if they want. Subsequent
  6961. server notices will then cause a new room to be created.</p>
  6962. <h2 id="synapse-configuration"><a class="header" href="#synapse-configuration">Synapse configuration</a></h2>
  6963. <p>Server notices come from a specific user id on the server. Server
  6964. administrators are free to choose the user id - something like <code>server</code> is
  6965. suggested, meaning the notices will come from
  6966. <code>@server:&lt;your_server_name&gt;</code>. Once the Server Notices user is configured, that
  6967. user id becomes a special, privileged user, so administrators should ensure
  6968. that <strong>it is not already allocated</strong>.</p>
  6969. <p>In order to support server notices, it is necessary to add some configuration
  6970. to the <code>homeserver.yaml</code> file. In particular, you should add a <code>server_notices</code>
  6971. section, which should look like this:</p>
  6972. <pre><code class="language-yaml">server_notices:
  6973. system_mxid_localpart: server
  6974. system_mxid_display_name: &quot;Server Notices&quot;
  6975. system_mxid_avatar_url: &quot;mxc://server.com/oumMVlgDnLYFaPVkExemNVVZ&quot;
  6976. room_name: &quot;Server Notices&quot;
  6977. </code></pre>
  6978. <p>The only compulsory setting is <code>system_mxid_localpart</code>, which defines the user
  6979. id of the Server Notices user, as above. <code>room_name</code> defines the name of the
  6980. room which will be created.</p>
  6981. <p><code>system_mxid_display_name</code> and <code>system_mxid_avatar_url</code> can be used to set the
  6982. displayname and avatar of the Server Notices user.</p>
  6983. <h2 id="sending-notices"><a class="header" href="#sending-notices">Sending notices</a></h2>
  6984. <p>To send server notices to users you can use the
  6985. <a href="admin_api/server_notices.html">admin_api</a>.</p>
  6986. <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>
  6987. <p>Synapse 0.30 introduces support for tracking whether users have agreed to the
  6988. terms and conditions set by the administrator of a server - and blocking access
  6989. to the server until they have.</p>
  6990. <p>There are several parts to this functionality; each requires some specific
  6991. configuration in <code>homeserver.yaml</code> to be enabled.</p>
  6992. <p>Note that various parts of the configuation and this document refer to the
  6993. &quot;privacy policy&quot;: agreement with a privacy policy is one particular use of this
  6994. feature, but of course adminstrators can specify other terms and conditions
  6995. unrelated to &quot;privacy&quot; per se.</p>
  6996. <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>
  6997. <p>Synapse can be configured to serve the user a simple policy form with an
  6998. &quot;accept&quot; button. Clicking &quot;Accept&quot; records the user's acceptance in the
  6999. database and shows a success page.</p>
  7000. <p>To enable this, first create templates for the policy and success pages.
  7001. These should be stored on the local filesystem.</p>
  7002. <p>These templates use the <a href="http://jinja.pocoo.org">Jinja2</a> templating language,
  7003. and <a href="https://github.com/matrix-org/synapse/tree/develop/docs/privacy_policy_templates/">docs/privacy_policy_templates</a>
  7004. gives examples of the sort of thing that can be done.</p>
  7005. <p>Note that the templates must be stored under a name giving the language of the
  7006. template - currently this must always be <code>en</code> (for &quot;English&quot;);
  7007. internationalisation support is intended for the future.</p>
  7008. <p>The template for the policy itself should be versioned and named according to
  7009. the version: for example <code>1.0.html</code>. The version of the policy which the user
  7010. has agreed to is stored in the database.</p>
  7011. <p>Once the templates are in place, make the following changes to <code>homeserver.yaml</code>:</p>
  7012. <ol>
  7013. <li>
  7014. <p>Add a <code>user_consent</code> section, which should look like:</p>
  7015. <pre><code class="language-yaml">user_consent:
  7016. template_dir: privacy_policy_templates
  7017. version: 1.0
  7018. </code></pre>
  7019. <p><code>template_dir</code> points to the directory containing the policy
  7020. templates. <code>version</code> defines the version of the policy which will be served
  7021. to the user. In the example above, Synapse will serve
  7022. <code>privacy_policy_templates/en/1.0.html</code>.</p>
  7023. </li>
  7024. <li>
  7025. <p>Add a <code>form_secret</code> setting at the top level:</p>
  7026. <pre><code class="language-yaml">form_secret: &quot;&lt;unique secret&gt;&quot;
  7027. </code></pre>
  7028. <p>This should be set to an arbitrary secret string (try <code>pwgen -y 30</code> to
  7029. generate suitable secrets).</p>
  7030. <p>More on what this is used for below.</p>
  7031. </li>
  7032. <li>
  7033. <p>Add <code>consent</code> wherever the <code>client</code> resource is currently enabled in the
  7034. <code>listeners</code> configuration. For example:</p>
  7035. <pre><code class="language-yaml">listeners:
  7036. - port: 8008
  7037. resources:
  7038. - names:
  7039. - client
  7040. - consent
  7041. </code></pre>
  7042. </li>
  7043. </ol>
  7044. <p>Finally, ensure that <code>jinja2</code> is installed. If you are using a virtualenv, this
  7045. should be a matter of <code>pip install Jinja2</code>. On debian, try <code>apt-get install python-jinja2</code>.</p>
  7046. <p>Once this is complete, and the server has been restarted, try visiting
  7047. <code>https://&lt;server&gt;/_matrix/consent</code>. If correctly configured, this should give
  7048. an error &quot;Missing string query parameter 'u'&quot;. It is now possible to manually
  7049. construct URIs where users can give their consent.</p>
  7050. <h3 id="enabling-consent-tracking-at-registration"><a class="header" href="#enabling-consent-tracking-at-registration">Enabling consent tracking at registration</a></h3>
  7051. <ol>
  7052. <li>
  7053. <p>Add the following to your configuration:</p>
  7054. <pre><code class="language-yaml">user_consent:
  7055. require_at_registration: true
  7056. policy_name: &quot;Privacy Policy&quot; # or whatever you'd like to call the policy
  7057. </code></pre>
  7058. </li>
  7059. <li>
  7060. <p>In your consent templates, make use of the <code>public_version</code> variable to
  7061. see if an unauthenticated user is viewing the page. This is typically
  7062. wrapped around the form that would be used to actually agree to the document:</p>
  7063. <pre><code class="language-html">{% if not public_version %}
  7064. &lt;!-- The variables used here are only provided when the 'u' param is given to the homeserver --&gt;
  7065. &lt;form method=&quot;post&quot; action=&quot;consent&quot;&gt;
  7066. &lt;input type=&quot;hidden&quot; name=&quot;v&quot; value=&quot;{{version}}&quot;/&gt;
  7067. &lt;input type=&quot;hidden&quot; name=&quot;u&quot; value=&quot;{{user}}&quot;/&gt;
  7068. &lt;input type=&quot;hidden&quot; name=&quot;h&quot; value=&quot;{{userhmac}}&quot;/&gt;
  7069. &lt;input type=&quot;submit&quot; value=&quot;Sure thing!&quot;/&gt;
  7070. &lt;/form&gt;
  7071. {% endif %}
  7072. </code></pre>
  7073. </li>
  7074. <li>
  7075. <p>Restart Synapse to apply the changes.</p>
  7076. </li>
  7077. </ol>
  7078. <p>Visiting <code>https://&lt;server&gt;/_matrix/consent</code> should now give you a view of the privacy
  7079. document. This is what users will be able to see when registering for accounts.</p>
  7080. <h3 id="constructing-the-consent-uri"><a class="header" href="#constructing-the-consent-uri">Constructing the consent URI</a></h3>
  7081. <p>It may be useful to manually construct the &quot;consent URI&quot; for a given user - for
  7082. instance, in order to send them an email asking them to consent. To do this,
  7083. take the base <code>https://&lt;server&gt;/_matrix/consent</code> URL and add the following
  7084. query parameters:</p>
  7085. <ul>
  7086. <li>
  7087. <p><code>u</code>: the user id of the user. This can either be a full MXID
  7088. (<code>@user:server.com</code>) or just the localpart (<code>user</code>).</p>
  7089. </li>
  7090. <li>
  7091. <p><code>h</code>: hex-encoded HMAC-SHA256 of <code>u</code> using the <code>form_secret</code> as a key. It is
  7092. possible to calculate this on the commandline with something like:</p>
  7093. <pre><code class="language-bash">echo -n '&lt;user&gt;' | openssl sha256 -hmac '&lt;form_secret&gt;'
  7094. </code></pre>
  7095. <p>This should result in a URI which looks something like:
  7096. <code>https://&lt;server&gt;/_matrix/consent?u=&lt;user&gt;&amp;h=68a152465a4d...</code>.</p>
  7097. </li>
  7098. </ul>
  7099. <p>Note that not providing a <code>u</code> parameter will be interpreted as wanting to view
  7100. the document from an unauthenticated perspective, such as prior to registration.
  7101. Therefore, the <code>h</code> parameter is not required in this scenario. To enable this
  7102. behaviour, set <code>require_at_registration</code> to <code>true</code> in your <code>user_consent</code> config.</p>
  7103. <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>
  7104. <p>It is possible to configure Synapse to send a <a href="server_notices.html">server
  7105. notice</a> to anybody who has not yet agreed to the current
  7106. version of the policy. To do so:</p>
  7107. <ul>
  7108. <li>
  7109. <p>ensure that the consent resource is configured, as in the previous section</p>
  7110. </li>
  7111. <li>
  7112. <p>ensure that server notices are configured, as in <a href="server_notices.html">the server notice documentation</a>.</p>
  7113. </li>
  7114. <li>
  7115. <p>Add <code>server_notice_content</code> under <code>user_consent</code> in <code>homeserver.yaml</code>. For
  7116. example:</p>
  7117. <pre><code class="language-yaml">user_consent:
  7118. server_notice_content:
  7119. msgtype: m.text
  7120. body: &gt;-
  7121. Please give your consent to the privacy policy at %(consent_uri)s.
  7122. </code></pre>
  7123. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  7124. consent uri for that user.</p>
  7125. </li>
  7126. <li>
  7127. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  7128. URI that clients use to connect to the server. (It is used to construct
  7129. <code>consent_uri</code> in the server notice.)</p>
  7130. </li>
  7131. </ul>
  7132. <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>
  7133. <p>Synapse can be configured to block any attempts to join rooms or send messages
  7134. until the user has given their agreement to the policy. (Joining the server
  7135. notices room is exempted from this).</p>
  7136. <p>To enable this, add <code>block_events_error</code> under <code>user_consent</code>. For example:</p>
  7137. <pre><code class="language-yaml">user_consent:
  7138. block_events_error: &gt;-
  7139. You can't send any messages until you consent to the privacy policy at
  7140. %(consent_uri)s.
  7141. </code></pre>
  7142. <p>Synapse automatically replaces the placeholder <code>%(consent_uri)s</code> with the
  7143. consent uri for that user.</p>
  7144. <p>ensure that <code>public_baseurl</code> is set in <code>homeserver.yaml</code>, and gives the base
  7145. URI that clients use to connect to the server. (It is used to construct
  7146. <code>consent_uri</code> in the error.)</p>
  7147. <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>
  7148. <p>The <code>GET /_matrix/media/r0/preview_url</code> endpoint provides a generic preview API
  7149. for URLs which outputs <a href="https://ogp.me/">Open Graph</a> responses (with some Matrix
  7150. specific additions).</p>
  7151. <p>This does have trade-offs compared to other designs:</p>
  7152. <ul>
  7153. <li>Pros:
  7154. <ul>
  7155. <li>Simple and flexible; can be used by any clients at any point</li>
  7156. </ul>
  7157. </li>
  7158. <li>Cons:
  7159. <ul>
  7160. <li>If each homeserver provides one of these independently, all the HSes in a
  7161. room may needlessly DoS the target URI</li>
  7162. <li>The URL metadata must be stored somewhere, rather than just using Matrix
  7163. itself to store the media.</li>
  7164. <li>Matrix cannot be used to distribute the metadata between homeservers.</li>
  7165. </ul>
  7166. </li>
  7167. </ul>
  7168. <p>When Synapse is asked to preview a URL it does the following:</p>
  7169. <ol>
  7170. <li>Checks against a URL blacklist (defined as <code>url_preview_url_blacklist</code> in the
  7171. config).</li>
  7172. <li>Checks the in-memory cache by URLs and returns the result if it exists. (This
  7173. is also used to de-duplicate processing of multiple in-flight requests at once.)</li>
  7174. <li>Kicks off a background process to generate a preview:
  7175. <ol>
  7176. <li>Checks the database cache by URL and timestamp and returns the result if it
  7177. has not expired and was successful (a 2xx return code).</li>
  7178. <li>Checks if the URL matches an <a href="https://oembed.com/">oEmbed</a> pattern. If it
  7179. does, update the URL to download.</li>
  7180. <li>Downloads the URL and stores it into a file via the media storage provider
  7181. and saves the local media metadata.</li>
  7182. <li>If the media is an image:
  7183. <ol>
  7184. <li>Generates thumbnails.</li>
  7185. <li>Generates an Open Graph response based on image properties.</li>
  7186. </ol>
  7187. </li>
  7188. <li>If the media is HTML:
  7189. <ol>
  7190. <li>Decodes the HTML via the stored file.</li>
  7191. <li>Generates an Open Graph response from the HTML.</li>
  7192. <li>If a JSON oEmbed URL was found in the HTML via autodiscovery:
  7193. <ol>
  7194. <li>Downloads the URL and stores it into a file via the media storage provider
  7195. and saves the local media metadata.</li>
  7196. <li>Convert the oEmbed response to an Open Graph response.</li>
  7197. <li>Override any Open Graph data from the HTML with data from oEmbed.</li>
  7198. </ol>
  7199. </li>
  7200. <li>If an image exists in the Open Graph response:
  7201. <ol>
  7202. <li>Downloads the URL and stores it into a file via the media storage
  7203. provider and saves the local media metadata.</li>
  7204. <li>Generates thumbnails.</li>
  7205. <li>Updates the Open Graph response based on image properties.</li>
  7206. </ol>
  7207. </li>
  7208. </ol>
  7209. </li>
  7210. <li>If the media is JSON and an oEmbed URL was found:
  7211. <ol>
  7212. <li>Convert the oEmbed response to an Open Graph response.</li>
  7213. <li>If a thumbnail or image is in the oEmbed response:
  7214. <ol>
  7215. <li>Downloads the URL and stores it into a file via the media storage
  7216. provider and saves the local media metadata.</li>
  7217. <li>Generates thumbnails.</li>
  7218. <li>Updates the Open Graph response based on image properties.</li>
  7219. </ol>
  7220. </li>
  7221. </ol>
  7222. </li>
  7223. <li>Stores the result in the database cache.</li>
  7224. </ol>
  7225. </li>
  7226. <li>Returns the result.</li>
  7227. </ol>
  7228. <p>The in-memory cache expires after 1 hour.</p>
  7229. <p>Expired entries in the database cache (and their associated media files) are
  7230. deleted every 10 seconds. The default expiration time is 1 hour from download.</p>
  7231. <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>
  7232. <p>The user directory is currently maintained based on the 'visible' users
  7233. on this particular server - i.e. ones which your account shares a room with, or
  7234. who are present in a publicly viewable room present on the server.</p>
  7235. <p>The directory info is stored in various tables, which can (typically after
  7236. DB corruption) get stale or out of sync. If this happens, for now the
  7237. solution to fix it is to use the <a href="usage/administration/admin_api/background_updates.html#run">admin API</a>
  7238. and execute the job <code>regenerate_directory</code>. This should then start a background task to
  7239. flush the current tables and regenerate the directory.</p>
  7240. <h2 id="data-model"><a class="header" href="#data-model">Data model</a></h2>
  7241. <p>There are five relevant tables that collectively form the &quot;user directory&quot;.
  7242. Three of them track a master list of all the users we could search for.
  7243. The last two (collectively called the &quot;search tables&quot;) track who can
  7244. see who.</p>
  7245. <p>From all of these tables we exclude three types of local user:</p>
  7246. <ul>
  7247. <li>support users</li>
  7248. <li>appservice users</li>
  7249. <li>deactivated users</li>
  7250. </ul>
  7251. <ul>
  7252. <li>
  7253. <p><code>user_directory</code>. This contains the user_id, display name and avatar we'll
  7254. return when you search the directory.</p>
  7255. <ul>
  7256. <li>Because there's only one directory entry per user, it's important that we only
  7257. ever put publicly visible names here. Otherwise we might leak a private
  7258. nickname or avatar used in a private room.</li>
  7259. <li>Indexed on rooms. Indexed on users.</li>
  7260. </ul>
  7261. </li>
  7262. <li>
  7263. <p><code>user_directory_search</code>. To be joined to <code>user_directory</code>. It contains an extra
  7264. column that enables full text search based on user ids and display names.
  7265. Different schemas for SQLite and Postgres with different code paths to match.</p>
  7266. <ul>
  7267. <li>Indexed on the full text search data. Indexed on users.</li>
  7268. </ul>
  7269. </li>
  7270. <li>
  7271. <p><code>user_directory_stream_pos</code>. When the initial background update to populate
  7272. the directory is complete, we record a stream position here. This indicates
  7273. that synapse should now listen for room changes and incrementally update
  7274. the directory where necessary.</p>
  7275. </li>
  7276. <li>
  7277. <p><code>users_in_public_rooms</code>. Contains associations between users and the public rooms they're in.
  7278. Used to determine which users are in public rooms and should be publicly visible in the directory.</p>
  7279. </li>
  7280. <li>
  7281. <p><code>users_who_share_private_rooms</code>. Rows are triples <code>(L, M, room id)</code> where <code>L</code>
  7282. is a local user and <code>M</code> is a local or remote user. <code>L</code> and <code>M</code> should be
  7283. different, but this isn't enforced by a constraint.</p>
  7284. </li>
  7285. </ul>
  7286. <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>
  7287. <p>Synapse admins can enable support for message retention policies on
  7288. their homeserver. Message retention policies exist at a room level,
  7289. follow the semantics described in
  7290. <a href="https://github.com/matrix-org/matrix-doc/blob/matthew/msc1763/proposals/1763-configurable-retention-periods.md">MSC1763</a>,
  7291. and allow server and room admins to configure how long messages should
  7292. be kept in a homeserver's database before being purged from it.
  7293. <strong>Please note that, as this feature isn't part of the Matrix
  7294. specification yet, this implementation is to be considered as
  7295. experimental.</strong> </p>
  7296. <p>A message retention policy is mainly defined by its <code>max_lifetime</code>
  7297. parameter, which defines how long a message can be kept around after
  7298. it was sent to the room. If a room doesn't have a message retention
  7299. policy, and there's no default one for a given server, then no message
  7300. sent in that room is ever purged on that server.</p>
  7301. <p>MSC1763 also specifies semantics for a <code>min_lifetime</code> parameter which
  7302. defines the amount of time after which an event <em>can</em> get purged (after
  7303. it was sent to the room), but Synapse doesn't currently support it
  7304. beyond registering it.</p>
  7305. <p>Both <code>max_lifetime</code> and <code>min_lifetime</code> are optional parameters.</p>
  7306. <p>Note that message retention policies don't apply to state events.</p>
  7307. <p>Once an event reaches its expiry date (defined as the time it was sent
  7308. plus the value for <code>max_lifetime</code> in the room), two things happen:</p>
  7309. <ul>
  7310. <li>Synapse stops serving the event to clients via any endpoint.</li>
  7311. <li>The message gets picked up by the next purge job (see the &quot;Purge jobs&quot;
  7312. section) and is removed from Synapse's database.</li>
  7313. </ul>
  7314. <p>Since purge jobs don't run continuously, this means that an event might
  7315. stay in a server's database for longer than the value for <code>max_lifetime</code>
  7316. in the room would allow, though hidden from clients.</p>
  7317. <p>Similarly, if a server (with support for message retention policies
  7318. enabled) receives from another server an event that should have been
  7319. purged according to its room's policy, then the receiving server will
  7320. process and store that event until it's picked up by the next purge job,
  7321. though it will always hide it from clients.</p>
  7322. <p>Synapse requires at least one message in each room, so it will never
  7323. delete the last message in a room. It will, however, hide it from
  7324. clients.</p>
  7325. <h2 id="server-configuration"><a class="header" href="#server-configuration">Server configuration</a></h2>
  7326. <p>Support for this feature can be enabled and configured in the
  7327. <code>retention</code> section of the Synapse configuration file (see the
  7328. <a href="https://github.com/matrix-org/synapse/blob/v1.36.0/docs/sample_config.yaml#L451-L518">sample file</a>).</p>
  7329. <p>To enable support for message retention policies, set the setting
  7330. <code>enabled</code> in this section to <code>true</code>.</p>
  7331. <h3 id="default-policy"><a class="header" href="#default-policy">Default policy</a></h3>
  7332. <p>A default message retention policy is a policy defined in Synapse's
  7333. configuration that is used by Synapse for every room that doesn't have a
  7334. message retention policy configured in its state. This allows server
  7335. admins to ensure that messages are never kept indefinitely in a server's
  7336. database. </p>
  7337. <p>A default policy can be defined as such, in the <code>retention</code> section of
  7338. the configuration file:</p>
  7339. <pre><code class="language-yaml">default_policy:
  7340. min_lifetime: 1d
  7341. max_lifetime: 1y
  7342. </code></pre>
  7343. <p>Here, <code>min_lifetime</code> and <code>max_lifetime</code> have the same meaning and level
  7344. of support as previously described. They can be expressed either as a
  7345. duration (using the units <code>s</code> (seconds), <code>m</code> (minutes), <code>h</code> (hours),
  7346. <code>d</code> (days), <code>w</code> (weeks) and <code>y</code> (years)) or as a number of milliseconds.</p>
  7347. <h3 id="purge-jobs"><a class="header" href="#purge-jobs">Purge jobs</a></h3>
  7348. <p>Purge jobs are the jobs that Synapse runs in the background to purge
  7349. expired events from the database. They are only run if support for
  7350. message retention policies is enabled in the server's configuration. If
  7351. no configuration for purge jobs is configured by the server admin,
  7352. Synapse will use a default configuration, which is described in the
  7353. <a href="https://github.com/matrix-org/synapse/blob/v1.36.0/docs/sample_config.yaml#L451-L518">sample configuration file</a>.</p>
  7354. <p>Some server admins might want a finer control on when events are removed
  7355. depending on an event's room's policy. This can be done by setting the
  7356. <code>purge_jobs</code> sub-section in the <code>retention</code> section of the configuration
  7357. file. An example of such configuration could be:</p>
  7358. <pre><code class="language-yaml">purge_jobs:
  7359. - longest_max_lifetime: 3d
  7360. interval: 12h
  7361. - shortest_max_lifetime: 3d
  7362. longest_max_lifetime: 1w
  7363. interval: 1d
  7364. - shortest_max_lifetime: 1w
  7365. interval: 2d
  7366. </code></pre>
  7367. <p>In this example, we define three jobs:</p>
  7368. <ul>
  7369. <li>one that runs twice a day (every 12 hours) and purges events in rooms
  7370. which policy's <code>max_lifetime</code> is lower or equal to 3 days.</li>
  7371. <li>one that runs once a day and purges events in rooms which policy's
  7372. <code>max_lifetime</code> is between 3 days and a week.</li>
  7373. <li>one that runs once every 2 days and purges events in rooms which
  7374. policy's <code>max_lifetime</code> is greater than a week.</li>
  7375. </ul>
  7376. <p>Note that this example is tailored to show different configurations and
  7377. features slightly more jobs than it's probably necessary (in practice, a
  7378. server admin would probably consider it better to replace the two last
  7379. jobs with one that runs once a day and handles rooms which which
  7380. policy's <code>max_lifetime</code> is greater than 3 days).</p>
  7381. <p>Keep in mind, when configuring these jobs, that a purge job can become
  7382. quite heavy on the server if it targets many rooms, therefore prefer
  7383. having jobs with a low interval that target a limited set of rooms. Also
  7384. make sure to include a job with no minimum and one with no maximum to
  7385. make sure your configuration handles every policy.</p>
  7386. <p>As previously mentioned in this documentation, while a purge job that
  7387. runs e.g. every day means that an expired event might stay in the
  7388. database for up to a day after its expiry, Synapse hides expired events
  7389. from clients as soon as they expire, so the event is not visible to
  7390. local users between its expiry date and the moment it gets purged from
  7391. the server's database.</p>
  7392. <h3 id="lifetime-limits"><a class="header" href="#lifetime-limits">Lifetime limits</a></h3>
  7393. <p>Server admins can set limits on the values of <code>max_lifetime</code> to use when
  7394. purging old events in a room. These limits can be defined as such in the
  7395. <code>retention</code> section of the configuration file:</p>
  7396. <pre><code class="language-yaml">allowed_lifetime_min: 1d
  7397. allowed_lifetime_max: 1y
  7398. </code></pre>
  7399. <p>The limits are considered when running purge jobs. If necessary, the
  7400. effective value of <code>max_lifetime</code> will be brought between
  7401. <code>allowed_lifetime_min</code> and <code>allowed_lifetime_max</code> (inclusive).
  7402. This means that, if the value of <code>max_lifetime</code> defined in the room's state
  7403. is lower than <code>allowed_lifetime_min</code>, the value of <code>allowed_lifetime_min</code>
  7404. will be used instead. Likewise, if the value of <code>max_lifetime</code> is higher
  7405. than <code>allowed_lifetime_max</code>, the value of <code>allowed_lifetime_max</code> will be
  7406. used instead.</p>
  7407. <p>In the example above, we ensure Synapse never deletes events that are less
  7408. than one day old, and that it always deletes events that are over a year
  7409. old.</p>
  7410. <p>If a default policy is set, and its <code>max_lifetime</code> value is lower than
  7411. <code>allowed_lifetime_min</code> or higher than <code>allowed_lifetime_max</code>, the same
  7412. process applies.</p>
  7413. <p>Both parameters are optional; if one is omitted Synapse won't use it to
  7414. adjust the effective value of <code>max_lifetime</code>.</p>
  7415. <p>Like other settings in this section, these parameters can be expressed
  7416. either as a duration or as a number of milliseconds.</p>
  7417. <h2 id="room-configuration"><a class="header" href="#room-configuration">Room configuration</a></h2>
  7418. <p>To configure a room's message retention policy, a room's admin or
  7419. moderator needs to send a state event in that room with the type
  7420. <code>m.room.retention</code> and the following content:</p>
  7421. <pre><code class="language-json">{
  7422. &quot;max_lifetime&quot;: ...
  7423. }
  7424. </code></pre>
  7425. <p>In this event's content, the <code>max_lifetime</code> parameter has the same
  7426. meaning as previously described, and needs to be expressed in
  7427. milliseconds. The event's content can also include a <code>min_lifetime</code>
  7428. parameter, which has the same meaning and limited support as previously
  7429. described.</p>
  7430. <p>Note that over every server in the room, only the ones with support for
  7431. message retention policies will actually remove expired events. This
  7432. support is currently not enabled by default in Synapse.</p>
  7433. <h2 id="note-on-reclaiming-disk-space"><a class="header" href="#note-on-reclaiming-disk-space">Note on reclaiming disk space</a></h2>
  7434. <p>While purge jobs actually delete data from the database, the disk space
  7435. used by the database might not decrease immediately on the database's
  7436. host. However, even though the database engine won't free up the disk
  7437. space, it will start writing new data into where the purged data was.</p>
  7438. <p>If you want to reclaim the freed disk space anyway and return it to the
  7439. operating system, the server admin needs to run <code>VACUUM FULL;</code> (or
  7440. <code>VACUUM;</code> for SQLite databases) on Synapse's database (see the related
  7441. <a href="https://www.postgresql.org/docs/current/sql-vacuum.html">PostgreSQL documentation</a>).</p>
  7442. <div style="break-before: page; page-break-before: always;"></div><h1 id="modules"><a class="header" href="#modules">Modules</a></h1>
  7443. <p>Synapse supports extending its functionality by configuring external modules.</p>
  7444. <p><strong>Note</strong>: When using third-party modules, you effectively allow someone else to run
  7445. custom code on your Synapse homeserver. Server admins are encouraged to verify the
  7446. provenance of the modules they use on their homeserver and make sure the modules aren't
  7447. running malicious code on their instance.</p>
  7448. <h2 id="using-modules"><a class="header" href="#using-modules">Using modules</a></h2>
  7449. <p>To use a module on Synapse, add it to the <code>modules</code> section of the configuration file:</p>
  7450. <pre><code class="language-yaml">modules:
  7451. - module: my_super_module.MySuperClass
  7452. config:
  7453. do_thing: true
  7454. - module: my_other_super_module.SomeClass
  7455. config: {}
  7456. </code></pre>
  7457. <p>Each module is defined by a path to a Python class as well as a configuration. This
  7458. information for a given module should be available in the module's own documentation.</p>
  7459. <h2 id="using-multiple-modules"><a class="header" href="#using-multiple-modules">Using multiple modules</a></h2>
  7460. <p>The order in which modules are listed in this section is important. When processing an
  7461. action that can be handled by several modules, Synapse will always prioritise the module
  7462. that appears first (i.e. is the highest in the list). This means:</p>
  7463. <ul>
  7464. <li>If several modules register the same callback, the callback registered by the module
  7465. that appears first is used.</li>
  7466. <li>If several modules try to register a handler for the same HTTP path, only the handler
  7467. registered by the module that appears first is used. Handlers registered by the other
  7468. module(s) are ignored and Synapse will log a warning message about them.</li>
  7469. </ul>
  7470. <p>Note that Synapse doesn't allow multiple modules implementing authentication checkers via
  7471. the password auth provider feature for the same login type with different fields. If this
  7472. happens, Synapse will refuse to start.</p>
  7473. <h2 id="current-status"><a class="header" href="#current-status">Current status</a></h2>
  7474. <p>We are currently in the process of migrating module interfaces to this system. While some
  7475. interfaces might be compatible with it, others still require configuring modules in
  7476. another part of Synapse's configuration file.</p>
  7477. <p>Currently, only the following pre-existing interfaces are compatible with this new system:</p>
  7478. <ul>
  7479. <li>spam checker</li>
  7480. <li>third-party rules</li>
  7481. <li>presence router</li>
  7482. <li>password auth providers</li>
  7483. </ul>
  7484. <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>
  7485. <p>A module is a Python class that uses Synapse's module API to interact with the
  7486. homeserver. It can register callbacks that Synapse will call on specific operations, as
  7487. well as web resources to attach to Synapse's web server.</p>
  7488. <p>When instantiated, a module is given its parsed configuration as well as an instance of
  7489. the <code>synapse.module_api.ModuleApi</code> class. The configuration is a dictionary, and is
  7490. either the output of the module's <code>parse_config</code> static method (see below), or the
  7491. configuration associated with the module in Synapse's configuration file.</p>
  7492. <p>See the documentation for the <code>ModuleApi</code> class
  7493. <a href="https://github.com/matrix-org/synapse/blob/master/synapse/module_api/__init__.py">here</a>.</p>
  7494. <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>
  7495. <p>If Synapse is running with other modules configured, the order each module appears in
  7496. within the <code>modules</code> section of the Synapse configuration file might restrict what it can
  7497. or cannot register. See <a href="modules/index.html#using-multiple-modules">this section</a> for more
  7498. information.</p>
  7499. <p>On top of the rules listed in the link above, if a callback returns a value that should
  7500. cause the current operation to fail (e.g. if a callback checking an event returns with a
  7501. value that should cause the event to be denied), Synapse will fail the operation and
  7502. ignore any subsequent callbacks that should have been run after this one.</p>
  7503. <p>The documentation for each callback mentions how Synapse behaves when
  7504. multiple modules implement it.</p>
  7505. <h2 id="handling-the-modules-configuration"><a class="header" href="#handling-the-modules-configuration">Handling the module's configuration</a></h2>
  7506. <p>A module can implement the following static method:</p>
  7507. <pre><code class="language-python">@staticmethod
  7508. def parse_config(config: dict) -&gt; dict
  7509. </code></pre>
  7510. <p>This method is given a dictionary resulting from parsing the YAML configuration for the
  7511. module. It may modify it (for example by parsing durations expressed as strings (e.g.
  7512. &quot;5d&quot;) into milliseconds, etc.), and return the modified dictionary. It may also verify
  7513. that the configuration is correct, and raise an instance of
  7514. <code>synapse.module_api.errors.ConfigError</code> if not.</p>
  7515. <h2 id="registering-a-web-resource"><a class="header" href="#registering-a-web-resource">Registering a web resource</a></h2>
  7516. <p>Modules can register web resources onto Synapse's web server using the following module
  7517. API method:</p>
  7518. <pre><code class="language-python">def ModuleApi.register_web_resource(path: str, resource: IResource) -&gt; None
  7519. </code></pre>
  7520. <p>The path is the full absolute path to register the resource at. For example, if you
  7521. register a resource for the path <code>/_synapse/client/my_super_module/say_hello</code>, Synapse
  7522. will serve it at <code>http(s)://[HS_URL]/_synapse/client/my_super_module/say_hello</code>. Note
  7523. that Synapse does not allow registering resources for several sub-paths in the <code>/_matrix</code>
  7524. namespace (such as anything under <code>/_matrix/client</code> for example). It is strongly
  7525. recommended that modules register their web resources under the <code>/_synapse/client</code>
  7526. namespace.</p>
  7527. <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>
  7528. interface (such as <a href="https://twistedmatrix.com/documents/current/api/twisted.web.resource.Resource.html">Resource</a>).</p>
  7529. <p>Only one resource can be registered for a given path. If several modules attempt to
  7530. register a resource for the same path, the module that appears first in Synapse's
  7531. configuration file takes priority.</p>
  7532. <p>Modules <strong>must</strong> register their web resources in their <code>__init__</code> method.</p>
  7533. <h2 id="registering-a-callback"><a class="header" href="#registering-a-callback">Registering a callback</a></h2>
  7534. <p>Modules can use Synapse's module API to register callbacks. Callbacks are functions that
  7535. Synapse will call when performing specific actions. Callbacks must be asynchronous (unless
  7536. specified otherwise), and are split in categories. A single module may implement callbacks
  7537. from multiple categories, and is under no obligation to implement all callbacks from the
  7538. categories it registers callbacks for.</p>
  7539. <p>Modules can register callbacks using one of the module API's <code>register_[...]_callbacks</code>
  7540. methods. The callback functions are passed to these methods as keyword arguments, with
  7541. the callback name as the argument name and the function as its value. A
  7542. <code>register_[...]_callbacks</code> method exists for each category.</p>
  7543. <p>Callbacks for each category can be found on their respective page of the
  7544. <a href="https://matrix-org.github.io/synapse">Synapse documentation website</a>.</p>
  7545. <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>
  7546. <p>Spam checker callbacks allow module developers to implement spam mitigation actions for
  7547. Synapse instances. Spam checker callbacks can be registered using the module API's
  7548. <code>register_spam_checker_callbacks</code> method.</p>
  7549. <h2 id="callbacks"><a class="header" href="#callbacks">Callbacks</a></h2>
  7550. <p>The available spam checker callbacks are:</p>
  7551. <h3 id="check_event_for_spam"><a class="header" href="#check_event_for_spam"><code>check_event_for_spam</code></a></h3>
  7552. <p><em>First introduced in Synapse v1.37.0</em></p>
  7553. <pre><code class="language-python">async def check_event_for_spam(event: &quot;synapse.events.EventBase&quot;) -&gt; Union[bool, str]
  7554. </code></pre>
  7555. <p>Called when receiving an event from a client or via federation. The module can return
  7556. either a <code>bool</code> to indicate whether the event must be rejected because of spam, or a <code>str</code>
  7557. to indicate the event must be rejected because of spam and to give a rejection reason to
  7558. forward to clients.</p>
  7559. <p>If multiple modules implement this callback, they will be considered in order. If a
  7560. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  7561. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  7562. any of the subsequent implementations of this callback.</p>
  7563. <h3 id="user_may_join_room"><a class="header" href="#user_may_join_room"><code>user_may_join_room</code></a></h3>
  7564. <p><em>First introduced in Synapse v1.37.0</em></p>
  7565. <pre><code class="language-python">async def user_may_join_room(user: str, room: str, is_invited: bool) -&gt; bool
  7566. </code></pre>
  7567. <p>Called when a user is trying to join a room. The module must return a <code>bool</code> to indicate
  7568. whether the user can join the room. The user is represented by their Matrix user ID (e.g.
  7569. <code>@alice:example.com</code>) and the room is represented by its Matrix ID (e.g.
  7570. <code>!room:example.com</code>). The module is also given a boolean to indicate whether the user
  7571. currently has a pending invite in the room.</p>
  7572. <p>This callback isn't called if the join is performed by a server administrator, or in the
  7573. context of a room creation.</p>
  7574. <p>If multiple modules implement this callback, they will be considered in order. If a
  7575. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7576. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7577. any of the subsequent implementations of this callback.</p>
  7578. <h3 id="user_may_invite"><a class="header" href="#user_may_invite"><code>user_may_invite</code></a></h3>
  7579. <p><em>First introduced in Synapse v1.37.0</em></p>
  7580. <pre><code class="language-python">async def user_may_invite(inviter: str, invitee: str, room_id: str) -&gt; bool
  7581. </code></pre>
  7582. <p>Called when processing an invitation. The module must return a <code>bool</code> indicating whether
  7583. the inviter can invite the invitee to the given room. Both inviter and invitee are
  7584. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  7585. <p>If multiple modules implement this callback, they will be considered in order. If a
  7586. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7587. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7588. any of the subsequent implementations of this callback.</p>
  7589. <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>
  7590. <p><em>First introduced in Synapse v1.45.0</em></p>
  7591. <pre><code class="language-python">async def user_may_send_3pid_invite(
  7592. inviter: str,
  7593. medium: str,
  7594. address: str,
  7595. room_id: str,
  7596. ) -&gt; bool
  7597. </code></pre>
  7598. <p>Called when processing an invitation using a third-party identifier (also called a 3PID,
  7599. e.g. an email address or a phone number). The module must return a <code>bool</code> indicating
  7600. whether the inviter can invite the invitee to the given room.</p>
  7601. <p>The inviter is represented by their Matrix user ID (e.g. <code>@alice:example.com</code>), and the
  7602. invitee is represented by its medium (e.g. &quot;email&quot;) and its address
  7603. (e.g. <code>alice@example.com</code>). See <a href="https://matrix.org/docs/spec/appendices#pid-types">the Matrix specification</a>
  7604. for more information regarding third-party identifiers.</p>
  7605. <p>For example, a call to this callback to send an invitation to the email address
  7606. <code>alice@example.com</code> would look like this:</p>
  7607. <pre><code class="language-python">await user_may_send_3pid_invite(
  7608. &quot;@bob:example.com&quot;, # The inviter's user ID
  7609. &quot;email&quot;, # The medium of the 3PID to invite
  7610. &quot;alice@example.com&quot;, # The address of the 3PID to invite
  7611. &quot;!some_room:example.com&quot;, # The ID of the room to send the invite into
  7612. )
  7613. </code></pre>
  7614. <p><strong>Note</strong>: If the third-party identifier is already associated with a matrix user ID,
  7615. <a href="modules/spam_checker_callbacks.html#user_may_invite"><code>user_may_invite</code></a> will be used instead.</p>
  7616. <p>If multiple modules implement this callback, they will be considered in order. If a
  7617. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7618. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7619. any of the subsequent implementations of this callback.</p>
  7620. <h3 id="user_may_create_room"><a class="header" href="#user_may_create_room"><code>user_may_create_room</code></a></h3>
  7621. <p><em>First introduced in Synapse v1.37.0</em></p>
  7622. <pre><code class="language-python">async def user_may_create_room(user: str) -&gt; bool
  7623. </code></pre>
  7624. <p>Called when processing a room creation request. The module must return a <code>bool</code> indicating
  7625. whether the given user (represented by their Matrix user ID) is allowed to create a room.</p>
  7626. <p>If multiple modules implement this callback, they will be considered in order. If a
  7627. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7628. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7629. any of the subsequent implementations of this callback.</p>
  7630. <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>
  7631. <p><em>First introduced in Synapse v1.37.0</em></p>
  7632. <pre><code class="language-python">async def user_may_create_room_alias(user: str, room_alias: &quot;synapse.types.RoomAlias&quot;) -&gt; bool
  7633. </code></pre>
  7634. <p>Called when trying to associate an alias with an existing room. The module must return a
  7635. <code>bool</code> indicating whether the given user (represented by their Matrix user ID) is allowed
  7636. to set the given alias.</p>
  7637. <p>If multiple modules implement this callback, they will be considered in order. If a
  7638. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7639. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7640. any of the subsequent implementations of this callback.</p>
  7641. <h3 id="user_may_publish_room"><a class="header" href="#user_may_publish_room"><code>user_may_publish_room</code></a></h3>
  7642. <p><em>First introduced in Synapse v1.37.0</em></p>
  7643. <pre><code class="language-python">async def user_may_publish_room(user: str, room_id: str) -&gt; bool
  7644. </code></pre>
  7645. <p>Called when trying to publish a room to the homeserver's public rooms directory. The
  7646. module must return a <code>bool</code> indicating whether the given user (represented by their
  7647. Matrix user ID) is allowed to publish the given room.</p>
  7648. <p>If multiple modules implement this callback, they will be considered in order. If a
  7649. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7650. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7651. any of the subsequent implementations of this callback.</p>
  7652. <h3 id="check_username_for_spam"><a class="header" href="#check_username_for_spam"><code>check_username_for_spam</code></a></h3>
  7653. <p><em>First introduced in Synapse v1.37.0</em></p>
  7654. <pre><code class="language-python">async def check_username_for_spam(user_profile: Dict[str, str]) -&gt; bool
  7655. </code></pre>
  7656. <p>Called when computing search results in the user directory. The module must return a
  7657. <code>bool</code> indicating whether the given user profile can appear in search results. The profile
  7658. is represented as a dictionary with the following keys:</p>
  7659. <ul>
  7660. <li><code>user_id</code>: The Matrix ID for this user.</li>
  7661. <li><code>display_name</code>: The user's display name.</li>
  7662. <li><code>avatar_url</code>: The <code>mxc://</code> URL to the user's avatar.</li>
  7663. </ul>
  7664. <p>The module is given a copy of the original dictionary, so modifying it from within the
  7665. module cannot modify a user's profile when included in user directory search results.</p>
  7666. <p>If multiple modules implement this callback, they will be considered in order. If a
  7667. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  7668. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  7669. any of the subsequent implementations of this callback.</p>
  7670. <h3 id="check_registration_for_spam"><a class="header" href="#check_registration_for_spam"><code>check_registration_for_spam</code></a></h3>
  7671. <p><em>First introduced in Synapse v1.37.0</em></p>
  7672. <pre><code class="language-python">async def check_registration_for_spam(
  7673. email_threepid: Optional[dict],
  7674. username: Optional[str],
  7675. request_info: Collection[Tuple[str, str]],
  7676. auth_provider_id: Optional[str] = None,
  7677. ) -&gt; &quot;synapse.spam_checker_api.RegistrationBehaviour&quot;
  7678. </code></pre>
  7679. <p>Called when registering a new user. The module must return a <code>RegistrationBehaviour</code>
  7680. indicating whether the registration can go through or must be denied, or whether the user
  7681. may be allowed to register but will be shadow banned.</p>
  7682. <p>The arguments passed to this callback are:</p>
  7683. <ul>
  7684. <li><code>email_threepid</code>: The email address used for registering, if any.</li>
  7685. <li><code>username</code>: The username the user would like to register. Can be <code>None</code>, meaning that
  7686. Synapse will generate one later.</li>
  7687. <li><code>request_info</code>: A collection of tuples, which first item is a user agent, and which
  7688. second item is an IP address. These user agents and IP addresses are the ones that were
  7689. used during the registration process.</li>
  7690. <li><code>auth_provider_id</code>: The identifier of the SSO authentication provider, if any.</li>
  7691. </ul>
  7692. <p>If multiple modules implement this callback, they will be considered in order. If a
  7693. callback returns <code>RegistrationBehaviour.ALLOW</code>, Synapse falls through to the next one.
  7694. The value of the first callback that does not return <code>RegistrationBehaviour.ALLOW</code> will
  7695. be used. If this happens, Synapse will not call any of the subsequent implementations of
  7696. this callback.</p>
  7697. <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>
  7698. <p><em>First introduced in Synapse v1.37.0</em></p>
  7699. <pre><code class="language-python">async def check_media_file_for_spam(
  7700. file_wrapper: &quot;synapse.rest.media.v1.media_storage.ReadableFileWrapper&quot;,
  7701. file_info: &quot;synapse.rest.media.v1._base.FileInfo&quot;,
  7702. ) -&gt; bool
  7703. </code></pre>
  7704. <p>Called when storing a local or remote file. The module must return a boolean indicating
  7705. whether the given file can be stored in the homeserver's media store.</p>
  7706. <p>If multiple modules implement this callback, they will be considered in order. If a
  7707. callback returns <code>False</code>, Synapse falls through to the next one. The value of the first
  7708. callback that does not return <code>False</code> will be used. If this happens, Synapse will not call
  7709. any of the subsequent implementations of this callback.</p>
  7710. <h2 id="example"><a class="header" href="#example">Example</a></h2>
  7711. <p>The example below is a module that implements the spam checker callback
  7712. <code>check_event_for_spam</code> to deny any message sent by users whose Matrix user IDs are
  7713. mentioned in a configured list, and registers a web resource to the path
  7714. <code>/_synapse/client/list_spam_checker/is_evil</code> that returns a JSON object indicating
  7715. whether the provided user appears in that list.</p>
  7716. <pre><code class="language-python">import json
  7717. from typing import Union
  7718. from twisted.web.resource import Resource
  7719. from twisted.web.server import Request
  7720. from synapse.module_api import ModuleApi
  7721. class IsUserEvilResource(Resource):
  7722. def __init__(self, config):
  7723. super(IsUserEvilResource, self).__init__()
  7724. self.evil_users = config.get(&quot;evil_users&quot;) or []
  7725. def render_GET(self, request: Request):
  7726. user = request.args.get(b&quot;user&quot;)[0].decode()
  7727. request.setHeader(b&quot;Content-Type&quot;, b&quot;application/json&quot;)
  7728. return json.dumps({&quot;evil&quot;: user in self.evil_users}).encode()
  7729. class ListSpamChecker:
  7730. def __init__(self, config: dict, api: ModuleApi):
  7731. self.api = api
  7732. self.evil_users = config.get(&quot;evil_users&quot;) or []
  7733. self.api.register_spam_checker_callbacks(
  7734. check_event_for_spam=self.check_event_for_spam,
  7735. )
  7736. self.api.register_web_resource(
  7737. path=&quot;/_synapse/client/list_spam_checker/is_evil&quot;,
  7738. resource=IsUserEvilResource(config),
  7739. )
  7740. async def check_event_for_spam(self, event: &quot;synapse.events.EventBase&quot;) -&gt; Union[bool, str]:
  7741. return event.sender not in self.evil_users
  7742. </code></pre>
  7743. <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>
  7744. <p>Third party rules callbacks allow module developers to add extra checks to verify the
  7745. validity of incoming events. Third party event rules callbacks can be registered using
  7746. the module API's <code>register_third_party_rules_callbacks</code> method.</p>
  7747. <h2 id="callbacks-1"><a class="header" href="#callbacks-1">Callbacks</a></h2>
  7748. <p>The available third party rules callbacks are:</p>
  7749. <h3 id="check_event_allowed"><a class="header" href="#check_event_allowed"><code>check_event_allowed</code></a></h3>
  7750. <p><em>First introduced in Synapse v1.39.0</em></p>
  7751. <pre><code class="language-python">async def check_event_allowed(
  7752. event: &quot;synapse.events.EventBase&quot;,
  7753. state_events: &quot;synapse.types.StateMap&quot;,
  7754. ) -&gt; Tuple[bool, Optional[dict]]
  7755. </code></pre>
  7756. <p><strong><span style="color:red">
  7757. This callback is very experimental and can and will break without notice. Module developers
  7758. are encouraged to implement <code>check_event_for_spam</code> from the spam checker category instead.
  7759. </span></strong></p>
  7760. <p>Called when processing any incoming event, with the event and a <code>StateMap</code>
  7761. representing the current state of the room the event is being sent into. A <code>StateMap</code> is
  7762. a dictionary that maps tuples containing an event type and a state key to the
  7763. corresponding state event. For example retrieving the room's <code>m.room.create</code> event from
  7764. the <code>state_events</code> argument would look like this: <code>state_events.get((&quot;m.room.create&quot;, &quot;&quot;))</code>.
  7765. The module must return a boolean indicating whether the event can be allowed.</p>
  7766. <p>Note that this callback function processes incoming events coming via federation
  7767. traffic (on top of client traffic). This means denying an event might cause the local
  7768. copy of the room's history to diverge from that of remote servers. This may cause
  7769. federation issues in the room. It is strongly recommended to only deny events using this
  7770. callback function if the sender is a local user, or in a private federation in which all
  7771. servers are using the same module, with the same configuration.</p>
  7772. <p>If the boolean returned by the module is <code>True</code>, it may also tell Synapse to replace the
  7773. event with new data by returning the new event's data as a dictionary. In order to do
  7774. that, it is recommended the module calls <code>event.get_dict()</code> to get the current event as a
  7775. dictionary, and modify the returned dictionary accordingly.</p>
  7776. <p>If <code>check_event_allowed</code> raises an exception, the module is assumed to have failed.
  7777. The event will not be accepted but is not treated as explicitly rejected, either.
  7778. An HTTP request causing the module check will likely result in a 500 Internal
  7779. Server Error.</p>
  7780. <p>When the boolean returned by the module is <code>False</code>, the event is rejected.
  7781. (Module developers should not use exceptions for rejection.)</p>
  7782. <p>Note that replacing the event only works for events sent by local users, not for events
  7783. received over federation.</p>
  7784. <p>If multiple modules implement this callback, they will be considered in order. If a
  7785. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7786. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7787. any of the subsequent implementations of this callback.</p>
  7788. <h3 id="on_create_room"><a class="header" href="#on_create_room"><code>on_create_room</code></a></h3>
  7789. <p><em>First introduced in Synapse v1.39.0</em></p>
  7790. <pre><code class="language-python">async def on_create_room(
  7791. requester: &quot;synapse.types.Requester&quot;,
  7792. request_content: dict,
  7793. is_requester_admin: bool,
  7794. ) -&gt; None
  7795. </code></pre>
  7796. <p>Called when processing a room creation request, with the <code>Requester</code> object for the user
  7797. performing the request, a dictionary representing the room creation request's JSON body
  7798. (see <a href="https://matrix.org/docs/spec/client_server/latest#post-matrix-client-r0-createroom">the spec</a>
  7799. for a list of possible parameters), and a boolean indicating whether the user performing
  7800. the request is a server admin.</p>
  7801. <p>Modules can modify the <code>request_content</code> (by e.g. adding events to its <code>initial_state</code>),
  7802. or deny the room's creation by raising a <code>module_api.errors.SynapseError</code>.</p>
  7803. <p>If multiple modules implement this callback, they will be considered in order. If a
  7804. callback returns without raising an exception, Synapse falls through to the next one. The
  7805. room creation will be forbidden as soon as one of the callbacks raises an exception. If
  7806. this happens, Synapse will not call any of the subsequent implementations of this
  7807. callback.</p>
  7808. <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>
  7809. <p><em>First introduced in Synapse v1.39.0</em></p>
  7810. <pre><code class="language-python">async def check_threepid_can_be_invited(
  7811. medium: str,
  7812. address: str,
  7813. state_events: &quot;synapse.types.StateMap&quot;,
  7814. ) -&gt; bool:
  7815. </code></pre>
  7816. <p>Called when processing an invite via a third-party identifier (i.e. email or phone number).
  7817. The module must return a boolean indicating whether the invite can go through.</p>
  7818. <p>If multiple modules implement this callback, they will be considered in order. If a
  7819. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7820. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7821. any of the subsequent implementations of this callback.</p>
  7822. <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>
  7823. <p><em>First introduced in Synapse v1.39.0</em></p>
  7824. <pre><code class="language-python">async def check_visibility_can_be_modified(
  7825. room_id: str,
  7826. state_events: &quot;synapse.types.StateMap&quot;,
  7827. new_visibility: str,
  7828. ) -&gt; bool:
  7829. </code></pre>
  7830. <p>Called when changing the visibility of a room in the local public room directory. The
  7831. visibility is a string that's either &quot;public&quot; or &quot;private&quot;. The module must return a
  7832. boolean indicating whether the change can go through.</p>
  7833. <p>If multiple modules implement this callback, they will be considered in order. If a
  7834. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  7835. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  7836. any of the subsequent implementations of this callback.</p>
  7837. <h3 id="on_new_event"><a class="header" href="#on_new_event"><code>on_new_event</code></a></h3>
  7838. <p><em>First introduced in Synapse v1.47.0</em></p>
  7839. <pre><code class="language-python">async def on_new_event(
  7840. event: &quot;synapse.events.EventBase&quot;,
  7841. state_events: &quot;synapse.types.StateMap&quot;,
  7842. ) -&gt; None:
  7843. </code></pre>
  7844. <p>Called after sending an event into a room. The module is passed the event, as well
  7845. as the state of the room <em>after</em> the event. This means that if the event is a state event,
  7846. it will be included in this state.</p>
  7847. <p>Note that this callback is called when the event has already been processed and stored
  7848. into the room, which means this callback cannot be used to deny persisting the event. To
  7849. 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>
  7850. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  7851. <h2 id="example-1"><a class="header" href="#example-1">Example</a></h2>
  7852. <p>The example below is a module that implements the third-party rules callback
  7853. <code>check_event_allowed</code> to censor incoming messages as dictated by a third-party service.</p>
  7854. <pre><code class="language-python">from typing import Optional, Tuple
  7855. from synapse.module_api import ModuleApi
  7856. _DEFAULT_CENSOR_ENDPOINT = &quot;https://my-internal-service.local/censor-event&quot;
  7857. class EventCensorer:
  7858. def __init__(self, config: dict, api: ModuleApi):
  7859. self.api = api
  7860. self._endpoint = config.get(&quot;endpoint&quot;, _DEFAULT_CENSOR_ENDPOINT)
  7861. self.api.register_third_party_rules_callbacks(
  7862. check_event_allowed=self.check_event_allowed,
  7863. )
  7864. async def check_event_allowed(
  7865. self,
  7866. event: &quot;synapse.events.EventBase&quot;,
  7867. state_events: &quot;synapse.types.StateMap&quot;,
  7868. ) -&gt; Tuple[bool, Optional[dict]]:
  7869. event_dict = event.get_dict()
  7870. new_event_content = await self.api.http_client.post_json_get_json(
  7871. uri=self._endpoint, post_json=event_dict,
  7872. )
  7873. event_dict[&quot;content&quot;] = new_event_content
  7874. return event_dict
  7875. </code></pre>
  7876. <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>
  7877. <p>Presence router callbacks allow module developers to specify additional users (local or remote)
  7878. to receive certain presence updates from local users. Presence router callbacks can be
  7879. registered using the module API's <code>register_presence_router_callbacks</code> method.</p>
  7880. <h2 id="callbacks-2"><a class="header" href="#callbacks-2">Callbacks</a></h2>
  7881. <p>The available presence router callbacks are:</p>
  7882. <h3 id="get_users_for_states"><a class="header" href="#get_users_for_states"><code>get_users_for_states</code></a></h3>
  7883. <p><em>First introduced in Synapse v1.42.0</em></p>
  7884. <pre><code class="language-python">async def get_users_for_states(
  7885. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  7886. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]
  7887. </code></pre>
  7888. <p><strong>Requires</strong> <code>get_interested_users</code> to also be registered</p>
  7889. <p>Called when processing updates to the presence state of one or more users. This callback can
  7890. be used to instruct the server to forward that presence state to specific users. The module
  7891. must return a dictionary that maps from Matrix user IDs (which can be local or remote) to the
  7892. <code>UserPresenceState</code> changes that they should be forwarded.</p>
  7893. <p>Synapse will then attempt to send the specified presence updates to each user when possible.</p>
  7894. <p>If multiple modules implement this callback, Synapse merges all the dictionaries returned
  7895. by the callbacks. If multiple callbacks return a dictionary containing the same key,
  7896. Synapse concatenates the sets associated with this key from each dictionary. </p>
  7897. <h3 id="get_interested_users"><a class="header" href="#get_interested_users"><code>get_interested_users</code></a></h3>
  7898. <p><em>First introduced in Synapse v1.42.0</em></p>
  7899. <pre><code class="language-python">async def get_interested_users(
  7900. user_id: str
  7901. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]
  7902. </code></pre>
  7903. <p><strong>Requires</strong> <code>get_users_for_states</code> to also be registered</p>
  7904. <p>Called when determining which users someone should be able to see the presence state of. This
  7905. callback should return complementary results to <code>get_users_for_state</code> or the presence information
  7906. may not be properly forwarded.</p>
  7907. <p>The callback is given the Matrix user ID for a local user that is requesting presence data and
  7908. should return the Matrix user IDs of the users whose presence state they are allowed to
  7909. query. The returned users can be local or remote. </p>
  7910. <p>Alternatively the callback can return <code>synapse.module_api.PRESENCE_ALL_USERS</code>
  7911. to indicate that the user should receive updates from all known users.</p>
  7912. <p>If multiple modules implement this callback, they will be considered in order. Synapse
  7913. calls each callback one by one, and use a concatenation of all the <code>set</code>s returned by the
  7914. callbacks. If one callback returns <code>synapse.module_api.PRESENCE_ALL_USERS</code>, Synapse uses
  7915. this value instead. If this happens, Synapse does not call any of the subsequent
  7916. implementations of this callback.</p>
  7917. <h2 id="example-2"><a class="header" href="#example-2">Example</a></h2>
  7918. <p>The example below is a module that implements both presence router callbacks, and ensures
  7919. that <code>@alice:example.org</code> receives all presence updates from <code>@bob:example.com</code> and
  7920. <code>@charlie:somewhere.org</code>, regardless of whether Alice shares a room with any of them.</p>
  7921. <pre><code class="language-python">from typing import Dict, Iterable, Set, Union
  7922. from synapse.module_api import ModuleApi
  7923. class CustomPresenceRouter:
  7924. def __init__(self, config: dict, api: ModuleApi):
  7925. self.api = api
  7926. self.api.register_presence_router_callbacks(
  7927. get_users_for_states=self.get_users_for_states,
  7928. get_interested_users=self.get_interested_users,
  7929. )
  7930. async def get_users_for_states(
  7931. self,
  7932. state_updates: Iterable[&quot;synapse.api.UserPresenceState&quot;],
  7933. ) -&gt; Dict[str, Set[&quot;synapse.api.UserPresenceState&quot;]]:
  7934. res = {}
  7935. for update in state_updates:
  7936. if (
  7937. update.user_id == &quot;@bob:example.com&quot;
  7938. or update.user_id == &quot;@charlie:somewhere.org&quot;
  7939. ):
  7940. res.setdefault(&quot;@alice:example.com&quot;, set()).add(update)
  7941. return res
  7942. async def get_interested_users(
  7943. self,
  7944. user_id: str,
  7945. ) -&gt; Union[Set[str], &quot;synapse.module_api.PRESENCE_ALL_USERS&quot;]:
  7946. if user_id == &quot;@alice:example.com&quot;:
  7947. return {&quot;@bob:example.com&quot;, &quot;@charlie:somewhere.org&quot;}
  7948. return set()
  7949. </code></pre>
  7950. <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>
  7951. <p>Account validity callbacks allow module developers to add extra steps to verify the
  7952. validity on an account, i.e. see if a user can be granted access to their account on the
  7953. Synapse instance. Account validity callbacks can be registered using the module API's
  7954. <code>register_account_validity_callbacks</code> method.</p>
  7955. <p>The available account validity callbacks are:</p>
  7956. <h3 id="is_user_expired"><a class="header" href="#is_user_expired"><code>is_user_expired</code></a></h3>
  7957. <p><em>First introduced in Synapse v1.39.0</em></p>
  7958. <pre><code class="language-python">async def is_user_expired(user: str) -&gt; Optional[bool]
  7959. </code></pre>
  7960. <p>Called when processing any authenticated request (except for logout requests). The module
  7961. can return a <code>bool</code> to indicate whether the user has expired and should be locked out of
  7962. their account, or <code>None</code> if the module wasn't able to figure it out. The user is
  7963. represented by their Matrix user ID (e.g. <code>@alice:example.com</code>).</p>
  7964. <p>If the module returns <code>True</code>, the current request will be denied with the error code
  7965. <code>ORG_MATRIX_EXPIRED_ACCOUNT</code> and the HTTP status code 403. Note that this doesn't
  7966. invalidate the user's access token.</p>
  7967. <p>If multiple modules implement this callback, they will be considered in order. If a
  7968. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  7969. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  7970. any of the subsequent implementations of this callback.</p>
  7971. <h3 id="on_user_registration"><a class="header" href="#on_user_registration"><code>on_user_registration</code></a></h3>
  7972. <p><em>First introduced in Synapse v1.39.0</em></p>
  7973. <pre><code class="language-python">async def on_user_registration(user: str) -&gt; None
  7974. </code></pre>
  7975. <p>Called after successfully registering a user, in case the module needs to perform extra
  7976. operations to keep track of them. (e.g. add them to a database table). The user is
  7977. represented by their Matrix user ID.</p>
  7978. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  7979. <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>
  7980. <p>Password auth providers offer a way for server administrators to integrate
  7981. their Synapse installation with an external authentication system. The callbacks can be
  7982. registered by using the Module API's <code>register_password_auth_provider_callbacks</code> method.</p>
  7983. <h2 id="callbacks-3"><a class="header" href="#callbacks-3">Callbacks</a></h2>
  7984. <h3 id="auth_checkers"><a class="header" href="#auth_checkers"><code>auth_checkers</code></a></h3>
  7985. <p><em>First introduced in Synapse v1.46.0</em></p>
  7986. <pre><code class="language-python">auth_checkers: Dict[Tuple[str, Tuple[str, ...]], Callable]
  7987. </code></pre>
  7988. <p>A dict mapping from tuples of a login type identifier (such as <code>m.login.password</code>) and a
  7989. tuple of field names (such as <code>(&quot;password&quot;, &quot;secret_thing&quot;)</code>) to authentication checking
  7990. callbacks, which should be of the following form:</p>
  7991. <pre><code class="language-python">async def check_auth(
  7992. user: str,
  7993. login_type: str,
  7994. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  7995. ) -&gt; Optional[
  7996. Tuple[
  7997. str,
  7998. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  7999. ]
  8000. ]
  8001. </code></pre>
  8002. <p>The login type and field names should be provided by the user in the
  8003. request to the <code>/login</code> API. <a href="https://matrix.org/docs/spec/client_server/latest#authentication-types">The Matrix specification</a>
  8004. defines some types, however user defined ones are also allowed.</p>
  8005. <p>The callback is passed the <code>user</code> field provided by the client (which might not be in
  8006. <code>@username:server</code> form), the login type, and a dictionary of login secrets passed by
  8007. the client.</p>
  8008. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  8009. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the
  8010. <code>/login</code> request. If the module doesn't wish to return a callback, it must return <code>None</code>
  8011. instead.</p>
  8012. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  8013. <p>If multiple modules register an auth checker for the same login type but with different
  8014. fields, Synapse will refuse to start.</p>
  8015. <p>If multiple modules register an auth checker for the same login type with the same fields,
  8016. then the callbacks will be executed in order, until one returns a Matrix User ID (and
  8017. optionally a callback). In that case, the return value of that callback will be accepted
  8018. and subsequent callbacks will not be fired. If every callback returns <code>None</code>, then the
  8019. authentication fails.</p>
  8020. <h3 id="check_3pid_auth"><a class="header" href="#check_3pid_auth"><code>check_3pid_auth</code></a></h3>
  8021. <p><em>First introduced in Synapse v1.46.0</em></p>
  8022. <pre><code class="language-python">async def check_3pid_auth(
  8023. medium: str,
  8024. address: str,
  8025. password: str,
  8026. ) -&gt; Optional[
  8027. Tuple[
  8028. str,
  8029. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]]
  8030. ]
  8031. ]
  8032. </code></pre>
  8033. <p>Called when a user attempts to register or log in with a third party identifier,
  8034. such as email. It is passed the medium (eg. <code>email</code>), an address (eg. <code>jdoe@example.com</code>)
  8035. and the user's password.</p>
  8036. <p>If the authentication is successful, the module must return the user's Matrix ID (e.g.
  8037. <code>@alice:example.com</code>) and optionally a callback to be called with the response to the <code>/login</code> request.
  8038. If the module doesn't wish to return a callback, it must return None instead.</p>
  8039. <p>If the authentication is unsuccessful, the module must return <code>None</code>.</p>
  8040. <p>If multiple modules implement this callback, they will be considered in order. If a
  8041. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  8042. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  8043. any of the subsequent implementations of this callback. If every callback return <code>None</code>,
  8044. the authentication is denied.</p>
  8045. <h3 id="on_logged_out"><a class="header" href="#on_logged_out"><code>on_logged_out</code></a></h3>
  8046. <p><em>First introduced in Synapse v1.46.0</em></p>
  8047. <pre><code class="language-python">async def on_logged_out(
  8048. user_id: str,
  8049. device_id: Optional[str],
  8050. access_token: str
  8051. ) -&gt; None
  8052. </code></pre>
  8053. <p>Called during a logout request for a user. It is passed the qualified user ID, the ID of the
  8054. deactivated device (if any: access tokens are occasionally created without an associated
  8055. device ID), and the (now deactivated) access token.</p>
  8056. <p>If multiple modules implement this callback, Synapse runs them all in order.</p>
  8057. <h3 id="get_username_for_registration"><a class="header" href="#get_username_for_registration"><code>get_username_for_registration</code></a></h3>
  8058. <p><em>First introduced in Synapse v1.52.0</em></p>
  8059. <pre><code class="language-python">async def get_username_for_registration(
  8060. uia_results: Dict[str, Any],
  8061. params: Dict[str, Any],
  8062. ) -&gt; Optional[str]
  8063. </code></pre>
  8064. <p>Called when registering a new user. The module can return a username to set for the user
  8065. being registered by returning it as a string, or <code>None</code> if it doesn't wish to force a
  8066. username for this user. If a username is returned, it will be used as the local part of a
  8067. user's full Matrix ID (e.g. it's <code>alice</code> in <code>@alice:example.com</code>).</p>
  8068. <p>This callback is called once <a href="https://spec.matrix.org/latest/client-server-api/#user-interactive-authentication-api">User-Interactive Authentication</a>
  8069. has been completed by the user. It is not called when registering a user via SSO. It is
  8070. passed two dictionaries, which include the information that the user has provided during
  8071. the registration process.</p>
  8072. <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>
  8073. flow followed by the user. Its keys are the identifiers of every step involved in the flow,
  8074. associated with either a boolean value indicating whether the step was correctly completed,
  8075. or additional information (e.g. email address, phone number...). A list of most existing
  8076. identifiers can be found in the <a href="https://spec.matrix.org/v1.1/client-server-api/#authentication-types">Matrix specification</a>.
  8077. Here's an example featuring all currently supported keys:</p>
  8078. <pre><code class="language-python">{
  8079. &quot;m.login.dummy&quot;: True, # Dummy authentication
  8080. &quot;m.login.terms&quot;: True, # User has accepted the terms of service for the homeserver
  8081. &quot;m.login.recaptcha&quot;: True, # User has completed the recaptcha challenge
  8082. &quot;m.login.email.identity&quot;: { # User has provided and verified an email address
  8083. &quot;medium&quot;: &quot;email&quot;,
  8084. &quot;address&quot;: &quot;alice@example.com&quot;,
  8085. &quot;validated_at&quot;: 1642701357084,
  8086. },
  8087. &quot;m.login.msisdn&quot;: { # User has provided and verified a phone number
  8088. &quot;medium&quot;: &quot;msisdn&quot;,
  8089. &quot;address&quot;: &quot;33123456789&quot;,
  8090. &quot;validated_at&quot;: 1642701357084,
  8091. },
  8092. &quot;m.login.registration_token&quot;: &quot;sometoken&quot;, # User has registered through a registration token
  8093. }
  8094. </code></pre>
  8095. <p>The second dictionary contains the parameters provided by the user's client in the request
  8096. to <code>/_matrix/client/v3/register</code>. See the <a href="https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3register">Matrix specification</a>
  8097. for a complete list of these parameters.</p>
  8098. <p>If the module cannot, or does not wish to, generate a username for this user, it must
  8099. return <code>None</code>.</p>
  8100. <p>If multiple modules implement this callback, they will be considered in order. If a
  8101. callback returns <code>None</code>, Synapse falls through to the next one. The value of the first
  8102. callback that does not return <code>None</code> will be used. If this happens, Synapse will not call
  8103. any of the subsequent implementations of this callback. If every callback return <code>None</code>,
  8104. the username provided by the user is used, if any (otherwise one is automatically
  8105. generated).</p>
  8106. <h2 id="is_3pid_allowed"><a class="header" href="#is_3pid_allowed"><code>is_3pid_allowed</code></a></h2>
  8107. <p><em>First introduced in Synapse v1.53.0</em></p>
  8108. <pre><code class="language-python">async def is_3pid_allowed(self, medium: str, address: str, registration: bool) -&gt; bool
  8109. </code></pre>
  8110. <p>Called when attempting to bind a third-party identifier (i.e. an email address or a phone
  8111. number). The module is given the medium of the third-party identifier (which is <code>email</code> if
  8112. the identifier is an email address, or <code>msisdn</code> if the identifier is a phone number) and
  8113. its address, as well as a boolean indicating whether the attempt to bind is happening as
  8114. part of registering a new user. The module must return a boolean indicating whether the
  8115. identifier can be allowed to be bound to an account on the local homeserver.</p>
  8116. <p>If multiple modules implement this callback, they will be considered in order. If a
  8117. callback returns <code>True</code>, Synapse falls through to the next one. The value of the first
  8118. callback that does not return <code>True</code> will be used. If this happens, Synapse will not call
  8119. any of the subsequent implementations of this callback.</p>
  8120. <h2 id="example-3"><a class="header" href="#example-3">Example</a></h2>
  8121. <p>The example module below implements authentication checkers for two different login types: </p>
  8122. <ul>
  8123. <li><code>my.login.type</code>
  8124. <ul>
  8125. <li>Expects a <code>my_field</code> field to be sent to <code>/login</code></li>
  8126. <li>Is checked by the method: <code>self.check_my_login</code></li>
  8127. </ul>
  8128. </li>
  8129. <li><code>m.login.password</code> (defined in <a href="https://matrix.org/docs/spec/client_server/latest#password-based">the spec</a>)
  8130. <ul>
  8131. <li>Expects a <code>password</code> field to be sent to <code>/login</code></li>
  8132. <li>Is checked by the method: <code>self.check_pass</code> </li>
  8133. </ul>
  8134. </li>
  8135. </ul>
  8136. <pre><code class="language-python">from typing import Awaitable, Callable, Optional, Tuple
  8137. import synapse
  8138. from synapse import module_api
  8139. class MyAuthProvider:
  8140. def __init__(self, config: dict, api: module_api):
  8141. self.api = api
  8142. self.credentials = {
  8143. &quot;bob&quot;: &quot;building&quot;,
  8144. &quot;@scoop:matrix.org&quot;: &quot;digging&quot;,
  8145. }
  8146. api.register_password_auth_provider_callbacks(
  8147. auth_checkers={
  8148. (&quot;my.login_type&quot;, (&quot;my_field&quot;,)): self.check_my_login,
  8149. (&quot;m.login.password&quot;, (&quot;password&quot;,)): self.check_pass,
  8150. },
  8151. )
  8152. async def check_my_login(
  8153. self,
  8154. username: str,
  8155. login_type: str,
  8156. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  8157. ) -&gt; Optional[
  8158. Tuple[
  8159. str,
  8160. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  8161. ]
  8162. ]:
  8163. if login_type != &quot;my.login_type&quot;:
  8164. return None
  8165. if self.credentials.get(username) == login_dict.get(&quot;my_field&quot;):
  8166. return self.api.get_qualified_user_id(username)
  8167. async def check_pass(
  8168. self,
  8169. username: str,
  8170. login_type: str,
  8171. login_dict: &quot;synapse.module_api.JsonDict&quot;,
  8172. ) -&gt; Optional[
  8173. Tuple[
  8174. str,
  8175. Optional[Callable[[&quot;synapse.module_api.LoginResponse&quot;], Awaitable[None]]],
  8176. ]
  8177. ]:
  8178. if login_type != &quot;m.login.password&quot;:
  8179. return None
  8180. if self.credentials.get(username) == login_dict.get(&quot;password&quot;):
  8181. return self.api.get_qualified_user_id(username)
  8182. </code></pre>
  8183. <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>
  8184. <p>Background update controller callbacks allow module developers to control (e.g. rate-limit)
  8185. how database background updates are run. A database background update is an operation
  8186. Synapse runs on its database in the background after it starts. It's usually used to run
  8187. database operations that would take too long if they were run at the same time as schema
  8188. updates (which are run on startup) and delay Synapse's startup too much: populating a
  8189. table with a big amount of data, adding an index on a big table, deleting superfluous data,
  8190. etc.</p>
  8191. <p>Background update controller callbacks can be registered using the module API's
  8192. <code>register_background_update_controller_callbacks</code> method. Only the first module (in order
  8193. of appearance in Synapse's configuration file) calling this method can register background
  8194. update controller callbacks, subsequent calls are ignored.</p>
  8195. <p>The available background update controller callbacks are:</p>
  8196. <h3 id="on_update"><a class="header" href="#on_update"><code>on_update</code></a></h3>
  8197. <p><em>First introduced in Synapse v1.49.0</em></p>
  8198. <pre><code class="language-python">def on_update(update_name: str, database_name: str, one_shot: bool) -&gt; AsyncContextManager[int]
  8199. </code></pre>
  8200. <p>Called when about to do an iteration of a background update. The module is given the name
  8201. of the update, the name of the database, and a flag to indicate whether the background
  8202. update will happen in one go and may take a long time (e.g. creating indices). If this last
  8203. argument is set to <code>False</code>, the update will be run in batches.</p>
  8204. <p>The module must return an async context manager. It will be entered before Synapse runs a
  8205. background update; this should return the desired duration of the iteration, in
  8206. milliseconds.</p>
  8207. <p>The context manager will be exited when the iteration completes. Note that the duration
  8208. returned by the context manager is a target, and an iteration may take substantially longer
  8209. or shorter. If the <code>one_shot</code> flag is set to <code>True</code>, the duration returned is ignored.</p>
  8210. <p><strong>Note</strong>: Unlike most module callbacks in Synapse, this one is <em>synchronous</em>. This is
  8211. because asynchronous operations are expected to be run by the async context manager.</p>
  8212. <p>This callback is required when registering any other background update controller callback.</p>
  8213. <h3 id="default_batch_size"><a class="header" href="#default_batch_size"><code>default_batch_size</code></a></h3>
  8214. <p><em>First introduced in Synapse v1.49.0</em></p>
  8215. <pre><code class="language-python">async def default_batch_size(update_name: str, database_name: str) -&gt; int
  8216. </code></pre>
  8217. <p>Called before the first iteration of a background update, with the name of the update and
  8218. of the database. The module must return the number of elements to process in this first
  8219. iteration.</p>
  8220. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  8221. <h3 id="min_batch_size"><a class="header" href="#min_batch_size"><code>min_batch_size</code></a></h3>
  8222. <p><em>First introduced in Synapse v1.49.0</em></p>
  8223. <pre><code class="language-python">async def min_batch_size(update_name: str, database_name: str) -&gt; int
  8224. </code></pre>
  8225. <p>Called before running a new batch for a background update, with the name of the update and
  8226. of the database. The module must return an integer representing the minimum number of
  8227. elements to process in this iteration. This number must be at least 1, and is used to
  8228. ensure that progress is always made.</p>
  8229. <p>If this callback is not defined, Synapse will use a default value of 100.</p>
  8230. <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>
  8231. <p>In order to port a module that uses Synapse's old module interface, its author needs to:</p>
  8232. <ul>
  8233. <li>ensure the module's callbacks are all asynchronous.</li>
  8234. <li>register their callbacks using one or more of the <code>register_[...]_callbacks</code> methods
  8235. 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>
  8236. for more info).</li>
  8237. </ul>
  8238. <p>Additionally, if the module is packaged with an additional web resource, the module
  8239. should register this resource in its <code>__init__</code> method using the <code>register_web_resource</code>
  8240. method from the <code>ModuleApi</code> class (see <a href="modules/writing_a_module.html#registering-a-web-resource">this section</a> for
  8241. more info).</p>
  8242. <p>There is no longer a <code>get_db_schema_files</code> callback provided for password auth provider modules. Any
  8243. changes to the database should now be made by the module using the module API class.</p>
  8244. <p>The module's author should also update any example in the module's configuration to only
  8245. use the new <code>modules</code> section in Synapse's configuration file (see <a href="modules/index.html#using-modules">this section</a>
  8246. for more info).</p>
  8247. <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>
  8248. <p>For small instances it recommended to run Synapse in the default monolith mode.
  8249. For larger instances where performance is a concern it can be helpful to split
  8250. out functionality into multiple separate python processes. These processes are
  8251. called 'workers', and are (eventually) intended to scale horizontally
  8252. independently.</p>
  8253. <p>Synapse's worker support is under active development and subject to change as
  8254. we attempt to rapidly scale ever larger Synapse instances. However we are
  8255. documenting it here to help admins needing a highly scalable Synapse instance
  8256. similar to the one running <code>matrix.org</code>.</p>
  8257. <p>All processes continue to share the same database instance, and as such,
  8258. workers only work with PostgreSQL-based Synapse deployments. SQLite should only
  8259. be used for demo purposes and any admin considering workers should already be
  8260. running PostgreSQL.</p>
  8261. <p>See also <a href="https://matrix.org/blog/2020/11/03/how-we-fixed-synapses-scalability">Matrix.org blog post</a>
  8262. for a higher level overview.</p>
  8263. <h2 id="main-processworker-communication"><a class="header" href="#main-processworker-communication">Main process/worker communication</a></h2>
  8264. <p>The processes communicate with each other via a Synapse-specific protocol called
  8265. 'replication' (analogous to MySQL- or Postgres-style database replication) which
  8266. feeds streams of newly written data between processes so they can be kept in
  8267. sync with the database state.</p>
  8268. <p>When configured to do so, Synapse uses a
  8269. <a href="https://redis.io/topics/pubsub">Redis pub/sub channel</a> to send the replication
  8270. stream between all configured Synapse processes. Additionally, processes may
  8271. make HTTP requests to each other, primarily for operations which need to wait
  8272. for a reply ─ such as sending an event.</p>
  8273. <p>Redis support was added in v1.13.0 with it becoming the recommended method in
  8274. v1.18.0. It replaced the old direct TCP connections (which is deprecated as of
  8275. v1.18.0) to the main process. With Redis, rather than all the workers connecting
  8276. to the main process, all the workers and the main process connect to Redis,
  8277. which relays replication commands between processes. This can give a significant
  8278. cpu saving on the main process and will be a prerequisite for upcoming
  8279. performance improvements.</p>
  8280. <p>If Redis support is enabled Synapse will use it as a shared cache, as well as a
  8281. pub/sub mechanism.</p>
  8282. <p>See the <a href="workers.html#architectural-diagram">Architectural diagram</a> section at the end for
  8283. a visualisation of what this looks like.</p>
  8284. <h2 id="setting-up-workers"><a class="header" href="#setting-up-workers">Setting up workers</a></h2>
  8285. <p>A Redis server is required to manage the communication between the processes.
  8286. The Redis server should be installed following the normal procedure for your
  8287. distribution (e.g. <code>apt install redis-server</code> on Debian). It is safe to use an
  8288. existing Redis deployment if you have one.</p>
  8289. <p>Once installed, check that Redis is running and accessible from the host running
  8290. Synapse, for example by executing <code>echo PING | nc -q1 localhost 6379</code> and seeing
  8291. a response of <code>+PONG</code>.</p>
  8292. <p>The appropriate dependencies must also be installed for Synapse. If using a
  8293. virtualenv, these can be installed with:</p>
  8294. <pre><code class="language-sh">pip install &quot;matrix-synapse[redis]&quot;
  8295. </code></pre>
  8296. <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
  8297. <code>matrix.org</code> and in the docker images at
  8298. https://hub.docker.com/r/matrixdotorg/synapse/.</p>
  8299. <p>To make effective use of the workers, you will need to configure an HTTP
  8300. reverse-proxy such as nginx or haproxy, which will direct incoming requests to
  8301. the correct worker, or to the main synapse instance. See
  8302. <a href="reverse_proxy.html">the reverse proxy documentation</a> for information on setting up a reverse
  8303. proxy.</p>
  8304. <p>When using workers, each worker process has its own configuration file which
  8305. contains settings specific to that worker, such as the HTTP listener that it
  8306. provides (if any), logging configuration, etc.</p>
  8307. <p>Normally, the worker processes are configured to read from a shared
  8308. configuration file as well as the worker-specific configuration files. This
  8309. makes it easier to keep common configuration settings synchronised across all
  8310. the processes.</p>
  8311. <p>The main process is somewhat special in this respect: it does not normally
  8312. need its own configuration file and can take all of its configuration from the
  8313. shared configuration file.</p>
  8314. <h3 id="shared-configuration"><a class="header" href="#shared-configuration">Shared configuration</a></h3>
  8315. <p>Normally, only a couple of changes are needed to make an existing configuration
  8316. file suitable for use with workers. First, you need to enable an &quot;HTTP replication
  8317. listener&quot; for the main process; and secondly, you need to enable redis-based
  8318. replication. Optionally, a shared secret can be used to authenticate HTTP
  8319. traffic between workers. For example:</p>
  8320. <pre><code class="language-yaml"># extend the existing `listeners` section. This defines the ports that the
  8321. # main process will listen on.
  8322. listeners:
  8323. # The HTTP replication port
  8324. - port: 9093
  8325. bind_address: '127.0.0.1'
  8326. type: http
  8327. resources:
  8328. - names: [replication]
  8329. # Add a random shared secret to authenticate traffic.
  8330. worker_replication_secret: &quot;&quot;
  8331. redis:
  8332. enabled: true
  8333. </code></pre>
  8334. <p>See the sample config for the full documentation of each option.</p>
  8335. <p>Under <strong>no circumstances</strong> should the replication listener be exposed to the
  8336. public internet; it has no authentication and is unencrypted.</p>
  8337. <h3 id="worker-configuration"><a class="header" href="#worker-configuration">Worker configuration</a></h3>
  8338. <p>In the config file for each worker, you must specify the type of worker
  8339. application (<code>worker_app</code>), and you should specify a unique name for the worker
  8340. (<code>worker_name</code>). The currently available worker applications are listed below.
  8341. You must also specify the HTTP replication endpoint that it should talk to on
  8342. the main synapse process. <code>worker_replication_host</code> should specify the host of
  8343. the main synapse and <code>worker_replication_http_port</code> should point to the HTTP
  8344. replication port. If the worker will handle HTTP requests then the
  8345. <code>worker_listeners</code> option should be set with a <code>http</code> listener, in the same way
  8346. as the <code>listeners</code> option in the shared config.</p>
  8347. <p>For example:</p>
  8348. <pre><code class="language-yaml">worker_app: synapse.app.generic_worker
  8349. worker_name: worker1
  8350. # The replication listener on the main synapse process.
  8351. worker_replication_host: 127.0.0.1
  8352. worker_replication_http_port: 9093
  8353. worker_listeners:
  8354. - type: http
  8355. port: 8083
  8356. resources:
  8357. - names:
  8358. - client
  8359. - federation
  8360. worker_log_config: /home/matrix/synapse/config/worker1_log_config.yaml
  8361. </code></pre>
  8362. <p>...is a full configuration for a generic worker instance, which will expose a
  8363. plain HTTP endpoint on port 8083 separately serving various endpoints, e.g.
  8364. <code>/sync</code>, which are listed below.</p>
  8365. <p>Obviously you should configure your reverse-proxy to route the relevant
  8366. endpoints to the worker (<code>localhost:8083</code> in the above example).</p>
  8367. <h3 id="running-synapse-with-workers"><a class="header" href="#running-synapse-with-workers">Running Synapse with workers</a></h3>
  8368. <p>Finally, you need to start your worker processes. This can be done with either
  8369. <code>synctl</code> or your distribution's preferred service manager such as <code>systemd</code>. We
  8370. recommend the use of <code>systemd</code> where available: for information on setting up
  8371. <code>systemd</code> to start synapse workers, see
  8372. <a href="systemd-with-workers">Systemd with Workers</a>. To use <code>synctl</code>, see
  8373. <a href="synctl_workers.html">Using synctl with Workers</a>.</p>
  8374. <h2 id="available-worker-applications"><a class="header" href="#available-worker-applications">Available worker applications</a></h2>
  8375. <h3 id="synapseappgeneric_worker"><a class="header" href="#synapseappgeneric_worker"><code>synapse.app.generic_worker</code></a></h3>
  8376. <p>This worker can handle API requests matching the following regular
  8377. expressions:</p>
  8378. <pre><code># Sync requests
  8379. ^/_matrix/client/(v2_alpha|r0|v3)/sync$
  8380. ^/_matrix/client/(api/v1|v2_alpha|r0|v3)/events$
  8381. ^/_matrix/client/(api/v1|r0|v3)/initialSync$
  8382. ^/_matrix/client/(api/v1|r0|v3)/rooms/[^/]+/initialSync$
  8383. # Federation requests
  8384. ^/_matrix/federation/v1/event/
  8385. ^/_matrix/federation/v1/state/
  8386. ^/_matrix/federation/v1/state_ids/
  8387. ^/_matrix/federation/v1/backfill/
  8388. ^/_matrix/federation/v1/get_missing_events/
  8389. ^/_matrix/federation/v1/publicRooms
  8390. ^/_matrix/federation/v1/query/
  8391. ^/_matrix/federation/v1/make_join/
  8392. ^/_matrix/federation/v1/make_leave/
  8393. ^/_matrix/federation/v1/send_join/
  8394. ^/_matrix/federation/v2/send_join/
  8395. ^/_matrix/federation/v1/send_leave/
  8396. ^/_matrix/federation/v2/send_leave/
  8397. ^/_matrix/federation/v1/invite/
  8398. ^/_matrix/federation/v2/invite/
  8399. ^/_matrix/federation/v1/query_auth/
  8400. ^/_matrix/federation/v1/event_auth/
  8401. ^/_matrix/federation/v1/exchange_third_party_invite/
  8402. ^/_matrix/federation/v1/user/devices/
  8403. ^/_matrix/federation/v1/get_groups_publicised$
  8404. ^/_matrix/key/v2/query
  8405. ^/_matrix/federation/unstable/org.matrix.msc2946/spaces/
  8406. ^/_matrix/federation/(v1|unstable/org.matrix.msc2946)/hierarchy/
  8407. # Inbound federation transaction request
  8408. ^/_matrix/federation/v1/send/
  8409. # Client API requests
  8410. ^/_matrix/client/(api/v1|r0|v3|unstable)/createRoom$
  8411. ^/_matrix/client/(api/v1|r0|v3|unstable)/publicRooms$
  8412. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/joined_members$
  8413. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/context/.*$
  8414. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/members$
  8415. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state$
  8416. ^/_matrix/client/unstable/org.matrix.msc2946/rooms/.*/spaces$
  8417. ^/_matrix/client/(v1|unstable/org.matrix.msc2946)/rooms/.*/hierarchy$
  8418. ^/_matrix/client/unstable/im.nheko.summary/rooms/.*/summary$
  8419. ^/_matrix/client/(api/v1|r0|v3|unstable)/account/3pid$
  8420. ^/_matrix/client/(api/v1|r0|v3|unstable)/devices$
  8421. ^/_matrix/client/(api/v1|r0|v3|unstable)/keys/query$
  8422. ^/_matrix/client/(api/v1|r0|v3|unstable)/keys/changes$
  8423. ^/_matrix/client/versions$
  8424. ^/_matrix/client/(api/v1|r0|v3|unstable)/voip/turnServer$
  8425. ^/_matrix/client/(api/v1|r0|v3|unstable)/joined_groups$
  8426. ^/_matrix/client/(api/v1|r0|v3|unstable)/publicised_groups$
  8427. ^/_matrix/client/(api/v1|r0|v3|unstable)/publicised_groups/
  8428. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/event/
  8429. ^/_matrix/client/(api/v1|r0|v3|unstable)/joined_rooms$
  8430. ^/_matrix/client/(api/v1|r0|v3|unstable)/search$
  8431. # Registration/login requests
  8432. ^/_matrix/client/(api/v1|r0|v3|unstable)/login$
  8433. ^/_matrix/client/(r0|v3|unstable)/register$
  8434. ^/_matrix/client/v1/register/m.login.registration_token/validity$
  8435. # Event sending requests
  8436. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/redact
  8437. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/send
  8438. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/state/
  8439. ^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/(join|invite|leave|ban|unban|kick)$
  8440. ^/_matrix/client/(api/v1|r0|v3|unstable)/join/
  8441. ^/_matrix/client/(api/v1|r0|v3|unstable)/profile/
  8442. </code></pre>
  8443. <p>Additionally, the following REST endpoints can be handled for GET requests:</p>
  8444. <pre><code>^/_matrix/federation/v1/groups/
  8445. </code></pre>
  8446. <p>Pagination requests can also be handled, but all requests for a given
  8447. room must be routed to the same instance. Additionally, care must be taken to
  8448. ensure that the purge history admin API is not used while pagination requests
  8449. for the room are in flight:</p>
  8450. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/rooms/.*/messages$
  8451. </code></pre>
  8452. <p>Additionally, the following endpoints should be included if Synapse is configured
  8453. to use SSO (you only need to include the ones for whichever SSO provider you're
  8454. using):</p>
  8455. <pre><code># for all SSO providers
  8456. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/sso/redirect
  8457. ^/_synapse/client/pick_idp$
  8458. ^/_synapse/client/pick_username
  8459. ^/_synapse/client/new_user_consent$
  8460. ^/_synapse/client/sso_register$
  8461. # OpenID Connect requests.
  8462. ^/_synapse/client/oidc/callback$
  8463. # SAML requests.
  8464. ^/_synapse/client/saml2/authn_response$
  8465. # CAS requests.
  8466. ^/_matrix/client/(api/v1|r0|v3|unstable)/login/cas/ticket$
  8467. </code></pre>
  8468. <p>Ensure that all SSO logins go to a single process.
  8469. For multiple workers not handling the SSO endpoints properly, see
  8470. <a href="https://github.com/matrix-org/synapse/issues/7530">#7530</a> and
  8471. <a href="https://github.com/matrix-org/synapse/issues/9427">#9427</a>.</p>
  8472. <p>Note that a HTTP listener with <code>client</code> and <code>federation</code> resources must be
  8473. configured in the <code>worker_listeners</code> option in the worker config.</p>
  8474. <h4 id="load-balancing"><a class="header" href="#load-balancing">Load balancing</a></h4>
  8475. <p>It is possible to run multiple instances of this worker app, with incoming requests
  8476. being load-balanced between them by the reverse-proxy. However, different endpoints
  8477. have different characteristics and so admins
  8478. may wish to run multiple groups of workers handling different endpoints so that
  8479. load balancing can be done in different ways.</p>
  8480. <p>For <code>/sync</code> and <code>/initialSync</code> requests it will be more efficient if all
  8481. requests from a particular user are routed to a single instance. Extracting a
  8482. user ID from the access token or <code>Authorization</code> header is currently left as an
  8483. exercise for the reader. Admins may additionally wish to separate out <code>/sync</code>
  8484. requests that have a <code>since</code> query parameter from those that don't (and
  8485. <code>/initialSync</code>), as requests that don't are known as &quot;initial sync&quot; that happens
  8486. when a user logs in on a new device and can be <em>very</em> resource intensive, so
  8487. isolating these requests will stop them from interfering with other users ongoing
  8488. syncs.</p>
  8489. <p>Federation and client requests can be balanced via simple round robin.</p>
  8490. <p>The inbound federation transaction request <code>^/_matrix/federation/v1/send/</code>
  8491. should be balanced by source IP so that transactions from the same remote server
  8492. go to the same process.</p>
  8493. <p>Registration/login requests can be handled separately purely to help ensure that
  8494. unexpected load doesn't affect new logins and sign ups.</p>
  8495. <p>Finally, event sending requests can be balanced by the room ID in the URI (or
  8496. the full URI, or even just round robin), the room ID is the path component after
  8497. <code>/rooms/</code>. If there is a large bridge connected that is sending or may send lots
  8498. of events, then a dedicated set of workers can be provisioned to limit the
  8499. effects of bursts of events from that bridge on events sent by normal users.</p>
  8500. <h4 id="stream-writers"><a class="header" href="#stream-writers">Stream writers</a></h4>
  8501. <p>Additionally, there is <em>experimental</em> support for moving writing of specific
  8502. streams (such as events) off of the main process to a particular worker. (This
  8503. is only supported with Redis-based replication.)</p>
  8504. <p>Currently supported streams are <code>events</code> and <code>typing</code>.</p>
  8505. <p>To enable this, the worker must have a HTTP replication listener configured,
  8506. have a <code>worker_name</code> and be listed in the <code>instance_map</code> config. For example to
  8507. move event persistence off to a dedicated worker, the shared configuration would
  8508. include:</p>
  8509. <pre><code class="language-yaml">instance_map:
  8510. event_persister1:
  8511. host: localhost
  8512. port: 8034
  8513. stream_writers:
  8514. events: event_persister1
  8515. </code></pre>
  8516. <p>The <code>events</code> stream also experimentally supports having multiple writers, where
  8517. work is sharded between them by room ID. Note that you <em>must</em> restart all worker
  8518. instances when adding or removing event persisters. An example <code>stream_writers</code>
  8519. configuration with multiple writers:</p>
  8520. <pre><code class="language-yaml">stream_writers:
  8521. events:
  8522. - event_persister1
  8523. - event_persister2
  8524. </code></pre>
  8525. <h4 id="background-tasks"><a class="header" href="#background-tasks">Background tasks</a></h4>
  8526. <p>There is also <em>experimental</em> support for moving background tasks to a separate
  8527. worker. Background tasks are run periodically or started via replication. Exactly
  8528. which tasks are configured to run depends on your Synapse configuration (e.g. if
  8529. stats is enabled).</p>
  8530. <p>To enable this, the worker must have a <code>worker_name</code> and can be configured to run
  8531. background tasks. For example, to move background tasks to a dedicated worker,
  8532. the shared configuration would include:</p>
  8533. <pre><code class="language-yaml">run_background_tasks_on: background_worker
  8534. </code></pre>
  8535. <p>You might also wish to investigate the <code>update_user_directory</code> and
  8536. <code>media_instance_running_background_jobs</code> settings.</p>
  8537. <h3 id="synapseapppusher"><a class="header" href="#synapseapppusher"><code>synapse.app.pusher</code></a></h3>
  8538. <p>Handles sending push notifications to sygnal and email. Doesn't handle any
  8539. REST endpoints itself, but you should set <code>start_pushers: False</code> in the
  8540. shared configuration file to stop the main synapse sending push notifications.</p>
  8541. <p>To run multiple instances at once the <code>pusher_instances</code> option should list all
  8542. pusher instances by their worker name, e.g.:</p>
  8543. <pre><code class="language-yaml">pusher_instances:
  8544. - pusher_worker1
  8545. - pusher_worker2
  8546. </code></pre>
  8547. <h3 id="synapseappappservice"><a class="header" href="#synapseappappservice"><code>synapse.app.appservice</code></a></h3>
  8548. <p>Handles sending output traffic to Application Services. Doesn't handle any
  8549. REST endpoints itself, but you should set <code>notify_appservices: False</code> in the
  8550. shared configuration file to stop the main synapse sending appservice notifications.</p>
  8551. <p>Note this worker cannot be load-balanced: only one instance should be active.</p>
  8552. <h3 id="synapseappfederation_sender"><a class="header" href="#synapseappfederation_sender"><code>synapse.app.federation_sender</code></a></h3>
  8553. <p>Handles sending federation traffic to other servers. Doesn't handle any
  8554. REST endpoints itself, but you should set <code>send_federation: False</code> in the
  8555. shared configuration file to stop the main synapse sending this traffic.</p>
  8556. <p>If running multiple federation senders then you must list each
  8557. instance in the <code>federation_sender_instances</code> option by their <code>worker_name</code>.
  8558. All instances must be stopped and started when adding or removing instances.
  8559. For example:</p>
  8560. <pre><code class="language-yaml">federation_sender_instances:
  8561. - federation_sender1
  8562. - federation_sender2
  8563. </code></pre>
  8564. <h3 id="synapseappmedia_repository"><a class="header" href="#synapseappmedia_repository"><code>synapse.app.media_repository</code></a></h3>
  8565. <p>Handles the media repository. It can handle all endpoints starting with:</p>
  8566. <pre><code>/_matrix/media/
  8567. </code></pre>
  8568. <p>... and the following regular expressions matching media-specific administration APIs:</p>
  8569. <pre><code>^/_synapse/admin/v1/purge_media_cache$
  8570. ^/_synapse/admin/v1/room/.*/media.*$
  8571. ^/_synapse/admin/v1/user/.*/media.*$
  8572. ^/_synapse/admin/v1/media/.*$
  8573. ^/_synapse/admin/v1/quarantine_media/.*$
  8574. ^/_synapse/admin/v1/users/.*/media$
  8575. </code></pre>
  8576. <p>You should also set <code>enable_media_repo: False</code> in the shared configuration
  8577. file to stop the main synapse running background jobs related to managing the
  8578. media repository. Note that doing so will prevent the main process from being
  8579. able to handle the above endpoints.</p>
  8580. <p>In the <code>media_repository</code> worker configuration file, configure the http listener to
  8581. expose the <code>media</code> resource. For example:</p>
  8582. <pre><code class="language-yaml">worker_listeners:
  8583. - type: http
  8584. port: 8085
  8585. resources:
  8586. - names:
  8587. - media
  8588. </code></pre>
  8589. <p>Note that if running multiple media repositories they must be on the same server
  8590. and you must configure a single instance to run the background tasks, e.g.:</p>
  8591. <pre><code class="language-yaml">media_instance_running_background_jobs: &quot;media-repository-1&quot;
  8592. </code></pre>
  8593. <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>
  8594. <h3 id="synapseappuser_dir"><a class="header" href="#synapseappuser_dir"><code>synapse.app.user_dir</code></a></h3>
  8595. <p>Handles searches in the user directory. It can handle REST endpoints matching
  8596. the following regular expressions:</p>
  8597. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/user_directory/search$
  8598. </code></pre>
  8599. <p>When using this worker you must also set <code>update_user_directory: False</code> in the
  8600. shared configuration file to stop the main synapse running background
  8601. jobs related to updating the user directory.</p>
  8602. <h3 id="synapseappfrontend_proxy"><a class="header" href="#synapseappfrontend_proxy"><code>synapse.app.frontend_proxy</code></a></h3>
  8603. <p>Proxies some frequently-requested client endpoints to add caching and remove
  8604. load from the main synapse. It can handle REST endpoints matching the following
  8605. regular expressions:</p>
  8606. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/keys/upload
  8607. </code></pre>
  8608. <p>If <code>use_presence</code> is False in the homeserver config, it can also handle REST
  8609. endpoints matching the following regular expressions:</p>
  8610. <pre><code>^/_matrix/client/(api/v1|r0|v3|unstable)/presence/[^/]+/status
  8611. </code></pre>
  8612. <p>This &quot;stub&quot; presence handler will pass through <code>GET</code> request but make the
  8613. <code>PUT</code> effectively a no-op.</p>
  8614. <p>It will proxy any requests it cannot handle to the main synapse instance. It
  8615. must therefore be configured with the location of the main instance, via
  8616. the <code>worker_main_http_uri</code> setting in the <code>frontend_proxy</code> worker configuration
  8617. file. For example:</p>
  8618. <pre><code class="language-yaml">worker_main_http_uri: http://127.0.0.1:8008
  8619. </code></pre>
  8620. <h3 id="historical-apps"><a class="header" href="#historical-apps">Historical apps</a></h3>
  8621. <p><em>Note:</em> Historically there used to be more apps, however they have been
  8622. amalgamated into a single <code>synapse.app.generic_worker</code> app. The remaining apps
  8623. are ones that do specific processing unrelated to requests, e.g. the <code>pusher</code>
  8624. that handles sending out push notifications for new events. The intention is for
  8625. all these to be folded into the <code>generic_worker</code> app and to use config to define
  8626. which processes handle the various proccessing such as push notifications.</p>
  8627. <h2 id="migration-from-old-config"><a class="header" href="#migration-from-old-config">Migration from old config</a></h2>
  8628. <p>There are two main independent changes that have been made: introducing Redis
  8629. support and merging apps into <code>synapse.app.generic_worker</code>. Both these changes
  8630. are backwards compatible and so no changes to the config are required, however
  8631. server admins are encouraged to plan to migrate to Redis as the old style direct
  8632. TCP replication config is deprecated.</p>
  8633. <p>To migrate to Redis add the <code>redis</code> config as above, and optionally remove the
  8634. TCP <code>replication</code> listener from master and <code>worker_replication_port</code> from worker
  8635. config.</p>
  8636. <p>To migrate apps to use <code>synapse.app.generic_worker</code> simply update the
  8637. <code>worker_app</code> option in the worker configs, and where worker are started (e.g.
  8638. in systemd service files, but not required for synctl).</p>
  8639. <h2 id="architectural-diagram"><a class="header" href="#architectural-diagram">Architectural diagram</a></h2>
  8640. <p>The following shows an example setup using Redis and a reverse proxy:</p>
  8641. <pre><code> Clients &amp; Federation
  8642. |
  8643. v
  8644. +-----------+
  8645. | |
  8646. | Reverse |
  8647. | Proxy |
  8648. | |
  8649. +-----------+
  8650. | | |
  8651. | | | HTTP requests
  8652. +-------------------+ | +-----------+
  8653. | +---+ |
  8654. | | |
  8655. v v v
  8656. +--------------+ +--------------+ +--------------+ +--------------+
  8657. | Main | | Generic | | Generic | | Event |
  8658. | Process | | Worker 1 | | Worker 2 | | Persister |
  8659. +--------------+ +--------------+ +--------------+ +--------------+
  8660. ^ ^ | ^ | | ^ | ^ ^
  8661. | | | | | | | | | |
  8662. | | | | | HTTP | | | | |
  8663. | +----------+&lt;--|---|---------+ | | | |
  8664. | | +-------------|--&gt;+----------+ |
  8665. | | | |
  8666. | | | |
  8667. v v v v
  8668. ====================================================================
  8669. Redis pub/sub channel
  8670. </code></pre>
  8671. <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>
  8672. <p>If you want to use <code>synctl</code> to manage your synapse processes, you will need to
  8673. create an an additional configuration file for the main synapse process. That
  8674. configuration should look like this:</p>
  8675. <pre><code class="language-yaml">worker_app: synapse.app.homeserver
  8676. </code></pre>
  8677. <p>Additionally, each worker app must be configured with the name of a &quot;pid file&quot;,
  8678. to which it will write its process ID when it starts. For example, for a
  8679. synchrotron, you might write:</p>
  8680. <pre><code class="language-yaml">worker_pid_file: /home/matrix/synapse/worker1.pid
  8681. </code></pre>
  8682. <p>Finally, to actually run your worker-based synapse, you must pass synctl the <code>-a</code>
  8683. commandline option to tell it to operate on all the worker configurations found
  8684. in the given directory, e.g.:</p>
  8685. <pre><code class="language-sh">synctl -a $CONFIG/workers start
  8686. </code></pre>
  8687. <p>Currently one should always restart all workers when restarting or upgrading
  8688. synapse, unless you explicitly know it's safe not to. For instance, restarting
  8689. synapse without restarting all the synchrotrons may result in broken typing
  8690. notifications.</p>
  8691. <p>To manipulate a specific worker, you pass the -w option to synctl:</p>
  8692. <pre><code class="language-sh">synctl -w $CONFIG/workers/worker1.yaml restart
  8693. </code></pre>
  8694. <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>
  8695. <p>This is a setup for managing synapse with systemd, including support for
  8696. managing workers. It provides a <code>matrix-synapse</code> service for the master, as
  8697. well as a <code>matrix-synapse-worker@</code> service template for any workers you
  8698. require. Additionally, to group the required services, it sets up a
  8699. <code>matrix-synapse.target</code>.</p>
  8700. <p>See the folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/system/">system</a>
  8701. for the systemd unit files.</p>
  8702. <p>The folder <a href="https://github.com/matrix-org/synapse/tree/develop/docs/systemd-with-workers/workers/">workers</a>
  8703. contains an example configuration for the <code>federation_reader</code> worker.</p>
  8704. <h2 id="synapse-configuration-files"><a class="header" href="#synapse-configuration-files">Synapse configuration files</a></h2>
  8705. <p>See <a href="systemd-with-workers/../workers.html">the worker documentation</a> for information on how to set up the
  8706. configuration files and reverse-proxy correctly.
  8707. Below is a sample <code>federation_reader</code> worker configuration file.</p>
  8708. <pre><code class="language-yaml">worker_app: synapse.app.federation_reader
  8709. worker_name: federation_reader1
  8710. worker_replication_host: 127.0.0.1
  8711. worker_replication_http_port: 9093
  8712. worker_listeners:
  8713. - type: http
  8714. port: 8011
  8715. resources:
  8716. - names: [federation]
  8717. worker_log_config: /etc/matrix-synapse/federation-reader-log.yaml
  8718. </code></pre>
  8719. <p>Systemd manages daemonization itself, so ensure that none of the configuration
  8720. files set either <code>daemonize</code> or <code>worker_daemonize</code>.</p>
  8721. <p>The config files of all workers are expected to be located in
  8722. <code>/etc/matrix-synapse/workers</code>. If you want to use a different location, edit
  8723. the provided <code>*.service</code> files accordingly.</p>
  8724. <p>There is no need for a separate configuration file for the master process.</p>
  8725. <h2 id="set-up"><a class="header" href="#set-up">Set up</a></h2>
  8726. <ol>
  8727. <li>Adjust synapse configuration files as above.</li>
  8728. <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>
  8729. to <code>/etc/systemd/system</code>.</li>
  8730. <li>Run <code>systemctl daemon-reload</code> to tell systemd to load the new unit files.</li>
  8731. <li>Run <code>systemctl enable matrix-synapse.service</code>. This will configure the
  8732. synapse master process to be started as part of the <code>matrix-synapse.target</code>
  8733. target.</li>
  8734. <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
  8735. should be a corresponding configuration file.
  8736. <code>/etc/matrix-synapse/workers/&lt;worker_name&gt;.yaml</code>.</li>
  8737. <li>Start all the synapse processes with <code>systemctl start matrix-synapse.target</code>.</li>
  8738. <li>Tell systemd to start synapse on boot with <code>systemctl enable matrix-synapse.target</code>.</li>
  8739. </ol>
  8740. <h2 id="usage"><a class="header" href="#usage">Usage</a></h2>
  8741. <p>Once the services are correctly set up, you can use the following commands
  8742. to manage your synapse installation:</p>
  8743. <pre><code class="language-sh"># Restart Synapse master and all workers
  8744. systemctl restart matrix-synapse.target
  8745. # Stop Synapse and all workers
  8746. systemctl stop matrix-synapse.target
  8747. # Restart the master alone
  8748. systemctl start matrix-synapse.service
  8749. # Restart a specific worker (eg. federation_reader); the master is
  8750. # unaffected by this.
  8751. systemctl restart matrix-synapse-worker@federation_reader.service
  8752. # Add a new worker (assuming all configs are set up already)
  8753. systemctl enable matrix-synapse-worker@federation_writer.service
  8754. systemctl restart matrix-synapse.target
  8755. </code></pre>
  8756. <h2 id="hardening"><a class="header" href="#hardening">Hardening</a></h2>
  8757. <p><strong>Optional:</strong> If further hardening is desired, the file
  8758. <code>override-hardened.conf</code> may be copied from
  8759. <a href="https://github.com/matrix-org/synapse/tree/develop/contrib/systemd/">contrib/systemd/override-hardened.conf</a>
  8760. in this repository to the location
  8761. <code>/etc/systemd/system/matrix-synapse.service.d/override-hardened.conf</code> (the
  8762. directory may have to be created). It enables certain sandboxing features in
  8763. systemd to further secure the synapse service. You may read the comments to
  8764. understand what the override file is doing. The same file will need to be copied to
  8765. <code>/etc/systemd/system/matrix-synapse-worker@.service.d/override-hardened-worker.conf</code>
  8766. (this directory may also have to be created) in order to apply the same
  8767. hardening options to any worker processes.</p>
  8768. <p>Once these files have been copied to their appropriate locations, simply reload
  8769. systemd's manager config files and restart all Synapse services to apply the hardening options. They will automatically
  8770. be applied at every restart as long as the override files are present at the
  8771. specified locations.</p>
  8772. <pre><code class="language-sh">systemctl daemon-reload
  8773. # Restart services
  8774. systemctl restart matrix-synapse.target
  8775. </code></pre>
  8776. <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
  8777. the changes being applied at a glance.</p>
  8778. <div style="break-before: page; page-break-before: always;"></div><h1 id="administration"><a class="header" href="#administration">Administration</a></h1>
  8779. <p>This section contains information on managing your Synapse homeserver. This includes:</p>
  8780. <ul>
  8781. <li>Managing users, rooms and media via the Admin API.</li>
  8782. <li>Setting up metrics and monitoring to give you insight into your homeserver's health.</li>
  8783. <li>Configuring structured logging.</li>
  8784. </ul>
  8785. <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>
  8786. <h2 id="authenticate-as-a-server-admin"><a class="header" href="#authenticate-as-a-server-admin">Authenticate as a server admin</a></h2>
  8787. <p>Many of the API calls in the admin api will require an <code>access_token</code> for a
  8788. server admin. (Note that a server admin is distinct from a room admin.)</p>
  8789. <p>A user can be marked as a server admin by updating the database directly, e.g.:</p>
  8790. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  8791. </code></pre>
  8792. <p>A new server admin user can also be created using the <code>register_new_matrix_user</code>
  8793. command. This is a script that is located in the <code>scripts/</code> directory, or possibly
  8794. already on your <code>$PATH</code> depending on how Synapse was installed.</p>
  8795. <p>Finding your user's <code>access_token</code> is client-dependent, but will usually be shown in the client's settings.</p>
  8796. <h2 id="making-an-admin-api-request"><a class="header" href="#making-an-admin-api-request">Making an Admin API request</a></h2>
  8797. <p>Once you have your <code>access_token</code>, you will need to authenticate each request to an Admin API endpoint by
  8798. providing the token as either a query parameter or a request header. To add it as a request header in cURL:</p>
  8799. <pre><code class="language-sh">curl --header &quot;Authorization: Bearer &lt;access_token&gt;&quot; &lt;the_rest_of_your_API_request&gt;
  8800. </code></pre>
  8801. <p>For more details on access tokens in Matrix, please refer to the complete
  8802. <a href="https://matrix.org/docs/spec/client_server/r0.6.1#using-access-tokens">matrix spec documentation</a>.</p>
  8803. <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>
  8804. <p>This API allows a server administrator to manage the validity of an account. To
  8805. use it, you must enable the account validity feature (under
  8806. <code>account_validity</code>) in Synapse's configuration.</p>
  8807. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  8808. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  8809. <h2 id="renew-account"><a class="header" href="#renew-account">Renew account</a></h2>
  8810. <p>This API extends the validity of an account by as much time as configured in the
  8811. <code>period</code> parameter from the <code>account_validity</code> configuration.</p>
  8812. <p>The API is:</p>
  8813. <pre><code>POST /_synapse/admin/v1/account_validity/validity
  8814. </code></pre>
  8815. <p>with the following body:</p>
  8816. <pre><code class="language-json">{
  8817. &quot;user_id&quot;: &quot;&lt;user ID for the account to renew&gt;&quot;,
  8818. &quot;expiration_ts&quot;: 0,
  8819. &quot;enable_renewal_emails&quot;: true
  8820. }
  8821. </code></pre>
  8822. <p><code>expiration_ts</code> is an optional parameter and overrides the expiration date,
  8823. which otherwise defaults to now + validity period.</p>
  8824. <p><code>enable_renewal_emails</code> is also an optional parameter and enables/disables
  8825. sending renewal emails to the user. Defaults to true.</p>
  8826. <p>The API returns with the new expiration date for this account, as a timestamp in
  8827. milliseconds since epoch:</p>
  8828. <pre><code class="language-json">{
  8829. &quot;expiration_ts&quot;: 0
  8830. }
  8831. </code></pre>
  8832. <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>
  8833. <p>This API allows a server administrator to manage the background updates being
  8834. run against the database.</p>
  8835. <h2 id="status"><a class="header" href="#status">Status</a></h2>
  8836. <p>This API gets the current status of the background updates.</p>
  8837. <p>The API is:</p>
  8838. <pre><code>GET /_synapse/admin/v1/background_updates/status
  8839. </code></pre>
  8840. <p>Returning:</p>
  8841. <pre><code class="language-json">{
  8842. &quot;enabled&quot;: true,
  8843. &quot;current_updates&quot;: {
  8844. &quot;&lt;db_name&gt;&quot;: {
  8845. &quot;name&quot;: &quot;&lt;background_update_name&gt;&quot;,
  8846. &quot;total_item_count&quot;: 50,
  8847. &quot;total_duration_ms&quot;: 10000.0,
  8848. &quot;average_items_per_ms&quot;: 2.2,
  8849. },
  8850. }
  8851. }
  8852. </code></pre>
  8853. <p><code>enabled</code> whether the background updates are enabled or disabled.</p>
  8854. <p><code>db_name</code> the database name (usually Synapse is configured with a single database named 'master').</p>
  8855. <p>For each update:</p>
  8856. <p><code>name</code> the name of the update.
  8857. <code>total_item_count</code> total number of &quot;items&quot; processed (the meaning of 'items' depends on the update in question).
  8858. <code>total_duration_ms</code> how long the background process has been running, not including time spent sleeping.
  8859. <code>average_items_per_ms</code> how many items are processed per millisecond based on an exponential average.</p>
  8860. <h2 id="enabled"><a class="header" href="#enabled">Enabled</a></h2>
  8861. <p>This API allow pausing background updates.</p>
  8862. <p>Background updates should <em>not</em> be paused for significant periods of time, as
  8863. this can affect the performance of Synapse.</p>
  8864. <p><em>Note</em>: This won't persist over restarts.</p>
  8865. <p><em>Note</em>: This won't cancel any update query that is currently running. This is
  8866. usually fine since most queries are short lived, except for <code>CREATE INDEX</code>
  8867. background updates which won't be cancelled once started.</p>
  8868. <p>The API is:</p>
  8869. <pre><code>POST /_synapse/admin/v1/background_updates/enabled
  8870. </code></pre>
  8871. <p>with the following body:</p>
  8872. <pre><code class="language-json">{
  8873. &quot;enabled&quot;: false
  8874. }
  8875. </code></pre>
  8876. <p><code>enabled</code> sets whether the background updates are enabled or disabled.</p>
  8877. <p>The API returns the <code>enabled</code> param.</p>
  8878. <pre><code class="language-json">{
  8879. &quot;enabled&quot;: false
  8880. }
  8881. </code></pre>
  8882. <p>There is also a <code>GET</code> version which returns the <code>enabled</code> state.</p>
  8883. <h2 id="run"><a class="header" href="#run">Run</a></h2>
  8884. <p>This API schedules a specific background update to run. The job starts immediately after calling the API.</p>
  8885. <p>The API is:</p>
  8886. <pre><code>POST /_synapse/admin/v1/background_updates/start_job
  8887. </code></pre>
  8888. <p>with the following body:</p>
  8889. <pre><code class="language-json">{
  8890. &quot;job_name&quot;: &quot;populate_stats_process_rooms&quot;
  8891. }
  8892. </code></pre>
  8893. <p>The following JSON body parameters are available:</p>
  8894. <ul>
  8895. <li><code>job_name</code> - A string which job to run. Valid values are:
  8896. <ul>
  8897. <li><code>populate_stats_process_rooms</code> - Recalculate the stats for all rooms.</li>
  8898. <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>
  8899. </ul>
  8900. </li>
  8901. </ul>
  8902. <div style="break-before: page; page-break-before: always;"></div><h1 id="delete-a-local-group"><a class="header" href="#delete-a-local-group">Delete a local group</a></h1>
  8903. <p>This API lets a server admin delete a local group. Doing so will kick all
  8904. users out of the group so that their clients will correctly handle the group
  8905. being deleted.</p>
  8906. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  8907. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  8908. <p>The API is:</p>
  8909. <pre><code>POST /_synapse/admin/v1/delete_group/&lt;group_id&gt;
  8910. </code></pre>
  8911. <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>
  8912. <p>This API returns information about reported events.</p>
  8913. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  8914. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  8915. <p>The api is:</p>
  8916. <pre><code>GET /_synapse/admin/v1/event_reports?from=0&amp;limit=10
  8917. </code></pre>
  8918. <p>It returns a JSON body like the following:</p>
  8919. <pre><code class="language-json">{
  8920. &quot;event_reports&quot;: [
  8921. {
  8922. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  8923. &quot;id&quot;: 2,
  8924. &quot;reason&quot;: &quot;foo&quot;,
  8925. &quot;score&quot;: -100,
  8926. &quot;received_ts&quot;: 1570897107409,
  8927. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  8928. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  8929. &quot;name&quot;: &quot;Matrix HQ&quot;,
  8930. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  8931. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  8932. },
  8933. {
  8934. &quot;event_id&quot;: &quot;$3IcdZsDaN_En-S1DF4EMCy3v4gNRKeOJs8W5qTOKj4I&quot;,
  8935. &quot;id&quot;: 3,
  8936. &quot;reason&quot;: &quot;bar&quot;,
  8937. &quot;score&quot;: -100,
  8938. &quot;received_ts&quot;: 1598889612059,
  8939. &quot;canonical_alias&quot;: &quot;#alias2:matrix.org&quot;,
  8940. &quot;room_id&quot;: &quot;!eGvUQuTCkHGVwNMOjv:matrix.org&quot;,
  8941. &quot;name&quot;: &quot;Your room name here&quot;,
  8942. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  8943. &quot;user_id&quot;: &quot;@bar:matrix.org&quot;
  8944. }
  8945. ],
  8946. &quot;next_token&quot;: 2,
  8947. &quot;total&quot;: 4
  8948. }
  8949. </code></pre>
  8950. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again with <code>from</code>
  8951. set to the value of <code>next_token</code>. This will return a new page.</p>
  8952. <p>If the endpoint does not return a <code>next_token</code> then there are no more reports to
  8953. paginate through.</p>
  8954. <p><strong>URL parameters:</strong></p>
  8955. <ul>
  8956. <li><code>limit</code>: integer - Is optional but is used for pagination, denoting the maximum number
  8957. of items to return in this call. Defaults to <code>100</code>.</li>
  8958. <li><code>from</code>: integer - Is optional but used for pagination, denoting the offset in the
  8959. returned results. This should be treated as an opaque value and not explicitly set to
  8960. anything other than the return value of <code>next_token</code> from a previous call. Defaults to <code>0</code>.</li>
  8961. <li><code>dir</code>: string - Direction of event report order. Whether to fetch the most recent
  8962. first (<code>b</code>) or the oldest first (<code>f</code>). Defaults to <code>b</code>.</li>
  8963. <li><code>user_id</code>: string - Is optional and filters to only return users with user IDs that
  8964. contain this value. This is the user who reported the event and wrote the reason.</li>
  8965. <li><code>room_id</code>: string - Is optional and filters to only return rooms with room IDs that
  8966. contain this value.</li>
  8967. </ul>
  8968. <p><strong>Response</strong></p>
  8969. <p>The following fields are returned in the JSON response body:</p>
  8970. <ul>
  8971. <li><code>id</code>: integer - ID of event report.</li>
  8972. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  8973. report was sent.</li>
  8974. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  8975. <li><code>name</code>: string - The name of the room.</li>
  8976. <li><code>event_id</code>: string - The ID of the reported event.</li>
  8977. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  8978. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank or <code>null</code>.</li>
  8979. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  8980. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;. May be <code>null</code>.</li>
  8981. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  8982. was reported.</li>
  8983. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  8984. have a canonical alias set.</li>
  8985. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  8986. <li><code>total</code>: integer - Total number of event reports related to the query
  8987. (<code>user_id</code> and <code>room_id</code>).</li>
  8988. </ul>
  8989. <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>
  8990. <p>This API returns information about a specific event report.</p>
  8991. <p>The api is:</p>
  8992. <pre><code>GET /_synapse/admin/v1/event_reports/&lt;report_id&gt;
  8993. </code></pre>
  8994. <p>It returns a JSON body like the following:</p>
  8995. <pre><code class="language-json">{
  8996. &quot;event_id&quot;: &quot;$bNUFCwGzWca1meCGkjp-zwslF-GfVcXukvRLI1_FaVY&quot;,
  8997. &quot;event_json&quot;: {
  8998. &quot;auth_events&quot;: [
  8999. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;,
  9000. &quot;$oggsNXxzPFRE3y53SUNd7nsj69-QzKv03a1RucHu-ws&quot;
  9001. ],
  9002. &quot;content&quot;: {
  9003. &quot;body&quot;: &quot;matrix.org: This Week in Matrix&quot;,
  9004. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  9005. &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;,
  9006. &quot;msgtype&quot;: &quot;m.notice&quot;
  9007. },
  9008. &quot;depth&quot;: 546,
  9009. &quot;hashes&quot;: {
  9010. &quot;sha256&quot;: &quot;xK1//xnmvHJIOvbgXlkI8eEqdvoMmihVDJ9J4SNlsAw&quot;
  9011. },
  9012. &quot;origin&quot;: &quot;matrix.org&quot;,
  9013. &quot;origin_server_ts&quot;: 1592291711430,
  9014. &quot;prev_events&quot;: [
  9015. &quot;$YK4arsKKcc0LRoe700pS8DSjOvUT4NDv0HfInlMFw2M&quot;
  9016. ],
  9017. &quot;prev_state&quot;: [],
  9018. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  9019. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  9020. &quot;signatures&quot;: {
  9021. &quot;matrix.org&quot;: {
  9022. &quot;ed25519:a_JaEG&quot;: &quot;cs+OUKW/iHx5pEidbWxh0UiNNHwe46Ai9LwNz+Ah16aWDNszVIe2gaAcVZfvNsBhakQTew51tlKmL2kspXk/Dg&quot;
  9023. }
  9024. },
  9025. &quot;type&quot;: &quot;m.room.message&quot;,
  9026. &quot;unsigned&quot;: {
  9027. &quot;age_ts&quot;: 1592291711430
  9028. }
  9029. },
  9030. &quot;id&quot;: &lt;report_id&gt;,
  9031. &quot;reason&quot;: &quot;foo&quot;,
  9032. &quot;score&quot;: -100,
  9033. &quot;received_ts&quot;: 1570897107409,
  9034. &quot;canonical_alias&quot;: &quot;#alias1:matrix.org&quot;,
  9035. &quot;room_id&quot;: &quot;!ERAgBpSOcCCuTJqQPk:matrix.org&quot;,
  9036. &quot;name&quot;: &quot;Matrix HQ&quot;,
  9037. &quot;sender&quot;: &quot;@foobar:matrix.org&quot;,
  9038. &quot;user_id&quot;: &quot;@foo:matrix.org&quot;
  9039. }
  9040. </code></pre>
  9041. <p><strong>URL parameters:</strong></p>
  9042. <ul>
  9043. <li><code>report_id</code>: string - The ID of the event report.</li>
  9044. </ul>
  9045. <p><strong>Response</strong></p>
  9046. <p>The following fields are returned in the JSON response body:</p>
  9047. <ul>
  9048. <li><code>id</code>: integer - ID of event report.</li>
  9049. <li><code>received_ts</code>: integer - The timestamp (in milliseconds since the unix epoch) when this
  9050. report was sent.</li>
  9051. <li><code>room_id</code>: string - The ID of the room in which the event being reported is located.</li>
  9052. <li><code>name</code>: string - The name of the room.</li>
  9053. <li><code>event_id</code>: string - The ID of the reported event.</li>
  9054. <li><code>user_id</code>: string - This is the user who reported the event and wrote the reason.</li>
  9055. <li><code>reason</code>: string - Comment made by the <code>user_id</code> in this report. May be blank.</li>
  9056. <li><code>score</code>: integer - Content is reported based upon a negative score, where -100 is
  9057. &quot;most offensive&quot; and 0 is &quot;inoffensive&quot;.</li>
  9058. <li><code>sender</code>: string - This is the ID of the user who sent the original message/event that
  9059. was reported.</li>
  9060. <li><code>canonical_alias</code>: string - The canonical alias of the room. <code>null</code> if the room does not
  9061. have a canonical alias set.</li>
  9062. <li><code>event_json</code>: object - Details of the original event that was reported.</li>
  9063. </ul>
  9064. <div style="break-before: page; page-break-before: always;"></div><h1 id="querying-media"><a class="header" href="#querying-media">Querying media</a></h1>
  9065. <p>These APIs allow extracting media information from the homeserver.</p>
  9066. <p>Details about the format of the <code>media_id</code> and storage of the media in the file system
  9067. are documented under <a href="admin_api/../media_repository.html">media repository</a>.</p>
  9068. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  9069. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  9070. <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>
  9071. <p>This API gets a list of known media in a room.
  9072. However, it only shows media from unencrypted events or rooms.</p>
  9073. <p>The API is:</p>
  9074. <pre><code>GET /_synapse/admin/v1/room/&lt;room_id&gt;/media
  9075. </code></pre>
  9076. <p>The API returns a JSON body like the following:</p>
  9077. <pre><code class="language-json">{
  9078. &quot;local&quot;: [
  9079. &quot;mxc://localhost/xwvutsrqponmlkjihgfedcba&quot;,
  9080. &quot;mxc://localhost/abcdefghijklmnopqrstuvwx&quot;
  9081. ],
  9082. &quot;remote&quot;: [
  9083. &quot;mxc://matrix.org/xwvutsrqponmlkjihgfedcba&quot;,
  9084. &quot;mxc://matrix.org/abcdefghijklmnopqrstuvwx&quot;
  9085. ]
  9086. }
  9087. </code></pre>
  9088. <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>
  9089. <p>Listing all media that has been uploaded by a local user can be achieved through
  9090. the use of the
  9091. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>
  9092. Admin API.</p>
  9093. <h1 id="quarantine-media"><a class="header" href="#quarantine-media">Quarantine media</a></h1>
  9094. <p>Quarantining media means that it is marked as inaccessible by users. It applies
  9095. to any local media, and any locally-cached copies of remote media.</p>
  9096. <p>The media file itself (and any thumbnails) is not deleted from the server.</p>
  9097. <h2 id="quarantining-media-by-id"><a class="header" href="#quarantining-media-by-id">Quarantining media by ID</a></h2>
  9098. <p>This API quarantines a single piece of local or remote media.</p>
  9099. <p>Request:</p>
  9100. <pre><code>POST /_synapse/admin/v1/media/quarantine/&lt;server_name&gt;/&lt;media_id&gt;
  9101. {}
  9102. </code></pre>
  9103. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  9104. form of <code>abcdefg12345...</code>.</p>
  9105. <p>Response:</p>
  9106. <pre><code class="language-json">{}
  9107. </code></pre>
  9108. <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>
  9109. <p>This API removes a single piece of local or remote media from quarantine.</p>
  9110. <p>Request:</p>
  9111. <pre><code>POST /_synapse/admin/v1/media/unquarantine/&lt;server_name&gt;/&lt;media_id&gt;
  9112. {}
  9113. </code></pre>
  9114. <p>Where <code>server_name</code> is in the form of <code>example.org</code>, and <code>media_id</code> is in the
  9115. form of <code>abcdefg12345...</code>.</p>
  9116. <p>Response:</p>
  9117. <pre><code class="language-json">{}
  9118. </code></pre>
  9119. <h2 id="quarantining-media-in-a-room"><a class="header" href="#quarantining-media-in-a-room">Quarantining media in a room</a></h2>
  9120. <p>This API quarantines all local and remote media in a room.</p>
  9121. <p>Request:</p>
  9122. <pre><code>POST /_synapse/admin/v1/room/&lt;room_id&gt;/media/quarantine
  9123. {}
  9124. </code></pre>
  9125. <p>Where <code>room_id</code> is in the form of <code>!roomid12345:example.org</code>.</p>
  9126. <p>Response:</p>
  9127. <pre><code class="language-json">{
  9128. &quot;num_quarantined&quot;: 10
  9129. }
  9130. </code></pre>
  9131. <p>The following fields are returned in the JSON response body:</p>
  9132. <ul>
  9133. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  9134. </ul>
  9135. <p>Note that there is a legacy endpoint, <code>POST /_synapse/admin/v1/quarantine_media/&lt;room_id&gt;</code>, that operates the same.
  9136. However, it is deprecated and may be removed in a future release.</p>
  9137. <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>
  9138. <p>This API quarantines all <em>local</em> media that a <em>local</em> user has uploaded. That is to say, if
  9139. you would like to quarantine media uploaded by a user on a remote homeserver, you should
  9140. instead use one of the other APIs.</p>
  9141. <p>Request:</p>
  9142. <pre><code>POST /_synapse/admin/v1/user/&lt;user_id&gt;/media/quarantine
  9143. {}
  9144. </code></pre>
  9145. <p>URL Parameters</p>
  9146. <ul>
  9147. <li><code>user_id</code>: string - User ID in the form of <code>@bob:example.org</code></li>
  9148. </ul>
  9149. <p>Response:</p>
  9150. <pre><code class="language-json">{
  9151. &quot;num_quarantined&quot;: 10
  9152. }
  9153. </code></pre>
  9154. <p>The following fields are returned in the JSON response body:</p>
  9155. <ul>
  9156. <li><code>num_quarantined</code>: integer - The number of media items successfully quarantined</li>
  9157. </ul>
  9158. <h2 id="protecting-media-from-being-quarantined"><a class="header" href="#protecting-media-from-being-quarantined">Protecting media from being quarantined</a></h2>
  9159. <p>This API protects a single piece of local media from being quarantined using the
  9160. above APIs. This is useful for sticker packs and other shared media which you do
  9161. not want to get quarantined, especially when
  9162. <a href="admin_api/media_admin_api.html#quarantining-media-in-a-room">quarantining media in a room</a>.</p>
  9163. <p>Request:</p>
  9164. <pre><code>POST /_synapse/admin/v1/media/protect/&lt;media_id&gt;
  9165. {}
  9166. </code></pre>
  9167. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  9168. <p>Response:</p>
  9169. <pre><code class="language-json">{}
  9170. </code></pre>
  9171. <h2 id="unprotecting-media-from-being-quarantined"><a class="header" href="#unprotecting-media-from-being-quarantined">Unprotecting media from being quarantined</a></h2>
  9172. <p>This API reverts the protection of a media.</p>
  9173. <p>Request:</p>
  9174. <pre><code>POST /_synapse/admin/v1/media/unprotect/&lt;media_id&gt;
  9175. {}
  9176. </code></pre>
  9177. <p>Where <code>media_id</code> is in the form of <code>abcdefg12345...</code>.</p>
  9178. <p>Response:</p>
  9179. <pre><code class="language-json">{}
  9180. </code></pre>
  9181. <h1 id="delete-local-media"><a class="header" href="#delete-local-media">Delete local media</a></h1>
  9182. <p>This API deletes the <em>local</em> media from the disk of your own server.
  9183. This includes any local thumbnails and copies of media downloaded from
  9184. remote homeservers.
  9185. This API will not affect media that has been uploaded to external
  9186. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).
  9187. See also <a href="admin_api/media_admin_api.html#purge-remote-media-api">Purge Remote Media API</a>.</p>
  9188. <h2 id="delete-a-specific-local-media"><a class="header" href="#delete-a-specific-local-media">Delete a specific local media</a></h2>
  9189. <p>Delete a specific <code>media_id</code>.</p>
  9190. <p>Request:</p>
  9191. <pre><code>DELETE /_synapse/admin/v1/media/&lt;server_name&gt;/&lt;media_id&gt;
  9192. {}
  9193. </code></pre>
  9194. <p>URL Parameters</p>
  9195. <ul>
  9196. <li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>)</li>
  9197. <li><code>media_id</code>: string - The ID of the media (e.g <code>abcdefghijklmnopqrstuvwx</code>)</li>
  9198. </ul>
  9199. <p>Response:</p>
  9200. <pre><code class="language-json">{
  9201. &quot;deleted_media&quot;: [
  9202. &quot;abcdefghijklmnopqrstuvwx&quot;
  9203. ],
  9204. &quot;total&quot;: 1
  9205. }
  9206. </code></pre>
  9207. <p>The following fields are returned in the JSON response body:</p>
  9208. <ul>
  9209. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  9210. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  9211. </ul>
  9212. <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>
  9213. <p>Request:</p>
  9214. <pre><code>POST /_synapse/admin/v1/media/&lt;server_name&gt;/delete?before_ts=&lt;before_ts&gt;
  9215. {}
  9216. </code></pre>
  9217. <p>URL Parameters</p>
  9218. <ul>
  9219. <li><code>server_name</code>: string - The name of your local server (e.g <code>matrix.org</code>).</li>
  9220. <li><code>before_ts</code>: string representing a positive integer - Unix timestamp in milliseconds.
  9221. Files that were last used before this timestamp will be deleted. It is the timestamp of
  9222. last access, not the timestamp when the file was created.</li>
  9223. <li><code>size_gt</code>: Optional - string representing a positive integer - Size of the media in bytes.
  9224. Files that are larger will be deleted. Defaults to <code>0</code>.</li>
  9225. <li><code>keep_profiles</code>: Optional - string representing a boolean - Switch to also delete files
  9226. that are still used in image data (e.g user profile, room avatar).
  9227. If <code>false</code> these files will be deleted. Defaults to <code>true</code>.</li>
  9228. </ul>
  9229. <p>Response:</p>
  9230. <pre><code class="language-json">{
  9231. &quot;deleted_media&quot;: [
  9232. &quot;abcdefghijklmnopqrstuvwx&quot;,
  9233. &quot;abcdefghijklmnopqrstuvwz&quot;
  9234. ],
  9235. &quot;total&quot;: 2
  9236. }
  9237. </code></pre>
  9238. <p>The following fields are returned in the JSON response body:</p>
  9239. <ul>
  9240. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  9241. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  9242. </ul>
  9243. <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>
  9244. <p>You can find details of how to delete multiple media uploaded by a user in
  9245. <a href="admin_api/user_admin_api.html#delete-media-uploaded-by-a-user">User Admin API</a>.</p>
  9246. <h1 id="purge-remote-media-api"><a class="header" href="#purge-remote-media-api">Purge Remote Media API</a></h1>
  9247. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  9248. <p>The API is:</p>
  9249. <pre><code>POST /_synapse/admin/v1/purge_media_cache?before_ts=&lt;unix_timestamp_in_ms&gt;
  9250. {}
  9251. </code></pre>
  9252. <p>URL Parameters</p>
  9253. <ul>
  9254. <li><code>unix_timestamp_in_ms</code>: string representing a positive integer - Unix timestamp in milliseconds.
  9255. All cached media that was last accessed before this timestamp will be removed.</li>
  9256. </ul>
  9257. <p>Response:</p>
  9258. <pre><code class="language-json">{
  9259. &quot;deleted&quot;: 10
  9260. }
  9261. </code></pre>
  9262. <p>The following fields are returned in the JSON response body:</p>
  9263. <ul>
  9264. <li><code>deleted</code>: integer - The number of media items successfully deleted</li>
  9265. </ul>
  9266. <p>If the user re-requests purged remote media, synapse will re-request the media
  9267. from the originating server.</p>
  9268. <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>
  9269. <p>The purge history API allows server admins to purge historic events from their
  9270. database, reclaiming disk space.</p>
  9271. <p>Depending on the amount of history being purged a call to the API may take
  9272. several minutes or longer. During this period users will not be able to
  9273. paginate further back in the room from the point being purged from.</p>
  9274. <p>Note that Synapse requires at least one message in each room, so it will never
  9275. delete the last message in a room.</p>
  9276. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  9277. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  9278. <p>The API is:</p>
  9279. <pre><code>POST /_synapse/admin/v1/purge_history/&lt;room_id&gt;[/&lt;event_id&gt;]
  9280. </code></pre>
  9281. <p>By default, events sent by local users are not deleted, as they may represent
  9282. the only copies of this content in existence. (Events sent by remote users are
  9283. deleted.)</p>
  9284. <p>Room state data (such as joins, leaves, topic) is always preserved.</p>
  9285. <p>To delete local message events as well, set <code>delete_local_events</code> in the body:</p>
  9286. <pre><code class="language-json">{
  9287. &quot;delete_local_events&quot;: true
  9288. }
  9289. </code></pre>
  9290. <p>The caller must specify the point in the room to purge up to. This can be
  9291. specified by including an event_id in the URI, or by setting a
  9292. <code>purge_up_to_event_id</code> or <code>purge_up_to_ts</code> in the request body. If an event
  9293. id is given, that event (and others at the same graph depth) will be retained.
  9294. If <code>purge_up_to_ts</code> is given, it should be a timestamp since the unix epoch,
  9295. in milliseconds.</p>
  9296. <p>The API starts the purge running, and returns immediately with a JSON body with
  9297. a purge id:</p>
  9298. <pre><code class="language-json">{
  9299. &quot;purge_id&quot;: &quot;&lt;opaque id&gt;&quot;
  9300. }
  9301. </code></pre>
  9302. <h2 id="purge-status-query"><a class="header" href="#purge-status-query">Purge status query</a></h2>
  9303. <p>It is possible to poll for updates on recent purges with a second API;</p>
  9304. <pre><code>GET /_synapse/admin/v1/purge_history_status/&lt;purge_id&gt;
  9305. </code></pre>
  9306. <p>This API returns a JSON body like the following:</p>
  9307. <pre><code class="language-json">{
  9308. &quot;status&quot;: &quot;active&quot;
  9309. }
  9310. </code></pre>
  9311. <p>The status will be one of <code>active</code>, <code>complete</code>, or <code>failed</code>.</p>
  9312. <p>If <code>status</code> is <code>failed</code> there will be a string <code>error</code> with the error message.</p>
  9313. <h2 id="reclaim-disk-space-postgres"><a class="header" href="#reclaim-disk-space-postgres">Reclaim disk space (Postgres)</a></h2>
  9314. <p>To reclaim the disk space and return it to the operating system, you need to run
  9315. <code>VACUUM FULL;</code> on the database.</p>
  9316. <p><a href="https://www.postgresql.org/docs/current/sql-vacuum.html">https://www.postgresql.org/docs/current/sql-vacuum.html</a></p>
  9317. <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>
  9318. <p>This API allows for the creation of users in an administrative and
  9319. non-interactive way. This is generally used for bootstrapping a Synapse
  9320. instance with administrator accounts.</p>
  9321. <p>To authenticate yourself to the server, you will need both the shared secret
  9322. (<code>registration_shared_secret</code> in the homeserver configuration), and a
  9323. one-time nonce. If the registration shared secret is not configured, this API
  9324. is not enabled.</p>
  9325. <p>To fetch the nonce, you need to request one from the API:</p>
  9326. <pre><code>&gt; GET /_synapse/admin/v1/register
  9327. &lt; {&quot;nonce&quot;: &quot;thisisanonce&quot;}
  9328. </code></pre>
  9329. <p>Once you have the nonce, you can make a <code>POST</code> to the same URL with a JSON
  9330. body containing the nonce, username, password, whether they are an admin
  9331. (optional, False by default), and a HMAC digest of the content. Also you can
  9332. set the displayname (optional, <code>username</code> by default).</p>
  9333. <p>As an example:</p>
  9334. <pre><code>&gt; POST /_synapse/admin/v1/register
  9335. &gt; {
  9336. &quot;nonce&quot;: &quot;thisisanonce&quot;,
  9337. &quot;username&quot;: &quot;pepper_roni&quot;,
  9338. &quot;displayname&quot;: &quot;Pepper Roni&quot;,
  9339. &quot;password&quot;: &quot;pizza&quot;,
  9340. &quot;admin&quot;: true,
  9341. &quot;mac&quot;: &quot;mac_digest_here&quot;
  9342. }
  9343. &lt; {
  9344. &quot;access_token&quot;: &quot;token_here&quot;,
  9345. &quot;user_id&quot;: &quot;@pepper_roni:localhost&quot;,
  9346. &quot;home_server&quot;: &quot;test&quot;,
  9347. &quot;device_id&quot;: &quot;device_id_here&quot;
  9348. }
  9349. </code></pre>
  9350. <p>The MAC is the hex digest output of the HMAC-SHA1 algorithm, with the key being
  9351. the shared secret and the content being the nonce, user, password, either the
  9352. string &quot;admin&quot; or &quot;notadmin&quot;, and optionally the user_type
  9353. each separated by NULs. For an example of generation in Python:</p>
  9354. <pre><code class="language-python">import hmac, hashlib
  9355. def generate_mac(nonce, user, password, admin=False, user_type=None):
  9356. mac = hmac.new(
  9357. key=shared_secret,
  9358. digestmod=hashlib.sha1,
  9359. )
  9360. mac.update(nonce.encode('utf8'))
  9361. mac.update(b&quot;\x00&quot;)
  9362. mac.update(user.encode('utf8'))
  9363. mac.update(b&quot;\x00&quot;)
  9364. mac.update(password.encode('utf8'))
  9365. mac.update(b&quot;\x00&quot;)
  9366. mac.update(b&quot;admin&quot; if admin else b&quot;notadmin&quot;)
  9367. if user_type:
  9368. mac.update(b&quot;\x00&quot;)
  9369. mac.update(user_type.encode('utf8'))
  9370. return mac.hexdigest()
  9371. </code></pre>
  9372. <div style="break-before: page; page-break-before: always;"></div><h1 id="registration-tokens"><a class="header" href="#registration-tokens">Registration Tokens</a></h1>
  9373. <p>This API allows you to manage tokens which can be used to authenticate
  9374. registration requests, as proposed in
  9375. <a href="https://github.com/matrix-org/matrix-doc/blob/main/proposals/3231-token-authenticated-registration.md">MSC3231</a>.
  9376. To use it, you will need to enable the <code>registration_requires_token</code> config
  9377. option, and authenticate by providing an <code>access_token</code> for a server admin:
  9378. see <a href="usage/administration/admin_api/../../usage/administration/admin_api">Admin API</a>.
  9379. Note that this API is still experimental; not all clients may support it yet.</p>
  9380. <h2 id="registration-token-objects"><a class="header" href="#registration-token-objects">Registration token objects</a></h2>
  9381. <p>Most endpoints make use of JSON objects that contain details about tokens.
  9382. These objects have the following fields:</p>
  9383. <ul>
  9384. <li><code>token</code>: The token which can be used to authenticate registration.</li>
  9385. <li><code>uses_allowed</code>: The number of times the token can be used to complete a
  9386. registration before it becomes invalid.</li>
  9387. <li><code>pending</code>: The number of pending uses the token has. When someone uses
  9388. the token to authenticate themselves, the pending counter is incremented
  9389. so that the token is not used more than the permitted number of times.
  9390. When the person completes registration the pending counter is decremented,
  9391. and the completed counter is incremented.</li>
  9392. <li><code>completed</code>: The number of times the token has been used to successfully
  9393. complete a registration.</li>
  9394. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  9395. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  9396. To convert this into a human-readable form you can remove the milliseconds
  9397. and use the <code>date</code> command. For example, <code>date -d '@1625394937'</code>.</li>
  9398. </ul>
  9399. <h2 id="list-all-tokens"><a class="header" href="#list-all-tokens">List all tokens</a></h2>
  9400. <p>Lists all tokens and details about them. If the request is successful, the top
  9401. level JSON object will have a <code>registration_tokens</code> key which is an array of
  9402. registration token objects.</p>
  9403. <pre><code>GET /_synapse/admin/v1/registration_tokens
  9404. </code></pre>
  9405. <p>Optional query parameters:</p>
  9406. <ul>
  9407. <li><code>valid</code>: <code>true</code> or <code>false</code>. If <code>true</code>, only valid tokens are returned.
  9408. If <code>false</code>, only tokens that have expired or have had all uses exhausted are
  9409. returned. If omitted, all tokens are returned regardless of validity.</li>
  9410. </ul>
  9411. <p>Example:</p>
  9412. <pre><code>GET /_synapse/admin/v1/registration_tokens
  9413. </code></pre>
  9414. <pre><code>200 OK
  9415. {
  9416. &quot;registration_tokens&quot;: [
  9417. {
  9418. &quot;token&quot;: &quot;abcd&quot;,
  9419. &quot;uses_allowed&quot;: 3,
  9420. &quot;pending&quot;: 0,
  9421. &quot;completed&quot;: 1,
  9422. &quot;expiry_time&quot;: null
  9423. },
  9424. {
  9425. &quot;token&quot;: &quot;pqrs&quot;,
  9426. &quot;uses_allowed&quot;: 2,
  9427. &quot;pending&quot;: 1,
  9428. &quot;completed&quot;: 1,
  9429. &quot;expiry_time&quot;: null
  9430. },
  9431. {
  9432. &quot;token&quot;: &quot;wxyz&quot;,
  9433. &quot;uses_allowed&quot;: null,
  9434. &quot;pending&quot;: 0,
  9435. &quot;completed&quot;: 9,
  9436. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  9437. }
  9438. ]
  9439. }
  9440. </code></pre>
  9441. <p>Example using the <code>valid</code> query parameter:</p>
  9442. <pre><code>GET /_synapse/admin/v1/registration_tokens?valid=false
  9443. </code></pre>
  9444. <pre><code>200 OK
  9445. {
  9446. &quot;registration_tokens&quot;: [
  9447. {
  9448. &quot;token&quot;: &quot;pqrs&quot;,
  9449. &quot;uses_allowed&quot;: 2,
  9450. &quot;pending&quot;: 1,
  9451. &quot;completed&quot;: 1,
  9452. &quot;expiry_time&quot;: null
  9453. },
  9454. {
  9455. &quot;token&quot;: &quot;wxyz&quot;,
  9456. &quot;uses_allowed&quot;: null,
  9457. &quot;pending&quot;: 0,
  9458. &quot;completed&quot;: 9,
  9459. &quot;expiry_time&quot;: 1625394937000 // 2021-07-04 10:35:37 UTC
  9460. }
  9461. ]
  9462. }
  9463. </code></pre>
  9464. <h2 id="get-one-token"><a class="header" href="#get-one-token">Get one token</a></h2>
  9465. <p>Get details about a single token. If the request is successful, the response
  9466. body will be a registration token object.</p>
  9467. <pre><code>GET /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  9468. </code></pre>
  9469. <p>Path parameters:</p>
  9470. <ul>
  9471. <li><code>token</code>: The registration token to return details of.</li>
  9472. </ul>
  9473. <p>Example:</p>
  9474. <pre><code>GET /_synapse/admin/v1/registration_tokens/abcd
  9475. </code></pre>
  9476. <pre><code>200 OK
  9477. {
  9478. &quot;token&quot;: &quot;abcd&quot;,
  9479. &quot;uses_allowed&quot;: 3,
  9480. &quot;pending&quot;: 0,
  9481. &quot;completed&quot;: 1,
  9482. &quot;expiry_time&quot;: null
  9483. }
  9484. </code></pre>
  9485. <h2 id="create-token"><a class="header" href="#create-token">Create token</a></h2>
  9486. <p>Create a new registration token. If the request is successful, the newly created
  9487. token will be returned as a registration token object in the response body.</p>
  9488. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  9489. </code></pre>
  9490. <p>The request body must be a JSON object and can contain the following fields:</p>
  9491. <ul>
  9492. <li><code>token</code>: The registration token. A string of no more than 64 characters that
  9493. consists only of characters matched by the regex <code>[A-Za-z0-9._~-]</code>.
  9494. Default: randomly generated.</li>
  9495. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  9496. a registration before it becomes invalid.
  9497. Default: <code>null</code> (unlimited uses).</li>
  9498. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  9499. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  9500. You could use, for example, <code>date '+%s000' -d 'tomorrow'</code>.
  9501. Default: <code>null</code> (token does not expire).</li>
  9502. <li><code>length</code>: The length of the token randomly generated if <code>token</code> is not
  9503. specified. Must be between 1 and 64 inclusive. Default: <code>16</code>.</li>
  9504. </ul>
  9505. <p>If a field is omitted the default is used.</p>
  9506. <p>Example using defaults:</p>
  9507. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  9508. {}
  9509. </code></pre>
  9510. <pre><code>200 OK
  9511. {
  9512. &quot;token&quot;: &quot;0M-9jbkf2t_Tgiw1&quot;,
  9513. &quot;uses_allowed&quot;: null,
  9514. &quot;pending&quot;: 0,
  9515. &quot;completed&quot;: 0,
  9516. &quot;expiry_time&quot;: null
  9517. }
  9518. </code></pre>
  9519. <p>Example specifying some fields:</p>
  9520. <pre><code>POST /_synapse/admin/v1/registration_tokens/new
  9521. {
  9522. &quot;token&quot;: &quot;defg&quot;,
  9523. &quot;uses_allowed&quot;: 1
  9524. }
  9525. </code></pre>
  9526. <pre><code>200 OK
  9527. {
  9528. &quot;token&quot;: &quot;defg&quot;,
  9529. &quot;uses_allowed&quot;: 1,
  9530. &quot;pending&quot;: 0,
  9531. &quot;completed&quot;: 0,
  9532. &quot;expiry_time&quot;: null
  9533. }
  9534. </code></pre>
  9535. <h2 id="update-token"><a class="header" href="#update-token">Update token</a></h2>
  9536. <p>Update the number of allowed uses or expiry time of a token. If the request is
  9537. successful, the updated token will be returned as a registration token object
  9538. in the response body.</p>
  9539. <pre><code>PUT /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  9540. </code></pre>
  9541. <p>Path parameters:</p>
  9542. <ul>
  9543. <li><code>token</code>: The registration token to update.</li>
  9544. </ul>
  9545. <p>The request body must be a JSON object and can contain the following fields:</p>
  9546. <ul>
  9547. <li><code>uses_allowed</code>: The integer number of times the token can be used to complete
  9548. a registration before it becomes invalid. By setting <code>uses_allowed</code> to <code>0</code>
  9549. the token can be easily made invalid without deleting it.
  9550. If <code>null</code> the token will have an unlimited number of uses.</li>
  9551. <li><code>expiry_time</code>: The latest time the token is valid. Given as the number of
  9552. milliseconds since 1970-01-01 00:00:00 UTC (the start of the Unix epoch).
  9553. If <code>null</code> the token will not expire.</li>
  9554. </ul>
  9555. <p>If a field is omitted its value is not modified.</p>
  9556. <p>Example:</p>
  9557. <pre><code>PUT /_synapse/admin/v1/registration_tokens/defg
  9558. {
  9559. &quot;expiry_time&quot;: 4781243146000 // 2121-07-06 11:05:46 UTC
  9560. }
  9561. </code></pre>
  9562. <pre><code>200 OK
  9563. {
  9564. &quot;token&quot;: &quot;defg&quot;,
  9565. &quot;uses_allowed&quot;: 1,
  9566. &quot;pending&quot;: 0,
  9567. &quot;completed&quot;: 0,
  9568. &quot;expiry_time&quot;: 4781243146000
  9569. }
  9570. </code></pre>
  9571. <h2 id="delete-token"><a class="header" href="#delete-token">Delete token</a></h2>
  9572. <p>Delete a registration token. If the request is successful, the response body
  9573. will be an empty JSON object.</p>
  9574. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/&lt;token&gt;
  9575. </code></pre>
  9576. <p>Path parameters:</p>
  9577. <ul>
  9578. <li><code>token</code>: The registration token to delete.</li>
  9579. </ul>
  9580. <p>Example:</p>
  9581. <pre><code>DELETE /_synapse/admin/v1/registration_tokens/wxyz
  9582. </code></pre>
  9583. <pre><code>200 OK
  9584. {}
  9585. </code></pre>
  9586. <h2 id="errors"><a class="header" href="#errors">Errors</a></h2>
  9587. <p>If a request fails a &quot;standard error response&quot; will be returned as defined in
  9588. the <a href="https://matrix.org/docs/spec/client_server/r0.6.1#api-standards">Matrix Client-Server API specification</a>.</p>
  9589. <p>For example, if the token specified in a path parameter does not exist a
  9590. <code>404 Not Found</code> error will be returned.</p>
  9591. <pre><code>GET /_synapse/admin/v1/registration_tokens/1234
  9592. </code></pre>
  9593. <pre><code>404 Not Found
  9594. {
  9595. &quot;errcode&quot;: &quot;M_NOT_FOUND&quot;,
  9596. &quot;error&quot;: &quot;No such registration token: 1234&quot;
  9597. }
  9598. </code></pre>
  9599. <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>
  9600. <p>This API allows an administrator to join an user account with a given <code>user_id</code>
  9601. to a room with a given <code>room_id_or_alias</code>. You can only modify the membership of
  9602. local users. The server administrator must be in the room and have permission to
  9603. invite users.</p>
  9604. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  9605. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  9606. <h2 id="parameters"><a class="header" href="#parameters">Parameters</a></h2>
  9607. <p>The following parameters are available:</p>
  9608. <ul>
  9609. <li><code>user_id</code> - Fully qualified user: for example, <code>@user:server.com</code>.</li>
  9610. <li><code>room_id_or_alias</code> - The room identifier or alias to join: for example,
  9611. <code>!636q39766251:server.com</code>.</li>
  9612. </ul>
  9613. <h2 id="usage-1"><a class="header" href="#usage-1">Usage</a></h2>
  9614. <pre><code>POST /_synapse/admin/v1/join/&lt;room_id_or_alias&gt;
  9615. {
  9616. &quot;user_id&quot;: &quot;@user:server.com&quot;
  9617. }
  9618. </code></pre>
  9619. <p>Response:</p>
  9620. <pre><code class="language-json">{
  9621. &quot;room_id&quot;: &quot;!636q39766251:server.com&quot;
  9622. }
  9623. </code></pre>
  9624. <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>
  9625. <p>The List Room admin API allows server admins to get a list of rooms on their
  9626. server. There are various parameters available that allow for filtering and
  9627. sorting the returned list. This API supports pagination.</p>
  9628. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  9629. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  9630. <p><strong>Parameters</strong></p>
  9631. <p>The following query parameters are available:</p>
  9632. <ul>
  9633. <li>
  9634. <p><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</p>
  9635. </li>
  9636. <li>
  9637. <p><code>limit</code> - Maximum amount of rooms to return. Defaults to <code>100</code>.</p>
  9638. </li>
  9639. <li>
  9640. <p><code>order_by</code> - The method in which to sort the returned list of rooms. Valid values are:</p>
  9641. <ul>
  9642. <li><code>alphabetical</code> - Same as <code>name</code>. This is deprecated.</li>
  9643. <li><code>size</code> - Same as <code>joined_members</code>. This is deprecated.</li>
  9644. <li><code>name</code> - Rooms are ordered alphabetically by room name. This is the default.</li>
  9645. <li><code>canonical_alias</code> - Rooms are ordered alphabetically by main alias address of the room.</li>
  9646. <li><code>joined_members</code> - Rooms are ordered by the number of members. Largest to smallest.</li>
  9647. <li><code>joined_local_members</code> - Rooms are ordered by the number of local members. Largest to smallest.</li>
  9648. <li><code>version</code> - Rooms are ordered by room version. Largest to smallest.</li>
  9649. <li><code>creator</code> - Rooms are ordered alphabetically by creator of the room.</li>
  9650. <li><code>encryption</code> - Rooms are ordered alphabetically by the end-to-end encryption algorithm.</li>
  9651. <li><code>federatable</code> - Rooms are ordered by whether the room is federatable.</li>
  9652. <li><code>public</code> - Rooms are ordered by visibility in room list.</li>
  9653. <li><code>join_rules</code> - Rooms are ordered alphabetically by join rules of the room.</li>
  9654. <li><code>guest_access</code> - Rooms are ordered alphabetically by guest access option of the room.</li>
  9655. <li><code>history_visibility</code> - Rooms are ordered alphabetically by visibility of history of the room.</li>
  9656. <li><code>state_events</code> - Rooms are ordered by number of state events. Largest to smallest.</li>
  9657. </ul>
  9658. </li>
  9659. <li>
  9660. <p><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  9661. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  9662. </li>
  9663. <li>
  9664. <p><code>search_term</code> - Filter rooms by their room name, canonical alias and room id.
  9665. Specifically, rooms are selected if the search term is contained in</p>
  9666. <ul>
  9667. <li>the room's name,</li>
  9668. <li>the local part of the room's canonical alias, or</li>
  9669. <li>the complete (local and server part) room's id (case sensitive).</li>
  9670. </ul>
  9671. <p>Defaults to no filtering.</p>
  9672. </li>
  9673. </ul>
  9674. <p><strong>Response</strong></p>
  9675. <p>The following fields are possible in the JSON response body:</p>
  9676. <ul>
  9677. <li><code>rooms</code> - An array of objects, each containing information about a room.
  9678. <ul>
  9679. <li>Room objects contain the following fields:
  9680. <ul>
  9681. <li><code>room_id</code> - The ID of the room.</li>
  9682. <li><code>name</code> - The name of the room.</li>
  9683. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  9684. <li><code>joined_members</code> - How many users are currently in the room.</li>
  9685. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  9686. <li><code>version</code> - The version of the room as a string.</li>
  9687. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  9688. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  9689. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  9690. <li><code>public</code> - Whether the room is visible in room directory.</li>
  9691. <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>
  9692. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  9693. <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>
  9694. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  9695. </ul>
  9696. </li>
  9697. </ul>
  9698. </li>
  9699. <li><code>offset</code> - The current pagination offset in rooms. This parameter should be
  9700. used instead of <code>next_token</code> for room offset as <code>next_token</code> is
  9701. not intended to be parsed.</li>
  9702. <li><code>total_rooms</code> - The total number of rooms this query can return. Using this
  9703. and <code>offset</code>, you have enough information to know the current
  9704. progression through the list.</li>
  9705. <li><code>next_batch</code> - If this field is present, we know that there are potentially
  9706. more rooms on the server that did not all fit into this response.
  9707. We can use <code>next_batch</code> to get the &quot;next page&quot; of results. To do
  9708. so, simply repeat your request, setting the <code>from</code> parameter to
  9709. the value of <code>next_batch</code>.</li>
  9710. <li><code>prev_batch</code> - If this field is present, it is possible to paginate backwards.
  9711. Use <code>prev_batch</code> for the <code>from</code> value in the next request to
  9712. get the &quot;previous page&quot; of results.</li>
  9713. </ul>
  9714. <p>The API is:</p>
  9715. <p>A standard request with no filtering:</p>
  9716. <pre><code>GET /_synapse/admin/v1/rooms
  9717. </code></pre>
  9718. <p>A response body like the following is returned:</p>
  9719. <pre><code class="language-json">{
  9720. &quot;rooms&quot;: [
  9721. {
  9722. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  9723. &quot;name&quot;: &quot;Matrix HQ&quot;,
  9724. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  9725. &quot;joined_members&quot;: 8326,
  9726. &quot;joined_local_members&quot;: 2,
  9727. &quot;version&quot;: &quot;1&quot;,
  9728. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  9729. &quot;encryption&quot;: null,
  9730. &quot;federatable&quot;: true,
  9731. &quot;public&quot;: true,
  9732. &quot;join_rules&quot;: &quot;invite&quot;,
  9733. &quot;guest_access&quot;: null,
  9734. &quot;history_visibility&quot;: &quot;shared&quot;,
  9735. &quot;state_events&quot;: 93534
  9736. },
  9737. ... (8 hidden items) ...
  9738. {
  9739. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  9740. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  9741. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  9742. &quot;joined_members&quot;: 314,
  9743. &quot;joined_local_members&quot;: 20,
  9744. &quot;version&quot;: &quot;4&quot;,
  9745. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  9746. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  9747. &quot;federatable&quot;: true,
  9748. &quot;public&quot;: false,
  9749. &quot;join_rules&quot;: &quot;invite&quot;,
  9750. &quot;guest_access&quot;: null,
  9751. &quot;history_visibility&quot;: &quot;shared&quot;,
  9752. &quot;state_events&quot;: 8345
  9753. }
  9754. ],
  9755. &quot;offset&quot;: 0,
  9756. &quot;total_rooms&quot;: 10
  9757. }
  9758. </code></pre>
  9759. <p>Filtering by room name:</p>
  9760. <pre><code>GET /_synapse/admin/v1/rooms?search_term=TWIM
  9761. </code></pre>
  9762. <p>A response body like the following is returned:</p>
  9763. <pre><code class="language-json">{
  9764. &quot;rooms&quot;: [
  9765. {
  9766. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  9767. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  9768. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  9769. &quot;joined_members&quot;: 314,
  9770. &quot;joined_local_members&quot;: 20,
  9771. &quot;version&quot;: &quot;4&quot;,
  9772. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  9773. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  9774. &quot;federatable&quot;: true,
  9775. &quot;public&quot;: false,
  9776. &quot;join_rules&quot;: &quot;invite&quot;,
  9777. &quot;guest_access&quot;: null,
  9778. &quot;history_visibility&quot;: &quot;shared&quot;,
  9779. &quot;state_events&quot;: 8
  9780. }
  9781. ],
  9782. &quot;offset&quot;: 0,
  9783. &quot;total_rooms&quot;: 1
  9784. }
  9785. </code></pre>
  9786. <p>Paginating through a list of rooms:</p>
  9787. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size
  9788. </code></pre>
  9789. <p>A response body like the following is returned:</p>
  9790. <pre><code class="language-json">{
  9791. &quot;rooms&quot;: [
  9792. {
  9793. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  9794. &quot;name&quot;: &quot;Matrix HQ&quot;,
  9795. &quot;canonical_alias&quot;: &quot;#matrix:matrix.org&quot;,
  9796. &quot;joined_members&quot;: 8326,
  9797. &quot;joined_local_members&quot;: 2,
  9798. &quot;version&quot;: &quot;1&quot;,
  9799. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  9800. &quot;encryption&quot;: null,
  9801. &quot;federatable&quot;: true,
  9802. &quot;public&quot;: true,
  9803. &quot;join_rules&quot;: &quot;invite&quot;,
  9804. &quot;guest_access&quot;: null,
  9805. &quot;history_visibility&quot;: &quot;shared&quot;,
  9806. &quot;state_events&quot;: 93534
  9807. },
  9808. ... (98 hidden items) ...
  9809. {
  9810. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  9811. &quot;name&quot;: &quot;This Week In Matrix (TWIM)&quot;,
  9812. &quot;canonical_alias&quot;: &quot;#twim:matrix.org&quot;,
  9813. &quot;joined_members&quot;: 314,
  9814. &quot;joined_local_members&quot;: 20,
  9815. &quot;version&quot;: &quot;4&quot;,
  9816. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  9817. &quot;encryption&quot;: &quot;m.megolm.v1.aes-sha2&quot;,
  9818. &quot;federatable&quot;: true,
  9819. &quot;public&quot;: false,
  9820. &quot;join_rules&quot;: &quot;invite&quot;,
  9821. &quot;guest_access&quot;: null,
  9822. &quot;history_visibility&quot;: &quot;shared&quot;,
  9823. &quot;state_events&quot;: 8345
  9824. }
  9825. ],
  9826. &quot;offset&quot;: 0,
  9827. &quot;total_rooms&quot;: 150,
  9828. &quot;next_token&quot;: 100
  9829. }
  9830. </code></pre>
  9831. <p>The presence of the <code>next_token</code> parameter tells us that there are more rooms
  9832. than returned in this request, and we need to make another request to get them.
  9833. To get the next batch of room results, we repeat our request, setting the <code>from</code>
  9834. parameter to the value of <code>next_token</code>.</p>
  9835. <pre><code>GET /_synapse/admin/v1/rooms?order_by=size&amp;from=100
  9836. </code></pre>
  9837. <p>A response body like the following is returned:</p>
  9838. <pre><code class="language-json">{
  9839. &quot;rooms&quot;: [
  9840. {
  9841. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  9842. &quot;name&quot;: &quot;Music Theory&quot;,
  9843. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  9844. &quot;joined_members&quot;: 127,
  9845. &quot;joined_local_members&quot;: 2,
  9846. &quot;version&quot;: &quot;1&quot;,
  9847. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  9848. &quot;encryption&quot;: null,
  9849. &quot;federatable&quot;: true,
  9850. &quot;public&quot;: true,
  9851. &quot;join_rules&quot;: &quot;invite&quot;,
  9852. &quot;guest_access&quot;: null,
  9853. &quot;history_visibility&quot;: &quot;shared&quot;,
  9854. &quot;state_events&quot;: 93534
  9855. },
  9856. ... (48 hidden items) ...
  9857. {
  9858. &quot;room_id&quot;: &quot;!twcBhHVdZlQWuuxBhN:termina.org.uk&quot;,
  9859. &quot;name&quot;: &quot;weechat-matrix&quot;,
  9860. &quot;canonical_alias&quot;: &quot;#weechat-matrix:termina.org.uk&quot;,
  9861. &quot;joined_members&quot;: 137,
  9862. &quot;joined_local_members&quot;: 20,
  9863. &quot;version&quot;: &quot;4&quot;,
  9864. &quot;creator&quot;: &quot;@foo:termina.org.uk&quot;,
  9865. &quot;encryption&quot;: null,
  9866. &quot;federatable&quot;: true,
  9867. &quot;public&quot;: true,
  9868. &quot;join_rules&quot;: &quot;invite&quot;,
  9869. &quot;guest_access&quot;: null,
  9870. &quot;history_visibility&quot;: &quot;shared&quot;,
  9871. &quot;state_events&quot;: 8345
  9872. }
  9873. ],
  9874. &quot;offset&quot;: 100,
  9875. &quot;prev_batch&quot;: 0,
  9876. &quot;total_rooms&quot;: 150
  9877. }
  9878. </code></pre>
  9879. <p>Once the <code>next_token</code> parameter is no longer present, we know we've reached the
  9880. end of the list.</p>
  9881. <h1 id="room-details-api"><a class="header" href="#room-details-api">Room Details API</a></h1>
  9882. <p>The Room Details admin API allows server admins to get all details of a room.</p>
  9883. <p>The following fields are possible in the JSON response body:</p>
  9884. <ul>
  9885. <li><code>room_id</code> - The ID of the room.</li>
  9886. <li><code>name</code> - The name of the room.</li>
  9887. <li><code>topic</code> - The topic of the room.</li>
  9888. <li><code>avatar</code> - The <code>mxc</code> URI to the avatar of the room.</li>
  9889. <li><code>canonical_alias</code> - The canonical (main) alias address of the room.</li>
  9890. <li><code>joined_members</code> - How many users are currently in the room.</li>
  9891. <li><code>joined_local_members</code> - How many local users are currently in the room.</li>
  9892. <li><code>joined_local_devices</code> - How many local devices are currently in the room.</li>
  9893. <li><code>version</code> - The version of the room as a string.</li>
  9894. <li><code>creator</code> - The <code>user_id</code> of the room creator.</li>
  9895. <li><code>encryption</code> - Algorithm of end-to-end encryption of messages. Is <code>null</code> if encryption is not active.</li>
  9896. <li><code>federatable</code> - Whether users on other servers can join this room.</li>
  9897. <li><code>public</code> - Whether the room is visible in room directory.</li>
  9898. <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>
  9899. <li><code>guest_access</code> - Whether guests can join the room. One of: [&quot;can_join&quot;, &quot;forbidden&quot;].</li>
  9900. <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>
  9901. <li><code>state_events</code> - Total number of state_events of a room. Complexity of the room.</li>
  9902. </ul>
  9903. <p>The API is:</p>
  9904. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;
  9905. </code></pre>
  9906. <p>A response body like the following is returned:</p>
  9907. <pre><code class="language-json">{
  9908. &quot;room_id&quot;: &quot;!mscvqgqpHYjBGDxNym:matrix.org&quot;,
  9909. &quot;name&quot;: &quot;Music Theory&quot;,
  9910. &quot;avatar&quot;: &quot;mxc://matrix.org/AQDaVFlbkQoErdOgqWRgiGSV&quot;,
  9911. &quot;topic&quot;: &quot;Theory, Composition, Notation, Analysis&quot;,
  9912. &quot;canonical_alias&quot;: &quot;#musictheory:matrix.org&quot;,
  9913. &quot;joined_members&quot;: 127,
  9914. &quot;joined_local_members&quot;: 2,
  9915. &quot;joined_local_devices&quot;: 2,
  9916. &quot;version&quot;: &quot;1&quot;,
  9917. &quot;creator&quot;: &quot;@foo:matrix.org&quot;,
  9918. &quot;encryption&quot;: null,
  9919. &quot;federatable&quot;: true,
  9920. &quot;public&quot;: true,
  9921. &quot;join_rules&quot;: &quot;invite&quot;,
  9922. &quot;guest_access&quot;: null,
  9923. &quot;history_visibility&quot;: &quot;shared&quot;,
  9924. &quot;state_events&quot;: 93534
  9925. }
  9926. </code></pre>
  9927. <h1 id="room-members-api"><a class="header" href="#room-members-api">Room Members API</a></h1>
  9928. <p>The Room Members admin API allows server admins to get a list of all members of a room.</p>
  9929. <p>The response includes the following fields:</p>
  9930. <ul>
  9931. <li><code>members</code> - A list of all the members that are present in the room, represented by their ids.</li>
  9932. <li><code>total</code> - Total number of members in the room.</li>
  9933. </ul>
  9934. <p>The API is:</p>
  9935. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/members
  9936. </code></pre>
  9937. <p>A response body like the following is returned:</p>
  9938. <pre><code class="language-json">{
  9939. &quot;members&quot;: [
  9940. &quot;@foo:matrix.org&quot;,
  9941. &quot;@bar:matrix.org&quot;,
  9942. &quot;@foobar:matrix.org&quot;
  9943. ],
  9944. &quot;total&quot;: 3
  9945. }
  9946. </code></pre>
  9947. <h1 id="room-state-api"><a class="header" href="#room-state-api">Room State API</a></h1>
  9948. <p>The Room State admin API allows server admins to get a list of all state events in a room.</p>
  9949. <p>The response includes the following fields:</p>
  9950. <ul>
  9951. <li><code>state</code> - The current state of the room at the time of request.</li>
  9952. </ul>
  9953. <p>The API is:</p>
  9954. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/state
  9955. </code></pre>
  9956. <p>A response body like the following is returned:</p>
  9957. <pre><code class="language-json">{
  9958. &quot;state&quot;: [
  9959. {&quot;type&quot;: &quot;m.room.create&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  9960. {&quot;type&quot;: &quot;m.room.power_levels&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true},
  9961. {&quot;type&quot;: &quot;m.room.name&quot;, &quot;state_key&quot;: &quot;&quot;, &quot;etc&quot;: true}
  9962. ]
  9963. }
  9964. </code></pre>
  9965. <h1 id="block-room-api"><a class="header" href="#block-room-api">Block Room API</a></h1>
  9966. <p>The Block Room admin API allows server admins to block and unblock rooms,
  9967. and query to see if a given room is blocked.
  9968. This API can be used to pre-emptively block a room, even if it's unknown to this
  9969. homeserver. Users will be prevented from joining a blocked room.</p>
  9970. <h2 id="block-or-unblock-a-room"><a class="header" href="#block-or-unblock-a-room">Block or unblock a room</a></h2>
  9971. <p>The API is:</p>
  9972. <pre><code>PUT /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  9973. </code></pre>
  9974. <p>with a body of:</p>
  9975. <pre><code class="language-json">{
  9976. &quot;block&quot;: true
  9977. }
  9978. </code></pre>
  9979. <p>A response body like the following is returned:</p>
  9980. <pre><code class="language-json">{
  9981. &quot;block&quot;: true
  9982. }
  9983. </code></pre>
  9984. <p><strong>Parameters</strong></p>
  9985. <p>The following parameters should be set in the URL:</p>
  9986. <ul>
  9987. <li><code>room_id</code> - The ID of the room.</li>
  9988. </ul>
  9989. <p>The following JSON body parameters are available:</p>
  9990. <ul>
  9991. <li><code>block</code> - If <code>true</code> the room will be blocked and if <code>false</code> the room will be unblocked.</li>
  9992. </ul>
  9993. <p><strong>Response</strong></p>
  9994. <p>The following fields are possible in the JSON response body:</p>
  9995. <ul>
  9996. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  9997. </ul>
  9998. <h2 id="get-block-status"><a class="header" href="#get-block-status">Get block status</a></h2>
  9999. <p>The API is:</p>
  10000. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/block
  10001. </code></pre>
  10002. <p>A response body like the following is returned:</p>
  10003. <pre><code class="language-json">{
  10004. &quot;block&quot;: true,
  10005. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  10006. }
  10007. </code></pre>
  10008. <p><strong>Parameters</strong></p>
  10009. <p>The following parameters should be set in the URL:</p>
  10010. <ul>
  10011. <li><code>room_id</code> - The ID of the room.</li>
  10012. </ul>
  10013. <p><strong>Response</strong></p>
  10014. <p>The following fields are possible in the JSON response body:</p>
  10015. <ul>
  10016. <li><code>block</code> - A boolean. <code>true</code> if the room is blocked, otherwise <code>false</code></li>
  10017. <li><code>user_id</code> - An optional string. If the room is blocked (<code>block</code> is <code>true</code>) shows
  10018. the user who has add the room to blocking list. Otherwise it is not displayed.</li>
  10019. </ul>
  10020. <h1 id="delete-room-api"><a class="header" href="#delete-room-api">Delete Room API</a></h1>
  10021. <p>The Delete Room admin API allows server admins to remove rooms from the server
  10022. and block these rooms.</p>
  10023. <p>Shuts down a room. Moves all local users and room aliases automatically to a
  10024. new room if <code>new_room_user_id</code> is set. Otherwise local users only
  10025. leave the room without any information.</p>
  10026. <p>The new room will be created with the user specified by the <code>new_room_user_id</code> parameter
  10027. as room administrator and will contain a message explaining what happened. Users invited
  10028. to the new room will have power level <code>-10</code> by default, and thus be unable to speak.</p>
  10029. <p>If <code>block</code> is <code>true</code>, users will be prevented from joining the old room.
  10030. This option can in <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> also be used to pre-emptively
  10031. block a room, even if it's unknown to this homeserver. In this case, the room will be
  10032. blocked, and no further action will be taken. If <code>block</code> is <code>false</code>, attempting to
  10033. delete an unknown room is invalid and will be rejected as a bad request.</p>
  10034. <p>This API will remove all trace of the old room from your database after removing
  10035. all local users. If <code>purge</code> is <code>true</code> (the default), all traces of the old room will
  10036. be removed from your database after removing all local users. If you do not want
  10037. this to happen, set <code>purge</code> to <code>false</code>.
  10038. Depending on the amount of history being purged, a call to the API may take
  10039. several minutes or longer.</p>
  10040. <p>The local server will only have the power to move local user and room aliases to
  10041. the new room. Users on other servers will be unaffected.</p>
  10042. <h2 id="version-1-old-version"><a class="header" href="#version-1-old-version">Version 1 (old version)</a></h2>
  10043. <p>This version works synchronously. That means you only get the response once the server has
  10044. finished the action, which may take a long time. If you request the same action
  10045. a second time, and the server has not finished the first one, the second request will block.
  10046. This is fixed in version 2 of this API. The parameters are the same in both APIs.
  10047. This API will become deprecated in the future.</p>
  10048. <p>The API is:</p>
  10049. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id&gt;
  10050. </code></pre>
  10051. <p>with a body of:</p>
  10052. <pre><code class="language-json">{
  10053. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  10054. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  10055. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  10056. &quot;block&quot;: true,
  10057. &quot;purge&quot;: true
  10058. }
  10059. </code></pre>
  10060. <p>A response body like the following is returned:</p>
  10061. <pre><code class="language-json">{
  10062. &quot;kicked_users&quot;: [
  10063. &quot;@foobar:example.com&quot;
  10064. ],
  10065. &quot;failed_to_kick_users&quot;: [],
  10066. &quot;local_aliases&quot;: [
  10067. &quot;#badroom:example.com&quot;,
  10068. &quot;#evilsaloon:example.com&quot;
  10069. ],
  10070. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  10071. }
  10072. </code></pre>
  10073. <p>The parameters and response values have the same format as
  10074. <a href="admin_api/rooms.html#version-2-new-version">version 2</a> of the API.</p>
  10075. <h2 id="version-2-new-version"><a class="header" href="#version-2-new-version">Version 2 (new version)</a></h2>
  10076. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  10077. <p>This version works asynchronously, meaning you get the response from server immediately
  10078. while the server works on that task in background. You can then request the status of the action
  10079. to check if it has completed.</p>
  10080. <p>The API is:</p>
  10081. <pre><code>DELETE /_synapse/admin/v2/rooms/&lt;room_id&gt;
  10082. </code></pre>
  10083. <p>with a body of:</p>
  10084. <pre><code class="language-json">{
  10085. &quot;new_room_user_id&quot;: &quot;@someuser:example.com&quot;,
  10086. &quot;room_name&quot;: &quot;Content Violation Notification&quot;,
  10087. &quot;message&quot;: &quot;Bad Room has been shutdown due to content violations on this server. Please review our Terms of Service.&quot;,
  10088. &quot;block&quot;: true,
  10089. &quot;purge&quot;: true
  10090. }
  10091. </code></pre>
  10092. <p>The API starts the shut down and purge running, and returns immediately with a JSON body with
  10093. a purge id:</p>
  10094. <pre><code class="language-json">{
  10095. &quot;delete_id&quot;: &quot;&lt;opaque id&gt;&quot;
  10096. }
  10097. </code></pre>
  10098. <p><strong>Parameters</strong></p>
  10099. <p>The following parameters should be set in the URL:</p>
  10100. <ul>
  10101. <li><code>room_id</code> - The ID of the room.</li>
  10102. </ul>
  10103. <p>The following JSON body parameters are available:</p>
  10104. <ul>
  10105. <li><code>new_room_user_id</code> - Optional. If set, a new room will be created with this user ID
  10106. as the creator and admin, and all users in the old room will be moved into that
  10107. room. If not set, no new room will be created and the users will just be removed
  10108. from the old room. The user ID must be on the local server, but does not necessarily
  10109. have to belong to a registered user.</li>
  10110. <li><code>room_name</code> - Optional. A string representing the name of the room that new users will be
  10111. invited to. Defaults to <code>Content Violation Notification</code></li>
  10112. <li><code>message</code> - Optional. A string containing the first message that will be sent as
  10113. <code>new_room_user_id</code> in the new room. Ideally this will clearly convey why the
  10114. 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>
  10115. <li><code>block</code> - Optional. If set to <code>true</code>, this room will be added to a blocking list,
  10116. preventing future attempts to join the room. Rooms can be blocked
  10117. even if they're not yet known to the homeserver (only with
  10118. <a href="admin_api/rooms.html#version-1-old-version">Version 1</a> of the API). Defaults to <code>false</code>.</li>
  10119. <li><code>purge</code> - Optional. If set to <code>true</code>, it will remove all traces of the room from your database.
  10120. Defaults to <code>true</code>.</li>
  10121. <li><code>force_purge</code> - Optional, and ignored unless <code>purge</code> is <code>true</code>. If set to <code>true</code>, it
  10122. will force a purge to go ahead even if there are local users still in the room. Do not
  10123. use this unless a regular <code>purge</code> operation fails, as it could leave those users'
  10124. clients in a confused state.</li>
  10125. </ul>
  10126. <p>The JSON body must not be empty. The body must be at least <code>{}</code>.</p>
  10127. <h2 id="status-of-deleting-rooms"><a class="header" href="#status-of-deleting-rooms">Status of deleting rooms</a></h2>
  10128. <p><strong>Note</strong>: This API is new, experimental and &quot;subject to change&quot;.</p>
  10129. <p>It is possible to query the status of the background task for deleting rooms.
  10130. The status can be queried up to 24 hours after completion of the task,
  10131. or until Synapse is restarted (whichever happens first).</p>
  10132. <h3 id="query-by-room_id"><a class="header" href="#query-by-room_id">Query by <code>room_id</code></a></h3>
  10133. <p>With this API you can get the status of all active deletion tasks, and all those completed in the last 24h,
  10134. for the given <code>room_id</code>.</p>
  10135. <p>The API is:</p>
  10136. <pre><code>GET /_synapse/admin/v2/rooms/&lt;room_id&gt;/delete_status
  10137. </code></pre>
  10138. <p>A response body like the following is returned:</p>
  10139. <pre><code class="language-json">{
  10140. &quot;results&quot;: [
  10141. {
  10142. &quot;delete_id&quot;: &quot;delete_id1&quot;,
  10143. &quot;status&quot;: &quot;failed&quot;,
  10144. &quot;error&quot;: &quot;error message&quot;,
  10145. &quot;shutdown_room&quot;: {
  10146. &quot;kicked_users&quot;: [],
  10147. &quot;failed_to_kick_users&quot;: [],
  10148. &quot;local_aliases&quot;: [],
  10149. &quot;new_room_id&quot;: null
  10150. }
  10151. }, {
  10152. &quot;delete_id&quot;: &quot;delete_id2&quot;,
  10153. &quot;status&quot;: &quot;purging&quot;,
  10154. &quot;shutdown_room&quot;: {
  10155. &quot;kicked_users&quot;: [
  10156. &quot;@foobar:example.com&quot;
  10157. ],
  10158. &quot;failed_to_kick_users&quot;: [],
  10159. &quot;local_aliases&quot;: [
  10160. &quot;#badroom:example.com&quot;,
  10161. &quot;#evilsaloon:example.com&quot;
  10162. ],
  10163. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  10164. }
  10165. }
  10166. ]
  10167. }
  10168. </code></pre>
  10169. <p><strong>Parameters</strong></p>
  10170. <p>The following parameters should be set in the URL:</p>
  10171. <ul>
  10172. <li><code>room_id</code> - The ID of the room.</li>
  10173. </ul>
  10174. <h3 id="query-by-delete_id"><a class="header" href="#query-by-delete_id">Query by <code>delete_id</code></a></h3>
  10175. <p>With this API you can get the status of one specific task by <code>delete_id</code>.</p>
  10176. <p>The API is:</p>
  10177. <pre><code>GET /_synapse/admin/v2/rooms/delete_status/&lt;delete_id&gt;
  10178. </code></pre>
  10179. <p>A response body like the following is returned:</p>
  10180. <pre><code class="language-json">{
  10181. &quot;status&quot;: &quot;purging&quot;,
  10182. &quot;shutdown_room&quot;: {
  10183. &quot;kicked_users&quot;: [
  10184. &quot;@foobar:example.com&quot;
  10185. ],
  10186. &quot;failed_to_kick_users&quot;: [],
  10187. &quot;local_aliases&quot;: [
  10188. &quot;#badroom:example.com&quot;,
  10189. &quot;#evilsaloon:example.com&quot;
  10190. ],
  10191. &quot;new_room_id&quot;: &quot;!newroomid:example.com&quot;
  10192. }
  10193. }
  10194. </code></pre>
  10195. <p><strong>Parameters</strong></p>
  10196. <p>The following parameters should be set in the URL:</p>
  10197. <ul>
  10198. <li><code>delete_id</code> - The ID for this delete.</li>
  10199. </ul>
  10200. <h3 id="response"><a class="header" href="#response">Response</a></h3>
  10201. <p>The following fields are returned in the JSON response body:</p>
  10202. <ul>
  10203. <li><code>results</code> - An array of objects, each containing information about one task.
  10204. This field is omitted from the result when you query by <code>delete_id</code>.
  10205. Task objects contain the following fields:
  10206. <ul>
  10207. <li><code>delete_id</code> - The ID for this purge if you query by <code>room_id</code>.</li>
  10208. <li><code>status</code> - The status will be one of:
  10209. <ul>
  10210. <li><code>shutting_down</code> - The process is removing users from the room.</li>
  10211. <li><code>purging</code> - The process is purging the room and event data from database.</li>
  10212. <li><code>complete</code> - The process has completed successfully.</li>
  10213. <li><code>failed</code> - The process is aborted, an error has occurred.</li>
  10214. </ul>
  10215. </li>
  10216. <li><code>error</code> - A string that shows an error message if <code>status</code> is <code>failed</code>.
  10217. Otherwise this field is hidden.</li>
  10218. <li><code>shutdown_room</code> - An object containing information about the result of shutting down the room.
  10219. <em>Note:</em> The result is shown after removing the room members.
  10220. The delete process can still be running. Please pay attention to the <code>status</code>.
  10221. <ul>
  10222. <li><code>kicked_users</code> - An array of users (<code>user_id</code>) that were kicked.</li>
  10223. <li><code>failed_to_kick_users</code> - An array of users (<code>user_id</code>) that that were not kicked.</li>
  10224. <li><code>local_aliases</code> - An array of strings representing the local aliases that were
  10225. migrated from the old room to the new.</li>
  10226. <li><code>new_room_id</code> - A string representing the room ID of the new room, or <code>null</code> if
  10227. no such room was created.</li>
  10228. </ul>
  10229. </li>
  10230. </ul>
  10231. </li>
  10232. </ul>
  10233. <h2 id="undoing-room-deletions"><a class="header" href="#undoing-room-deletions">Undoing room deletions</a></h2>
  10234. <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,
  10235. the structure can and does change without notice.</p>
  10236. <p>First, it's important to understand that a room deletion is very destructive. Undoing a deletion is not as simple as pretending it
  10237. 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
  10238. to recover at all:</p>
  10239. <ul>
  10240. <li>If the room was invite-only, your users will need to be re-invited.</li>
  10241. <li>If the room no longer has any members at all, it'll be impossible to rejoin.</li>
  10242. <li>The first user to rejoin will have to do so via an alias on a different
  10243. server (or receive an invite from a user on a different server).</li>
  10244. </ul>
  10245. <p>With all that being said, if you still want to try and recover the room:</p>
  10246. <ol>
  10247. <li>
  10248. <p>If the room was <code>block</code>ed, you must unblock it on your server. This can be
  10249. accomplished as follows:</p>
  10250. <ol>
  10251. <li>For safety reasons, shut down Synapse.</li>
  10252. <li>In the database, run <code>DELETE FROM blocked_rooms WHERE room_id = '!example:example.org';</code>
  10253. <ul>
  10254. <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>
  10255. <li>The room ID is the same one supplied to the delete room API, not the Content Violation room.</li>
  10256. </ul>
  10257. </li>
  10258. <li>Restart Synapse.</li>
  10259. </ol>
  10260. <p>This step is unnecessary if <code>block</code> was not set.</p>
  10261. </li>
  10262. <li>
  10263. <p>Any room aliases on your server that pointed to the deleted room may have
  10264. been deleted, or redirected to the Content Violation room. These will need
  10265. to be restored manually.</p>
  10266. </li>
  10267. <li>
  10268. <p>Users on your server that were in the deleted room will have been kicked
  10269. from the room. Consider whether you want to update their membership
  10270. (possibly via the <a href="admin_api/room_membership.html">Edit Room Membership API</a>) or let
  10271. them handle rejoining themselves.</p>
  10272. </li>
  10273. <li>
  10274. <p>If <code>new_room_user_id</code> was given, a 'Content Violation' will have been
  10275. created. Consider whether you want to delete that roomm.</p>
  10276. </li>
  10277. </ol>
  10278. <h1 id="make-room-admin-api"><a class="header" href="#make-room-admin-api">Make Room Admin API</a></h1>
  10279. <p>Grants another user the highest power available to a local user who is in the room.
  10280. If the user is not in the room, and it is not publicly joinable, then invite the user.</p>
  10281. <p>By default the server admin (the caller) is granted power, but another user can
  10282. optionally be specified, e.g.:</p>
  10283. <pre><code>POST /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/make_room_admin
  10284. {
  10285. &quot;user_id&quot;: &quot;@foo:example.com&quot;
  10286. }
  10287. </code></pre>
  10288. <h1 id="forward-extremities-admin-api"><a class="header" href="#forward-extremities-admin-api">Forward Extremities Admin API</a></h1>
  10289. <p>Enables querying and deleting forward extremities from rooms. When a lot of forward
  10290. extremities accumulate in a room, performance can become degraded. For details, see
  10291. <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.</p>
  10292. <h2 id="check-for-forward-extremities"><a class="header" href="#check-for-forward-extremities">Check for forward extremities</a></h2>
  10293. <p>To check the status of forward extremities for a room:</p>
  10294. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  10295. </code></pre>
  10296. <p>A response as follows will be returned:</p>
  10297. <pre><code class="language-json">{
  10298. &quot;count&quot;: 1,
  10299. &quot;results&quot;: [
  10300. {
  10301. &quot;event_id&quot;: &quot;$M5SP266vsnxctfwFgFLNceaCo3ujhRtg_NiiHabcdefgh&quot;,
  10302. &quot;state_group&quot;: 439,
  10303. &quot;depth&quot;: 123,
  10304. &quot;received_ts&quot;: 1611263016761
  10305. }
  10306. ]
  10307. }
  10308. </code></pre>
  10309. <h2 id="deleting-forward-extremities"><a class="header" href="#deleting-forward-extremities">Deleting forward extremities</a></h2>
  10310. <p><strong>WARNING</strong>: Please ensure you know what you're doing and have read
  10311. the related issue <a href="https://github.com/matrix-org/synapse/issues/1760">#1760</a>.
  10312. Under no situations should this API be executed as an automated maintenance task!</p>
  10313. <p>If a room has lots of forward extremities, the extra can be
  10314. deleted as follows:</p>
  10315. <pre><code>DELETE /_synapse/admin/v1/rooms/&lt;room_id_or_alias&gt;/forward_extremities
  10316. </code></pre>
  10317. <p>A response as follows will be returned, indicating the amount of forward extremities
  10318. that were deleted.</p>
  10319. <pre><code class="language-json">{
  10320. &quot;deleted&quot;: 1
  10321. }
  10322. </code></pre>
  10323. <h1 id="event-context-api"><a class="header" href="#event-context-api">Event Context API</a></h1>
  10324. <p>This API lets a client find the context of an event. This is designed primarily to investigate abuse reports.</p>
  10325. <pre><code>GET /_synapse/admin/v1/rooms/&lt;room_id&gt;/context/&lt;event_id&gt;
  10326. </code></pre>
  10327. <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>
  10328. <p>Example response:</p>
  10329. <pre><code class="language-json">{
  10330. &quot;end&quot;: &quot;t29-57_2_0_2&quot;,
  10331. &quot;events_after&quot;: [
  10332. {
  10333. &quot;content&quot;: {
  10334. &quot;body&quot;: &quot;This is an example text message&quot;,
  10335. &quot;msgtype&quot;: &quot;m.text&quot;,
  10336. &quot;format&quot;: &quot;org.matrix.custom.html&quot;,
  10337. &quot;formatted_body&quot;: &quot;&lt;b&gt;This is an example text message&lt;/b&gt;&quot;
  10338. },
  10339. &quot;type&quot;: &quot;m.room.message&quot;,
  10340. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  10341. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  10342. &quot;sender&quot;: &quot;@example:example.org&quot;,
  10343. &quot;origin_server_ts&quot;: 1432735824653,
  10344. &quot;unsigned&quot;: {
  10345. &quot;age&quot;: 1234
  10346. }
  10347. }
  10348. ],
  10349. &quot;event&quot;: {
  10350. &quot;content&quot;: {
  10351. &quot;body&quot;: &quot;filename.jpg&quot;,
  10352. &quot;info&quot;: {
  10353. &quot;h&quot;: 398,
  10354. &quot;w&quot;: 394,
  10355. &quot;mimetype&quot;: &quot;image/jpeg&quot;,
  10356. &quot;size&quot;: 31037
  10357. },
  10358. &quot;url&quot;: &quot;mxc://example.org/JWEIFJgwEIhweiWJE&quot;,
  10359. &quot;msgtype&quot;: &quot;m.image&quot;
  10360. },
  10361. &quot;type&quot;: &quot;m.room.message&quot;,
  10362. &quot;event_id&quot;: &quot;$f3h4d129462ha:example.com&quot;,
  10363. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  10364. &quot;sender&quot;: &quot;@example:example.org&quot;,
  10365. &quot;origin_server_ts&quot;: 1432735824653,
  10366. &quot;unsigned&quot;: {
  10367. &quot;age&quot;: 1234
  10368. }
  10369. },
  10370. &quot;events_before&quot;: [
  10371. {
  10372. &quot;content&quot;: {
  10373. &quot;body&quot;: &quot;something-important.doc&quot;,
  10374. &quot;filename&quot;: &quot;something-important.doc&quot;,
  10375. &quot;info&quot;: {
  10376. &quot;mimetype&quot;: &quot;application/msword&quot;,
  10377. &quot;size&quot;: 46144
  10378. },
  10379. &quot;msgtype&quot;: &quot;m.file&quot;,
  10380. &quot;url&quot;: &quot;mxc://example.org/FHyPlCeYUSFFxlgbQYZmoEoe&quot;
  10381. },
  10382. &quot;type&quot;: &quot;m.room.message&quot;,
  10383. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  10384. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  10385. &quot;sender&quot;: &quot;@example:example.org&quot;,
  10386. &quot;origin_server_ts&quot;: 1432735824653,
  10387. &quot;unsigned&quot;: {
  10388. &quot;age&quot;: 1234
  10389. }
  10390. }
  10391. ],
  10392. &quot;start&quot;: &quot;t27-54_2_0_2&quot;,
  10393. &quot;state&quot;: [
  10394. {
  10395. &quot;content&quot;: {
  10396. &quot;creator&quot;: &quot;@example:example.org&quot;,
  10397. &quot;room_version&quot;: &quot;1&quot;,
  10398. &quot;m.federate&quot;: true,
  10399. &quot;predecessor&quot;: {
  10400. &quot;event_id&quot;: &quot;$something:example.org&quot;,
  10401. &quot;room_id&quot;: &quot;!oldroom:example.org&quot;
  10402. }
  10403. },
  10404. &quot;type&quot;: &quot;m.room.create&quot;,
  10405. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  10406. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  10407. &quot;sender&quot;: &quot;@example:example.org&quot;,
  10408. &quot;origin_server_ts&quot;: 1432735824653,
  10409. &quot;unsigned&quot;: {
  10410. &quot;age&quot;: 1234
  10411. },
  10412. &quot;state_key&quot;: &quot;&quot;
  10413. },
  10414. {
  10415. &quot;content&quot;: {
  10416. &quot;membership&quot;: &quot;join&quot;,
  10417. &quot;avatar_url&quot;: &quot;mxc://example.org/SEsfnsuifSDFSSEF&quot;,
  10418. &quot;displayname&quot;: &quot;Alice Margatroid&quot;
  10419. },
  10420. &quot;type&quot;: &quot;m.room.member&quot;,
  10421. &quot;event_id&quot;: &quot;$143273582443PhrSn:example.org&quot;,
  10422. &quot;room_id&quot;: &quot;!636q39766251:example.com&quot;,
  10423. &quot;sender&quot;: &quot;@example:example.org&quot;,
  10424. &quot;origin_server_ts&quot;: 1432735824653,
  10425. &quot;unsigned&quot;: {
  10426. &quot;age&quot;: 1234
  10427. },
  10428. &quot;state_key&quot;: &quot;@alice:example.org&quot;
  10429. }
  10430. ]
  10431. }
  10432. </code></pre>
  10433. <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>
  10434. <p>The API to send notices is as follows:</p>
  10435. <pre><code>POST /_synapse/admin/v1/send_server_notice
  10436. </code></pre>
  10437. <p>or:</p>
  10438. <pre><code>PUT /_synapse/admin/v1/send_server_notice/{txnId}
  10439. </code></pre>
  10440. <p>You will need to authenticate with an access token for an admin user.</p>
  10441. <p>When using the <code>PUT</code> form, retransmissions with the same transaction ID will be
  10442. ignored in the same way as with <code>PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}</code>.</p>
  10443. <p>The request body should look something like the following:</p>
  10444. <pre><code class="language-json">{
  10445. &quot;user_id&quot;: &quot;@target_user:server_name&quot;,
  10446. &quot;content&quot;: {
  10447. &quot;msgtype&quot;: &quot;m.text&quot;,
  10448. &quot;body&quot;: &quot;This is my message&quot;
  10449. }
  10450. }
  10451. </code></pre>
  10452. <p>You can optionally include the following additional parameters:</p>
  10453. <ul>
  10454. <li><code>type</code>: the type of event. Defaults to <code>m.room.message</code>.</li>
  10455. <li><code>state_key</code>: Setting this will result in a state event being sent.</li>
  10456. </ul>
  10457. <p>Once the notice has been sent, the API will return the following response:</p>
  10458. <pre><code class="language-json">{
  10459. &quot;event_id&quot;: &quot;&lt;event_id&gt;&quot;
  10460. }
  10461. </code></pre>
  10462. <p>Note that server notices must be enabled in <code>homeserver.yaml</code> before this API
  10463. can be used. See <a href="admin_api/../server_notices.html">the server notices documentation</a> for more information.</p>
  10464. <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>
  10465. <p>Returns information about all local media usage of users. Gives the
  10466. possibility to filter them by time and user.</p>
  10467. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10468. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10469. <p>The API is:</p>
  10470. <pre><code>GET /_synapse/admin/v1/statistics/users/media
  10471. </code></pre>
  10472. <p>A response body like the following is returned:</p>
  10473. <pre><code class="language-json">{
  10474. &quot;users&quot;: [
  10475. {
  10476. &quot;displayname&quot;: &quot;foo_user_0&quot;,
  10477. &quot;media_count&quot;: 2,
  10478. &quot;media_length&quot;: 134,
  10479. &quot;user_id&quot;: &quot;@foo_user_0:test&quot;
  10480. },
  10481. {
  10482. &quot;displayname&quot;: &quot;foo_user_1&quot;,
  10483. &quot;media_count&quot;: 2,
  10484. &quot;media_length&quot;: 134,
  10485. &quot;user_id&quot;: &quot;@foo_user_1:test&quot;
  10486. }
  10487. ],
  10488. &quot;next_token&quot;: 3,
  10489. &quot;total&quot;: 10
  10490. }
  10491. </code></pre>
  10492. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint
  10493. again with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  10494. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  10495. reports to paginate through.</p>
  10496. <p><strong>Parameters</strong></p>
  10497. <p>The following parameters should be set in the URL:</p>
  10498. <ul>
  10499. <li><code>limit</code>: string representing a positive integer - Is optional but is
  10500. used for pagination, denoting the maximum number of items to return
  10501. in this call. Defaults to <code>100</code>.</li>
  10502. <li><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  10503. denoting the offset in the returned results. This should be treated as an opaque value
  10504. and not explicitly set to anything other than the return value of <code>next_token</code> from a
  10505. previous call. Defaults to <code>0</code>.</li>
  10506. <li><code>order_by</code> - string - The method in which to sort the returned list of users. Valid values are:
  10507. <ul>
  10508. <li><code>user_id</code> - Users are ordered alphabetically by <code>user_id</code>. This is the default.</li>
  10509. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  10510. <li><code>media_length</code> - Users are ordered by the total size of uploaded media in bytes.
  10511. Smallest to largest.</li>
  10512. <li><code>media_count</code> - Users are ordered by number of uploaded media. Smallest to largest.</li>
  10513. </ul>
  10514. </li>
  10515. <li><code>from_ts</code> - string representing a positive integer - Considers only
  10516. files created at this timestamp or later. Unix timestamp in ms.</li>
  10517. <li><code>until_ts</code> - string representing a positive integer - Considers only
  10518. files created at this timestamp or earlier. Unix timestamp in ms.</li>
  10519. <li><code>search_term</code> - string - Filter users by their user ID localpart <strong>or</strong> displayname.
  10520. The search term can be found in any part of the string.
  10521. Defaults to no filtering.</li>
  10522. <li><code>dir</code> - string - Direction of order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  10523. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  10524. </ul>
  10525. <p><strong>Response</strong></p>
  10526. <p>The following fields are returned in the JSON response body:</p>
  10527. <ul>
  10528. <li><code>users</code> - An array of objects, each containing information
  10529. about the user and their local media. Objects contain the following fields:
  10530. <ul>
  10531. <li><code>displayname</code> - string - Displayname of this user.</li>
  10532. <li><code>media_count</code> - integer - Number of uploaded media by this user.</li>
  10533. <li><code>media_length</code> - integer - Size of uploaded media in bytes by this user.</li>
  10534. <li><code>user_id</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  10535. </ul>
  10536. </li>
  10537. <li><code>next_token</code> - integer - Opaque value used for pagination. See above.</li>
  10538. <li><code>total</code> - integer - Total number of users after filtering.</li>
  10539. </ul>
  10540. <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>
  10541. <p>To use it, you will need to authenticate by providing an <code>access_token</code>
  10542. for a server admin: see <a href="admin_api/../usage/administration/admin_api">Admin API</a>.</p>
  10543. <h2 id="query-user-account"><a class="header" href="#query-user-account">Query User Account</a></h2>
  10544. <p>This API returns information about a specific user account.</p>
  10545. <p>The api is:</p>
  10546. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;
  10547. </code></pre>
  10548. <p>It returns a JSON body like the following:</p>
  10549. <pre><code class="language-jsonc">{
  10550. &quot;name&quot;: &quot;@user:example.com&quot;,
  10551. &quot;displayname&quot;: &quot;User&quot;, // can be null if not set
  10552. &quot;threepids&quot;: [
  10553. {
  10554. &quot;medium&quot;: &quot;email&quot;,
  10555. &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;,
  10556. &quot;added_at&quot;: 1586458409743,
  10557. &quot;validated_at&quot;: 1586458409743
  10558. },
  10559. {
  10560. &quot;medium&quot;: &quot;email&quot;,
  10561. &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;,
  10562. &quot;added_at&quot;: 1586458409743,
  10563. &quot;validated_at&quot;: 1586458409743
  10564. }
  10565. ],
  10566. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;, // can be null if not set
  10567. &quot;is_guest&quot;: 0,
  10568. &quot;admin&quot;: 0,
  10569. &quot;deactivated&quot;: 0,
  10570. &quot;shadow_banned&quot;: 0,
  10571. &quot;creation_ts&quot;: 1560432506,
  10572. &quot;appservice_id&quot;: null,
  10573. &quot;consent_server_notice_sent&quot;: null,
  10574. &quot;consent_version&quot;: null,
  10575. &quot;external_ids&quot;: [
  10576. {
  10577. &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
  10578. &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
  10579. },
  10580. {
  10581. &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
  10582. &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
  10583. }
  10584. ],
  10585. &quot;user_type&quot;: null
  10586. }
  10587. </code></pre>
  10588. <p>URL parameters:</p>
  10589. <ul>
  10590. <li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
  10591. </ul>
  10592. <h2 id="create-or-modify-account"><a class="header" href="#create-or-modify-account">Create or modify Account</a></h2>
  10593. <p>This API allows an administrator to create or modify a user account with a
  10594. specific <code>user_id</code>.</p>
  10595. <p>This api is:</p>
  10596. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;
  10597. </code></pre>
  10598. <p>with a body of:</p>
  10599. <pre><code class="language-json">{
  10600. &quot;password&quot;: &quot;user_password&quot;,
  10601. &quot;displayname&quot;: &quot;User&quot;,
  10602. &quot;threepids&quot;: [
  10603. {
  10604. &quot;medium&quot;: &quot;email&quot;,
  10605. &quot;address&quot;: &quot;&lt;user_mail_1&gt;&quot;
  10606. },
  10607. {
  10608. &quot;medium&quot;: &quot;email&quot;,
  10609. &quot;address&quot;: &quot;&lt;user_mail_2&gt;&quot;
  10610. }
  10611. ],
  10612. &quot;external_ids&quot;: [
  10613. {
  10614. &quot;auth_provider&quot;: &quot;&lt;provider1&gt;&quot;,
  10615. &quot;external_id&quot;: &quot;&lt;user_id_provider_1&gt;&quot;
  10616. },
  10617. {
  10618. &quot;auth_provider&quot;: &quot;&lt;provider2&gt;&quot;,
  10619. &quot;external_id&quot;: &quot;&lt;user_id_provider_2&gt;&quot;
  10620. }
  10621. ],
  10622. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
  10623. &quot;admin&quot;: false,
  10624. &quot;deactivated&quot;: false,
  10625. &quot;user_type&quot;: null
  10626. }
  10627. </code></pre>
  10628. <p>Returns HTTP status code:</p>
  10629. <ul>
  10630. <li><code>201</code> - When a new user object was created.</li>
  10631. <li><code>200</code> - When a user was modified.</li>
  10632. </ul>
  10633. <p>URL parameters:</p>
  10634. <ul>
  10635. <li><code>user_id</code>: fully-qualified user id: for example, <code>@user:server.com</code>.</li>
  10636. </ul>
  10637. <p>Body parameters:</p>
  10638. <ul>
  10639. <li><code>password</code> - string, optional. If provided, the user's password is updated and all
  10640. devices are logged out.</li>
  10641. <li><code>displayname</code> - string, optional, defaults to the value of <code>user_id</code>.</li>
  10642. <li><code>threepids</code> - array, optional, allows setting the third-party IDs (email, msisdn)
  10643. <ul>
  10644. <li><code>medium</code> - string. Kind of third-party ID, either <code>email</code> or <code>msisdn</code>.</li>
  10645. <li><code>address</code> - string. Value of third-party ID.
  10646. belonging to a user.</li>
  10647. </ul>
  10648. </li>
  10649. <li><code>external_ids</code> - array, optional. Allow setting the identifier of the external identity
  10650. provider for SSO (Single sign-on). Details in
  10651. <a href="admin_api/../usage/configuration/homeserver_sample_config.html">Sample Configuration File</a>
  10652. section <code>sso</code> and <code>oidc_providers</code>.
  10653. <ul>
  10654. <li><code>auth_provider</code> - string. ID of the external identity provider. Value of <code>idp_id</code>
  10655. in homeserver configuration.</li>
  10656. <li><code>external_id</code> - string, user ID in the external identity provider.</li>
  10657. </ul>
  10658. </li>
  10659. <li><code>avatar_url</code> - string, optional, must be a
  10660. <a href="https://matrix.org/docs/spec/client_server/r0.6.0#matrix-content-mxc-uris">MXC URI</a>.</li>
  10661. <li><code>admin</code> - bool, optional, defaults to <code>false</code>.</li>
  10662. <li><code>deactivated</code> - bool, optional. If unspecified, deactivation state will be left
  10663. unchanged on existing accounts and set to <code>false</code> for new accounts.
  10664. A user cannot be erased by deactivating with this API. For details on
  10665. deactivating users see <a href="admin_api/user_admin_api.html#deactivate-account">Deactivate Account</a>.</li>
  10666. <li><code>user_type</code> - string or null, optional. If provided, the user type will be
  10667. adjusted. If <code>null</code> given, the user type will be cleared. Other
  10668. allowed options are: <code>bot</code> and <code>support</code>.</li>
  10669. </ul>
  10670. <p>If the user already exists then optional parameters default to the current value.</p>
  10671. <p>In order to re-activate an account <code>deactivated</code> must be set to <code>false</code>. If
  10672. users do not login via single-sign-on, a new <code>password</code> must be provided.</p>
  10673. <h2 id="list-accounts"><a class="header" href="#list-accounts">List Accounts</a></h2>
  10674. <p>This API returns all local user accounts.
  10675. By default, the response is ordered by ascending user ID.</p>
  10676. <pre><code>GET /_synapse/admin/v2/users?from=0&amp;limit=10&amp;guests=false
  10677. </code></pre>
  10678. <p>A response body like the following is returned:</p>
  10679. <pre><code class="language-json">{
  10680. &quot;users&quot;: [
  10681. {
  10682. &quot;name&quot;: &quot;&lt;user_id1&gt;&quot;,
  10683. &quot;is_guest&quot;: 0,
  10684. &quot;admin&quot;: 0,
  10685. &quot;user_type&quot;: null,
  10686. &quot;deactivated&quot;: 0,
  10687. &quot;shadow_banned&quot;: 0,
  10688. &quot;displayname&quot;: &quot;&lt;User One&gt;&quot;,
  10689. &quot;avatar_url&quot;: null,
  10690. &quot;creation_ts&quot;: 1560432668000
  10691. }, {
  10692. &quot;name&quot;: &quot;&lt;user_id2&gt;&quot;,
  10693. &quot;is_guest&quot;: 0,
  10694. &quot;admin&quot;: 1,
  10695. &quot;user_type&quot;: null,
  10696. &quot;deactivated&quot;: 0,
  10697. &quot;shadow_banned&quot;: 0,
  10698. &quot;displayname&quot;: &quot;&lt;User Two&gt;&quot;,
  10699. &quot;avatar_url&quot;: &quot;&lt;avatar_url&gt;&quot;,
  10700. &quot;creation_ts&quot;: 1561550621000
  10701. }
  10702. ],
  10703. &quot;next_token&quot;: &quot;100&quot;,
  10704. &quot;total&quot;: 200
  10705. }
  10706. </code></pre>
  10707. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  10708. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  10709. <p>If the endpoint does not return a <code>next_token</code> then there are no more users
  10710. to paginate through.</p>
  10711. <p><strong>Parameters</strong></p>
  10712. <p>The following parameters should be set in the URL:</p>
  10713. <ul>
  10714. <li>
  10715. <p><code>user_id</code> - Is optional and filters to only return users with user IDs
  10716. that contain this value. This parameter is ignored when using the <code>name</code> parameter.</p>
  10717. </li>
  10718. <li>
  10719. <p><code>name</code> - Is optional and filters to only return users with user ID localparts
  10720. <strong>or</strong> displaynames that contain this value.</p>
  10721. </li>
  10722. <li>
  10723. <p><code>guests</code> - string representing a bool - Is optional and if <code>false</code> will <strong>exclude</strong> guest users.
  10724. Defaults to <code>true</code> to include guest users.</p>
  10725. </li>
  10726. <li>
  10727. <p><code>deactivated</code> - string representing a bool - Is optional and if <code>true</code> will <strong>include</strong> deactivated users.
  10728. Defaults to <code>false</code> to exclude deactivated users.</p>
  10729. </li>
  10730. <li>
  10731. <p><code>limit</code> - string representing a positive integer - Is optional but is used for pagination,
  10732. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  10733. </li>
  10734. <li>
  10735. <p><code>from</code> - string representing a positive integer - Is optional but used for pagination,
  10736. denoting the offset in the returned results. This should be treated as an opaque value and
  10737. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  10738. Defaults to <code>0</code>.</p>
  10739. </li>
  10740. <li>
  10741. <p><code>order_by</code> - The method by which to sort the returned list of users.
  10742. If the ordered field has duplicates, the second order is always by ascending <code>name</code>,
  10743. which guarantees a stable ordering. Valid values are:</p>
  10744. <ul>
  10745. <li><code>name</code> - Users are ordered alphabetically by <code>name</code>. This is the default.</li>
  10746. <li><code>is_guest</code> - Users are ordered by <code>is_guest</code> status.</li>
  10747. <li><code>admin</code> - Users are ordered by <code>admin</code> status.</li>
  10748. <li><code>user_type</code> - Users are ordered alphabetically by <code>user_type</code>.</li>
  10749. <li><code>deactivated</code> - Users are ordered by <code>deactivated</code> status.</li>
  10750. <li><code>shadow_banned</code> - Users are ordered by <code>shadow_banned</code> status.</li>
  10751. <li><code>displayname</code> - Users are ordered alphabetically by <code>displayname</code>.</li>
  10752. <li><code>avatar_url</code> - Users are ordered alphabetically by avatar URL.</li>
  10753. <li><code>creation_ts</code> - Users are ordered by when the users was created in ms.</li>
  10754. </ul>
  10755. </li>
  10756. <li>
  10757. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  10758. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  10759. </li>
  10760. </ul>
  10761. <p>Caution. The database only has indexes on the columns <code>name</code> and <code>creation_ts</code>.
  10762. This means that if a different sort order is used (<code>is_guest</code>, <code>admin</code>,
  10763. <code>user_type</code>, <code>deactivated</code>, <code>shadow_banned</code>, <code>avatar_url</code> or <code>displayname</code>),
  10764. this can cause a large load on the database, especially for large environments.</p>
  10765. <p><strong>Response</strong></p>
  10766. <p>The following fields are returned in the JSON response body:</p>
  10767. <ul>
  10768. <li>
  10769. <p><code>users</code> - An array of objects, each containing information about an user.
  10770. User objects contain the following fields:</p>
  10771. <ul>
  10772. <li><code>name</code> - string - Fully-qualified user ID (ex. <code>@user:server.com</code>).</li>
  10773. <li><code>is_guest</code> - bool - Status if that user is a guest account.</li>
  10774. <li><code>admin</code> - bool - Status if that user is a server administrator.</li>
  10775. <li><code>user_type</code> - string - Type of the user. Normal users are type <code>None</code>.
  10776. This allows user type specific behaviour. There are also types <code>support</code> and <code>bot</code>. </li>
  10777. <li><code>deactivated</code> - bool - Status if that user has been marked as deactivated.</li>
  10778. <li><code>shadow_banned</code> - bool - Status if that user has been marked as shadow banned.</li>
  10779. <li><code>displayname</code> - string - The user's display name if they have set one.</li>
  10780. <li><code>avatar_url</code> - string - The user's avatar URL if they have set one.</li>
  10781. <li><code>creation_ts</code> - integer - The user's creation timestamp in ms.</li>
  10782. </ul>
  10783. </li>
  10784. <li>
  10785. <p><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</p>
  10786. </li>
  10787. <li>
  10788. <p><code>total</code> - integer - Total number of media.</p>
  10789. </li>
  10790. </ul>
  10791. <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>
  10792. <p>This API returns information about the active sessions for a specific user.</p>
  10793. <p>The endpoints are:</p>
  10794. <pre><code>GET /_synapse/admin/v1/whois/&lt;user_id&gt;
  10795. </code></pre>
  10796. <p>and:</p>
  10797. <pre><code>GET /_matrix/client/r0/admin/whois/&lt;userId&gt;
  10798. </code></pre>
  10799. <p>See also: <a href="https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-admin-whois-userid">Client Server
  10800. API Whois</a>.</p>
  10801. <p>It returns a JSON body like the following:</p>
  10802. <pre><code class="language-json">{
  10803. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;,
  10804. &quot;devices&quot;: {
  10805. &quot;&quot;: {
  10806. &quot;sessions&quot;: [
  10807. {
  10808. &quot;connections&quot;: [
  10809. {
  10810. &quot;ip&quot;: &quot;1.2.3.4&quot;,
  10811. &quot;last_seen&quot;: 1417222374433,
  10812. &quot;user_agent&quot;: &quot;Mozilla/5.0 ...&quot;
  10813. },
  10814. {
  10815. &quot;ip&quot;: &quot;1.2.3.10&quot;,
  10816. &quot;last_seen&quot;: 1417222374500,
  10817. &quot;user_agent&quot;: &quot;Dalvik/2.1.0 ...&quot;
  10818. }
  10819. ]
  10820. }
  10821. ]
  10822. }
  10823. }
  10824. }
  10825. </code></pre>
  10826. <p><code>last_seen</code> is measured in milliseconds since the Unix epoch.</p>
  10827. <h2 id="deactivate-account"><a class="header" href="#deactivate-account">Deactivate Account</a></h2>
  10828. <p>This API deactivates an account. It removes active access tokens, resets the
  10829. password, and deletes third-party IDs (to prevent the user requesting a
  10830. password reset).</p>
  10831. <p>It can also mark the user as GDPR-erased. This means messages sent by the
  10832. user will still be visible by anyone that was in the room when these messages
  10833. were sent, but hidden from users joining the room afterwards.</p>
  10834. <p>The api is:</p>
  10835. <pre><code>POST /_synapse/admin/v1/deactivate/&lt;user_id&gt;
  10836. </code></pre>
  10837. <p>with a body of:</p>
  10838. <pre><code class="language-json">{
  10839. &quot;erase&quot;: true
  10840. }
  10841. </code></pre>
  10842. <p>The erase parameter is optional and defaults to <code>false</code>.
  10843. An empty body may be passed for backwards compatibility.</p>
  10844. <p>The following actions are performed when deactivating an user:</p>
  10845. <ul>
  10846. <li>Try to unbind 3PIDs from the identity server</li>
  10847. <li>Remove all 3PIDs from the homeserver</li>
  10848. <li>Delete all devices and E2EE keys</li>
  10849. <li>Delete all access tokens</li>
  10850. <li>Delete all pushers</li>
  10851. <li>Delete the password hash</li>
  10852. <li>Removal from all rooms the user is a member of</li>
  10853. <li>Remove the user from the user directory</li>
  10854. <li>Reject all pending invites</li>
  10855. <li>Remove all account validity information related to the user</li>
  10856. <li>Remove the arbitrary data store known as <em>account data</em>. For example, this includes:
  10857. <ul>
  10858. <li>list of ignored users;</li>
  10859. <li>push rules;</li>
  10860. <li>secret storage keys; and</li>
  10861. <li>cross-signing keys.</li>
  10862. </ul>
  10863. </li>
  10864. </ul>
  10865. <p>The following additional actions are performed during deactivation if <code>erase</code>
  10866. is set to <code>true</code>:</p>
  10867. <ul>
  10868. <li>Remove the user's display name</li>
  10869. <li>Remove the user's avatar URL</li>
  10870. <li>Mark the user as erased</li>
  10871. </ul>
  10872. <p>The following actions are <strong>NOT</strong> performed. The list may be incomplete.</p>
  10873. <ul>
  10874. <li>Remove mappings of SSO IDs</li>
  10875. <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>
  10876. <li>Delete sent and received messages</li>
  10877. <li>Remove the user's creation (registration) timestamp</li>
  10878. <li><a href="admin_api/user_admin_api.html#override-ratelimiting-for-users">Remove rate limit overrides</a></li>
  10879. <li>Remove from monthly active users</li>
  10880. </ul>
  10881. <h2 id="reset-password"><a class="header" href="#reset-password">Reset password</a></h2>
  10882. <p>Changes the password of another user. This will automatically log the user out of all their devices.</p>
  10883. <p>The api is:</p>
  10884. <pre><code>POST /_synapse/admin/v1/reset_password/&lt;user_id&gt;
  10885. </code></pre>
  10886. <p>with a body of:</p>
  10887. <pre><code class="language-json">{
  10888. &quot;new_password&quot;: &quot;&lt;secret&gt;&quot;,
  10889. &quot;logout_devices&quot;: true
  10890. }
  10891. </code></pre>
  10892. <p>The parameter <code>new_password</code> is required.
  10893. The parameter <code>logout_devices</code> is optional and defaults to <code>true</code>.</p>
  10894. <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>
  10895. <p>The api is:</p>
  10896. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  10897. </code></pre>
  10898. <p>A response body like the following is returned:</p>
  10899. <pre><code class="language-json">{
  10900. &quot;admin&quot;: true
  10901. }
  10902. </code></pre>
  10903. <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>
  10904. <p>Note that you cannot demote yourself.</p>
  10905. <p>The api is:</p>
  10906. <pre><code>PUT /_synapse/admin/v1/users/&lt;user_id&gt;/admin
  10907. </code></pre>
  10908. <p>with a body of:</p>
  10909. <pre><code class="language-json">{
  10910. &quot;admin&quot;: true
  10911. }
  10912. </code></pre>
  10913. <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>
  10914. <p>Gets a list of all <code>room_id</code> that a specific <code>user_id</code> is member.</p>
  10915. <p>The API is:</p>
  10916. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/joined_rooms
  10917. </code></pre>
  10918. <p>A response body like the following is returned:</p>
  10919. <pre><code class="language-json"> {
  10920. &quot;joined_rooms&quot;: [
  10921. &quot;!DuGcnbhHGaSZQoNQR:matrix.org&quot;,
  10922. &quot;!ZtSaPCawyWtxfWiIy:matrix.org&quot;
  10923. ],
  10924. &quot;total&quot;: 2
  10925. }
  10926. </code></pre>
  10927. <p>The server returns the list of rooms of which the user and the server
  10928. are member. If the user is local, all the rooms of which the user is
  10929. member are returned.</p>
  10930. <p><strong>Parameters</strong></p>
  10931. <p>The following parameters should be set in the URL:</p>
  10932. <ul>
  10933. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  10934. </ul>
  10935. <p><strong>Response</strong></p>
  10936. <p>The following fields are returned in the JSON response body:</p>
  10937. <ul>
  10938. <li><code>joined_rooms</code> - An array of <code>room_id</code>.</li>
  10939. <li><code>total</code> - Number of rooms.</li>
  10940. </ul>
  10941. <h2 id="account-data"><a class="header" href="#account-data">Account Data</a></h2>
  10942. <p>Gets information about account data for a specific <code>user_id</code>.</p>
  10943. <p>The API is:</p>
  10944. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/accountdata
  10945. </code></pre>
  10946. <p>A response body like the following is returned:</p>
  10947. <pre><code class="language-json">{
  10948. &quot;account_data&quot;: {
  10949. &quot;global&quot;: {
  10950. &quot;m.secret_storage.key.LmIGHTg5W&quot;: {
  10951. &quot;algorithm&quot;: &quot;m.secret_storage.v1.aes-hmac-sha2&quot;,
  10952. &quot;iv&quot;: &quot;fwjNZatxg==&quot;,
  10953. &quot;mac&quot;: &quot;eWh9kNnLWZUNOgnc=&quot;
  10954. },
  10955. &quot;im.vector.hide_profile&quot;: {
  10956. &quot;hide_profile&quot;: true
  10957. },
  10958. &quot;org.matrix.preview_urls&quot;: {
  10959. &quot;disable&quot;: false
  10960. },
  10961. &quot;im.vector.riot.breadcrumb_rooms&quot;: {
  10962. &quot;rooms&quot;: [
  10963. &quot;!LxcBDAsDUVAfJDEo:matrix.org&quot;,
  10964. &quot;!MAhRxqasbItjOqxu:matrix.org&quot;
  10965. ]
  10966. },
  10967. &quot;m.accepted_terms&quot;: {
  10968. &quot;accepted&quot;: [
  10969. &quot;https://example.org/somewhere/privacy-1.2-en.html&quot;,
  10970. &quot;https://example.org/somewhere/terms-2.0-en.html&quot;
  10971. ]
  10972. },
  10973. &quot;im.vector.setting.breadcrumbs&quot;: {
  10974. &quot;recent_rooms&quot;: [
  10975. &quot;!MAhRxqasbItqxuEt:matrix.org&quot;,
  10976. &quot;!ZtSaPCawyWtxiImy:matrix.org&quot;
  10977. ]
  10978. }
  10979. },
  10980. &quot;rooms&quot;: {
  10981. &quot;!GUdfZSHUJibpiVqHYd:matrix.org&quot;: {
  10982. &quot;m.fully_read&quot;: {
  10983. &quot;event_id&quot;: &quot;$156334540fYIhZ:matrix.org&quot;
  10984. }
  10985. },
  10986. &quot;!tOZwOOiqwCYQkLhV:matrix.org&quot;: {
  10987. &quot;m.fully_read&quot;: {
  10988. &quot;event_id&quot;: &quot;$xjsIyp4_NaVl2yPvIZs_k1Jl8tsC_Sp23wjqXPno&quot;
  10989. }
  10990. }
  10991. }
  10992. }
  10993. }
  10994. </code></pre>
  10995. <p><strong>Parameters</strong></p>
  10996. <p>The following parameters should be set in the URL:</p>
  10997. <ul>
  10998. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  10999. </ul>
  11000. <p><strong>Response</strong></p>
  11001. <p>The following fields are returned in the JSON response body:</p>
  11002. <ul>
  11003. <li><code>account_data</code> - A map containing the account data for the user
  11004. <ul>
  11005. <li><code>global</code> - A map containing the global account data for the user</li>
  11006. <li><code>rooms</code> - A map containing the account data per room for the user</li>
  11007. </ul>
  11008. </li>
  11009. </ul>
  11010. <h2 id="user-media"><a class="header" href="#user-media">User media</a></h2>
  11011. <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>
  11012. <p>Gets a list of all local media that a specific <code>user_id</code> has created.
  11013. These are media that the user has uploaded themselves
  11014. (<a href="admin_api/../media_repository.html#local-media">local media</a>), as well as
  11015. <a href="admin_api/../media_repository.html#url-previews">URL preview images</a> requested by the user if the
  11016. <a href="admin_api/../development/url_previews.html">feature is enabled</a>.</p>
  11017. <p>By default, the response is ordered by descending creation date and ascending media ID.
  11018. The newest media is on top. You can change the order with parameters
  11019. <code>order_by</code> and <code>dir</code>.</p>
  11020. <p>The API is:</p>
  11021. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/media
  11022. </code></pre>
  11023. <p>A response body like the following is returned:</p>
  11024. <pre><code class="language-json">{
  11025. &quot;media&quot;: [
  11026. {
  11027. &quot;created_ts&quot;: 100400,
  11028. &quot;last_access_ts&quot;: null,
  11029. &quot;media_id&quot;: &quot;qXhyRzulkwLsNHTbpHreuEgo&quot;,
  11030. &quot;media_length&quot;: 67,
  11031. &quot;media_type&quot;: &quot;image/png&quot;,
  11032. &quot;quarantined_by&quot;: null,
  11033. &quot;safe_from_quarantine&quot;: false,
  11034. &quot;upload_name&quot;: &quot;test1.png&quot;
  11035. },
  11036. {
  11037. &quot;created_ts&quot;: 200400,
  11038. &quot;last_access_ts&quot;: null,
  11039. &quot;media_id&quot;: &quot;FHfiSnzoINDatrXHQIXBtahw&quot;,
  11040. &quot;media_length&quot;: 67,
  11041. &quot;media_type&quot;: &quot;image/png&quot;,
  11042. &quot;quarantined_by&quot;: null,
  11043. &quot;safe_from_quarantine&quot;: false,
  11044. &quot;upload_name&quot;: &quot;test2.png&quot;
  11045. }
  11046. ],
  11047. &quot;next_token&quot;: 3,
  11048. &quot;total&quot;: 2
  11049. }
  11050. </code></pre>
  11051. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  11052. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  11053. <p>If the endpoint does not return a <code>next_token</code> then there are no more
  11054. reports to paginate through.</p>
  11055. <p><strong>Parameters</strong></p>
  11056. <p>The following parameters should be set in the URL:</p>
  11057. <ul>
  11058. <li>
  11059. <p><code>user_id</code> - string - fully qualified: for example, <code>@user:server.com</code>.</p>
  11060. </li>
  11061. <li>
  11062. <p><code>limit</code>: string representing a positive integer - Is optional but is used for pagination,
  11063. denoting the maximum number of items to return in this call. Defaults to <code>100</code>.</p>
  11064. </li>
  11065. <li>
  11066. <p><code>from</code>: string representing a positive integer - Is optional but used for pagination,
  11067. denoting the offset in the returned results. This should be treated as an opaque value and
  11068. not explicitly set to anything other than the return value of <code>next_token</code> from a previous call.
  11069. Defaults to <code>0</code>.</p>
  11070. </li>
  11071. <li>
  11072. <p><code>order_by</code> - The method by which to sort the returned list of media.
  11073. If the ordered field has duplicates, the second order is always by ascending <code>media_id</code>,
  11074. which guarantees a stable ordering. Valid values are:</p>
  11075. <ul>
  11076. <li><code>media_id</code> - Media are ordered alphabetically by <code>media_id</code>.</li>
  11077. <li><code>upload_name</code> - Media are ordered alphabetically by name the media was uploaded with.</li>
  11078. <li><code>created_ts</code> - Media are ordered by when the content was uploaded in ms.
  11079. Smallest to largest. This is the default.</li>
  11080. <li><code>last_access_ts</code> - Media are ordered by when the content was last accessed in ms.
  11081. Smallest to largest.</li>
  11082. <li><code>media_length</code> - Media are ordered by length of the media in bytes.
  11083. Smallest to largest.</li>
  11084. <li><code>media_type</code> - Media are ordered alphabetically by MIME-type.</li>
  11085. <li><code>quarantined_by</code> - Media are ordered alphabetically by the user ID that
  11086. initiated the quarantine request for this media.</li>
  11087. <li><code>safe_from_quarantine</code> - Media are ordered by the status if this media is safe
  11088. from quarantining.</li>
  11089. </ul>
  11090. </li>
  11091. <li>
  11092. <p><code>dir</code> - Direction of media order. Either <code>f</code> for forwards or <code>b</code> for backwards.
  11093. Setting this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</p>
  11094. </li>
  11095. </ul>
  11096. <p>If neither <code>order_by</code> nor <code>dir</code> is set, the default order is newest media on top
  11097. (corresponds to <code>order_by</code> = <code>created_ts</code> and <code>dir</code> = <code>b</code>).</p>
  11098. <p>Caution. The database only has indexes on the columns <code>media_id</code>,
  11099. <code>user_id</code> and <code>created_ts</code>. This means that if a different sort order is used
  11100. (<code>upload_name</code>, <code>last_access_ts</code>, <code>media_length</code>, <code>media_type</code>,
  11101. <code>quarantined_by</code> or <code>safe_from_quarantine</code>), this can cause a large load on the
  11102. database, especially for large environments.</p>
  11103. <p><strong>Response</strong></p>
  11104. <p>The following fields are returned in the JSON response body:</p>
  11105. <ul>
  11106. <li><code>media</code> - An array of objects, each containing information about a media.
  11107. Media objects contain the following fields:
  11108. <ul>
  11109. <li><code>created_ts</code> - integer - Timestamp when the content was uploaded in ms.</li>
  11110. <li><code>last_access_ts</code> - integer - Timestamp when the content was last accessed in ms.</li>
  11111. <li><code>media_id</code> - string - The id used to refer to the media. Details about the format
  11112. are documented under
  11113. <a href="admin_api/../media_repository.html">media repository</a>.</li>
  11114. <li><code>media_length</code> - integer - Length of the media in bytes.</li>
  11115. <li><code>media_type</code> - string - The MIME-type of the media.</li>
  11116. <li><code>quarantined_by</code> - string - The user ID that initiated the quarantine request
  11117. for this media.</li>
  11118. <li><code>safe_from_quarantine</code> - bool - Status if this media is safe from quarantining.</li>
  11119. <li><code>upload_name</code> - string - The name the media was uploaded with.</li>
  11120. </ul>
  11121. </li>
  11122. <li><code>next_token</code>: integer - Indication for pagination. See above.</li>
  11123. <li><code>total</code> - integer - Total number of media.</li>
  11124. </ul>
  11125. <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>
  11126. <p>This API deletes the <em>local</em> media from the disk of your own server
  11127. that a specific <code>user_id</code> has created. This includes any local thumbnails.</p>
  11128. <p>This API will not affect media that has been uploaded to external
  11129. media repositories (e.g https://github.com/turt2live/matrix-media-repo/).</p>
  11130. <p>By default, the API deletes media ordered by descending creation date and ascending media ID.
  11131. The newest media is deleted first. You can change the order with parameters
  11132. <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>
  11133. <p>The API is:</p>
  11134. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/media
  11135. </code></pre>
  11136. <p>A response body like the following is returned:</p>
  11137. <pre><code class="language-json">{
  11138. &quot;deleted_media&quot;: [
  11139. &quot;abcdefghijklmnopqrstuvwx&quot;
  11140. ],
  11141. &quot;total&quot;: 1
  11142. }
  11143. </code></pre>
  11144. <p>The following fields are returned in the JSON response body:</p>
  11145. <ul>
  11146. <li><code>deleted_media</code>: an array of strings - List of deleted <code>media_id</code></li>
  11147. <li><code>total</code>: integer - Total number of deleted <code>media_id</code></li>
  11148. </ul>
  11149. <p><strong>Note</strong>: There is no <code>next_token</code>. This is not useful for deleting media, because
  11150. after deleting media the remaining media have a new order.</p>
  11151. <p><strong>Parameters</strong></p>
  11152. <p>This API has the same parameters as
  11153. <a href="admin_api/user_admin_api.html#list-media-uploaded-by-a-user">List media uploaded by a user</a>.
  11154. With the parameters you can for example limit the number of files to delete at once or
  11155. delete largest/smallest or newest/oldest files first.</p>
  11156. <h2 id="login-as-a-user"><a class="header" href="#login-as-a-user">Login as a user</a></h2>
  11157. <p>Get an access token that can be used to authenticate as that user. Useful for
  11158. when admins wish to do actions on behalf of a user.</p>
  11159. <p>The API is:</p>
  11160. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/login
  11161. {}
  11162. </code></pre>
  11163. <p>An optional <code>valid_until_ms</code> field can be specified in the request body as an
  11164. integer timestamp that specifies when the token should expire. By default tokens
  11165. do not expire.</p>
  11166. <p>A response body like the following is returned:</p>
  11167. <pre><code class="language-json">{
  11168. &quot;access_token&quot;: &quot;&lt;opaque_access_token_string&gt;&quot;
  11169. }
  11170. </code></pre>
  11171. <p>This API does <em>not</em> generate a new device for the user, and so will not appear
  11172. their <code>/devices</code> list, and in general the target user should not be able to
  11173. tell they have been logged in as.</p>
  11174. <p>To expire the token call the standard <code>/logout</code> API with the token.</p>
  11175. <p>Note: The token will expire if the <em>admin</em> user calls <code>/logout/all</code> from any
  11176. of their devices, but the token will <em>not</em> expire if the target user does the
  11177. same.</p>
  11178. <h2 id="user-devices"><a class="header" href="#user-devices">User devices</a></h2>
  11179. <h3 id="list-all-devices"><a class="header" href="#list-all-devices">List all devices</a></h3>
  11180. <p>Gets information about all devices for a specific <code>user_id</code>.</p>
  11181. <p>The API is:</p>
  11182. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices
  11183. </code></pre>
  11184. <p>A response body like the following is returned:</p>
  11185. <pre><code class="language-json">{
  11186. &quot;devices&quot;: [
  11187. {
  11188. &quot;device_id&quot;: &quot;QBUAZIFURK&quot;,
  11189. &quot;display_name&quot;: &quot;android&quot;,
  11190. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  11191. &quot;last_seen_ts&quot;: 1474491775024,
  11192. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  11193. },
  11194. {
  11195. &quot;device_id&quot;: &quot;AUIECTSRND&quot;,
  11196. &quot;display_name&quot;: &quot;ios&quot;,
  11197. &quot;last_seen_ip&quot;: &quot;1.2.3.5&quot;,
  11198. &quot;last_seen_ts&quot;: 1474491775025,
  11199. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  11200. }
  11201. ],
  11202. &quot;total&quot;: 2
  11203. }
  11204. </code></pre>
  11205. <p><strong>Parameters</strong></p>
  11206. <p>The following parameters should be set in the URL:</p>
  11207. <ul>
  11208. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  11209. </ul>
  11210. <p><strong>Response</strong></p>
  11211. <p>The following fields are returned in the JSON response body:</p>
  11212. <ul>
  11213. <li>
  11214. <p><code>devices</code> - An array of objects, each containing information about a device.
  11215. Device objects contain the following fields:</p>
  11216. <ul>
  11217. <li><code>device_id</code> - Identifier of device.</li>
  11218. <li><code>display_name</code> - Display name set by the user for this device.
  11219. Absent if no name has been set.</li>
  11220. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  11221. (May be a few minutes out of date, for efficiency reasons).</li>
  11222. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  11223. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  11224. <li><code>user_id</code> - Owner of device.</li>
  11225. </ul>
  11226. </li>
  11227. <li>
  11228. <p><code>total</code> - Total number of user's devices.</p>
  11229. </li>
  11230. </ul>
  11231. <h3 id="delete-multiple-devices"><a class="header" href="#delete-multiple-devices">Delete multiple devices</a></h3>
  11232. <p>Deletes the given devices for a specific <code>user_id</code>, and invalidates
  11233. any access token associated with them.</p>
  11234. <p>The API is:</p>
  11235. <pre><code>POST /_synapse/admin/v2/users/&lt;user_id&gt;/delete_devices
  11236. {
  11237. &quot;devices&quot;: [
  11238. &quot;QBUAZIFURK&quot;,
  11239. &quot;AUIECTSRND&quot;
  11240. ],
  11241. }
  11242. </code></pre>
  11243. <p>An empty JSON dict is returned.</p>
  11244. <p><strong>Parameters</strong></p>
  11245. <p>The following parameters should be set in the URL:</p>
  11246. <ul>
  11247. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  11248. </ul>
  11249. <p>The following fields are required in the JSON request body:</p>
  11250. <ul>
  11251. <li><code>devices</code> - The list of device IDs to delete.</li>
  11252. </ul>
  11253. <h3 id="show-a-device"><a class="header" href="#show-a-device">Show a device</a></h3>
  11254. <p>Gets information on a single device, by <code>device_id</code> for a specific <code>user_id</code>.</p>
  11255. <p>The API is:</p>
  11256. <pre><code>GET /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  11257. </code></pre>
  11258. <p>A response body like the following is returned:</p>
  11259. <pre><code class="language-json">{
  11260. &quot;device_id&quot;: &quot;&lt;device_id&gt;&quot;,
  11261. &quot;display_name&quot;: &quot;android&quot;,
  11262. &quot;last_seen_ip&quot;: &quot;1.2.3.4&quot;,
  11263. &quot;last_seen_ts&quot;: 1474491775024,
  11264. &quot;user_id&quot;: &quot;&lt;user_id&gt;&quot;
  11265. }
  11266. </code></pre>
  11267. <p><strong>Parameters</strong></p>
  11268. <p>The following parameters should be set in the URL:</p>
  11269. <ul>
  11270. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  11271. <li><code>device_id</code> - The device to retrieve.</li>
  11272. </ul>
  11273. <p><strong>Response</strong></p>
  11274. <p>The following fields are returned in the JSON response body:</p>
  11275. <ul>
  11276. <li><code>device_id</code> - Identifier of device.</li>
  11277. <li><code>display_name</code> - Display name set by the user for this device.
  11278. Absent if no name has been set.</li>
  11279. <li><code>last_seen_ip</code> - The IP address where this device was last seen.
  11280. (May be a few minutes out of date, for efficiency reasons).</li>
  11281. <li><code>last_seen_ts</code> - The timestamp (in milliseconds since the unix epoch) when this
  11282. devices was last seen. (May be a few minutes out of date, for efficiency reasons).</li>
  11283. <li><code>user_id</code> - Owner of device.</li>
  11284. </ul>
  11285. <h3 id="update-a-device"><a class="header" href="#update-a-device">Update a device</a></h3>
  11286. <p>Updates the metadata on the given <code>device_id</code> for a specific <code>user_id</code>.</p>
  11287. <p>The API is:</p>
  11288. <pre><code>PUT /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  11289. {
  11290. &quot;display_name&quot;: &quot;My other phone&quot;
  11291. }
  11292. </code></pre>
  11293. <p>An empty JSON dict is returned.</p>
  11294. <p><strong>Parameters</strong></p>
  11295. <p>The following parameters should be set in the URL:</p>
  11296. <ul>
  11297. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  11298. <li><code>device_id</code> - The device to update.</li>
  11299. </ul>
  11300. <p>The following fields are required in the JSON request body:</p>
  11301. <ul>
  11302. <li><code>display_name</code> - The new display name for this device. If not given,
  11303. the display name is unchanged.</li>
  11304. </ul>
  11305. <h3 id="delete-a-device"><a class="header" href="#delete-a-device">Delete a device</a></h3>
  11306. <p>Deletes the given <code>device_id</code> for a specific <code>user_id</code>,
  11307. and invalidates any access token associated with it.</p>
  11308. <p>The API is:</p>
  11309. <pre><code>DELETE /_synapse/admin/v2/users/&lt;user_id&gt;/devices/&lt;device_id&gt;
  11310. {}
  11311. </code></pre>
  11312. <p>An empty JSON dict is returned.</p>
  11313. <p><strong>Parameters</strong></p>
  11314. <p>The following parameters should be set in the URL:</p>
  11315. <ul>
  11316. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  11317. <li><code>device_id</code> - The device to delete.</li>
  11318. </ul>
  11319. <h2 id="list-all-pushers"><a class="header" href="#list-all-pushers">List all pushers</a></h2>
  11320. <p>Gets information about all pushers for a specific <code>user_id</code>.</p>
  11321. <p>The API is:</p>
  11322. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/pushers
  11323. </code></pre>
  11324. <p>A response body like the following is returned:</p>
  11325. <pre><code class="language-json">{
  11326. &quot;pushers&quot;: [
  11327. {
  11328. &quot;app_display_name&quot;:&quot;HTTP Push Notifications&quot;,
  11329. &quot;app_id&quot;:&quot;m.http&quot;,
  11330. &quot;data&quot;: {
  11331. &quot;url&quot;:&quot;example.com&quot;
  11332. },
  11333. &quot;device_display_name&quot;:&quot;pushy push&quot;,
  11334. &quot;kind&quot;:&quot;http&quot;,
  11335. &quot;lang&quot;:&quot;None&quot;,
  11336. &quot;profile_tag&quot;:&quot;&quot;,
  11337. &quot;pushkey&quot;:&quot;a@example.com&quot;
  11338. }
  11339. ],
  11340. &quot;total&quot;: 1
  11341. }
  11342. </code></pre>
  11343. <p><strong>Parameters</strong></p>
  11344. <p>The following parameters should be set in the URL:</p>
  11345. <ul>
  11346. <li><code>user_id</code> - fully qualified: for example, <code>@user:server.com</code>.</li>
  11347. </ul>
  11348. <p><strong>Response</strong></p>
  11349. <p>The following fields are returned in the JSON response body:</p>
  11350. <ul>
  11351. <li>
  11352. <p><code>pushers</code> - An array containing the current pushers for the user</p>
  11353. <ul>
  11354. <li>
  11355. <p><code>app_display_name</code> - string - A string that will allow the user to identify
  11356. what application owns this pusher.</p>
  11357. </li>
  11358. <li>
  11359. <p><code>app_id</code> - string - This is a reverse-DNS style identifier for the application.
  11360. Max length, 64 chars.</p>
  11361. </li>
  11362. <li>
  11363. <p><code>data</code> - A dictionary of information for the pusher implementation itself.</p>
  11364. <ul>
  11365. <li>
  11366. <p><code>url</code> - string - Required if <code>kind</code> is <code>http</code>. The URL to use to send
  11367. notifications to.</p>
  11368. </li>
  11369. <li>
  11370. <p><code>format</code> - string - The format to use when sending notifications to the
  11371. Push Gateway.</p>
  11372. </li>
  11373. </ul>
  11374. </li>
  11375. <li>
  11376. <p><code>device_display_name</code> - string - A string that will allow the user to identify
  11377. what device owns this pusher.</p>
  11378. </li>
  11379. <li>
  11380. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  11381. this pusher executes.</p>
  11382. </li>
  11383. <li>
  11384. <p><code>kind</code> - string - The kind of pusher. &quot;http&quot; is a pusher that sends HTTP pokes.</p>
  11385. </li>
  11386. <li>
  11387. <p><code>lang</code> - string - The preferred language for receiving notifications
  11388. (e.g. 'en' or 'en-US')</p>
  11389. </li>
  11390. <li>
  11391. <p><code>profile_tag</code> - string - This string determines which set of device specific rules
  11392. this pusher executes.</p>
  11393. </li>
  11394. <li>
  11395. <p><code>pushkey</code> - string - This is a unique identifier for this pusher.
  11396. Max length, 512 bytes.</p>
  11397. </li>
  11398. </ul>
  11399. </li>
  11400. <li>
  11401. <p><code>total</code> - integer - Number of pushers.</p>
  11402. </li>
  11403. </ul>
  11404. <p>See also the
  11405. <a href="https://matrix.org/docs/spec/client_server/latest#get-matrix-client-r0-pushers">Client-Server API Spec on pushers</a>.</p>
  11406. <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>
  11407. <p>Shadow-banning is a useful tool for moderating malicious or egregiously abusive users.
  11408. A shadow-banned users receives successful responses to their client-server API requests,
  11409. but the events are not propagated into rooms. This can be an effective tool as it
  11410. (hopefully) takes longer for the user to realise they are being moderated before
  11411. pivoting to another account.</p>
  11412. <p>Shadow-banning a user should be used as a tool of last resort and may lead to confusing
  11413. or broken behaviour for the client. A shadow-banned user will not receive any
  11414. notification and it is generally more appropriate to ban or kick abusive users.
  11415. A shadow-banned user will be unable to contact anyone on the server.</p>
  11416. <p>To shadow-ban a user the API is:</p>
  11417. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  11418. </code></pre>
  11419. <p>To un-shadow-ban a user the API is:</p>
  11420. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/shadow_ban
  11421. </code></pre>
  11422. <p>An empty JSON dict is returned in both cases.</p>
  11423. <p><strong>Parameters</strong></p>
  11424. <p>The following parameters should be set in the URL:</p>
  11425. <ul>
  11426. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  11427. be local.</li>
  11428. </ul>
  11429. <h2 id="override-ratelimiting-for-users"><a class="header" href="#override-ratelimiting-for-users">Override ratelimiting for users</a></h2>
  11430. <p>This API allows to override or disable ratelimiting for a specific user.
  11431. There are specific APIs to set, get and delete a ratelimit.</p>
  11432. <h3 id="get-status-of-ratelimit"><a class="header" href="#get-status-of-ratelimit">Get status of ratelimit</a></h3>
  11433. <p>The API is:</p>
  11434. <pre><code>GET /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  11435. </code></pre>
  11436. <p>A response body like the following is returned:</p>
  11437. <pre><code class="language-json">{
  11438. &quot;messages_per_second&quot;: 0,
  11439. &quot;burst_count&quot;: 0
  11440. }
  11441. </code></pre>
  11442. <p><strong>Parameters</strong></p>
  11443. <p>The following parameters should be set in the URL:</p>
  11444. <ul>
  11445. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  11446. be local.</li>
  11447. </ul>
  11448. <p><strong>Response</strong></p>
  11449. <p>The following fields are returned in the JSON response body:</p>
  11450. <ul>
  11451. <li><code>messages_per_second</code> - integer - The number of actions that can
  11452. be performed in a second. <code>0</code> mean that ratelimiting is disabled for this user.</li>
  11453. <li><code>burst_count</code> - integer - How many actions that can be performed before
  11454. being limited.</li>
  11455. </ul>
  11456. <p>If <strong>no</strong> custom ratelimit is set, an empty JSON dict is returned.</p>
  11457. <pre><code class="language-json">{}
  11458. </code></pre>
  11459. <h3 id="set-ratelimit"><a class="header" href="#set-ratelimit">Set ratelimit</a></h3>
  11460. <p>The API is:</p>
  11461. <pre><code>POST /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  11462. </code></pre>
  11463. <p>A response body like the following is returned:</p>
  11464. <pre><code class="language-json">{
  11465. &quot;messages_per_second&quot;: 0,
  11466. &quot;burst_count&quot;: 0
  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>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  11473. be local.</li>
  11474. </ul>
  11475. <p>Body parameters:</p>
  11476. <ul>
  11477. <li><code>messages_per_second</code> - positive integer, optional. The number of actions that can
  11478. be performed in a second. Defaults to <code>0</code>.</li>
  11479. <li><code>burst_count</code> - positive integer, optional. How many actions that can be performed
  11480. before being limited. Defaults to <code>0</code>.</li>
  11481. </ul>
  11482. <p>To disable users' ratelimit set both values to <code>0</code>.</p>
  11483. <p><strong>Response</strong></p>
  11484. <p>The following fields are returned in the JSON response body:</p>
  11485. <ul>
  11486. <li><code>messages_per_second</code> - integer - The number of actions that can
  11487. be performed in a second.</li>
  11488. <li><code>burst_count</code> - integer - How many actions that can be performed before
  11489. being limited.</li>
  11490. </ul>
  11491. <h3 id="delete-ratelimit"><a class="header" href="#delete-ratelimit">Delete ratelimit</a></h3>
  11492. <p>The API is:</p>
  11493. <pre><code>DELETE /_synapse/admin/v1/users/&lt;user_id&gt;/override_ratelimit
  11494. </code></pre>
  11495. <p>An empty JSON dict is returned.</p>
  11496. <pre><code class="language-json">{}
  11497. </code></pre>
  11498. <p><strong>Parameters</strong></p>
  11499. <p>The following parameters should be set in the URL:</p>
  11500. <ul>
  11501. <li><code>user_id</code> - The fully qualified MXID: for example, <code>@user:server.com</code>. The user must
  11502. be local.</li>
  11503. </ul>
  11504. <h3 id="check-username-availability"><a class="header" href="#check-username-availability">Check username availability</a></h3>
  11505. <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
  11506. API</a>
  11507. for more information.</p>
  11508. <p>This endpoint will work even if registration is disabled on the server, unlike
  11509. <code>/_matrix/client/r0/register/available</code>.</p>
  11510. <p>The API is:</p>
  11511. <pre><code>GET /_synapse/admin/v1/username_available?username=$localpart
  11512. </code></pre>
  11513. <p>The request and response format is the same as the
  11514. <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>
  11515. <div style="break-before: page; page-break-before: always;"></div><h1 id="version-api"><a class="header" href="#version-api">Version API</a></h1>
  11516. <p>This API returns the running Synapse version and the Python version
  11517. on which Synapse is being run. This is useful when a Synapse instance
  11518. is behind a proxy that does not forward the 'Server' header (which also
  11519. contains Synapse version information).</p>
  11520. <p>The api is:</p>
  11521. <pre><code>GET /_synapse/admin/v1/server_version
  11522. </code></pre>
  11523. <p>It returns a JSON body like the following:</p>
  11524. <pre><code class="language-json">{
  11525. &quot;server_version&quot;: &quot;0.99.2rc1 (b=develop, abcdef123)&quot;,
  11526. &quot;python_version&quot;: &quot;3.7.8&quot;
  11527. }
  11528. </code></pre>
  11529. <div style="break-before: page; page-break-before: always;"></div><h1 id="federation-api"><a class="header" href="#federation-api">Federation API</a></h1>
  11530. <p>This API allows a server administrator to manage Synapse's federation with other homeservers.</p>
  11531. <p>Note: This API is new, experimental and &quot;subject to change&quot;.</p>
  11532. <h2 id="list-of-destinations"><a class="header" href="#list-of-destinations">List of destinations</a></h2>
  11533. <p>This API gets the current destination retry timing info for all remote servers.</p>
  11534. <p>The list contains all the servers with which the server federates,
  11535. regardless of whether an error occurred or not.
  11536. If an error occurs, it may take up to 20 minutes for the error to be displayed here,
  11537. as a complete retry must have failed.</p>
  11538. <p>The API is:</p>
  11539. <p>A standard request with no filtering:</p>
  11540. <pre><code>GET /_synapse/admin/v1/federation/destinations
  11541. </code></pre>
  11542. <p>A response body like the following is returned:</p>
  11543. <pre><code class="language-json">{
  11544. &quot;destinations&quot;:[
  11545. {
  11546. &quot;destination&quot;: &quot;matrix.org&quot;,
  11547. &quot;retry_last_ts&quot;: 1557332397936,
  11548. &quot;retry_interval&quot;: 3000000,
  11549. &quot;failure_ts&quot;: 1557329397936,
  11550. &quot;last_successful_stream_ordering&quot;: null
  11551. }
  11552. ],
  11553. &quot;total&quot;: 1
  11554. }
  11555. </code></pre>
  11556. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  11557. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  11558. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  11559. to paginate through.</p>
  11560. <p><strong>Parameters</strong></p>
  11561. <p>The following query parameters are available:</p>
  11562. <ul>
  11563. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  11564. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  11565. <li><code>order_by</code> - The method in which to sort the returned list of destinations.
  11566. Valid values are:
  11567. <ul>
  11568. <li><code>destination</code> - Destinations are ordered alphabetically by remote server name.
  11569. This is the default.</li>
  11570. <li><code>retry_last_ts</code> - Destinations are ordered by time of last retry attempt in ms.</li>
  11571. <li><code>retry_interval</code> - Destinations are ordered by how long until next retry in ms.</li>
  11572. <li><code>failure_ts</code> - Destinations are ordered by when the server started failing in ms.</li>
  11573. <li><code>last_successful_stream_ordering</code> - Destinations are ordered by the stream ordering
  11574. of the most recent successfully-sent PDU.</li>
  11575. </ul>
  11576. </li>
  11577. <li><code>dir</code> - Direction of room order. Either <code>f</code> for forwards or <code>b</code> for backwards. Setting
  11578. this value to <code>b</code> will reverse the above sort order. Defaults to <code>f</code>.</li>
  11579. </ul>
  11580. <p><em>Caution:</em> The database only has an index on the column <code>destination</code>.
  11581. This means that if a different sort order is used,
  11582. this can cause a large load on the database, especially for large environments.</p>
  11583. <p><strong>Response</strong></p>
  11584. <p>The following fields are returned in the JSON response body:</p>
  11585. <ul>
  11586. <li><code>destinations</code> - An array of objects, each containing information about a destination.
  11587. Destination objects contain the following fields:
  11588. <ul>
  11589. <li><code>destination</code> - string - Name of the remote server to federate.</li>
  11590. <li><code>retry_last_ts</code> - integer - The last time Synapse tried and failed to reach the
  11591. remote server, in ms. This is <code>0</code> if the last attempt to communicate with the
  11592. remote server was successful.</li>
  11593. <li><code>retry_interval</code> - integer - How long since the last time Synapse tried to reach
  11594. the remote server before trying again, in ms. This is <code>0</code> if no further retrying occuring.</li>
  11595. <li><code>failure_ts</code> - nullable integer - The first time Synapse tried and failed to reach the
  11596. remote server, in ms. This is <code>null</code> if communication with the remote server has never failed.</li>
  11597. <li><code>last_successful_stream_ordering</code> - nullable integer - The stream ordering of the most
  11598. recent successfully-sent <a href="usage/administration/admin_api/understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  11599. to this destination, or <code>null</code> if this information has not been tracked yet.</li>
  11600. </ul>
  11601. </li>
  11602. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  11603. <li><code>total</code> - integer - Total number of destinations.</li>
  11604. </ul>
  11605. <h2 id="destination-details-api"><a class="header" href="#destination-details-api">Destination Details API</a></h2>
  11606. <p>This API gets the retry timing info for a specific remote server.</p>
  11607. <p>The API is:</p>
  11608. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;
  11609. </code></pre>
  11610. <p>A response body like the following is returned:</p>
  11611. <pre><code class="language-json">{
  11612. &quot;destination&quot;: &quot;matrix.org&quot;,
  11613. &quot;retry_last_ts&quot;: 1557332397936,
  11614. &quot;retry_interval&quot;: 3000000,
  11615. &quot;failure_ts&quot;: 1557329397936,
  11616. &quot;last_successful_stream_ordering&quot;: null
  11617. }
  11618. </code></pre>
  11619. <p><strong>Parameters</strong></p>
  11620. <p>The following parameters should be set in the URL:</p>
  11621. <ul>
  11622. <li><code>destination</code> - Name of the remote server.</li>
  11623. </ul>
  11624. <p><strong>Response</strong></p>
  11625. <p>The response fields are the same like in the <code>destinations</code> array in
  11626. <a href="usage/administration/admin_api/federation.html#list-of-destinations">List of destinations</a> response.</p>
  11627. <h2 id="destination-rooms"><a class="header" href="#destination-rooms">Destination rooms</a></h2>
  11628. <p>This API gets the rooms that federate with a specific remote server.</p>
  11629. <p>The API is:</p>
  11630. <pre><code>GET /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/rooms
  11631. </code></pre>
  11632. <p>A response body like the following is returned:</p>
  11633. <pre><code class="language-json">{
  11634. &quot;rooms&quot;:[
  11635. {
  11636. &quot;room_id&quot;: &quot;!OGEhHVWSdvArJzumhm:matrix.org&quot;,
  11637. &quot;stream_ordering&quot;: 8326
  11638. },
  11639. {
  11640. &quot;room_id&quot;: &quot;!xYvNcQPhnkrdUmYczI:matrix.org&quot;,
  11641. &quot;stream_ordering&quot;: 93534
  11642. }
  11643. ],
  11644. &quot;total&quot;: 2
  11645. }
  11646. </code></pre>
  11647. <p>To paginate, check for <code>next_token</code> and if present, call the endpoint again
  11648. with <code>from</code> set to the value of <code>next_token</code>. This will return a new page.</p>
  11649. <p>If the endpoint does not return a <code>next_token</code> then there are no more destinations
  11650. to paginate through.</p>
  11651. <p><strong>Parameters</strong></p>
  11652. <p>The following parameters should be set in the URL:</p>
  11653. <ul>
  11654. <li><code>destination</code> - Name of the remote server.</li>
  11655. </ul>
  11656. <p>The following query parameters are available:</p>
  11657. <ul>
  11658. <li><code>from</code> - Offset in the returned list. Defaults to <code>0</code>.</li>
  11659. <li><code>limit</code> - Maximum amount of destinations to return. Defaults to <code>100</code>.</li>
  11660. <li><code>dir</code> - Direction of room order by <code>room_id</code>. Either <code>f</code> for forwards or <code>b</code> for
  11661. backwards. Defaults to <code>f</code>.</li>
  11662. </ul>
  11663. <p><strong>Response</strong></p>
  11664. <p>The following fields are returned in the JSON response body:</p>
  11665. <ul>
  11666. <li><code>rooms</code> - An array of objects, each containing information about a room.
  11667. Room objects contain the following fields:
  11668. <ul>
  11669. <li><code>room_id</code> - string - The ID of the room.</li>
  11670. <li><code>stream_ordering</code> - integer - The stream ordering of the most recent
  11671. successfully-sent <a href="usage/administration/admin_api/understanding_synapse_through_grafana_graphs.html#federation">PDU</a>
  11672. to this destination in this room.</li>
  11673. </ul>
  11674. </li>
  11675. <li><code>next_token</code>: string representing a positive integer - Indication for pagination. See above.</li>
  11676. <li><code>total</code> - integer - Total number of destinations.</li>
  11677. </ul>
  11678. <h2 id="reset-connection-timeout"><a class="header" href="#reset-connection-timeout">Reset connection timeout</a></h2>
  11679. <p>Synapse makes federation requests to other homeservers. If a federation request fails,
  11680. Synapse will mark the destination homeserver as offline, preventing any future requests
  11681. to that server for a &quot;cooldown&quot; period. This period grows over time if the server
  11682. continues to fail its responses
  11683. (<a href="https://en.wikipedia.org/wiki/Exponential_backoff">exponential backoff</a>).</p>
  11684. <p>Admins can cancel the cooldown period with this API.</p>
  11685. <p>This API resets the retry timing for a specific remote server and tries to connect to
  11686. the remote server again. It does not wait for the next <code>retry_interval</code>.
  11687. The connection must have previously run into an error and <code>retry_last_ts</code>
  11688. (<a href="usage/administration/admin_api/federation.html#destination-details-api">Destination Details API</a>) must not be equal to <code>0</code>.</p>
  11689. <p>The connection attempt is carried out in the background and can take a while
  11690. even if the API already returns the http status 200.</p>
  11691. <p>The API is:</p>
  11692. <pre><code>POST /_synapse/admin/v1/federation/destinations/&lt;destination&gt;/reset_connection
  11693. {}
  11694. </code></pre>
  11695. <p><strong>Parameters</strong></p>
  11696. <p>The following parameters should be set in the URL:</p>
  11697. <ul>
  11698. <li><code>destination</code> - Name of the remote server.</li>
  11699. </ul>
  11700. <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>
  11701. <p>The &quot;manhole&quot; allows server administrators to access a Python shell on a running
  11702. Synapse installation. This is a very powerful mechanism for administration and
  11703. debugging.</p>
  11704. <p><strong><em>Security Warning</em></strong></p>
  11705. <p>Note that this will give administrative access to synapse to <strong>all users</strong> with
  11706. shell access to the server. It should therefore <strong>not</strong> be enabled in
  11707. environments where untrusted users have shell access.</p>
  11708. <h2 id="configuring-the-manhole"><a class="header" href="#configuring-the-manhole">Configuring the manhole</a></h2>
  11709. <p>To enable it, first uncomment the <code>manhole</code> listener configuration in
  11710. <code>homeserver.yaml</code>. The configuration is slightly different if you're using docker.</p>
  11711. <h4 id="docker-config"><a class="header" href="#docker-config">Docker config</a></h4>
  11712. <p>If you are using Docker, set <code>bind_addresses</code> to <code>['0.0.0.0']</code> as shown:</p>
  11713. <pre><code class="language-yaml">listeners:
  11714. - port: 9000
  11715. bind_addresses: ['0.0.0.0']
  11716. type: manhole
  11717. </code></pre>
  11718. <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
  11719. <code>manhole</code> port forwarding. The <code>-p 127.0.0.1:9000:9000</code> below is important: it
  11720. ensures that access to the <code>manhole</code> is only possible for local users.</p>
  11721. <pre><code class="language-bash">docker run -d --name synapse \
  11722. --mount type=volume,src=synapse-data,dst=/data \
  11723. -p 8008:8008 \
  11724. -p 127.0.0.1:9000:9000 \
  11725. matrixdotorg/synapse:latest
  11726. </code></pre>
  11727. <h4 id="native-config"><a class="header" href="#native-config">Native config</a></h4>
  11728. <p>If you are not using docker, set <code>bind_addresses</code> to <code>['::1', '127.0.0.1']</code> as shown.
  11729. The <code>bind_addresses</code> in the example below is important: it ensures that access to the
  11730. <code>manhole</code> is only possible for local users).</p>
  11731. <pre><code class="language-yaml">listeners:
  11732. - port: 9000
  11733. bind_addresses: ['::1', '127.0.0.1']
  11734. type: manhole
  11735. </code></pre>
  11736. <h3 id="security-settings"><a class="header" href="#security-settings">Security settings</a></h3>
  11737. <p>The following config options are available:</p>
  11738. <ul>
  11739. <li><code>username</code> - The username for the manhole (defaults to <code>matrix</code>)</li>
  11740. <li><code>password</code> - The password for the manhole (defaults to <code>rabbithole</code>)</li>
  11741. <li><code>ssh_priv_key</code> - The path to a private SSH key (defaults to a hardcoded value)</li>
  11742. <li><code>ssh_pub_key</code> - The path to a public SSH key (defaults to a hardcoded value)</li>
  11743. </ul>
  11744. <p>For example:</p>
  11745. <pre><code class="language-yaml">manhole_settings:
  11746. username: manhole
  11747. password: mypassword
  11748. ssh_priv_key: &quot;/home/synapse/manhole_keys/id_rsa&quot;
  11749. ssh_pub_key: &quot;/home/synapse/manhole_keys/id_rsa.pub&quot;
  11750. </code></pre>
  11751. <h2 id="accessing-synapse-manhole"><a class="header" href="#accessing-synapse-manhole">Accessing synapse manhole</a></h2>
  11752. <p>Then restart synapse, and point an ssh client at port 9000 on localhost, using
  11753. the username and password configured in <code>homeserver.yaml</code> - with the default
  11754. configuration, this would be:</p>
  11755. <pre><code class="language-bash">ssh -p9000 matrix@localhost
  11756. </code></pre>
  11757. <p>Then enter the password when prompted (the default is <code>rabbithole</code>).</p>
  11758. <p>This gives a Python REPL in which <code>hs</code> gives access to the
  11759. <code>synapse.server.HomeServer</code> object - which in turn gives access to many other
  11760. parts of the process.</p>
  11761. <p>Note that, prior to Synapse 1.41, any call which returns a coroutine will need to be wrapped in <code>ensureDeferred</code>.</p>
  11762. <p>As a simple example, retrieving an event from the database:</p>
  11763. <pre><code class="language-pycon">&gt;&gt;&gt; from twisted.internet import defer
  11764. &gt;&gt;&gt; defer.ensureDeferred(hs.get_datastore().get_event('$1416420717069yeQaw:matrix.org'))
  11765. &lt;Deferred at 0x7ff253fc6998 current result: &lt;FrozenEvent event_id='$1416420717069yeQaw:matrix.org', type='m.room.create', state_key=''&gt;&gt;
  11766. </code></pre>
  11767. <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>
  11768. <ol>
  11769. <li>
  11770. <p>Install Prometheus:</p>
  11771. <p>Follow instructions at
  11772. <a href="http://prometheus.io/docs/introduction/install/">http://prometheus.io/docs/introduction/install/</a></p>
  11773. </li>
  11774. <li>
  11775. <p>Enable Synapse metrics:</p>
  11776. <p>There are two methods of enabling metrics in Synapse.</p>
  11777. <p>The first serves the metrics as a part of the usual web server and
  11778. can be enabled by adding the &quot;metrics&quot; resource to the existing
  11779. listener as such:</p>
  11780. <pre><code class="language-yaml"> resources:
  11781. - names:
  11782. - client
  11783. - metrics
  11784. </code></pre>
  11785. <p>This provides a simple way of adding metrics to your Synapse
  11786. installation, and serves under <code>/_synapse/metrics</code>. If you do not
  11787. wish your metrics be publicly exposed, you will need to either
  11788. filter it out at your load balancer, or use the second method.</p>
  11789. <p>The second method runs the metrics server on a different port, in a
  11790. different thread to Synapse. This can make it more resilient to
  11791. heavy load meaning metrics cannot be retrieved, and can be exposed
  11792. to just internal networks easier. The served metrics are available
  11793. over HTTP only, and will be available at <code>/_synapse/metrics</code>.</p>
  11794. <p>Add a new listener to homeserver.yaml:</p>
  11795. <pre><code class="language-yaml"> listeners:
  11796. - type: metrics
  11797. port: 9000
  11798. bind_addresses:
  11799. - '0.0.0.0'
  11800. </code></pre>
  11801. <p>For both options, you will need to ensure that <code>enable_metrics</code> is
  11802. set to <code>True</code>.</p>
  11803. </li>
  11804. <li>
  11805. <p>Restart Synapse.</p>
  11806. </li>
  11807. <li>
  11808. <p>Add a Prometheus target for Synapse.</p>
  11809. <p>It needs to set the <code>metrics_path</code> to a non-default value (under
  11810. <code>scrape_configs</code>):</p>
  11811. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  11812. scrape_interval: 15s
  11813. metrics_path: &quot;/_synapse/metrics&quot;
  11814. static_configs:
  11815. - targets: [&quot;my.server.here:port&quot;]
  11816. </code></pre>
  11817. <p>where <code>my.server.here</code> is the IP address of Synapse, and <code>port</code> is
  11818. the listener port configured with the <code>metrics</code> resource.</p>
  11819. <p>If your prometheus is older than 1.5.2, you will need to replace
  11820. <code>static_configs</code> in the above with <code>target_groups</code>.</p>
  11821. </li>
  11822. <li>
  11823. <p>Restart Prometheus.</p>
  11824. </li>
  11825. <li>
  11826. <p>Consider using the <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana/">grafana dashboard</a>
  11827. and required <a href="https://github.com/matrix-org/synapse/tree/master/contrib/prometheus/">recording rules</a> </p>
  11828. </li>
  11829. </ol>
  11830. <h2 id="monitoring-workers"><a class="header" href="#monitoring-workers">Monitoring workers</a></h2>
  11831. <p>To monitor a Synapse installation using <a href="workers.html">workers</a>,
  11832. every worker needs to be monitored independently, in addition to
  11833. the main homeserver process. This is because workers don't send
  11834. their metrics to the main homeserver process, but expose them
  11835. directly (if they are configured to do so).</p>
  11836. <p>To allow collecting metrics from a worker, you need to add a
  11837. <code>metrics</code> listener to its configuration, by adding the following
  11838. under <code>worker_listeners</code>:</p>
  11839. <pre><code class="language-yaml"> - type: metrics
  11840. bind_address: ''
  11841. port: 9101
  11842. </code></pre>
  11843. <p>The <code>bind_address</code> and <code>port</code> parameters should be set so that
  11844. the resulting listener can be reached by prometheus, and they
  11845. don't clash with an existing worker.
  11846. With this example, the worker's metrics would then be available
  11847. on <code>http://127.0.0.1:9101</code>.</p>
  11848. <p>Example Prometheus target for Synapse with workers:</p>
  11849. <pre><code class="language-yaml"> - job_name: &quot;synapse&quot;
  11850. scrape_interval: 15s
  11851. metrics_path: &quot;/_synapse/metrics&quot;
  11852. static_configs:
  11853. - targets: [&quot;my.server.here:port&quot;]
  11854. labels:
  11855. instance: &quot;my.server&quot;
  11856. job: &quot;master&quot;
  11857. index: 1
  11858. - targets: [&quot;my.workerserver.here:port&quot;]
  11859. labels:
  11860. instance: &quot;my.server&quot;
  11861. job: &quot;generic_worker&quot;
  11862. index: 1
  11863. - targets: [&quot;my.workerserver.here:port&quot;]
  11864. labels:
  11865. instance: &quot;my.server&quot;
  11866. job: &quot;generic_worker&quot;
  11867. index: 2
  11868. - targets: [&quot;my.workerserver.here:port&quot;]
  11869. labels:
  11870. instance: &quot;my.server&quot;
  11871. job: &quot;media_repository&quot;
  11872. index: 1
  11873. </code></pre>
  11874. <p>Labels (<code>instance</code>, <code>job</code>, <code>index</code>) can be defined as anything.
  11875. The labels are used to group graphs in grafana.</p>
  11876. <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>
  11877. <p>Synapse 1.2 updates the Prometheus metrics to match the naming
  11878. convention of the upstream <code>prometheus_client</code>. The old names are
  11879. considered deprecated and will be removed in a future version of
  11880. Synapse.</p>
  11881. <table><thead><tr><th>New Name</th><th>Old Name</th></tr></thead><tbody>
  11882. <tr><td>python_gc_objects_collected_total</td><td>python_gc_objects_collected</td></tr>
  11883. <tr><td>python_gc_objects_uncollectable_total</td><td>python_gc_objects_uncollectable</td></tr>
  11884. <tr><td>python_gc_collections_total</td><td>python_gc_collections</td></tr>
  11885. <tr><td>process_cpu_seconds_total</td><td>process_cpu_seconds</td></tr>
  11886. <tr><td>synapse_federation_client_sent_transactions_total</td><td>synapse_federation_client_sent_transactions</td></tr>
  11887. <tr><td>synapse_federation_client_events_processed_total</td><td>synapse_federation_client_events_processed</td></tr>
  11888. <tr><td>synapse_event_processing_loop_count_total</td><td>synapse_event_processing_loop_count</td></tr>
  11889. <tr><td>synapse_event_processing_loop_room_count_total</td><td>synapse_event_processing_loop_room_count</td></tr>
  11890. <tr><td>synapse_util_metrics_block_count_total</td><td>synapse_util_metrics_block_count</td></tr>
  11891. <tr><td>synapse_util_metrics_block_time_seconds_total</td><td>synapse_util_metrics_block_time_seconds</td></tr>
  11892. <tr><td>synapse_util_metrics_block_ru_utime_seconds_total</td><td>synapse_util_metrics_block_ru_utime_seconds</td></tr>
  11893. <tr><td>synapse_util_metrics_block_ru_stime_seconds_total</td><td>synapse_util_metrics_block_ru_stime_seconds</td></tr>
  11894. <tr><td>synapse_util_metrics_block_db_txn_count_total</td><td>synapse_util_metrics_block_db_txn_count</td></tr>
  11895. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds_total</td><td>synapse_util_metrics_block_db_txn_duration_seconds</td></tr>
  11896. <tr><td>synapse_util_metrics_block_db_sched_duration_seconds_total</td><td>synapse_util_metrics_block_db_sched_duration_seconds</td></tr>
  11897. <tr><td>synapse_background_process_start_count_total</td><td>synapse_background_process_start_count</td></tr>
  11898. <tr><td>synapse_background_process_ru_utime_seconds_total</td><td>synapse_background_process_ru_utime_seconds</td></tr>
  11899. <tr><td>synapse_background_process_ru_stime_seconds_total</td><td>synapse_background_process_ru_stime_seconds</td></tr>
  11900. <tr><td>synapse_background_process_db_txn_count_total</td><td>synapse_background_process_db_txn_count</td></tr>
  11901. <tr><td>synapse_background_process_db_txn_duration_seconds_total</td><td>synapse_background_process_db_txn_duration_seconds</td></tr>
  11902. <tr><td>synapse_background_process_db_sched_duration_seconds_total</td><td>synapse_background_process_db_sched_duration_seconds</td></tr>
  11903. <tr><td>synapse_storage_events_persisted_events_total</td><td>synapse_storage_events_persisted_events</td></tr>
  11904. <tr><td>synapse_storage_events_persisted_events_sep_total</td><td>synapse_storage_events_persisted_events_sep</td></tr>
  11905. <tr><td>synapse_storage_events_state_delta_total</td><td>synapse_storage_events_state_delta</td></tr>
  11906. <tr><td>synapse_storage_events_state_delta_single_event_total</td><td>synapse_storage_events_state_delta_single_event</td></tr>
  11907. <tr><td>synapse_storage_events_state_delta_reuse_delta_total</td><td>synapse_storage_events_state_delta_reuse_delta</td></tr>
  11908. <tr><td>synapse_federation_server_received_pdus_total</td><td>synapse_federation_server_received_pdus</td></tr>
  11909. <tr><td>synapse_federation_server_received_edus_total</td><td>synapse_federation_server_received_edus</td></tr>
  11910. <tr><td>synapse_handler_presence_notified_presence_total</td><td>synapse_handler_presence_notified_presence</td></tr>
  11911. <tr><td>synapse_handler_presence_federation_presence_out_total</td><td>synapse_handler_presence_federation_presence_out</td></tr>
  11912. <tr><td>synapse_handler_presence_presence_updates_total</td><td>synapse_handler_presence_presence_updates</td></tr>
  11913. <tr><td>synapse_handler_presence_timers_fired_total</td><td>synapse_handler_presence_timers_fired</td></tr>
  11914. <tr><td>synapse_handler_presence_federation_presence_total</td><td>synapse_handler_presence_federation_presence</td></tr>
  11915. <tr><td>synapse_handler_presence_bump_active_time_total</td><td>synapse_handler_presence_bump_active_time</td></tr>
  11916. <tr><td>synapse_federation_client_sent_edus_total</td><td>synapse_federation_client_sent_edus</td></tr>
  11917. <tr><td>synapse_federation_client_sent_pdu_destinations_count_total</td><td>synapse_federation_client_sent_pdu_destinations:count</td></tr>
  11918. <tr><td>synapse_federation_client_sent_pdu_destinations_total</td><td>synapse_federation_client_sent_pdu_destinations:total</td></tr>
  11919. <tr><td>synapse_handlers_appservice_events_processed_total</td><td>synapse_handlers_appservice_events_processed</td></tr>
  11920. <tr><td>synapse_notifier_notified_events_total</td><td>synapse_notifier_notified_events</td></tr>
  11921. <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>
  11922. <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>
  11923. <tr><td>synapse_http_httppusher_http_pushes_processed_total</td><td>synapse_http_httppusher_http_pushes_processed</td></tr>
  11924. <tr><td>synapse_http_httppusher_http_pushes_failed_total</td><td>synapse_http_httppusher_http_pushes_failed</td></tr>
  11925. <tr><td>synapse_http_httppusher_badge_updates_processed_total</td><td>synapse_http_httppusher_badge_updates_processed</td></tr>
  11926. <tr><td>synapse_http_httppusher_badge_updates_failed_total</td><td>synapse_http_httppusher_badge_updates_failed</td></tr>
  11927. </tbody></table>
  11928. <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>
  11929. <p>The duplicated metrics deprecated in Synapse 0.27.0 have been removed.</p>
  11930. <p>All time duration-based metrics have been changed to be seconds. This
  11931. affects:</p>
  11932. <table><thead><tr><th>msec -&gt; sec metrics</th></tr></thead><tbody>
  11933. <tr><td>python_gc_time</td></tr>
  11934. <tr><td>python_twisted_reactor_tick_time</td></tr>
  11935. <tr><td>synapse_storage_query_time</td></tr>
  11936. <tr><td>synapse_storage_schedule_time</td></tr>
  11937. <tr><td>synapse_storage_transaction_time</td></tr>
  11938. </tbody></table>
  11939. <p>Several metrics have been changed to be histograms, which sort entries
  11940. into buckets and allow better analysis. The following metrics are now
  11941. histograms:</p>
  11942. <table><thead><tr><th>Altered metrics</th></tr></thead><tbody>
  11943. <tr><td>python_gc_time</td></tr>
  11944. <tr><td>python_twisted_reactor_pending_calls</td></tr>
  11945. <tr><td>python_twisted_reactor_tick_time</td></tr>
  11946. <tr><td>synapse_http_server_response_time_seconds</td></tr>
  11947. <tr><td>synapse_storage_query_time</td></tr>
  11948. <tr><td>synapse_storage_schedule_time</td></tr>
  11949. <tr><td>synapse_storage_transaction_time</td></tr>
  11950. </tbody></table>
  11951. <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>
  11952. <p>Synapse 0.27.0 begins the process of rationalising the duplicate
  11953. <code>*:count</code> metrics reported for the resource tracking for code blocks and
  11954. HTTP requests.</p>
  11955. <p>At the same time, the corresponding <code>*:total</code> metrics are being renamed,
  11956. as the <code>:total</code> suffix no longer makes sense in the absence of a
  11957. corresponding <code>:count</code> metric.</p>
  11958. <p>To enable a graceful migration path, this release just adds new names
  11959. for the metrics being renamed. A future release will remove the old
  11960. ones.</p>
  11961. <p>The following table shows the new metrics, and the old metrics which
  11962. they are replacing.</p>
  11963. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  11964. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_timer:count</td></tr>
  11965. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_utime:count</td></tr>
  11966. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_ru_stime:count</td></tr>
  11967. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_count:count</td></tr>
  11968. <tr><td>synapse_util_metrics_block_count</td><td>synapse_util_metrics_block_db_txn_duration:count</td></tr>
  11969. <tr><td>synapse_util_metrics_block_time_seconds</td><td>synapse_util_metrics_block_timer:total</td></tr>
  11970. <tr><td>synapse_util_metrics_block_ru_utime_seconds</td><td>synapse_util_metrics_block_ru_utime:total</td></tr>
  11971. <tr><td>synapse_util_metrics_block_ru_stime_seconds</td><td>synapse_util_metrics_block_ru_stime:total</td></tr>
  11972. <tr><td>synapse_util_metrics_block_db_txn_count</td><td>synapse_util_metrics_block_db_txn_count:total</td></tr>
  11973. <tr><td>synapse_util_metrics_block_db_txn_duration_seconds</td><td>synapse_util_metrics_block_db_txn_duration:total</td></tr>
  11974. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_requests</td></tr>
  11975. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_time:count</td></tr>
  11976. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_utime:count</td></tr>
  11977. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_ru_stime:count</td></tr>
  11978. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_count:count</td></tr>
  11979. <tr><td>synapse_http_server_response_count</td><td>synapse_http_server_response_db_txn_duration:count</td></tr>
  11980. <tr><td>synapse_http_server_response_time_seconds</td><td>synapse_http_server_response_time:total</td></tr>
  11981. <tr><td>synapse_http_server_response_ru_utime_seconds</td><td>synapse_http_server_response_ru_utime:total</td></tr>
  11982. <tr><td>synapse_http_server_response_ru_stime_seconds</td><td>synapse_http_server_response_ru_stime:total</td></tr>
  11983. <tr><td>synapse_http_server_response_db_txn_count</td><td>synapse_http_server_response_db_txn_count:total</td></tr>
  11984. <tr><td>synapse_http_server_response_db_txn_duration_seconds</td><td>synapse_http_server_response_db_txn_duration:total</td></tr>
  11985. </tbody></table>
  11986. <h2 id="standard-metric-names"><a class="header" href="#standard-metric-names">Standard Metric Names</a></h2>
  11987. <p>As of synapse version 0.18.2, the format of the process-wide metrics has
  11988. been changed to fit prometheus standard naming conventions. Additionally
  11989. the units have been changed to seconds, from miliseconds.</p>
  11990. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  11991. <tr><td>process_cpu_user_seconds_total</td><td>process_resource_utime / 1000</td></tr>
  11992. <tr><td>process_cpu_system_seconds_total</td><td>process_resource_stime / 1000</td></tr>
  11993. <tr><td>process_open_fds (no 'type' label)</td><td>process_fds</td></tr>
  11994. </tbody></table>
  11995. <p>The python-specific counts of garbage collector performance have been
  11996. renamed.</p>
  11997. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  11998. <tr><td>python_gc_time</td><td>reactor_gc_time</td></tr>
  11999. <tr><td>python_gc_unreachable_total</td><td>reactor_gc_unreachable</td></tr>
  12000. <tr><td>python_gc_counts</td><td>reactor_gc_counts</td></tr>
  12001. </tbody></table>
  12002. <p>The twisted-specific reactor metrics have been renamed.</p>
  12003. <table><thead><tr><th>New name</th><th>Old name</th></tr></thead><tbody>
  12004. <tr><td>python_twisted_reactor_pending_calls</td><td>reactor_pending_calls</td></tr>
  12005. <tr><td>python_twisted_reactor_tick_time</td><td>reactor_tick_time</td></tr>
  12006. </tbody></table>
  12007. <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>
  12008. <p>It is possible to monitor much of the internal state of Synapse using <a href="https://prometheus.io">Prometheus</a>
  12009. metrics and <a href="https://grafana.com/">Grafana</a>.
  12010. A guide for configuring Synapse to provide metrics is available <a href="usage/administration/../../metrics-howto.html">here</a>
  12011. and information on setting up Grafana is <a href="https://github.com/matrix-org/synapse/tree/master/contrib/grafana">here</a>.
  12012. In this setup, Prometheus will periodically scrape the information Synapse provides and
  12013. store a record of it over time. Grafana is then used as an interface to query and
  12014. present this information through a series of pretty graphs.</p>
  12015. <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>
  12016. <h2 id="message-event-send-time"><a class="header" href="#message-event-send-time">Message Event Send Time</a></h2>
  12017. <p><img src="https://user-images.githubusercontent.com/1342360/82239409-a1c8e900-9930-11ea-8081-e4614e0c63f4.png" alt="image" /></p>
  12018. <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>
  12019. <h2 id="transaction-count-and-transaction-duration"><a class="header" href="#transaction-count-and-transaction-duration">Transaction Count and Transaction Duration</a></h2>
  12020. <p><img src="https://user-images.githubusercontent.com/1342360/82239985-8d392080-9931-11ea-80d0-843ab2f22e1e.png" alt="image" /></p>
  12021. <p><img src="https://user-images.githubusercontent.com/1342360/82240050-ab068580-9931-11ea-98f1-f94671cbac9a.png" alt="image" /></p>
  12022. <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>
  12023. <p><img src="https://user-images.githubusercontent.com/1342360/82240192-e86b1300-9931-11ea-9aac-3e2c9bfa6fdc.png" alt="image" /></p>
  12024. <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>
  12025. <p><img src="https://user-images.githubusercontent.com/1342360/82240467-62030100-9932-11ea-8db9-917f2d977fe1.png" alt="image" /></p>
  12026. <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>
  12027. <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>
  12028. <h2 id="federation"><a class="header" href="#federation">Federation</a></h2>
  12029. <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>
  12030. <ul>
  12031. <li>PDU (Persistent Data Unit) - room events: messages, state events (join/leave), etc. These are permanently stored in the database.</li>
  12032. <li>EDU (Ephemeral Data Unit) - other data, which need not be stored permanently, such as read receipts, typing notifications.</li>
  12033. </ul>
  12034. <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>
  12035. <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>
  12036. <h2 id="caches"><a class="header" href="#caches">Caches</a></h2>
  12037. <p><img src="https://user-images.githubusercontent.com/1342360/82240572-8b239180-9932-11ea-96ff-6b5f0e57ebe5.png" alt="image" /></p>
  12038. <p><img src="https://user-images.githubusercontent.com/1342360/82240666-b8703f80-9932-11ea-86af-9f663988d8da.png" alt="image" /></p>
  12039. <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>
  12040. <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>
  12041. <p><img src="https://user-images.githubusercontent.com/1342360/82240766-de95df80-9932-11ea-8c15-5acfc57c48da.png" alt="image" /></p>
  12042. <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>
  12043. <h2 id="forward-extremities"><a class="header" href="#forward-extremities">Forward Extremities</a></h2>
  12044. <p><img src="https://user-images.githubusercontent.com/1342360/82241440-13566680-9934-11ea-8b88-ba468db937ed.png" alt="image" /></p>
  12045. <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>
  12046. <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>
  12047. <h2 id="garbage-collection"><a class="header" href="#garbage-collection">Garbage Collection</a></h2>
  12048. <p><img src="https://user-images.githubusercontent.com/1342360/82241911-da6ac180-9934-11ea-9a0d-a311fe22acd0.png" alt="image" /></p>
  12049. <p>Large spikes in garbage collection times (bigger than shown here, I'm talking in the
  12050. multiple seconds range), can cause lots of problems in Synapse performance. It's more an
  12051. indicator of problems, and a symptom of other problems though, so check other graphs for what might be causing it.</p>
  12052. <h2 id="final-thoughts"><a class="header" href="#final-thoughts">Final Thoughts</a></h2>
  12053. <p>If you're still having performance problems with your Synapse instance and you've
  12054. tried everything you can, it may just be a lack of system resources. Consider adding
  12055. more CPU and RAM, and make use of <a href="usage/administration/../../workers.html">worker mode</a>
  12056. to make use of multiple CPU cores / multiple machines for your homeserver.</p>
  12057. <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>
  12058. <h2 id="size-of-full-matrix-db"><a class="header" href="#size-of-full-matrix-db">Size of full matrix db</a></h2>
  12059. <p><code>SELECT pg_size_pretty( pg_database_size( 'matrix' ) );</code></p>
  12060. <h3 id="result-example"><a class="header" href="#result-example">Result example:</a></h3>
  12061. <pre><code>pg_size_pretty
  12062. ----------------
  12063. 6420 MB
  12064. (1 row)
  12065. </code></pre>
  12066. <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>
  12067. <pre><code class="language-sql">SELECT r.name, s.room_id, s.current_state_events
  12068. FROM room_stats_current s
  12069. LEFT JOIN room_stats_state r USING (room_id)
  12070. ORDER BY current_state_events DESC
  12071. LIMIT 20;
  12072. </code></pre>
  12073. <p>and by state_group_events count:</p>
  12074. <pre><code class="language-sql">SELECT rss.name, s.room_id, count(s.room_id) FROM state_groups_state s
  12075. LEFT JOIN room_stats_state rss USING (room_id)
  12076. GROUP BY s.room_id, rss.name
  12077. ORDER BY count(s.room_id) DESC
  12078. LIMIT 20;
  12079. </code></pre>
  12080. <p>plus same, but with join removed for performance reasons:</p>
  12081. <pre><code class="language-sql">SELECT s.room_id, count(s.room_id) FROM state_groups_state s
  12082. GROUP BY s.room_id
  12083. ORDER BY count(s.room_id) DESC
  12084. LIMIT 20;
  12085. </code></pre>
  12086. <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>
  12087. <pre><code class="language-sql">SELECT relname, n_live_tup as rows
  12088. FROM pg_stat_user_tables
  12089. ORDER BY n_live_tup DESC
  12090. LIMIT 20;
  12091. </code></pre>
  12092. <p>This query is quick, but may be very approximate, for exact number of rows use <code>SELECT COUNT(*) FROM &lt;table_name&gt;</code>.</p>
  12093. <h3 id="result-example-1"><a class="header" href="#result-example-1">Result example:</a></h3>
  12094. <pre><code>state_groups_state - 161687170
  12095. event_auth - 8584785
  12096. event_edges - 6995633
  12097. event_json - 6585916
  12098. event_reference_hashes - 6580990
  12099. events - 6578879
  12100. received_transactions - 5713989
  12101. event_to_state_groups - 4873377
  12102. stream_ordering_to_exterm - 4136285
  12103. current_state_delta_stream - 3770972
  12104. event_search - 3670521
  12105. state_events - 2845082
  12106. room_memberships - 2785854
  12107. cache_invalidation_stream - 2448218
  12108. state_groups - 1255467
  12109. state_group_edges - 1229849
  12110. current_state_events - 1222905
  12111. users_in_public_rooms - 364059
  12112. device_lists_stream - 326903
  12113. user_directory_search - 316433
  12114. </code></pre>
  12115. <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>
  12116. <pre><code class="language-sql">SELECT e.room_id, r.name, COUNT(e.event_id) cnt FROM events e
  12117. LEFT JOIN room_stats_state r USING (room_id)
  12118. WHERE e.origin_server_ts &gt;= DATE_PART('epoch', NOW() - INTERVAL '1 day') * 1000 GROUP BY e.room_id, r.name ORDER BY cnt DESC LIMIT 20;
  12119. </code></pre>
  12120. <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>
  12121. <pre><code class="language-sql">SELECT user_id, SUM(total_events)
  12122. FROM user_stats_historical
  12123. WHERE TO_TIMESTAMP(end_ts/1000) AT TIME ZONE 'UTC' &gt; date_trunc('day', now() - interval '1 month')
  12124. GROUP BY user_id
  12125. ORDER BY SUM(total_events) DESC
  12126. LIMIT 20;
  12127. </code></pre>
  12128. <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>
  12129. <pre><code class="language-sql">SELECT e.room_id, r.name, e.event_id, e.type, e.content, j.json FROM events e
  12130. LEFT JOIN event_json j USING (room_id)
  12131. LEFT JOIN room_stats_state r USING (room_id)
  12132. WHERE sender = '@LOGIN:example.com'
  12133. AND e.type = 'm.room.message'
  12134. ORDER BY stream_ordering DESC
  12135. LIMIT 100;
  12136. </code></pre>
  12137. <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>
  12138. <pre><code class="language-sql">SELECT nspname || '.' || relname AS &quot;relation&quot;,
  12139. pg_size_pretty(pg_total_relation_size(C.oid)) AS &quot;total_size&quot;
  12140. FROM pg_class C
  12141. LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
  12142. WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  12143. AND C.relkind &lt;&gt; 'i'
  12144. AND nspname !~ '^pg_toast'
  12145. ORDER BY pg_total_relation_size(C.oid) DESC
  12146. LIMIT 20;
  12147. </code></pre>
  12148. <h3 id="result-example-2"><a class="header" href="#result-example-2">Result example:</a></h3>
  12149. <pre><code>public.state_groups_state - 27 GB
  12150. public.event_json - 9855 MB
  12151. public.events - 3675 MB
  12152. public.event_edges - 3404 MB
  12153. public.received_transactions - 2745 MB
  12154. public.event_reference_hashes - 1864 MB
  12155. public.event_auth - 1775 MB
  12156. public.stream_ordering_to_exterm - 1663 MB
  12157. public.event_search - 1370 MB
  12158. public.room_memberships - 1050 MB
  12159. public.event_to_state_groups - 948 MB
  12160. public.current_state_delta_stream - 711 MB
  12161. public.state_events - 611 MB
  12162. public.presence_stream - 530 MB
  12163. public.current_state_events - 525 MB
  12164. public.cache_invalidation_stream - 466 MB
  12165. public.receipts_linearized - 279 MB
  12166. public.state_groups - 160 MB
  12167. public.device_lists_remote_cache - 124 MB
  12168. public.state_group_edges - 122 MB
  12169. </code></pre>
  12170. <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>
  12171. <p><code>echo &quot;select event_json.room_id,room_stats_state.name from event_json,room_stats_state where room_stats_state.room_id=event_json.room_id&quot; | psql synapse | sort | uniq -c | sort -n</code></p>
  12172. <h3 id="result-example-3"><a class="header" href="#result-example-3">Result example:</a></h3>
  12173. <pre><code> 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix
  12174. 9459 !FPUfgzXYWTKgIrwKxW:matrix.org | This Week in Matrix (TWIM)
  12175. 17799 !iDIOImbmXxwNngznsa:matrix.org | Linux in Russian
  12176. 18739 !GnEEPYXUhoaHbkFBNX:matrix.org | Riot Android
  12177. 23373 !QtykxKocfZaZOUrTwp:matrix.org | Matrix HQ
  12178. 39504 !gTQfWzbYncrtNrvEkB:matrix.org | ru.[matrix]
  12179. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot
  12180. 43601 !iNmaIQExDMeqdITdHH:matrix.org | Riot Web/Desktop
  12181. </code></pre>
  12182. <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>
  12183. <pre><code class="language-sql">SELECT rss.room_id, rss.name, rss.canonical_alias, rss.topic, rss.encryption, rsc.joined_members, rsc.local_users_in_room, rss.join_rules
  12184. FROM room_stats_state rss
  12185. LEFT JOIN room_stats_current rsc USING (room_id)
  12186. WHERE room_id IN (WHERE room_id IN (
  12187. '!OGEhHVWSdvArJzumhm:matrix.org',
  12188. '!YTvKGNlinIzlkMTVRl:matrix.org'
  12189. )
  12190. </code></pre>
  12191. <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>
  12192. <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>
  12193. <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>
  12194. <p>The purge remote media API allows server admins to purge old cached remote media.</p>
  12195. <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>
  12196. <p>This API deletes the <em>local</em> media from the disk of your own server.</p>
  12197. <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>
  12198. <p>The purge history API allows server admins to purge historic events from their database, reclaiming disk space.</p>
  12199. <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>
  12200. <p>Tool for compressing (deduplicating) <code>state_groups_state</code> table.</p>
  12201. <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>
  12202. <p>Some easy SQL that reports useful stats about your Synapse database.</p>
  12203. <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>
  12204. <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>
  12205. <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>
  12206. <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>
  12207. <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>
  12208. <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>
  12209. <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>
  12210. <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>
  12211. <p>A full state group just records the event id for each piece of state in the room at that point.</p>
  12212. <h2 id="known-bugs-with-state-groups"><a class="header" href="#known-bugs-with-state-groups">Known bugs with state groups</a></h2>
  12213. <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>
  12214. <h2 id="compression-tool"><a class="header" href="#compression-tool">Compression tool</a></h2>
  12215. <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>
  12216. <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>
  12217. <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>
  12218. <p>See the following for how to decode the dense data available from the default logging configuration.</p>
  12219. <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]
  12220. -AAAAAAAAAAAAAAAAAAAAA- -BBBBBBBBBBBBBBBBBBBBBB- -C- -DD- -EEEEEE- -FFFFFFFFF- -GG- -HHHHHHHHHHHHHHHHHHHHHHH- -IIIIII- -JJJJJJJ- -KKKKKK-, -LLLLLL- -MMMMMMM- -NNNNNN- O -P- -QQ- -RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR- -SSSSSSSSSSSS- -TTTTTT-
  12221. </code></pre>
  12222. <table><thead><tr><th>Part</th><th>Explanation</th></tr></thead><tbody>
  12223. <tr><td>AAAA</td><td>Timestamp request was logged (not recieved)</td></tr>
  12224. <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>
  12225. <tr><td>CCCC</td><td>Line number in code</td></tr>
  12226. <tr><td>DDDD</td><td>Log Level</td></tr>
  12227. <tr><td>EEEE</td><td>Request Identifier (This identifier is shared by related log lines)</td></tr>
  12228. <tr><td>FFFF</td><td>Source IP (Or X-Forwarded-For if enabled)</td></tr>
  12229. <tr><td>GGGG</td><td>Server Port</td></tr>
  12230. <tr><td>HHHH</td><td>Federated Server or Local User making request (blank if unauthenticated or not supplied)</td></tr>
  12231. <tr><td>IIII</td><td>Total Time to process the request</td></tr>
  12232. <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>
  12233. <tr><td>KKKK</td><td>Userland CPU time</td></tr>
  12234. <tr><td>LLLL</td><td>System CPU time</td></tr>
  12235. <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>
  12236. <tr><td>NNNN</td><td>Total time waiting for response to DB queries across all parallel DB work from this request</td></tr>
  12237. <tr><td>OOOO</td><td>Count of DB transactions performed</td></tr>
  12238. <tr><td>PPPP</td><td>Response body size</td></tr>
  12239. <tr><td>QQQQ</td><td>Response status code (prefixed with ! if the socket was closed before the response was generated)</td></tr>
  12240. <tr><td>RRRR</td><td>Request</td></tr>
  12241. <tr><td>SSSS</td><td>User-agent</td></tr>
  12242. <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>
  12243. </tbody></table>
  12244. <p>MMMM / NNNN can be greater than IIII if there are multiple slow database queries
  12245. running in parallel.</p>
  12246. <p>Some actions can result in multiple identical http requests, which will return
  12247. the same data, but only the first request will report time/transactions in
  12248. <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
  12249. response and will simultaneously return with the first request, but with very
  12250. small processing times.</p>
  12251. <div style="break-before: page; page-break-before: always;"></div><h2 id="admin-faq"><a class="header" href="#admin-faq">Admin FAQ</a></h2>
  12252. <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>
  12253. <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>
  12254. <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>
  12255. <pre><code class="language-sql">UPDATE users SET admin = 1 WHERE name = '@foo:bar.com';
  12256. </code></pre>
  12257. <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>
  12258. <p>Run this sql query on your db:</p>
  12259. <pre><code class="language-sql">SELECT * FROM destinations;
  12260. </code></pre>
  12261. <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>
  12262. <p>Run this sql query on your db:</p>
  12263. <pre><code class="language-sql">SELECT DISTINCT split_part(state_key, ':', 2)
  12264. FROM current_state_events AS c
  12265. INNER JOIN room_memberships AS m USING (room_id, event_id)
  12266. WHERE room_id = '!cURbafjkfsMDVwdRDQ:matrix.org' AND membership = 'join';
  12267. </code></pre>
  12268. <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>
  12269. <pre><code class="language-sql">SELECT NAME from users;
  12270. </code></pre>
  12271. <h2 id="manually-resetting-passwords"><a class="header" href="#manually-resetting-passwords">Manually resetting passwords:</a></h2>
  12272. <p>See https://github.com/matrix-org/synapse/blob/master/README.rst#password-reset</p>
  12273. <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>
  12274. <p>Deleting your database is unlikely to make anything better. </p>
  12275. <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>
  12276. <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>
  12277. <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>
  12278. <p>There are two exceptions when it might be sensible to delete your database and start again:</p>
  12279. <ul>
  12280. <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>
  12281. <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.
  12282. (In both cases you probably also want to clear out the media_store.)</li>
  12283. </ul>
  12284. <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>
  12285. <p>Using the following curl command:</p>
  12286. <pre><code>curl -H 'Authorization: Bearer &lt;access-token&gt;' -X DELETE https://matrix.org/_matrix/client/r0/directory/room/&lt;room-alias&gt;
  12287. </code></pre>
  12288. <p><code>&lt;access-token&gt;</code> - can be obtained in riot by looking in the riot settings, down the bottom is:
  12289. Access Token:&lt;click to reveal&gt; </p>
  12290. <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>
  12291. <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>
  12292. <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>
  12293. <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;
  12294. </code></pre>
  12295. <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>
  12296. <pre><code>grep 'GET-37' homeserver.log
  12297. </code></pre>
  12298. <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>
  12299. <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>
  12300. <p>See <a href="usage/administration/request_log.html">Request log format</a>.</p>
  12301. <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>
  12302. <pre><code class="language-sql">SELECT s.canonical_alias, g.room_id, count(*) AS num_rows
  12303. FROM
  12304. state_groups_state AS g,
  12305. room_stats_state AS s
  12306. WHERE g.room_id = s.room_id
  12307. GROUP BY s.canonical_alias, g.room_id
  12308. ORDER BY num_rows desc
  12309. LIMIT 10;
  12310. </code></pre>
  12311. <p>You can also use the <a href="usage/administration/../../admin_api/rooms.html#list-room-api">List Room API</a>
  12312. and <code>order_by</code> <code>state_events</code>.</p>
  12313. <div style="break-before: page; page-break-before: always;"></div><h1 id="contributing"><a class="header" href="#contributing">Contributing</a></h1>
  12314. <p>This document aims to get you started with contributing to Synapse!</p>
  12315. <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>
  12316. <p>Everyone is welcome to contribute code to <a href="https://github.com/matrix-org">matrix.org
  12317. projects</a>, provided that they are willing to
  12318. license their contributions under the same license as the project itself. We
  12319. follow a simple 'inbound=outbound' model for contributions: the act of
  12320. submitting an 'inbound' contribution means that the contributor agrees to
  12321. license the code under the same terms as the project's overall 'outbound'
  12322. license - in our case, this is almost always Apache Software License v2 (see
  12323. <a href="https://github.com/matrix-org/synapse/blob/develop/LICENSE">LICENSE</a>).</p>
  12324. <h1 id="2-what-do-i-need"><a class="header" href="#2-what-do-i-need">2. What do I need?</a></h1>
  12325. <p>If you are running Windows, the Windows Subsystem for Linux (WSL) is strongly
  12326. recommended for development. More information about WSL can be found at
  12327. <a href="https://docs.microsoft.com/en-us/windows/wsl/install">https://docs.microsoft.com/en-us/windows/wsl/install</a>. Running Synapse natively
  12328. on Windows is not officially supported.</p>
  12329. <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>
  12330. <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>
  12331. <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>
  12332. <p>For some tests, you will need <a href="https://docs.docker.com/get-docker/">a recent version of Docker</a>.</p>
  12333. <h1 id="3-get-the-source"><a class="header" href="#3-get-the-source">3. Get the source.</a></h1>
  12334. <p>The preferred and easiest way to contribute changes is to fork the relevant
  12335. 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
  12336. changes into our repo.</p>
  12337. <p>Please base your changes on the <code>develop</code> branch.</p>
  12338. <pre><code class="language-sh">git clone git@github.com:YOUR_GITHUB_USER_NAME/synapse.git
  12339. git checkout develop
  12340. </code></pre>
  12341. <p>If you need help getting started with git, this is beyond the scope of the document, but you
  12342. can find many good git tutorials on the web.</p>
  12343. <h1 id="4-install-the-dependencies"><a class="header" href="#4-install-the-dependencies">4. Install the dependencies</a></h1>
  12344. <p>Once you have installed Python 3 and added the source, please open a terminal and
  12345. setup a <em>virtualenv</em>, as follows:</p>
  12346. <pre><code class="language-sh">cd path/where/you/have/cloned/the/repository
  12347. python3 -m venv ./env
  12348. source ./env/bin/activate
  12349. pip install wheel
  12350. pip install -e &quot;.[all,dev]&quot;
  12351. pip install tox
  12352. </code></pre>
  12353. <p>This will install the developer dependencies for the project.</p>
  12354. <h1 id="5-get-in-touch"><a class="header" href="#5-get-in-touch">5. Get in touch.</a></h1>
  12355. <p>Join our developer community on Matrix: <a href="https://matrix.to/#/#synapse-dev:matrix.org">#synapse-dev:matrix.org</a>!</p>
  12356. <h1 id="6-pick-an-issue"><a class="header" href="#6-pick-an-issue">6. Pick an issue.</a></h1>
  12357. <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>
  12358. to work on.</p>
  12359. <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>
  12360. <p>There is a growing amount of documentation located in the
  12361. <a href="https://github.com/matrix-org/synapse/tree/develop/docs"><code>docs</code></a>
  12362. directory, with a rendered version <a href="https://matrix-org.github.io/synapse">available online</a>.
  12363. This documentation is intended primarily for sysadmins running their
  12364. own Synapse instance, as well as developers interacting externally with
  12365. Synapse.
  12366. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/development"><code>docs/development</code></a>
  12367. exists primarily to house documentation for
  12368. Synapse developers.
  12369. <a href="https://github.com/matrix-org/synapse/tree/develop/docs/admin_api"><code>docs/admin_api</code></a> houses documentation
  12370. regarding Synapse's Admin API, which is used mostly by sysadmins and external
  12371. service developers.</p>
  12372. <p>Synapse's code style is documented <a href="development/../code_style.html">here</a>. Please follow
  12373. it, including the conventions for the <a href="development/../code_style.html#configuration-file-format">sample configuration
  12374. file</a>.</p>
  12375. <p>We welcome improvements and additions to our documentation itself! When
  12376. writing new pages, please
  12377. <a href="https://github.com/matrix-org/synapse/tree/develop/docs#adding-to-the-documentation">build <code>docs</code> to a book</a>
  12378. to check that your contributions render correctly. The docs are written in
  12379. <a href="https://guides.github.com/features/mastering-markdown/">GitHub-Flavoured Markdown</a>.</p>
  12380. <p>Some documentation also exists in <a href="https://github.com/matrix-org/synapse/wiki">Synapse's GitHub
  12381. Wiki</a>, although this is primarily
  12382. contributed to by community authors.</p>
  12383. <h1 id="8-test-test-test"><a class="header" href="#8-test-test-test">8. Test, test, test!</a></h1>
  12384. <p><a name="test-test-test"></a></p>
  12385. <p>While you're developing and before submitting a patch, you'll
  12386. want to test your code.</p>
  12387. <h2 id="run-the-linters"><a class="header" href="#run-the-linters">Run the linters.</a></h2>
  12388. <p>The linters look at your code and do two things:</p>
  12389. <ul>
  12390. <li>ensure that your code follows the coding style adopted by the project;</li>
  12391. <li>catch a number of errors in your code.</li>
  12392. </ul>
  12393. <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 into your python virtual environment</a>.</p>
  12394. <pre><code class="language-sh">source ./env/bin/activate
  12395. ./scripts-dev/lint.sh
  12396. </code></pre>
  12397. <p>Note that this script <em>will modify your files</em> to fix styling errors.
  12398. Make sure that you have saved all your files.</p>
  12399. <p>If you wish to restrict the linters to only the files changed since the last commit
  12400. (much faster!), you can instead run:</p>
  12401. <pre><code class="language-sh">source ./env/bin/activate
  12402. ./scripts-dev/lint.sh -d
  12403. </code></pre>
  12404. <p>Or if you know exactly which files you wish to lint, you can instead run:</p>
  12405. <pre><code class="language-sh">source ./env/bin/activate
  12406. ./scripts-dev/lint.sh path/to/file1.py path/to/file2.py path/to/folder
  12407. </code></pre>
  12408. <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>
  12409. <p>The unit tests run parts of Synapse, including your changes, to see if anything
  12410. was broken. They are slower than the linters but will typically catch more errors.</p>
  12411. <pre><code class="language-sh">source ./env/bin/activate
  12412. trial tests
  12413. </code></pre>
  12414. <p>If you wish to only run <em>some</em> unit tests, you may specify
  12415. another module instead of <code>tests</code> - or a test class or a method:</p>
  12416. <pre><code class="language-sh">source ./env/bin/activate
  12417. trial tests.rest.admin.test_room tests.handlers.test_admin.ExfiltrateData.test_invite
  12418. </code></pre>
  12419. <p>If your tests fail, you may wish to look at the logs (the default log level is <code>ERROR</code>):</p>
  12420. <pre><code class="language-sh">less _trial_temp/test.log
  12421. </code></pre>
  12422. <p>To increase the log level for the tests, set <code>SYNAPSE_TEST_LOG_LEVEL</code>:</p>
  12423. <pre><code class="language-sh">SYNAPSE_TEST_LOG_LEVEL=DEBUG trial tests
  12424. </code></pre>
  12425. <p>By default, tests will use an in-memory SQLite database for test data. For additional
  12426. help with debugging, one can use an on-disk SQLite database file instead, in order to
  12427. review database state during and after running tests. This can be done by setting
  12428. the <code>SYNAPSE_TEST_PERSIST_SQLITE_DB</code> environment variable. Doing so will cause the
  12429. database state to be stored in a file named <code>test.db</code> under the trial process'
  12430. working directory. Typically, this ends up being <code>_trial_temp/test.db</code>. For example:</p>
  12431. <pre><code class="language-sh">SYNAPSE_TEST_PERSIST_SQLITE_DB=1 trial tests
  12432. </code></pre>
  12433. <p>The database file can then be inspected with:</p>
  12434. <pre><code class="language-sh">sqlite3 _trial_temp/test.db
  12435. </code></pre>
  12436. <p>Note that the database file is cleared at the beginning of each test run. Thus it
  12437. will always only contain the data generated by the <em>last run test</em>. Though generally
  12438. when debugging, one is only running a single test anyway.</p>
  12439. <h3 id="running-tests-under-postgresql"><a class="header" href="#running-tests-under-postgresql">Running tests under PostgreSQL</a></h3>
  12440. <p>Invoking <code>trial</code> as above will use an in-memory SQLite database. This is great for
  12441. quick development and testing. However, we recommend using a PostgreSQL database
  12442. in production (and indeed, we have some code paths specific to each database).
  12443. This means that we need to run our unit tests against PostgreSQL too. Our CI does
  12444. this automatically for pull requests and release candidates, but it's sometimes
  12445. useful to reproduce this locally.</p>
  12446. <p>To do so, <a href="development/../postgres.html">configure Postgres</a> and run <code>trial</code> with the
  12447. following environment variables matching your configuration:</p>
  12448. <ul>
  12449. <li><code>SYNAPSE_POSTGRES</code> to anything nonempty</li>
  12450. <li><code>SYNAPSE_POSTGRES_HOST</code></li>
  12451. <li><code>SYNAPSE_POSTGRES_USER</code></li>
  12452. <li><code>SYNAPSE_POSTGRES_PASSWORD</code></li>
  12453. </ul>
  12454. <p>For example:</p>
  12455. <pre><code class="language-shell">export SYNAPSE_POSTGRES=1
  12456. export SYNAPSE_POSTGRES_HOST=localhost
  12457. export SYNAPSE_POSTGRES_USER=postgres
  12458. export SYNAPSE_POSTGRES_PASSWORD=mydevenvpassword
  12459. trial
  12460. </code></pre>
  12461. <h4 id="prebuilt-container"><a class="header" href="#prebuilt-container">Prebuilt container</a></h4>
  12462. <p>Since configuring PostgreSQL can be fiddly, we can make use of a pre-made
  12463. Docker container to set up PostgreSQL and run our tests for us. To do so, run</p>
  12464. <pre><code class="language-shell">scripts-dev/test_postgresql.sh
  12465. </code></pre>
  12466. <p>Any extra arguments to the script will be passed to <code>tox</code> and then to <code>trial</code>,
  12467. so we can run a specific test in this container with e.g.</p>
  12468. <pre><code class="language-shell">scripts-dev/test_postgresql.sh tests.replication.test_sharded_event_persister.EventPersisterShardTestCase
  12469. </code></pre>
  12470. <p>The container creates a folder in your Synapse checkout called
  12471. <code>.tox-pg-container</code> and uses this as a tox environment. The output of any
  12472. <code>trial</code> runs goes into <code>_trial_temp</code> in your synapse source directory — the same
  12473. as running <code>trial</code> directly on your host machine.</p>
  12474. <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>
  12475. <p>The integration tests are a more comprehensive suite of tests. They
  12476. run a full version of Synapse, including your changes, to check if
  12477. anything was broken. They are slower than the unit tests but will
  12478. typically catch more errors.</p>
  12479. <p>The following command will let you run the integration test with the most common
  12480. configuration:</p>
  12481. <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
  12482. </code></pre>
  12483. <p>This configuration should generally cover your needs. For more details about other configurations, see <a href="https://github.com/matrix-org/sytest/blob/develop/docker/README.md">documentation in the SyTest repo</a>.</p>
  12484. <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>
  12485. <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>
  12486. <p>It's often nice to develop on Synapse and write Complement tests at the same time.
  12487. Here is how to run your local Synapse checkout against your local Complement checkout.</p>
  12488. <p>(checkout <a href="https://github.com/matrix-org/complement"><code>complement</code></a> alongside your <code>synapse</code> checkout)</p>
  12489. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh
  12490. </code></pre>
  12491. <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>
  12492. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh TestBackfillingHistory
  12493. </code></pre>
  12494. <p>To run a specific test, you can specify the whole name structure:</p>
  12495. <pre><code class="language-sh">COMPLEMENT_DIR=../complement ./scripts-dev/complement.sh TestBackfillingHistory/parallel/Backfilled_historical_events_resolve_with_proper_state_in_correct_order
  12496. </code></pre>
  12497. <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>
  12498. <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>
  12499. <ol>
  12500. <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>
  12501. <li>Start the Complement tests</li>
  12502. <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>
  12503. <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>
  12504. <li>Install sqlite (database driver), <code>apt-get update &amp;&amp; apt-get install -y sqlite3</code></li>
  12505. <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>
  12506. </ol>
  12507. <h1 id="9-submit-your-patch"><a class="header" href="#9-submit-your-patch">9. Submit your patch.</a></h1>
  12508. <p>Once you're happy with your patch, it's time to prepare a Pull Request.</p>
  12509. <p>To prepare a Pull Request, please:</p>
  12510. <ol>
  12511. <li>verify that <a href="development/contributing_guide.html#test-test-test">all the tests pass</a>, including the coding style;</li>
  12512. <li><a href="development/contributing_guide.html#sign-off">sign off</a> your contribution;</li>
  12513. <li><code>git push</code> your commit to your fork of Synapse;</li>
  12514. <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>
  12515. <li>add a <a href="development/contributing_guide.html#changelog">changelog entry</a> and push it to your Pull Request;</li>
  12516. <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>
  12517. <li>if you need to update your PR, please avoid rebasing and just add new commits to your branch.</li>
  12518. </ol>
  12519. <h2 id="changelog"><a class="header" href="#changelog">Changelog</a></h2>
  12520. <p>All changes, even minor ones, need a corresponding changelog / newsfragment
  12521. entry. These are managed by <a href="https://github.com/hawkowl/towncrier">Towncrier</a>.</p>
  12522. <p>To create a changelog entry, make a new file in the <code>changelog.d</code> directory named
  12523. in the format of <code>PRnumber.type</code>. The type can be one of the following:</p>
  12524. <ul>
  12525. <li><code>feature</code></li>
  12526. <li><code>bugfix</code></li>
  12527. <li><code>docker</code> (for updates to the Docker image)</li>
  12528. <li><code>doc</code> (for updates to the documentation)</li>
  12529. <li><code>removal</code> (also used for deprecations)</li>
  12530. <li><code>misc</code> (for internal-only changes)</li>
  12531. </ul>
  12532. <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
  12533. release, so the content of the file should be a short description of your
  12534. change in the same style as the rest of the changelog. The file can contain Markdown
  12535. formatting, and should end with a full stop (.) or an exclamation mark (!) for
  12536. consistency.</p>
  12537. <p>Adding credits to the changelog is encouraged, we value your
  12538. contributions and would like to have you shouted out in the release notes!</p>
  12539. <p>For example, a fix in PR #1234 would have its changelog entry in
  12540. <code>changelog.d/1234.bugfix</code>, and contain content like:</p>
  12541. <blockquote>
  12542. <p>The security levels of Florbs are now validated when received
  12543. via the <code>/federation/florb</code> endpoint. Contributed by Jane Matrix.</p>
  12544. </blockquote>
  12545. <p>If there are multiple pull requests involved in a single bugfix/feature/etc,
  12546. then the content for each <code>changelog.d</code> file should be the same. Towncrier will
  12547. merge the matching files together into a single changelog entry when we come to
  12548. release.</p>
  12549. <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>
  12550. <p>Obviously, you don't know if you should call your newsfile
  12551. <code>1234.bugfix</code> or <code>5678.bugfix</code> until you create the PR, which leads to a
  12552. chicken-and-egg problem.</p>
  12553. <p>There are two options for solving this:</p>
  12554. <ol>
  12555. <li>
  12556. <p>Open the PR without a changelog file, see what number you got, and <em>then</em>
  12557. add the changelog file to your branch (see <a href="development/contributing_guide.html#updating-your-pull-request">Updating your pull
  12558. request</a>), or:</p>
  12559. </li>
  12560. <li>
  12561. <p>Look at the <a href="https://github.com/matrix-org/synapse/issues?q=">list of all
  12562. issues/PRs</a>, add one to the
  12563. highest number you see, and quickly open the PR before somebody else claims
  12564. your number.</p>
  12565. <p><a href="https://github.com/richvdh/scripts/blob/master/next_github_number.sh">This
  12566. script</a>
  12567. might be helpful if you find yourself doing this a lot.</p>
  12568. </li>
  12569. </ol>
  12570. <p>Sorry, we know it's a bit fiddly, but it's <em>really</em> helpful for us when we come
  12571. to put together a release!</p>
  12572. <h3 id="debian-changelog"><a class="header" href="#debian-changelog">Debian changelog</a></h3>
  12573. <p>Changes which affect the debian packaging files (in <code>debian</code>) are an
  12574. exception to the rule that all changes require a <code>changelog.d</code> file.</p>
  12575. <p>In this case, you will need to add an entry to the debian changelog for the
  12576. next release. For this, run the following command:</p>
  12577. <pre><code>dch
  12578. </code></pre>
  12579. <p>This will make up a new version number (if there isn't already an unreleased
  12580. version in flight), and open an editor where you can add a new changelog entry.
  12581. (Our release process will ensure that the version number and maintainer name is
  12582. corrected for the release.)</p>
  12583. <p>If your change affects both the debian packaging <em>and</em> files outside the debian
  12584. directory, you will need both a regular newsfragment <em>and</em> an entry in the
  12585. debian changelog. (Though typically such changes should be submitted as two
  12586. separate pull requests.)</p>
  12587. <h2 id="sign-off"><a class="header" href="#sign-off">Sign off</a></h2>
  12588. <p>In order to have a concrete record that your contribution is intentional
  12589. and you agree to license it under the same terms as the project's license, we've adopted the
  12590. same lightweight approach that the Linux Kernel
  12591. <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>,
  12592. <a href="https://github.com/docker/docker/blob/master/CONTRIBUTING.md">Docker</a>, and many other
  12593. projects use: the DCO (Developer Certificate of Origin:
  12594. http://developercertificate.org/). This is a simple declaration that you wrote
  12595. the contribution or otherwise have the right to contribute it to Matrix:</p>
  12596. <pre><code>Developer Certificate of Origin
  12597. Version 1.1
  12598. Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
  12599. 660 York Street, Suite 102,
  12600. San Francisco, CA 94110 USA
  12601. Everyone is permitted to copy and distribute verbatim copies of this
  12602. license document, but changing it is not allowed.
  12603. Developer's Certificate of Origin 1.1
  12604. By making a contribution to this project, I certify that:
  12605. (a) The contribution was created in whole or in part by me and I
  12606. have the right to submit it under the open source license
  12607. indicated in the file; or
  12608. (b) The contribution is based upon previous work that, to the best
  12609. of my knowledge, is covered under an appropriate open source
  12610. license and I have the right under that license to submit that
  12611. work with modifications, whether created in whole or in part
  12612. by me, under the same open source license (unless I am
  12613. permitted to submit under a different license), as indicated
  12614. in the file; or
  12615. (c) The contribution was provided directly to me by some other
  12616. person who certified (a), (b) or (c) and I have not modified
  12617. it.
  12618. (d) I understand and agree that this project and the contribution
  12619. are public and that a record of the contribution (including all
  12620. personal information I submit with it, including my sign-off) is
  12621. maintained indefinitely and may be redistributed consistent with
  12622. this project or the open source license(s) involved.
  12623. </code></pre>
  12624. <p>If you agree to this for your contribution, then all that's needed is to
  12625. include the line in your commit or pull request comment:</p>
  12626. <pre><code>Signed-off-by: Your Name &lt;your@email.example.org&gt;
  12627. </code></pre>
  12628. <p>We accept contributions under a legally identifiable name, such as
  12629. your name on government documentation or common-law names (names
  12630. claimed by legitimate usage or repute). Unfortunately, we cannot
  12631. accept anonymous contributions at this time.</p>
  12632. <p>Git allows you to add this signoff automatically when using the <code>-s</code>
  12633. flag to <code>git commit</code>, which uses the name and email set in your
  12634. <code>user.name</code> and <code>user.email</code> git configs.</p>
  12635. <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>
  12636. <p>Once the Pull Request is opened, you will see a few things:</p>
  12637. <ol>
  12638. <li>our automated CI (Continuous Integration) pipeline will run (again) the linters, the unit tests, the integration tests and more;</li>
  12639. <li>one or more of the developers will take a look at your Pull Request and offer feedback.</li>
  12640. </ol>
  12641. <p>From this point, you should:</p>
  12642. <ol>
  12643. <li>Look at the results of the CI pipeline.
  12644. <ul>
  12645. <li>If there is any error, fix the error.</li>
  12646. </ul>
  12647. </li>
  12648. <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>
  12649. <li>Create a new commit with the changes.
  12650. <ul>
  12651. <li>Please do NOT overwrite the history. New commits make the reviewer's life easier.</li>
  12652. <li>Push this commits to your Pull Request.</li>
  12653. </ul>
  12654. </li>
  12655. <li>Back to 1.</li>
  12656. </ol>
  12657. <p>Once both the CI and the developers are happy, the patch will be merged into Synapse and released shortly!</p>
  12658. <h1 id="11-find-a-new-issue"><a class="header" href="#11-find-a-new-issue">11. Find a new issue.</a></h1>
  12659. <p>By now, you know the drill!</p>
  12660. <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>
  12661. <p>There are some notes for those with commit access to the project on how we
  12662. manage git <a href="development/git.html">here</a>.</p>
  12663. <h1 id="conclusion"><a class="header" href="#conclusion">Conclusion</a></h1>
  12664. <p>That's it! Matrix is a very open and collaborative project as you might expect
  12665. given our obsession with open communication. If we're going to successfully
  12666. matrix together all the fragmented communication technologies out there we are
  12667. reliant on contributions and collaboration from the community to do so. So
  12668. please get involved - and we hope you have as much fun hacking on Matrix as we
  12669. do!</p>
  12670. <div style="break-before: page; page-break-before: always;"></div><h1 id="code-style"><a class="header" href="#code-style">Code Style</a></h1>
  12671. <h2 id="formatting-tools"><a class="header" href="#formatting-tools">Formatting tools</a></h2>
  12672. <p>The Synapse codebase uses a number of code formatting tools in order to
  12673. quickly and automatically check for formatting (and sometimes logical)
  12674. errors in code.</p>
  12675. <p>The necessary tools are detailed below.</p>
  12676. <p>First install them with:</p>
  12677. <pre><code class="language-sh">pip install -e &quot;.[lint,mypy]&quot;
  12678. </code></pre>
  12679. <ul>
  12680. <li>
  12681. <p><strong>black</strong></p>
  12682. <p>The Synapse codebase uses <a href="https://pypi.org/project/black/">black</a>
  12683. as an opinionated code formatter, ensuring all comitted code is
  12684. properly formatted.</p>
  12685. <p>Have <code>black</code> auto-format your code (it shouldn't change any
  12686. functionality) with:</p>
  12687. <pre><code class="language-sh">black . --exclude=&quot;\.tox|build|env&quot;
  12688. </code></pre>
  12689. </li>
  12690. <li>
  12691. <p><strong>flake8</strong></p>
  12692. <p><code>flake8</code> is a code checking tool. We require code to pass <code>flake8</code>
  12693. before being merged into the codebase.</p>
  12694. <p>Check all application and test code with:</p>
  12695. <pre><code class="language-sh">flake8 synapse tests
  12696. </code></pre>
  12697. </li>
  12698. <li>
  12699. <p><strong>isort</strong></p>
  12700. <p><code>isort</code> ensures imports are nicely formatted, and can suggest and
  12701. auto-fix issues such as double-importing.</p>
  12702. <p>Auto-fix imports with:</p>
  12703. <pre><code class="language-sh">isort -rc synapse tests
  12704. </code></pre>
  12705. <p><code>-rc</code> means to recursively search the given directories.</p>
  12706. </li>
  12707. </ul>
  12708. <p>It's worth noting that modern IDEs and text editors can run these tools
  12709. automatically on save. It may be worth looking into whether this
  12710. functionality is supported in your editor for a more convenient
  12711. development workflow. It is not, however, recommended to run <code>flake8</code> on
  12712. save as it takes a while and is very resource intensive.</p>
  12713. <h2 id="general-rules"><a class="header" href="#general-rules">General rules</a></h2>
  12714. <ul>
  12715. <li><strong>Naming</strong>:
  12716. <ul>
  12717. <li>Use camel case for class and type names</li>
  12718. <li>Use underscores for functions and variables.</li>
  12719. </ul>
  12720. </li>
  12721. <li><strong>Docstrings</strong>: should follow the <a href="https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings">google code
  12722. style</a>.
  12723. See the
  12724. <a href="http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html">examples</a>
  12725. in the sphinx documentation.</li>
  12726. <li><strong>Imports</strong>:
  12727. <ul>
  12728. <li>
  12729. <p>Imports should be sorted by <code>isort</code> as described above.</p>
  12730. </li>
  12731. <li>
  12732. <p>Prefer to import classes and functions rather than packages or
  12733. modules.</p>
  12734. <p>Example:</p>
  12735. <pre><code class="language-python">from synapse.types import UserID
  12736. ...
  12737. user_id = UserID(local, server)
  12738. </code></pre>
  12739. <p>is preferred over:</p>
  12740. <pre><code class="language-python">from synapse import types
  12741. ...
  12742. user_id = types.UserID(local, server)
  12743. </code></pre>
  12744. <p>(or any other variant).</p>
  12745. <p>This goes against the advice in the Google style guide, but it
  12746. means that errors in the name are caught early (at import time).</p>
  12747. </li>
  12748. <li>
  12749. <p>Avoid wildcard imports (<code>from synapse.types import *</code>) and
  12750. relative imports (<code>from .types import UserID</code>).</p>
  12751. </li>
  12752. </ul>
  12753. </li>
  12754. </ul>
  12755. <h2 id="configuration-file-format"><a class="header" href="#configuration-file-format">Configuration file format</a></h2>
  12756. <p>The <a href="./sample_config.yaml">sample configuration file</a> acts as a
  12757. reference to Synapse's configuration options for server administrators.
  12758. Remember that many readers will be unfamiliar with YAML and server
  12759. administration in general, so that it is important that the file be as
  12760. easy to understand as possible, which includes following a consistent
  12761. format.</p>
  12762. <p>Some guidelines follow:</p>
  12763. <ul>
  12764. <li>
  12765. <p>Sections should be separated with a heading consisting of a single
  12766. line prefixed and suffixed with <code>##</code>. There should be <strong>two</strong> blank
  12767. lines before the section header, and <strong>one</strong> after.</p>
  12768. </li>
  12769. <li>
  12770. <p>Each option should be listed in the file with the following format:</p>
  12771. <ul>
  12772. <li>
  12773. <p>A comment describing the setting. Each line of this comment
  12774. should be prefixed with a hash (<code>#</code>) and a space.</p>
  12775. <p>The comment should describe the default behaviour (ie, what
  12776. happens if the setting is omitted), as well as what the effect
  12777. will be if the setting is changed.</p>
  12778. <p>Often, the comment end with something like &quot;uncomment the
  12779. following to <do action>&quot;.</p>
  12780. </li>
  12781. <li>
  12782. <p>A line consisting of only <code>#</code>.</p>
  12783. </li>
  12784. <li>
  12785. <p>A commented-out example setting, prefixed with only <code>#</code>.</p>
  12786. <p>For boolean (on/off) options, convention is that this example
  12787. should be the <em>opposite</em> to the default (so the comment will end
  12788. with &quot;Uncomment the following to enable [or disable]
  12789. <feature>.&quot; For other options, the example should give some
  12790. non-default value which is likely to be useful to the reader.</p>
  12791. </li>
  12792. </ul>
  12793. </li>
  12794. <li>
  12795. <p>There should be a blank line between each option.</p>
  12796. </li>
  12797. <li>
  12798. <p>Where several settings are grouped into a single dict, <em>avoid</em> the
  12799. convention where the whole block is commented out, resulting in
  12800. comment lines starting <code># #</code>, as this is hard to read and confusing
  12801. to edit. Instead, leave the top-level config option uncommented, and
  12802. follow the conventions above for sub-options. Ensure that your code
  12803. correctly handles the top-level option being set to <code>None</code> (as it
  12804. will be if no sub-options are enabled).</p>
  12805. </li>
  12806. <li>
  12807. <p>Lines should be wrapped at 80 characters.</p>
  12808. </li>
  12809. <li>
  12810. <p>Use two-space indents.</p>
  12811. </li>
  12812. <li>
  12813. <p><code>true</code> and <code>false</code> are spelt thus (as opposed to <code>True</code>, etc.)</p>
  12814. </li>
  12815. <li>
  12816. <p>Use single quotes (<code>'</code>) rather than double-quotes (<code>&quot;</code>) or backticks
  12817. (<code>`</code>) to refer to configuration options.</p>
  12818. </li>
  12819. </ul>
  12820. <p>Example:</p>
  12821. <pre><code class="language-yaml">## Frobnication ##
  12822. # The frobnicator will ensure that all requests are fully frobnicated.
  12823. # To enable it, uncomment the following.
  12824. #
  12825. #frobnicator_enabled: true
  12826. # By default, the frobnicator will frobnicate with the default frobber.
  12827. # The following will make it use an alternative frobber.
  12828. #
  12829. #frobincator_frobber: special_frobber
  12830. # Settings for the frobber
  12831. #
  12832. frobber:
  12833. # frobbing speed. Defaults to 1.
  12834. #
  12835. #speed: 10
  12836. # frobbing distance. Defaults to 1000.
  12837. #
  12838. #distance: 100
  12839. </code></pre>
  12840. <p>Note that the sample configuration is generated from the synapse code
  12841. and is maintained by a script, <code>scripts-dev/generate_sample_config</code>.
  12842. Making sure that the output from this script matches the desired format
  12843. is left as an exercise for the reader!</p>
  12844. <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>
  12845. <p>Releases of Synapse follow a two week release cycle with new releases usually
  12846. occurring on Tuesdays:</p>
  12847. <ul>
  12848. <li>Day 0: Synapse <code>N - 1</code> is released.</li>
  12849. <li>Day 7: Synapse <code>N</code> release candidate 1 is released.</li>
  12850. <li>Days 7 - 13: Synapse <code>N</code> release candidates 2+ are released, if bugs are found.</li>
  12851. <li>Day 14: Synapse <code>N</code> is released.</li>
  12852. </ul>
  12853. <p>Note that this schedule might be modified depending on the availability of the
  12854. Synapse team, e.g. releases may be skipped to avoid holidays.</p>
  12855. <p>Release announcements can be found in the
  12856. <a href="https://matrix.org/blog/category/releases">release category of the Matrix blog</a>.</p>
  12857. <h2 id="bugfix-releases"><a class="header" href="#bugfix-releases">Bugfix releases</a></h2>
  12858. <p>If a bug is found after release that is deemed severe enough (by a combination
  12859. of the impacted users and the impact on those users) then a bugfix release may
  12860. be issued. This may be at any point in the release cycle.</p>
  12861. <h2 id="security-releases"><a class="header" href="#security-releases">Security releases</a></h2>
  12862. <p>Security will sometimes be backported to the previous version and released
  12863. immediately before the next release candidate. An example of this might be:</p>
  12864. <ul>
  12865. <li>Day 0: Synapse N - 1 is released.</li>
  12866. <li>Day 7: Synapse (N - 1).1 is released as Synapse N - 1 + the security fix.</li>
  12867. <li>Day 7: Synapse N release candidate 1 is released (including the security fix).</li>
  12868. </ul>
  12869. <p>Depending on the impact and complexity of security fixes, multiple fixes might
  12870. be held to be released together.</p>
  12871. <p>In some cases, a pre-disclosure of a security release will be issued as a notice
  12872. to Synapse operators that there is an upcoming security release. These can be
  12873. found in the <a href="https://matrix.org/blog/category/security">security category of the Matrix blog</a>.</p>
  12874. <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>
  12875. <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>
  12876. <p>In an ideal world, our git commit history would be a linear progression of
  12877. commits each of which contains a single change building on what came
  12878. before. Here, by way of an arbitrary example, is the top of <code>git log --graph b2dba0607</code>:</p>
  12879. <img src="development/img/git/clean.png" alt="clean git graph" width="500px">
  12880. <p>Note how the commit comment explains clearly what is changing and why. Also
  12881. note the <em>absence</em> of merge commits, as well as the absence of commits called
  12882. things like (to pick a few culprits):
  12883. <a href="https://github.com/matrix-org/synapse/commit/84691da6c">“pep8”</a>, <a href="https://github.com/matrix-org/synapse/commit/474810d9d">“fix broken
  12884. test”</a>,
  12885. <a href="https://github.com/matrix-org/synapse/commit/c9d72e457">“oops”</a>,
  12886. <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
  12887. the president?”</a>.</p>
  12888. <p>There are a number of reasons why keeping a clean commit history is a good
  12889. thing:</p>
  12890. <ul>
  12891. <li>
  12892. <p>From time to time, after a change lands, it turns out to be necessary to
  12893. revert it, or to backport it to a release branch. Those operations are
  12894. <em>much</em> easier when the change is contained in a single commit.</p>
  12895. </li>
  12896. <li>
  12897. <p>Similarly, it's much easier to answer questions like “is the fix for
  12898. <code>/publicRooms</code> on the release branch?” if that change consists of a single
  12899. commit.</p>
  12900. </li>
  12901. <li>
  12902. <p>Likewise: “what has changed on this branch in the last week?” is much
  12903. clearer without merges and “pep8” commits everywhere.</p>
  12904. </li>
  12905. <li>
  12906. <p>Sometimes we need to figure out where a bug got introduced, or some
  12907. behaviour changed. One way of doing that is with <code>git bisect</code>: pick an
  12908. arbitrary commit between the known good point and the known bad point, and
  12909. see how the code behaves. However, that strategy fails if the commit you
  12910. chose is the middle of someone's epic branch in which they broke the world
  12911. before putting it back together again.</p>
  12912. </li>
  12913. </ul>
  12914. <p>One counterargument is that it is sometimes useful to see how a PR evolved as
  12915. it went through review cycles. This is true, but that information is always
  12916. 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
  12917. namespace</a>).</p>
  12918. <p>Of course, in reality, things are more complicated than that. We have release
  12919. branches as well as <code>develop</code> and <code>master</code>, and we deliberately merge changes
  12920. between them. Bugs often slip through and have to be fixed later. That's all
  12921. fine: this not a cast-iron rule which must be obeyed, but an ideal to aim
  12922. towards.</p>
  12923. <h2 id="merges-squashes-rebases-wtf"><a class="header" href="#merges-squashes-rebases-wtf">Merges, squashes, rebases: wtf?</a></h2>
  12924. <p>Ok, so that's what we'd like to achieve. How do we achieve it?</p>
  12925. <p>The TL;DR is: when you come to merge a pull request, you <em>probably</em> want to
  12926. “squash and merge”:</p>
  12927. <p><img src="development/img/git/squash.png" alt="squash and merge" />.</p>
  12928. <p>(This applies whether you are merging your own PR, or that of another
  12929. contributor.)</p>
  12930. <p>“Squash and merge”<sup id="a1"><a href="development/git.html#f1">1</a></sup> takes all of the changes in the
  12931. PR, and bundles them into a single commit. GitHub gives you the opportunity to
  12932. edit the commit message before you confirm, and normally you should do so,
  12933. because the default will be useless (again: <code>* woops typo</code> is not a useful
  12934. thing to keep in the historical record).</p>
  12935. <p>The main problem with this approach comes when you have a series of pull
  12936. requests which build on top of one another: as soon as you squash-merge the
  12937. first PR, you'll end up with a stack of conflicts to resolve in all of the
  12938. others. In general, it's best to avoid this situation in the first place by
  12939. trying not to have multiple related PRs in flight at the same time. Still,
  12940. sometimes that's not possible and doing a regular merge is the lesser evil.</p>
  12941. <p>Another occasion in which a regular merge makes more sense is a PR where you've
  12942. deliberately created a series of commits each of which makes sense in its own
  12943. right. For example: <a href="https://github.com/matrix-org/synapse/pull/6837">a PR which gradually propagates a refactoring operation
  12944. through the codebase</a>, or <a href="https://github.com/matrix-org/synapse/pull/5987">a
  12945. PR which is the culmination of several other
  12946. PRs</a>. In this case the ability
  12947. to figure out when a particular change/bug was introduced could be very useful.</p>
  12948. <p>Ultimately: <strong>this is not a hard-and-fast-rule</strong>. If in doubt, ask yourself “do
  12949. each of the commits I am about to merge make sense in their own right”, but
  12950. remember that we're just doing our best to balance “keeping the commit history
  12951. clean” with other factors.</p>
  12952. <h2 id="git-branching-model"><a class="header" href="#git-branching-model">Git branching model</a></h2>
  12953. <p>A <a href="https://nvie.com/posts/a-successful-git-branching-model/">lot</a>
  12954. <a href="http://scottchacon.com/2011/08/31/github-flow.html">of</a>
  12955. <a href="https://www.endoflineblog.com/gitflow-considered-harmful">words</a> have been
  12956. written in the past about git branching models (no really, <a href="https://martinfowler.com/articles/branching-patterns.html">a
  12957. lot</a>). I tend to
  12958. think the whole thing is overblown. Fundamentally, it's not that
  12959. complicated. Here's how we do it.</p>
  12960. <p>Let's start with a picture:</p>
  12961. <p><img src="development/img/git/branches.jpg" alt="branching model" /></p>
  12962. <p>It looks complicated, but it's really not. There's one basic rule: <em>anyone</em> is
  12963. free to merge from <em>any</em> more-stable branch to <em>any</em> less-stable branch at
  12964. <em>any</em> time<sup id="a2"><a href="development/git.html#f2">2</a></sup>. (The principle behind this is that if a
  12965. change is good enough for the more-stable branch, then it's also good enough go
  12966. put in a less-stable branch.)</p>
  12967. <p>Meanwhile, merging (or squashing, as per the above) from a less-stable to a
  12968. more-stable branch is a deliberate action in which you want to publish a change
  12969. or a set of changes to (some subset of) the world: for example, this happens
  12970. when a PR is landed, or as part of our release process.</p>
  12971. <p>So, what counts as a more- or less-stable branch? A little reflection will show
  12972. that our active branches are ordered thus, from more-stable to less-stable:</p>
  12973. <ul>
  12974. <li><code>master</code> (tracks our last release).</li>
  12975. <li><code>release-vX.Y</code> (the branch where we prepare the next release)<sup
  12976. id="a3"><a href="development/git.html#f3">3</a></sup>.</li>
  12977. <li>PR branches which are targeting the release.</li>
  12978. <li><code>develop</code> (our &quot;mainline&quot; branch containing our bleeding-edge).</li>
  12979. <li>regular PR branches.</li>
  12980. </ul>
  12981. <p>The corollary is: if you have a bugfix that needs to land in both
  12982. <code>release-vX.Y</code> <em>and</em> <code>develop</code>, then you should base your PR on
  12983. <code>release-vX.Y</code>, get it merged there, and then merge from <code>release-vX.Y</code> to
  12984. <code>develop</code>. (If a fix lands in <code>develop</code> and we later need it in a
  12985. release-branch, we can of course cherry-pick it, but landing it in the release
  12986. branch first helps reduce the chance of annoying conflicts.)</p>
  12987. <hr />
  12988. <p><b id="f1">[1]</b>: “Squash and merge” is GitHub's term for this
  12989. operation. Given that there is no merge involved, I'm not convinced it's the
  12990. most intuitive name. <a href="development/git.html#a1">^</a></p>
  12991. <p><b id="f2">[2]</b>: Well, anyone with commit access.<a href="development/git.html#a2">^</a></p>
  12992. <p><b id="f3">[3]</b>: Very, very occasionally (I think this has happened once in
  12993. the history of Synapse), we've had two releases in flight at once. Obviously,
  12994. <code>release-v1.2</code> is more-stable than <code>release-v1.3</code>. <a href="development/git.html#a3">^</a></p>
  12995. <div style="break-before: page; page-break-before: always;"></div><h1 id="opentracing"><a class="header" href="#opentracing">OpenTracing</a></h1>
  12996. <h2 id="background"><a class="header" href="#background">Background</a></h2>
  12997. <p>OpenTracing is a semi-standard being adopted by a number of distributed
  12998. tracing platforms. It is a common api for facilitating vendor-agnostic
  12999. tracing instrumentation. That is, we can use the OpenTracing api and
  13000. select one of a number of tracer implementations to do the heavy lifting
  13001. in the background. Our current selected implementation is Jaeger.</p>
  13002. <p>OpenTracing is a tool which gives an insight into the causal
  13003. relationship of work done in and between servers. The servers each track
  13004. events and report them to a centralised server - in Synapse's case:
  13005. Jaeger. The basic unit used to represent events is the span. The span
  13006. roughly represents a single piece of work that was done and the time at
  13007. which it occurred. A span can have child spans, meaning that the work of
  13008. the child had to be completed for the parent span to complete, or it can
  13009. have follow-on spans which represent work that is undertaken as a result
  13010. of the parent but is not depended on by the parent to in order to
  13011. finish.</p>
  13012. <p>Since this is undertaken in a distributed environment a request to
  13013. another server, such as an RPC or a simple GET, can be considered a span
  13014. (a unit or work) for the local server. This causal link is what
  13015. OpenTracing aims to capture and visualise. In order to do this metadata
  13016. about the local server's span, i.e the 'span context', needs to be
  13017. included with the request to the remote.</p>
  13018. <p>It is up to the remote server to decide what it does with the spans it
  13019. creates. This is called the sampling policy and it can be configured
  13020. through Jaeger's settings.</p>
  13021. <p>For OpenTracing concepts see
  13022. <a href="https://opentracing.io/docs/overview/what-is-tracing/">https://opentracing.io/docs/overview/what-is-tracing/</a>.</p>
  13023. <p>For more information about Jaeger's implementation see
  13024. <a href="https://www.jaegertracing.io/docs/">https://www.jaegertracing.io/docs/</a></p>
  13025. <h2 id="setting-up-opentracing"><a class="header" href="#setting-up-opentracing">Setting up OpenTracing</a></h2>
  13026. <p>To receive OpenTracing spans, start up a Jaeger server. This can be done
  13027. using docker like so:</p>
  13028. <pre><code class="language-sh">docker run -d --name jaeger \
  13029. -p 6831:6831/udp \
  13030. -p 6832:6832/udp \
  13031. -p 5778:5778 \
  13032. -p 16686:16686 \
  13033. -p 14268:14268 \
  13034. jaegertracing/all-in-one:1
  13035. </code></pre>
  13036. <p>Latest documentation is probably at
  13037. https://www.jaegertracing.io/docs/latest/getting-started.</p>
  13038. <h2 id="enable-opentracing-in-synapse"><a class="header" href="#enable-opentracing-in-synapse">Enable OpenTracing in Synapse</a></h2>
  13039. <p>OpenTracing is not enabled by default. It must be enabled in the
  13040. homeserver config by uncommenting the config options under <code>opentracing</code>
  13041. as shown in the <a href="./sample_config.yaml">sample config</a>. For example:</p>
  13042. <pre><code class="language-yaml">opentracing:
  13043. enabled: true
  13044. homeserver_whitelist:
  13045. - &quot;mytrustedhomeserver.org&quot;
  13046. - &quot;*.myotherhomeservers.com&quot;
  13047. </code></pre>
  13048. <h2 id="homeserver-whitelisting"><a class="header" href="#homeserver-whitelisting">Homeserver whitelisting</a></h2>
  13049. <p>The homeserver whitelist is configured using regular expressions. A list
  13050. of regular expressions can be given and their union will be compared
  13051. when propagating any spans contexts to another homeserver.</p>
  13052. <p>Though it's mostly safe to send and receive span contexts to and from
  13053. untrusted users since span contexts are usually opaque ids it can lead
  13054. to two problems, namely:</p>
  13055. <ul>
  13056. <li>If the span context is marked as sampled by the sending homeserver
  13057. the receiver will sample it. Therefore two homeservers with wildly
  13058. different sampling policies could incur higher sampling counts than
  13059. intended.</li>
  13060. <li>Sending servers can attach arbitrary data to spans, known as
  13061. 'baggage'. For safety this has been disabled in Synapse but that
  13062. doesn't prevent another server sending you baggage which will be
  13063. logged to OpenTracing's logs.</li>
  13064. </ul>
  13065. <h2 id="configuring-jaeger"><a class="header" href="#configuring-jaeger">Configuring Jaeger</a></h2>
  13066. <p>Sampling strategies can be set as in this document:
  13067. <a href="https://www.jaegertracing.io/docs/latest/sampling/">https://www.jaegertracing.io/docs/latest/sampling/</a>.</p>
  13068. <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>
  13069. <p>Synapse's database schema is stored in the <code>synapse.storage.schema</code> module.</p>
  13070. <h2 id="logical-databases"><a class="header" href="#logical-databases">Logical databases</a></h2>
  13071. <p>Synapse supports splitting its datastore across multiple physical databases (which can
  13072. be useful for large installations), and the schema files are therefore split according
  13073. to the logical database they apply to.</p>
  13074. <p>At the time of writing, the following &quot;logical&quot; databases are supported:</p>
  13075. <ul>
  13076. <li><code>state</code> - used to store Matrix room state (more specifically, <code>state_groups</code>,
  13077. their relationships and contents).</li>
  13078. <li><code>main</code> - stores everything else.</li>
  13079. </ul>
  13080. <p>Additionally, the <code>common</code> directory contains schema files for tables which must be
  13081. present on <em>all</em> physical databases.</p>
  13082. <h2 id="synapse-schema-versions"><a class="header" href="#synapse-schema-versions">Synapse schema versions</a></h2>
  13083. <p>Synapse manages its database schema via &quot;schema versions&quot;. These are mainly used to
  13084. help avoid confusion if the Synapse codebase is rolled back after the database is
  13085. updated. They work as follows:</p>
  13086. <ul>
  13087. <li>
  13088. <p>The Synapse codebase defines a constant <code>synapse.storage.schema.SCHEMA_VERSION</code>
  13089. which represents the expectations made about the database by that version. For
  13090. example, as of Synapse v1.36, this is <code>59</code>.</p>
  13091. </li>
  13092. <li>
  13093. <p>The database stores a &quot;compatibility version&quot; in
  13094. <code>schema_compat_version.compat_version</code> which defines the <code>SCHEMA_VERSION</code> of the
  13095. oldest version of Synapse which will work with the database. On startup, if
  13096. <code>compat_version</code> is found to be newer than <code>SCHEMA_VERSION</code>, Synapse will refuse to
  13097. start.</p>
  13098. <p>Synapse automatically updates this field from
  13099. <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code>.</p>
  13100. </li>
  13101. <li>
  13102. <p>Whenever a backwards-incompatible change is made to the database format (normally
  13103. via a <code>delta</code> file), <code>synapse.storage.schema.SCHEMA_COMPAT_VERSION</code> is also updated
  13104. so that administrators can not accidentally roll back to a too-old version of Synapse.</p>
  13105. </li>
  13106. </ul>
  13107. <p>Generally, the goal is to maintain compatibility with at least one or two previous
  13108. releases of Synapse, so any substantial change tends to require multiple releases and a
  13109. bit of forward-planning to get right.</p>
  13110. <p>As a worked example: we want to remove the <code>room_stats_historical</code> table. Here is how it
  13111. might pan out.</p>
  13112. <ol>
  13113. <li>
  13114. <p>Replace any code that <em>reads</em> from <code>room_stats_historical</code> with alternative
  13115. implementations, but keep writing to it in case of rollback to an earlier version.
  13116. Also, increase <code>synapse.storage.schema.SCHEMA_VERSION</code>. In this
  13117. instance, there is no existing code which reads from <code>room_stats_historical</code>, so
  13118. our starting point is:</p>
  13119. <p>v1.36.0: <code>SCHEMA_VERSION=59</code>, <code>SCHEMA_COMPAT_VERSION=59</code></p>
  13120. </li>
  13121. <li>
  13122. <p>Next (say in Synapse v1.37.0): remove the code that <em>writes</em> to
  13123. <code>room_stats_historical</code>, but don’t yet remove the table in case of rollback to
  13124. v1.36.0. Again, we increase <code>synapse.storage.schema.SCHEMA_VERSION</code>, but
  13125. because we have not broken compatibility with v1.36, we do not yet update
  13126. <code>SCHEMA_COMPAT_VERSION</code>. We now have:</p>
  13127. <p>v1.37.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=59</code>.</p>
  13128. </li>
  13129. <li>
  13130. <p>Later (say in Synapse v1.38.0): we can remove the table altogether. This will
  13131. break compatibility with v1.36.0, so we must update <code>SCHEMA_COMPAT_VERSION</code> accordingly.
  13132. There is no need to update <code>synapse.storage.schema.SCHEMA_VERSION</code>, since there is no
  13133. change to the Synapse codebase here. So we end up with:</p>
  13134. <p>v1.38.0: <code>SCHEMA_VERSION=60</code>, <code>SCHEMA_COMPAT_VERSION=60</code>.</p>
  13135. </li>
  13136. </ol>
  13137. <p>If in doubt about whether to update <code>SCHEMA_VERSION</code> or not, it is generally best to
  13138. lean towards doing so.</p>
  13139. <h2 id="full-schema-dumps"><a class="header" href="#full-schema-dumps">Full schema dumps</a></h2>
  13140. <p>In the <code>full_schemas</code> directories, only the most recently-numbered snapshot is used
  13141. (<code>54</code> at the time of writing). Older snapshots (eg, <code>16</code>) are present for historical
  13142. reference only.</p>
  13143. <h3 id="building-full-schema-dumps"><a class="header" href="#building-full-schema-dumps">Building full schema dumps</a></h3>
  13144. <p>If you want to recreate these schemas, they need to be made from a database that
  13145. has had all background updates run.</p>
  13146. <p>To do so, use <code>scripts-dev/make_full_schema.sh</code>. This will produce new
  13147. <code>full.sql.postgres</code> and <code>full.sql.sqlite</code> files.</p>
  13148. <p>Ensure postgres is installed, then run:</p>
  13149. <pre><code class="language-sh">./scripts-dev/make_full_schema.sh -p postgres_username -o output_dir/
  13150. </code></pre>
  13151. <p>NB at the time of writing, this script predates the split into separate <code>state</code>/<code>main</code>
  13152. databases so will require updates to handle that correctly.</p>
  13153. <h2 id="delta-files"><a class="header" href="#delta-files">Delta files</a></h2>
  13154. <p>Delta files define the steps required to upgrade the database from an earlier version.
  13155. They can be written as either a file containing a series of SQL statements, or a Python
  13156. module.</p>
  13157. <p>Synapse remembers which delta files it has applied to a database (they are stored in the
  13158. <code>applied_schema_deltas</code> table) and will not re-apply them (even if a given file is
  13159. subsequently updated).</p>
  13160. <p>Delta files should be placed in a directory named <code>synapse/storage/schema/&lt;database&gt;/delta/&lt;version&gt;/</code>.
  13161. They are applied in alphanumeric order, so by convention the first two characters
  13162. of the filename should be an integer such as <code>01</code>, to put the file in the right order.</p>
  13163. <h3 id="sql-delta-files"><a class="header" href="#sql-delta-files">SQL delta files</a></h3>
  13164. <p>These should be named <code>*.sql</code>, or — for changes which should only be applied for a
  13165. given database engine — <code>*.sql.posgres</code> or <code>*.sql.sqlite</code>. For example, a delta which
  13166. adds a new column to the <code>foo</code> table might be called <code>01add_bar_to_foo.sql</code>.</p>
  13167. <p>Note that our SQL parser is a bit simple - it understands comments (<code>--</code> and <code>/*...*/</code>),
  13168. 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>
  13169. <h3 id="python-delta-files"><a class="header" href="#python-delta-files">Python delta files</a></h3>
  13170. <p>For more flexibility, a delta file can take the form of a python module. These should
  13171. be named <code>*.py</code>. Note that database-engine-specific modules are not supported here –
  13172. instead you can write <code>if isinstance(database_engine, PostgresEngine)</code> or similar.</p>
  13173. <p>A Python delta module should define either or both of the following functions:</p>
  13174. <pre><code class="language-python">import synapse.config.homeserver
  13175. import synapse.storage.engines
  13176. import synapse.storage.types
  13177. def run_create(
  13178. cur: synapse.storage.types.Cursor,
  13179. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  13180. ) -&gt; None:
  13181. &quot;&quot;&quot;Called whenever an existing or new database is to be upgraded&quot;&quot;&quot;
  13182. ...
  13183. def run_upgrade(
  13184. cur: synapse.storage.types.Cursor,
  13185. database_engine: synapse.storage.engines.BaseDatabaseEngine,
  13186. config: synapse.config.homeserver.HomeServerConfig,
  13187. ) -&gt; None:
  13188. &quot;&quot;&quot;Called whenever an existing database is to be upgraded.&quot;&quot;&quot;
  13189. ...
  13190. </code></pre>
  13191. <h2 id="boolean-columns"><a class="header" href="#boolean-columns">Boolean columns</a></h2>
  13192. <p>Boolean columns require special treatment, since SQLite treats booleans the
  13193. same as integers.</p>
  13194. <p>There are three separate aspects to this:</p>
  13195. <ul>
  13196. <li>
  13197. <p>Any new boolean column must be added to the <code>BOOLEAN_COLUMNS</code> list in
  13198. <code>scripts/synapse_port_db</code>. This tells the port script to cast the integer
  13199. value from SQLite to a boolean before writing the value to the postgres
  13200. database.</p>
  13201. </li>
  13202. <li>
  13203. <p>Before SQLite 3.23, <code>TRUE</code> and <code>FALSE</code> were not recognised as constants by
  13204. SQLite, and the <code>IS [NOT] TRUE</code>/<code>IS [NOT] FALSE</code> operators were not
  13205. supported. This makes it necessary to avoid using <code>TRUE</code> and <code>FALSE</code>
  13206. constants in SQL commands.</p>
  13207. <p>For example, to insert a <code>TRUE</code> value into the database, write:</p>
  13208. <pre><code class="language-python">txn.execute(&quot;INSERT INTO tbl(col) VALUES (?)&quot;, (True, ))
  13209. </code></pre>
  13210. </li>
  13211. <li>
  13212. <p>Default values for new boolean columns present a particular
  13213. difficulty. Generally it is best to create separate schema files for
  13214. Postgres and SQLite. For example:</p>
  13215. <pre><code class="language-sql"># in 00delta.sql.postgres:
  13216. ALTER TABLE tbl ADD COLUMN col BOOLEAN DEFAULT FALSE;
  13217. </code></pre>
  13218. <pre><code class="language-sql"># in 00delta.sql.sqlite:
  13219. ALTER TABLE tbl ADD COLUMN col BOOLEAN DEFAULT 0;
  13220. </code></pre>
  13221. <p>Note that there is a particularly insidious failure mode here: the Postgres
  13222. flavour will be accepted by SQLite 3.22, but will give a column whose
  13223. default value is the <strong>string</strong> <code>&quot;FALSE&quot;</code> - which, when cast back to a boolean
  13224. in Python, evaluates to <code>True</code>.</p>
  13225. </li>
  13226. </ul>
  13227. <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>
  13228. <p>It can be desirable to implement &quot;experimental&quot; features which are disabled by
  13229. default and must be explicitly enabled via the Synapse configuration. This is
  13230. applicable for features which:</p>
  13231. <ul>
  13232. <li>Are unstable in the Matrix spec (e.g. those defined by an MSC that has not yet been merged).</li>
  13233. <li>Developers are not confident in their use by general Synapse administrators/users
  13234. (e.g. a feature is incomplete, buggy, performs poorly, or needs further testing).</li>
  13235. </ul>
  13236. <p>Note that this only really applies to features which are expected to be desirable
  13237. to a broad audience. The <a href="development/../modules/index.html">module infrastructure</a> should
  13238. instead be investigated for non-standard features.</p>
  13239. <p>Guarding experimental features behind configuration flags should help with some
  13240. of the following scenarios:</p>
  13241. <ul>
  13242. <li>Ensure that clients do not assume that unstable features exist (failing
  13243. gracefully if they do not).</li>
  13244. <li>Unstable features do not become de-facto standards and can be removed
  13245. aggressively (since only those who have opted-in will be affected).</li>
  13246. <li>Ease finding the implementation of unstable features in Synapse (for future
  13247. removal or stabilization).</li>
  13248. <li>Ease testing a feature (or removal of feature) due to enabling/disabling without
  13249. code changes. It also becomes possible to ask for wider testing, if desired.</li>
  13250. </ul>
  13251. <p>Experimental configuration flags should be disabled by default (requiring Synapse
  13252. administrators to explicitly opt-in), although there are situations where it makes
  13253. sense (from a product point-of-view) to enable features by default. This is
  13254. expected and not an issue.</p>
  13255. <p>It is not a requirement for experimental features to be behind a configuration flag,
  13256. but one should be used if unsure.</p>
  13257. <p>New experimental configuration flags should be added under the <code>experimental</code>
  13258. configuration key (see the <code>synapse.config.experimental</code> file) and either explain
  13259. (briefly) what is being enabled, or include the MSC number.</p>
  13260. <div style="break-before: page; page-break-before: always;"></div><h1 id="log-contexts"><a class="header" href="#log-contexts">Log Contexts</a></h1>
  13261. <p>To help track the processing of individual requests, synapse uses a
  13262. '<code>log context</code>' to track which request it is handling at any given
  13263. moment. This is done via a thread-local variable; a <code>logging.Filter</code> is
  13264. then used to fish the information back out of the thread-local variable
  13265. and add it to each log record.</p>
  13266. <p>Logcontexts are also used for CPU and database accounting, so that we
  13267. can track which requests were responsible for high CPU use or database
  13268. activity.</p>
  13269. <p>The <code>synapse.logging.context</code> module provides facilities for managing
  13270. the current log context (as well as providing the <code>LoggingContextFilter</code>
  13271. class).</p>
  13272. <p>Asynchronous functions make the whole thing complicated, so this document describes
  13273. how it all works, and how to write code which follows the rules.</p>
  13274. <p>In this document, &quot;awaitable&quot; refers to any object which can be <code>await</code>ed. In the context of
  13275. Synapse, that normally means either a coroutine or a Twisted
  13276. <a href="https://twistedmatrix.com/documents/current/api/twisted.internet.defer.Deferred.html"><code>Deferred</code></a>.</p>
  13277. <h2 id="logcontexts-without-asynchronous-code"><a class="header" href="#logcontexts-without-asynchronous-code">Logcontexts without asynchronous code</a></h2>
  13278. <p>In the absence of any asynchronous voodoo, things are simple enough. As with
  13279. any code of this nature, the rule is that our function should leave
  13280. things as it found them:</p>
  13281. <pre><code class="language-python">from synapse.logging import context # omitted from future snippets
  13282. def handle_request(request_id):
  13283. request_context = context.LoggingContext()
  13284. calling_context = context.set_current_context(request_context)
  13285. try:
  13286. request_context.request = request_id
  13287. do_request_handling()
  13288. logger.debug(&quot;finished&quot;)
  13289. finally:
  13290. context.set_current_context(calling_context)
  13291. def do_request_handling():
  13292. logger.debug(&quot;phew&quot;) # this will be logged against request_id
  13293. </code></pre>
  13294. <p>LoggingContext implements the context management methods, so the above
  13295. can be written much more succinctly as:</p>
  13296. <pre><code class="language-python">def handle_request(request_id):
  13297. with context.LoggingContext() as request_context:
  13298. request_context.request = request_id
  13299. do_request_handling()
  13300. logger.debug(&quot;finished&quot;)
  13301. def do_request_handling():
  13302. logger.debug(&quot;phew&quot;)
  13303. </code></pre>
  13304. <h2 id="using-logcontexts-with-awaitables"><a class="header" href="#using-logcontexts-with-awaitables">Using logcontexts with awaitables</a></h2>
  13305. <p>Awaitables break the linear flow of code so that there is no longer a single entry point
  13306. where we should set the logcontext and a single exit point where we should remove it.</p>
  13307. <p>Consider the example above, where <code>do_request_handling</code> needs to do some
  13308. blocking operation, and returns an awaitable:</p>
  13309. <pre><code class="language-python">async def handle_request(request_id):
  13310. with context.LoggingContext() as request_context:
  13311. request_context.request = request_id
  13312. await do_request_handling()
  13313. logger.debug(&quot;finished&quot;)
  13314. </code></pre>
  13315. <p>In the above flow:</p>
  13316. <ul>
  13317. <li>The logcontext is set</li>
  13318. <li><code>do_request_handling</code> is called, and returns an awaitable</li>
  13319. <li><code>handle_request</code> awaits the awaitable</li>
  13320. <li>Execution of <code>handle_request</code> is suspended</li>
  13321. </ul>
  13322. <p>So we have stopped processing the request (and will probably go on to
  13323. start processing the next), without clearing the logcontext.</p>
  13324. <p>To circumvent this problem, synapse code assumes that, wherever you have
  13325. an awaitable, you will want to <code>await</code> it. To that end, whereever
  13326. functions return awaitables, we adopt the following conventions:</p>
  13327. <p><strong>Rules for functions returning awaitables:</strong></p>
  13328. <blockquote>
  13329. <ul>
  13330. <li>If the awaitable is already complete, the function returns with the
  13331. same logcontext it started with.</li>
  13332. <li>If the awaitable is incomplete, the function clears the logcontext
  13333. before returning; when the awaitable completes, it restores the
  13334. logcontext before running any callbacks.</li>
  13335. </ul>
  13336. </blockquote>
  13337. <p>That sounds complicated, but actually it means a lot of code (including
  13338. the example above) &quot;just works&quot;. There are two cases:</p>
  13339. <ul>
  13340. <li>
  13341. <p>If <code>do_request_handling</code> returns a completed awaitable, then the
  13342. logcontext will still be in place. In this case, execution will
  13343. continue immediately after the <code>await</code>; the &quot;finished&quot; line will
  13344. be logged against the right context, and the <code>with</code> block restores
  13345. the original context before we return to the caller.</p>
  13346. </li>
  13347. <li>
  13348. <p>If the returned awaitable is incomplete, <code>do_request_handling</code> clears
  13349. the logcontext before returning. The logcontext is therefore clear
  13350. when <code>handle_request</code> <code>await</code>s the awaitable.</p>
  13351. <p>Once <code>do_request_handling</code>'s awaitable completes, it will reinstate
  13352. the logcontext, before running the second half of <code>handle_request</code>,
  13353. so again the &quot;finished&quot; line will be logged against the right context,
  13354. and the <code>with</code> block restores the original context.</p>
  13355. </li>
  13356. </ul>
  13357. <p>As an aside, it's worth noting that <code>handle_request</code> follows our rules</p>
  13358. <ul>
  13359. <li>though that only matters if the caller has its own logcontext which it
  13360. cares about.</li>
  13361. </ul>
  13362. <p>The following sections describe pitfalls and helpful patterns when
  13363. implementing these rules.</p>
  13364. <h2 id="always-await-your-awaitables"><a class="header" href="#always-await-your-awaitables">Always await your awaitables</a></h2>
  13365. <p>Whenever you get an awaitable back from a function, you should <code>await</code> on
  13366. it as soon as possible. Do not pass go; do not do any logging; do not
  13367. call any other functions.</p>
  13368. <pre><code class="language-python">async def fun():
  13369. logger.debug(&quot;starting&quot;)
  13370. await do_some_stuff() # just like this
  13371. coro = more_stuff()
  13372. result = await coro # also fine, of course
  13373. return result
  13374. </code></pre>
  13375. <p>Provided this pattern is followed all the way back up to the callchain
  13376. to where the logcontext was set, this will make things work out ok:
  13377. provided <code>do_some_stuff</code> and <code>more_stuff</code> follow the rules above, then
  13378. so will <code>fun</code>.</p>
  13379. <p>It's all too easy to forget to <code>await</code>: for instance if we forgot that
  13380. <code>do_some_stuff</code> returned an awaitable, we might plough on regardless. This
  13381. leads to a mess; it will probably work itself out eventually, but not
  13382. before a load of stuff has been logged against the wrong context.
  13383. (Normally, other things will break, more obviously, if you forget to
  13384. <code>await</code>, so this tends not to be a major problem in practice.)</p>
  13385. <p>Of course sometimes you need to do something a bit fancier with your
  13386. awaitable - not all code follows the linear A-then-B-then-C pattern.
  13387. Notes on implementing more complex patterns are in later sections.</p>
  13388. <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>
  13389. <p>Most of the time, an awaitable comes from another synapse function.
  13390. Sometimes, though, we need to make up a new awaitable, or we get an awaitable
  13391. back from external code. We need to make it follow our rules.</p>
  13392. <p>The easy way to do it is by using <code>context.make_deferred_yieldable</code>. Suppose we want to implement
  13393. <code>sleep</code>, which returns a deferred which will run its callbacks after a
  13394. given number of seconds. That might look like:</p>
  13395. <pre><code class="language-python"># not a logcontext-rules-compliant function
  13396. def get_sleep_deferred(seconds):
  13397. d = defer.Deferred()
  13398. reactor.callLater(seconds, d.callback, None)
  13399. return d
  13400. </code></pre>
  13401. <p>That doesn't follow the rules, but we can fix it by calling it through
  13402. <code>context.make_deferred_yieldable</code>:</p>
  13403. <pre><code class="language-python">async def sleep(seconds):
  13404. return await context.make_deferred_yieldable(get_sleep_deferred(seconds))
  13405. </code></pre>
  13406. <h2 id="fire-and-forget"><a class="header" href="#fire-and-forget">Fire-and-forget</a></h2>
  13407. <p>Sometimes you want to fire off a chain of execution, but not wait for
  13408. its result. That might look a bit like this:</p>
  13409. <pre><code class="language-python">async def do_request_handling():
  13410. await foreground_operation()
  13411. # *don't* do this
  13412. background_operation()
  13413. logger.debug(&quot;Request handling complete&quot;)
  13414. async def background_operation():
  13415. await first_background_step()
  13416. logger.debug(&quot;Completed first step&quot;)
  13417. await second_background_step()
  13418. logger.debug(&quot;Completed second step&quot;)
  13419. </code></pre>
  13420. <p>The above code does a couple of steps in the background after
  13421. <code>do_request_handling</code> has finished. The log lines are still logged
  13422. against the <code>request_context</code> logcontext, which may or may not be
  13423. desirable. There are two big problems with the above, however. The first
  13424. problem is that, if <code>background_operation</code> returns an incomplete
  13425. awaitable, it will expect its caller to <code>await</code> immediately, so will have
  13426. cleared the logcontext. In this example, that means that 'Request
  13427. handling complete' will be logged without any context.</p>
  13428. <p>The second problem, which is potentially even worse, is that when the
  13429. awaitable returned by <code>background_operation</code> completes, it will restore
  13430. the original logcontext. There is nothing waiting on that awaitable, so
  13431. the logcontext will leak into the reactor and possibly get attached to
  13432. some arbitrary future operation.</p>
  13433. <p>There are two potential solutions to this.</p>
  13434. <p>One option is to surround the call to <code>background_operation</code> with a
  13435. <code>PreserveLoggingContext</code> call. That will reset the logcontext before
  13436. starting <code>background_operation</code> (so the context restored when the
  13437. deferred completes will be the empty logcontext), and will restore the
  13438. current logcontext before continuing the foreground process:</p>
  13439. <pre><code class="language-python">async def do_request_handling():
  13440. await foreground_operation()
  13441. # start background_operation off in the empty logcontext, to
  13442. # avoid leaking the current context into the reactor.
  13443. with PreserveLoggingContext():
  13444. background_operation()
  13445. # this will now be logged against the request context
  13446. logger.debug(&quot;Request handling complete&quot;)
  13447. </code></pre>
  13448. <p>Obviously that option means that the operations done in
  13449. <code>background_operation</code> would be not be logged against a logcontext
  13450. (though that might be fixed by setting a different logcontext via a
  13451. <code>with LoggingContext(...)</code> in <code>background_operation</code>).</p>
  13452. <p>The second option is to use <code>context.run_in_background</code>, which wraps a
  13453. function so that it doesn't reset the logcontext even when it returns
  13454. an incomplete awaitable, and adds a callback to the returned awaitable to
  13455. reset the logcontext. In other words, it turns a function that follows
  13456. the Synapse rules about logcontexts and awaitables into one which behaves
  13457. more like an external function --- the opposite operation to that
  13458. described in the previous section. It can be used like this:</p>
  13459. <pre><code class="language-python">async def do_request_handling():
  13460. await foreground_operation()
  13461. context.run_in_background(background_operation)
  13462. # this will now be logged against the request context
  13463. logger.debug(&quot;Request handling complete&quot;)
  13464. </code></pre>
  13465. <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>
  13466. <p>A typical example of this is where we want to collect together two or
  13467. more awaitables via <code>defer.gatherResults</code>:</p>
  13468. <pre><code class="language-python">a1 = operation1()
  13469. a2 = operation2()
  13470. a3 = defer.gatherResults([a1, a2])
  13471. </code></pre>
  13472. <p>This is really a variation of the fire-and-forget problem above, in that
  13473. we are firing off <code>a1</code> and <code>a2</code> without awaiting on them. The difference
  13474. is that we now have third-party code attached to their callbacks. Anyway
  13475. either technique given in the <a href="log_contexts.html#fire-and-forget">Fire-and-forget</a>
  13476. section will work.</p>
  13477. <p>Of course, the new awaitable returned by <code>gather</code> needs to be
  13478. wrapped in order to make it follow the logcontext rules before we can
  13479. 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
  13480. follow the
  13481. rules</a>.</p>
  13482. <p>So, option one: reset the logcontext before starting the operations to
  13483. be gathered:</p>
  13484. <pre><code class="language-python">async def do_request_handling():
  13485. with PreserveLoggingContext():
  13486. a1 = operation1()
  13487. a2 = operation2()
  13488. result = await defer.gatherResults([a1, a2])
  13489. </code></pre>
  13490. <p>In this case particularly, though, option two, of using
  13491. <code>context.run_in_background</code> almost certainly makes more sense, so that
  13492. <code>operation1</code> and <code>operation2</code> are both logged against the original
  13493. logcontext. This looks like:</p>
  13494. <pre><code class="language-python">async def do_request_handling():
  13495. a1 = context.run_in_background(operation1)
  13496. a2 = context.run_in_background(operation2)
  13497. result = await make_deferred_yieldable(defer.gatherResults([a1, a2]))
  13498. </code></pre>
  13499. <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>
  13500. <p>It turns out that our logcontext rules do not play nicely with awaitable
  13501. chains which get orphaned and garbage-collected.</p>
  13502. <p>Imagine we have some code that looks like this:</p>
  13503. <pre><code class="language-python">listener_queue = []
  13504. def on_something_interesting():
  13505. for d in listener_queue:
  13506. d.callback(&quot;foo&quot;)
  13507. async def await_something_interesting():
  13508. new_awaitable = defer.Deferred()
  13509. listener_queue.append(new_awaitable)
  13510. with PreserveLoggingContext():
  13511. await new_awaitable
  13512. </code></pre>
  13513. <p>Obviously, the idea here is that we have a bunch of things which are
  13514. waiting for an event. (It's just an example of the problem here, but a
  13515. relatively common one.)</p>
  13516. <p>Now let's imagine two further things happen. First of all, whatever was
  13517. waiting for the interesting thing goes away. (Perhaps the request times
  13518. out, or something <em>even more</em> interesting happens.)</p>
  13519. <p>Secondly, let's suppose that we decide that the interesting thing is
  13520. never going to happen, and we reset the listener queue:</p>
  13521. <pre><code class="language-python">def reset_listener_queue():
  13522. listener_queue.clear()
  13523. </code></pre>
  13524. <p>So, both ends of the awaitable chain have now dropped their references,
  13525. and the awaitable chain is now orphaned, and will be garbage-collected at
  13526. some point. Note that <code>await_something_interesting</code> is a coroutine,
  13527. which Python implements as a generator function. When Python
  13528. garbage-collects generator functions, it gives them a chance to
  13529. clean up by making the <code>await</code> (or <code>yield</code>) raise a <code>GeneratorExit</code>
  13530. exception. In our case, that means that the <code>__exit__</code> handler of
  13531. <code>PreserveLoggingContext</code> will carefully restore the request context, but
  13532. there is now nothing waiting for its return, so the request context is
  13533. never cleared.</p>
  13534. <p>To reiterate, this problem only arises when <em>both</em> ends of a awaitable
  13535. chain are dropped. Dropping the the reference to an awaitable you're
  13536. supposed to be awaiting is bad practice, so this doesn't
  13537. actually happen too much. Unfortunately, when it does happen, it will
  13538. lead to leaked logcontexts which are incredibly hard to track down.</p>
  13539. <div style="break-before: page; page-break-before: always;"></div><h1 id="replication-architecture"><a class="header" href="#replication-architecture">Replication Architecture</a></h1>
  13540. <h2 id="motivation"><a class="header" href="#motivation">Motivation</a></h2>
  13541. <p>We'd like to be able to split some of the work that synapse does into
  13542. multiple python processes. In theory multiple synapse processes could
  13543. share a single postgresql database and we'd scale up by running more
  13544. synapse processes. However much of synapse assumes that only one process
  13545. is interacting with the database, both for assigning unique identifiers
  13546. when inserting into tables, notifying components about new updates, and
  13547. for invalidating its caches.</p>
  13548. <p>So running multiple copies of the current code isn't an option. One way
  13549. to run multiple processes would be to have a single writer process and
  13550. multiple reader processes connected to the same database. In order to do
  13551. this we'd need a way for the reader process to invalidate its in-memory
  13552. caches when an update happens on the writer. One way to do this is for
  13553. the writer to present an append-only log of updates which the readers
  13554. can consume to invalidate their caches and to push updates to listening
  13555. clients or pushers.</p>
  13556. <p>Synapse already stores much of its data as an append-only log so that it
  13557. can correctly respond to <code>/sync</code> requests so the amount of code changes
  13558. needed to expose the append-only log to the readers should be fairly
  13559. minimal.</p>
  13560. <h2 id="architecture"><a class="header" href="#architecture">Architecture</a></h2>
  13561. <h3 id="the-replication-protocol"><a class="header" href="#the-replication-protocol">The Replication Protocol</a></h3>
  13562. <p>See <a href="tcp_replication.html">the TCP replication documentation</a>.</p>
  13563. <h3 id="the-slaved-datastore"><a class="header" href="#the-slaved-datastore">The Slaved DataStore</a></h3>
  13564. <p>There are read-only version of the synapse storage layer in
  13565. <code>synapse/replication/slave/storage</code> that use the response of the
  13566. replication API to invalidate their caches.</p>
  13567. <div style="break-before: page; page-break-before: always;"></div><h1 id="tcp-replication"><a class="header" href="#tcp-replication">TCP Replication</a></h1>
  13568. <h2 id="motivation-1"><a class="header" href="#motivation-1">Motivation</a></h2>
  13569. <p>Previously the workers used an HTTP long poll mechanism to get updates
  13570. from the master, which had the problem of causing a lot of duplicate
  13571. work on the server. This TCP protocol replaces those APIs with the aim
  13572. of increased efficiency.</p>
  13573. <h2 id="overview-3"><a class="header" href="#overview-3">Overview</a></h2>
  13574. <p>The protocol is based on fire and forget, line based commands. An
  13575. example flow would be (where '&gt;' indicates master to worker and
  13576. '&lt;' worker to master flows):</p>
  13577. <pre><code>&gt; SERVER example.com
  13578. &lt; REPLICATE
  13579. &gt; POSITION events master 53 53
  13580. &gt; RDATA events master 54 [&quot;$foo1:bar.com&quot;, ...]
  13581. &gt; RDATA events master 55 [&quot;$foo4:bar.com&quot;, ...]
  13582. </code></pre>
  13583. <p>The example shows the server accepting a new connection and sending its identity
  13584. with the <code>SERVER</code> command, followed by the client server to respond with the
  13585. position of all streams. The server then periodically sends <code>RDATA</code> commands
  13586. which have the format <code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row&gt;</code>, where
  13587. the format of <code>&lt;row&gt;</code> is defined by the individual streams. The
  13588. <code>&lt;instance_name&gt;</code> is the name of the Synapse process that generated the data
  13589. (usually &quot;master&quot;).</p>
  13590. <p>Error reporting happens by either the client or server sending an ERROR
  13591. command, and usually the connection will be closed.</p>
  13592. <p>Since the protocol is a simple line based, its possible to manually
  13593. connect to the server using a tool like netcat. A few things should be
  13594. noted when manually using the protocol:</p>
  13595. <ul>
  13596. <li>The federation stream is only available if federation sending has
  13597. been disabled on the main process.</li>
  13598. <li>The server will only time connections out that have sent a <code>PING</code>
  13599. command. If a ping is sent then the connection will be closed if no
  13600. further commands are receieved within 15s. Both the client and
  13601. server protocol implementations will send an initial PING on
  13602. connection and ensure at least one command every 5s is sent (not
  13603. necessarily <code>PING</code>).</li>
  13604. <li><code>RDATA</code> commands <em>usually</em> include a numeric token, however if the
  13605. stream has multiple rows to replicate per token the server will send
  13606. multiple <code>RDATA</code> commands, with all but the last having a token of
  13607. <code>batch</code>. See the documentation on <code>commands.RdataCommand</code> for
  13608. further details.</li>
  13609. </ul>
  13610. <h2 id="architecture-1"><a class="header" href="#architecture-1">Architecture</a></h2>
  13611. <p>The basic structure of the protocol is line based, where the initial
  13612. word of each line specifies the command. The rest of the line is parsed
  13613. based on the command. For example, the RDATA command is defined as:</p>
  13614. <pre><code>RDATA &lt;stream_name&gt; &lt;instance_name&gt; &lt;token&gt; &lt;row_json&gt;
  13615. </code></pre>
  13616. <p>(Note that &lt;row_json&gt; may contains spaces, but cannot contain
  13617. newlines.)</p>
  13618. <p>Blank lines are ignored.</p>
  13619. <h3 id="keep-alives"><a class="header" href="#keep-alives">Keep alives</a></h3>
  13620. <p>Both sides are expected to send at least one command every 5s or so, and
  13621. should send a <code>PING</code> command if necessary. If either side do not receive
  13622. a command within e.g. 15s then the connection should be closed.</p>
  13623. <p>Because the server may be connected to manually using e.g. netcat, the
  13624. timeouts aren't enabled until an initial <code>PING</code> command is seen. Both
  13625. the client and server implementations below send a <code>PING</code> command
  13626. immediately on connection to ensure the timeouts are enabled.</p>
  13627. <p>This ensures that both sides can quickly realize if the tcp connection
  13628. has gone and handle the situation appropriately.</p>
  13629. <h3 id="start-up"><a class="header" href="#start-up">Start up</a></h3>
  13630. <p>When a new connection is made, the server:</p>
  13631. <ul>
  13632. <li>Sends a <code>SERVER</code> command, which includes the identity of the server,
  13633. allowing the client to detect if its connected to the expected
  13634. server</li>
  13635. <li>Sends a <code>PING</code> command as above, to enable the client to time out
  13636. connections promptly.</li>
  13637. </ul>
  13638. <p>The client:</p>
  13639. <ul>
  13640. <li>Sends a <code>NAME</code> command, allowing the server to associate a human
  13641. friendly name with the connection. This is optional.</li>
  13642. <li>Sends a <code>PING</code> as above</li>
  13643. <li>Sends a <code>REPLICATE</code> to get the current position of all streams.</li>
  13644. <li>On receipt of a <code>SERVER</code> command, checks that the server name
  13645. matches the expected server name.</li>
  13646. </ul>
  13647. <h3 id="error-handling"><a class="header" href="#error-handling">Error handling</a></h3>
  13648. <p>If either side detects an error it can send an <code>ERROR</code> command and close
  13649. the connection.</p>
  13650. <p>If the client side loses the connection to the server it should
  13651. reconnect, following the steps above.</p>
  13652. <h3 id="congestion"><a class="header" href="#congestion">Congestion</a></h3>
  13653. <p>If the server sends messages faster than the client can consume them the
  13654. server will first buffer a (fairly large) number of commands and then
  13655. disconnect the client. This ensures that we don't queue up an unbounded
  13656. number of commands in memory and gives us a potential oppurtunity to
  13657. squawk loudly. When/if the client recovers it can reconnect to the
  13658. server and ask for missed messages.</p>
  13659. <h3 id="reliability"><a class="header" href="#reliability">Reliability</a></h3>
  13660. <p>In general the replication stream should be considered an unreliable
  13661. transport since e.g. commands are not resent if the connection
  13662. disappears.</p>
  13663. <p>The exception to that are the replication streams, i.e. RDATA commands,
  13664. since these include tokens which can be used to restart the stream on
  13665. connection errors.</p>
  13666. <p>The client should keep track of the token in the last RDATA command
  13667. received for each stream so that on reconneciton it can start streaming
  13668. from the correct place. Note: not all RDATA have valid tokens due to
  13669. batching. See <code>RdataCommand</code> for more details.</p>
  13670. <h3 id="example-4"><a class="header" href="#example-4">Example</a></h3>
  13671. <p>An example iteraction is shown below. Each line is prefixed with '&gt;'
  13672. or '&lt;' to indicate which side is sending, these are <em>not</em> included on
  13673. the wire:</p>
  13674. <pre><code>* connection established *
  13675. &gt; SERVER localhost:8823
  13676. &gt; PING 1490197665618
  13677. &lt; NAME synapse.app.appservice
  13678. &lt; PING 1490197665618
  13679. &lt; REPLICATE
  13680. &gt; POSITION events master 1 1
  13681. &gt; POSITION backfill master 1 1
  13682. &gt; POSITION caches master 1 1
  13683. &gt; RDATA caches master 2 [&quot;get_user_by_id&quot;,[&quot;@01register-user:localhost:8823&quot;],1490197670513]
  13684. &gt; RDATA events master 14 [&quot;$149019767112vOHxz:localhost:8823&quot;,
  13685. &quot;!AFDCvgApUmpdfVjIXm:localhost:8823&quot;,&quot;m.room.guest_access&quot;,&quot;&quot;,null]
  13686. &lt; PING 1490197675618
  13687. &gt; ERROR server stopping
  13688. * connection closed by server *
  13689. </code></pre>
  13690. <p>The <code>POSITION</code> command sent by the server is used to set the clients
  13691. position without needing to send data with the <code>RDATA</code> command.</p>
  13692. <p>An example of a batched set of <code>RDATA</code> is:</p>
  13693. <pre><code>&gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test:localhost:8823&quot;],1490197670513]
  13694. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test2:localhost:8823&quot;],1490197670513]
  13695. &gt; RDATA caches master batch [&quot;get_user_by_id&quot;,[&quot;@test3:localhost:8823&quot;],1490197670513]
  13696. &gt; RDATA caches master 54 [&quot;get_user_by_id&quot;,[&quot;@test4:localhost:8823&quot;],1490197670513]
  13697. </code></pre>
  13698. <p>In this case the client shouldn't advance their caches token until it
  13699. sees the the last <code>RDATA</code>.</p>
  13700. <h3 id="list-of-commands"><a class="header" href="#list-of-commands">List of commands</a></h3>
  13701. <p>The list of valid commands, with which side can send it: server (S) or
  13702. client (C):</p>
  13703. <h4 id="server-s"><a class="header" href="#server-s">SERVER (S)</a></h4>
  13704. <p>Sent at the start to identify which server the client is talking to</p>
  13705. <h4 id="rdata-s"><a class="header" href="#rdata-s">RDATA (S)</a></h4>
  13706. <p>A single update in a stream</p>
  13707. <h4 id="position-s"><a class="header" href="#position-s">POSITION (S)</a></h4>
  13708. <p>On receipt of a POSITION command clients should check if they have missed any
  13709. updates, and if so then fetch them out of band. Sent in response to a
  13710. REPLICATE command (but can happen at any time).</p>
  13711. <p>The POSITION command includes the source of the stream. Currently all streams
  13712. are written by a single process (usually &quot;master&quot;). If fetching missing
  13713. updates via HTTP API, rather than via the DB, then processes should make the
  13714. request to the appropriate process.</p>
  13715. <p>Two positions are included, the &quot;new&quot; position and the last position sent respectively.
  13716. This allows servers to tell instances that the positions have advanced but no
  13717. data has been written, without clients needlessly checking to see if they
  13718. have missed any updates.</p>
  13719. <h4 id="error-s-c"><a class="header" href="#error-s-c">ERROR (S, C)</a></h4>
  13720. <p>There was an error</p>
  13721. <h4 id="ping-s-c"><a class="header" href="#ping-s-c">PING (S, C)</a></h4>
  13722. <p>Sent periodically to ensure the connection is still alive</p>
  13723. <h4 id="name-c"><a class="header" href="#name-c">NAME (C)</a></h4>
  13724. <p>Sent at the start by client to inform the server who they are</p>
  13725. <h4 id="replicate-c"><a class="header" href="#replicate-c">REPLICATE (C)</a></h4>
  13726. <p>Asks the server for the current position of all streams.</p>
  13727. <h4 id="user_sync-c"><a class="header" href="#user_sync-c">USER_SYNC (C)</a></h4>
  13728. <p>A user has started or stopped syncing on this process.</p>
  13729. <h4 id="clear_user_sync-c"><a class="header" href="#clear_user_sync-c">CLEAR_USER_SYNC (C)</a></h4>
  13730. <p>The server should clear all associated user sync data from the worker.</p>
  13731. <p>This is used when a worker is shutting down.</p>
  13732. <h4 id="federation_ack-c"><a class="header" href="#federation_ack-c">FEDERATION_ACK (C)</a></h4>
  13733. <p>Acknowledge receipt of some federation data</p>
  13734. <h3 id="remote_server_up-s-c"><a class="header" href="#remote_server_up-s-c">REMOTE_SERVER_UP (S, C)</a></h3>
  13735. <p>Inform other processes that a remote server may have come back online.</p>
  13736. <p>See <code>synapse/replication/tcp/commands.py</code> for a detailed description and
  13737. the format of each command.</p>
  13738. <h3 id="cache-invalidation-stream"><a class="header" href="#cache-invalidation-stream">Cache Invalidation Stream</a></h3>
  13739. <p>The cache invalidation stream is used to inform workers when they need
  13740. to invalidate any of their caches in the data store. This is done by
  13741. streaming all cache invalidations done on master down to the workers,
  13742. assuming that any caches on the workers also exist on the master.</p>
  13743. <p>Each individual cache invalidation results in a row being sent down
  13744. replication, which includes the cache name (the name of the function)
  13745. and they key to invalidate. For example:</p>
  13746. <pre><code>&gt; RDATA caches master 550953771 [&quot;get_user_by_id&quot;, [&quot;@bob:example.com&quot;], 1550574873251]
  13747. </code></pre>
  13748. <p>Alternatively, an entire cache can be invalidated by sending down a <code>null</code>
  13749. instead of the key. For example:</p>
  13750. <pre><code>&gt; RDATA caches master 550953772 [&quot;get_user_by_id&quot;, null, 1550574873252]
  13751. </code></pre>
  13752. <p>However, there are times when a number of caches need to be invalidated
  13753. at the same time with the same key. To reduce traffic we batch those
  13754. invalidations into a single poke by defining a special cache name that
  13755. workers understand to mean to expand to invalidate the correct caches.</p>
  13756. <p>Currently the special cache names are declared in
  13757. <code>synapse/storage/_base.py</code> and are:</p>
  13758. <ol>
  13759. <li><code>cs_cache_fake</code> ─ invalidates caches that depend on the current
  13760. state</li>
  13761. </ol>
  13762. <div style="break-before: page; page-break-before: always;"></div><h1 id="internal-documentation"><a class="header" href="#internal-documentation">Internal Documentation</a></h1>
  13763. <p>This section covers implementation documentation for various parts of Synapse.</p>
  13764. <p>If a developer is planning to make a change to a feature of Synapse, it can be useful for
  13765. general documentation of how that feature is implemented to be available. This saves the
  13766. developer time in place of needing to understand how the feature works by reading the
  13767. code.</p>
  13768. <p>Documentation that would be more useful for the perspective of a system administrator,
  13769. rather than a developer who's intending to change to code, should instead be placed
  13770. under the Usage section of the documentation.</p>
  13771. <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>
  13772. <p>https://fujifish.github.io/samling/samling.html (https://github.com/fujifish/samling) is a great resource for being able to tinker with the
  13773. SAML options within Synapse without needing to deploy and configure a complicated software stack.</p>
  13774. <p>To make Synapse (and therefore Element) use it:</p>
  13775. <ol>
  13776. <li>Use the samling.html URL above or deploy your own and visit the IdP Metadata tab.</li>
  13777. <li>Copy the XML to your clipboard.</li>
  13778. <li>On your Synapse server, create a new file <code>samling.xml</code> next to your <code>homeserver.yaml</code> with
  13779. the XML from step 2 as the contents.</li>
  13780. <li>Edit your <code>homeserver.yaml</code> to include:
  13781. <pre><code class="language-yaml">saml2_config:
  13782. sp_config:
  13783. allow_unknown_attributes: true # Works around a bug with AVA Hashes: https://github.com/IdentityPython/pysaml2/issues/388
  13784. metadata:
  13785. local: [&quot;samling.xml&quot;]
  13786. </code></pre>
  13787. </li>
  13788. <li>Ensure that your <code>homeserver.yaml</code> has a setting for <code>public_baseurl</code>:
  13789. <pre><code class="language-yaml">public_baseurl: http://localhost:8080/
  13790. </code></pre>
  13791. </li>
  13792. <li>Run <code>apt-get install xmlsec1</code> and <code>pip install --upgrade --force 'pysaml2&gt;=4.5.0'</code> to ensure
  13793. the dependencies are installed and ready to go.</li>
  13794. <li>Restart Synapse.</li>
  13795. </ol>
  13796. <p>Then in Element:</p>
  13797. <ol>
  13798. <li>Visit the login page and point Element towards your homeserver using the <code>public_baseurl</code> above.</li>
  13799. <li>Click the Single Sign-On button.</li>
  13800. <li>On the samling page, enter a Name Identifier and add a SAML Attribute for <code>uid=your_localpart</code>.
  13801. The response must also be signed.</li>
  13802. <li>Click &quot;Next&quot;.</li>
  13803. <li>Click &quot;Post Response&quot; (change nothing).</li>
  13804. <li>You should be logged in.</li>
  13805. </ol>
  13806. <p>If you try and repeat this process, you may be automatically logged in using the information you
  13807. gave previously. To fix this, open your developer console (<code>F12</code> or <code>Ctrl+Shift+I</code>) while on the
  13808. samling page and clear the site data. In Chrome, this will be a button on the Application tab.</p>
  13809. <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>
  13810. <p>The <a href="https://github.com/jbittel/django-mama-cas">django-mama-cas</a> project is an
  13811. easy to run CAS implementation built on top of Django.</p>
  13812. <h2 id="prerequisites"><a class="header" href="#prerequisites">Prerequisites</a></h2>
  13813. <ol>
  13814. <li>Create a new virtualenv: <code>python3 -m venv &lt;your virtualenv&gt;</code></li>
  13815. <li>Activate your virtualenv: <code>source /path/to/your/virtualenv/bin/activate</code></li>
  13816. <li>Install Django and django-mama-cas:
  13817. <pre><code class="language-sh">python -m pip install &quot;django&lt;3&quot; &quot;django-mama-cas==2.4.0&quot;
  13818. </code></pre>
  13819. </li>
  13820. <li>Create a Django project in the current directory:
  13821. <pre><code class="language-sh">django-admin startproject cas_test .
  13822. </code></pre>
  13823. </li>
  13824. <li>Follow the <a href="https://django-mama-cas.readthedocs.io/en/latest/installation.html#configuring">install directions</a> for django-mama-cas</li>
  13825. <li>Setup the SQLite database: <code>python manage.py migrate</code></li>
  13826. <li>Create a user:
  13827. <pre><code class="language-sh">python manage.py createsuperuser
  13828. </code></pre>
  13829. <ol>
  13830. <li>Use whatever you want as the username and password.</li>
  13831. <li>Leave the other fields blank.</li>
  13832. </ol>
  13833. </li>
  13834. <li>Use the built-in Django test server to serve the CAS endpoints on port 8000:
  13835. <pre><code class="language-sh">python manage.py runserver
  13836. </code></pre>
  13837. </li>
  13838. </ol>
  13839. <p>You should now have a Django project configured to serve CAS authentication with
  13840. a single user created.</p>
  13841. <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>
  13842. <ol>
  13843. <li>Modify your <code>homeserver.yaml</code> to enable CAS and point it to your locally
  13844. running Django test server:
  13845. <pre><code class="language-yaml">cas_config:
  13846. enabled: true
  13847. server_url: &quot;http://localhost:8000&quot;
  13848. service_url: &quot;http://localhost:8081&quot;
  13849. #displayname_attribute: name
  13850. #required_attributes:
  13851. # name: value
  13852. </code></pre>
  13853. </li>
  13854. <li>Restart Synapse.</li>
  13855. </ol>
  13856. <p>Note that the above configuration assumes the homeserver is running on port 8081
  13857. and that the CAS server is on port 8000, both on localhost.</p>
  13858. <h2 id="testing-the-configuration"><a class="header" href="#testing-the-configuration">Testing the configuration</a></h2>
  13859. <p>Then in Element:</p>
  13860. <ol>
  13861. <li>Visit the login page with a Element pointing at your homeserver.</li>
  13862. <li>Click the Single Sign-On button.</li>
  13863. <li>Login using the credentials created with <code>createsuperuser</code>.</li>
  13864. <li>You should be logged in.</li>
  13865. </ol>
  13866. <p>If you want to repeat this process you'll need to manually logout first:</p>
  13867. <ol>
  13868. <li>http://localhost:8000/admin/</li>
  13869. <li>Click &quot;logout&quot; in the top right.</li>
  13870. </ol>
  13871. <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>
  13872. <h2 id="edges"><a class="header" href="#edges">Edges</a></h2>
  13873. <p>The word &quot;edge&quot; comes from graph theory lingo. An edge is just a connection
  13874. between two events. In Synapse, we connect events by specifying their
  13875. <code>prev_events</code>. A subsequent event points back at a previous event.</p>
  13876. <pre><code>A (oldest) &lt;---- B &lt;---- C (most recent)
  13877. </code></pre>
  13878. <h2 id="depth-and-stream-ordering"><a class="header" href="#depth-and-stream-ordering">Depth and stream ordering</a></h2>
  13879. <p>Events are normally sorted by <code>(topological_ordering, stream_ordering)</code> where
  13880. <code>topological_ordering</code> is just <code>depth</code>. In other words, we first sort by <code>depth</code>
  13881. and then tie-break based on <code>stream_ordering</code>. <code>depth</code> is incremented as new
  13882. messages are added to the DAG. Normally, <code>stream_ordering</code> is an auto
  13883. incrementing integer, but backfilled events start with <code>stream_ordering=-1</code> and decrement.</p>
  13884. <hr />
  13885. <ul>
  13886. <li><code>/sync</code> returns things in the order they arrive at the server (<code>stream_ordering</code>).</li>
  13887. <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>
  13888. </ul>
  13889. <p>The general idea is that, if you're following a room in real-time (i.e.
  13890. <code>/sync</code>), you probably want to see the messages as they arrive at your server,
  13891. rather than skipping any that arrived late; whereas if you're looking at a
  13892. historical section of timeline (i.e. <code>/messages</code>), you want to see the best
  13893. representation of the state of the room as others were seeing it at the time.</p>
  13894. <h2 id="forward-extremity"><a class="header" href="#forward-extremity">Forward extremity</a></h2>
  13895. <p>Most-recent-in-time events in the DAG which are not referenced by any other events' <code>prev_events</code> yet.</p>
  13896. <p>The forward extremities of a room are used as the <code>prev_events</code> when the next event is sent.</p>
  13897. <h2 id="backward-extremity"><a class="header" href="#backward-extremity">Backward extremity</a></h2>
  13898. <p>The current marker of where we have backfilled up to and will generally be the
  13899. <code>prev_events</code> of the oldest-in-time events we have in the DAG. This gives a starting point when
  13900. backfilling history.</p>
  13901. <p>When we persist a non-outlier event, we clear it as a backward extremity and set
  13902. all of its <code>prev_events</code> as the new backward extremities if they aren't already
  13903. persisted in the <code>events</code> table.</p>
  13904. <h2 id="outliers"><a class="header" href="#outliers">Outliers</a></h2>
  13905. <p>We mark an event as an <code>outlier</code> when we haven't figured out the state for the
  13906. room at that point in the DAG yet.</p>
  13907. <p>We won't <em>necessarily</em> have the <code>prev_events</code> of an <code>outlier</code> in the database,
  13908. but it's entirely possible that we <em>might</em>.</p>
  13909. <p>For example, when we fetch the event auth chain or state for a given event, we
  13910. mark all of those claimed auth events as outliers because we haven't done the
  13911. state calculation ourself.</p>
  13912. <h2 id="state-groups"><a class="header" href="#state-groups">State groups</a></h2>
  13913. <p>For every non-outlier event we need to know the state at that event. Instead of
  13914. storing the full state for each event in the DB (i.e. a <code>event_id -&gt; state</code>
  13915. mapping), which is <em>very</em> space inefficient when state doesn't change, we
  13916. instead assign each different set of state a &quot;state group&quot; and then have
  13917. mappings of <code>event_id -&gt; state_group</code> and <code>state_group -&gt; state</code>.</p>
  13918. <h3 id="stage-group-edges"><a class="header" href="#stage-group-edges">Stage group edges</a></h3>
  13919. <p>TODO: <code>state_group_edges</code> is a further optimization...
  13920. notes from @Azrenbeth, https://pastebin.com/seUGVGeT</p>
  13921. <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>
  13922. <p>The auth chain difference algorithm is used by V2 state resolution, where a
  13923. naive implementation can be a significant source of CPU and DB usage.</p>
  13924. <h3 id="definitions"><a class="header" href="#definitions">Definitions</a></h3>
  13925. <p>A <em>state set</em> is a set of state events; e.g. the input of a state resolution
  13926. algorithm is a collection of state sets.</p>
  13927. <p>The <em>auth chain</em> of a set of events are all the events' auth events and <em>their</em>
  13928. auth events, recursively (i.e. the events reachable by walking the graph induced
  13929. by an event's auth events links).</p>
  13930. <p>The <em>auth chain difference</em> of a collection of state sets is the union minus the
  13931. intersection of the sets of auth chains corresponding to the state sets, i.e an
  13932. event is in the auth chain difference if it is reachable by walking the auth
  13933. event graph from at least one of the state sets but not from <em>all</em> of the state
  13934. sets.</p>
  13935. <h2 id="breadth-first-walk-algorithm"><a class="header" href="#breadth-first-walk-algorithm">Breadth First Walk Algorithm</a></h2>
  13936. <p>A way of calculating the auth chain difference without calculating the full auth
  13937. chains for each state set is to do a parallel breadth first walk (ordered by
  13938. depth) of each state set's auth chain. By tracking which events are reachable
  13939. from each state set we can finish early if every pending event is reachable from
  13940. every state set.</p>
  13941. <p>This can work well for state sets that have a small auth chain difference, but
  13942. can be very inefficient for larger differences. However, this algorithm is still
  13943. used if we don't have a chain cover index for the room (e.g. because we're in
  13944. the process of indexing it).</p>
  13945. <h2 id="chain-cover-index"><a class="header" href="#chain-cover-index">Chain Cover Index</a></h2>
  13946. <p>Synapse computes auth chain differences by pre-computing a &quot;chain cover&quot; index
  13947. for the auth chain in a room, allowing efficient reachability queries like &quot;is
  13948. event A in the auth chain of event B&quot;. This is done by assigning every event a
  13949. <em>chain ID</em> and <em>sequence number</em> (e.g. <code>(5,3)</code>), and having a map of <em>links</em>
  13950. between chains (e.g. <code>(5,3) -&gt; (2,4)</code>) such that A is reachable by B (i.e. <code>A</code>
  13951. is in the auth chain of <code>B</code>) if and only if either:</p>
  13952. <ol>
  13953. <li>A and B have the same chain ID and <code>A</code>'s sequence number is less than <code>B</code>'s
  13954. sequence number; or</li>
  13955. <li>there is a link <code>L</code> between <code>B</code>'s chain ID and <code>A</code>'s chain ID such that
  13956. <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>
  13957. </ol>
  13958. <p>There are actually two potential implementations, one where we store links from
  13959. each chain to every other reachable chain (the transitive closure of the links
  13960. graph), and one where we remove redundant links (the transitive reduction of the
  13961. links graph) e.g. if we have chains <code>C3 -&gt; C2 -&gt; C1</code> then the link <code>C3 -&gt; C1</code>
  13962. would not be stored. Synapse uses the former implementations so that it doesn't
  13963. need to recurse to test reachability between chains.</p>
  13964. <h3 id="example-5"><a class="header" href="#example-5">Example</a></h3>
  13965. <p>An example auth graph would look like the following, where chains have been
  13966. formed based on type/state_key and are denoted by colour and are labelled with
  13967. <code>(chain ID, sequence number)</code>. Links are denoted by the arrows (links in grey
  13968. are those that would be remove in the second implementation described above).</p>
  13969. <p><img src="auth_chain_diff.dot.png" alt="Example" /></p>
  13970. <p>Note that we don't include all links between events and their auth events, as
  13971. most of those links would be redundant. For example, all events point to the
  13972. create event, but each chain only needs the one link from it's base to the
  13973. create event.</p>
  13974. <h2 id="using-the-index"><a class="header" href="#using-the-index">Using the Index</a></h2>
  13975. <p>This index can be used to calculate the auth chain difference of the state sets
  13976. by looking at the chain ID and sequence numbers reachable from each state set:</p>
  13977. <ol>
  13978. <li>For every state set lookup the chain ID/sequence numbers of each state event</li>
  13979. <li>Use the index to find all chains and the maximum sequence number reachable
  13980. from each state set.</li>
  13981. <li>The auth chain difference is then all events in each chain that have sequence
  13982. numbers between the maximum sequence number reachable from <em>any</em> state set and
  13983. the minimum reachable by <em>all</em> state sets (if any).</li>
  13984. </ol>
  13985. <p>Note that steps 2 is effectively calculating the auth chain for each state set
  13986. (in terms of chain IDs and sequence numbers), and step 3 is calculating the
  13987. difference between the union and intersection of the auth chains.</p>
  13988. <h3 id="worked-example"><a class="header" href="#worked-example">Worked Example</a></h3>
  13989. <p>For example, given the above graph, we can calculate the difference between
  13990. state sets consisting of:</p>
  13991. <ol>
  13992. <li><code>S1</code>: Alice's invite <code>(4,1)</code> and Bob's second join <code>(2,2)</code>; and</li>
  13993. <li><code>S2</code>: Alice's second join <code>(4,3)</code> and Bob's first join <code>(2,1)</code>.</li>
  13994. </ol>
  13995. <p>Using the index we see that the following auth chains are reachable from each
  13996. state set:</p>
  13997. <ol>
  13998. <li><code>S1</code>: <code>(1,1)</code>, <code>(2,2)</code>, <code>(3,1)</code> &amp; <code>(4,1)</code></li>
  13999. <li><code>S2</code>: <code>(1,1)</code>, <code>(2,1)</code>, <code>(3,2)</code> &amp; <code>(4,3)</code></li>
  14000. </ol>
  14001. <p>And so, for each the ranges that are in the auth chain difference:</p>
  14002. <ol>
  14003. <li>Chain 1: None, (since everything can reach the create event).</li>
  14004. <li>Chain 2: The range <code>(1, 2]</code> (i.e. just <code>2</code>), as <code>1</code> is reachable by all state
  14005. sets and the maximum reachable is <code>2</code> (corresponding to Bob's second join).</li>
  14006. <li>Chain 3: Similarly the range <code>(1, 2]</code> (corresponding to the second power
  14007. level).</li>
  14008. <li>Chain 4: The range <code>(1, 3]</code> (corresponding to both of Alice's joins).</li>
  14009. </ol>
  14010. <p>So the final result is: Bob's second join <code>(2,2)</code>, the second power level
  14011. <code>(3,2)</code> and both of Alice's joins <code>(4,2)</code> &amp; <code>(4,3)</code>.</p>
  14012. <div style="break-before: page; page-break-before: always;"></div><h1 id="media-repository"><a class="header" href="#media-repository">Media Repository</a></h1>
  14013. <p><em>Synapse implementation-specific details for the media repository</em></p>
  14014. <p>The media repository</p>
  14015. <ul>
  14016. <li>stores avatars, attachments and their thumbnails for media uploaded by local
  14017. users.</li>
  14018. <li>caches avatars, attachments and their thumbnails for media uploaded by remote
  14019. users.</li>
  14020. <li>caches resources and thumbnails used for
  14021. <a href="development/url_previews.html">URL previews</a>.</li>
  14022. </ul>
  14023. <p>All media in Matrix can be identified by a unique
  14024. <a href="https://spec.matrix.org/latest/client-server-api/#matrix-content-mxc-uris">MXC URI</a>,
  14025. consisting of a server name and media ID:</p>
  14026. <pre><code>mxc://&lt;server-name&gt;/&lt;media-id&gt;
  14027. </code></pre>
  14028. <h2 id="local-media"><a class="header" href="#local-media">Local Media</a></h2>
  14029. <p>Synapse generates 24 character media IDs for content uploaded by local users.
  14030. These media IDs consist of upper and lowercase letters and are case-sensitive.
  14031. Other homeserver implementations may generate media IDs differently.</p>
  14032. <p>Local media is recorded in the <code>local_media_repository</code> table, which includes
  14033. metadata such as MIME types, upload times and file sizes.
  14034. Note that this table is shared by the URL cache, which has a different media ID
  14035. scheme.</p>
  14036. <h3 id="paths"><a class="header" href="#paths">Paths</a></h3>
  14037. <p>A file with media ID <code>aabbcccccccccccccccccccc</code> and its <code>128x96</code> <code>image/jpeg</code>
  14038. thumbnail, created by scaling, would be stored at:</p>
  14039. <pre><code>local_content/aa/bb/cccccccccccccccccccc
  14040. local_thumbnails/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  14041. </code></pre>
  14042. <h2 id="remote-media"><a class="header" href="#remote-media">Remote Media</a></h2>
  14043. <p>When media from a remote homeserver is requested from Synapse, it is assigned
  14044. a local <code>filesystem_id</code>, with the same format as locally-generated media IDs,
  14045. as described above.</p>
  14046. <p>A record of remote media is stored in the <code>remote_media_cache</code> table, which
  14047. can be used to map remote MXC URIs (server names and media IDs) to local
  14048. <code>filesystem_id</code>s.</p>
  14049. <h3 id="paths-1"><a class="header" href="#paths-1">Paths</a></h3>
  14050. <p>A file from <code>matrix.org</code> with <code>filesystem_id</code> <code>aabbcccccccccccccccccccc</code> and its
  14051. <code>128x96</code> <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  14052. <pre><code>remote_content/matrix.org/aa/bb/cccccccccccccccccccc
  14053. remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg-scale
  14054. </code></pre>
  14055. <p>Older thumbnails may omit the thumbnailing method:</p>
  14056. <pre><code>remote_thumbnail/matrix.org/aa/bb/cccccccccccccccccccc/128-96-image-jpeg
  14057. </code></pre>
  14058. <p>Note that <code>remote_thumbnail/</code> does not have an <code>s</code>.</p>
  14059. <h2 id="url-previews-2"><a class="header" href="#url-previews-2">URL Previews</a></h2>
  14060. <p>See <a href="development/url_previews.html">URL Previews</a> for documentation on the URL preview
  14061. process.</p>
  14062. <p>When generating previews for URLs, Synapse may download and cache various
  14063. resources, including images. These resources are assigned temporary media IDs
  14064. of the form <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code>, where <code>yyyy-mm-dd</code> is the current
  14065. date and <code>aaaaaaaaaaaaaaaa</code> is a random sequence of 16 case-sensitive letters.</p>
  14066. <p>The metadata for these cached resources is stored in the
  14067. <code>local_media_repository</code> and <code>local_media_repository_url_cache</code> tables.</p>
  14068. <p>Resources for URL previews are deleted after a few days.</p>
  14069. <h3 id="paths-2"><a class="header" href="#paths-2">Paths</a></h3>
  14070. <p>The file with media ID <code>yyyy-mm-dd_aaaaaaaaaaaaaaaa</code> and its <code>128x96</code>
  14071. <code>image/jpeg</code> thumbnail, created by scaling, would be stored at:</p>
  14072. <pre><code>url_cache/yyyy-mm-dd/aaaaaaaaaaaaaaaa
  14073. url_cache_thumbnails/yyyy-mm-dd/aaaaaaaaaaaaaaaa/128-96-image-jpeg-scale
  14074. </code></pre>
  14075. <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>
  14076. <p>Synapse maintains room and user statistics in various tables. These can be used
  14077. for administrative purposes but are also used when generating the public room
  14078. directory.</p>
  14079. <h1 id="synapse-developer-documentation"><a class="header" href="#synapse-developer-documentation">Synapse Developer Documentation</a></h1>
  14080. <h2 id="high-level-concepts"><a class="header" href="#high-level-concepts">High-Level Concepts</a></h2>
  14081. <h3 id="definitions-1"><a class="header" href="#definitions-1">Definitions</a></h3>
  14082. <ul>
  14083. <li><strong>subject</strong>: Something we are tracking stats about – currently a room or user.</li>
  14084. <li><strong>current row</strong>: An entry for a subject in the appropriate current statistics
  14085. table. Each subject can have only one.</li>
  14086. </ul>
  14087. <h3 id="overview-4"><a class="header" href="#overview-4">Overview</a></h3>
  14088. <p>Stats correspond to the present values. Current rows contain the most up-to-date
  14089. statistics for a room. Each subject can only have one entry.</p>
  14090. <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>
  14091. <p>Synapse has a number of platform dependencies, including Python and PostgreSQL.
  14092. This document outlines the policy towards which versions we support, and when we
  14093. drop support for versions in the future.</p>
  14094. <h2 id="policy"><a class="header" href="#policy">Policy</a></h2>
  14095. <p>Synapse follows the upstream support life cycles for Python and PostgreSQL,
  14096. i.e. when a version reaches End of Life Synapse will withdraw support for that
  14097. version in future releases.</p>
  14098. <p>Details on the upstream support life cycles for Python and PostgreSQL are
  14099. documented at <a href="https://endoflife.date/python">https://endoflife.date/python</a> and
  14100. <a href="https://endoflife.date/postgresql">https://endoflife.date/postgresql</a>.</p>
  14101. <h2 id="context"><a class="header" href="#context">Context</a></h2>
  14102. <p>It is important for system admins to have a clear understanding of the platform
  14103. requirements of Synapse and its deprecation policies so that they can
  14104. effectively plan upgrading their infrastructure ahead of time. This is
  14105. especially important in contexts where upgrading the infrastructure requires
  14106. auditing and approval from a security team, or where otherwise upgrading is a
  14107. long process.</p>
  14108. <p>By following the upstream support life cycles Synapse can ensure that its
  14109. dependencies continue to get security patches, while not requiring system admins
  14110. to constantly update their platform dependencies to the latest versions.</p>
  14111. <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>
  14112. <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>
  14113. <ul>
  14114. <li><strong>Platform</strong>: 2x1GHz armhf 2GiB ram <a href="https://wiki.debian.org/CheapServerBoxHardware">Single-board computers</a>, SSD, postgres.</li>
  14115. </ul>
  14116. <h3 id="presence"><a class="header" href="#presence">Presence</a></h3>
  14117. <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>
  14118. <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>
  14119. <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>
  14120. <h3 id="joining"><a class="header" href="#joining">Joining</a></h3>
  14121. <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>
  14122. <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>
  14123. <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>
  14124. <h3 id="sessions"><a class="header" href="#sessions">Sessions</a></h3>
  14125. <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>
  14126. <h3 id="recommended-configuration"><a class="header" href="#recommended-configuration">Recommended configuration</a></h3>
  14127. <p>Put the below in a new file at /etc/matrix-synapse/conf.d/sbc.yaml to override the defaults in homeserver.yaml.</p>
  14128. <pre><code># Set to false to disable presence tracking on this homeserver.
  14129. use_presence: false
  14130. # When this is enabled, the room &quot;complexity&quot; will be checked before a user
  14131. # joins a new remote room. If it is above the complexity limit, the server will
  14132. # disallow joining, or will instantly leave.
  14133. limit_remote_rooms:
  14134. # Uncomment to enable room complexity checking.
  14135. #enabled: true
  14136. complexity: 3.0
  14137. # Database configuration
  14138. database:
  14139. name: psycopg2
  14140. args:
  14141. user: matrix-synapse
  14142. # Generate a long, secure one with a password manager
  14143. password: hunter2
  14144. database: matrix-synapse
  14145. host: localhost
  14146. cp_min: 5
  14147. cp_max: 10
  14148. </code></pre>
  14149. <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>
  14150. <pre><code>admin@homeserver:~$ zgrep '/client/r0/join/' /var/log/matrix-synapse/homeserver.log* | awk '{print $18, $25}' | sort --human-numeric-sort
  14151. 29.922sec/-0.002sec /_matrix/client/r0/join/%23debian-fasttrack%3Apoddery.com
  14152. 182.088sec/0.003sec /_matrix/client/r0/join/%23decentralizedweb-general%3Amatrix.org
  14153. 911.625sec/-570.847sec /_matrix/client/r0/join/%23synapse%3Amatrix.org
  14154. 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'
  14155. canonical_alias | joined_members | current_state_events
  14156. -------------------------------+----------------+----------------------
  14157. #_oftc_#debian:matrix.org | 871 | 52355
  14158. #matrix:matrix.org | 6379 | 10684
  14159. #irc:matrix.org | 461 | 3751
  14160. #decentralizedweb-general:matrix.org | 997 | 1509
  14161. #whatsapp:maunium.net | 554 | 854
  14162. </code></pre>
  14163. </main>
  14164. <nav class="nav-wrapper" aria-label="Page navigation">
  14165. <!-- Mobile navigation buttons -->
  14166. <div style="clear: both"></div>
  14167. </nav>
  14168. </div>
  14169. </div>
  14170. <nav class="nav-wide-wrapper" aria-label="Page navigation">
  14171. </nav>
  14172. </div>
  14173. <script type="text/javascript">
  14174. window.playground_copyable = true;
  14175. </script>
  14176. <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
  14177. <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
  14178. <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
  14179. <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
  14180. <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
  14181. <script src="book.js" type="text/javascript" charset="utf-8"></script>
  14182. <!-- Custom JS scripts -->
  14183. <script type="text/javascript" src="docs/website_files/table-of-contents.js"></script>
  14184. <script type="text/javascript" src="docs/website_files/version-picker.js"></script>
  14185. <script type="text/javascript" src="docs/website_files/version.js"></script>
  14186. <script type="text/javascript">
  14187. window.addEventListener('load', function() {
  14188. window.setTimeout(window.print, 100);
  14189. });
  14190. </script>
  14191. </body>
  14192. </html>