1
0

test_user.py 137 KB

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