test_user.py 144 KB

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