test_user.py 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399
  1. # Copyright 2018 New Vector Ltd
  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 json
  17. import urllib.parse
  18. from binascii import unhexlify
  19. from typing import List, Optional
  20. from unittest.mock import Mock, patch
  21. import synapse.rest.admin
  22. from synapse.api.constants import UserTypes
  23. from synapse.api.errors import Codes, HttpResponseException, ResourceLimitError
  24. from synapse.api.room_versions import RoomVersions
  25. from synapse.rest.client.v1 import login, logout, profile, room
  26. from synapse.rest.client.v2_alpha import devices, sync
  27. from synapse.types import JsonDict, UserID
  28. from tests import unittest
  29. from tests.server import FakeSite, make_request
  30. from tests.test_utils import make_awaitable
  31. from tests.unittest import override_config
  32. class UserRegisterTestCase(unittest.HomeserverTestCase):
  33. servlets = [
  34. synapse.rest.admin.register_servlets_for_client_rest_resource,
  35. profile.register_servlets,
  36. ]
  37. def make_homeserver(self, reactor, clock):
  38. self.url = "/_synapse/admin/v1/register"
  39. self.registration_handler = Mock()
  40. self.identity_handler = Mock()
  41. self.login_handler = Mock()
  42. self.device_handler = Mock()
  43. self.device_handler.check_device_registered = Mock(return_value="FAKE")
  44. self.datastore = Mock(return_value=Mock())
  45. self.datastore.get_current_state_deltas = Mock(return_value=(0, []))
  46. self.hs = self.setup_test_homeserver()
  47. self.hs.config.registration_shared_secret = "shared"
  48. self.hs.get_media_repository = Mock()
  49. self.hs.get_deactivate_account_handler = Mock()
  50. return self.hs
  51. def test_disabled(self):
  52. """
  53. If there is no shared secret, registration through this method will be
  54. prevented.
  55. """
  56. self.hs.config.registration_shared_secret = None
  57. channel = self.make_request("POST", self.url, b"{}")
  58. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  59. self.assertEqual(
  60. "Shared secret registration is not enabled", channel.json_body["error"]
  61. )
  62. def test_get_nonce(self):
  63. """
  64. Calling GET on the endpoint will return a randomised nonce, using the
  65. homeserver's secrets provider.
  66. """
  67. with patch("secrets.token_hex") as token_hex:
  68. # Patch secrets.token_hex for the duration of this context
  69. token_hex.return_value = "abcd"
  70. channel = self.make_request("GET", self.url)
  71. self.assertEqual(channel.json_body, {"nonce": "abcd"})
  72. def test_expired_nonce(self):
  73. """
  74. Calling GET on the endpoint will return a randomised nonce, which will
  75. only last for SALT_TIMEOUT (60s).
  76. """
  77. channel = self.make_request("GET", self.url)
  78. nonce = channel.json_body["nonce"]
  79. # 59 seconds
  80. self.reactor.advance(59)
  81. body = json.dumps({"nonce": nonce})
  82. channel = self.make_request("POST", self.url, body.encode("utf8"))
  83. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  84. self.assertEqual("username must be specified", channel.json_body["error"])
  85. # 61 seconds
  86. self.reactor.advance(2)
  87. channel = self.make_request("POST", self.url, body.encode("utf8"))
  88. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  89. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  90. def test_register_incorrect_nonce(self):
  91. """
  92. Only the provided nonce can be used, as it's checked in the MAC.
  93. """
  94. channel = self.make_request("GET", self.url)
  95. nonce = channel.json_body["nonce"]
  96. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  97. want_mac.update(b"notthenonce\x00bob\x00abc123\x00admin")
  98. want_mac = want_mac.hexdigest()
  99. body = json.dumps(
  100. {
  101. "nonce": nonce,
  102. "username": "bob",
  103. "password": "abc123",
  104. "admin": True,
  105. "mac": want_mac,
  106. }
  107. )
  108. channel = self.make_request("POST", self.url, body.encode("utf8"))
  109. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  110. self.assertEqual("HMAC incorrect", channel.json_body["error"])
  111. def test_register_correct_nonce(self):
  112. """
  113. When the correct nonce is provided, and the right key is provided, the
  114. user is registered.
  115. """
  116. channel = self.make_request("GET", self.url)
  117. nonce = channel.json_body["nonce"]
  118. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  119. want_mac.update(
  120. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  121. )
  122. want_mac = want_mac.hexdigest()
  123. body = json.dumps(
  124. {
  125. "nonce": nonce,
  126. "username": "bob",
  127. "password": "abc123",
  128. "admin": True,
  129. "user_type": UserTypes.SUPPORT,
  130. "mac": want_mac,
  131. }
  132. )
  133. channel = self.make_request("POST", self.url, body.encode("utf8"))
  134. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  135. self.assertEqual("@bob:test", channel.json_body["user_id"])
  136. def test_nonce_reuse(self):
  137. """
  138. A valid unrecognised nonce.
  139. """
  140. channel = self.make_request("GET", self.url)
  141. nonce = channel.json_body["nonce"]
  142. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  143. want_mac.update(nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin")
  144. want_mac = want_mac.hexdigest()
  145. body = json.dumps(
  146. {
  147. "nonce": nonce,
  148. "username": "bob",
  149. "password": "abc123",
  150. "admin": True,
  151. "mac": want_mac,
  152. }
  153. )
  154. channel = self.make_request("POST", self.url, body.encode("utf8"))
  155. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  156. self.assertEqual("@bob:test", channel.json_body["user_id"])
  157. # Now, try and reuse it
  158. channel = self.make_request("POST", self.url, body.encode("utf8"))
  159. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  160. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  161. def test_missing_parts(self):
  162. """
  163. Synapse will complain if you don't give nonce, username, password, and
  164. mac. Admin and user_types are optional. Additional checks are done for length
  165. and type.
  166. """
  167. def nonce():
  168. channel = self.make_request("GET", self.url)
  169. return channel.json_body["nonce"]
  170. #
  171. # Nonce check
  172. #
  173. # Must be present
  174. body = json.dumps({})
  175. channel = self.make_request("POST", self.url, body.encode("utf8"))
  176. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  177. self.assertEqual("nonce must be specified", channel.json_body["error"])
  178. #
  179. # Username checks
  180. #
  181. # Must be present
  182. body = json.dumps({"nonce": nonce()})
  183. channel = self.make_request("POST", self.url, body.encode("utf8"))
  184. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  185. self.assertEqual("username must be specified", channel.json_body["error"])
  186. # Must be a string
  187. body = json.dumps({"nonce": nonce(), "username": 1234})
  188. channel = self.make_request("POST", self.url, body.encode("utf8"))
  189. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  190. self.assertEqual("Invalid username", channel.json_body["error"])
  191. # Must not have null bytes
  192. body = json.dumps({"nonce": nonce(), "username": "abcd\u0000"})
  193. channel = self.make_request("POST", self.url, body.encode("utf8"))
  194. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  195. self.assertEqual("Invalid username", channel.json_body["error"])
  196. # Must not have null bytes
  197. body = json.dumps({"nonce": nonce(), "username": "a" * 1000})
  198. channel = self.make_request("POST", self.url, body.encode("utf8"))
  199. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  200. self.assertEqual("Invalid username", channel.json_body["error"])
  201. #
  202. # Password checks
  203. #
  204. # Must be present
  205. body = json.dumps({"nonce": nonce(), "username": "a"})
  206. channel = self.make_request("POST", self.url, body.encode("utf8"))
  207. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  208. self.assertEqual("password must be specified", channel.json_body["error"])
  209. # Must be a string
  210. body = json.dumps({"nonce": nonce(), "username": "a", "password": 1234})
  211. channel = self.make_request("POST", self.url, body.encode("utf8"))
  212. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  213. self.assertEqual("Invalid password", channel.json_body["error"])
  214. # Must not have null bytes
  215. body = json.dumps({"nonce": nonce(), "username": "a", "password": "abcd\u0000"})
  216. channel = self.make_request("POST", self.url, body.encode("utf8"))
  217. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  218. self.assertEqual("Invalid password", channel.json_body["error"])
  219. # Super long
  220. body = json.dumps({"nonce": nonce(), "username": "a", "password": "A" * 1000})
  221. channel = self.make_request("POST", self.url, body.encode("utf8"))
  222. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  223. self.assertEqual("Invalid password", channel.json_body["error"])
  224. #
  225. # user_type check
  226. #
  227. # Invalid user_type
  228. body = json.dumps(
  229. {
  230. "nonce": nonce(),
  231. "username": "a",
  232. "password": "1234",
  233. "user_type": "invalid",
  234. }
  235. )
  236. channel = self.make_request("POST", self.url, body.encode("utf8"))
  237. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  238. self.assertEqual("Invalid user type", channel.json_body["error"])
  239. def test_displayname(self):
  240. """
  241. Test that displayname of new user is set
  242. """
  243. # set no displayname
  244. channel = self.make_request("GET", self.url)
  245. nonce = channel.json_body["nonce"]
  246. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  247. want_mac.update(nonce.encode("ascii") + b"\x00bob1\x00abc123\x00notadmin")
  248. want_mac = want_mac.hexdigest()
  249. body = json.dumps(
  250. {"nonce": nonce, "username": "bob1", "password": "abc123", "mac": want_mac}
  251. )
  252. channel = self.make_request("POST", self.url, body.encode("utf8"))
  253. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  254. self.assertEqual("@bob1:test", channel.json_body["user_id"])
  255. channel = self.make_request("GET", "/profile/@bob1:test/displayname")
  256. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  257. self.assertEqual("bob1", channel.json_body["displayname"])
  258. # displayname is None
  259. channel = self.make_request("GET", self.url)
  260. nonce = channel.json_body["nonce"]
  261. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  262. want_mac.update(nonce.encode("ascii") + b"\x00bob2\x00abc123\x00notadmin")
  263. want_mac = want_mac.hexdigest()
  264. body = json.dumps(
  265. {
  266. "nonce": nonce,
  267. "username": "bob2",
  268. "displayname": None,
  269. "password": "abc123",
  270. "mac": want_mac,
  271. }
  272. )
  273. channel = self.make_request("POST", self.url, body.encode("utf8"))
  274. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  275. self.assertEqual("@bob2:test", channel.json_body["user_id"])
  276. channel = self.make_request("GET", "/profile/@bob2:test/displayname")
  277. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  278. self.assertEqual("bob2", channel.json_body["displayname"])
  279. # displayname is empty
  280. channel = self.make_request("GET", self.url)
  281. nonce = channel.json_body["nonce"]
  282. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  283. want_mac.update(nonce.encode("ascii") + b"\x00bob3\x00abc123\x00notadmin")
  284. want_mac = want_mac.hexdigest()
  285. body = json.dumps(
  286. {
  287. "nonce": nonce,
  288. "username": "bob3",
  289. "displayname": "",
  290. "password": "abc123",
  291. "mac": want_mac,
  292. }
  293. )
  294. channel = self.make_request("POST", self.url, body.encode("utf8"))
  295. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  296. self.assertEqual("@bob3:test", channel.json_body["user_id"])
  297. channel = self.make_request("GET", "/profile/@bob3:test/displayname")
  298. self.assertEqual(404, int(channel.result["code"]), msg=channel.result["body"])
  299. # set displayname
  300. channel = self.make_request("GET", self.url)
  301. nonce = channel.json_body["nonce"]
  302. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  303. want_mac.update(nonce.encode("ascii") + b"\x00bob4\x00abc123\x00notadmin")
  304. want_mac = want_mac.hexdigest()
  305. body = json.dumps(
  306. {
  307. "nonce": nonce,
  308. "username": "bob4",
  309. "displayname": "Bob's Name",
  310. "password": "abc123",
  311. "mac": want_mac,
  312. }
  313. )
  314. channel = self.make_request("POST", self.url, body.encode("utf8"))
  315. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["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, int(channel.result["code"]), msg=channel.result["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):
  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_datastore()
  330. # Set monthly active users to the limit
  331. store.get_monthly_active_count = Mock(
  332. return_value=make_awaitable(self.hs.config.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 = want_mac.hexdigest()
  347. body = json.dumps(
  348. {
  349. "nonce": nonce,
  350. "username": "bob",
  351. "password": "abc123",
  352. "admin": True,
  353. "user_type": UserTypes.SUPPORT,
  354. "mac": want_mac,
  355. }
  356. )
  357. channel = self.make_request("POST", self.url, body.encode("utf8"))
  358. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  359. self.assertEqual("@bob:test", channel.json_body["user_id"])
  360. class UsersListTestCase(unittest.HomeserverTestCase):
  361. servlets = [
  362. synapse.rest.admin.register_servlets,
  363. login.register_servlets,
  364. ]
  365. url = "/_synapse/admin/v2/users"
  366. def prepare(self, reactor, clock, hs):
  367. self.store = hs.get_datastore()
  368. self.admin_user = self.register_user("admin", "pass", admin=True)
  369. self.admin_user_tok = self.login("admin", "pass")
  370. def test_no_auth(self):
  371. """
  372. Try to list users without authentication.
  373. """
  374. channel = self.make_request("GET", self.url, b"{}")
  375. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  376. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  377. def test_requester_is_no_admin(self):
  378. """
  379. If the user is not a server admin, an error is returned.
  380. """
  381. self._create_users(1)
  382. other_user_token = self.login("user1", "pass1")
  383. channel = self.make_request("GET", self.url, access_token=other_user_token)
  384. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  385. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  386. def test_all_users(self):
  387. """
  388. List all users, including deactivated users.
  389. """
  390. self._create_users(2)
  391. channel = self.make_request(
  392. "GET",
  393. self.url + "?deactivated=true",
  394. b"{}",
  395. access_token=self.admin_user_tok,
  396. )
  397. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  398. self.assertEqual(3, len(channel.json_body["users"]))
  399. self.assertEqual(3, channel.json_body["total"])
  400. # Check that all fields are available
  401. self._check_fields(channel.json_body["users"])
  402. def test_search_term(self):
  403. """Test that searching for a users works correctly"""
  404. def _search_test(
  405. expected_user_id: Optional[str],
  406. search_term: str,
  407. search_field: Optional[str] = "name",
  408. expected_http_code: Optional[int] = 200,
  409. ):
  410. """Search for a user and check that the returned user's id is a match
  411. Args:
  412. expected_user_id: The user_id expected to be returned by the API. Set
  413. to None to expect zero results for the search
  414. search_term: The term to search for user names with
  415. search_field: Field which is to request: `name` or `user_id`
  416. expected_http_code: The expected http code for the request
  417. """
  418. url = self.url + "?%s=%s" % (
  419. search_field,
  420. search_term,
  421. )
  422. channel = self.make_request(
  423. "GET",
  424. url.encode("ascii"),
  425. access_token=self.admin_user_tok,
  426. )
  427. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  428. if expected_http_code != 200:
  429. return
  430. # Check that users were returned
  431. self.assertTrue("users" in channel.json_body)
  432. self._check_fields(channel.json_body["users"])
  433. users = channel.json_body["users"]
  434. # Check that the expected number of users were returned
  435. expected_user_count = 1 if expected_user_id else 0
  436. self.assertEqual(len(users), expected_user_count)
  437. self.assertEqual(channel.json_body["total"], expected_user_count)
  438. if expected_user_id:
  439. # Check that the first returned user id is correct
  440. u = users[0]
  441. self.assertEqual(expected_user_id, u["name"])
  442. self._create_users(2)
  443. user1 = "@user1:test"
  444. user2 = "@user2:test"
  445. # Perform search tests
  446. _search_test(user1, "er1")
  447. _search_test(user1, "me 1")
  448. _search_test(user2, "er2")
  449. _search_test(user2, "me 2")
  450. _search_test(user1, "er1", "user_id")
  451. _search_test(user2, "er2", "user_id")
  452. # Test case insensitive
  453. _search_test(user1, "ER1")
  454. _search_test(user1, "NAME 1")
  455. _search_test(user2, "ER2")
  456. _search_test(user2, "NAME 2")
  457. _search_test(user1, "ER1", "user_id")
  458. _search_test(user2, "ER2", "user_id")
  459. _search_test(None, "foo")
  460. _search_test(None, "bar")
  461. _search_test(None, "foo", "user_id")
  462. _search_test(None, "bar", "user_id")
  463. def test_invalid_parameter(self):
  464. """
  465. If parameters are invalid, an error is returned.
  466. """
  467. # negative limit
  468. channel = self.make_request(
  469. "GET",
  470. self.url + "?limit=-5",
  471. access_token=self.admin_user_tok,
  472. )
  473. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  474. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  475. # negative from
  476. channel = self.make_request(
  477. "GET",
  478. self.url + "?from=-5",
  479. access_token=self.admin_user_tok,
  480. )
  481. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  482. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  483. # invalid guests
  484. channel = self.make_request(
  485. "GET",
  486. self.url + "?guests=not_bool",
  487. access_token=self.admin_user_tok,
  488. )
  489. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  490. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  491. # invalid deactivated
  492. channel = self.make_request(
  493. "GET",
  494. self.url + "?deactivated=not_bool",
  495. access_token=self.admin_user_tok,
  496. )
  497. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  498. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  499. # unkown order_by
  500. channel = self.make_request(
  501. "GET",
  502. self.url + "?order_by=bar",
  503. access_token=self.admin_user_tok,
  504. )
  505. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  506. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  507. # invalid search order
  508. channel = self.make_request(
  509. "GET",
  510. self.url + "?dir=bar",
  511. access_token=self.admin_user_tok,
  512. )
  513. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  514. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  515. def test_limit(self):
  516. """
  517. Testing list of users with limit
  518. """
  519. number_users = 20
  520. # Create one less user (since there's already an admin user).
  521. self._create_users(number_users - 1)
  522. channel = self.make_request(
  523. "GET",
  524. self.url + "?limit=5",
  525. access_token=self.admin_user_tok,
  526. )
  527. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  528. self.assertEqual(channel.json_body["total"], number_users)
  529. self.assertEqual(len(channel.json_body["users"]), 5)
  530. self.assertEqual(channel.json_body["next_token"], "5")
  531. self._check_fields(channel.json_body["users"])
  532. def test_from(self):
  533. """
  534. Testing list of users with a defined starting point (from)
  535. """
  536. number_users = 20
  537. # Create one less user (since there's already an admin user).
  538. self._create_users(number_users - 1)
  539. channel = self.make_request(
  540. "GET",
  541. self.url + "?from=5",
  542. access_token=self.admin_user_tok,
  543. )
  544. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  545. self.assertEqual(channel.json_body["total"], number_users)
  546. self.assertEqual(len(channel.json_body["users"]), 15)
  547. self.assertNotIn("next_token", channel.json_body)
  548. self._check_fields(channel.json_body["users"])
  549. def test_limit_and_from(self):
  550. """
  551. Testing list of users with a defined starting point and limit
  552. """
  553. number_users = 20
  554. # Create one less user (since there's already an admin user).
  555. self._create_users(number_users - 1)
  556. channel = self.make_request(
  557. "GET",
  558. self.url + "?from=5&limit=10",
  559. access_token=self.admin_user_tok,
  560. )
  561. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  562. self.assertEqual(channel.json_body["total"], number_users)
  563. self.assertEqual(channel.json_body["next_token"], "15")
  564. self.assertEqual(len(channel.json_body["users"]), 10)
  565. self._check_fields(channel.json_body["users"])
  566. def test_next_token(self):
  567. """
  568. Testing that `next_token` appears at the right place
  569. """
  570. number_users = 20
  571. # Create one less user (since there's already an admin user).
  572. self._create_users(number_users - 1)
  573. # `next_token` does not appear
  574. # Number of results is the number of entries
  575. channel = self.make_request(
  576. "GET",
  577. self.url + "?limit=20",
  578. access_token=self.admin_user_tok,
  579. )
  580. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  581. self.assertEqual(channel.json_body["total"], number_users)
  582. self.assertEqual(len(channel.json_body["users"]), number_users)
  583. self.assertNotIn("next_token", channel.json_body)
  584. # `next_token` does not appear
  585. # Number of max results is larger than the number of entries
  586. channel = self.make_request(
  587. "GET",
  588. self.url + "?limit=21",
  589. access_token=self.admin_user_tok,
  590. )
  591. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  592. self.assertEqual(channel.json_body["total"], number_users)
  593. self.assertEqual(len(channel.json_body["users"]), number_users)
  594. self.assertNotIn("next_token", channel.json_body)
  595. # `next_token` does appear
  596. # Number of max results is smaller than the number of entries
  597. channel = self.make_request(
  598. "GET",
  599. self.url + "?limit=19",
  600. access_token=self.admin_user_tok,
  601. )
  602. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  603. self.assertEqual(channel.json_body["total"], number_users)
  604. self.assertEqual(len(channel.json_body["users"]), 19)
  605. self.assertEqual(channel.json_body["next_token"], "19")
  606. # Check
  607. # Set `from` to value of `next_token` for request remaining entries
  608. # `next_token` does not appear
  609. channel = self.make_request(
  610. "GET",
  611. self.url + "?from=19",
  612. access_token=self.admin_user_tok,
  613. )
  614. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  615. self.assertEqual(channel.json_body["total"], number_users)
  616. self.assertEqual(len(channel.json_body["users"]), 1)
  617. self.assertNotIn("next_token", channel.json_body)
  618. def test_order_by(self):
  619. """
  620. Testing order list with parameter `order_by`
  621. """
  622. user1 = self.register_user("user1", "pass1", admin=False, displayname="Name Z")
  623. user2 = self.register_user("user2", "pass2", admin=False, displayname="Name Y")
  624. # Modify user
  625. self.get_success(self.store.set_user_deactivated_status(user1, True))
  626. self.get_success(self.store.set_shadow_banned(UserID.from_string(user1), True))
  627. # Set avatar URL to all users, that no user has a NULL value to avoid
  628. # different sort order between SQlite and PostreSQL
  629. self.get_success(self.store.set_profile_avatar_url("user1", "mxc://url3"))
  630. self.get_success(self.store.set_profile_avatar_url("user2", "mxc://url2"))
  631. self.get_success(self.store.set_profile_avatar_url("admin", "mxc://url1"))
  632. # order by default (name)
  633. self._order_test([self.admin_user, user1, user2], None)
  634. self._order_test([self.admin_user, user1, user2], None, "f")
  635. self._order_test([user2, user1, self.admin_user], None, "b")
  636. # order by name
  637. self._order_test([self.admin_user, user1, user2], "name")
  638. self._order_test([self.admin_user, user1, user2], "name", "f")
  639. self._order_test([user2, user1, self.admin_user], "name", "b")
  640. # order by displayname
  641. self._order_test([user2, user1, self.admin_user], "displayname")
  642. self._order_test([user2, user1, self.admin_user], "displayname", "f")
  643. self._order_test([self.admin_user, user1, user2], "displayname", "b")
  644. # order by is_guest
  645. # like sort by ascending name, as no guest user here
  646. self._order_test([self.admin_user, user1, user2], "is_guest")
  647. self._order_test([self.admin_user, user1, user2], "is_guest", "f")
  648. self._order_test([self.admin_user, user1, user2], "is_guest", "b")
  649. # order by admin
  650. self._order_test([user1, user2, self.admin_user], "admin")
  651. self._order_test([user1, user2, self.admin_user], "admin", "f")
  652. self._order_test([self.admin_user, user1, user2], "admin", "b")
  653. # order by deactivated
  654. self._order_test([self.admin_user, user2, user1], "deactivated")
  655. self._order_test([self.admin_user, user2, user1], "deactivated", "f")
  656. self._order_test([user1, self.admin_user, user2], "deactivated", "b")
  657. # order by user_type
  658. # like sort by ascending name, as no special user type here
  659. self._order_test([self.admin_user, user1, user2], "user_type")
  660. self._order_test([self.admin_user, user1, user2], "user_type", "f")
  661. self._order_test([self.admin_user, user1, user2], "is_guest", "b")
  662. # order by shadow_banned
  663. self._order_test([self.admin_user, user2, user1], "shadow_banned")
  664. self._order_test([self.admin_user, user2, user1], "shadow_banned", "f")
  665. self._order_test([user1, self.admin_user, user2], "shadow_banned", "b")
  666. # order by avatar_url
  667. self._order_test([self.admin_user, user2, user1], "avatar_url")
  668. self._order_test([self.admin_user, user2, user1], "avatar_url", "f")
  669. self._order_test([user1, user2, self.admin_user], "avatar_url", "b")
  670. def _order_test(
  671. self,
  672. expected_user_list: List[str],
  673. order_by: Optional[str],
  674. dir: Optional[str] = None,
  675. ):
  676. """Request the list of users in a certain order. Assert that order is what
  677. we expect
  678. Args:
  679. expected_user_list: The list of user_id in the order we expect to get
  680. back from the server
  681. order_by: The type of ordering to give the server
  682. dir: The direction of ordering to give the server
  683. """
  684. url = self.url + "?deactivated=true&"
  685. if order_by is not None:
  686. url += "order_by=%s&" % (order_by,)
  687. if dir is not None and dir in ("b", "f"):
  688. url += "dir=%s" % (dir,)
  689. channel = self.make_request(
  690. "GET",
  691. url.encode("ascii"),
  692. access_token=self.admin_user_tok,
  693. )
  694. self.assertEqual(200, channel.code, msg=channel.json_body)
  695. self.assertEqual(channel.json_body["total"], len(expected_user_list))
  696. returned_order = [row["name"] for row in channel.json_body["users"]]
  697. self.assertEqual(expected_user_list, returned_order)
  698. self._check_fields(channel.json_body["users"])
  699. def _check_fields(self, content: JsonDict):
  700. """Checks that the expected user attributes are present in content
  701. Args:
  702. content: List that is checked for content
  703. """
  704. for u in content:
  705. self.assertIn("name", u)
  706. self.assertIn("is_guest", u)
  707. self.assertIn("admin", u)
  708. self.assertIn("user_type", u)
  709. self.assertIn("deactivated", u)
  710. self.assertIn("shadow_banned", u)
  711. self.assertIn("displayname", u)
  712. self.assertIn("avatar_url", u)
  713. def _create_users(self, number_users: int):
  714. """
  715. Create a number of users
  716. Args:
  717. number_users: Number of users to be created
  718. """
  719. for i in range(1, number_users + 1):
  720. self.register_user(
  721. "user%d" % i,
  722. "pass%d" % i,
  723. admin=False,
  724. displayname="Name %d" % i,
  725. )
  726. class DeactivateAccountTestCase(unittest.HomeserverTestCase):
  727. servlets = [
  728. synapse.rest.admin.register_servlets,
  729. login.register_servlets,
  730. ]
  731. def prepare(self, reactor, clock, hs):
  732. self.store = hs.get_datastore()
  733. self.admin_user = self.register_user("admin", "pass", admin=True)
  734. self.admin_user_tok = self.login("admin", "pass")
  735. self.other_user = self.register_user("user", "pass", displayname="User1")
  736. self.other_user_token = self.login("user", "pass")
  737. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  738. self.other_user
  739. )
  740. self.url = "/_synapse/admin/v1/deactivate/%s" % urllib.parse.quote(
  741. self.other_user
  742. )
  743. # set attributes for user
  744. self.get_success(
  745. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  746. )
  747. self.get_success(
  748. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  749. )
  750. def test_no_auth(self):
  751. """
  752. Try to deactivate users without authentication.
  753. """
  754. channel = self.make_request("POST", self.url, b"{}")
  755. self.assertEqual(401, channel.code, msg=channel.json_body)
  756. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  757. def test_requester_is_not_admin(self):
  758. """
  759. If the user is not a server admin, an error is returned.
  760. """
  761. url = "/_synapse/admin/v1/deactivate/@bob:test"
  762. channel = self.make_request("POST", url, access_token=self.other_user_token)
  763. self.assertEqual(403, channel.code, msg=channel.json_body)
  764. self.assertEqual("You are not a server admin", channel.json_body["error"])
  765. channel = self.make_request(
  766. "POST",
  767. url,
  768. access_token=self.other_user_token,
  769. content=b"{}",
  770. )
  771. self.assertEqual(403, channel.code, msg=channel.json_body)
  772. self.assertEqual("You are not a server admin", channel.json_body["error"])
  773. def test_user_does_not_exist(self):
  774. """
  775. Tests that deactivation for a user that does not exist returns a 404
  776. """
  777. channel = self.make_request(
  778. "POST",
  779. "/_synapse/admin/v1/deactivate/@unknown_person:test",
  780. access_token=self.admin_user_tok,
  781. )
  782. self.assertEqual(404, channel.code, msg=channel.json_body)
  783. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  784. def test_erase_is_not_bool(self):
  785. """
  786. If parameter `erase` is not boolean, return an error
  787. """
  788. body = json.dumps({"erase": "False"})
  789. channel = self.make_request(
  790. "POST",
  791. self.url,
  792. content=body.encode(encoding="utf_8"),
  793. access_token=self.admin_user_tok,
  794. )
  795. self.assertEqual(400, channel.code, msg=channel.json_body)
  796. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  797. def test_user_is_not_local(self):
  798. """
  799. Tests that deactivation for a user that is not a local returns a 400
  800. """
  801. url = "/_synapse/admin/v1/deactivate/@unknown_person:unknown_domain"
  802. channel = self.make_request("POST", url, access_token=self.admin_user_tok)
  803. self.assertEqual(400, channel.code, msg=channel.json_body)
  804. self.assertEqual("Can only deactivate local users", channel.json_body["error"])
  805. def test_deactivate_user_erase_true(self):
  806. """
  807. Test deactivating a user and set `erase` to `true`
  808. """
  809. # Get user
  810. channel = self.make_request(
  811. "GET",
  812. self.url_other_user,
  813. access_token=self.admin_user_tok,
  814. )
  815. self.assertEqual(200, channel.code, msg=channel.json_body)
  816. self.assertEqual("@user:test", channel.json_body["name"])
  817. self.assertEqual(False, channel.json_body["deactivated"])
  818. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  819. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  820. self.assertEqual("User1", channel.json_body["displayname"])
  821. # Deactivate and erase user
  822. channel = self.make_request(
  823. "POST",
  824. self.url,
  825. access_token=self.admin_user_tok,
  826. content={"erase": True},
  827. )
  828. self.assertEqual(200, channel.code, msg=channel.json_body)
  829. # Get user
  830. channel = self.make_request(
  831. "GET",
  832. self.url_other_user,
  833. access_token=self.admin_user_tok,
  834. )
  835. self.assertEqual(200, channel.code, msg=channel.json_body)
  836. self.assertEqual("@user:test", channel.json_body["name"])
  837. self.assertEqual(True, channel.json_body["deactivated"])
  838. self.assertEqual(0, len(channel.json_body["threepids"]))
  839. self.assertIsNone(channel.json_body["avatar_url"])
  840. self.assertIsNone(channel.json_body["displayname"])
  841. self._is_erased("@user:test", True)
  842. def test_deactivate_user_erase_false(self):
  843. """
  844. Test deactivating a user and set `erase` to `false`
  845. """
  846. # Get user
  847. channel = self.make_request(
  848. "GET",
  849. self.url_other_user,
  850. access_token=self.admin_user_tok,
  851. )
  852. self.assertEqual(200, channel.code, msg=channel.json_body)
  853. self.assertEqual("@user:test", channel.json_body["name"])
  854. self.assertEqual(False, channel.json_body["deactivated"])
  855. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  856. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  857. self.assertEqual("User1", channel.json_body["displayname"])
  858. # Deactivate user
  859. channel = self.make_request(
  860. "POST",
  861. self.url,
  862. access_token=self.admin_user_tok,
  863. content={"erase": False},
  864. )
  865. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  866. # Get user
  867. channel = self.make_request(
  868. "GET",
  869. self.url_other_user,
  870. access_token=self.admin_user_tok,
  871. )
  872. self.assertEqual(200, channel.code, msg=channel.json_body)
  873. self.assertEqual("@user:test", channel.json_body["name"])
  874. self.assertEqual(True, channel.json_body["deactivated"])
  875. self.assertEqual(0, len(channel.json_body["threepids"]))
  876. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  877. self.assertEqual("User1", channel.json_body["displayname"])
  878. self._is_erased("@user:test", False)
  879. def test_deactivate_user_erase_true_no_profile(self):
  880. """
  881. Test deactivating a user and set `erase` to `true`
  882. if user has no profile information (stored in the database table `profiles`).
  883. """
  884. # Users normally have an entry in `profiles`, but occasionally they are created without one.
  885. # To test deactivation for users without a profile, we delete the profile information for our user.
  886. self.get_success(
  887. self.store.db_pool.simple_delete_one(
  888. table="profiles", keyvalues={"user_id": "user"}
  889. )
  890. )
  891. # Get user
  892. channel = self.make_request(
  893. "GET",
  894. self.url_other_user,
  895. access_token=self.admin_user_tok,
  896. )
  897. self.assertEqual(200, channel.code, msg=channel.json_body)
  898. self.assertEqual("@user:test", channel.json_body["name"])
  899. self.assertEqual(False, channel.json_body["deactivated"])
  900. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  901. self.assertIsNone(channel.json_body["avatar_url"])
  902. self.assertIsNone(channel.json_body["displayname"])
  903. # Deactivate and erase user
  904. channel = self.make_request(
  905. "POST",
  906. self.url,
  907. access_token=self.admin_user_tok,
  908. content={"erase": True},
  909. )
  910. self.assertEqual(200, channel.code, msg=channel.json_body)
  911. # Get user
  912. channel = self.make_request(
  913. "GET",
  914. self.url_other_user,
  915. access_token=self.admin_user_tok,
  916. )
  917. self.assertEqual(200, channel.code, msg=channel.json_body)
  918. self.assertEqual("@user:test", channel.json_body["name"])
  919. self.assertEqual(True, channel.json_body["deactivated"])
  920. self.assertEqual(0, len(channel.json_body["threepids"]))
  921. self.assertIsNone(channel.json_body["avatar_url"])
  922. self.assertIsNone(channel.json_body["displayname"])
  923. self._is_erased("@user:test", True)
  924. def _is_erased(self, user_id: str, expect: bool) -> None:
  925. """Assert that the user is erased or not"""
  926. d = self.store.is_user_erased(user_id)
  927. if expect:
  928. self.assertTrue(self.get_success(d))
  929. else:
  930. self.assertFalse(self.get_success(d))
  931. class UserRestTestCase(unittest.HomeserverTestCase):
  932. servlets = [
  933. synapse.rest.admin.register_servlets,
  934. login.register_servlets,
  935. sync.register_servlets,
  936. ]
  937. def prepare(self, reactor, clock, hs):
  938. self.store = hs.get_datastore()
  939. self.auth_handler = hs.get_auth_handler()
  940. # create users and get access tokens
  941. # regardless of whether password login or SSO is allowed
  942. self.admin_user = self.register_user("admin", "pass", admin=True)
  943. self.admin_user_tok = self.get_success(
  944. self.auth_handler.get_access_token_for_user_id(
  945. self.admin_user, device_id=None, valid_until_ms=None
  946. )
  947. )
  948. self.other_user = self.register_user("user", "pass", displayname="User")
  949. self.other_user_token = self.get_success(
  950. self.auth_handler.get_access_token_for_user_id(
  951. self.other_user, device_id=None, valid_until_ms=None
  952. )
  953. )
  954. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  955. self.other_user
  956. )
  957. def test_requester_is_no_admin(self):
  958. """
  959. If the user is not a server admin, an error is returned.
  960. """
  961. url = "/_synapse/admin/v2/users/@bob:test"
  962. channel = self.make_request(
  963. "GET",
  964. url,
  965. access_token=self.other_user_token,
  966. )
  967. self.assertEqual(403, channel.code, msg=channel.json_body)
  968. self.assertEqual("You are not a server admin", channel.json_body["error"])
  969. channel = self.make_request(
  970. "PUT",
  971. url,
  972. access_token=self.other_user_token,
  973. content=b"{}",
  974. )
  975. self.assertEqual(403, channel.code, msg=channel.json_body)
  976. self.assertEqual("You are not a server admin", channel.json_body["error"])
  977. def test_user_does_not_exist(self):
  978. """
  979. Tests that a lookup for a user that does not exist returns a 404
  980. """
  981. channel = self.make_request(
  982. "GET",
  983. "/_synapse/admin/v2/users/@unknown_person:test",
  984. access_token=self.admin_user_tok,
  985. )
  986. self.assertEqual(404, channel.code, msg=channel.json_body)
  987. self.assertEqual("M_NOT_FOUND", channel.json_body["errcode"])
  988. def test_get_user(self):
  989. """
  990. Test a simple get of a user.
  991. """
  992. channel = self.make_request(
  993. "GET",
  994. self.url_other_user,
  995. access_token=self.admin_user_tok,
  996. )
  997. self.assertEqual(200, channel.code, msg=channel.json_body)
  998. self.assertEqual("@user:test", channel.json_body["name"])
  999. self.assertEqual("User", channel.json_body["displayname"])
  1000. self._check_fields(channel.json_body)
  1001. def test_get_user_with_sso(self):
  1002. """
  1003. Test get a user with SSO details.
  1004. """
  1005. self.get_success(
  1006. self.store.record_user_external_id(
  1007. "auth_provider1", "external_id1", self.other_user
  1008. )
  1009. )
  1010. self.get_success(
  1011. self.store.record_user_external_id(
  1012. "auth_provider2", "external_id2", self.other_user
  1013. )
  1014. )
  1015. channel = self.make_request(
  1016. "GET",
  1017. self.url_other_user,
  1018. access_token=self.admin_user_tok,
  1019. )
  1020. self.assertEqual(200, channel.code, msg=channel.json_body)
  1021. self.assertEqual("@user:test", channel.json_body["name"])
  1022. self.assertEqual(
  1023. "external_id1", channel.json_body["external_ids"][0]["external_id"]
  1024. )
  1025. self.assertEqual(
  1026. "auth_provider1", channel.json_body["external_ids"][0]["auth_provider"]
  1027. )
  1028. self.assertEqual(
  1029. "external_id2", channel.json_body["external_ids"][1]["external_id"]
  1030. )
  1031. self.assertEqual(
  1032. "auth_provider2", channel.json_body["external_ids"][1]["auth_provider"]
  1033. )
  1034. self._check_fields(channel.json_body)
  1035. def test_create_server_admin(self):
  1036. """
  1037. Check that a new admin user is created successfully.
  1038. """
  1039. url = "/_synapse/admin/v2/users/@bob:test"
  1040. # Create user (server admin)
  1041. body = {
  1042. "password": "abc123",
  1043. "admin": True,
  1044. "displayname": "Bob's name",
  1045. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1046. "avatar_url": "mxc://fibble/wibble",
  1047. }
  1048. channel = self.make_request(
  1049. "PUT",
  1050. url,
  1051. access_token=self.admin_user_tok,
  1052. content=body,
  1053. )
  1054. self.assertEqual(201, channel.code, msg=channel.json_body)
  1055. self.assertEqual("@bob:test", channel.json_body["name"])
  1056. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1057. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1058. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1059. self.assertTrue(channel.json_body["admin"])
  1060. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1061. self._check_fields(channel.json_body)
  1062. # Get user
  1063. channel = self.make_request(
  1064. "GET",
  1065. url,
  1066. access_token=self.admin_user_tok,
  1067. )
  1068. self.assertEqual(200, channel.code, msg=channel.json_body)
  1069. self.assertEqual("@bob:test", channel.json_body["name"])
  1070. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1071. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1072. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1073. self.assertTrue(channel.json_body["admin"])
  1074. self.assertFalse(channel.json_body["is_guest"])
  1075. self.assertFalse(channel.json_body["deactivated"])
  1076. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1077. self._check_fields(channel.json_body)
  1078. def test_create_user(self):
  1079. """
  1080. Check that a new regular user is created successfully.
  1081. """
  1082. url = "/_synapse/admin/v2/users/@bob:test"
  1083. # Create user
  1084. body = {
  1085. "password": "abc123",
  1086. "admin": False,
  1087. "displayname": "Bob's name",
  1088. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1089. "avatar_url": "mxc://fibble/wibble",
  1090. }
  1091. channel = self.make_request(
  1092. "PUT",
  1093. url,
  1094. access_token=self.admin_user_tok,
  1095. content=body,
  1096. )
  1097. self.assertEqual(201, channel.code, msg=channel.json_body)
  1098. self.assertEqual("@bob:test", channel.json_body["name"])
  1099. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1100. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1101. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1102. self.assertFalse(channel.json_body["admin"])
  1103. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1104. self._check_fields(channel.json_body)
  1105. # Get user
  1106. channel = self.make_request(
  1107. "GET",
  1108. url,
  1109. access_token=self.admin_user_tok,
  1110. )
  1111. self.assertEqual(200, channel.code, msg=channel.json_body)
  1112. self.assertEqual("@bob:test", channel.json_body["name"])
  1113. self.assertEqual("Bob's name", channel.json_body["displayname"])
  1114. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1115. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1116. self.assertFalse(channel.json_body["admin"])
  1117. self.assertFalse(channel.json_body["is_guest"])
  1118. self.assertFalse(channel.json_body["deactivated"])
  1119. self.assertFalse(channel.json_body["shadow_banned"])
  1120. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  1121. self._check_fields(channel.json_body)
  1122. @override_config(
  1123. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1124. )
  1125. def test_create_user_mau_limit_reached_active_admin(self):
  1126. """
  1127. Check that an admin can register a new user via the admin API
  1128. even if the MAU limit is reached.
  1129. Admin user was active before creating user.
  1130. """
  1131. handler = self.hs.get_registration_handler()
  1132. # Sync to set admin user to active
  1133. # before limit of monthly active users is reached
  1134. channel = self.make_request("GET", "/sync", access_token=self.admin_user_tok)
  1135. if channel.code != 200:
  1136. raise HttpResponseException(
  1137. channel.code, channel.result["reason"], channel.result["body"]
  1138. )
  1139. # Set monthly active users to the limit
  1140. self.store.get_monthly_active_count = Mock(
  1141. return_value=make_awaitable(self.hs.config.max_mau_value)
  1142. )
  1143. # Check that the blocking of monthly active users is working as expected
  1144. # The registration of a new user fails due to the limit
  1145. self.get_failure(
  1146. handler.register_user(localpart="local_part"), ResourceLimitError
  1147. )
  1148. # Register new user with admin API
  1149. url = "/_synapse/admin/v2/users/@bob:test"
  1150. # Create user
  1151. channel = self.make_request(
  1152. "PUT",
  1153. url,
  1154. access_token=self.admin_user_tok,
  1155. content={"password": "abc123", "admin": False},
  1156. )
  1157. self.assertEqual(201, channel.code, msg=channel.json_body)
  1158. self.assertEqual("@bob:test", channel.json_body["name"])
  1159. self.assertFalse(channel.json_body["admin"])
  1160. @override_config(
  1161. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  1162. )
  1163. def test_create_user_mau_limit_reached_passive_admin(self):
  1164. """
  1165. Check that an admin can register a new user via the admin API
  1166. even if the MAU limit is reached.
  1167. Admin user was not active before creating user.
  1168. """
  1169. handler = self.hs.get_registration_handler()
  1170. # Set monthly active users to the limit
  1171. self.store.get_monthly_active_count = Mock(
  1172. return_value=make_awaitable(self.hs.config.max_mau_value)
  1173. )
  1174. # Check that the blocking of monthly active users is working as expected
  1175. # The registration of a new user fails due to the limit
  1176. self.get_failure(
  1177. handler.register_user(localpart="local_part"), ResourceLimitError
  1178. )
  1179. # Register new user with admin API
  1180. url = "/_synapse/admin/v2/users/@bob:test"
  1181. # Create user
  1182. channel = self.make_request(
  1183. "PUT",
  1184. url,
  1185. access_token=self.admin_user_tok,
  1186. content={"password": "abc123", "admin": False},
  1187. )
  1188. # Admin user is not blocked by mau anymore
  1189. self.assertEqual(201, channel.code, msg=channel.json_body)
  1190. self.assertEqual("@bob:test", channel.json_body["name"])
  1191. self.assertFalse(channel.json_body["admin"])
  1192. @override_config(
  1193. {
  1194. "email": {
  1195. "enable_notifs": True,
  1196. "notif_for_new_users": True,
  1197. "notif_from": "test@example.com",
  1198. },
  1199. "public_baseurl": "https://example.com",
  1200. }
  1201. )
  1202. def test_create_user_email_notif_for_new_users(self):
  1203. """
  1204. Check that a new regular user is created successfully and
  1205. got an email pusher.
  1206. """
  1207. url = "/_synapse/admin/v2/users/@bob:test"
  1208. # Create user
  1209. body = {
  1210. "password": "abc123",
  1211. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1212. }
  1213. channel = self.make_request(
  1214. "PUT",
  1215. url,
  1216. access_token=self.admin_user_tok,
  1217. content=body,
  1218. )
  1219. self.assertEqual(201, channel.code, msg=channel.json_body)
  1220. self.assertEqual("@bob:test", channel.json_body["name"])
  1221. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1222. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1223. pushers = self.get_success(
  1224. self.store.get_pushers_by({"user_name": "@bob:test"})
  1225. )
  1226. pushers = list(pushers)
  1227. self.assertEqual(len(pushers), 1)
  1228. self.assertEqual("@bob:test", pushers[0].user_name)
  1229. @override_config(
  1230. {
  1231. "email": {
  1232. "enable_notifs": False,
  1233. "notif_for_new_users": False,
  1234. "notif_from": "test@example.com",
  1235. },
  1236. "public_baseurl": "https://example.com",
  1237. }
  1238. )
  1239. def test_create_user_email_no_notif_for_new_users(self):
  1240. """
  1241. Check that a new regular user is created successfully and
  1242. got not an email pusher.
  1243. """
  1244. url = "/_synapse/admin/v2/users/@bob:test"
  1245. # Create user
  1246. body = {
  1247. "password": "abc123",
  1248. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  1249. }
  1250. channel = self.make_request(
  1251. "PUT",
  1252. url,
  1253. access_token=self.admin_user_tok,
  1254. content=body,
  1255. )
  1256. self.assertEqual(201, channel.code, msg=channel.json_body)
  1257. self.assertEqual("@bob:test", channel.json_body["name"])
  1258. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1259. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1260. pushers = self.get_success(
  1261. self.store.get_pushers_by({"user_name": "@bob:test"})
  1262. )
  1263. pushers = list(pushers)
  1264. self.assertEqual(len(pushers), 0)
  1265. def test_set_password(self):
  1266. """
  1267. Test setting a new password for another user.
  1268. """
  1269. # Change password
  1270. channel = self.make_request(
  1271. "PUT",
  1272. self.url_other_user,
  1273. access_token=self.admin_user_tok,
  1274. content={"password": "hahaha"},
  1275. )
  1276. self.assertEqual(200, channel.code, msg=channel.json_body)
  1277. self._check_fields(channel.json_body)
  1278. def test_set_displayname(self):
  1279. """
  1280. Test setting the displayname of another user.
  1281. """
  1282. # Modify user
  1283. channel = self.make_request(
  1284. "PUT",
  1285. self.url_other_user,
  1286. access_token=self.admin_user_tok,
  1287. content={"displayname": "foobar"},
  1288. )
  1289. self.assertEqual(200, channel.code, msg=channel.json_body)
  1290. self.assertEqual("@user:test", channel.json_body["name"])
  1291. self.assertEqual("foobar", channel.json_body["displayname"])
  1292. # Get user
  1293. channel = self.make_request(
  1294. "GET",
  1295. self.url_other_user,
  1296. access_token=self.admin_user_tok,
  1297. )
  1298. self.assertEqual(200, channel.code, msg=channel.json_body)
  1299. self.assertEqual("@user:test", channel.json_body["name"])
  1300. self.assertEqual("foobar", channel.json_body["displayname"])
  1301. def test_set_threepid(self):
  1302. """
  1303. Test setting threepid for an other user.
  1304. """
  1305. # Delete old and add new threepid to user
  1306. channel = self.make_request(
  1307. "PUT",
  1308. self.url_other_user,
  1309. access_token=self.admin_user_tok,
  1310. content={"threepids": [{"medium": "email", "address": "bob3@bob.bob"}]},
  1311. )
  1312. self.assertEqual(200, channel.code, msg=channel.json_body)
  1313. self.assertEqual("@user:test", channel.json_body["name"])
  1314. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1315. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  1316. # Get user
  1317. channel = self.make_request(
  1318. "GET",
  1319. self.url_other_user,
  1320. access_token=self.admin_user_tok,
  1321. )
  1322. self.assertEqual(200, channel.code, msg=channel.json_body)
  1323. self.assertEqual("@user:test", channel.json_body["name"])
  1324. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1325. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  1326. def test_deactivate_user(self):
  1327. """
  1328. Test deactivating another user.
  1329. """
  1330. # set attributes for user
  1331. self.get_success(
  1332. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  1333. )
  1334. self.get_success(
  1335. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  1336. )
  1337. # Get user
  1338. channel = self.make_request(
  1339. "GET",
  1340. self.url_other_user,
  1341. access_token=self.admin_user_tok,
  1342. )
  1343. self.assertEqual(200, channel.code, msg=channel.json_body)
  1344. self.assertEqual("@user:test", channel.json_body["name"])
  1345. self.assertFalse(channel.json_body["deactivated"])
  1346. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1347. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1348. self.assertEqual("User", channel.json_body["displayname"])
  1349. # Deactivate user
  1350. channel = self.make_request(
  1351. "PUT",
  1352. self.url_other_user,
  1353. access_token=self.admin_user_tok,
  1354. content={"deactivated": True},
  1355. )
  1356. self.assertEqual(200, channel.code, msg=channel.json_body)
  1357. self.assertEqual("@user:test", channel.json_body["name"])
  1358. self.assertTrue(channel.json_body["deactivated"])
  1359. self.assertIsNone(channel.json_body["password_hash"])
  1360. self.assertEqual(0, len(channel.json_body["threepids"]))
  1361. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1362. self.assertEqual("User", channel.json_body["displayname"])
  1363. # the user is deactivated, the threepid will be deleted
  1364. # Get user
  1365. channel = self.make_request(
  1366. "GET",
  1367. self.url_other_user,
  1368. access_token=self.admin_user_tok,
  1369. )
  1370. self.assertEqual(200, channel.code, msg=channel.json_body)
  1371. self.assertEqual("@user:test", channel.json_body["name"])
  1372. self.assertTrue(channel.json_body["deactivated"])
  1373. self.assertIsNone(channel.json_body["password_hash"])
  1374. self.assertEqual(0, len(channel.json_body["threepids"]))
  1375. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1376. self.assertEqual("User", channel.json_body["displayname"])
  1377. @override_config({"user_directory": {"enabled": True, "search_all_users": True}})
  1378. def test_change_name_deactivate_user_user_directory(self):
  1379. """
  1380. Test change profile information of a deactivated user and
  1381. check that it does not appear in user directory
  1382. """
  1383. # is in user directory
  1384. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1385. self.assertTrue(profile["display_name"] == "User")
  1386. # Deactivate user
  1387. channel = self.make_request(
  1388. "PUT",
  1389. self.url_other_user,
  1390. access_token=self.admin_user_tok,
  1391. content={"deactivated": True},
  1392. )
  1393. self.assertEqual(200, channel.code, msg=channel.json_body)
  1394. self.assertEqual("@user:test", channel.json_body["name"])
  1395. self.assertTrue(channel.json_body["deactivated"])
  1396. # is not in user directory
  1397. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1398. self.assertIsNone(profile)
  1399. # Set new displayname user
  1400. channel = self.make_request(
  1401. "PUT",
  1402. self.url_other_user,
  1403. access_token=self.admin_user_tok,
  1404. content={"displayname": "Foobar"},
  1405. )
  1406. self.assertEqual(200, channel.code, msg=channel.json_body)
  1407. self.assertEqual("@user:test", channel.json_body["name"])
  1408. self.assertTrue(channel.json_body["deactivated"])
  1409. self.assertEqual("Foobar", channel.json_body["displayname"])
  1410. # is not in user directory
  1411. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1412. self.assertIsNone(profile)
  1413. def test_reactivate_user(self):
  1414. """
  1415. Test reactivating another user.
  1416. """
  1417. # Deactivate the user.
  1418. self._deactivate_user("@user:test")
  1419. # Attempt to reactivate the user (without a password).
  1420. channel = self.make_request(
  1421. "PUT",
  1422. self.url_other_user,
  1423. access_token=self.admin_user_tok,
  1424. content={"deactivated": False},
  1425. )
  1426. self.assertEqual(400, channel.code, msg=channel.json_body)
  1427. # Reactivate the user.
  1428. channel = self.make_request(
  1429. "PUT",
  1430. self.url_other_user,
  1431. access_token=self.admin_user_tok,
  1432. content={"deactivated": False, "password": "foo"},
  1433. )
  1434. self.assertEqual(200, channel.code, msg=channel.json_body)
  1435. self.assertEqual("@user:test", channel.json_body["name"])
  1436. self.assertFalse(channel.json_body["deactivated"])
  1437. self.assertIsNotNone(channel.json_body["password_hash"])
  1438. self._is_erased("@user:test", False)
  1439. @override_config({"password_config": {"localdb_enabled": False}})
  1440. def test_reactivate_user_localdb_disabled(self):
  1441. """
  1442. Test reactivating another user when using SSO.
  1443. """
  1444. # Deactivate the user.
  1445. self._deactivate_user("@user:test")
  1446. # Reactivate the user with a password
  1447. channel = self.make_request(
  1448. "PUT",
  1449. self.url_other_user,
  1450. access_token=self.admin_user_tok,
  1451. content={"deactivated": False, "password": "foo"},
  1452. )
  1453. self.assertEqual(403, channel.code, msg=channel.json_body)
  1454. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1455. # Reactivate the user without a password.
  1456. channel = self.make_request(
  1457. "PUT",
  1458. self.url_other_user,
  1459. access_token=self.admin_user_tok,
  1460. content={"deactivated": False},
  1461. )
  1462. self.assertEqual(200, channel.code, msg=channel.json_body)
  1463. self.assertEqual("@user:test", channel.json_body["name"])
  1464. self.assertFalse(channel.json_body["deactivated"])
  1465. self.assertIsNone(channel.json_body["password_hash"])
  1466. self._is_erased("@user:test", False)
  1467. @override_config({"password_config": {"enabled": False}})
  1468. def test_reactivate_user_password_disabled(self):
  1469. """
  1470. Test reactivating another user when using SSO.
  1471. """
  1472. # Deactivate the user.
  1473. self._deactivate_user("@user:test")
  1474. # Reactivate the user with a password
  1475. channel = self.make_request(
  1476. "PUT",
  1477. self.url_other_user,
  1478. access_token=self.admin_user_tok,
  1479. content={"deactivated": False, "password": "foo"},
  1480. )
  1481. self.assertEqual(403, channel.code, msg=channel.json_body)
  1482. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1483. # Reactivate the user without a password.
  1484. channel = self.make_request(
  1485. "PUT",
  1486. self.url_other_user,
  1487. access_token=self.admin_user_tok,
  1488. content={"deactivated": False},
  1489. )
  1490. self.assertEqual(200, channel.code, msg=channel.json_body)
  1491. self.assertEqual("@user:test", channel.json_body["name"])
  1492. self.assertFalse(channel.json_body["deactivated"])
  1493. self.assertIsNone(channel.json_body["password_hash"])
  1494. self._is_erased("@user:test", False)
  1495. def test_set_user_as_admin(self):
  1496. """
  1497. Test setting the admin flag on a user.
  1498. """
  1499. # Set a user as an admin
  1500. channel = self.make_request(
  1501. "PUT",
  1502. self.url_other_user,
  1503. access_token=self.admin_user_tok,
  1504. content={"admin": True},
  1505. )
  1506. self.assertEqual(200, channel.code, msg=channel.json_body)
  1507. self.assertEqual("@user:test", channel.json_body["name"])
  1508. self.assertTrue(channel.json_body["admin"])
  1509. # Get user
  1510. channel = self.make_request(
  1511. "GET",
  1512. self.url_other_user,
  1513. access_token=self.admin_user_tok,
  1514. )
  1515. self.assertEqual(200, channel.code, msg=channel.json_body)
  1516. self.assertEqual("@user:test", channel.json_body["name"])
  1517. self.assertTrue(channel.json_body["admin"])
  1518. def test_accidental_deactivation_prevention(self):
  1519. """
  1520. Ensure an account can't accidentally be deactivated by using a str value
  1521. for the deactivated body parameter
  1522. """
  1523. url = "/_synapse/admin/v2/users/@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"},
  1530. )
  1531. self.assertEqual(201, channel.code, msg=channel.json_body)
  1532. self.assertEqual("@bob:test", channel.json_body["name"])
  1533. self.assertEqual("bob", channel.json_body["displayname"])
  1534. # Get user
  1535. channel = self.make_request(
  1536. "GET",
  1537. url,
  1538. access_token=self.admin_user_tok,
  1539. )
  1540. self.assertEqual(200, channel.code, msg=channel.json_body)
  1541. self.assertEqual("@bob:test", channel.json_body["name"])
  1542. self.assertEqual("bob", channel.json_body["displayname"])
  1543. self.assertEqual(0, channel.json_body["deactivated"])
  1544. # Change password (and use a str for deactivate instead of a bool)
  1545. channel = self.make_request(
  1546. "PUT",
  1547. url,
  1548. access_token=self.admin_user_tok,
  1549. content={"password": "abc123", "deactivated": "false"},
  1550. )
  1551. self.assertEqual(400, channel.code, msg=channel.json_body)
  1552. # Check user is not deactivated
  1553. channel = self.make_request(
  1554. "GET",
  1555. url,
  1556. access_token=self.admin_user_tok,
  1557. )
  1558. self.assertEqual(200, channel.code, msg=channel.json_body)
  1559. self.assertEqual("@bob:test", channel.json_body["name"])
  1560. self.assertEqual("bob", channel.json_body["displayname"])
  1561. # Ensure they're still alive
  1562. self.assertEqual(0, channel.json_body["deactivated"])
  1563. def _is_erased(self, user_id: str, expect: bool) -> None:
  1564. """Assert that the user is erased or not"""
  1565. d = self.store.is_user_erased(user_id)
  1566. if expect:
  1567. self.assertTrue(self.get_success(d))
  1568. else:
  1569. self.assertFalse(self.get_success(d))
  1570. def _deactivate_user(self, user_id: str) -> None:
  1571. """Deactivate user and set as erased"""
  1572. # Deactivate the user.
  1573. channel = self.make_request(
  1574. "PUT",
  1575. "/_synapse/admin/v2/users/%s" % urllib.parse.quote(user_id),
  1576. access_token=self.admin_user_tok,
  1577. content={"deactivated": True},
  1578. )
  1579. self.assertEqual(200, channel.code, msg=channel.json_body)
  1580. self.assertTrue(channel.json_body["deactivated"])
  1581. self.assertIsNone(channel.json_body["password_hash"])
  1582. self._is_erased(user_id, False)
  1583. d = self.store.mark_user_erased(user_id)
  1584. self.assertIsNone(self.get_success(d))
  1585. self._is_erased(user_id, True)
  1586. def _check_fields(self, content: JsonDict):
  1587. """Checks that the expected user attributes are present in content
  1588. Args:
  1589. content: Content dictionary to check
  1590. """
  1591. self.assertIn("displayname", content)
  1592. self.assertIn("threepids", content)
  1593. self.assertIn("avatar_url", content)
  1594. self.assertIn("admin", content)
  1595. self.assertIn("deactivated", content)
  1596. self.assertIn("shadow_banned", content)
  1597. self.assertIn("password_hash", content)
  1598. self.assertIn("creation_ts", content)
  1599. self.assertIn("appservice_id", content)
  1600. self.assertIn("consent_server_notice_sent", content)
  1601. self.assertIn("consent_version", content)
  1602. self.assertIn("external_ids", content)
  1603. class UserMembershipRestTestCase(unittest.HomeserverTestCase):
  1604. servlets = [
  1605. synapse.rest.admin.register_servlets,
  1606. login.register_servlets,
  1607. room.register_servlets,
  1608. ]
  1609. def prepare(self, reactor, clock, hs):
  1610. self.admin_user = self.register_user("admin", "pass", admin=True)
  1611. self.admin_user_tok = self.login("admin", "pass")
  1612. self.other_user = self.register_user("user", "pass")
  1613. self.url = "/_synapse/admin/v1/users/%s/joined_rooms" % urllib.parse.quote(
  1614. self.other_user
  1615. )
  1616. def test_no_auth(self):
  1617. """
  1618. Try to list rooms of an user without authentication.
  1619. """
  1620. channel = self.make_request("GET", self.url, b"{}")
  1621. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1622. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1623. def test_requester_is_no_admin(self):
  1624. """
  1625. If the user is not a server admin, an error is returned.
  1626. """
  1627. other_user_token = self.login("user", "pass")
  1628. channel = self.make_request(
  1629. "GET",
  1630. self.url,
  1631. access_token=other_user_token,
  1632. )
  1633. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1634. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1635. def test_user_does_not_exist(self):
  1636. """
  1637. Tests that a lookup for a user that does not exist returns an empty list
  1638. """
  1639. url = "/_synapse/admin/v1/users/@unknown_person:test/joined_rooms"
  1640. channel = self.make_request(
  1641. "GET",
  1642. url,
  1643. access_token=self.admin_user_tok,
  1644. )
  1645. self.assertEqual(200, channel.code, msg=channel.json_body)
  1646. self.assertEqual(0, channel.json_body["total"])
  1647. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1648. def test_user_is_not_local(self):
  1649. """
  1650. Tests that a lookup for a user that is not a local and participates in no conversation returns an empty list
  1651. """
  1652. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/joined_rooms"
  1653. channel = self.make_request(
  1654. "GET",
  1655. url,
  1656. access_token=self.admin_user_tok,
  1657. )
  1658. self.assertEqual(200, channel.code, msg=channel.json_body)
  1659. self.assertEqual(0, channel.json_body["total"])
  1660. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1661. def test_no_memberships(self):
  1662. """
  1663. Tests that a normal lookup for rooms is successfully
  1664. if user has no memberships
  1665. """
  1666. # Get rooms
  1667. channel = self.make_request(
  1668. "GET",
  1669. self.url,
  1670. access_token=self.admin_user_tok,
  1671. )
  1672. self.assertEqual(200, channel.code, msg=channel.json_body)
  1673. self.assertEqual(0, channel.json_body["total"])
  1674. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1675. def test_get_rooms(self):
  1676. """
  1677. Tests that a normal lookup for rooms is successfully
  1678. """
  1679. # Create rooms and join
  1680. other_user_tok = self.login("user", "pass")
  1681. number_rooms = 5
  1682. for _ in range(number_rooms):
  1683. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  1684. # Get rooms
  1685. channel = self.make_request(
  1686. "GET",
  1687. self.url,
  1688. access_token=self.admin_user_tok,
  1689. )
  1690. self.assertEqual(200, channel.code, msg=channel.json_body)
  1691. self.assertEqual(number_rooms, channel.json_body["total"])
  1692. self.assertEqual(number_rooms, len(channel.json_body["joined_rooms"]))
  1693. def test_get_rooms_with_nonlocal_user(self):
  1694. """
  1695. Tests that a normal lookup for rooms is successful with a non-local user
  1696. """
  1697. other_user_tok = self.login("user", "pass")
  1698. event_builder_factory = self.hs.get_event_builder_factory()
  1699. event_creation_handler = self.hs.get_event_creation_handler()
  1700. storage = self.hs.get_storage()
  1701. # Create two rooms, one with a local user only and one with both a local
  1702. # and remote user.
  1703. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  1704. local_and_remote_room_id = self.helper.create_room_as(
  1705. self.other_user, tok=other_user_tok
  1706. )
  1707. # Add a remote user to the room.
  1708. builder = event_builder_factory.for_room_version(
  1709. RoomVersions.V1,
  1710. {
  1711. "type": "m.room.member",
  1712. "sender": "@joiner:remote_hs",
  1713. "state_key": "@joiner:remote_hs",
  1714. "room_id": local_and_remote_room_id,
  1715. "content": {"membership": "join"},
  1716. },
  1717. )
  1718. event, context = self.get_success(
  1719. event_creation_handler.create_new_client_event(builder)
  1720. )
  1721. self.get_success(storage.persistence.persist_event(event, context))
  1722. # Now get rooms
  1723. url = "/_synapse/admin/v1/users/@joiner:remote_hs/joined_rooms"
  1724. channel = self.make_request(
  1725. "GET",
  1726. url,
  1727. access_token=self.admin_user_tok,
  1728. )
  1729. self.assertEqual(200, channel.code, msg=channel.json_body)
  1730. self.assertEqual(1, channel.json_body["total"])
  1731. self.assertEqual([local_and_remote_room_id], channel.json_body["joined_rooms"])
  1732. class PushersRestTestCase(unittest.HomeserverTestCase):
  1733. servlets = [
  1734. synapse.rest.admin.register_servlets,
  1735. login.register_servlets,
  1736. ]
  1737. def prepare(self, reactor, clock, hs):
  1738. self.store = hs.get_datastore()
  1739. self.admin_user = self.register_user("admin", "pass", admin=True)
  1740. self.admin_user_tok = self.login("admin", "pass")
  1741. self.other_user = self.register_user("user", "pass")
  1742. self.url = "/_synapse/admin/v1/users/%s/pushers" % urllib.parse.quote(
  1743. self.other_user
  1744. )
  1745. def test_no_auth(self):
  1746. """
  1747. Try to list pushers of an user without authentication.
  1748. """
  1749. channel = self.make_request("GET", self.url, b"{}")
  1750. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1751. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1752. def test_requester_is_no_admin(self):
  1753. """
  1754. If the user is not a server admin, an error is returned.
  1755. """
  1756. other_user_token = self.login("user", "pass")
  1757. channel = self.make_request(
  1758. "GET",
  1759. self.url,
  1760. access_token=other_user_token,
  1761. )
  1762. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1763. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1764. def test_user_does_not_exist(self):
  1765. """
  1766. Tests that a lookup for a user that does not exist returns a 404
  1767. """
  1768. url = "/_synapse/admin/v1/users/@unknown_person:test/pushers"
  1769. channel = self.make_request(
  1770. "GET",
  1771. url,
  1772. access_token=self.admin_user_tok,
  1773. )
  1774. self.assertEqual(404, channel.code, msg=channel.json_body)
  1775. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1776. def test_user_is_not_local(self):
  1777. """
  1778. Tests that a lookup for a user that is not a local returns a 400
  1779. """
  1780. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/pushers"
  1781. channel = self.make_request(
  1782. "GET",
  1783. url,
  1784. access_token=self.admin_user_tok,
  1785. )
  1786. self.assertEqual(400, channel.code, msg=channel.json_body)
  1787. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  1788. def test_get_pushers(self):
  1789. """
  1790. Tests that a normal lookup for pushers is successfully
  1791. """
  1792. # Get pushers
  1793. channel = self.make_request(
  1794. "GET",
  1795. self.url,
  1796. access_token=self.admin_user_tok,
  1797. )
  1798. self.assertEqual(200, channel.code, msg=channel.json_body)
  1799. self.assertEqual(0, channel.json_body["total"])
  1800. # Register the pusher
  1801. other_user_token = self.login("user", "pass")
  1802. user_tuple = self.get_success(
  1803. self.store.get_user_by_access_token(other_user_token)
  1804. )
  1805. token_id = user_tuple.token_id
  1806. self.get_success(
  1807. self.hs.get_pusherpool().add_pusher(
  1808. user_id=self.other_user,
  1809. access_token=token_id,
  1810. kind="http",
  1811. app_id="m.http",
  1812. app_display_name="HTTP Push Notifications",
  1813. device_display_name="pushy push",
  1814. pushkey="a@example.com",
  1815. lang=None,
  1816. data={"url": "https://example.com/_matrix/push/v1/notify"},
  1817. )
  1818. )
  1819. # Get pushers
  1820. channel = self.make_request(
  1821. "GET",
  1822. self.url,
  1823. access_token=self.admin_user_tok,
  1824. )
  1825. self.assertEqual(200, channel.code, msg=channel.json_body)
  1826. self.assertEqual(1, channel.json_body["total"])
  1827. for p in channel.json_body["pushers"]:
  1828. self.assertIn("pushkey", p)
  1829. self.assertIn("kind", p)
  1830. self.assertIn("app_id", p)
  1831. self.assertIn("app_display_name", p)
  1832. self.assertIn("device_display_name", p)
  1833. self.assertIn("profile_tag", p)
  1834. self.assertIn("lang", p)
  1835. self.assertIn("url", p["data"])
  1836. class UserMediaRestTestCase(unittest.HomeserverTestCase):
  1837. servlets = [
  1838. synapse.rest.admin.register_servlets,
  1839. login.register_servlets,
  1840. ]
  1841. def prepare(self, reactor, clock, hs):
  1842. self.store = hs.get_datastore()
  1843. self.media_repo = hs.get_media_repository_resource()
  1844. self.admin_user = self.register_user("admin", "pass", admin=True)
  1845. self.admin_user_tok = self.login("admin", "pass")
  1846. self.other_user = self.register_user("user", "pass")
  1847. self.url = "/_synapse/admin/v1/users/%s/media" % urllib.parse.quote(
  1848. self.other_user
  1849. )
  1850. def test_no_auth(self):
  1851. """
  1852. Try to list media of an user without authentication.
  1853. """
  1854. channel = self.make_request("GET", self.url, b"{}")
  1855. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1856. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1857. def test_requester_is_no_admin(self):
  1858. """
  1859. If the user is not a server admin, an error is returned.
  1860. """
  1861. other_user_token = self.login("user", "pass")
  1862. channel = self.make_request(
  1863. "GET",
  1864. self.url,
  1865. access_token=other_user_token,
  1866. )
  1867. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1868. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1869. def test_user_does_not_exist(self):
  1870. """
  1871. Tests that a lookup for a user that does not exist returns a 404
  1872. """
  1873. url = "/_synapse/admin/v1/users/@unknown_person:test/media"
  1874. channel = self.make_request(
  1875. "GET",
  1876. url,
  1877. access_token=self.admin_user_tok,
  1878. )
  1879. self.assertEqual(404, channel.code, msg=channel.json_body)
  1880. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1881. def test_user_is_not_local(self):
  1882. """
  1883. Tests that a lookup for a user that is not a local returns a 400
  1884. """
  1885. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/media"
  1886. channel = self.make_request(
  1887. "GET",
  1888. url,
  1889. access_token=self.admin_user_tok,
  1890. )
  1891. self.assertEqual(400, channel.code, msg=channel.json_body)
  1892. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  1893. def test_limit(self):
  1894. """
  1895. Testing list of media with limit
  1896. """
  1897. number_media = 20
  1898. other_user_tok = self.login("user", "pass")
  1899. self._create_media_for_user(other_user_tok, number_media)
  1900. channel = self.make_request(
  1901. "GET",
  1902. self.url + "?limit=5",
  1903. access_token=self.admin_user_tok,
  1904. )
  1905. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1906. self.assertEqual(channel.json_body["total"], number_media)
  1907. self.assertEqual(len(channel.json_body["media"]), 5)
  1908. self.assertEqual(channel.json_body["next_token"], 5)
  1909. self._check_fields(channel.json_body["media"])
  1910. def test_from(self):
  1911. """
  1912. Testing list of media with a defined starting point (from)
  1913. """
  1914. number_media = 20
  1915. other_user_tok = self.login("user", "pass")
  1916. self._create_media_for_user(other_user_tok, number_media)
  1917. channel = self.make_request(
  1918. "GET",
  1919. self.url + "?from=5",
  1920. access_token=self.admin_user_tok,
  1921. )
  1922. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1923. self.assertEqual(channel.json_body["total"], number_media)
  1924. self.assertEqual(len(channel.json_body["media"]), 15)
  1925. self.assertNotIn("next_token", channel.json_body)
  1926. self._check_fields(channel.json_body["media"])
  1927. def test_limit_and_from(self):
  1928. """
  1929. Testing list of media with a defined starting point and limit
  1930. """
  1931. number_media = 20
  1932. other_user_tok = self.login("user", "pass")
  1933. self._create_media_for_user(other_user_tok, number_media)
  1934. channel = self.make_request(
  1935. "GET",
  1936. self.url + "?from=5&limit=10",
  1937. access_token=self.admin_user_tok,
  1938. )
  1939. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1940. self.assertEqual(channel.json_body["total"], number_media)
  1941. self.assertEqual(channel.json_body["next_token"], 15)
  1942. self.assertEqual(len(channel.json_body["media"]), 10)
  1943. self._check_fields(channel.json_body["media"])
  1944. def test_invalid_parameter(self):
  1945. """
  1946. If parameters are invalid, an error is returned.
  1947. """
  1948. # unkown order_by
  1949. channel = self.make_request(
  1950. "GET",
  1951. self.url + "?order_by=bar",
  1952. access_token=self.admin_user_tok,
  1953. )
  1954. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1955. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1956. # invalid search order
  1957. channel = self.make_request(
  1958. "GET",
  1959. self.url + "?dir=bar",
  1960. access_token=self.admin_user_tok,
  1961. )
  1962. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1963. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  1964. # negative limit
  1965. channel = self.make_request(
  1966. "GET",
  1967. self.url + "?limit=-5",
  1968. access_token=self.admin_user_tok,
  1969. )
  1970. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1971. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  1972. # negative from
  1973. channel = self.make_request(
  1974. "GET",
  1975. self.url + "?from=-5",
  1976. access_token=self.admin_user_tok,
  1977. )
  1978. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1979. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  1980. def test_next_token(self):
  1981. """
  1982. Testing that `next_token` appears at the right place
  1983. """
  1984. number_media = 20
  1985. other_user_tok = self.login("user", "pass")
  1986. self._create_media_for_user(other_user_tok, number_media)
  1987. # `next_token` does not appear
  1988. # Number of results is the number of entries
  1989. channel = self.make_request(
  1990. "GET",
  1991. self.url + "?limit=20",
  1992. access_token=self.admin_user_tok,
  1993. )
  1994. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1995. self.assertEqual(channel.json_body["total"], number_media)
  1996. self.assertEqual(len(channel.json_body["media"]), number_media)
  1997. self.assertNotIn("next_token", channel.json_body)
  1998. # `next_token` does not appear
  1999. # Number of max results is larger than the number of entries
  2000. channel = self.make_request(
  2001. "GET",
  2002. self.url + "?limit=21",
  2003. access_token=self.admin_user_tok,
  2004. )
  2005. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2006. self.assertEqual(channel.json_body["total"], number_media)
  2007. self.assertEqual(len(channel.json_body["media"]), number_media)
  2008. self.assertNotIn("next_token", channel.json_body)
  2009. # `next_token` does appear
  2010. # Number of max results is smaller than the number of entries
  2011. channel = self.make_request(
  2012. "GET",
  2013. self.url + "?limit=19",
  2014. access_token=self.admin_user_tok,
  2015. )
  2016. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2017. self.assertEqual(channel.json_body["total"], number_media)
  2018. self.assertEqual(len(channel.json_body["media"]), 19)
  2019. self.assertEqual(channel.json_body["next_token"], 19)
  2020. # Check
  2021. # Set `from` to value of `next_token` for request remaining entries
  2022. # `next_token` does not appear
  2023. channel = self.make_request(
  2024. "GET",
  2025. self.url + "?from=19",
  2026. access_token=self.admin_user_tok,
  2027. )
  2028. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2029. self.assertEqual(channel.json_body["total"], number_media)
  2030. self.assertEqual(len(channel.json_body["media"]), 1)
  2031. self.assertNotIn("next_token", channel.json_body)
  2032. def test_user_has_no_media(self):
  2033. """
  2034. Tests that a normal lookup for media is successfully
  2035. if user has no media created
  2036. """
  2037. channel = self.make_request(
  2038. "GET",
  2039. self.url,
  2040. access_token=self.admin_user_tok,
  2041. )
  2042. self.assertEqual(200, channel.code, msg=channel.json_body)
  2043. self.assertEqual(0, channel.json_body["total"])
  2044. self.assertEqual(0, len(channel.json_body["media"]))
  2045. def test_get_media(self):
  2046. """
  2047. Tests that a normal lookup for media is successfully
  2048. """
  2049. number_media = 5
  2050. other_user_tok = self.login("user", "pass")
  2051. self._create_media_for_user(other_user_tok, number_media)
  2052. channel = self.make_request(
  2053. "GET",
  2054. self.url,
  2055. access_token=self.admin_user_tok,
  2056. )
  2057. self.assertEqual(200, channel.code, msg=channel.json_body)
  2058. self.assertEqual(number_media, channel.json_body["total"])
  2059. self.assertEqual(number_media, len(channel.json_body["media"]))
  2060. self.assertNotIn("next_token", channel.json_body)
  2061. self._check_fields(channel.json_body["media"])
  2062. def test_order_by(self):
  2063. """
  2064. Testing order list with parameter `order_by`
  2065. """
  2066. other_user_tok = self.login("user", "pass")
  2067. # Resolution: 1×1, MIME type: image/png, Extension: png, Size: 67 B
  2068. image_data1 = unhexlify(
  2069. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  2070. b"0000001f15c4890000000a49444154789c63000100000500010d"
  2071. b"0a2db40000000049454e44ae426082"
  2072. )
  2073. # Resolution: 1×1, MIME type: image/gif, Extension: gif, Size: 35 B
  2074. image_data2 = unhexlify(
  2075. b"47494638376101000100800100000000"
  2076. b"ffffff2c00000000010001000002024c"
  2077. b"01003b"
  2078. )
  2079. # Resolution: 1×1, MIME type: image/bmp, Extension: bmp, Size: 54 B
  2080. image_data3 = unhexlify(
  2081. b"424d3a0000000000000036000000280000000100000001000000"
  2082. b"0100180000000000040000000000000000000000000000000000"
  2083. b"0000"
  2084. )
  2085. # create media and make sure they do not have the same timestamp
  2086. media1 = self._create_media_and_access(other_user_tok, image_data1, "image.png")
  2087. self.pump(1.0)
  2088. media2 = self._create_media_and_access(other_user_tok, image_data2, "image.gif")
  2089. self.pump(1.0)
  2090. media3 = self._create_media_and_access(other_user_tok, image_data3, "image.bmp")
  2091. self.pump(1.0)
  2092. # Mark one media as safe from quarantine.
  2093. self.get_success(self.store.mark_local_media_as_safe(media2))
  2094. # Quarantine one media
  2095. self.get_success(
  2096. self.store.quarantine_media_by_id("test", media3, self.admin_user)
  2097. )
  2098. # order by default ("created_ts")
  2099. # default is backwards
  2100. self._order_test([media3, media2, media1], None)
  2101. self._order_test([media1, media2, media3], None, "f")
  2102. self._order_test([media3, media2, media1], None, "b")
  2103. # sort by media_id
  2104. sorted_media = sorted([media1, media2, media3], reverse=False)
  2105. sorted_media_reverse = sorted(sorted_media, reverse=True)
  2106. # order by media_id
  2107. self._order_test(sorted_media, "media_id")
  2108. self._order_test(sorted_media, "media_id", "f")
  2109. self._order_test(sorted_media_reverse, "media_id", "b")
  2110. # order by upload_name
  2111. self._order_test([media3, media2, media1], "upload_name")
  2112. self._order_test([media3, media2, media1], "upload_name", "f")
  2113. self._order_test([media1, media2, media3], "upload_name", "b")
  2114. # order by media_type
  2115. # result is ordered by media_id
  2116. # because of uploaded media_type is always 'application/json'
  2117. self._order_test(sorted_media, "media_type")
  2118. self._order_test(sorted_media, "media_type", "f")
  2119. self._order_test(sorted_media, "media_type", "b")
  2120. # order by media_length
  2121. self._order_test([media2, media3, media1], "media_length")
  2122. self._order_test([media2, media3, media1], "media_length", "f")
  2123. self._order_test([media1, media3, media2], "media_length", "b")
  2124. # order by created_ts
  2125. self._order_test([media1, media2, media3], "created_ts")
  2126. self._order_test([media1, media2, media3], "created_ts", "f")
  2127. self._order_test([media3, media2, media1], "created_ts", "b")
  2128. # order by last_access_ts
  2129. self._order_test([media1, media2, media3], "last_access_ts")
  2130. self._order_test([media1, media2, media3], "last_access_ts", "f")
  2131. self._order_test([media3, media2, media1], "last_access_ts", "b")
  2132. # order by quarantined_by
  2133. # one media is in quarantine, others are ordered by media_ids
  2134. # Different sort order of SQlite and PostreSQL
  2135. # If a media is not in quarantine `quarantined_by` is NULL
  2136. # SQLite considers NULL to be smaller than any other value.
  2137. # PostreSQL considers NULL to be larger than any other value.
  2138. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by")
  2139. # self._order_test(sorted([media1, media2]) + [media3], "quarantined_by", "f")
  2140. # self._order_test([media3] + sorted([media1, media2]), "quarantined_by", "b")
  2141. # order by safe_from_quarantine
  2142. # one media is safe from quarantine, others are ordered by media_ids
  2143. self._order_test(sorted([media1, media3]) + [media2], "safe_from_quarantine")
  2144. self._order_test(
  2145. sorted([media1, media3]) + [media2], "safe_from_quarantine", "f"
  2146. )
  2147. self._order_test(
  2148. [media2] + sorted([media1, media3]), "safe_from_quarantine", "b"
  2149. )
  2150. def _create_media_for_user(self, user_token: str, number_media: int):
  2151. """
  2152. Create a number of media for a specific user
  2153. Args:
  2154. user_token: Access token of the user
  2155. number_media: Number of media to be created for the user
  2156. """
  2157. for _ in range(number_media):
  2158. # file size is 67 Byte
  2159. image_data = unhexlify(
  2160. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  2161. b"0000001f15c4890000000a49444154789c63000100000500010d"
  2162. b"0a2db40000000049454e44ae426082"
  2163. )
  2164. self._create_media_and_access(user_token, image_data)
  2165. def _create_media_and_access(
  2166. self,
  2167. user_token: str,
  2168. image_data: bytes,
  2169. filename: str = "image1.png",
  2170. ) -> str:
  2171. """
  2172. Create one media for a specific user, access and returns `media_id`
  2173. Args:
  2174. user_token: Access token of the user
  2175. image_data: binary data of image
  2176. filename: The filename of the media to be uploaded
  2177. Returns:
  2178. The ID of the newly created media.
  2179. """
  2180. upload_resource = self.media_repo.children[b"upload"]
  2181. download_resource = self.media_repo.children[b"download"]
  2182. # Upload some media into the room
  2183. response = self.helper.upload_media(
  2184. upload_resource, image_data, user_token, filename, expect_code=200
  2185. )
  2186. # Extract media ID from the response
  2187. server_and_media_id = response["content_uri"][6:] # Cut off 'mxc://'
  2188. media_id = server_and_media_id.split("/")[1]
  2189. # Try to access a media and to create `last_access_ts`
  2190. channel = make_request(
  2191. self.reactor,
  2192. FakeSite(download_resource),
  2193. "GET",
  2194. server_and_media_id,
  2195. shorthand=False,
  2196. access_token=user_token,
  2197. )
  2198. self.assertEqual(
  2199. 200,
  2200. channel.code,
  2201. msg=(
  2202. "Expected to receive a 200 on accessing media: %s" % server_and_media_id
  2203. ),
  2204. )
  2205. return media_id
  2206. def _check_fields(self, content: JsonDict):
  2207. """Checks that the expected user attributes are present in content
  2208. Args:
  2209. content: List that is checked for content
  2210. """
  2211. for m in content:
  2212. self.assertIn("media_id", m)
  2213. self.assertIn("media_type", m)
  2214. self.assertIn("media_length", m)
  2215. self.assertIn("upload_name", m)
  2216. self.assertIn("created_ts", m)
  2217. self.assertIn("last_access_ts", m)
  2218. self.assertIn("quarantined_by", m)
  2219. self.assertIn("safe_from_quarantine", m)
  2220. def _order_test(
  2221. self,
  2222. expected_media_list: List[str],
  2223. order_by: Optional[str],
  2224. dir: Optional[str] = None,
  2225. ):
  2226. """Request the list of media in a certain order. Assert that order is what
  2227. we expect
  2228. Args:
  2229. expected_media_list: The list of media_ids in the order we expect to get
  2230. back from the server
  2231. order_by: The type of ordering to give the server
  2232. dir: The direction of ordering to give the server
  2233. """
  2234. url = self.url + "?"
  2235. if order_by is not None:
  2236. url += "order_by=%s&" % (order_by,)
  2237. if dir is not None and dir in ("b", "f"):
  2238. url += "dir=%s" % (dir,)
  2239. channel = self.make_request(
  2240. "GET",
  2241. url.encode("ascii"),
  2242. access_token=self.admin_user_tok,
  2243. )
  2244. self.assertEqual(200, channel.code, msg=channel.json_body)
  2245. self.assertEqual(channel.json_body["total"], len(expected_media_list))
  2246. returned_order = [row["media_id"] for row in channel.json_body["media"]]
  2247. self.assertEqual(expected_media_list, returned_order)
  2248. self._check_fields(channel.json_body["media"])
  2249. class UserTokenRestTestCase(unittest.HomeserverTestCase):
  2250. """Test for /_synapse/admin/v1/users/<user>/login"""
  2251. servlets = [
  2252. synapse.rest.admin.register_servlets,
  2253. login.register_servlets,
  2254. sync.register_servlets,
  2255. room.register_servlets,
  2256. devices.register_servlets,
  2257. logout.register_servlets,
  2258. ]
  2259. def prepare(self, reactor, clock, hs):
  2260. self.store = hs.get_datastore()
  2261. self.admin_user = self.register_user("admin", "pass", admin=True)
  2262. self.admin_user_tok = self.login("admin", "pass")
  2263. self.other_user = self.register_user("user", "pass")
  2264. self.other_user_tok = self.login("user", "pass")
  2265. self.url = "/_synapse/admin/v1/users/%s/login" % urllib.parse.quote(
  2266. self.other_user
  2267. )
  2268. def _get_token(self) -> str:
  2269. channel = self.make_request(
  2270. "POST", self.url, b"{}", access_token=self.admin_user_tok
  2271. )
  2272. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2273. return channel.json_body["access_token"]
  2274. def test_no_auth(self):
  2275. """Try to login as a user without authentication."""
  2276. channel = self.make_request("POST", self.url, b"{}")
  2277. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2278. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2279. def test_not_admin(self):
  2280. """Try to login as a user as a non-admin user."""
  2281. channel = self.make_request(
  2282. "POST", self.url, b"{}", access_token=self.other_user_tok
  2283. )
  2284. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2285. def test_send_event(self):
  2286. """Test that sending event as a user works."""
  2287. # Create a room.
  2288. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  2289. # Login in as the user
  2290. puppet_token = self._get_token()
  2291. # Test that sending works, and generates the event as the right user.
  2292. resp = self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  2293. event_id = resp["event_id"]
  2294. event = self.get_success(self.store.get_event(event_id))
  2295. self.assertEqual(event.sender, self.other_user)
  2296. def test_devices(self):
  2297. """Tests that logging in as a user doesn't create a new device for them."""
  2298. # Login in as the user
  2299. self._get_token()
  2300. # Check that we don't see a new device in our devices list
  2301. channel = self.make_request(
  2302. "GET", "devices", b"{}", access_token=self.other_user_tok
  2303. )
  2304. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2305. # We should only see the one device (from the login in `prepare`)
  2306. self.assertEqual(len(channel.json_body["devices"]), 1)
  2307. def test_logout(self):
  2308. """Test that calling `/logout` with the token works."""
  2309. # Login in as the user
  2310. puppet_token = self._get_token()
  2311. # Test that we can successfully make a request
  2312. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2313. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2314. # Logout with the puppet token
  2315. channel = self.make_request("POST", "logout", b"{}", access_token=puppet_token)
  2316. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2317. # The puppet token should no longer work
  2318. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2319. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2320. # .. but the real user's tokens should still work
  2321. channel = self.make_request(
  2322. "GET", "devices", b"{}", access_token=self.other_user_tok
  2323. )
  2324. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2325. def test_user_logout_all(self):
  2326. """Tests that the target user calling `/logout/all` does *not* expire
  2327. the token.
  2328. """
  2329. # Login in as the user
  2330. puppet_token = self._get_token()
  2331. # Test that we can successfully make a request
  2332. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2333. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2334. # Logout all with the real user token
  2335. channel = self.make_request(
  2336. "POST", "logout/all", b"{}", access_token=self.other_user_tok
  2337. )
  2338. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2339. # The puppet token should still work
  2340. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2341. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2342. # .. but the real user's tokens shouldn't
  2343. channel = self.make_request(
  2344. "GET", "devices", b"{}", access_token=self.other_user_tok
  2345. )
  2346. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2347. def test_admin_logout_all(self):
  2348. """Tests that the admin user calling `/logout/all` does expire the
  2349. token.
  2350. """
  2351. # Login in as the user
  2352. puppet_token = self._get_token()
  2353. # Test that we can successfully make a request
  2354. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2355. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2356. # Logout all with the admin user token
  2357. channel = self.make_request(
  2358. "POST", "logout/all", b"{}", access_token=self.admin_user_tok
  2359. )
  2360. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2361. # The puppet token should no longer work
  2362. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  2363. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2364. # .. but the real user's tokens should still work
  2365. channel = self.make_request(
  2366. "GET", "devices", b"{}", access_token=self.other_user_tok
  2367. )
  2368. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2369. @unittest.override_config(
  2370. {
  2371. "public_baseurl": "https://example.org/",
  2372. "user_consent": {
  2373. "version": "1.0",
  2374. "policy_name": "My Cool Privacy Policy",
  2375. "template_dir": "/",
  2376. "require_at_registration": True,
  2377. "block_events_error": "You should accept the policy",
  2378. },
  2379. "form_secret": "123secret",
  2380. }
  2381. )
  2382. def test_consent(self):
  2383. """Test that sending a message is not subject to the privacy policies."""
  2384. # Have the admin user accept the terms.
  2385. self.get_success(self.store.user_set_consent_version(self.admin_user, "1.0"))
  2386. # First, cheekily accept the terms and create a room
  2387. self.get_success(self.store.user_set_consent_version(self.other_user, "1.0"))
  2388. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  2389. self.helper.send_event(room_id, "com.example.test", tok=self.other_user_tok)
  2390. # Now unaccept it and check that we can't send an event
  2391. self.get_success(self.store.user_set_consent_version(self.other_user, "0.0"))
  2392. self.helper.send_event(
  2393. room_id, "com.example.test", tok=self.other_user_tok, expect_code=403
  2394. )
  2395. # Login in as the user
  2396. puppet_token = self._get_token()
  2397. # Sending an event on their behalf should work fine
  2398. self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  2399. @override_config(
  2400. {"limit_usage_by_mau": True, "max_mau_value": 1, "mau_trial_days": 0}
  2401. )
  2402. def test_mau_limit(self):
  2403. # Create a room as the admin user. This will bump the monthly active users to 1.
  2404. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  2405. # Trying to join as the other user should fail due to reaching MAU limit.
  2406. self.helper.join(
  2407. room_id, user=self.other_user, tok=self.other_user_tok, expect_code=403
  2408. )
  2409. # Logging in as the other user and joining a room should work, even
  2410. # though the MAU limit would stop the user doing so.
  2411. puppet_token = self._get_token()
  2412. self.helper.join(room_id, user=self.other_user, tok=puppet_token)
  2413. class WhoisRestTestCase(unittest.HomeserverTestCase):
  2414. servlets = [
  2415. synapse.rest.admin.register_servlets,
  2416. login.register_servlets,
  2417. ]
  2418. def prepare(self, reactor, clock, hs):
  2419. self.admin_user = self.register_user("admin", "pass", admin=True)
  2420. self.admin_user_tok = self.login("admin", "pass")
  2421. self.other_user = self.register_user("user", "pass")
  2422. self.url1 = "/_synapse/admin/v1/whois/%s" % urllib.parse.quote(self.other_user)
  2423. self.url2 = "/_matrix/client/r0/admin/whois/%s" % urllib.parse.quote(
  2424. self.other_user
  2425. )
  2426. def test_no_auth(self):
  2427. """
  2428. Try to get information of an user without authentication.
  2429. """
  2430. channel = self.make_request("GET", self.url1, b"{}")
  2431. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2432. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2433. channel = self.make_request("GET", self.url2, b"{}")
  2434. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2435. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2436. def test_requester_is_not_admin(self):
  2437. """
  2438. If the user is not a server admin, an error is returned.
  2439. """
  2440. self.register_user("user2", "pass")
  2441. other_user2_token = self.login("user2", "pass")
  2442. channel = self.make_request(
  2443. "GET",
  2444. self.url1,
  2445. access_token=other_user2_token,
  2446. )
  2447. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2448. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2449. channel = self.make_request(
  2450. "GET",
  2451. self.url2,
  2452. access_token=other_user2_token,
  2453. )
  2454. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2455. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2456. def test_user_is_not_local(self):
  2457. """
  2458. Tests that a lookup for a user that is not a local returns a 400
  2459. """
  2460. url1 = "/_synapse/admin/v1/whois/@unknown_person:unknown_domain"
  2461. url2 = "/_matrix/client/r0/admin/whois/@unknown_person:unknown_domain"
  2462. channel = self.make_request(
  2463. "GET",
  2464. url1,
  2465. access_token=self.admin_user_tok,
  2466. )
  2467. self.assertEqual(400, channel.code, msg=channel.json_body)
  2468. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  2469. channel = self.make_request(
  2470. "GET",
  2471. url2,
  2472. access_token=self.admin_user_tok,
  2473. )
  2474. self.assertEqual(400, channel.code, msg=channel.json_body)
  2475. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  2476. def test_get_whois_admin(self):
  2477. """
  2478. The lookup should succeed for an admin.
  2479. """
  2480. channel = self.make_request(
  2481. "GET",
  2482. self.url1,
  2483. access_token=self.admin_user_tok,
  2484. )
  2485. self.assertEqual(200, channel.code, msg=channel.json_body)
  2486. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2487. self.assertIn("devices", channel.json_body)
  2488. channel = self.make_request(
  2489. "GET",
  2490. self.url2,
  2491. access_token=self.admin_user_tok,
  2492. )
  2493. self.assertEqual(200, channel.code, msg=channel.json_body)
  2494. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2495. self.assertIn("devices", channel.json_body)
  2496. def test_get_whois_user(self):
  2497. """
  2498. The lookup should succeed for a normal user looking up their own information.
  2499. """
  2500. other_user_token = self.login("user", "pass")
  2501. channel = self.make_request(
  2502. "GET",
  2503. self.url1,
  2504. access_token=other_user_token,
  2505. )
  2506. self.assertEqual(200, channel.code, msg=channel.json_body)
  2507. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2508. self.assertIn("devices", channel.json_body)
  2509. channel = self.make_request(
  2510. "GET",
  2511. self.url2,
  2512. access_token=other_user_token,
  2513. )
  2514. self.assertEqual(200, channel.code, msg=channel.json_body)
  2515. self.assertEqual(self.other_user, channel.json_body["user_id"])
  2516. self.assertIn("devices", channel.json_body)
  2517. class ShadowBanRestTestCase(unittest.HomeserverTestCase):
  2518. servlets = [
  2519. synapse.rest.admin.register_servlets,
  2520. login.register_servlets,
  2521. ]
  2522. def prepare(self, reactor, clock, hs):
  2523. self.store = hs.get_datastore()
  2524. self.admin_user = self.register_user("admin", "pass", admin=True)
  2525. self.admin_user_tok = self.login("admin", "pass")
  2526. self.other_user = self.register_user("user", "pass")
  2527. self.url = "/_synapse/admin/v1/users/%s/shadow_ban" % urllib.parse.quote(
  2528. self.other_user
  2529. )
  2530. def test_no_auth(self):
  2531. """
  2532. Try to get information of an user without authentication.
  2533. """
  2534. channel = self.make_request("POST", self.url)
  2535. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2536. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2537. def test_requester_is_not_admin(self):
  2538. """
  2539. If the user is not a server admin, an error is returned.
  2540. """
  2541. other_user_token = self.login("user", "pass")
  2542. channel = self.make_request("POST", self.url, access_token=other_user_token)
  2543. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2544. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2545. def test_user_is_not_local(self):
  2546. """
  2547. Tests that shadow-banning for a user that is not a local returns a 400
  2548. """
  2549. url = "/_synapse/admin/v1/whois/@unknown_person:unknown_domain"
  2550. channel = self.make_request("POST", url, access_token=self.admin_user_tok)
  2551. self.assertEqual(400, channel.code, msg=channel.json_body)
  2552. def test_success(self):
  2553. """
  2554. Shadow-banning should succeed for an admin.
  2555. """
  2556. # The user starts off as not shadow-banned.
  2557. other_user_token = self.login("user", "pass")
  2558. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  2559. self.assertFalse(result.shadow_banned)
  2560. channel = self.make_request("POST", self.url, access_token=self.admin_user_tok)
  2561. self.assertEqual(200, channel.code, msg=channel.json_body)
  2562. self.assertEqual({}, channel.json_body)
  2563. # Ensure the user is shadow-banned (and the cache was cleared).
  2564. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  2565. self.assertTrue(result.shadow_banned)
  2566. class RateLimitTestCase(unittest.HomeserverTestCase):
  2567. servlets = [
  2568. synapse.rest.admin.register_servlets,
  2569. login.register_servlets,
  2570. ]
  2571. def prepare(self, reactor, clock, hs):
  2572. self.store = hs.get_datastore()
  2573. self.admin_user = self.register_user("admin", "pass", admin=True)
  2574. self.admin_user_tok = self.login("admin", "pass")
  2575. self.other_user = self.register_user("user", "pass")
  2576. self.url = (
  2577. "/_synapse/admin/v1/users/%s/override_ratelimit"
  2578. % urllib.parse.quote(self.other_user)
  2579. )
  2580. def test_no_auth(self):
  2581. """
  2582. Try to get information of a user without authentication.
  2583. """
  2584. channel = self.make_request("GET", self.url, b"{}")
  2585. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2586. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2587. channel = self.make_request("POST", self.url, b"{}")
  2588. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2589. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2590. channel = self.make_request("DELETE", self.url, b"{}")
  2591. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  2592. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  2593. def test_requester_is_no_admin(self):
  2594. """
  2595. If the user is not a server admin, an error is returned.
  2596. """
  2597. other_user_token = self.login("user", "pass")
  2598. channel = self.make_request(
  2599. "GET",
  2600. self.url,
  2601. access_token=other_user_token,
  2602. )
  2603. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2604. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2605. channel = self.make_request(
  2606. "POST",
  2607. self.url,
  2608. access_token=other_user_token,
  2609. )
  2610. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2611. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2612. channel = self.make_request(
  2613. "DELETE",
  2614. self.url,
  2615. access_token=other_user_token,
  2616. )
  2617. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  2618. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  2619. def test_user_does_not_exist(self):
  2620. """
  2621. Tests that a lookup for a user that does not exist returns a 404
  2622. """
  2623. url = "/_synapse/admin/v1/users/@unknown_person:test/override_ratelimit"
  2624. channel = self.make_request(
  2625. "GET",
  2626. url,
  2627. access_token=self.admin_user_tok,
  2628. )
  2629. self.assertEqual(404, channel.code, msg=channel.json_body)
  2630. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2631. channel = self.make_request(
  2632. "POST",
  2633. url,
  2634. access_token=self.admin_user_tok,
  2635. )
  2636. self.assertEqual(404, channel.code, msg=channel.json_body)
  2637. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2638. channel = self.make_request(
  2639. "DELETE",
  2640. url,
  2641. access_token=self.admin_user_tok,
  2642. )
  2643. self.assertEqual(404, channel.code, msg=channel.json_body)
  2644. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  2645. def test_user_is_not_local(self):
  2646. """
  2647. Tests that a lookup for a user that is not a local returns a 400
  2648. """
  2649. url = (
  2650. "/_synapse/admin/v1/users/@unknown_person:unknown_domain/override_ratelimit"
  2651. )
  2652. channel = self.make_request(
  2653. "GET",
  2654. url,
  2655. access_token=self.admin_user_tok,
  2656. )
  2657. self.assertEqual(400, channel.code, msg=channel.json_body)
  2658. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  2659. channel = self.make_request(
  2660. "POST",
  2661. url,
  2662. access_token=self.admin_user_tok,
  2663. )
  2664. self.assertEqual(400, channel.code, msg=channel.json_body)
  2665. self.assertEqual(
  2666. "Only local users can be ratelimited", channel.json_body["error"]
  2667. )
  2668. channel = self.make_request(
  2669. "DELETE",
  2670. url,
  2671. access_token=self.admin_user_tok,
  2672. )
  2673. self.assertEqual(400, channel.code, msg=channel.json_body)
  2674. self.assertEqual(
  2675. "Only local users can be ratelimited", channel.json_body["error"]
  2676. )
  2677. def test_invalid_parameter(self):
  2678. """
  2679. If parameters are invalid, an error is returned.
  2680. """
  2681. # messages_per_second is a string
  2682. channel = self.make_request(
  2683. "POST",
  2684. self.url,
  2685. access_token=self.admin_user_tok,
  2686. content={"messages_per_second": "string"},
  2687. )
  2688. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  2689. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2690. # messages_per_second is negative
  2691. channel = self.make_request(
  2692. "POST",
  2693. self.url,
  2694. access_token=self.admin_user_tok,
  2695. content={"messages_per_second": -1},
  2696. )
  2697. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  2698. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2699. # burst_count is a string
  2700. channel = self.make_request(
  2701. "POST",
  2702. self.url,
  2703. access_token=self.admin_user_tok,
  2704. content={"burst_count": "string"},
  2705. )
  2706. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  2707. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2708. # burst_count is negative
  2709. channel = self.make_request(
  2710. "POST",
  2711. self.url,
  2712. access_token=self.admin_user_tok,
  2713. content={"burst_count": -1},
  2714. )
  2715. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  2716. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  2717. def test_return_zero_when_null(self):
  2718. """
  2719. If values in database are `null` API should return an int `0`
  2720. """
  2721. self.get_success(
  2722. self.store.db_pool.simple_upsert(
  2723. table="ratelimit_override",
  2724. keyvalues={"user_id": self.other_user},
  2725. values={
  2726. "messages_per_second": None,
  2727. "burst_count": None,
  2728. },
  2729. )
  2730. )
  2731. # request status
  2732. channel = self.make_request(
  2733. "GET",
  2734. self.url,
  2735. access_token=self.admin_user_tok,
  2736. )
  2737. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2738. self.assertEqual(0, channel.json_body["messages_per_second"])
  2739. self.assertEqual(0, channel.json_body["burst_count"])
  2740. def test_success(self):
  2741. """
  2742. Rate-limiting (set/update/delete) should succeed for an admin.
  2743. """
  2744. # request status
  2745. channel = self.make_request(
  2746. "GET",
  2747. self.url,
  2748. access_token=self.admin_user_tok,
  2749. )
  2750. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2751. self.assertNotIn("messages_per_second", channel.json_body)
  2752. self.assertNotIn("burst_count", channel.json_body)
  2753. # set ratelimit
  2754. channel = self.make_request(
  2755. "POST",
  2756. self.url,
  2757. access_token=self.admin_user_tok,
  2758. content={"messages_per_second": 10, "burst_count": 11},
  2759. )
  2760. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2761. self.assertEqual(10, channel.json_body["messages_per_second"])
  2762. self.assertEqual(11, channel.json_body["burst_count"])
  2763. # update ratelimit
  2764. channel = self.make_request(
  2765. "POST",
  2766. self.url,
  2767. access_token=self.admin_user_tok,
  2768. content={"messages_per_second": 20, "burst_count": 21},
  2769. )
  2770. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2771. self.assertEqual(20, channel.json_body["messages_per_second"])
  2772. self.assertEqual(21, channel.json_body["burst_count"])
  2773. # request status
  2774. channel = self.make_request(
  2775. "GET",
  2776. self.url,
  2777. access_token=self.admin_user_tok,
  2778. )
  2779. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2780. self.assertEqual(20, channel.json_body["messages_per_second"])
  2781. self.assertEqual(21, channel.json_body["burst_count"])
  2782. # delete ratelimit
  2783. channel = self.make_request(
  2784. "DELETE",
  2785. self.url,
  2786. access_token=self.admin_user_tok,
  2787. )
  2788. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2789. self.assertNotIn("messages_per_second", channel.json_body)
  2790. self.assertNotIn("burst_count", channel.json_body)
  2791. # request status
  2792. channel = self.make_request(
  2793. "GET",
  2794. self.url,
  2795. access_token=self.admin_user_tok,
  2796. )
  2797. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  2798. self.assertNotIn("messages_per_second", channel.json_body)
  2799. self.assertNotIn("burst_count", channel.json_body)