test_user.py 168 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733
  1. # Copyright 2018-2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import hashlib
  15. import hmac
  16. import os
  17. import urllib.parse
  18. from binascii import unhexlify
  19. from typing import List, Optional
  20. from unittest.mock import Mock, patch
  21. from parameterized import parameterized, parameterized_class
  22. from twisted.test.proto_helpers import MemoryReactor
  23. import synapse.rest.admin
  24. from synapse.api.constants import ApprovalNoticeMedium, LoginType, UserTypes
  25. from synapse.api.errors import Codes, HttpResponseException, ResourceLimitError
  26. from synapse.api.room_versions import RoomVersions
  27. from synapse.media.filepath import MediaFilePaths
  28. from synapse.rest.client import (
  29. devices,
  30. login,
  31. logout,
  32. profile,
  33. register,
  34. room,
  35. sync,
  36. user_directory,
  37. )
  38. from synapse.server import HomeServer
  39. from synapse.types import JsonDict, UserID, create_requester
  40. from synapse.util import Clock
  41. from tests import unittest
  42. from tests.server import FakeSite, make_request
  43. from tests.test_utils import SMALL_PNG, make_awaitable
  44. from tests.unittest import override_config
  45. class UserRegisterTestCase(unittest.HomeserverTestCase):
  46. servlets = [
  47. synapse.rest.admin.register_servlets_for_client_rest_resource,
  48. profile.register_servlets,
  49. ]
  50. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  51. self.url = "/_synapse/admin/v1/register"
  52. self.registration_handler = Mock()
  53. self.identity_handler = Mock()
  54. self.login_handler = Mock()
  55. self.device_handler = Mock()
  56. self.device_handler.check_device_registered = Mock(return_value="FAKE")
  57. self.datastore = Mock(return_value=Mock())
  58. self.datastore.get_current_state_deltas = Mock(return_value=(0, []))
  59. self.hs = self.setup_test_homeserver()
  60. self.hs.config.registration.registration_shared_secret = "shared"
  61. self.hs.get_media_repository = Mock() # type: ignore[assignment]
  62. self.hs.get_deactivate_account_handler = Mock() # type: ignore[assignment]
  63. return self.hs
  64. def test_disabled(self) -> None:
  65. """
  66. If there is no shared secret, registration through this method will be
  67. prevented.
  68. """
  69. self.hs.config.registration.registration_shared_secret = None
  70. channel = self.make_request("POST", self.url, b"{}")
  71. self.assertEqual(400, channel.code, msg=channel.json_body)
  72. self.assertEqual(
  73. "Shared secret registration is not enabled", channel.json_body["error"]
  74. )
  75. def test_get_nonce(self) -> None:
  76. """
  77. Calling GET on the endpoint will return a randomised nonce, using the
  78. homeserver's secrets provider.
  79. """
  80. with patch("secrets.token_hex") as token_hex:
  81. # Patch secrets.token_hex for the duration of this context
  82. token_hex.return_value = "abcd"
  83. channel = self.make_request("GET", self.url)
  84. self.assertEqual(channel.json_body, {"nonce": "abcd"})
  85. def test_expired_nonce(self) -> None:
  86. """
  87. Calling GET on the endpoint will return a randomised nonce, which will
  88. only last for SALT_TIMEOUT (60s).
  89. """
  90. channel = self.make_request("GET", self.url)
  91. nonce = channel.json_body["nonce"]
  92. # 59 seconds
  93. self.reactor.advance(59)
  94. body = {"nonce": nonce}
  95. channel = self.make_request("POST", self.url, body)
  96. self.assertEqual(400, channel.code, msg=channel.json_body)
  97. self.assertEqual("username must be specified", channel.json_body["error"])
  98. # 61 seconds
  99. self.reactor.advance(2)
  100. channel = self.make_request("POST", self.url, body)
  101. self.assertEqual(400, channel.code, msg=channel.json_body)
  102. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  103. def test_register_incorrect_nonce(self) -> None:
  104. """
  105. Only the provided nonce can be used, as it's checked in the MAC.
  106. """
  107. channel = self.make_request("GET", self.url)
  108. nonce = channel.json_body["nonce"]
  109. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  110. want_mac.update(b"notthenonce\x00bob\x00abc123\x00admin")
  111. want_mac_str = want_mac.hexdigest()
  112. body = {
  113. "nonce": nonce,
  114. "username": "bob",
  115. "password": "abc123",
  116. "admin": True,
  117. "mac": want_mac_str,
  118. }
  119. channel = self.make_request("POST", self.url, body)
  120. self.assertEqual(403, channel.code, msg=channel.json_body)
  121. self.assertEqual("HMAC incorrect", channel.json_body["error"])
  122. def test_register_correct_nonce(self) -> None:
  123. """
  124. When the correct nonce is provided, and the right key is provided, the
  125. user is registered.
  126. """
  127. channel = self.make_request("GET", self.url)
  128. nonce = channel.json_body["nonce"]
  129. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  130. want_mac.update(
  131. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  132. )
  133. want_mac_str = want_mac.hexdigest()
  134. body = {
  135. "nonce": nonce,
  136. "username": "bob",
  137. "password": "abc123",
  138. "admin": True,
  139. "user_type": UserTypes.SUPPORT,
  140. "mac": want_mac_str,
  141. }
  142. channel = self.make_request("POST", self.url, body)
  143. self.assertEqual(200, channel.code, msg=channel.json_body)
  144. self.assertEqual("@bob:test", channel.json_body["user_id"])
  145. def test_nonce_reuse(self) -> None:
  146. """
  147. A valid unrecognised nonce.
  148. """
  149. channel = self.make_request("GET", self.url)
  150. nonce = channel.json_body["nonce"]
  151. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  152. want_mac.update(nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin")
  153. want_mac_str = want_mac.hexdigest()
  154. body = {
  155. "nonce": nonce,
  156. "username": "bob",
  157. "password": "abc123",
  158. "admin": True,
  159. "mac": want_mac_str,
  160. }
  161. channel = self.make_request("POST", self.url, body)
  162. self.assertEqual(200, channel.code, msg=channel.json_body)
  163. self.assertEqual("@bob:test", channel.json_body["user_id"])
  164. # Now, try and reuse it
  165. channel = self.make_request("POST", self.url, body)
  166. self.assertEqual(400, channel.code, msg=channel.json_body)
  167. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  168. def test_missing_parts(self) -> None:
  169. """
  170. Synapse will complain if you don't give nonce, username, password, and
  171. mac. Admin and user_types are optional. Additional checks are done for length
  172. and type.
  173. """
  174. def nonce() -> str:
  175. channel = self.make_request("GET", self.url)
  176. return channel.json_body["nonce"]
  177. #
  178. # Nonce check
  179. #
  180. # Must be an empty body present
  181. channel = self.make_request("POST", self.url, {})
  182. self.assertEqual(400, channel.code, msg=channel.json_body)
  183. self.assertEqual("nonce must be specified", channel.json_body["error"])
  184. #
  185. # Username checks
  186. #
  187. # Must be present
  188. channel = self.make_request("POST", self.url, {"nonce": nonce()})
  189. self.assertEqual(400, channel.code, msg=channel.json_body)
  190. self.assertEqual("username must be specified", channel.json_body["error"])
  191. # Must be a string
  192. body = {"nonce": nonce(), "username": 1234}
  193. channel = self.make_request("POST", self.url, body)
  194. self.assertEqual(400, channel.code, msg=channel.json_body)
  195. self.assertEqual("Invalid username", channel.json_body["error"])
  196. # Must not have null bytes
  197. body = {"nonce": nonce(), "username": "abcd\u0000"}
  198. channel = self.make_request("POST", self.url, body)
  199. self.assertEqual(400, channel.code, msg=channel.json_body)
  200. self.assertEqual("Invalid username", channel.json_body["error"])
  201. # Must not have null bytes
  202. body = {"nonce": nonce(), "username": "a" * 1000}
  203. channel = self.make_request("POST", self.url, body)
  204. self.assertEqual(400, channel.code, msg=channel.json_body)
  205. self.assertEqual("Invalid username", channel.json_body["error"])
  206. #
  207. # Password checks
  208. #
  209. # Must be present
  210. body = {"nonce": nonce(), "username": "a"}
  211. channel = self.make_request("POST", self.url, body)
  212. self.assertEqual(400, channel.code, msg=channel.json_body)
  213. self.assertEqual("password must be specified", channel.json_body["error"])
  214. # Must be a string
  215. body = {"nonce": nonce(), "username": "a", "password": 1234}
  216. channel = self.make_request("POST", self.url, body)
  217. self.assertEqual(400, channel.code, msg=channel.json_body)
  218. self.assertEqual("Invalid password", channel.json_body["error"])
  219. # Must not have null bytes
  220. body = {"nonce": nonce(), "username": "a", "password": "abcd\u0000"}
  221. channel = self.make_request("POST", self.url, body)
  222. self.assertEqual(400, channel.code, msg=channel.json_body)
  223. self.assertEqual("Invalid password", channel.json_body["error"])
  224. # Super long
  225. body = {"nonce": nonce(), "username": "a", "password": "A" * 1000}
  226. channel = self.make_request("POST", self.url, body)
  227. self.assertEqual(400, channel.code, msg=channel.json_body)
  228. self.assertEqual("Invalid password", channel.json_body["error"])
  229. #
  230. # user_type check
  231. #
  232. # Invalid user_type
  233. body = {
  234. "nonce": nonce(),
  235. "username": "a",
  236. "password": "1234",
  237. "user_type": "invalid",
  238. }
  239. channel = self.make_request("POST", self.url, body)
  240. self.assertEqual(400, channel.code, msg=channel.json_body)
  241. self.assertEqual("Invalid user type", channel.json_body["error"])
  242. def test_displayname(self) -> None:
  243. """
  244. Test that displayname of new user is set
  245. """
  246. # set no displayname
  247. channel = self.make_request("GET", self.url)
  248. nonce = channel.json_body["nonce"]
  249. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  250. want_mac.update(nonce.encode("ascii") + b"\x00bob1\x00abc123\x00notadmin")
  251. want_mac_str = want_mac.hexdigest()
  252. body = {
  253. "nonce": nonce,
  254. "username": "bob1",
  255. "password": "abc123",
  256. "mac": want_mac_str,
  257. }
  258. channel = self.make_request("POST", self.url, body)
  259. self.assertEqual(200, channel.code, msg=channel.json_body)
  260. self.assertEqual("@bob1:test", channel.json_body["user_id"])
  261. channel = self.make_request("GET", "/profile/@bob1:test/displayname")
  262. self.assertEqual(200, channel.code, msg=channel.json_body)
  263. self.assertEqual("bob1", channel.json_body["displayname"])
  264. # displayname is None
  265. channel = self.make_request("GET", self.url)
  266. nonce = channel.json_body["nonce"]
  267. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  268. want_mac.update(nonce.encode("ascii") + b"\x00bob2\x00abc123\x00notadmin")
  269. want_mac_str = want_mac.hexdigest()
  270. body = {
  271. "nonce": nonce,
  272. "username": "bob2",
  273. "displayname": None,
  274. "password": "abc123",
  275. "mac": want_mac_str,
  276. }
  277. channel = self.make_request("POST", self.url, body)
  278. self.assertEqual(200, channel.code, msg=channel.json_body)
  279. self.assertEqual("@bob2:test", channel.json_body["user_id"])
  280. channel = self.make_request("GET", "/profile/@bob2:test/displayname")
  281. self.assertEqual(200, channel.code, msg=channel.json_body)
  282. self.assertEqual("bob2", channel.json_body["displayname"])
  283. # displayname is empty
  284. channel = self.make_request("GET", self.url)
  285. nonce = channel.json_body["nonce"]
  286. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  287. want_mac.update(nonce.encode("ascii") + b"\x00bob3\x00abc123\x00notadmin")
  288. want_mac_str = want_mac.hexdigest()
  289. body = {
  290. "nonce": nonce,
  291. "username": "bob3",
  292. "displayname": "",
  293. "password": "abc123",
  294. "mac": want_mac_str,
  295. }
  296. channel = self.make_request("POST", self.url, body)
  297. self.assertEqual(200, channel.code, msg=channel.json_body)
  298. self.assertEqual("@bob3:test", channel.json_body["user_id"])
  299. channel = self.make_request("GET", "/profile/@bob3:test/displayname")
  300. self.assertEqual(404, channel.code, msg=channel.json_body)
  301. # set displayname
  302. channel = self.make_request("GET", self.url)
  303. nonce = channel.json_body["nonce"]
  304. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  305. want_mac.update(nonce.encode("ascii") + b"\x00bob4\x00abc123\x00notadmin")
  306. want_mac_str = want_mac.hexdigest()
  307. body = {
  308. "nonce": nonce,
  309. "username": "bob4",
  310. "displayname": "Bob's Name",
  311. "password": "abc123",
  312. "mac": want_mac_str,
  313. }
  314. channel = self.make_request("POST", self.url, body)
  315. self.assertEqual(200, channel.code, msg=channel.json_body)
  316. self.assertEqual("@bob4:test", channel.json_body["user_id"])
  317. channel = self.make_request("GET", "/profile/@bob4:test/displayname")
  318. self.assertEqual(200, channel.code, msg=channel.json_body)
  319. self.assertEqual("Bob's Name", channel.json_body["displayname"])
  320. @override_config(
  321. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  322. )
  323. def test_register_mau_limit_reached(self) -> None:
  324. """
  325. Check we can register a user via the shared secret registration API
  326. even if the MAU limit is reached.
  327. """
  328. handler = self.hs.get_registration_handler()
  329. store = self.hs.get_datastores().main
  330. # Set monthly active users to the limit
  331. store.get_monthly_active_count = Mock(
  332. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  333. )
  334. # Check that the blocking of monthly active users is working as expected
  335. # The registration of a new user fails due to the limit
  336. self.get_failure(
  337. handler.register_user(localpart="local_part"), ResourceLimitError
  338. )
  339. # Register new user with admin API
  340. channel = self.make_request("GET", self.url)
  341. nonce = channel.json_body["nonce"]
  342. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  343. want_mac.update(
  344. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  345. )
  346. want_mac_str = want_mac.hexdigest()
  347. body = {
  348. "nonce": nonce,
  349. "username": "bob",
  350. "password": "abc123",
  351. "admin": True,
  352. "user_type": UserTypes.SUPPORT,
  353. "mac": want_mac_str,
  354. }
  355. channel = self.make_request("POST", self.url, body)
  356. self.assertEqual(200, channel.code, msg=channel.json_body)
  357. self.assertEqual("@bob:test", channel.json_body["user_id"])
  358. class UsersListTestCase(unittest.HomeserverTestCase):
  359. servlets = [
  360. synapse.rest.admin.register_servlets,
  361. login.register_servlets,
  362. ]
  363. url = "/_synapse/admin/v2/users"
  364. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  365. self.store = hs.get_datastores().main
  366. self.admin_user = self.register_user("admin", "pass", admin=True)
  367. self.admin_user_tok = self.login("admin", "pass")
  368. def test_no_auth(self) -> None:
  369. """
  370. Try to list users without authentication.
  371. """
  372. channel = self.make_request("GET", self.url, b"{}")
  373. self.assertEqual(401, channel.code, msg=channel.json_body)
  374. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  375. def test_requester_is_no_admin(self) -> None:
  376. """
  377. If the user is not a server admin, an error is returned.
  378. """
  379. self._create_users(1)
  380. other_user_token = self.login("user1", "pass1")
  381. channel = self.make_request("GET", self.url, access_token=other_user_token)
  382. self.assertEqual(403, channel.code, msg=channel.json_body)
  383. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  384. def test_all_users(self) -> None:
  385. """
  386. List all users, including deactivated users.
  387. """
  388. self._create_users(2)
  389. channel = self.make_request(
  390. "GET",
  391. self.url + "?deactivated=true",
  392. {},
  393. access_token=self.admin_user_tok,
  394. )
  395. self.assertEqual(200, channel.code, msg=channel.json_body)
  396. self.assertEqual(3, len(channel.json_body["users"]))
  397. self.assertEqual(3, channel.json_body["total"])
  398. # Check that all fields are available
  399. self._check_fields(channel.json_body["users"])
  400. def test_search_term(self) -> None:
  401. """Test that searching for a users works correctly"""
  402. def _search_test(
  403. expected_user_id: Optional[str],
  404. search_term: str,
  405. search_field: Optional[str] = "name",
  406. expected_http_code: Optional[int] = 200,
  407. ) -> None:
  408. """Search for a user and check that the returned user's id is a match
  409. Args:
  410. expected_user_id: The user_id expected to be returned by the API. Set
  411. to None to expect zero results for the search
  412. search_term: The term to search for user names with
  413. search_field: Field which is to request: `name` or `user_id`
  414. expected_http_code: The expected http code for the request
  415. """
  416. url = self.url + "?%s=%s" % (
  417. search_field,
  418. search_term,
  419. )
  420. channel = self.make_request(
  421. "GET",
  422. url,
  423. access_token=self.admin_user_tok,
  424. )
  425. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  426. if expected_http_code != 200:
  427. return
  428. # Check that users were returned
  429. self.assertTrue("users" in channel.json_body)
  430. self._check_fields(channel.json_body["users"])
  431. users = channel.json_body["users"]
  432. # Check that the expected number of users were returned
  433. expected_user_count = 1 if expected_user_id else 0
  434. self.assertEqual(len(users), expected_user_count)
  435. self.assertEqual(channel.json_body["total"], expected_user_count)
  436. if expected_user_id:
  437. # Check that the first returned user id is correct
  438. u = users[0]
  439. self.assertEqual(expected_user_id, u["name"])
  440. self._create_users(2)
  441. user1 = "@user1:test"
  442. user2 = "@user2:test"
  443. # Perform search tests
  444. _search_test(user1, "er1")
  445. _search_test(user1, "me 1")
  446. _search_test(user2, "er2")
  447. _search_test(user2, "me 2")
  448. _search_test(user1, "er1", "user_id")
  449. _search_test(user2, "er2", "user_id")
  450. # Test case insensitive
  451. _search_test(user1, "ER1")
  452. _search_test(user1, "NAME 1")
  453. _search_test(user2, "ER2")
  454. _search_test(user2, "NAME 2")
  455. _search_test(user1, "ER1", "user_id")
  456. _search_test(user2, "ER2", "user_id")
  457. _search_test(None, "foo")
  458. _search_test(None, "bar")
  459. _search_test(None, "foo", "user_id")
  460. _search_test(None, "bar", "user_id")
  461. @override_config(
  462. {
  463. "experimental_features": {
  464. "msc3866": {
  465. "enabled": True,
  466. "require_approval_for_new_accounts": True,
  467. }
  468. }
  469. }
  470. )
  471. def test_invalid_parameter(self) -> None:
  472. """
  473. If parameters are invalid, an error is returned.
  474. """
  475. # negative limit
  476. channel = self.make_request(
  477. "GET",
  478. self.url + "?limit=-5",
  479. access_token=self.admin_user_tok,
  480. )
  481. self.assertEqual(400, channel.code, msg=channel.json_body)
  482. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  483. # negative from
  484. channel = self.make_request(
  485. "GET",
  486. self.url + "?from=-5",
  487. access_token=self.admin_user_tok,
  488. )
  489. self.assertEqual(400, channel.code, msg=channel.json_body)
  490. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  491. # invalid guests
  492. channel = self.make_request(
  493. "GET",
  494. self.url + "?guests=not_bool",
  495. access_token=self.admin_user_tok,
  496. )
  497. self.assertEqual(400, channel.code, msg=channel.json_body)
  498. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  499. # invalid deactivated
  500. channel = self.make_request(
  501. "GET",
  502. self.url + "?deactivated=not_bool",
  503. access_token=self.admin_user_tok,
  504. )
  505. self.assertEqual(400, channel.code, msg=channel.json_body)
  506. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  507. # invalid approved
  508. channel = self.make_request(
  509. "GET",
  510. self.url + "?approved=not_bool",
  511. access_token=self.admin_user_tok,
  512. )
  513. self.assertEqual(400, channel.code, msg=channel.json_body)
  514. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  515. # unkown order_by
  516. channel = self.make_request(
  517. "GET",
  518. self.url + "?order_by=bar",
  519. access_token=self.admin_user_tok,
  520. )
  521. self.assertEqual(400, channel.code, msg=channel.json_body)
  522. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  523. # invalid search order
  524. channel = self.make_request(
  525. "GET",
  526. self.url + "?dir=bar",
  527. access_token=self.admin_user_tok,
  528. )
  529. self.assertEqual(400, channel.code, msg=channel.json_body)
  530. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  531. def test_limit(self) -> None:
  532. """
  533. Testing list of users with limit
  534. """
  535. number_users = 20
  536. # Create one less user (since there's already an admin user).
  537. self._create_users(number_users - 1)
  538. channel = self.make_request(
  539. "GET",
  540. self.url + "?limit=5",
  541. access_token=self.admin_user_tok,
  542. )
  543. self.assertEqual(200, channel.code, msg=channel.json_body)
  544. self.assertEqual(channel.json_body["total"], number_users)
  545. self.assertEqual(len(channel.json_body["users"]), 5)
  546. self.assertEqual(channel.json_body["next_token"], "5")
  547. self._check_fields(channel.json_body["users"])
  548. def test_from(self) -> None:
  549. """
  550. Testing list of users with a defined starting point (from)
  551. """
  552. number_users = 20
  553. # Create one less user (since there's already an admin user).
  554. self._create_users(number_users - 1)
  555. channel = self.make_request(
  556. "GET",
  557. self.url + "?from=5",
  558. access_token=self.admin_user_tok,
  559. )
  560. self.assertEqual(200, channel.code, msg=channel.json_body)
  561. self.assertEqual(channel.json_body["total"], number_users)
  562. self.assertEqual(len(channel.json_body["users"]), 15)
  563. self.assertNotIn("next_token", channel.json_body)
  564. self._check_fields(channel.json_body["users"])
  565. def test_limit_and_from(self) -> None:
  566. """
  567. Testing list of users with a defined starting point and limit
  568. """
  569. number_users = 20
  570. # Create one less user (since there's already an admin user).
  571. self._create_users(number_users - 1)
  572. channel = self.make_request(
  573. "GET",
  574. self.url + "?from=5&limit=10",
  575. access_token=self.admin_user_tok,
  576. )
  577. self.assertEqual(200, channel.code, msg=channel.json_body)
  578. self.assertEqual(channel.json_body["total"], number_users)
  579. self.assertEqual(channel.json_body["next_token"], "15")
  580. self.assertEqual(len(channel.json_body["users"]), 10)
  581. self._check_fields(channel.json_body["users"])
  582. def test_next_token(self) -> None:
  583. """
  584. Testing that `next_token` appears at the right place
  585. """
  586. number_users = 20
  587. # Create one less user (since there's already an admin user).
  588. self._create_users(number_users - 1)
  589. # `next_token` does not appear
  590. # Number of results is the number of entries
  591. channel = self.make_request(
  592. "GET",
  593. self.url + "?limit=20",
  594. access_token=self.admin_user_tok,
  595. )
  596. self.assertEqual(200, channel.code, msg=channel.json_body)
  597. self.assertEqual(channel.json_body["total"], number_users)
  598. self.assertEqual(len(channel.json_body["users"]), number_users)
  599. self.assertNotIn("next_token", channel.json_body)
  600. # `next_token` does not appear
  601. # Number of max results is larger than the number of entries
  602. channel = self.make_request(
  603. "GET",
  604. self.url + "?limit=21",
  605. access_token=self.admin_user_tok,
  606. )
  607. self.assertEqual(200, channel.code, msg=channel.json_body)
  608. self.assertEqual(channel.json_body["total"], number_users)
  609. self.assertEqual(len(channel.json_body["users"]), number_users)
  610. self.assertNotIn("next_token", channel.json_body)
  611. # `next_token` does appear
  612. # Number of max results is smaller than the number of entries
  613. channel = self.make_request(
  614. "GET",
  615. self.url + "?limit=19",
  616. access_token=self.admin_user_tok,
  617. )
  618. self.assertEqual(200, channel.code, msg=channel.json_body)
  619. self.assertEqual(channel.json_body["total"], number_users)
  620. self.assertEqual(len(channel.json_body["users"]), 19)
  621. self.assertEqual(channel.json_body["next_token"], "19")
  622. # Check
  623. # Set `from` to value of `next_token` for request remaining entries
  624. # `next_token` does not appear
  625. channel = self.make_request(
  626. "GET",
  627. self.url + "?from=19",
  628. access_token=self.admin_user_tok,
  629. )
  630. self.assertEqual(200, channel.code, msg=channel.json_body)
  631. self.assertEqual(channel.json_body["total"], number_users)
  632. self.assertEqual(len(channel.json_body["users"]), 1)
  633. self.assertNotIn("next_token", channel.json_body)
  634. def test_order_by(self) -> None:
  635. """
  636. Testing order list with parameter `order_by`
  637. """
  638. # make sure that the users do not have the same timestamps
  639. self.reactor.advance(10)
  640. user1 = self.register_user("user1", "pass1", admin=False, displayname="Name Z")
  641. self.reactor.advance(10)
  642. user2 = self.register_user("user2", "pass2", admin=False, displayname="Name Y")
  643. # Modify user
  644. self.get_success(self.store.set_user_deactivated_status(user1, True))
  645. self.get_success(self.store.set_shadow_banned(UserID.from_string(user1), True))
  646. # Set avatar URL to all users, that no user has a NULL value to avoid
  647. # different sort order between SQlite and PostreSQL
  648. self.get_success(
  649. self.store.set_profile_avatar_url(
  650. UserID.from_string("@user1:test"), "mxc://url3"
  651. )
  652. )
  653. self.get_success(
  654. self.store.set_profile_avatar_url(
  655. UserID.from_string("@user2:test"), "mxc://url2"
  656. )
  657. )
  658. self.get_success(
  659. self.store.set_profile_avatar_url(
  660. UserID.from_string("@admin:test"), "mxc://url1"
  661. )
  662. )
  663. # order by default (name)
  664. self._order_test([self.admin_user, user1, user2], None)
  665. self._order_test([self.admin_user, user1, user2], None, "f")
  666. self._order_test([user2, user1, self.admin_user], None, "b")
  667. # order by name
  668. self._order_test([self.admin_user, user1, user2], "name")
  669. self._order_test([self.admin_user, user1, user2], "name", "f")
  670. self._order_test([user2, user1, self.admin_user], "name", "b")
  671. # order by displayname
  672. self._order_test([user2, user1, self.admin_user], "displayname")
  673. self._order_test([user2, user1, self.admin_user], "displayname", "f")
  674. self._order_test([self.admin_user, user1, user2], "displayname", "b")
  675. # order by is_guest
  676. # like sort by ascending name, as no guest user here
  677. self._order_test([self.admin_user, user1, user2], "is_guest")
  678. self._order_test([self.admin_user, user1, user2], "is_guest", "f")
  679. self._order_test([self.admin_user, user1, user2], "is_guest", "b")
  680. # order by admin
  681. self._order_test([user1, user2, self.admin_user], "admin")
  682. self._order_test([user1, user2, self.admin_user], "admin", "f")
  683. self._order_test([self.admin_user, user1, user2], "admin", "b")
  684. # order by deactivated
  685. self._order_test([self.admin_user, user2, user1], "deactivated")
  686. self._order_test([self.admin_user, user2, user1], "deactivated", "f")
  687. self._order_test([user1, self.admin_user, user2], "deactivated", "b")
  688. # order by user_type
  689. # like sort by ascending name, as no special user type here
  690. self._order_test([self.admin_user, user1, user2], "user_type")
  691. self._order_test([self.admin_user, user1, user2], "user_type", "f")
  692. self._order_test([self.admin_user, user1, user2], "is_guest", "b")
  693. # order by shadow_banned
  694. self._order_test([self.admin_user, user2, user1], "shadow_banned")
  695. self._order_test([self.admin_user, user2, user1], "shadow_banned", "f")
  696. self._order_test([user1, self.admin_user, user2], "shadow_banned", "b")
  697. # order by avatar_url
  698. self._order_test([self.admin_user, user2, user1], "avatar_url")
  699. self._order_test([self.admin_user, user2, user1], "avatar_url", "f")
  700. self._order_test([user1, user2, self.admin_user], "avatar_url", "b")
  701. # order by creation_ts
  702. self._order_test([self.admin_user, user1, user2], "creation_ts")
  703. self._order_test([self.admin_user, user1, user2], "creation_ts", "f")
  704. self._order_test([user2, user1, self.admin_user], "creation_ts", "b")
  705. @override_config(
  706. {
  707. "experimental_features": {
  708. "msc3866": {
  709. "enabled": True,
  710. "require_approval_for_new_accounts": True,
  711. }
  712. }
  713. }
  714. )
  715. def test_filter_out_approved(self) -> None:
  716. """Tests that the endpoint can filter out approved users."""
  717. # Create our users.
  718. self._create_users(2)
  719. # Get the list of users.
  720. channel = self.make_request(
  721. "GET",
  722. self.url,
  723. access_token=self.admin_user_tok,
  724. )
  725. self.assertEqual(200, channel.code, channel.result)
  726. # Exclude the admin, because we don't want to accidentally un-approve the admin.
  727. non_admin_user_ids = [
  728. user["name"]
  729. for user in channel.json_body["users"]
  730. if user["name"] != self.admin_user
  731. ]
  732. self.assertEqual(2, len(non_admin_user_ids), non_admin_user_ids)
  733. # Select a user and un-approve them. We do this rather than the other way around
  734. # because, since these users are created by an admin, we consider them already
  735. # approved.
  736. not_approved_user = non_admin_user_ids[0]
  737. channel = self.make_request(
  738. "PUT",
  739. f"/_synapse/admin/v2/users/{not_approved_user}",
  740. {"approved": False},
  741. access_token=self.admin_user_tok,
  742. )
  743. self.assertEqual(200, channel.code, channel.result)
  744. # Now get the list of users again, this time filtering out approved users.
  745. channel = self.make_request(
  746. "GET",
  747. self.url + "?approved=false",
  748. access_token=self.admin_user_tok,
  749. )
  750. self.assertEqual(200, channel.code, channel.result)
  751. non_admin_user_ids = [
  752. user["name"]
  753. for user in channel.json_body["users"]
  754. if user["name"] != self.admin_user
  755. ]
  756. # We should only have our unapproved user now.
  757. self.assertEqual(1, len(non_admin_user_ids), non_admin_user_ids)
  758. self.assertEqual(not_approved_user, non_admin_user_ids[0])
  759. def test_filter_not_user_types(self) -> None:
  760. """Tests that the endpoint handles the not_user_types param"""
  761. regular_user_id = self.register_user("normalo", "secret")
  762. bot_user_id = self.register_user("robo", "secret")
  763. self.make_request(
  764. "PUT",
  765. "/_synapse/admin/v2/users/" + urllib.parse.quote(bot_user_id),
  766. {"user_type": UserTypes.BOT},
  767. access_token=self.admin_user_tok,
  768. )
  769. support_user_id = self.register_user("foo", "secret")
  770. self.make_request(
  771. "PUT",
  772. "/_synapse/admin/v2/users/" + urllib.parse.quote(support_user_id),
  773. {"user_type": UserTypes.SUPPORT},
  774. access_token=self.admin_user_tok,
  775. )
  776. def test_user_type(
  777. expected_user_ids: List[str], not_user_types: Optional[List[str]] = None
  778. ) -> None:
  779. """Runs a test for the not_user_types param
  780. Args:
  781. expected_user_ids: Ids of the users that are expected to be returned
  782. not_user_types: List of values for the not_user_types param
  783. """
  784. user_type_query = ""
  785. if not_user_types is not None:
  786. user_type_query = "&".join(
  787. [f"not_user_type={u}" for u in not_user_types]
  788. )
  789. test_url = f"{self.url}?{user_type_query}"
  790. channel = self.make_request(
  791. "GET",
  792. test_url,
  793. access_token=self.admin_user_tok,
  794. )
  795. self.assertEqual(200, channel.code)
  796. self.assertEqual(channel.json_body["total"], len(expected_user_ids))
  797. self.assertEqual(
  798. expected_user_ids,
  799. [u["name"] for u in channel.json_body["users"]],
  800. )
  801. # Request without user_types → all users expected
  802. test_user_type([self.admin_user, support_user_id, regular_user_id, bot_user_id])
  803. # Request and exclude bot users
  804. test_user_type(
  805. [self.admin_user, support_user_id, regular_user_id],
  806. not_user_types=[UserTypes.BOT],
  807. )
  808. # Request and exclude bot and support users
  809. test_user_type(
  810. [self.admin_user, regular_user_id],
  811. not_user_types=[UserTypes.BOT, UserTypes.SUPPORT],
  812. )
  813. # Request and exclude empty user types → only expected the bot and support user
  814. test_user_type([support_user_id, bot_user_id], not_user_types=[""])
  815. # Request and exclude empty user types and bots → only expected the support user
  816. test_user_type([support_user_id], not_user_types=["", UserTypes.BOT])
  817. # Request and exclude a custom type (neither service nor bot) → expect all users
  818. test_user_type(
  819. [self.admin_user, support_user_id, regular_user_id, bot_user_id],
  820. not_user_types=["custom"],
  821. )
  822. def test_erasure_status(self) -> None:
  823. # Create a new user.
  824. user_id = self.register_user("eraseme", "eraseme")
  825. # They should appear in the list users API, marked as not erased.
  826. channel = self.make_request(
  827. "GET",
  828. self.url + "?deactivated=true",
  829. access_token=self.admin_user_tok,
  830. )
  831. users = {user["name"]: user for user in channel.json_body["users"]}
  832. self.assertIs(users[user_id]["erased"], False)
  833. # Deactivate that user, requesting erasure.
  834. deactivate_account_handler = self.hs.get_deactivate_account_handler()
  835. self.get_success(
  836. deactivate_account_handler.deactivate_account(
  837. user_id, erase_data=True, requester=create_requester(user_id)
  838. )
  839. )
  840. # Repeat the list users query. They should now be marked as erased.
  841. channel = self.make_request(
  842. "GET",
  843. self.url + "?deactivated=true",
  844. access_token=self.admin_user_tok,
  845. )
  846. users = {user["name"]: user for user in channel.json_body["users"]}
  847. self.assertIs(users[user_id]["erased"], True)
  848. def _order_test(
  849. self,
  850. expected_user_list: List[str],
  851. order_by: Optional[str],
  852. dir: Optional[str] = None,
  853. ) -> None:
  854. """Request the list of users in a certain order. Assert that order is what
  855. we expect
  856. Args:
  857. expected_user_list: The list of user_id in the order we expect to get
  858. back from the server
  859. order_by: The type of ordering to give the server
  860. dir: The direction of ordering to give the server
  861. """
  862. url = self.url + "?deactivated=true&"
  863. if order_by is not None:
  864. url += "order_by=%s&" % (order_by,)
  865. if dir is not None and dir in ("b", "f"):
  866. url += "dir=%s" % (dir,)
  867. channel = self.make_request(
  868. "GET",
  869. url,
  870. access_token=self.admin_user_tok,
  871. )
  872. self.assertEqual(200, channel.code, msg=channel.json_body)
  873. self.assertEqual(channel.json_body["total"], len(expected_user_list))
  874. returned_order = [row["name"] for row in channel.json_body["users"]]
  875. self.assertEqual(expected_user_list, returned_order)
  876. self._check_fields(channel.json_body["users"])
  877. def _check_fields(self, content: List[JsonDict]) -> None:
  878. """Checks that the expected user attributes are present in content
  879. Args:
  880. content: List that is checked for content
  881. """
  882. for u in content:
  883. self.assertIn("name", u)
  884. self.assertIn("is_guest", u)
  885. self.assertIn("admin", u)
  886. self.assertIn("user_type", u)
  887. self.assertIn("deactivated", u)
  888. self.assertIn("shadow_banned", u)
  889. self.assertIn("displayname", u)
  890. self.assertIn("avatar_url", u)
  891. self.assertIn("creation_ts", u)
  892. def _create_users(self, number_users: int) -> None:
  893. """
  894. Create a number of users
  895. Args:
  896. number_users: Number of users to be created
  897. """
  898. for i in range(1, number_users + 1):
  899. self.register_user(
  900. "user%d" % i,
  901. "pass%d" % i,
  902. admin=False,
  903. displayname="Name %d" % i,
  904. )
  905. class UserDevicesTestCase(unittest.HomeserverTestCase):
  906. """
  907. Tests user device management-related Admin APIs.
  908. """
  909. servlets = [
  910. synapse.rest.admin.register_servlets,
  911. login.register_servlets,
  912. sync.register_servlets,
  913. ]
  914. def prepare(
  915. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  916. ) -> None:
  917. # Set up an Admin user to query the Admin API with.
  918. self.admin_user_id = self.register_user("admin", "pass", admin=True)
  919. self.admin_user_token = self.login("admin", "pass")
  920. # Set up a test user to query the devices of.
  921. self.other_user_device_id = "TESTDEVICEID"
  922. self.other_user_device_display_name = "My Test Device"
  923. self.other_user_client_ip = "1.2.3.4"
  924. self.other_user_user_agent = "EquestriaTechnology/123.0"
  925. self.other_user_id = self.register_user("user", "pass", displayname="User1")
  926. self.other_user_token = self.login(
  927. "user",
  928. "pass",
  929. device_id=self.other_user_device_id,
  930. additional_request_fields={
  931. "initial_device_display_name": self.other_user_device_display_name,
  932. },
  933. )
  934. # Have the "other user" make a request so that the "last_seen_*" fields are
  935. # populated in the tests below.
  936. channel = self.make_request(
  937. "GET",
  938. "/_matrix/client/v3/sync",
  939. access_token=self.other_user_token,
  940. client_ip=self.other_user_client_ip,
  941. custom_headers=[
  942. ("User-Agent", self.other_user_user_agent),
  943. ],
  944. )
  945. self.assertEqual(200, channel.code, msg=channel.json_body)
  946. def test_list_user_devices(self) -> None:
  947. """
  948. Tests that a user's devices and attributes are listed correctly via the Admin API.
  949. """
  950. # Request all devices of "other user"
  951. channel = self.make_request(
  952. "GET",
  953. f"/_synapse/admin/v2/users/{self.other_user_id}/devices",
  954. access_token=self.admin_user_token,
  955. )
  956. self.assertEqual(200, channel.code, msg=channel.json_body)
  957. # Double-check we got the single device expected
  958. user_devices = channel.json_body["devices"]
  959. self.assertEqual(len(user_devices), 1)
  960. self.assertEqual(channel.json_body["total"], 1)
  961. # Check that all the attributes of the device reported are as expected.
  962. self._validate_attributes_of_device_response(user_devices[0])
  963. # Request just a single device for "other user" by its ID
  964. channel = self.make_request(
  965. "GET",
  966. f"/_synapse/admin/v2/users/{self.other_user_id}/devices/"
  967. f"{self.other_user_device_id}",
  968. access_token=self.admin_user_token,
  969. )
  970. self.assertEqual(200, channel.code, msg=channel.json_body)
  971. # Check that all the attributes of the device reported are as expected.
  972. self._validate_attributes_of_device_response(channel.json_body)
  973. def _validate_attributes_of_device_response(self, response: JsonDict) -> None:
  974. # Check that all device expected attributes are present
  975. self.assertEqual(response["user_id"], self.other_user_id)
  976. self.assertEqual(response["device_id"], self.other_user_device_id)
  977. self.assertEqual(response["display_name"], self.other_user_device_display_name)
  978. self.assertEqual(response["last_seen_ip"], self.other_user_client_ip)
  979. self.assertEqual(response["last_seen_user_agent"], self.other_user_user_agent)
  980. self.assertIsInstance(response["last_seen_ts"], int)
  981. self.assertGreater(response["last_seen_ts"], 0)
  982. class DeactivateAccountTestCase(unittest.HomeserverTestCase):
  983. servlets = [
  984. synapse.rest.admin.register_servlets,
  985. login.register_servlets,
  986. ]
  987. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  988. self.store = hs.get_datastores().main
  989. self.admin_user = self.register_user("admin", "pass", admin=True)
  990. self.admin_user_tok = self.login("admin", "pass")
  991. self.other_user = self.register_user("user", "pass", displayname="User1")
  992. self.other_user_token = self.login("user", "pass")
  993. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  994. self.other_user
  995. )
  996. self.url = "/_synapse/admin/v1/deactivate/%s" % urllib.parse.quote(
  997. self.other_user
  998. )
  999. # set attributes for user
  1000. self.get_success(
  1001. self.store.set_profile_avatar_url(
  1002. UserID.from_string("@user:test"), "mxc://servername/mediaid"
  1003. )
  1004. )
  1005. self.get_success(
  1006. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  1007. )
  1008. def test_no_auth(self) -> None:
  1009. """
  1010. Try to deactivate users without authentication.
  1011. """
  1012. channel = self.make_request("POST", self.url, b"{}")
  1013. self.assertEqual(401, channel.code, msg=channel.json_body)
  1014. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1015. def test_requester_is_not_admin(self) -> None:
  1016. """
  1017. If the user is not a server admin, an error is returned.
  1018. """
  1019. url = "/_synapse/admin/v1/deactivate/@bob:test"
  1020. channel = self.make_request("POST", url, access_token=self.other_user_token)
  1021. self.assertEqual(403, channel.code, msg=channel.json_body)
  1022. self.assertEqual("You are not a server admin", channel.json_body["error"])
  1023. channel = self.make_request(
  1024. "POST",
  1025. url,
  1026. access_token=self.other_user_token,
  1027. content=b"{}",
  1028. )
  1029. self.assertEqual(403, channel.code, msg=channel.json_body)
  1030. self.assertEqual("You are not a server admin", channel.json_body["error"])
  1031. def test_user_does_not_exist(self) -> None:
  1032. """
  1033. Tests that deactivation for a user that does not exist returns a 404
  1034. """
  1035. channel = self.make_request(
  1036. "POST",
  1037. "/_synapse/admin/v1/deactivate/@unknown_person:test",
  1038. access_token=self.admin_user_tok,
  1039. )
  1040. self.assertEqual(404, channel.code, msg=channel.json_body)
  1041. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1042. def test_erase_is_not_bool(self) -> None:
  1043. """
  1044. If parameter `erase` is not boolean, return an error
  1045. """
  1046. channel = self.make_request(
  1047. "POST",
  1048. self.url,
  1049. content={"erase": "False"},
  1050. access_token=self.admin_user_tok,
  1051. )
  1052. self.assertEqual(400, channel.code, msg=channel.json_body)
  1053. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  1054. def test_user_is_not_local(self) -> None:
  1055. """
  1056. Tests that deactivation for a user that is not a local returns a 400
  1057. """
  1058. url = "/_synapse/admin/v1/deactivate/@unknown_person:unknown_domain"
  1059. channel = self.make_request("POST", url, access_token=self.admin_user_tok)
  1060. self.assertEqual(400, channel.code, msg=channel.json_body)
  1061. self.assertEqual("Can only deactivate local users", channel.json_body["error"])
  1062. def test_deactivate_user_erase_true(self) -> None:
  1063. """
  1064. Test deactivating a user and set `erase` to `true`
  1065. """
  1066. # Get user
  1067. channel = self.make_request(
  1068. "GET",
  1069. self.url_other_user,
  1070. access_token=self.admin_user_tok,
  1071. )
  1072. self.assertEqual(200, channel.code, msg=channel.json_body)
  1073. self.assertEqual("@user:test", channel.json_body["name"])
  1074. self.assertEqual(False, channel.json_body["deactivated"])
  1075. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1076. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1077. self.assertEqual("User1", channel.json_body["displayname"])
  1078. self.assertFalse(channel.json_body["erased"])
  1079. # Deactivate and erase user
  1080. channel = self.make_request(
  1081. "POST",
  1082. self.url,
  1083. access_token=self.admin_user_tok,
  1084. content={"erase": True},
  1085. )
  1086. self.assertEqual(200, channel.code, msg=channel.json_body)
  1087. # Get user
  1088. channel = self.make_request(
  1089. "GET",
  1090. self.url_other_user,
  1091. access_token=self.admin_user_tok,
  1092. )
  1093. self.assertEqual(200, channel.code, msg=channel.json_body)
  1094. self.assertEqual("@user:test", channel.json_body["name"])
  1095. self.assertEqual(True, channel.json_body["deactivated"])
  1096. self.assertEqual(0, len(channel.json_body["threepids"]))
  1097. self.assertIsNone(channel.json_body["avatar_url"])
  1098. self.assertIsNone(channel.json_body["displayname"])
  1099. self.assertTrue(channel.json_body["erased"])
  1100. self._is_erased("@user:test", True)
  1101. @override_config({"max_avatar_size": 1234})
  1102. def test_deactivate_user_erase_true_avatar_nonnull_but_empty(self) -> None:
  1103. """Check we can erase a user whose avatar is the empty string.
  1104. Reproduces #12257.
  1105. """
  1106. # Patch `self.other_user` to have an empty string as their avatar.
  1107. self.get_success(
  1108. self.store.set_profile_avatar_url(UserID.from_string("@user:test"), "")
  1109. )
  1110. # Check we can still erase them.
  1111. channel = self.make_request(
  1112. "POST",
  1113. self.url,
  1114. access_token=self.admin_user_tok,
  1115. content={"erase": True},
  1116. )
  1117. self.assertEqual(200, channel.code, msg=channel.json_body)
  1118. self._is_erased("@user:test", True)
  1119. def test_deactivate_user_erase_false(self) -> None:
  1120. """
  1121. Test deactivating a user and set `erase` to `false`
  1122. """
  1123. # Get user
  1124. channel = self.make_request(
  1125. "GET",
  1126. self.url_other_user,
  1127. access_token=self.admin_user_tok,
  1128. )
  1129. self.assertEqual(200, channel.code, msg=channel.json_body)
  1130. self.assertEqual("@user:test", channel.json_body["name"])
  1131. self.assertEqual(False, channel.json_body["deactivated"])
  1132. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1133. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1134. self.assertEqual("User1", channel.json_body["displayname"])
  1135. # Deactivate user
  1136. channel = self.make_request(
  1137. "POST",
  1138. self.url,
  1139. access_token=self.admin_user_tok,
  1140. content={"erase": False},
  1141. )
  1142. self.assertEqual(200, channel.code, msg=channel.json_body)
  1143. # Get user
  1144. channel = self.make_request(
  1145. "GET",
  1146. self.url_other_user,
  1147. access_token=self.admin_user_tok,
  1148. )
  1149. self.assertEqual(200, channel.code, msg=channel.json_body)
  1150. self.assertEqual("@user:test", channel.json_body["name"])
  1151. self.assertEqual(True, channel.json_body["deactivated"])
  1152. self.assertEqual(0, len(channel.json_body["threepids"]))
  1153. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1154. self.assertEqual("User1", channel.json_body["displayname"])
  1155. self._is_erased("@user:test", False)
  1156. def test_deactivate_user_erase_true_no_profile(self) -> None:
  1157. """
  1158. Test deactivating a user and set `erase` to `true`
  1159. if user has no profile information (stored in the database table `profiles`).
  1160. """
  1161. # Users normally have an entry in `profiles`, but occasionally they are created without one.
  1162. # To test deactivation for users without a profile, we delete the profile information for our user.
  1163. self.get_success(
  1164. self.store.db_pool.simple_delete_one(
  1165. table="profiles", keyvalues={"full_user_id": "@user:test"}
  1166. )
  1167. )
  1168. # Get user
  1169. channel = self.make_request(
  1170. "GET",
  1171. self.url_other_user,
  1172. access_token=self.admin_user_tok,
  1173. )
  1174. self.assertEqual(200, channel.code, msg=channel.json_body)
  1175. self.assertEqual("@user:test", channel.json_body["name"])
  1176. self.assertEqual(False, channel.json_body["deactivated"])
  1177. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1178. self.assertIsNone(channel.json_body["avatar_url"])
  1179. self.assertIsNone(channel.json_body["displayname"])
  1180. # Deactivate and erase user
  1181. channel = self.make_request(
  1182. "POST",
  1183. self.url,
  1184. access_token=self.admin_user_tok,
  1185. content={"erase": True},
  1186. )
  1187. self.assertEqual(200, channel.code, msg=channel.json_body)
  1188. # Get user
  1189. channel = self.make_request(
  1190. "GET",
  1191. self.url_other_user,
  1192. access_token=self.admin_user_tok,
  1193. )
  1194. self.assertEqual(200, channel.code, msg=channel.json_body)
  1195. self.assertEqual("@user:test", channel.json_body["name"])
  1196. self.assertEqual(True, channel.json_body["deactivated"])
  1197. self.assertEqual(0, len(channel.json_body["threepids"]))
  1198. self.assertIsNone(channel.json_body["avatar_url"])
  1199. self.assertIsNone(channel.json_body["displayname"])
  1200. self._is_erased("@user:test", True)
  1201. def _is_erased(self, user_id: str, expect: bool) -> None:
  1202. """Assert that the user is erased or not"""
  1203. d = self.store.is_user_erased(user_id)
  1204. if expect:
  1205. self.assertTrue(self.get_success(d))
  1206. else:
  1207. self.assertFalse(self.get_success(d))
  1208. class UserRestTestCase(unittest.HomeserverTestCase):
  1209. servlets = [
  1210. synapse.rest.admin.register_servlets,
  1211. login.register_servlets,
  1212. sync.register_servlets,
  1213. register.register_servlets,
  1214. user_directory.register_servlets,
  1215. ]
  1216. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  1217. self.store = hs.get_datastores().main
  1218. self.auth_handler = hs.get_auth_handler()
  1219. # create users and get access tokens
  1220. # regardless of whether password login or SSO is allowed
  1221. self.admin_user = self.register_user("admin", "pass", admin=True)
  1222. self.admin_user_tok = self.get_success(
  1223. self.auth_handler.create_access_token_for_user_id(
  1224. self.admin_user, device_id=None, valid_until_ms=None
  1225. )
  1226. )
  1227. self.other_user = self.register_user("user", "pass", displayname="User")
  1228. self.other_user_token = self.get_success(
  1229. self.auth_handler.create_access_token_for_user_id(
  1230. self.other_user, device_id=None, valid_until_ms=None
  1231. )
  1232. )
  1233. self.url_prefix = "/_synapse/admin/v2/users/%s"
  1234. self.url_other_user = self.url_prefix % self.other_user
  1235. def test_requester_is_no_admin(self) -> None:
  1236. """
  1237. If the user is not a server admin, an error is returned.
  1238. """
  1239. url = self.url_prefix % "@bob:test"
  1240. channel = self.make_request(
  1241. "GET",
  1242. url,
  1243. access_token=self.other_user_token,
  1244. )
  1245. self.assertEqual(403, channel.code, msg=channel.json_body)
  1246. self.assertEqual("You are not a server admin", channel.json_body["error"])
  1247. channel = self.make_request(
  1248. "PUT",
  1249. url,
  1250. access_token=self.other_user_token,
  1251. content=b"{}",
  1252. )
  1253. self.assertEqual(403, channel.code, msg=channel.json_body)
  1254. self.assertEqual("You are not a server admin", channel.json_body["error"])
  1255. def test_user_does_not_exist(self) -> None:
  1256. """
  1257. Tests that a lookup for a user that does not exist returns a 404
  1258. """
  1259. channel = self.make_request(
  1260. "GET",
  1261. self.url_prefix % "@unknown_person:test",
  1262. access_token=self.admin_user_tok,
  1263. )
  1264. self.assertEqual(404, channel.code, msg=channel.json_body)
  1265. self.assertEqual("M_NOT_FOUND", channel.json_body["errcode"])
  1266. def test_invalid_parameter(self) -> None:
  1267. """
  1268. If parameters are invalid, an error is returned.
  1269. """
  1270. # admin not bool
  1271. channel = self.make_request(
  1272. "PUT",
  1273. self.url_other_user,
  1274. access_token=self.admin_user_tok,
  1275. content={"admin": "not_bool"},
  1276. )
  1277. self.assertEqual(400, channel.code, msg=channel.json_body)
  1278. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  1279. # deactivated not bool
  1280. channel = self.make_request(
  1281. "PUT",
  1282. self.url_other_user,
  1283. access_token=self.admin_user_tok,
  1284. content={"deactivated": "not_bool"},
  1285. )
  1286. self.assertEqual(400, channel.code, msg=channel.json_body)
  1287. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1288. # password not str
  1289. channel = self.make_request(
  1290. "PUT",
  1291. self.url_other_user,
  1292. access_token=self.admin_user_tok,
  1293. content={"password": True},
  1294. )
  1295. self.assertEqual(400, channel.code, msg=channel.json_body)
  1296. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1297. # password not length
  1298. channel = self.make_request(
  1299. "PUT",
  1300. self.url_other_user,
  1301. access_token=self.admin_user_tok,
  1302. content={"password": "x" * 513},
  1303. )
  1304. self.assertEqual(400, channel.code, msg=channel.json_body)
  1305. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1306. # user_type not valid
  1307. channel = self.make_request(
  1308. "PUT",
  1309. self.url_other_user,
  1310. access_token=self.admin_user_tok,
  1311. content={"user_type": "new type"},
  1312. )
  1313. self.assertEqual(400, channel.code, msg=channel.json_body)
  1314. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1315. # external_ids not valid
  1316. channel = self.make_request(
  1317. "PUT",
  1318. self.url_other_user,
  1319. access_token=self.admin_user_tok,
  1320. content={
  1321. "external_ids": {"auth_provider": "prov", "wrong_external_id": "id"}
  1322. },
  1323. )
  1324. self.assertEqual(400, channel.code, msg=channel.json_body)
  1325. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1326. channel = self.make_request(
  1327. "PUT",
  1328. self.url_other_user,
  1329. access_token=self.admin_user_tok,
  1330. content={"external_ids": {"external_id": "id"}},
  1331. )
  1332. self.assertEqual(400, channel.code, msg=channel.json_body)
  1333. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1334. # threepids not valid
  1335. channel = self.make_request(
  1336. "PUT",
  1337. self.url_other_user,
  1338. access_token=self.admin_user_tok,
  1339. content={"threepids": {"medium": "email", "wrong_address": "id"}},
  1340. )
  1341. self.assertEqual(400, channel.code, msg=channel.json_body)
  1342. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1343. channel = self.make_request(
  1344. "PUT",
  1345. self.url_other_user,
  1346. access_token=self.admin_user_tok,
  1347. content={"threepids": {"address": "value"}},
  1348. )
  1349. self.assertEqual(400, channel.code, msg=channel.json_body)
  1350. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  1351. def test_get_user(self) -> None:
  1352. """
  1353. Test a simple get of a user.
  1354. """
  1355. channel = self.make_request(
  1356. "GET",
  1357. self.url_other_user,
  1358. access_token=self.admin_user_tok,
  1359. )
  1360. self.assertEqual(200, channel.code, msg=channel.json_body)
  1361. self.assertEqual("@user:test", channel.json_body["name"])
  1362. self.assertEqual("User", channel.json_body["displayname"])
  1363. self._check_fields(channel.json_body)
  1364. def test_create_server_admin(self) -> None:
  1365. """
  1366. Check that a new admin user is created successfully.
  1367. """
  1368. url = self.url_prefix % "@bob:test"
  1369. # Create user (server admin)
  1370. body = {
  1371. "password": "abc123",
  1372. "admin": True,
  1373. "displayname": "Bob's name",
  1374. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1375. "avatar_url": "mxc://fibble/wibble",
  1376. }
  1377. channel = self.make_request(
  1378. "PUT",
  1379. url,
  1380. access_token=self.admin_user_tok,
  1381. content=body,
  1382. )
  1383. self.assertEqual(201, channel.code, msg=channel.json_body)
  1384. self.assertEqual("@bob:test", channel.json_body["name"])
  1385. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1386. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1387. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1388. self.assertTrue(channel.json_body["admin"])
  1389. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1390. self._check_fields(channel.json_body)
  1391. # Get user
  1392. channel = self.make_request(
  1393. "GET",
  1394. url,
  1395. access_token=self.admin_user_tok,
  1396. )
  1397. self.assertEqual(200, channel.code, msg=channel.json_body)
  1398. self.assertEqual("@bob:test", channel.json_body["name"])
  1399. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1400. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1401. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1402. self.assertTrue(channel.json_body["admin"])
  1403. self.assertFalse(channel.json_body["is_guest"])
  1404. self.assertFalse(channel.json_body["deactivated"])
  1405. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1406. self._check_fields(channel.json_body)
  1407. def test_create_user(self) -> None:
  1408. """
  1409. Check that a new regular user is created successfully.
  1410. """
  1411. url = self.url_prefix % "@bob:test"
  1412. # Create user
  1413. body = {
  1414. "password": "abc123",
  1415. "admin": False,
  1416. "displayname": "Bob's name",
  1417. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1418. "external_ids": [
  1419. {
  1420. "external_id": "external_id1",
  1421. "auth_provider": "auth_provider1",
  1422. },
  1423. ],
  1424. "avatar_url": "mxc://fibble/wibble",
  1425. }
  1426. channel = self.make_request(
  1427. "PUT",
  1428. url,
  1429. access_token=self.admin_user_tok,
  1430. content=body,
  1431. )
  1432. self.assertEqual(201, channel.code, msg=channel.json_body)
  1433. self.assertEqual("@bob:test", channel.json_body["name"])
  1434. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1435. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1436. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1437. self.assertEqual(1, len(channel.json_body["threepids"]))
  1438. self.assertEqual(
  1439. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1440. )
  1441. self.assertEqual(
  1442. "auth_provider1", channel.json_body["external_ids"][0]["auth_provider"]
  1443. )
  1444. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1445. self.assertFalse(channel.json_body["admin"])
  1446. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1447. self._check_fields(channel.json_body)
  1448. # Get user
  1449. channel = self.make_request(
  1450. "GET",
  1451. url,
  1452. access_token=self.admin_user_tok,
  1453. )
  1454. self.assertEqual(200, channel.code, msg=channel.json_body)
  1455. self.assertEqual("@bob:test", channel.json_body["name"])
  1456. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1457. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1458. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1459. self.assertFalse(channel.json_body["admin"])
  1460. self.assertFalse(channel.json_body["is_guest"])
  1461. self.assertFalse(channel.json_body["deactivated"])
  1462. self.assertFalse(channel.json_body["shadow_banned"])
  1463. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1464. self._check_fields(channel.json_body)
  1465. @override_config(
  1466. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1467. )
  1468. def test_create_user_mau_limit_reached_active_admin(self) -> None:
  1469. """
  1470. Check that an admin can register a new user via the admin API
  1471. even if the MAU limit is reached.
  1472. Admin user was active before creating user.
  1473. """
  1474. handler = self.hs.get_registration_handler()
  1475. # Sync to set admin user to active
  1476. # before limit of monthly active users is reached
  1477. channel = self.make_request("GET", "/sync", access_token=self.admin_user_tok)
  1478. if channel.code != 200:
  1479. raise HttpResponseException(
  1480. channel.code, channel.result["reason"], channel.result["body"]
  1481. )
  1482. # Set monthly active users to the limit
  1483. self.store.get_monthly_active_count = Mock(
  1484. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  1485. )
  1486. # Check that the blocking of monthly active users is working as expected
  1487. # The registration of a new user fails due to the limit
  1488. self.get_failure(
  1489. handler.register_user(localpart="local_part"), ResourceLimitError
  1490. )
  1491. # Register new user with admin API
  1492. url = self.url_prefix % "@bob:test"
  1493. # Create user
  1494. channel = self.make_request(
  1495. "PUT",
  1496. url,
  1497. access_token=self.admin_user_tok,
  1498. content={"password": "abc123", "admin": False},
  1499. )
  1500. self.assertEqual(201, channel.code, msg=channel.json_body)
  1501. self.assertEqual("@bob:test", channel.json_body["name"])
  1502. self.assertFalse(channel.json_body["admin"])
  1503. @override_config(
  1504. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1505. )
  1506. def test_create_user_mau_limit_reached_passive_admin(self) -> None:
  1507. """
  1508. Check that an admin can register a new user via the admin API
  1509. even if the MAU limit is reached.
  1510. Admin user was not active before creating user.
  1511. """
  1512. handler = self.hs.get_registration_handler()
  1513. # Set monthly active users to the limit
  1514. self.store.get_monthly_active_count = Mock(
  1515. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  1516. )
  1517. # Check that the blocking of monthly active users is working as expected
  1518. # The registration of a new user fails due to the limit
  1519. self.get_failure(
  1520. handler.register_user(localpart="local_part"), ResourceLimitError
  1521. )
  1522. # Register new user with admin API
  1523. url = self.url_prefix % "@bob:test"
  1524. # Create user
  1525. channel = self.make_request(
  1526. "PUT",
  1527. url,
  1528. access_token=self.admin_user_tok,
  1529. content={"password": "abc123", "admin": False},
  1530. )
  1531. # Admin user is not blocked by mau anymore
  1532. self.assertEqual(201, channel.code, msg=channel.json_body)
  1533. self.assertEqual("@bob:test", channel.json_body["name"])
  1534. self.assertFalse(channel.json_body["admin"])
  1535. @override_config(
  1536. {
  1537. "email": {
  1538. "enable_notifs": True,
  1539. "notif_for_new_users": True,
  1540. "notif_from": "test@example.com",
  1541. },
  1542. "public_baseurl": "https://example.com",
  1543. }
  1544. )
  1545. def test_create_user_email_notif_for_new_users(self) -> None:
  1546. """
  1547. Check that a new regular user is created successfully and
  1548. got an email pusher.
  1549. """
  1550. url = self.url_prefix % "@bob:test"
  1551. # Create user
  1552. body = {
  1553. "password": "abc123",
  1554. # Note that the given email is not in canonical form.
  1555. "threepids": [{"medium": "email", "address": "Bob@bob.bob"}],
  1556. }
  1557. channel = self.make_request(
  1558. "PUT",
  1559. url,
  1560. access_token=self.admin_user_tok,
  1561. content=body,
  1562. )
  1563. self.assertEqual(201, channel.code, msg=channel.json_body)
  1564. self.assertEqual("@bob:test", channel.json_body["name"])
  1565. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1566. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1567. pushers = list(
  1568. self.get_success(self.store.get_pushers_by({"user_name": "@bob:test"}))
  1569. )
  1570. self.assertEqual(len(pushers), 1)
  1571. self.assertEqual("@bob:test", pushers[0].user_name)
  1572. @override_config(
  1573. {
  1574. "email": {
  1575. "enable_notifs": False,
  1576. "notif_for_new_users": False,
  1577. "notif_from": "test@example.com",
  1578. },
  1579. "public_baseurl": "https://example.com",
  1580. }
  1581. )
  1582. def test_create_user_email_no_notif_for_new_users(self) -> None:
  1583. """
  1584. Check that a new regular user is created successfully and
  1585. got not an email pusher.
  1586. """
  1587. url = self.url_prefix % "@bob:test"
  1588. # Create user
  1589. body = {
  1590. "password": "abc123",
  1591. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1592. }
  1593. channel = self.make_request(
  1594. "PUT",
  1595. url,
  1596. access_token=self.admin_user_tok,
  1597. content=body,
  1598. )
  1599. self.assertEqual(201, channel.code, msg=channel.json_body)
  1600. self.assertEqual("@bob:test", channel.json_body["name"])
  1601. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1602. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1603. pushers = list(
  1604. self.get_success(self.store.get_pushers_by({"user_name": "@bob:test"}))
  1605. )
  1606. self.assertEqual(len(pushers), 0)
  1607. @override_config(
  1608. {
  1609. "email": {
  1610. "enable_notifs": True,
  1611. "notif_for_new_users": True,
  1612. "notif_from": "test@example.com",
  1613. },
  1614. "public_baseurl": "https://example.com",
  1615. }
  1616. )
  1617. def test_create_user_email_notif_for_new_users_with_msisdn_threepid(self) -> None:
  1618. """
  1619. Check that a new regular user is created successfully when they have a msisdn
  1620. threepid and email notif_for_new_users is set to True.
  1621. """
  1622. url = self.url_prefix % "@bob:test"
  1623. # Create user
  1624. body = {
  1625. "password": "abc123",
  1626. "threepids": [{"medium": "msisdn", "address": "1234567890"}],
  1627. }
  1628. channel = self.make_request(
  1629. "PUT",
  1630. url,
  1631. access_token=self.admin_user_tok,
  1632. content=body,
  1633. )
  1634. self.assertEqual(201, channel.code, msg=channel.json_body)
  1635. self.assertEqual("@bob:test", channel.json_body["name"])
  1636. self.assertEqual("msisdn", channel.json_body["threepids"][0]["medium"])
  1637. self.assertEqual("1234567890", channel.json_body["threepids"][0]["address"])
  1638. def test_set_password(self) -> None:
  1639. """
  1640. Test setting a new password for another user.
  1641. """
  1642. # Change password
  1643. channel = self.make_request(
  1644. "PUT",
  1645. self.url_other_user,
  1646. access_token=self.admin_user_tok,
  1647. content={"password": "hahaha"},
  1648. )
  1649. self.assertEqual(200, channel.code, msg=channel.json_body)
  1650. self._check_fields(channel.json_body)
  1651. def test_set_displayname(self) -> None:
  1652. """
  1653. Test setting the displayname of another user.
  1654. """
  1655. # Modify user
  1656. channel = self.make_request(
  1657. "PUT",
  1658. self.url_other_user,
  1659. access_token=self.admin_user_tok,
  1660. content={"displayname": "foobar"},
  1661. )
  1662. self.assertEqual(200, channel.code, msg=channel.json_body)
  1663. self.assertEqual("@user:test", channel.json_body["name"])
  1664. self.assertEqual("foobar", channel.json_body["displayname"])
  1665. # Get user
  1666. channel = self.make_request(
  1667. "GET",
  1668. self.url_other_user,
  1669. access_token=self.admin_user_tok,
  1670. )
  1671. self.assertEqual(200, channel.code, msg=channel.json_body)
  1672. self.assertEqual("@user:test", channel.json_body["name"])
  1673. self.assertEqual("foobar", channel.json_body["displayname"])
  1674. def test_set_threepid(self) -> None:
  1675. """
  1676. Test setting threepid for an other user.
  1677. """
  1678. # Add two threepids to user
  1679. channel = self.make_request(
  1680. "PUT",
  1681. self.url_other_user,
  1682. access_token=self.admin_user_tok,
  1683. content={
  1684. "threepids": [
  1685. {"medium": "email", "address": "bob1@bob.bob"},
  1686. {"medium": "email", "address": "bob2@bob.bob"},
  1687. ],
  1688. },
  1689. )
  1690. self.assertEqual(200, channel.code, msg=channel.json_body)
  1691. self.assertEqual("@user:test", channel.json_body["name"])
  1692. self.assertEqual(2, len(channel.json_body["threepids"]))
  1693. # result does not always have the same sort order, therefore it becomes sorted
  1694. sorted_result = sorted(
  1695. channel.json_body["threepids"], key=lambda k: k["address"]
  1696. )
  1697. self.assertEqual("email", sorted_result[0]["medium"])
  1698. self.assertEqual("bob1@bob.bob", sorted_result[0]["address"])
  1699. self.assertEqual("email", sorted_result[1]["medium"])
  1700. self.assertEqual("bob2@bob.bob", sorted_result[1]["address"])
  1701. self._check_fields(channel.json_body)
  1702. # Set a new and remove a threepid
  1703. channel = self.make_request(
  1704. "PUT",
  1705. self.url_other_user,
  1706. access_token=self.admin_user_tok,
  1707. content={
  1708. "threepids": [
  1709. {"medium": "email", "address": "bob2@bob.bob"},
  1710. {"medium": "email", "address": "bob3@bob.bob"},
  1711. ],
  1712. },
  1713. )
  1714. self.assertEqual(200, channel.code, msg=channel.json_body)
  1715. self.assertEqual("@user:test", channel.json_body["name"])
  1716. self.assertEqual(2, len(channel.json_body["threepids"]))
  1717. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1718. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1719. self.assertEqual("email", channel.json_body["threepids"][1]["medium"])
  1720. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][1]["address"])
  1721. self._check_fields(channel.json_body)
  1722. # Get user
  1723. channel = self.make_request(
  1724. "GET",
  1725. self.url_other_user,
  1726. access_token=self.admin_user_tok,
  1727. )
  1728. self.assertEqual(200, channel.code, msg=channel.json_body)
  1729. self.assertEqual("@user:test", channel.json_body["name"])
  1730. self.assertEqual(2, len(channel.json_body["threepids"]))
  1731. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1732. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1733. self.assertEqual("email", channel.json_body["threepids"][1]["medium"])
  1734. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][1]["address"])
  1735. self._check_fields(channel.json_body)
  1736. # Remove threepids
  1737. channel = self.make_request(
  1738. "PUT",
  1739. self.url_other_user,
  1740. access_token=self.admin_user_tok,
  1741. content={"threepids": []},
  1742. )
  1743. self.assertEqual(200, channel.code, msg=channel.json_body)
  1744. self.assertEqual("@user:test", channel.json_body["name"])
  1745. self.assertEqual(0, len(channel.json_body["threepids"]))
  1746. self._check_fields(channel.json_body)
  1747. def test_set_duplicate_threepid(self) -> None:
  1748. """
  1749. Test setting the same threepid for a second user.
  1750. First user loses and second user gets mapping of this threepid.
  1751. """
  1752. # create a user to set a threepid
  1753. first_user = self.register_user("first_user", "pass")
  1754. url_first_user = self.url_prefix % first_user
  1755. # Add threepid to first user
  1756. channel = self.make_request(
  1757. "PUT",
  1758. url_first_user,
  1759. access_token=self.admin_user_tok,
  1760. content={
  1761. "threepids": [
  1762. {"medium": "email", "address": "bob1@bob.bob"},
  1763. ],
  1764. },
  1765. )
  1766. self.assertEqual(200, channel.code, msg=channel.json_body)
  1767. self.assertEqual(first_user, channel.json_body["name"])
  1768. self.assertEqual(1, len(channel.json_body["threepids"]))
  1769. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1770. self.assertEqual("bob1@bob.bob", channel.json_body["threepids"][0]["address"])
  1771. self._check_fields(channel.json_body)
  1772. # Add threepids to other user
  1773. channel = self.make_request(
  1774. "PUT",
  1775. self.url_other_user,
  1776. access_token=self.admin_user_tok,
  1777. content={
  1778. "threepids": [
  1779. {"medium": "email", "address": "bob2@bob.bob"},
  1780. ],
  1781. },
  1782. )
  1783. self.assertEqual(200, channel.code, msg=channel.json_body)
  1784. self.assertEqual("@user:test", channel.json_body["name"])
  1785. self.assertEqual(1, len(channel.json_body["threepids"]))
  1786. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1787. self.assertEqual("bob2@bob.bob", channel.json_body["threepids"][0]["address"])
  1788. self._check_fields(channel.json_body)
  1789. # Add two new threepids to other user
  1790. # one is used by first_user
  1791. channel = self.make_request(
  1792. "PUT",
  1793. self.url_other_user,
  1794. access_token=self.admin_user_tok,
  1795. content={
  1796. "threepids": [
  1797. {"medium": "email", "address": "bob1@bob.bob"},
  1798. {"medium": "email", "address": "bob3@bob.bob"},
  1799. ],
  1800. },
  1801. )
  1802. # other user has this two threepids
  1803. self.assertEqual(200, channel.code, msg=channel.json_body)
  1804. self.assertEqual("@user:test", channel.json_body["name"])
  1805. self.assertEqual(2, len(channel.json_body["threepids"]))
  1806. # result does not always have the same sort order, therefore it becomes sorted
  1807. sorted_result = sorted(
  1808. channel.json_body["threepids"], key=lambda k: k["address"]
  1809. )
  1810. self.assertEqual("email", sorted_result[0]["medium"])
  1811. self.assertEqual("bob1@bob.bob", sorted_result[0]["address"])
  1812. self.assertEqual("email", sorted_result[1]["medium"])
  1813. self.assertEqual("bob3@bob.bob", sorted_result[1]["address"])
  1814. self._check_fields(channel.json_body)
  1815. # first_user has no threepid anymore
  1816. channel = self.make_request(
  1817. "GET",
  1818. url_first_user,
  1819. access_token=self.admin_user_tok,
  1820. )
  1821. self.assertEqual(200, channel.code, msg=channel.json_body)
  1822. self.assertEqual(first_user, channel.json_body["name"])
  1823. self.assertEqual(0, len(channel.json_body["threepids"]))
  1824. self._check_fields(channel.json_body)
  1825. def test_set_external_id(self) -> None:
  1826. """
  1827. Test setting external id for an other user.
  1828. """
  1829. # Add two external_ids
  1830. channel = self.make_request(
  1831. "PUT",
  1832. self.url_other_user,
  1833. access_token=self.admin_user_tok,
  1834. content={
  1835. "external_ids": [
  1836. {
  1837. "external_id": "external_id1",
  1838. "auth_provider": "auth_provider1",
  1839. },
  1840. {
  1841. "external_id": "external_id2",
  1842. "auth_provider": "auth_provider2",
  1843. },
  1844. ]
  1845. },
  1846. )
  1847. self.assertEqual(200, channel.code, msg=channel.json_body)
  1848. self.assertEqual("@user:test", channel.json_body["name"])
  1849. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1850. # result does not always have the same sort order, therefore it becomes sorted
  1851. self.assertEqual(
  1852. sorted(channel.json_body["external_ids"], key=lambda k: k["auth_provider"]),
  1853. [
  1854. {"auth_provider": "auth_provider1", "external_id": "external_id1"},
  1855. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1856. ],
  1857. )
  1858. self._check_fields(channel.json_body)
  1859. # Set a new and remove an external_id
  1860. channel = self.make_request(
  1861. "PUT",
  1862. self.url_other_user,
  1863. access_token=self.admin_user_tok,
  1864. content={
  1865. "external_ids": [
  1866. {
  1867. "external_id": "external_id2",
  1868. "auth_provider": "auth_provider2",
  1869. },
  1870. {
  1871. "external_id": "external_id3",
  1872. "auth_provider": "auth_provider3",
  1873. },
  1874. ]
  1875. },
  1876. )
  1877. self.assertEqual(200, channel.code, msg=channel.json_body)
  1878. self.assertEqual("@user:test", channel.json_body["name"])
  1879. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1880. self.assertEqual(
  1881. channel.json_body["external_ids"],
  1882. [
  1883. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1884. {"auth_provider": "auth_provider3", "external_id": "external_id3"},
  1885. ],
  1886. )
  1887. self._check_fields(channel.json_body)
  1888. # Get user
  1889. channel = self.make_request(
  1890. "GET",
  1891. self.url_other_user,
  1892. access_token=self.admin_user_tok,
  1893. )
  1894. self.assertEqual(200, channel.code, msg=channel.json_body)
  1895. self.assertEqual("@user:test", channel.json_body["name"])
  1896. self.assertEqual(2, len(channel.json_body["external_ids"]))
  1897. self.assertEqual(
  1898. channel.json_body["external_ids"],
  1899. [
  1900. {"auth_provider": "auth_provider2", "external_id": "external_id2"},
  1901. {"auth_provider": "auth_provider3", "external_id": "external_id3"},
  1902. ],
  1903. )
  1904. self._check_fields(channel.json_body)
  1905. # Remove external_ids
  1906. channel = self.make_request(
  1907. "PUT",
  1908. self.url_other_user,
  1909. access_token=self.admin_user_tok,
  1910. content={"external_ids": []},
  1911. )
  1912. self.assertEqual(200, channel.code, msg=channel.json_body)
  1913. self.assertEqual("@user:test", channel.json_body["name"])
  1914. self.assertEqual(0, len(channel.json_body["external_ids"]))
  1915. def test_set_duplicate_external_id(self) -> None:
  1916. """
  1917. Test that setting the same external id for a second user fails and
  1918. external id from user must not be changed.
  1919. """
  1920. # create a user to use an external id
  1921. first_user = self.register_user("first_user", "pass")
  1922. url_first_user = self.url_prefix % first_user
  1923. # Add an external id to first user
  1924. channel = self.make_request(
  1925. "PUT",
  1926. url_first_user,
  1927. access_token=self.admin_user_tok,
  1928. content={
  1929. "external_ids": [
  1930. {
  1931. "external_id": "external_id1",
  1932. "auth_provider": "auth_provider",
  1933. },
  1934. ],
  1935. },
  1936. )
  1937. self.assertEqual(200, channel.code, msg=channel.json_body)
  1938. self.assertEqual(first_user, channel.json_body["name"])
  1939. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1940. self.assertEqual(
  1941. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1942. )
  1943. self.assertEqual(
  1944. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1945. )
  1946. self._check_fields(channel.json_body)
  1947. # Add an external id to other user
  1948. channel = self.make_request(
  1949. "PUT",
  1950. self.url_other_user,
  1951. access_token=self.admin_user_tok,
  1952. content={
  1953. "external_ids": [
  1954. {
  1955. "external_id": "external_id2",
  1956. "auth_provider": "auth_provider",
  1957. },
  1958. ],
  1959. },
  1960. )
  1961. self.assertEqual(200, channel.code, msg=channel.json_body)
  1962. self.assertEqual("@user:test", channel.json_body["name"])
  1963. self.assertEqual(1, len(channel.json_body["external_ids"]))
  1964. self.assertEqual(
  1965. "external_id2", channel.json_body["external_ids"][0]["external_id"]
  1966. )
  1967. self.assertEqual(
  1968. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  1969. )
  1970. self._check_fields(channel.json_body)
  1971. # Add two new external_ids to other user
  1972. # one is used by first
  1973. channel = self.make_request(
  1974. "PUT",
  1975. self.url_other_user,
  1976. access_token=self.admin_user_tok,
  1977. content={
  1978. "external_ids": [
  1979. {
  1980. "external_id": "external_id1",
  1981. "auth_provider": "auth_provider",
  1982. },
  1983. {
  1984. "external_id": "external_id3",
  1985. "auth_provider": "auth_provider",
  1986. },
  1987. ],
  1988. },
  1989. )
  1990. # must fail
  1991. self.assertEqual(409, channel.code, msg=channel.json_body)
  1992. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1993. self.assertEqual("External id is already in use.", channel.json_body["error"])
  1994. # other user must not changed
  1995. channel = self.make_request(
  1996. "GET",
  1997. self.url_other_user,
  1998. access_token=self.admin_user_tok,
  1999. )
  2000. self.assertEqual(200, channel.code, msg=channel.json_body)
  2001. self.assertEqual("@user:test", channel.json_body["name"])
  2002. self.assertEqual(1, len(channel.json_body["external_ids"]))
  2003. self.assertEqual(
  2004. "external_id2", channel.json_body["external_ids"][0]["external_id"]
  2005. )
  2006. self.assertEqual(
  2007. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  2008. )
  2009. self._check_fields(channel.json_body)
  2010. # first user must not changed
  2011. channel = self.make_request(
  2012. "GET",
  2013. url_first_user,
  2014. access_token=self.admin_user_tok,
  2015. )
  2016. self.assertEqual(200, channel.code, msg=channel.json_body)
  2017. self.assertEqual(first_user, channel.json_body["name"])
  2018. self.assertEqual(1, len(channel.json_body["external_ids"]))
  2019. self.assertEqual(
  2020. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  2021. )
  2022. self.assertEqual(
  2023. "auth_provider", channel.json_body["external_ids"][0]["auth_provider"]
  2024. )
  2025. self._check_fields(channel.json_body)
  2026. def test_deactivate_user(self) -> None:
  2027. """
  2028. Test deactivating another user.
  2029. """
  2030. # set attributes for user
  2031. self.get_success(
  2032. self.store.set_profile_avatar_url(
  2033. UserID.from_string("@user:test"), "mxc://servername/mediaid"
  2034. )
  2035. )
  2036. self.get_success(
  2037. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  2038. )
  2039. # Get user
  2040. channel = self.make_request(
  2041. "GET",
  2042. self.url_other_user,
  2043. access_token=self.admin_user_tok,
  2044. )
  2045. self.assertEqual(200, channel.code, msg=channel.json_body)
  2046. self.assertEqual("@user:test", channel.json_body["name"])
  2047. self.assertFalse(channel.json_body["deactivated"])
  2048. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  2049. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  2050. self.assertEqual("User", channel.json_body["displayname"])
  2051. # Deactivate user
  2052. channel = self.make_request(
  2053. "PUT",
  2054. self.url_other_user,
  2055. access_token=self.admin_user_tok,
  2056. content={"deactivated": True},
  2057. )
  2058. self.assertEqual(200, channel.code, msg=channel.json_body)
  2059. self.assertEqual("@user:test", channel.json_body["name"])
  2060. self.assertTrue(channel.json_body["deactivated"])
  2061. self.assertEqual(0, len(channel.json_body["threepids"]))
  2062. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  2063. self.assertEqual("User", channel.json_body["displayname"])
  2064. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2065. self.assertNotIn("password_hash", channel.json_body)
  2066. # the user is deactivated, the threepid will be deleted
  2067. # Get user
  2068. channel = self.make_request(
  2069. "GET",
  2070. self.url_other_user,
  2071. access_token=self.admin_user_tok,
  2072. )
  2073. self.assertEqual(200, channel.code, msg=channel.json_body)
  2074. self.assertEqual("@user:test", channel.json_body["name"])
  2075. self.assertTrue(channel.json_body["deactivated"])
  2076. self.assertEqual(0, len(channel.json_body["threepids"]))
  2077. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  2078. self.assertEqual("User", channel.json_body["displayname"])
  2079. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2080. self.assertNotIn("password_hash", channel.json_body)
  2081. def test_locked_user(self) -> None:
  2082. # User can sync
  2083. channel = self.make_request(
  2084. "GET",
  2085. "/_matrix/client/v3/sync",
  2086. access_token=self.other_user_token,
  2087. )
  2088. self.assertEqual(200, channel.code, msg=channel.json_body)
  2089. # Lock user
  2090. channel = self.make_request(
  2091. "PUT",
  2092. self.url_other_user,
  2093. access_token=self.admin_user_tok,
  2094. content={"locked": True},
  2095. )
  2096. # User is not authorized to sync anymore
  2097. channel = self.make_request(
  2098. "GET",
  2099. "/_matrix/client/v3/sync",
  2100. access_token=self.other_user_token,
  2101. )
  2102. self.assertEqual(401, channel.code, msg=channel.json_body)
  2103. self.assertEqual(Codes.USER_LOCKED, channel.json_body["errcode"])
  2104. self.assertTrue(channel.json_body["soft_logout"])
  2105. @override_config({"user_directory": {"enabled": True, "search_all_users": True}})
  2106. def test_locked_user_not_in_user_dir(self) -> None:
  2107. # User is available in the user dir
  2108. channel = self.make_request(
  2109. "POST",
  2110. "/_matrix/client/v3/user_directory/search",
  2111. {"search_term": self.other_user},
  2112. access_token=self.admin_user_tok,
  2113. )
  2114. self.assertEqual(200, channel.code, msg=channel.json_body)
  2115. self.assertIn("results", channel.json_body)
  2116. self.assertEqual(1, len(channel.json_body["results"]))
  2117. # Lock user
  2118. channel = self.make_request(
  2119. "PUT",
  2120. self.url_other_user,
  2121. access_token=self.admin_user_tok,
  2122. content={"locked": True},
  2123. )
  2124. # User is not available anymore in the user dir
  2125. channel = self.make_request(
  2126. "POST",
  2127. "/_matrix/client/v3/user_directory/search",
  2128. {"search_term": self.other_user},
  2129. access_token=self.admin_user_tok,
  2130. )
  2131. self.assertEqual(200, channel.code, msg=channel.json_body)
  2132. self.assertIn("results", channel.json_body)
  2133. self.assertEqual(0, len(channel.json_body["results"]))
  2134. @override_config(
  2135. {
  2136. "user_directory": {
  2137. "enabled": True,
  2138. "search_all_users": True,
  2139. "show_locked_users": True,
  2140. }
  2141. }
  2142. )
  2143. def test_locked_user_in_user_dir_with_show_locked_users_option(self) -> None:
  2144. # User is available in the user dir
  2145. channel = self.make_request(
  2146. "POST",
  2147. "/_matrix/client/v3/user_directory/search",
  2148. {"search_term": self.other_user},
  2149. access_token=self.admin_user_tok,
  2150. )
  2151. self.assertEqual(200, channel.code, msg=channel.json_body)
  2152. self.assertIn("results", channel.json_body)
  2153. self.assertEqual(1, len(channel.json_body["results"]))
  2154. # Lock user
  2155. channel = self.make_request(
  2156. "PUT",
  2157. self.url_other_user,
  2158. access_token=self.admin_user_tok,
  2159. content={"locked": True},
  2160. )
  2161. # User is still available in the user dir
  2162. channel = self.make_request(
  2163. "POST",
  2164. "/_matrix/client/v3/user_directory/search",
  2165. {"search_term": self.other_user},
  2166. access_token=self.admin_user_tok,
  2167. )
  2168. self.assertEqual(200, channel.code, msg=channel.json_body)
  2169. self.assertIn("results", channel.json_body)
  2170. self.assertEqual(1, len(channel.json_body["results"]))
  2171. @override_config({"user_directory": {"enabled": True, "search_all_users": True}})
  2172. def test_change_name_deactivate_user_user_directory(self) -> None:
  2173. """
  2174. Test change profile information of a deactivated user and
  2175. check that it does not appear in user directory
  2176. """
  2177. # is in user directory
  2178. profile = self.get_success(self.store._get_user_in_directory(self.other_user))
  2179. assert profile is not None
  2180. self.assertTrue(profile["display_name"] == "User")
  2181. # Deactivate user
  2182. channel = self.make_request(
  2183. "PUT",
  2184. self.url_other_user,
  2185. access_token=self.admin_user_tok,
  2186. content={"deactivated": True},
  2187. )
  2188. self.assertEqual(200, channel.code, msg=channel.json_body)
  2189. self.assertEqual("@user:test", channel.json_body["name"])
  2190. self.assertTrue(channel.json_body["deactivated"])
  2191. # is not in user directory
  2192. profile = self.get_success(self.store._get_user_in_directory(self.other_user))
  2193. self.assertIsNone(profile)
  2194. # Set new displayname user
  2195. channel = self.make_request(
  2196. "PUT",
  2197. self.url_other_user,
  2198. access_token=self.admin_user_tok,
  2199. content={"displayname": "Foobar"},
  2200. )
  2201. self.assertEqual(200, channel.code, msg=channel.json_body)
  2202. self.assertEqual("@user:test", channel.json_body["name"])
  2203. self.assertTrue(channel.json_body["deactivated"])
  2204. self.assertEqual("Foobar", channel.json_body["displayname"])
  2205. # is not in user directory
  2206. profile = self.get_success(self.store._get_user_in_directory(self.other_user))
  2207. self.assertIsNone(profile)
  2208. def test_reactivate_user(self) -> None:
  2209. """
  2210. Test reactivating another user.
  2211. """
  2212. # Deactivate the user.
  2213. self._deactivate_user("@user:test")
  2214. # Attempt to reactivate the user (without a password).
  2215. channel = self.make_request(
  2216. "PUT",
  2217. self.url_other_user,
  2218. access_token=self.admin_user_tok,
  2219. content={"deactivated": False},
  2220. )
  2221. self.assertEqual(400, channel.code, msg=channel.json_body)
  2222. # Reactivate the user.
  2223. channel = self.make_request(
  2224. "PUT",
  2225. self.url_other_user,
  2226. access_token=self.admin_user_tok,
  2227. content={"deactivated": False, "password": "foo"},
  2228. )
  2229. self.assertEqual(200, channel.code, msg=channel.json_body)
  2230. self.assertEqual("@user:test", channel.json_body["name"])
  2231. self.assertFalse(channel.json_body["deactivated"])
  2232. self._is_erased("@user:test", False)
  2233. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2234. self.assertNotIn("password_hash", channel.json_body)
  2235. @override_config({"password_config": {"localdb_enabled": False}})
  2236. def test_reactivate_user_localdb_disabled(self) -> None:
  2237. """
  2238. Test reactivating another user when using SSO.
  2239. """
  2240. # Deactivate the user.
  2241. self._deactivate_user("@user:test")
  2242. # Reactivate the user with a password
  2243. channel = self.make_request(
  2244. "PUT",
  2245. self.url_other_user,
  2246. access_token=self.admin_user_tok,
  2247. content={"deactivated": False, "password": "foo"},
  2248. )
  2249. self.assertEqual(403, channel.code, msg=channel.json_body)
  2250. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2251. # Reactivate the user without a password.
  2252. channel = self.make_request(
  2253. "PUT",
  2254. self.url_other_user,
  2255. access_token=self.admin_user_tok,
  2256. content={"deactivated": False},
  2257. )
  2258. self.assertEqual(200, channel.code, msg=channel.json_body)
  2259. self.assertEqual("@user:test", channel.json_body["name"])
  2260. self.assertFalse(channel.json_body["deactivated"])
  2261. self._is_erased("@user:test", False)
  2262. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2263. self.assertNotIn("password_hash", channel.json_body)
  2264. @override_config({"password_config": {"enabled": False}})
  2265. def test_reactivate_user_password_disabled(self) -> None:
  2266. """
  2267. Test reactivating another user when using SSO.
  2268. """
  2269. # Deactivate the user.
  2270. self._deactivate_user("@user:test")
  2271. # Reactivate the user with a password
  2272. channel = self.make_request(
  2273. "PUT",
  2274. self.url_other_user,
  2275. access_token=self.admin_user_tok,
  2276. content={"deactivated": False, "password": "foo"},
  2277. )
  2278. self.assertEqual(403, channel.code, msg=channel.json_body)
  2279. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2280. # Reactivate the user without a password.
  2281. channel = self.make_request(
  2282. "PUT",
  2283. self.url_other_user,
  2284. access_token=self.admin_user_tok,
  2285. content={"deactivated": False},
  2286. )
  2287. self.assertEqual(200, channel.code, msg=channel.json_body)
  2288. self.assertEqual("@user:test", channel.json_body["name"])
  2289. self.assertFalse(channel.json_body["deactivated"])
  2290. self._is_erased("@user:test", False)
  2291. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2292. self.assertNotIn("password_hash", channel.json_body)
  2293. def test_set_user_as_admin(self) -> None:
  2294. """
  2295. Test setting the admin flag on a user.
  2296. """
  2297. # Set a user as an admin
  2298. channel = self.make_request(
  2299. "PUT",
  2300. self.url_other_user,
  2301. access_token=self.admin_user_tok,
  2302. content={"admin": True},
  2303. )
  2304. self.assertEqual(200, channel.code, msg=channel.json_body)
  2305. self.assertEqual("@user:test", channel.json_body["name"])
  2306. self.assertTrue(channel.json_body["admin"])
  2307. # Get user
  2308. channel = self.make_request(
  2309. "GET",
  2310. self.url_other_user,
  2311. access_token=self.admin_user_tok,
  2312. )
  2313. self.assertEqual(200, channel.code, msg=channel.json_body)
  2314. self.assertEqual("@user:test", channel.json_body["name"])
  2315. self.assertTrue(channel.json_body["admin"])
  2316. def test_set_user_type(self) -> None:
  2317. """
  2318. Test changing user type.
  2319. """
  2320. # Set to support type
  2321. channel = self.make_request(
  2322. "PUT",
  2323. self.url_other_user,
  2324. access_token=self.admin_user_tok,
  2325. content={"user_type": UserTypes.SUPPORT},
  2326. )
  2327. self.assertEqual(200, channel.code, msg=channel.json_body)
  2328. self.assertEqual("@user:test", channel.json_body["name"])
  2329. self.assertEqual(UserTypes.SUPPORT, channel.json_body["user_type"])
  2330. # Get user
  2331. channel = self.make_request(
  2332. "GET",
  2333. self.url_other_user,
  2334. access_token=self.admin_user_tok,
  2335. )
  2336. self.assertEqual(200, channel.code, msg=channel.json_body)
  2337. self.assertEqual("@user:test", channel.json_body["name"])
  2338. self.assertEqual(UserTypes.SUPPORT, channel.json_body["user_type"])
  2339. # Change back to a regular user
  2340. channel = self.make_request(
  2341. "PUT",
  2342. self.url_other_user,
  2343. access_token=self.admin_user_tok,
  2344. content={"user_type": None},
  2345. )
  2346. self.assertEqual(200, channel.code, msg=channel.json_body)
  2347. self.assertEqual("@user:test", channel.json_body["name"])
  2348. self.assertIsNone(channel.json_body["user_type"])
  2349. # Get user
  2350. channel = self.make_request(
  2351. "GET",
  2352. self.url_other_user,
  2353. access_token=self.admin_user_tok,
  2354. )
  2355. self.assertEqual(200, channel.code, msg=channel.json_body)
  2356. self.assertEqual("@user:test", channel.json_body["name"])
  2357. self.assertIsNone(channel.json_body["user_type"])
  2358. def test_accidental_deactivation_prevention(self) -> None:
  2359. """
  2360. Ensure an account can't accidentally be deactivated by using a str value
  2361. for the deactivated body parameter
  2362. """
  2363. url = self.url_prefix % "@bob:test"
  2364. # Create user
  2365. channel = self.make_request(
  2366. "PUT",
  2367. url,
  2368. access_token=self.admin_user_tok,
  2369. content={"password": "abc123"},
  2370. )
  2371. self.assertEqual(201, channel.code, msg=channel.json_body)
  2372. self.assertEqual("@bob:test", channel.json_body["name"])
  2373. self.assertEqual("bob", channel.json_body["displayname"])
  2374. # Get user
  2375. channel = self.make_request(
  2376. "GET",
  2377. url,
  2378. access_token=self.admin_user_tok,
  2379. )
  2380. self.assertEqual(200, channel.code, msg=channel.json_body)
  2381. self.assertEqual("@bob:test", channel.json_body["name"])
  2382. self.assertEqual("bob", channel.json_body["displayname"])
  2383. self.assertEqual(0, channel.json_body["deactivated"])
  2384. # Change password (and use a str for deactivate instead of a bool)
  2385. channel = self.make_request(
  2386. "PUT",
  2387. url,
  2388. access_token=self.admin_user_tok,
  2389. content={"password": "abc123", "deactivated": "false"},
  2390. )
  2391. self.assertEqual(400, channel.code, msg=channel.json_body)
  2392. # Check user is not deactivated
  2393. channel = self.make_request(
  2394. "GET",
  2395. url,
  2396. access_token=self.admin_user_tok,
  2397. )
  2398. self.assertEqual(200, channel.code, msg=channel.json_body)
  2399. self.assertEqual("@bob:test", channel.json_body["name"])
  2400. self.assertEqual("bob", channel.json_body["displayname"])
  2401. # Ensure they're still alive
  2402. self.assertEqual(0, channel.json_body["deactivated"])
  2403. @override_config(
  2404. {
  2405. "experimental_features": {
  2406. "msc3866": {
  2407. "enabled": True,
  2408. "require_approval_for_new_accounts": True,
  2409. }
  2410. }
  2411. }
  2412. )
  2413. def test_approve_account(self) -> None:
  2414. """Tests that approving an account correctly sets the approved flag for the user."""
  2415. url = self.url_prefix % "@bob:test"
  2416. # Create the user using the client-server API since otherwise the user will be
  2417. # marked as approved automatically.
  2418. channel = self.make_request(
  2419. "POST",
  2420. "register",
  2421. {
  2422. "username": "bob",
  2423. "password": "test",
  2424. "auth": {"type": LoginType.DUMMY},
  2425. },
  2426. )
  2427. self.assertEqual(403, channel.code, channel.result)
  2428. self.assertEqual(Codes.USER_AWAITING_APPROVAL, channel.json_body["errcode"])
  2429. self.assertEqual(
  2430. ApprovalNoticeMedium.NONE, channel.json_body["approval_notice_medium"]
  2431. )
  2432. # Get user
  2433. channel = self.make_request(
  2434. "GET",
  2435. url,
  2436. access_token=self.admin_user_tok,
  2437. )
  2438. self.assertEqual(200, channel.code, msg=channel.json_body)
  2439. self.assertIs(False, channel.json_body["approved"])
  2440. # Approve user
  2441. channel = self.make_request(
  2442. "PUT",
  2443. url,
  2444. access_token=self.admin_user_tok,
  2445. content={"approved": True},
  2446. )
  2447. self.assertEqual(200, channel.code, msg=channel.json_body)
  2448. self.assertIs(True, channel.json_body["approved"])
  2449. # Check that the user is now approved
  2450. channel = self.make_request(
  2451. "GET",
  2452. url,
  2453. access_token=self.admin_user_tok,
  2454. )
  2455. self.assertEqual(200, channel.code, msg=channel.json_body)
  2456. self.assertIs(True, channel.json_body["approved"])
  2457. @override_config(
  2458. {
  2459. "experimental_features": {
  2460. "msc3866": {
  2461. "enabled": True,
  2462. "require_approval_for_new_accounts": True,
  2463. }
  2464. }
  2465. }
  2466. )
  2467. def test_register_approved(self) -> None:
  2468. url = self.url_prefix % "@bob:test"
  2469. # Create user
  2470. channel = self.make_request(
  2471. "PUT",
  2472. url,
  2473. access_token=self.admin_user_tok,
  2474. content={"password": "abc123", "approved": True},
  2475. )
  2476. self.assertEqual(201, channel.code, msg=channel.json_body)
  2477. self.assertEqual("@bob:test", channel.json_body["name"])
  2478. self.assertEqual(1, channel.json_body["approved"])
  2479. # Get user
  2480. channel = self.make_request(
  2481. "GET",
  2482. url,
  2483. access_token=self.admin_user_tok,
  2484. )
  2485. self.assertEqual(200, channel.code, msg=channel.json_body)
  2486. self.assertEqual("@bob:test", channel.json_body["name"])
  2487. self.assertEqual(1, channel.json_body["approved"])
  2488. def _is_erased(self, user_id: str, expect: bool) -> None:
  2489. """Assert that the user is erased or not"""
  2490. d = self.store.is_user_erased(user_id)
  2491. if expect:
  2492. self.assertTrue(self.get_success(d))
  2493. else:
  2494. self.assertFalse(self.get_success(d))
  2495. def _deactivate_user(self, user_id: str) -> None:
  2496. """Deactivate user and set as erased"""
  2497. # Deactivate the user.
  2498. channel = self.make_request(
  2499. "PUT",
  2500. self.url_prefix % urllib.parse.quote(user_id),
  2501. access_token=self.admin_user_tok,
  2502. content={"deactivated": True},
  2503. )
  2504. self.assertEqual(200, channel.code, msg=channel.json_body)
  2505. self.assertTrue(channel.json_body["deactivated"])
  2506. self._is_erased(user_id, False)
  2507. d = self.store.mark_user_erased(user_id)
  2508. self.assertIsNone(self.get_success(d))
  2509. self._is_erased(user_id, True)
  2510. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2511. self.assertNotIn("password_hash", channel.json_body)
  2512. def _check_fields(self, content: JsonDict) -> None:
  2513. """Checks that the expected user attributes are present in content
  2514. Args:
  2515. content: Content dictionary to check
  2516. """
  2517. self.assertIn("displayname", content)
  2518. self.assertIn("threepids", content)
  2519. self.assertIn("avatar_url", content)
  2520. self.assertIn("admin", content)
  2521. self.assertIn("deactivated", content)
  2522. self.assertIn("erased", content)
  2523. self.assertIn("shadow_banned", content)
  2524. self.assertIn("creation_ts", content)
  2525. self.assertIn("appservice_id", content)
  2526. self.assertIn("consent_server_notice_sent", content)
  2527. self.assertIn("consent_version", content)
  2528. self.assertIn("consent_ts", content)
  2529. self.assertIn("external_ids", content)
  2530. # This key was removed intentionally. Ensure it is not accidentally re-included.
  2531. self.assertNotIn("password_hash", content)
  2532. class UserMembershipRestTestCase(unittest.HomeserverTestCase):
  2533. servlets = [
  2534. synapse.rest.admin.register_servlets,
  2535. login.register_servlets,
  2536. room.register_servlets,
  2537. ]
  2538. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2539. self.admin_user = self.register_user("admin", "pass", admin=True)
  2540. self.admin_user_tok = self.login("admin", "pass")
  2541. self.other_user = self.register_user("user", "pass")
  2542. self.url = "/_synapse/admin/v1/users/%s/joined_rooms" % urllib.parse.quote(
  2543. self.other_user
  2544. )
  2545. def test_no_auth(self) -> None:
  2546. """
  2547. Try to list rooms of an user without authentication.
  2548. """
  2549. channel = self.make_request("GET", self.url, b"{}")
  2550. self.assertEqual(401, channel.code, msg=channel.json_body)
  2551. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2552. def test_requester_is_no_admin(self) -> None:
  2553. """
  2554. If the user is not a server admin, an error is returned.
  2555. """
  2556. other_user_token = self.login("user", "pass")
  2557. channel = self.make_request(
  2558. "GET",
  2559. self.url,
  2560. access_token=other_user_token,
  2561. )
  2562. self.assertEqual(403, channel.code, msg=channel.json_body)
  2563. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2564. def test_user_does_not_exist(self) -> None:
  2565. """
  2566. Tests that a lookup for a user that does not exist returns an empty list
  2567. """
  2568. url = "/_synapse/admin/v1/users/@unknown_person:test/joined_rooms"
  2569. channel = self.make_request(
  2570. "GET",
  2571. url,
  2572. access_token=self.admin_user_tok,
  2573. )
  2574. self.assertEqual(200, channel.code, msg=channel.json_body)
  2575. self.assertEqual(0, channel.json_body["total"])
  2576. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2577. def test_user_is_not_local(self) -> None:
  2578. """
  2579. Tests that a lookup for a user that is not a local and participates in no conversation returns an empty list
  2580. """
  2581. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/joined_rooms"
  2582. channel = self.make_request(
  2583. "GET",
  2584. url,
  2585. access_token=self.admin_user_tok,
  2586. )
  2587. self.assertEqual(200, channel.code, msg=channel.json_body)
  2588. self.assertEqual(0, channel.json_body["total"])
  2589. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2590. def test_no_memberships(self) -> None:
  2591. """
  2592. Tests that a normal lookup for rooms is successfully
  2593. if user has no memberships
  2594. """
  2595. # Get rooms
  2596. channel = self.make_request(
  2597. "GET",
  2598. self.url,
  2599. access_token=self.admin_user_tok,
  2600. )
  2601. self.assertEqual(200, channel.code, msg=channel.json_body)
  2602. self.assertEqual(0, channel.json_body["total"])
  2603. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  2604. def test_get_rooms(self) -> None:
  2605. """
  2606. Tests that a normal lookup for rooms is successfully
  2607. """
  2608. # Create rooms and join
  2609. other_user_tok = self.login("user", "pass")
  2610. number_rooms = 5
  2611. for _ in range(number_rooms):
  2612. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  2613. # Get rooms
  2614. channel = self.make_request(
  2615. "GET",
  2616. self.url,
  2617. access_token=self.admin_user_tok,
  2618. )
  2619. self.assertEqual(200, channel.code, msg=channel.json_body)
  2620. self.assertEqual(number_rooms, channel.json_body["total"])
  2621. self.assertEqual(number_rooms, len(channel.json_body["joined_rooms"]))
  2622. def test_get_rooms_with_nonlocal_user(self) -> None:
  2623. """
  2624. Tests that a normal lookup for rooms is successful with a non-local user
  2625. """
  2626. other_user_tok = self.login("user", "pass")
  2627. event_builder_factory = self.hs.get_event_builder_factory()
  2628. event_creation_handler = self.hs.get_event_creation_handler()
  2629. persistence = self.hs.get_storage_controllers().persistence
  2630. assert persistence is not None
  2631. # Create two rooms, one with a local user only and one with both a local
  2632. # and remote user.
  2633. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  2634. local_and_remote_room_id = self.helper.create_room_as(
  2635. self.other_user, tok=other_user_tok
  2636. )
  2637. # Add a remote user to the room.
  2638. builder = event_builder_factory.for_room_version(
  2639. RoomVersions.V1,
  2640. {
  2641. "type": "m.room.member",
  2642. "sender": "@joiner:remote_hs",
  2643. "state_key": "@joiner:remote_hs",
  2644. "room_id": local_and_remote_room_id,
  2645. "content": {"membership": "join"},
  2646. },
  2647. )
  2648. event, unpersisted_context = self.get_success(
  2649. event_creation_handler.create_new_client_event(builder)
  2650. )
  2651. context = self.get_success(unpersisted_context.persist(event))
  2652. self.get_success(persistence.persist_event(event, context))
  2653. # Now get rooms
  2654. url = "/_synapse/admin/v1/users/@joiner:remote_hs/joined_rooms"
  2655. channel = self.make_request(
  2656. "GET",
  2657. url,
  2658. access_token=self.admin_user_tok,
  2659. )
  2660. self.assertEqual(200, channel.code, msg=channel.json_body)
  2661. self.assertEqual(1, channel.json_body["total"])
  2662. self.assertEqual([local_and_remote_room_id], channel.json_body["joined_rooms"])
  2663. class PushersRestTestCase(unittest.HomeserverTestCase):
  2664. servlets = [
  2665. synapse.rest.admin.register_servlets,
  2666. login.register_servlets,
  2667. ]
  2668. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2669. self.store = hs.get_datastores().main
  2670. self.admin_user = self.register_user("admin", "pass", admin=True)
  2671. self.admin_user_tok = self.login("admin", "pass")
  2672. self.other_user = self.register_user("user", "pass")
  2673. self.url = "/_synapse/admin/v1/users/%s/pushers" % urllib.parse.quote(
  2674. self.other_user
  2675. )
  2676. def test_no_auth(self) -> None:
  2677. """
  2678. Try to list pushers of an user without authentication.
  2679. """
  2680. channel = self.make_request("GET", self.url, b"{}")
  2681. self.assertEqual(401, channel.code, msg=channel.json_body)
  2682. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2683. def test_requester_is_no_admin(self) -> None:
  2684. """
  2685. If the user is not a server admin, an error is returned.
  2686. """
  2687. other_user_token = self.login("user", "pass")
  2688. channel = self.make_request(
  2689. "GET",
  2690. self.url,
  2691. access_token=other_user_token,
  2692. )
  2693. self.assertEqual(403, channel.code, msg=channel.json_body)
  2694. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2695. def test_user_does_not_exist(self) -> None:
  2696. """
  2697. Tests that a lookup for a user that does not exist returns a 404
  2698. """
  2699. url = "/_synapse/admin/v1/users/@unknown_person:test/pushers"
  2700. channel = self.make_request(
  2701. "GET",
  2702. url,
  2703. access_token=self.admin_user_tok,
  2704. )
  2705. self.assertEqual(404, channel.code, msg=channel.json_body)
  2706. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2707. def test_user_is_not_local(self) -> None:
  2708. """
  2709. Tests that a lookup for a user that is not a local returns a 400
  2710. """
  2711. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/pushers"
  2712. channel = self.make_request(
  2713. "GET",
  2714. url,
  2715. access_token=self.admin_user_tok,
  2716. )
  2717. self.assertEqual(400, channel.code, msg=channel.json_body)
  2718. self.assertEqual("Can only look up local users", channel.json_body["error"])
  2719. def test_get_pushers(self) -> None:
  2720. """
  2721. Tests that a normal lookup for pushers is successfully
  2722. """
  2723. # Get pushers
  2724. channel = self.make_request(
  2725. "GET",
  2726. self.url,
  2727. access_token=self.admin_user_tok,
  2728. )
  2729. self.assertEqual(200, channel.code, msg=channel.json_body)
  2730. self.assertEqual(0, channel.json_body["total"])
  2731. # Register the pusher
  2732. other_user_token = self.login("user", "pass")
  2733. user_tuple = self.get_success(
  2734. self.store.get_user_by_access_token(other_user_token)
  2735. )
  2736. assert user_tuple is not None
  2737. device_id = user_tuple.device_id
  2738. self.get_success(
  2739. self.hs.get_pusherpool().add_or_update_pusher(
  2740. user_id=self.other_user,
  2741. device_id=device_id,
  2742. kind="http",
  2743. app_id="m.http",
  2744. app_display_name="HTTP Push Notifications",
  2745. device_display_name="pushy push",
  2746. pushkey="a@example.com",
  2747. lang=None,
  2748. data={"url": "https://example.com/_matrix/push/v1/notify"},
  2749. )
  2750. )
  2751. # Get pushers
  2752. channel = self.make_request(
  2753. "GET",
  2754. self.url,
  2755. access_token=self.admin_user_tok,
  2756. )
  2757. self.assertEqual(200, channel.code, msg=channel.json_body)
  2758. self.assertEqual(1, channel.json_body["total"])
  2759. for p in channel.json_body["pushers"]:
  2760. self.assertIn("pushkey", p)
  2761. self.assertIn("kind", p)
  2762. self.assertIn("app_id", p)
  2763. self.assertIn("app_display_name", p)
  2764. self.assertIn("device_display_name", p)
  2765. self.assertIn("profile_tag", p)
  2766. self.assertIn("lang", p)
  2767. self.assertIn("url", p["data"])
  2768. class UserMediaRestTestCase(unittest.HomeserverTestCase):
  2769. servlets = [
  2770. synapse.rest.admin.register_servlets,
  2771. login.register_servlets,
  2772. ]
  2773. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  2774. self.store = hs.get_datastores().main
  2775. self.media_repo = hs.get_media_repository_resource()
  2776. self.filepaths = MediaFilePaths(hs.config.media.media_store_path)
  2777. self.admin_user = self.register_user("admin", "pass", admin=True)
  2778. self.admin_user_tok = self.login("admin", "pass")
  2779. self.other_user = self.register_user("user", "pass")
  2780. self.url = "/_synapse/admin/v1/users/%s/media" % urllib.parse.quote(
  2781. self.other_user
  2782. )
  2783. @parameterized.expand(["GET", "DELETE"])
  2784. def test_no_auth(self, method: str) -> None:
  2785. """Try to list media of an user without authentication."""
  2786. channel = self.make_request(method, self.url, {})
  2787. self.assertEqual(401, channel.code, msg=channel.json_body)
  2788. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2789. @parameterized.expand(["GET", "DELETE"])
  2790. def test_requester_is_no_admin(self, method: str) -> None:
  2791. """If the user is not a server admin, an error is returned."""
  2792. other_user_token = self.login("user", "pass")
  2793. channel = self.make_request(
  2794. method,
  2795. self.url,
  2796. access_token=other_user_token,
  2797. )
  2798. self.assertEqual(403, channel.code, msg=channel.json_body)
  2799. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2800. @parameterized.expand(["GET", "DELETE"])
  2801. def test_user_does_not_exist(self, method: str) -> None:
  2802. """Tests that a lookup for a user that does not exist returns a 404"""
  2803. url = "/_synapse/admin/v1/users/@unknown_person:test/media"
  2804. channel = self.make_request(
  2805. method,
  2806. url,
  2807. access_token=self.admin_user_tok,
  2808. )
  2809. self.assertEqual(404, channel.code, msg=channel.json_body)
  2810. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2811. @parameterized.expand(["GET", "DELETE"])
  2812. def test_user_is_not_local(self, method: str) -> None:
  2813. """Tests that a lookup for a user that is not a local returns a 400"""
  2814. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/media"
  2815. channel = self.make_request(
  2816. method,
  2817. url,
  2818. access_token=self.admin_user_tok,
  2819. )
  2820. self.assertEqual(400, channel.code, msg=channel.json_body)
  2821. self.assertEqual("Can only look up local users", channel.json_body["error"])
  2822. def test_limit_GET(self) -> None:
  2823. """Testing list of media with limit"""
  2824. number_media = 20
  2825. other_user_tok = self.login("user", "pass")
  2826. self._create_media_for_user(other_user_tok, number_media)
  2827. channel = self.make_request(
  2828. "GET",
  2829. self.url + "?limit=5",
  2830. access_token=self.admin_user_tok,
  2831. )
  2832. self.assertEqual(200, channel.code, msg=channel.json_body)
  2833. self.assertEqual(channel.json_body["total"], number_media)
  2834. self.assertEqual(len(channel.json_body["media"]), 5)
  2835. self.assertEqual(channel.json_body["next_token"], 5)
  2836. self._check_fields(channel.json_body["media"])
  2837. def test_limit_DELETE(self) -> None:
  2838. """Testing delete of media with limit"""
  2839. number_media = 20
  2840. other_user_tok = self.login("user", "pass")
  2841. self._create_media_for_user(other_user_tok, number_media)
  2842. channel = self.make_request(
  2843. "DELETE",
  2844. self.url + "?limit=5",
  2845. access_token=self.admin_user_tok,
  2846. )
  2847. self.assertEqual(200, channel.code, msg=channel.json_body)
  2848. self.assertEqual(channel.json_body["total"], 5)
  2849. self.assertEqual(len(channel.json_body["deleted_media"]), 5)
  2850. def test_from_GET(self) -> None:
  2851. """Testing list of media with a defined starting point (from)"""
  2852. number_media = 20
  2853. other_user_tok = self.login("user", "pass")
  2854. self._create_media_for_user(other_user_tok, number_media)
  2855. channel = self.make_request(
  2856. "GET",
  2857. self.url + "?from=5",
  2858. access_token=self.admin_user_tok,
  2859. )
  2860. self.assertEqual(200, channel.code, msg=channel.json_body)
  2861. self.assertEqual(channel.json_body["total"], number_media)
  2862. self.assertEqual(len(channel.json_body["media"]), 15)
  2863. self.assertNotIn("next_token", channel.json_body)
  2864. self._check_fields(channel.json_body["media"])
  2865. def test_from_DELETE(self) -> None:
  2866. """Testing delete of media with a defined starting point (from)"""
  2867. number_media = 20
  2868. other_user_tok = self.login("user", "pass")
  2869. self._create_media_for_user(other_user_tok, number_media)
  2870. channel = self.make_request(
  2871. "DELETE",
  2872. self.url + "?from=5",
  2873. access_token=self.admin_user_tok,
  2874. )
  2875. self.assertEqual(200, channel.code, msg=channel.json_body)
  2876. self.assertEqual(channel.json_body["total"], 15)
  2877. self.assertEqual(len(channel.json_body["deleted_media"]), 15)
  2878. def test_limit_and_from_GET(self) -> None:
  2879. """Testing list of media with a defined starting point and limit"""
  2880. number_media = 20
  2881. other_user_tok = self.login("user", "pass")
  2882. self._create_media_for_user(other_user_tok, number_media)
  2883. channel = self.make_request(
  2884. "GET",
  2885. self.url + "?from=5&limit=10",
  2886. access_token=self.admin_user_tok,
  2887. )
  2888. self.assertEqual(200, channel.code, msg=channel.json_body)
  2889. self.assertEqual(channel.json_body["total"], number_media)
  2890. self.assertEqual(channel.json_body["next_token"], 15)
  2891. self.assertEqual(len(channel.json_body["media"]), 10)
  2892. self._check_fields(channel.json_body["media"])
  2893. def test_limit_and_from_DELETE(self) -> None:
  2894. """Testing delete of media with a defined starting point and limit"""
  2895. number_media = 20
  2896. other_user_tok = self.login("user", "pass")
  2897. self._create_media_for_user(other_user_tok, number_media)
  2898. channel = self.make_request(
  2899. "DELETE",
  2900. self.url + "?from=5&limit=10",
  2901. access_token=self.admin_user_tok,
  2902. )
  2903. self.assertEqual(200, channel.code, msg=channel.json_body)
  2904. self.assertEqual(channel.json_body["total"], 10)
  2905. self.assertEqual(len(channel.json_body["deleted_media"]), 10)
  2906. @parameterized.expand(["GET", "DELETE"])
  2907. def test_invalid_parameter(self, method: str) -> None:
  2908. """If parameters are invalid, an error is returned."""
  2909. # unkown order_by
  2910. channel = self.make_request(
  2911. method,
  2912. self.url + "?order_by=bar",
  2913. access_token=self.admin_user_tok,
  2914. )
  2915. self.assertEqual(400, channel.code, msg=channel.json_body)
  2916. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2917. # invalid search order
  2918. channel = self.make_request(
  2919. method,
  2920. self.url + "?dir=bar",
  2921. access_token=self.admin_user_tok,
  2922. )
  2923. self.assertEqual(400, channel.code, msg=channel.json_body)
  2924. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2925. # negative limit
  2926. channel = self.make_request(
  2927. method,
  2928. self.url + "?limit=-5",
  2929. access_token=self.admin_user_tok,
  2930. )
  2931. self.assertEqual(400, channel.code, msg=channel.json_body)
  2932. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2933. # negative from
  2934. channel = self.make_request(
  2935. method,
  2936. self.url + "?from=-5",
  2937. access_token=self.admin_user_tok,
  2938. )
  2939. self.assertEqual(400, channel.code, msg=channel.json_body)
  2940. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2941. def test_next_token(self) -> None:
  2942. """
  2943. Testing that `next_token` appears at the right place
  2944. For deleting media `next_token` is not useful, because
  2945. after deleting media the media has a new order.
  2946. """
  2947. number_media = 20
  2948. other_user_tok = self.login("user", "pass")
  2949. self._create_media_for_user(other_user_tok, number_media)
  2950. # `next_token` does not appear
  2951. # Number of results is the number of entries
  2952. channel = self.make_request(
  2953. "GET",
  2954. self.url + "?limit=20",
  2955. access_token=self.admin_user_tok,
  2956. )
  2957. self.assertEqual(200, channel.code, msg=channel.json_body)
  2958. self.assertEqual(channel.json_body["total"], number_media)
  2959. self.assertEqual(len(channel.json_body["media"]), number_media)
  2960. self.assertNotIn("next_token", channel.json_body)
  2961. # `next_token` does not appear
  2962. # Number of max results is larger than the number of entries
  2963. channel = self.make_request(
  2964. "GET",
  2965. self.url + "?limit=21",
  2966. access_token=self.admin_user_tok,
  2967. )
  2968. self.assertEqual(200, channel.code, msg=channel.json_body)
  2969. self.assertEqual(channel.json_body["total"], number_media)
  2970. self.assertEqual(len(channel.json_body["media"]), number_media)
  2971. self.assertNotIn("next_token", channel.json_body)
  2972. # `next_token` does appear
  2973. # Number of max results is smaller than the number of entries
  2974. channel = self.make_request(
  2975. "GET",
  2976. self.url + "?limit=19",
  2977. access_token=self.admin_user_tok,
  2978. )
  2979. self.assertEqual(200, channel.code, msg=channel.json_body)
  2980. self.assertEqual(channel.json_body["total"], number_media)
  2981. self.assertEqual(len(channel.json_body["media"]), 19)
  2982. self.assertEqual(channel.json_body["next_token"], 19)
  2983. # Check
  2984. # Set `from` to value of `next_token` for request remaining entries
  2985. # `next_token` does not appear
  2986. channel = self.make_request(
  2987. "GET",
  2988. self.url + "?from=19",
  2989. access_token=self.admin_user_tok,
  2990. )
  2991. self.assertEqual(200, channel.code, msg=channel.json_body)
  2992. self.assertEqual(channel.json_body["total"], number_media)
  2993. self.assertEqual(len(channel.json_body["media"]), 1)
  2994. self.assertNotIn("next_token", channel.json_body)
  2995. def test_user_has_no_media_GET(self) -> None:
  2996. """
  2997. Tests that a normal lookup for media is successfully
  2998. if user has no media created
  2999. """
  3000. channel = self.make_request(
  3001. "GET",
  3002. self.url,
  3003. access_token=self.admin_user_tok,
  3004. )
  3005. self.assertEqual(200, channel.code, msg=channel.json_body)
  3006. self.assertEqual(0, channel.json_body["total"])
  3007. self.assertEqual(0, len(channel.json_body["media"]))
  3008. def test_user_has_no_media_DELETE(self) -> None:
  3009. """
  3010. Tests that a delete is successful if user has no media
  3011. """
  3012. channel = self.make_request(
  3013. "DELETE",
  3014. self.url,
  3015. access_token=self.admin_user_tok,
  3016. )
  3017. self.assertEqual(200, channel.code, msg=channel.json_body)
  3018. self.assertEqual(0, channel.json_body["total"])
  3019. self.assertEqual(0, len(channel.json_body["deleted_media"]))
  3020. def test_get_media(self) -> None:
  3021. """Tests that a normal lookup for media is successful"""
  3022. number_media = 5
  3023. other_user_tok = self.login("user", "pass")
  3024. self._create_media_for_user(other_user_tok, number_media)
  3025. channel = self.make_request(
  3026. "GET",
  3027. self.url,
  3028. access_token=self.admin_user_tok,
  3029. )
  3030. self.assertEqual(200, channel.code, msg=channel.json_body)
  3031. self.assertEqual(number_media, channel.json_body["total"])
  3032. self.assertEqual(number_media, len(channel.json_body["media"]))
  3033. self.assertNotIn("next_token", channel.json_body)
  3034. self._check_fields(channel.json_body["media"])
  3035. def test_delete_media(self) -> None:
  3036. """Tests that a normal delete of media is successful"""
  3037. number_media = 5
  3038. other_user_tok = self.login("user", "pass")
  3039. media_ids = self._create_media_for_user(other_user_tok, number_media)
  3040. # Test if the file exists
  3041. local_paths = []
  3042. for media_id in media_ids:
  3043. local_path = self.filepaths.local_media_filepath(media_id)
  3044. self.assertTrue(os.path.exists(local_path))
  3045. local_paths.append(local_path)
  3046. channel = self.make_request(
  3047. "DELETE",
  3048. self.url,
  3049. access_token=self.admin_user_tok,
  3050. )
  3051. self.assertEqual(200, channel.code, msg=channel.json_body)
  3052. self.assertEqual(number_media, channel.json_body["total"])
  3053. self.assertEqual(number_media, len(channel.json_body["deleted_media"]))
  3054. self.assertCountEqual(channel.json_body["deleted_media"], media_ids)
  3055. # Test if the file is deleted
  3056. for local_path in local_paths:
  3057. self.assertFalse(os.path.exists(local_path))
  3058. def test_order_by(self) -> None:
  3059. """
  3060. Testing order list with parameter `order_by`
  3061. """
  3062. other_user_tok = self.login("user", "pass")
  3063. # Resolution: 1×1, MIME type: image/png, Extension: png, Size: 67 B
  3064. image_data1 = SMALL_PNG
  3065. # Resolution: 1×1, MIME type: image/gif, Extension: gif, Size: 35 B
  3066. image_data2 = unhexlify(
  3067. b"47494638376101000100800100000000"
  3068. b"ffffff2c00000000010001000002024c"
  3069. b"01003b"
  3070. )
  3071. # Resolution: 1×1, MIME type: image/bmp, Extension: bmp, Size: 54 B
  3072. image_data3 = unhexlify(
  3073. b"424d3a0000000000000036000000280000000100000001000000"
  3074. b"0100180000000000040000000000000000000000000000000000"
  3075. b"0000"
  3076. )
  3077. # create media and make sure they do not have the same timestamp
  3078. media1 = self._create_media_and_access(other_user_tok, image_data1, "image.png")
  3079. self.pump(1.0)
  3080. media2 = self._create_media_and_access(other_user_tok, image_data2, "image.gif")
  3081. self.pump(1.0)
  3082. media3 = self._create_media_and_access(other_user_tok, image_data3, "image.bmp")
  3083. self.pump(1.0)
  3084. # Mark one media as safe from quarantine.
  3085. self.get_success(self.store.mark_local_media_as_safe(media2))
  3086. # Quarantine one media
  3087. self.get_success(
  3088. self.store.quarantine_media_by_id("test", media3, self.admin_user)
  3089. )
  3090. # order by default ("created_ts")
  3091. # default is backwards
  3092. self._order_test([media3, media2, media1], None)
  3093. self._order_test([media1, media2, media3], None, "f")
  3094. self._order_test([media3, media2, media1], None, "b")
  3095. # sort by media_id
  3096. sorted_media = sorted([media1, media2, media3], reverse=False)
  3097. sorted_media_reverse = sorted(sorted_media, reverse=True)
  3098. # order by media_id
  3099. self._order_test(sorted_media, "media_id")
  3100. self._order_test(sorted_media, "media_id", "f")
  3101. self._order_test(sorted_media_reverse, "media_id", "b")
  3102. # order by upload_name
  3103. self._order_test([media3, media2, media1], "upload_name")
  3104. self._order_test([media3, media2, media1], "upload_name", "f")
  3105. self._order_test([media1, media2, media3], "upload_name", "b")
  3106. # order by media_type
  3107. # result is ordered by media_id
  3108. # because of uploaded media_type is always 'application/json'
  3109. self._order_test(sorted_media, "media_type")
  3110. self._order_test(sorted_media, "media_type", "f")
  3111. self._order_test(sorted_media, "media_type", "b")
  3112. # order by media_length
  3113. self._order_test([media2, media3, media1], "media_length")
  3114. self._order_test([media2, media3, media1], "media_length", "f")
  3115. self._order_test([media1, media3, media2], "media_length", "b")
  3116. # order by created_ts
  3117. self._order_test([media1, media2, media3], "created_ts")
  3118. self._order_test([media1, media2, media3], "created_ts", "f")
  3119. self._order_test([media3, media2, media1], "created_ts", "b")
  3120. # order by last_access_ts
  3121. self._order_test([media1, media2, media3], "last_access_ts")
  3122. self._order_test([media1, media2, media3], "last_access_ts", "f")
  3123. self._order_test([media3, media2, media1], "last_access_ts", "b")
  3124. # order by quarantined_by
  3125. # one media is in quarantine, others are ordered by media_ids
  3126. # Different sort order of SQlite and PostreSQL
  3127. # If a media is not in quarantine `quarantined_by` is NULL
  3128. # SQLite considers NULL to be smaller than any other value.
  3129. # PostreSQL considers NULL to be larger than any other value.
  3130. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by")
  3131. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by", "f")
  3132. # self._order_test([media3] + sorted([media1, media2]), "quarantined_by", "b")
  3133. # order by safe_from_quarantine
  3134. # one media is safe from quarantine, others are ordered by media_ids
  3135. self._order_test(sorted([media1, media3]) + [media2], "safe_from_quarantine")
  3136. self._order_test(
  3137. sorted([media1, media3]) + [media2], "safe_from_quarantine", "f"
  3138. )
  3139. self._order_test(
  3140. [media2] + sorted([media1, media3]), "safe_from_quarantine", "b"
  3141. )
  3142. def _create_media_for_user(self, user_token: str, number_media: int) -> List[str]:
  3143. """
  3144. Create a number of media for a specific user
  3145. Args:
  3146. user_token: Access token of the user
  3147. number_media: Number of media to be created for the user
  3148. Returns:
  3149. List of created media ID
  3150. """
  3151. media_ids = []
  3152. for _ in range(number_media):
  3153. media_ids.append(self._create_media_and_access(user_token, SMALL_PNG))
  3154. return media_ids
  3155. def _create_media_and_access(
  3156. self,
  3157. user_token: str,
  3158. image_data: bytes,
  3159. filename: str = "image1.png",
  3160. ) -> str:
  3161. """
  3162. Create one media for a specific user, access and returns `media_id`
  3163. Args:
  3164. user_token: Access token of the user
  3165. image_data: binary data of image
  3166. filename: The filename of the media to be uploaded
  3167. Returns:
  3168. The ID of the newly created media.
  3169. """
  3170. upload_resource = self.media_repo.children[b"upload"]
  3171. download_resource = self.media_repo.children[b"download"]
  3172. # Upload some media into the room
  3173. response = self.helper.upload_media(
  3174. upload_resource, image_data, user_token, filename, expect_code=200
  3175. )
  3176. # Extract media ID from the response
  3177. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  3178. media_id = server_and_media_id.split("/")[1]
  3179. # Try to access a media and to create `last_access_ts`
  3180. channel = make_request(
  3181. self.reactor,
  3182. FakeSite(download_resource, self.reactor),
  3183. "GET",
  3184. server_and_media_id,
  3185. shorthand=False,
  3186. access_token=user_token,
  3187. )
  3188. self.assertEqual(
  3189. 200,
  3190. channel.code,
  3191. msg=(
  3192. f"Expected to receive a 200 on accessing media: {server_and_media_id}"
  3193. ),
  3194. )
  3195. return media_id
  3196. def _check_fields(self, content: List[JsonDict]) -> None:
  3197. """Checks that the expected user attributes are present in content
  3198. Args:
  3199. content: List that is checked for content
  3200. """
  3201. for m in content:
  3202. self.assertIn("media_id", m)
  3203. self.assertIn("media_type", m)
  3204. self.assertIn("media_length", m)
  3205. self.assertIn("upload_name", m)
  3206. self.assertIn("created_ts", m)
  3207. self.assertIn("last_access_ts", m)
  3208. self.assertIn("quarantined_by", m)
  3209. self.assertIn("safe_from_quarantine", m)
  3210. def _order_test(
  3211. self,
  3212. expected_media_list: List[str],
  3213. order_by: Optional[str],
  3214. dir: Optional[str] = None,
  3215. ) -> None:
  3216. """Request the list of media in a certain order. Assert that order is what
  3217. we expect
  3218. Args:
  3219. expected_media_list: The list of media_ids in the order we expect to get
  3220. back from the server
  3221. order_by: The type of ordering to give the server
  3222. dir: The direction of ordering to give the server
  3223. """
  3224. url = self.url + "?"
  3225. if order_by is not None:
  3226. url += f"order_by={order_by}&"
  3227. if dir is not None and dir in ("b", "f"):
  3228. url += f"dir={dir}"
  3229. channel = self.make_request(
  3230. "GET",
  3231. url,
  3232. access_token=self.admin_user_tok,
  3233. )
  3234. self.assertEqual(200, channel.code, msg=channel.json_body)
  3235. self.assertEqual(channel.json_body["total"], len(expected_media_list))
  3236. returned_order = [row["media_id"] for row in channel.json_body["media"]]
  3237. self.assertEqual(expected_media_list, returned_order)
  3238. self._check_fields(channel.json_body["media"])
  3239. class UserTokenRestTestCase(unittest.HomeserverTestCase):
  3240. """Test for /_synapse/admin/v1/users/<user>/login"""
  3241. servlets = [
  3242. synapse.rest.admin.register_servlets,
  3243. login.register_servlets,
  3244. sync.register_servlets,
  3245. room.register_servlets,
  3246. devices.register_servlets,
  3247. logout.register_servlets,
  3248. ]
  3249. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3250. self.store = hs.get_datastores().main
  3251. self.admin_user = self.register_user("admin", "pass", admin=True)
  3252. self.admin_user_tok = self.login("admin", "pass")
  3253. self.other_user = self.register_user("user", "pass")
  3254. self.other_user_tok = self.login("user", "pass")
  3255. self.url = "/_synapse/admin/v1/users/%s/login" % urllib.parse.quote(
  3256. self.other_user
  3257. )
  3258. def _get_token(self) -> str:
  3259. channel = self.make_request(
  3260. "POST", self.url, b"{}", access_token=self.admin_user_tok
  3261. )
  3262. self.assertEqual(200, channel.code, msg=channel.json_body)
  3263. return channel.json_body["access_token"]
  3264. def test_no_auth(self) -> None:
  3265. """Try to login as a user without authentication."""
  3266. channel = self.make_request("POST", self.url, b"{}")
  3267. self.assertEqual(401, channel.code, msg=channel.json_body)
  3268. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3269. def test_not_admin(self) -> None:
  3270. """Try to login as a user as a non-admin user."""
  3271. channel = self.make_request(
  3272. "POST", self.url, b"{}", access_token=self.other_user_tok
  3273. )
  3274. self.assertEqual(403, channel.code, msg=channel.json_body)
  3275. def test_send_event(self) -> None:
  3276. """Test that sending event as a user works."""
  3277. # Create a room.
  3278. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  3279. # Login in as the user
  3280. puppet_token = self._get_token()
  3281. # Test that sending works, and generates the event as the right user.
  3282. resp = self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  3283. event_id = resp["event_id"]
  3284. event = self.get_success(self.store.get_event(event_id))
  3285. self.assertEqual(event.sender, self.other_user)
  3286. def test_devices(self) -> None:
  3287. """Tests that logging in as a user doesn't create a new device for them."""
  3288. # Login in as the user
  3289. self._get_token()
  3290. # Check that we don't see a new device in our devices list
  3291. channel = self.make_request(
  3292. "GET", "devices", b"{}", access_token=self.other_user_tok
  3293. )
  3294. self.assertEqual(200, channel.code, msg=channel.json_body)
  3295. # We should only see the one device (from the login in `prepare`)
  3296. self.assertEqual(len(channel.json_body["devices"]), 1)
  3297. def test_logout(self) -> None:
  3298. """Test that calling `/logout` with the token works."""
  3299. # Login in as the user
  3300. puppet_token = self._get_token()
  3301. # Test that we can successfully make a request
  3302. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3303. self.assertEqual(200, channel.code, msg=channel.json_body)
  3304. # Logout with the puppet token
  3305. channel = self.make_request("POST", "logout", b"{}", access_token=puppet_token)
  3306. self.assertEqual(200, channel.code, msg=channel.json_body)
  3307. # The puppet token should no longer work
  3308. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3309. self.assertEqual(401, channel.code, msg=channel.json_body)
  3310. # .. but the real user's tokens should still work
  3311. channel = self.make_request(
  3312. "GET", "devices", b"{}", access_token=self.other_user_tok
  3313. )
  3314. self.assertEqual(200, channel.code, msg=channel.json_body)
  3315. def test_user_logout_all(self) -> None:
  3316. """Tests that the target user calling `/logout/all` does *not* expire
  3317. the token.
  3318. """
  3319. # Login in as the user
  3320. puppet_token = self._get_token()
  3321. # Test that we can successfully make a request
  3322. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3323. self.assertEqual(200, channel.code, msg=channel.json_body)
  3324. # Logout all with the real user token
  3325. channel = self.make_request(
  3326. "POST", "logout/all", b"{}", access_token=self.other_user_tok
  3327. )
  3328. self.assertEqual(200, channel.code, msg=channel.json_body)
  3329. # The puppet token should still work
  3330. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3331. self.assertEqual(200, channel.code, msg=channel.json_body)
  3332. # .. but the real user's tokens shouldn't
  3333. channel = self.make_request(
  3334. "GET", "devices", b"{}", access_token=self.other_user_tok
  3335. )
  3336. self.assertEqual(401, channel.code, msg=channel.json_body)
  3337. def test_admin_logout_all(self) -> None:
  3338. """Tests that the admin user calling `/logout/all` does expire the
  3339. token.
  3340. """
  3341. # Login in as the user
  3342. puppet_token = self._get_token()
  3343. # Test that we can successfully make a request
  3344. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3345. self.assertEqual(200, channel.code, msg=channel.json_body)
  3346. # Logout all with the admin user token
  3347. channel = self.make_request(
  3348. "POST", "logout/all", b"{}", access_token=self.admin_user_tok
  3349. )
  3350. self.assertEqual(200, channel.code, msg=channel.json_body)
  3351. # The puppet token should no longer work
  3352. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  3353. self.assertEqual(401, channel.code, msg=channel.json_body)
  3354. # .. but the real user's tokens should still work
  3355. channel = self.make_request(
  3356. "GET", "devices", b"{}", access_token=self.other_user_tok
  3357. )
  3358. self.assertEqual(200, channel.code, msg=channel.json_body)
  3359. @unittest.override_config(
  3360. {
  3361. "public_baseurl": "https://example.org/",
  3362. "user_consent": {
  3363. "version": "1.0",
  3364. "policy_name": "My Cool Privacy Policy",
  3365. "template_dir": "/",
  3366. "require_at_registration": True,
  3367. "block_events_error": "You should accept the policy",
  3368. },
  3369. "form_secret": "123secret",
  3370. }
  3371. )
  3372. def test_consent(self) -> None:
  3373. """Test that sending a message is not subject to the privacy policies."""
  3374. # Have the admin user accept the terms.
  3375. self.get_success(self.store.user_set_consent_version(self.admin_user, "1.0"))
  3376. # First, cheekily accept the terms and create a room
  3377. self.get_success(self.store.user_set_consent_version(self.other_user, "1.0"))
  3378. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  3379. self.helper.send_event(room_id, "com.example.test", tok=self.other_user_tok)
  3380. # Now unaccept it and check that we can't send an event
  3381. self.get_success(self.store.user_set_consent_version(self.other_user, "0.0"))
  3382. self.helper.send_event(
  3383. room_id,
  3384. "com.example.test",
  3385. tok=self.other_user_tok,
  3386. expect_code=403,
  3387. )
  3388. # Login in as the user
  3389. puppet_token = self._get_token()
  3390. # Sending an event on their behalf should work fine
  3391. self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  3392. @override_config(
  3393. {"limit_usage_by_mau": True, "max_mau_value": 1, "mau_trial_days": 0}
  3394. )
  3395. def test_mau_limit(self) -> None:
  3396. # Create a room as the admin user. This will bump the monthly active users to 1.
  3397. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  3398. # Trying to join as the other user should fail due to reaching MAU limit.
  3399. self.helper.join(
  3400. room_id,
  3401. user=self.other_user,
  3402. tok=self.other_user_tok,
  3403. expect_code=403,
  3404. )
  3405. # Logging in as the other user and joining a room should work, even
  3406. # though the MAU limit would stop the user doing so.
  3407. puppet_token = self._get_token()
  3408. self.helper.join(room_id, user=self.other_user, tok=puppet_token)
  3409. @parameterized_class(
  3410. ("url_prefix",),
  3411. [
  3412. ("/_synapse/admin/v1/whois/%s",),
  3413. ("/_matrix/client/r0/admin/whois/%s",),
  3414. ],
  3415. )
  3416. class WhoisRestTestCase(unittest.HomeserverTestCase):
  3417. servlets = [
  3418. synapse.rest.admin.register_servlets,
  3419. login.register_servlets,
  3420. ]
  3421. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3422. self.admin_user = self.register_user("admin", "pass", admin=True)
  3423. self.admin_user_tok = self.login("admin", "pass")
  3424. self.other_user = self.register_user("user", "pass")
  3425. self.url = self.url_prefix % self.other_user # type: ignore[attr-defined]
  3426. def test_no_auth(self) -> None:
  3427. """
  3428. Try to get information of an user without authentication.
  3429. """
  3430. channel = self.make_request("GET", self.url, b"{}")
  3431. self.assertEqual(401, channel.code, msg=channel.json_body)
  3432. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3433. def test_requester_is_not_admin(self) -> None:
  3434. """
  3435. If the user is not a server admin, an error is returned.
  3436. """
  3437. self.register_user("user2", "pass")
  3438. other_user2_token = self.login("user2", "pass")
  3439. channel = self.make_request(
  3440. "GET",
  3441. self.url,
  3442. access_token=other_user2_token,
  3443. )
  3444. self.assertEqual(403, channel.code, msg=channel.json_body)
  3445. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3446. def test_user_is_not_local(self) -> None:
  3447. """
  3448. Tests that a lookup for a user that is not a local returns a 400
  3449. """
  3450. url = self.url_prefix % "@unknown_person:unknown_domain" # type: ignore[attr-defined]
  3451. channel = self.make_request(
  3452. "GET",
  3453. url,
  3454. access_token=self.admin_user_tok,
  3455. )
  3456. self.assertEqual(400, channel.code, msg=channel.json_body)
  3457. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  3458. def test_get_whois_admin(self) -> None:
  3459. """
  3460. The lookup should succeed for an admin.
  3461. """
  3462. channel = self.make_request(
  3463. "GET",
  3464. self.url,
  3465. access_token=self.admin_user_tok,
  3466. )
  3467. self.assertEqual(200, channel.code, msg=channel.json_body)
  3468. self.assertEqual(self.other_user, channel.json_body["user_id"])
  3469. self.assertIn("devices", channel.json_body)
  3470. def test_get_whois_user(self) -> None:
  3471. """
  3472. The lookup should succeed for a normal user looking up their own information.
  3473. """
  3474. other_user_token = self.login("user", "pass")
  3475. channel = self.make_request(
  3476. "GET",
  3477. self.url,
  3478. access_token=other_user_token,
  3479. )
  3480. self.assertEqual(200, channel.code, msg=channel.json_body)
  3481. self.assertEqual(self.other_user, channel.json_body["user_id"])
  3482. self.assertIn("devices", channel.json_body)
  3483. class ShadowBanRestTestCase(unittest.HomeserverTestCase):
  3484. servlets = [
  3485. synapse.rest.admin.register_servlets,
  3486. login.register_servlets,
  3487. ]
  3488. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3489. self.store = hs.get_datastores().main
  3490. self.admin_user = self.register_user("admin", "pass", admin=True)
  3491. self.admin_user_tok = self.login("admin", "pass")
  3492. self.other_user = self.register_user("user", "pass")
  3493. self.url = "/_synapse/admin/v1/users/%s/shadow_ban" % urllib.parse.quote(
  3494. self.other_user
  3495. )
  3496. @parameterized.expand(["POST", "DELETE"])
  3497. def test_no_auth(self, method: str) -> None:
  3498. """
  3499. Try to get information of an user without authentication.
  3500. """
  3501. channel = self.make_request(method, self.url)
  3502. self.assertEqual(401, channel.code, msg=channel.json_body)
  3503. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3504. @parameterized.expand(["POST", "DELETE"])
  3505. def test_requester_is_not_admin(self, method: str) -> None:
  3506. """
  3507. If the user is not a server admin, an error is returned.
  3508. """
  3509. other_user_token = self.login("user", "pass")
  3510. channel = self.make_request(method, self.url, access_token=other_user_token)
  3511. self.assertEqual(403, channel.code, msg=channel.json_body)
  3512. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3513. @parameterized.expand(["POST", "DELETE"])
  3514. def test_user_is_not_local(self, method: str) -> None:
  3515. """
  3516. Tests that shadow-banning for a user that is not a local returns a 400
  3517. """
  3518. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/shadow_ban"
  3519. channel = self.make_request(method, url, access_token=self.admin_user_tok)
  3520. self.assertEqual(400, channel.code, msg=channel.json_body)
  3521. def test_success(self) -> None:
  3522. """
  3523. Shadow-banning should succeed for an admin.
  3524. """
  3525. # The user starts off as not shadow-banned.
  3526. other_user_token = self.login("user", "pass")
  3527. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3528. assert result is not None
  3529. self.assertFalse(result.shadow_banned)
  3530. channel = self.make_request("POST", self.url, access_token=self.admin_user_tok)
  3531. self.assertEqual(200, channel.code, msg=channel.json_body)
  3532. self.assertEqual({}, channel.json_body)
  3533. # Ensure the user is shadow-banned (and the cache was cleared).
  3534. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3535. assert result is not None
  3536. self.assertTrue(result.shadow_banned)
  3537. # Un-shadow-ban the user.
  3538. channel = self.make_request(
  3539. "DELETE", self.url, access_token=self.admin_user_tok
  3540. )
  3541. self.assertEqual(200, channel.code, msg=channel.json_body)
  3542. self.assertEqual({}, channel.json_body)
  3543. # Ensure the user is no longer shadow-banned (and the cache was cleared).
  3544. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  3545. assert result is not None
  3546. self.assertFalse(result.shadow_banned)
  3547. class RateLimitTestCase(unittest.HomeserverTestCase):
  3548. servlets = [
  3549. synapse.rest.admin.register_servlets,
  3550. login.register_servlets,
  3551. ]
  3552. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3553. self.store = hs.get_datastores().main
  3554. self.admin_user = self.register_user("admin", "pass", admin=True)
  3555. self.admin_user_tok = self.login("admin", "pass")
  3556. self.other_user = self.register_user("user", "pass")
  3557. self.url = (
  3558. "/_synapse/admin/v1/users/%s/override_ratelimit"
  3559. % urllib.parse.quote(self.other_user)
  3560. )
  3561. @parameterized.expand(["GET", "POST", "DELETE"])
  3562. def test_no_auth(self, method: str) -> None:
  3563. """
  3564. Try to get information of a user without authentication.
  3565. """
  3566. channel = self.make_request(method, self.url, b"{}")
  3567. self.assertEqual(401, channel.code, msg=channel.json_body)
  3568. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3569. @parameterized.expand(["GET", "POST", "DELETE"])
  3570. def test_requester_is_no_admin(self, method: str) -> None:
  3571. """
  3572. If the user is not a server admin, an error is returned.
  3573. """
  3574. other_user_token = self.login("user", "pass")
  3575. channel = self.make_request(
  3576. method,
  3577. self.url,
  3578. access_token=other_user_token,
  3579. )
  3580. self.assertEqual(403, channel.code, msg=channel.json_body)
  3581. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3582. @parameterized.expand(["GET", "POST", "DELETE"])
  3583. def test_user_does_not_exist(self, method: str) -> None:
  3584. """
  3585. Tests that a lookup for a user that does not exist returns a 404
  3586. """
  3587. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  3588. channel = self.make_request(
  3589. method,
  3590. url,
  3591. access_token=self.admin_user_tok,
  3592. )
  3593. self.assertEqual(404, channel.code, msg=channel.json_body)
  3594. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3595. @parameterized.expand(
  3596. [
  3597. ("GET", "Can only look up local users"),
  3598. ("POST", "Only local users can be ratelimited"),
  3599. ("DELETE", "Only local users can be ratelimited"),
  3600. ]
  3601. )
  3602. def test_user_is_not_local(self, method: str, error_msg: str) -> None:
  3603. """
  3604. Tests that a lookup for a user that is not a local returns a 400
  3605. """
  3606. url = (
  3607. "/_synapse/admin/v1/users/@unknown_person:unknown_domain/override_ratelimit"
  3608. )
  3609. channel = self.make_request(
  3610. method,
  3611. url,
  3612. access_token=self.admin_user_tok,
  3613. )
  3614. self.assertEqual(400, channel.code, msg=channel.json_body)
  3615. self.assertEqual(error_msg, channel.json_body["error"])
  3616. def test_invalid_parameter(self) -> None:
  3617. """
  3618. If parameters are invalid, an error is returned.
  3619. """
  3620. # messages_per_second is a string
  3621. channel = self.make_request(
  3622. "POST",
  3623. self.url,
  3624. access_token=self.admin_user_tok,
  3625. content={"messages_per_second": "string"},
  3626. )
  3627. self.assertEqual(400, channel.code, msg=channel.json_body)
  3628. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3629. # messages_per_second is negative
  3630. channel = self.make_request(
  3631. "POST",
  3632. self.url,
  3633. access_token=self.admin_user_tok,
  3634. content={"messages_per_second": -1},
  3635. )
  3636. self.assertEqual(400, channel.code, msg=channel.json_body)
  3637. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3638. # burst_count is a string
  3639. channel = self.make_request(
  3640. "POST",
  3641. self.url,
  3642. access_token=self.admin_user_tok,
  3643. content={"burst_count": "string"},
  3644. )
  3645. self.assertEqual(400, channel.code, msg=channel.json_body)
  3646. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3647. # burst_count is negative
  3648. channel = self.make_request(
  3649. "POST",
  3650. self.url,
  3651. access_token=self.admin_user_tok,
  3652. content={"burst_count": -1},
  3653. )
  3654. self.assertEqual(400, channel.code, msg=channel.json_body)
  3655. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  3656. def test_return_zero_when_null(self) -> None:
  3657. """
  3658. If values in database are `null` API should return an int `0`
  3659. """
  3660. self.get_success(
  3661. self.store.db_pool.simple_upsert(
  3662. table="ratelimit_override",
  3663. keyvalues={"user_id": self.other_user},
  3664. values={
  3665. "messages_per_second": None,
  3666. "burst_count": None,
  3667. },
  3668. )
  3669. )
  3670. # request status
  3671. channel = self.make_request(
  3672. "GET",
  3673. self.url,
  3674. access_token=self.admin_user_tok,
  3675. )
  3676. self.assertEqual(200, channel.code, msg=channel.json_body)
  3677. self.assertEqual(0, channel.json_body["messages_per_second"])
  3678. self.assertEqual(0, channel.json_body["burst_count"])
  3679. def test_success(self) -> None:
  3680. """
  3681. Rate-limiting (set/update/delete) should succeed for an admin.
  3682. """
  3683. # request status
  3684. channel = self.make_request(
  3685. "GET",
  3686. self.url,
  3687. access_token=self.admin_user_tok,
  3688. )
  3689. self.assertEqual(200, channel.code, msg=channel.json_body)
  3690. self.assertNotIn("messages_per_second", channel.json_body)
  3691. self.assertNotIn("burst_count", channel.json_body)
  3692. # set ratelimit
  3693. channel = self.make_request(
  3694. "POST",
  3695. self.url,
  3696. access_token=self.admin_user_tok,
  3697. content={"messages_per_second": 10, "burst_count": 11},
  3698. )
  3699. self.assertEqual(200, channel.code, msg=channel.json_body)
  3700. self.assertEqual(10, channel.json_body["messages_per_second"])
  3701. self.assertEqual(11, channel.json_body["burst_count"])
  3702. # update ratelimit
  3703. channel = self.make_request(
  3704. "POST",
  3705. self.url,
  3706. access_token=self.admin_user_tok,
  3707. content={"messages_per_second": 20, "burst_count": 21},
  3708. )
  3709. self.assertEqual(200, channel.code, msg=channel.json_body)
  3710. self.assertEqual(20, channel.json_body["messages_per_second"])
  3711. self.assertEqual(21, channel.json_body["burst_count"])
  3712. # request status
  3713. channel = self.make_request(
  3714. "GET",
  3715. self.url,
  3716. access_token=self.admin_user_tok,
  3717. )
  3718. self.assertEqual(200, channel.code, msg=channel.json_body)
  3719. self.assertEqual(20, channel.json_body["messages_per_second"])
  3720. self.assertEqual(21, channel.json_body["burst_count"])
  3721. # delete ratelimit
  3722. channel = self.make_request(
  3723. "DELETE",
  3724. self.url,
  3725. access_token=self.admin_user_tok,
  3726. )
  3727. self.assertEqual(200, channel.code, msg=channel.json_body)
  3728. self.assertNotIn("messages_per_second", channel.json_body)
  3729. self.assertNotIn("burst_count", channel.json_body)
  3730. # request status
  3731. channel = self.make_request(
  3732. "GET",
  3733. self.url,
  3734. access_token=self.admin_user_tok,
  3735. )
  3736. self.assertEqual(200, channel.code, msg=channel.json_body)
  3737. self.assertNotIn("messages_per_second", channel.json_body)
  3738. self.assertNotIn("burst_count", channel.json_body)
  3739. class AccountDataTestCase(unittest.HomeserverTestCase):
  3740. servlets = [
  3741. synapse.rest.admin.register_servlets,
  3742. login.register_servlets,
  3743. ]
  3744. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3745. self.store = hs.get_datastores().main
  3746. self.admin_user = self.register_user("admin", "pass", admin=True)
  3747. self.admin_user_tok = self.login("admin", "pass")
  3748. self.other_user = self.register_user("user", "pass")
  3749. self.url = f"/_synapse/admin/v1/users/{self.other_user}/accountdata"
  3750. def test_no_auth(self) -> None:
  3751. """Try to get information of a user without authentication."""
  3752. channel = self.make_request("GET", self.url, {})
  3753. self.assertEqual(401, channel.code, msg=channel.json_body)
  3754. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3755. def test_requester_is_no_admin(self) -> None:
  3756. """If the user is not a server admin, an error is returned."""
  3757. other_user_token = self.login("user", "pass")
  3758. channel = self.make_request(
  3759. "GET",
  3760. self.url,
  3761. access_token=other_user_token,
  3762. )
  3763. self.assertEqual(403, channel.code, msg=channel.json_body)
  3764. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  3765. def test_user_does_not_exist(self) -> None:
  3766. """Tests that a lookup for a user that does not exist returns a 404"""
  3767. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  3768. channel = self.make_request(
  3769. "GET",
  3770. url,
  3771. access_token=self.admin_user_tok,
  3772. )
  3773. self.assertEqual(404, channel.code, msg=channel.json_body)
  3774. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3775. def test_user_is_not_local(self) -> None:
  3776. """Tests that a lookup for a user that is not a local returns a 400"""
  3777. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/accountdata"
  3778. channel = self.make_request(
  3779. "GET",
  3780. url,
  3781. access_token=self.admin_user_tok,
  3782. )
  3783. self.assertEqual(400, channel.code, msg=channel.json_body)
  3784. self.assertEqual("Can only look up local users", channel.json_body["error"])
  3785. def test_success(self) -> None:
  3786. """Request account data should succeed for an admin."""
  3787. # add account data
  3788. self.get_success(
  3789. self.store.add_account_data_for_user(self.other_user, "m.global", {"a": 1})
  3790. )
  3791. self.get_success(
  3792. self.store.add_account_data_to_room(
  3793. self.other_user, "test_room", "m.per_room", {"b": 2}
  3794. )
  3795. )
  3796. channel = self.make_request(
  3797. "GET",
  3798. self.url,
  3799. access_token=self.admin_user_tok,
  3800. )
  3801. self.assertEqual(200, channel.code, msg=channel.json_body)
  3802. self.assertEqual(
  3803. {"a": 1}, channel.json_body["account_data"]["global"]["m.global"]
  3804. )
  3805. self.assertEqual(
  3806. {"b": 2},
  3807. channel.json_body["account_data"]["rooms"]["test_room"]["m.per_room"],
  3808. )
  3809. class UsersByExternalIdTestCase(unittest.HomeserverTestCase):
  3810. servlets = [
  3811. synapse.rest.admin.register_servlets,
  3812. login.register_servlets,
  3813. ]
  3814. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3815. self.store = hs.get_datastores().main
  3816. self.admin_user = self.register_user("admin", "pass", admin=True)
  3817. self.admin_user_tok = self.login("admin", "pass")
  3818. self.other_user = self.register_user("user", "pass")
  3819. self.get_success(
  3820. self.store.record_user_external_id(
  3821. "the-auth-provider", "the-external-id", self.other_user
  3822. )
  3823. )
  3824. self.get_success(
  3825. self.store.record_user_external_id(
  3826. "another-auth-provider", "a:complex@external/id", self.other_user
  3827. )
  3828. )
  3829. def test_no_auth(self) -> None:
  3830. """Try to lookup a user without authentication."""
  3831. url = (
  3832. "/_synapse/admin/v1/auth_providers/the-auth-provider/users/the-external-id"
  3833. )
  3834. channel = self.make_request(
  3835. "GET",
  3836. url,
  3837. )
  3838. self.assertEqual(401, channel.code, msg=channel.json_body)
  3839. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3840. def test_binding_does_not_exist(self) -> None:
  3841. """Tests that a lookup for an external ID that does not exist returns a 404"""
  3842. url = "/_synapse/admin/v1/auth_providers/the-auth-provider/users/unknown-id"
  3843. channel = self.make_request(
  3844. "GET",
  3845. url,
  3846. access_token=self.admin_user_tok,
  3847. )
  3848. self.assertEqual(404, channel.code, msg=channel.json_body)
  3849. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3850. def test_success(self) -> None:
  3851. """Tests a successful external ID lookup"""
  3852. url = (
  3853. "/_synapse/admin/v1/auth_providers/the-auth-provider/users/the-external-id"
  3854. )
  3855. channel = self.make_request(
  3856. "GET",
  3857. url,
  3858. access_token=self.admin_user_tok,
  3859. )
  3860. self.assertEqual(200, channel.code, msg=channel.json_body)
  3861. self.assertEqual(
  3862. {"user_id": self.other_user},
  3863. channel.json_body,
  3864. )
  3865. def test_success_urlencoded(self) -> None:
  3866. """Tests a successful external ID lookup with an url-encoded ID"""
  3867. url = "/_synapse/admin/v1/auth_providers/another-auth-provider/users/a%3Acomplex%40external%2Fid"
  3868. channel = self.make_request(
  3869. "GET",
  3870. url,
  3871. access_token=self.admin_user_tok,
  3872. )
  3873. self.assertEqual(200, channel.code, msg=channel.json_body)
  3874. self.assertEqual(
  3875. {"user_id": self.other_user},
  3876. channel.json_body,
  3877. )
  3878. class UsersByThreePidTestCase(unittest.HomeserverTestCase):
  3879. servlets = [
  3880. synapse.rest.admin.register_servlets,
  3881. login.register_servlets,
  3882. ]
  3883. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  3884. self.store = hs.get_datastores().main
  3885. self.admin_user = self.register_user("admin", "pass", admin=True)
  3886. self.admin_user_tok = self.login("admin", "pass")
  3887. self.other_user = self.register_user("user", "pass")
  3888. self.get_success(
  3889. self.store.user_add_threepid(
  3890. self.other_user, "email", "user@email.com", 1, 1
  3891. )
  3892. )
  3893. self.get_success(
  3894. self.store.user_add_threepid(self.other_user, "msidn", "+1-12345678", 1, 1)
  3895. )
  3896. def test_no_auth(self) -> None:
  3897. """Try to look up a user without authentication."""
  3898. url = "/_synapse/admin/v1/threepid/email/users/user%40email.com"
  3899. channel = self.make_request(
  3900. "GET",
  3901. url,
  3902. )
  3903. self.assertEqual(401, channel.code, msg=channel.json_body)
  3904. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  3905. def test_medium_does_not_exist(self) -> None:
  3906. """Tests that both a lookup for a medium that does not exist and a user that
  3907. doesn't exist with that third party ID returns a 404"""
  3908. # test for unknown medium
  3909. url = "/_synapse/admin/v1/threepid/publickey/users/unknown-key"
  3910. channel = self.make_request(
  3911. "GET",
  3912. url,
  3913. access_token=self.admin_user_tok,
  3914. )
  3915. self.assertEqual(404, channel.code, msg=channel.json_body)
  3916. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3917. # test for unknown user with a known medium
  3918. url = "/_synapse/admin/v1/threepid/email/users/unknown"
  3919. channel = self.make_request(
  3920. "GET",
  3921. url,
  3922. access_token=self.admin_user_tok,
  3923. )
  3924. self.assertEqual(404, channel.code, msg=channel.json_body)
  3925. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  3926. def test_success(self) -> None:
  3927. """Tests a successful medium + address lookup"""
  3928. # test for email medium with encoded value of user@email.com
  3929. url = "/_synapse/admin/v1/threepid/email/users/user%40email.com"
  3930. channel = self.make_request(
  3931. "GET",
  3932. url,
  3933. access_token=self.admin_user_tok,
  3934. )
  3935. self.assertEqual(200, channel.code, msg=channel.json_body)
  3936. self.assertEqual(
  3937. {"user_id": self.other_user},
  3938. channel.json_body,
  3939. )
  3940. # test for msidn medium with encoded value of +1-12345678
  3941. url = "/_synapse/admin/v1/threepid/msidn/users/%2B1-12345678"
  3942. channel = self.make_request(
  3943. "GET",
  3944. url,
  3945. access_token=self.admin_user_tok,
  3946. )
  3947. self.assertEqual(200, channel.code, msg=channel.json_body)
  3948. self.assertEqual(
  3949. {"user_id": self.other_user},
  3950. channel.json_body,
  3951. )