test_user.py 147 KB

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