test_user.py 145 KB

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