test_user.py 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import hashlib
  16. import hmac
  17. import json
  18. import urllib.parse
  19. from binascii import unhexlify
  20. from typing import Optional
  21. from mock import Mock
  22. import synapse.rest.admin
  23. from synapse.api.constants import UserTypes
  24. from synapse.api.errors import Codes, HttpResponseException, ResourceLimitError
  25. from synapse.api.room_versions import RoomVersions
  26. from synapse.rest.client.v1 import login, logout, profile, room
  27. from synapse.rest.client.v2_alpha import devices, sync
  28. from synapse.types import JsonDict
  29. from tests import unittest
  30. from tests.test_utils import make_awaitable
  31. from tests.unittest import override_config
  32. class UserRegisterTestCase(unittest.HomeserverTestCase):
  33. servlets = [
  34. synapse.rest.admin.register_servlets_for_client_rest_resource,
  35. profile.register_servlets,
  36. ]
  37. def make_homeserver(self, reactor, clock):
  38. self.url = "/_synapse/admin/v1/register"
  39. self.registration_handler = Mock()
  40. self.identity_handler = Mock()
  41. self.login_handler = Mock()
  42. self.device_handler = Mock()
  43. self.device_handler.check_device_registered = Mock(return_value="FAKE")
  44. self.datastore = Mock(return_value=Mock())
  45. self.datastore.get_current_state_deltas = Mock(return_value=(0, []))
  46. self.secrets = Mock()
  47. self.hs = self.setup_test_homeserver()
  48. self.hs.config.registration_shared_secret = "shared"
  49. self.hs.get_media_repository = Mock()
  50. self.hs.get_deactivate_account_handler = Mock()
  51. return self.hs
  52. def test_disabled(self):
  53. """
  54. If there is no shared secret, registration through this method will be
  55. prevented.
  56. """
  57. self.hs.config.registration_shared_secret = None
  58. channel = self.make_request("POST", self.url, b"{}")
  59. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  60. self.assertEqual(
  61. "Shared secret registration is not enabled", channel.json_body["error"]
  62. )
  63. def test_get_nonce(self):
  64. """
  65. Calling GET on the endpoint will return a randomised nonce, using the
  66. homeserver's secrets provider.
  67. """
  68. secrets = Mock()
  69. secrets.token_hex = Mock(return_value="abcd")
  70. self.hs.get_secrets = Mock(return_value=secrets)
  71. channel = self.make_request("GET", self.url)
  72. self.assertEqual(channel.json_body, {"nonce": "abcd"})
  73. def test_expired_nonce(self):
  74. """
  75. Calling GET on the endpoint will return a randomised nonce, which will
  76. only last for SALT_TIMEOUT (60s).
  77. """
  78. channel = self.make_request("GET", self.url)
  79. nonce = channel.json_body["nonce"]
  80. # 59 seconds
  81. self.reactor.advance(59)
  82. body = json.dumps({"nonce": nonce})
  83. channel = self.make_request("POST", self.url, body.encode("utf8"))
  84. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  85. self.assertEqual("username must be specified", channel.json_body["error"])
  86. # 61 seconds
  87. self.reactor.advance(2)
  88. channel = self.make_request("POST", self.url, body.encode("utf8"))
  89. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  90. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  91. def test_register_incorrect_nonce(self):
  92. """
  93. Only the provided nonce can be used, as it's checked in the MAC.
  94. """
  95. channel = self.make_request("GET", self.url)
  96. nonce = channel.json_body["nonce"]
  97. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  98. want_mac.update(b"notthenonce\x00bob\x00abc123\x00admin")
  99. want_mac = want_mac.hexdigest()
  100. body = json.dumps(
  101. {
  102. "nonce": nonce,
  103. "username": "bob",
  104. "password": "abc123",
  105. "admin": True,
  106. "mac": want_mac,
  107. }
  108. )
  109. channel = self.make_request("POST", self.url, body.encode("utf8"))
  110. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  111. self.assertEqual("HMAC incorrect", channel.json_body["error"])
  112. def test_register_correct_nonce(self):
  113. """
  114. When the correct nonce is provided, and the right key is provided, the
  115. user is registered.
  116. """
  117. channel = self.make_request("GET", self.url)
  118. nonce = channel.json_body["nonce"]
  119. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  120. want_mac.update(
  121. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  122. )
  123. want_mac = want_mac.hexdigest()
  124. body = json.dumps(
  125. {
  126. "nonce": nonce,
  127. "username": "bob",
  128. "password": "abc123",
  129. "admin": True,
  130. "user_type": UserTypes.SUPPORT,
  131. "mac": want_mac,
  132. }
  133. )
  134. channel = self.make_request("POST", self.url, body.encode("utf8"))
  135. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  136. self.assertEqual("@bob:test", channel.json_body["user_id"])
  137. def test_nonce_reuse(self):
  138. """
  139. A valid unrecognised nonce.
  140. """
  141. channel = self.make_request("GET", self.url)
  142. nonce = channel.json_body["nonce"]
  143. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  144. want_mac.update(nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin")
  145. want_mac = want_mac.hexdigest()
  146. body = json.dumps(
  147. {
  148. "nonce": nonce,
  149. "username": "bob",
  150. "password": "abc123",
  151. "admin": True,
  152. "mac": want_mac,
  153. }
  154. )
  155. channel = self.make_request("POST", self.url, body.encode("utf8"))
  156. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  157. self.assertEqual("@bob:test", channel.json_body["user_id"])
  158. # Now, try and reuse it
  159. channel = self.make_request("POST", self.url, body.encode("utf8"))
  160. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  161. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  162. def test_missing_parts(self):
  163. """
  164. Synapse will complain if you don't give nonce, username, password, and
  165. mac. Admin and user_types are optional. Additional checks are done for length
  166. and type.
  167. """
  168. def nonce():
  169. channel = self.make_request("GET", self.url)
  170. return channel.json_body["nonce"]
  171. #
  172. # Nonce check
  173. #
  174. # Must be present
  175. body = json.dumps({})
  176. channel = self.make_request("POST", self.url, body.encode("utf8"))
  177. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  178. self.assertEqual("nonce must be specified", channel.json_body["error"])
  179. #
  180. # Username checks
  181. #
  182. # Must be present
  183. body = json.dumps({"nonce": nonce()})
  184. channel = self.make_request("POST", self.url, body.encode("utf8"))
  185. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  186. self.assertEqual("username must be specified", channel.json_body["error"])
  187. # Must be a string
  188. body = json.dumps({"nonce": nonce(), "username": 1234})
  189. channel = self.make_request("POST", self.url, body.encode("utf8"))
  190. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  191. self.assertEqual("Invalid username", channel.json_body["error"])
  192. # Must not have null bytes
  193. body = json.dumps({"nonce": nonce(), "username": "abcd\u0000"})
  194. channel = self.make_request("POST", self.url, body.encode("utf8"))
  195. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  196. self.assertEqual("Invalid username", channel.json_body["error"])
  197. # Must not have null bytes
  198. body = json.dumps({"nonce": nonce(), "username": "a" * 1000})
  199. channel = self.make_request("POST", self.url, body.encode("utf8"))
  200. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  201. self.assertEqual("Invalid username", channel.json_body["error"])
  202. #
  203. # Password checks
  204. #
  205. # Must be present
  206. body = json.dumps({"nonce": nonce(), "username": "a"})
  207. channel = self.make_request("POST", self.url, body.encode("utf8"))
  208. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  209. self.assertEqual("password must be specified", channel.json_body["error"])
  210. # Must be a string
  211. body = json.dumps({"nonce": nonce(), "username": "a", "password": 1234})
  212. channel = self.make_request("POST", self.url, body.encode("utf8"))
  213. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  214. self.assertEqual("Invalid password", channel.json_body["error"])
  215. # Must not have null bytes
  216. body = json.dumps({"nonce": nonce(), "username": "a", "password": "abcd\u0000"})
  217. channel = self.make_request("POST", self.url, body.encode("utf8"))
  218. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  219. self.assertEqual("Invalid password", channel.json_body["error"])
  220. # Super long
  221. body = json.dumps({"nonce": nonce(), "username": "a", "password": "A" * 1000})
  222. channel = self.make_request("POST", self.url, body.encode("utf8"))
  223. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  224. self.assertEqual("Invalid password", channel.json_body["error"])
  225. #
  226. # user_type check
  227. #
  228. # Invalid user_type
  229. body = json.dumps(
  230. {
  231. "nonce": nonce(),
  232. "username": "a",
  233. "password": "1234",
  234. "user_type": "invalid",
  235. }
  236. )
  237. channel = self.make_request("POST", self.url, body.encode("utf8"))
  238. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  239. self.assertEqual("Invalid user type", channel.json_body["error"])
  240. def test_displayname(self):
  241. """
  242. Test that displayname of new user is set
  243. """
  244. # set no displayname
  245. channel = self.make_request("GET", self.url)
  246. nonce = channel.json_body["nonce"]
  247. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  248. want_mac.update(nonce.encode("ascii") + b"\x00bob1\x00abc123\x00notadmin")
  249. want_mac = want_mac.hexdigest()
  250. body = json.dumps(
  251. {"nonce": nonce, "username": "bob1", "password": "abc123", "mac": want_mac}
  252. )
  253. channel = self.make_request("POST", self.url, body.encode("utf8"))
  254. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  255. self.assertEqual("@bob1:test", channel.json_body["user_id"])
  256. channel = self.make_request("GET", "/profile/@bob1:test/displayname")
  257. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  258. self.assertEqual("bob1", channel.json_body["displayname"])
  259. # displayname is None
  260. channel = self.make_request("GET", self.url)
  261. nonce = channel.json_body["nonce"]
  262. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  263. want_mac.update(nonce.encode("ascii") + b"\x00bob2\x00abc123\x00notadmin")
  264. want_mac = want_mac.hexdigest()
  265. body = json.dumps(
  266. {
  267. "nonce": nonce,
  268. "username": "bob2",
  269. "displayname": None,
  270. "password": "abc123",
  271. "mac": want_mac,
  272. }
  273. )
  274. channel = self.make_request("POST", self.url, body.encode("utf8"))
  275. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  276. self.assertEqual("@bob2:test", channel.json_body["user_id"])
  277. channel = self.make_request("GET", "/profile/@bob2:test/displayname")
  278. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  279. self.assertEqual("bob2", channel.json_body["displayname"])
  280. # displayname is empty
  281. channel = self.make_request("GET", self.url)
  282. nonce = channel.json_body["nonce"]
  283. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  284. want_mac.update(nonce.encode("ascii") + b"\x00bob3\x00abc123\x00notadmin")
  285. want_mac = want_mac.hexdigest()
  286. body = json.dumps(
  287. {
  288. "nonce": nonce,
  289. "username": "bob3",
  290. "displayname": "",
  291. "password": "abc123",
  292. "mac": want_mac,
  293. }
  294. )
  295. channel = self.make_request("POST", self.url, body.encode("utf8"))
  296. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  297. self.assertEqual("@bob3:test", channel.json_body["user_id"])
  298. channel = self.make_request("GET", "/profile/@bob3:test/displayname")
  299. self.assertEqual(404, int(channel.result["code"]), msg=channel.result["body"])
  300. # set displayname
  301. channel = self.make_request("GET", self.url)
  302. nonce = channel.json_body["nonce"]
  303. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  304. want_mac.update(nonce.encode("ascii") + b"\x00bob4\x00abc123\x00notadmin")
  305. want_mac = want_mac.hexdigest()
  306. body = json.dumps(
  307. {
  308. "nonce": nonce,
  309. "username": "bob4",
  310. "displayname": "Bob's Name",
  311. "password": "abc123",
  312. "mac": want_mac,
  313. }
  314. )
  315. channel = self.make_request("POST", self.url, body.encode("utf8"))
  316. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  317. self.assertEqual("@bob4:test", channel.json_body["user_id"])
  318. channel = self.make_request("GET", "/profile/@bob4:test/displayname")
  319. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  320. self.assertEqual("Bob's Name", channel.json_body["displayname"])
  321. @override_config(
  322. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  323. )
  324. def test_register_mau_limit_reached(self):
  325. """
  326. Check we can register a user via the shared secret registration API
  327. even if the MAU limit is reached.
  328. """
  329. handler = self.hs.get_registration_handler()
  330. store = self.hs.get_datastore()
  331. # Set monthly active users to the limit
  332. store.get_monthly_active_count = Mock(
  333. return_value=make_awaitable(self.hs.config.max_mau_value)
  334. )
  335. # Check that the blocking of monthly active users is working as expected
  336. # The registration of a new user fails due to the limit
  337. self.get_failure(
  338. handler.register_user(localpart="local_part"), ResourceLimitError
  339. )
  340. # Register new user with admin API
  341. channel = self.make_request("GET", self.url)
  342. nonce = channel.json_body["nonce"]
  343. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  344. want_mac.update(
  345. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  346. )
  347. want_mac = want_mac.hexdigest()
  348. body = json.dumps(
  349. {
  350. "nonce": nonce,
  351. "username": "bob",
  352. "password": "abc123",
  353. "admin": True,
  354. "user_type": UserTypes.SUPPORT,
  355. "mac": want_mac,
  356. }
  357. )
  358. channel = self.make_request("POST", self.url, body.encode("utf8"))
  359. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  360. self.assertEqual("@bob:test", channel.json_body["user_id"])
  361. class UsersListTestCase(unittest.HomeserverTestCase):
  362. servlets = [
  363. synapse.rest.admin.register_servlets,
  364. login.register_servlets,
  365. ]
  366. url = "/_synapse/admin/v2/users"
  367. def prepare(self, reactor, clock, hs):
  368. self.admin_user = self.register_user("admin", "pass", admin=True)
  369. self.admin_user_tok = self.login("admin", "pass")
  370. def test_no_auth(self):
  371. """
  372. Try to list users without authentication.
  373. """
  374. channel = self.make_request("GET", self.url, b"{}")
  375. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  376. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  377. def test_requester_is_no_admin(self):
  378. """
  379. If the user is not a server admin, an error is returned.
  380. """
  381. self._create_users(1)
  382. other_user_token = self.login("user1", "pass1")
  383. channel = self.make_request("GET", self.url, access_token=other_user_token)
  384. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  385. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  386. def test_all_users(self):
  387. """
  388. List all users, including deactivated users.
  389. """
  390. self._create_users(2)
  391. channel = self.make_request(
  392. "GET",
  393. self.url + "?deactivated=true",
  394. b"{}",
  395. access_token=self.admin_user_tok,
  396. )
  397. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  398. self.assertEqual(3, len(channel.json_body["users"]))
  399. self.assertEqual(3, channel.json_body["total"])
  400. # Check that all fields are available
  401. self._check_fields(channel.json_body["users"])
  402. def test_search_term(self):
  403. """Test that searching for a users works correctly"""
  404. def _search_test(
  405. expected_user_id: Optional[str],
  406. search_term: str,
  407. search_field: Optional[str] = "name",
  408. expected_http_code: Optional[int] = 200,
  409. ):
  410. """Search for a user and check that the returned user's id is a match
  411. Args:
  412. expected_user_id: The user_id expected to be returned by the API. Set
  413. to None to expect zero results for the search
  414. search_term: The term to search for user names with
  415. search_field: Field which is to request: `name` or `user_id`
  416. expected_http_code: The expected http code for the request
  417. """
  418. url = self.url + "?%s=%s" % (search_field, search_term,)
  419. channel = self.make_request(
  420. "GET", url.encode("ascii"), access_token=self.admin_user_tok,
  421. )
  422. self.assertEqual(expected_http_code, channel.code, msg=channel.json_body)
  423. if expected_http_code != 200:
  424. return
  425. # Check that users were returned
  426. self.assertTrue("users" in channel.json_body)
  427. self._check_fields(channel.json_body["users"])
  428. users = channel.json_body["users"]
  429. # Check that the expected number of users were returned
  430. expected_user_count = 1 if expected_user_id else 0
  431. self.assertEqual(len(users), expected_user_count)
  432. self.assertEqual(channel.json_body["total"], expected_user_count)
  433. if expected_user_id:
  434. # Check that the first returned user id is correct
  435. u = users[0]
  436. self.assertEqual(expected_user_id, u["name"])
  437. self._create_users(2)
  438. user1 = "@user1:test"
  439. user2 = "@user2:test"
  440. # Perform search tests
  441. _search_test(user1, "er1")
  442. _search_test(user1, "me 1")
  443. _search_test(user2, "er2")
  444. _search_test(user2, "me 2")
  445. _search_test(user1, "er1", "user_id")
  446. _search_test(user2, "er2", "user_id")
  447. # Test case insensitive
  448. _search_test(user1, "ER1")
  449. _search_test(user1, "NAME 1")
  450. _search_test(user2, "ER2")
  451. _search_test(user2, "NAME 2")
  452. _search_test(user1, "ER1", "user_id")
  453. _search_test(user2, "ER2", "user_id")
  454. _search_test(None, "foo")
  455. _search_test(None, "bar")
  456. _search_test(None, "foo", "user_id")
  457. _search_test(None, "bar", "user_id")
  458. def test_invalid_parameter(self):
  459. """
  460. If parameters are invalid, an error is returned.
  461. """
  462. # negative limit
  463. channel = self.make_request(
  464. "GET", self.url + "?limit=-5", access_token=self.admin_user_tok,
  465. )
  466. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  467. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  468. # negative from
  469. channel = self.make_request(
  470. "GET", self.url + "?from=-5", access_token=self.admin_user_tok,
  471. )
  472. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  473. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  474. # invalid guests
  475. channel = self.make_request(
  476. "GET", self.url + "?guests=not_bool", access_token=self.admin_user_tok,
  477. )
  478. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  479. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  480. # invalid deactivated
  481. channel = self.make_request(
  482. "GET", self.url + "?deactivated=not_bool", access_token=self.admin_user_tok,
  483. )
  484. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  485. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  486. def test_limit(self):
  487. """
  488. Testing list of users with limit
  489. """
  490. number_users = 20
  491. # Create one less user (since there's already an admin user).
  492. self._create_users(number_users - 1)
  493. channel = self.make_request(
  494. "GET", self.url + "?limit=5", access_token=self.admin_user_tok,
  495. )
  496. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  497. self.assertEqual(channel.json_body["total"], number_users)
  498. self.assertEqual(len(channel.json_body["users"]), 5)
  499. self.assertEqual(channel.json_body["next_token"], "5")
  500. self._check_fields(channel.json_body["users"])
  501. def test_from(self):
  502. """
  503. Testing list of users with a defined starting point (from)
  504. """
  505. number_users = 20
  506. # Create one less user (since there's already an admin user).
  507. self._create_users(number_users - 1)
  508. channel = self.make_request(
  509. "GET", self.url + "?from=5", access_token=self.admin_user_tok,
  510. )
  511. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  512. self.assertEqual(channel.json_body["total"], number_users)
  513. self.assertEqual(len(channel.json_body["users"]), 15)
  514. self.assertNotIn("next_token", channel.json_body)
  515. self._check_fields(channel.json_body["users"])
  516. def test_limit_and_from(self):
  517. """
  518. Testing list of users with a defined starting point and limit
  519. """
  520. number_users = 20
  521. # Create one less user (since there's already an admin user).
  522. self._create_users(number_users - 1)
  523. channel = self.make_request(
  524. "GET", self.url + "?from=5&limit=10", access_token=self.admin_user_tok,
  525. )
  526. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  527. self.assertEqual(channel.json_body["total"], number_users)
  528. self.assertEqual(channel.json_body["next_token"], "15")
  529. self.assertEqual(len(channel.json_body["users"]), 10)
  530. self._check_fields(channel.json_body["users"])
  531. def test_next_token(self):
  532. """
  533. Testing that `next_token` appears at the right place
  534. """
  535. number_users = 20
  536. # Create one less user (since there's already an admin user).
  537. self._create_users(number_users - 1)
  538. # `next_token` does not appear
  539. # Number of results is the number of entries
  540. channel = self.make_request(
  541. "GET", self.url + "?limit=20", access_token=self.admin_user_tok,
  542. )
  543. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  544. self.assertEqual(channel.json_body["total"], number_users)
  545. self.assertEqual(len(channel.json_body["users"]), number_users)
  546. self.assertNotIn("next_token", channel.json_body)
  547. # `next_token` does not appear
  548. # Number of max results is larger than the number of entries
  549. channel = self.make_request(
  550. "GET", self.url + "?limit=21", access_token=self.admin_user_tok,
  551. )
  552. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  553. self.assertEqual(channel.json_body["total"], number_users)
  554. self.assertEqual(len(channel.json_body["users"]), number_users)
  555. self.assertNotIn("next_token", channel.json_body)
  556. # `next_token` does appear
  557. # Number of max results is smaller than the number of entries
  558. channel = self.make_request(
  559. "GET", self.url + "?limit=19", access_token=self.admin_user_tok,
  560. )
  561. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  562. self.assertEqual(channel.json_body["total"], number_users)
  563. self.assertEqual(len(channel.json_body["users"]), 19)
  564. self.assertEqual(channel.json_body["next_token"], "19")
  565. # Check
  566. # Set `from` to value of `next_token` for request remaining entries
  567. # `next_token` does not appear
  568. channel = self.make_request(
  569. "GET", self.url + "?from=19", access_token=self.admin_user_tok,
  570. )
  571. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  572. self.assertEqual(channel.json_body["total"], number_users)
  573. self.assertEqual(len(channel.json_body["users"]), 1)
  574. self.assertNotIn("next_token", channel.json_body)
  575. def _check_fields(self, content: JsonDict):
  576. """Checks that the expected user attributes are present in content
  577. Args:
  578. content: List that is checked for content
  579. """
  580. for u in content:
  581. self.assertIn("name", u)
  582. self.assertIn("is_guest", u)
  583. self.assertIn("admin", u)
  584. self.assertIn("user_type", u)
  585. self.assertIn("deactivated", u)
  586. self.assertIn("displayname", u)
  587. self.assertIn("avatar_url", u)
  588. def _create_users(self, number_users: int):
  589. """
  590. Create a number of users
  591. Args:
  592. number_users: Number of users to be created
  593. """
  594. for i in range(1, number_users + 1):
  595. self.register_user(
  596. "user%d" % i, "pass%d" % i, admin=False, displayname="Name %d" % i,
  597. )
  598. class DeactivateAccountTestCase(unittest.HomeserverTestCase):
  599. servlets = [
  600. synapse.rest.admin.register_servlets,
  601. login.register_servlets,
  602. ]
  603. def prepare(self, reactor, clock, hs):
  604. self.store = hs.get_datastore()
  605. self.admin_user = self.register_user("admin", "pass", admin=True)
  606. self.admin_user_tok = self.login("admin", "pass")
  607. self.other_user = self.register_user("user", "pass", displayname="User1")
  608. self.other_user_token = self.login("user", "pass")
  609. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  610. self.other_user
  611. )
  612. self.url = "/_synapse/admin/v1/deactivate/%s" % urllib.parse.quote(
  613. self.other_user
  614. )
  615. # set attributes for user
  616. self.get_success(
  617. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  618. )
  619. self.get_success(
  620. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  621. )
  622. def test_no_auth(self):
  623. """
  624. Try to deactivate users without authentication.
  625. """
  626. channel = self.make_request("POST", self.url, b"{}")
  627. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  628. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  629. def test_requester_is_not_admin(self):
  630. """
  631. If the user is not a server admin, an error is returned.
  632. """
  633. url = "/_synapse/admin/v1/deactivate/@bob:test"
  634. channel = self.make_request("POST", url, access_token=self.other_user_token)
  635. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  636. self.assertEqual("You are not a server admin", channel.json_body["error"])
  637. channel = self.make_request(
  638. "POST", url, access_token=self.other_user_token, content=b"{}",
  639. )
  640. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  641. self.assertEqual("You are not a server admin", channel.json_body["error"])
  642. def test_user_does_not_exist(self):
  643. """
  644. Tests that deactivation for a user that does not exist returns a 404
  645. """
  646. channel = self.make_request(
  647. "POST",
  648. "/_synapse/admin/v1/deactivate/@unknown_person:test",
  649. access_token=self.admin_user_tok,
  650. )
  651. self.assertEqual(404, channel.code, msg=channel.json_body)
  652. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  653. def test_erase_is_not_bool(self):
  654. """
  655. If parameter `erase` is not boolean, return an error
  656. """
  657. body = json.dumps({"erase": "False"})
  658. channel = self.make_request(
  659. "POST",
  660. self.url,
  661. content=body.encode(encoding="utf_8"),
  662. access_token=self.admin_user_tok,
  663. )
  664. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  665. self.assertEqual(Codes.BAD_JSON, channel.json_body["errcode"])
  666. def test_user_is_not_local(self):
  667. """
  668. Tests that deactivation for a user that is not a local returns a 400
  669. """
  670. url = "/_synapse/admin/v1/deactivate/@unknown_person:unknown_domain"
  671. channel = self.make_request("POST", url, access_token=self.admin_user_tok)
  672. self.assertEqual(400, channel.code, msg=channel.json_body)
  673. self.assertEqual("Can only deactivate local users", channel.json_body["error"])
  674. def test_deactivate_user_erase_true(self):
  675. """
  676. Test deactivating an user and set `erase` to `true`
  677. """
  678. # Get user
  679. channel = self.make_request(
  680. "GET", self.url_other_user, access_token=self.admin_user_tok,
  681. )
  682. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  683. self.assertEqual("@user:test", channel.json_body["name"])
  684. self.assertEqual(False, channel.json_body["deactivated"])
  685. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  686. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  687. self.assertEqual("User1", channel.json_body["displayname"])
  688. # Deactivate user
  689. body = json.dumps({"erase": True})
  690. channel = self.make_request(
  691. "POST",
  692. self.url,
  693. access_token=self.admin_user_tok,
  694. content=body.encode(encoding="utf_8"),
  695. )
  696. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  697. # Get user
  698. channel = self.make_request(
  699. "GET", self.url_other_user, access_token=self.admin_user_tok,
  700. )
  701. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  702. self.assertEqual("@user:test", channel.json_body["name"])
  703. self.assertEqual(True, channel.json_body["deactivated"])
  704. self.assertEqual(0, len(channel.json_body["threepids"]))
  705. self.assertIsNone(channel.json_body["avatar_url"])
  706. self.assertIsNone(channel.json_body["displayname"])
  707. self._is_erased("@user:test", True)
  708. def test_deactivate_user_erase_false(self):
  709. """
  710. Test deactivating an user and set `erase` to `false`
  711. """
  712. # Get user
  713. channel = self.make_request(
  714. "GET", self.url_other_user, access_token=self.admin_user_tok,
  715. )
  716. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  717. self.assertEqual("@user:test", channel.json_body["name"])
  718. self.assertEqual(False, channel.json_body["deactivated"])
  719. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  720. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  721. self.assertEqual("User1", channel.json_body["displayname"])
  722. # Deactivate user
  723. body = json.dumps({"erase": False})
  724. channel = self.make_request(
  725. "POST",
  726. self.url,
  727. access_token=self.admin_user_tok,
  728. content=body.encode(encoding="utf_8"),
  729. )
  730. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  731. # Get user
  732. channel = self.make_request(
  733. "GET", self.url_other_user, access_token=self.admin_user_tok,
  734. )
  735. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  736. self.assertEqual("@user:test", channel.json_body["name"])
  737. self.assertEqual(True, channel.json_body["deactivated"])
  738. self.assertEqual(0, len(channel.json_body["threepids"]))
  739. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  740. self.assertEqual("User1", channel.json_body["displayname"])
  741. self._is_erased("@user:test", False)
  742. def _is_erased(self, user_id: str, expect: bool) -> None:
  743. """Assert that the user is erased or not
  744. """
  745. d = self.store.is_user_erased(user_id)
  746. if expect:
  747. self.assertTrue(self.get_success(d))
  748. else:
  749. self.assertFalse(self.get_success(d))
  750. class UserRestTestCase(unittest.HomeserverTestCase):
  751. servlets = [
  752. synapse.rest.admin.register_servlets,
  753. login.register_servlets,
  754. sync.register_servlets,
  755. ]
  756. def prepare(self, reactor, clock, hs):
  757. self.store = hs.get_datastore()
  758. self.admin_user = self.register_user("admin", "pass", admin=True)
  759. self.admin_user_tok = self.login("admin", "pass")
  760. self.other_user = self.register_user("user", "pass", displayname="User")
  761. self.other_user_token = self.login("user", "pass")
  762. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  763. self.other_user
  764. )
  765. def test_requester_is_no_admin(self):
  766. """
  767. If the user is not a server admin, an error is returned.
  768. """
  769. url = "/_synapse/admin/v2/users/@bob:test"
  770. channel = self.make_request("GET", url, access_token=self.other_user_token,)
  771. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  772. self.assertEqual("You are not a server admin", channel.json_body["error"])
  773. channel = self.make_request(
  774. "PUT", url, access_token=self.other_user_token, content=b"{}",
  775. )
  776. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  777. self.assertEqual("You are not a server admin", channel.json_body["error"])
  778. def test_user_does_not_exist(self):
  779. """
  780. Tests that a lookup for a user that does not exist returns a 404
  781. """
  782. channel = self.make_request(
  783. "GET",
  784. "/_synapse/admin/v2/users/@unknown_person:test",
  785. access_token=self.admin_user_tok,
  786. )
  787. self.assertEqual(404, channel.code, msg=channel.json_body)
  788. self.assertEqual("M_NOT_FOUND", channel.json_body["errcode"])
  789. def test_create_server_admin(self):
  790. """
  791. Check that a new admin user is created successfully.
  792. """
  793. url = "/_synapse/admin/v2/users/@bob:test"
  794. # Create user (server admin)
  795. body = json.dumps(
  796. {
  797. "password": "abc123",
  798. "admin": True,
  799. "displayname": "Bob's name",
  800. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  801. "avatar_url": "mxc://fibble/wibble",
  802. }
  803. )
  804. channel = self.make_request(
  805. "PUT",
  806. url,
  807. access_token=self.admin_user_tok,
  808. content=body.encode(encoding="utf_8"),
  809. )
  810. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  811. self.assertEqual("@bob:test", channel.json_body["name"])
  812. self.assertEqual("Bob's name", channel.json_body["displayname"])
  813. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  814. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  815. self.assertEqual(True, channel.json_body["admin"])
  816. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  817. # Get user
  818. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  819. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  820. self.assertEqual("@bob:test", channel.json_body["name"])
  821. self.assertEqual("Bob's name", channel.json_body["displayname"])
  822. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  823. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  824. self.assertEqual(True, channel.json_body["admin"])
  825. self.assertEqual(False, channel.json_body["is_guest"])
  826. self.assertEqual(False, channel.json_body["deactivated"])
  827. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  828. def test_create_user(self):
  829. """
  830. Check that a new regular user is created successfully.
  831. """
  832. url = "/_synapse/admin/v2/users/@bob:test"
  833. # Create user
  834. body = json.dumps(
  835. {
  836. "password": "abc123",
  837. "admin": False,
  838. "displayname": "Bob's name",
  839. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  840. "avatar_url": "mxc://fibble/wibble",
  841. }
  842. )
  843. channel = self.make_request(
  844. "PUT",
  845. url,
  846. access_token=self.admin_user_tok,
  847. content=body.encode(encoding="utf_8"),
  848. )
  849. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  850. self.assertEqual("@bob:test", channel.json_body["name"])
  851. self.assertEqual("Bob's name", channel.json_body["displayname"])
  852. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  853. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  854. self.assertEqual(False, channel.json_body["admin"])
  855. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  856. # Get user
  857. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  858. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  859. self.assertEqual("@bob:test", channel.json_body["name"])
  860. self.assertEqual("Bob's name", channel.json_body["displayname"])
  861. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  862. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  863. self.assertEqual(False, channel.json_body["admin"])
  864. self.assertEqual(False, channel.json_body["is_guest"])
  865. self.assertEqual(False, channel.json_body["deactivated"])
  866. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  867. @override_config(
  868. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  869. )
  870. def test_create_user_mau_limit_reached_active_admin(self):
  871. """
  872. Check that an admin can register a new user via the admin API
  873. even if the MAU limit is reached.
  874. Admin user was active before creating user.
  875. """
  876. handler = self.hs.get_registration_handler()
  877. # Sync to set admin user to active
  878. # before limit of monthly active users is reached
  879. channel = self.make_request("GET", "/sync", access_token=self.admin_user_tok)
  880. if channel.code != 200:
  881. raise HttpResponseException(
  882. channel.code, channel.result["reason"], channel.result["body"]
  883. )
  884. # Set monthly active users to the limit
  885. self.store.get_monthly_active_count = Mock(
  886. return_value=make_awaitable(self.hs.config.max_mau_value)
  887. )
  888. # Check that the blocking of monthly active users is working as expected
  889. # The registration of a new user fails due to the limit
  890. self.get_failure(
  891. handler.register_user(localpart="local_part"), ResourceLimitError
  892. )
  893. # Register new user with admin API
  894. url = "/_synapse/admin/v2/users/@bob:test"
  895. # Create user
  896. body = json.dumps({"password": "abc123", "admin": False})
  897. channel = self.make_request(
  898. "PUT",
  899. url,
  900. access_token=self.admin_user_tok,
  901. content=body.encode(encoding="utf_8"),
  902. )
  903. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  904. self.assertEqual("@bob:test", channel.json_body["name"])
  905. self.assertEqual(False, channel.json_body["admin"])
  906. @override_config(
  907. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  908. )
  909. def test_create_user_mau_limit_reached_passive_admin(self):
  910. """
  911. Check that an admin can register a new user via the admin API
  912. even if the MAU limit is reached.
  913. Admin user was not active before creating user.
  914. """
  915. handler = self.hs.get_registration_handler()
  916. # Set monthly active users to the limit
  917. self.store.get_monthly_active_count = Mock(
  918. return_value=make_awaitable(self.hs.config.max_mau_value)
  919. )
  920. # Check that the blocking of monthly active users is working as expected
  921. # The registration of a new user fails due to the limit
  922. self.get_failure(
  923. handler.register_user(localpart="local_part"), ResourceLimitError
  924. )
  925. # Register new user with admin API
  926. url = "/_synapse/admin/v2/users/@bob:test"
  927. # Create user
  928. body = json.dumps({"password": "abc123", "admin": False})
  929. channel = self.make_request(
  930. "PUT",
  931. url,
  932. access_token=self.admin_user_tok,
  933. content=body.encode(encoding="utf_8"),
  934. )
  935. # Admin user is not blocked by mau anymore
  936. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  937. self.assertEqual("@bob:test", channel.json_body["name"])
  938. self.assertEqual(False, channel.json_body["admin"])
  939. @override_config(
  940. {
  941. "email": {
  942. "enable_notifs": True,
  943. "notif_for_new_users": True,
  944. "notif_from": "test@example.com",
  945. },
  946. "public_baseurl": "https://example.com",
  947. }
  948. )
  949. def test_create_user_email_notif_for_new_users(self):
  950. """
  951. Check that a new regular user is created successfully and
  952. got an email pusher.
  953. """
  954. url = "/_synapse/admin/v2/users/@bob:test"
  955. # Create user
  956. body = json.dumps(
  957. {
  958. "password": "abc123",
  959. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  960. }
  961. )
  962. channel = self.make_request(
  963. "PUT",
  964. url,
  965. access_token=self.admin_user_tok,
  966. content=body.encode(encoding="utf_8"),
  967. )
  968. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  969. self.assertEqual("@bob:test", channel.json_body["name"])
  970. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  971. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  972. pushers = self.get_success(
  973. self.store.get_pushers_by({"user_name": "@bob:test"})
  974. )
  975. pushers = list(pushers)
  976. self.assertEqual(len(pushers), 1)
  977. self.assertEqual("@bob:test", pushers[0].user_name)
  978. @override_config(
  979. {
  980. "email": {
  981. "enable_notifs": False,
  982. "notif_for_new_users": False,
  983. "notif_from": "test@example.com",
  984. },
  985. "public_baseurl": "https://example.com",
  986. }
  987. )
  988. def test_create_user_email_no_notif_for_new_users(self):
  989. """
  990. Check that a new regular user is created successfully and
  991. got not an email pusher.
  992. """
  993. url = "/_synapse/admin/v2/users/@bob:test"
  994. # Create user
  995. body = json.dumps(
  996. {
  997. "password": "abc123",
  998. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  999. }
  1000. )
  1001. channel = self.make_request(
  1002. "PUT",
  1003. url,
  1004. access_token=self.admin_user_tok,
  1005. content=body.encode(encoding="utf_8"),
  1006. )
  1007. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  1008. self.assertEqual("@bob:test", channel.json_body["name"])
  1009. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1010. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  1011. pushers = self.get_success(
  1012. self.store.get_pushers_by({"user_name": "@bob:test"})
  1013. )
  1014. pushers = list(pushers)
  1015. self.assertEqual(len(pushers), 0)
  1016. def test_set_password(self):
  1017. """
  1018. Test setting a new password for another user.
  1019. """
  1020. # Change password
  1021. body = json.dumps({"password": "hahaha"})
  1022. channel = self.make_request(
  1023. "PUT",
  1024. self.url_other_user,
  1025. access_token=self.admin_user_tok,
  1026. content=body.encode(encoding="utf_8"),
  1027. )
  1028. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1029. def test_set_displayname(self):
  1030. """
  1031. Test setting the displayname of another user.
  1032. """
  1033. # Modify user
  1034. body = json.dumps({"displayname": "foobar"})
  1035. channel = self.make_request(
  1036. "PUT",
  1037. self.url_other_user,
  1038. access_token=self.admin_user_tok,
  1039. content=body.encode(encoding="utf_8"),
  1040. )
  1041. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1042. self.assertEqual("@user:test", channel.json_body["name"])
  1043. self.assertEqual("foobar", channel.json_body["displayname"])
  1044. # Get user
  1045. channel = self.make_request(
  1046. "GET", self.url_other_user, access_token=self.admin_user_tok,
  1047. )
  1048. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1049. self.assertEqual("@user:test", channel.json_body["name"])
  1050. self.assertEqual("foobar", channel.json_body["displayname"])
  1051. def test_set_threepid(self):
  1052. """
  1053. Test setting threepid for an other user.
  1054. """
  1055. # Delete old and add new threepid to user
  1056. body = json.dumps(
  1057. {"threepids": [{"medium": "email", "address": "bob3@bob.bob"}]}
  1058. )
  1059. channel = self.make_request(
  1060. "PUT",
  1061. self.url_other_user,
  1062. access_token=self.admin_user_tok,
  1063. content=body.encode(encoding="utf_8"),
  1064. )
  1065. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1066. self.assertEqual("@user:test", channel.json_body["name"])
  1067. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1068. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  1069. # Get user
  1070. channel = self.make_request(
  1071. "GET", self.url_other_user, access_token=self.admin_user_tok,
  1072. )
  1073. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1074. self.assertEqual("@user:test", channel.json_body["name"])
  1075. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  1076. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  1077. def test_deactivate_user(self):
  1078. """
  1079. Test deactivating another user.
  1080. """
  1081. # set attributes for user
  1082. self.get_success(
  1083. self.store.set_profile_avatar_url("user", "mxc://servername/mediaid")
  1084. )
  1085. self.get_success(
  1086. self.store.user_add_threepid("@user:test", "email", "foo@bar.com", 0, 0)
  1087. )
  1088. # Get user
  1089. channel = self.make_request(
  1090. "GET", self.url_other_user, access_token=self.admin_user_tok,
  1091. )
  1092. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1093. self.assertEqual("@user:test", channel.json_body["name"])
  1094. self.assertEqual(False, channel.json_body["deactivated"])
  1095. self.assertEqual("foo@bar.com", channel.json_body["threepids"][0]["address"])
  1096. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1097. self.assertEqual("User", channel.json_body["displayname"])
  1098. # Deactivate user
  1099. body = json.dumps({"deactivated": True})
  1100. channel = self.make_request(
  1101. "PUT",
  1102. self.url_other_user,
  1103. access_token=self.admin_user_tok,
  1104. content=body.encode(encoding="utf_8"),
  1105. )
  1106. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1107. self.assertEqual("@user:test", channel.json_body["name"])
  1108. self.assertEqual(True, channel.json_body["deactivated"])
  1109. self.assertEqual(0, len(channel.json_body["threepids"]))
  1110. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1111. self.assertEqual("User", channel.json_body["displayname"])
  1112. # the user is deactivated, the threepid will be deleted
  1113. # Get user
  1114. channel = self.make_request(
  1115. "GET", self.url_other_user, access_token=self.admin_user_tok,
  1116. )
  1117. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1118. self.assertEqual("@user:test", channel.json_body["name"])
  1119. self.assertEqual(True, channel.json_body["deactivated"])
  1120. self.assertEqual(0, len(channel.json_body["threepids"]))
  1121. self.assertEqual("mxc://servername/mediaid", channel.json_body["avatar_url"])
  1122. self.assertEqual("User", channel.json_body["displayname"])
  1123. @override_config({"user_directory": {"enabled": True, "search_all_users": True}})
  1124. def test_change_name_deactivate_user_user_directory(self):
  1125. """
  1126. Test change profile information of a deactivated user and
  1127. check that it does not appear in user directory
  1128. """
  1129. # is in user directory
  1130. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1131. self.assertTrue(profile["display_name"] == "User")
  1132. # Deactivate user
  1133. body = json.dumps({"deactivated": True})
  1134. channel = self.make_request(
  1135. "PUT",
  1136. self.url_other_user,
  1137. access_token=self.admin_user_tok,
  1138. content=body.encode(encoding="utf_8"),
  1139. )
  1140. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1141. self.assertEqual("@user:test", channel.json_body["name"])
  1142. self.assertEqual(True, channel.json_body["deactivated"])
  1143. # is not in user directory
  1144. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1145. self.assertTrue(profile is None)
  1146. # Set new displayname user
  1147. body = json.dumps({"displayname": "Foobar"})
  1148. channel = self.make_request(
  1149. "PUT",
  1150. self.url_other_user,
  1151. access_token=self.admin_user_tok,
  1152. content=body.encode(encoding="utf_8"),
  1153. )
  1154. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1155. self.assertEqual("@user:test", channel.json_body["name"])
  1156. self.assertEqual(True, channel.json_body["deactivated"])
  1157. self.assertEqual("Foobar", channel.json_body["displayname"])
  1158. # is not in user directory
  1159. profile = self.get_success(self.store.get_user_in_directory(self.other_user))
  1160. self.assertTrue(profile is None)
  1161. def test_reactivate_user(self):
  1162. """
  1163. Test reactivating another user.
  1164. """
  1165. # Deactivate the user.
  1166. channel = self.make_request(
  1167. "PUT",
  1168. self.url_other_user,
  1169. access_token=self.admin_user_tok,
  1170. content=json.dumps({"deactivated": True}).encode(encoding="utf_8"),
  1171. )
  1172. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1173. self._is_erased("@user:test", False)
  1174. d = self.store.mark_user_erased("@user:test")
  1175. self.assertIsNone(self.get_success(d))
  1176. self._is_erased("@user:test", True)
  1177. # Attempt to reactivate the user (without a password).
  1178. channel = self.make_request(
  1179. "PUT",
  1180. self.url_other_user,
  1181. access_token=self.admin_user_tok,
  1182. content=json.dumps({"deactivated": False}).encode(encoding="utf_8"),
  1183. )
  1184. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1185. # Reactivate the user.
  1186. channel = self.make_request(
  1187. "PUT",
  1188. self.url_other_user,
  1189. access_token=self.admin_user_tok,
  1190. content=json.dumps({"deactivated": False, "password": "foo"}).encode(
  1191. encoding="utf_8"
  1192. ),
  1193. )
  1194. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1195. # Get user
  1196. channel = self.make_request(
  1197. "GET", self.url_other_user, access_token=self.admin_user_tok,
  1198. )
  1199. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1200. self.assertEqual("@user:test", channel.json_body["name"])
  1201. self.assertEqual(False, channel.json_body["deactivated"])
  1202. self._is_erased("@user:test", False)
  1203. def test_set_user_as_admin(self):
  1204. """
  1205. Test setting the admin flag on a user.
  1206. """
  1207. # Set a user as an admin
  1208. body = json.dumps({"admin": True})
  1209. channel = self.make_request(
  1210. "PUT",
  1211. self.url_other_user,
  1212. access_token=self.admin_user_tok,
  1213. content=body.encode(encoding="utf_8"),
  1214. )
  1215. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1216. self.assertEqual("@user:test", channel.json_body["name"])
  1217. self.assertEqual(True, channel.json_body["admin"])
  1218. # Get user
  1219. channel = self.make_request(
  1220. "GET", self.url_other_user, access_token=self.admin_user_tok,
  1221. )
  1222. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1223. self.assertEqual("@user:test", channel.json_body["name"])
  1224. self.assertEqual(True, channel.json_body["admin"])
  1225. def test_accidental_deactivation_prevention(self):
  1226. """
  1227. Ensure an account can't accidentally be deactivated by using a str value
  1228. for the deactivated body parameter
  1229. """
  1230. url = "/_synapse/admin/v2/users/@bob:test"
  1231. # Create user
  1232. body = json.dumps({"password": "abc123"})
  1233. channel = self.make_request(
  1234. "PUT",
  1235. url,
  1236. access_token=self.admin_user_tok,
  1237. content=body.encode(encoding="utf_8"),
  1238. )
  1239. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  1240. self.assertEqual("@bob:test", channel.json_body["name"])
  1241. self.assertEqual("bob", channel.json_body["displayname"])
  1242. # Get user
  1243. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1244. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1245. self.assertEqual("@bob:test", channel.json_body["name"])
  1246. self.assertEqual("bob", channel.json_body["displayname"])
  1247. self.assertEqual(0, channel.json_body["deactivated"])
  1248. # Change password (and use a str for deactivate instead of a bool)
  1249. body = json.dumps({"password": "abc123", "deactivated": "false"}) # oops!
  1250. channel = self.make_request(
  1251. "PUT",
  1252. url,
  1253. access_token=self.admin_user_tok,
  1254. content=body.encode(encoding="utf_8"),
  1255. )
  1256. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1257. # Check user is not deactivated
  1258. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1259. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1260. self.assertEqual("@bob:test", channel.json_body["name"])
  1261. self.assertEqual("bob", channel.json_body["displayname"])
  1262. # Ensure they're still alive
  1263. self.assertEqual(0, channel.json_body["deactivated"])
  1264. def _is_erased(self, user_id, expect):
  1265. """Assert that the user is erased or not
  1266. """
  1267. d = self.store.is_user_erased(user_id)
  1268. if expect:
  1269. self.assertTrue(self.get_success(d))
  1270. else:
  1271. self.assertFalse(self.get_success(d))
  1272. class UserMembershipRestTestCase(unittest.HomeserverTestCase):
  1273. servlets = [
  1274. synapse.rest.admin.register_servlets,
  1275. login.register_servlets,
  1276. room.register_servlets,
  1277. ]
  1278. def prepare(self, reactor, clock, hs):
  1279. self.admin_user = self.register_user("admin", "pass", admin=True)
  1280. self.admin_user_tok = self.login("admin", "pass")
  1281. self.other_user = self.register_user("user", "pass")
  1282. self.url = "/_synapse/admin/v1/users/%s/joined_rooms" % urllib.parse.quote(
  1283. self.other_user
  1284. )
  1285. def test_no_auth(self):
  1286. """
  1287. Try to list rooms of an user without authentication.
  1288. """
  1289. channel = self.make_request("GET", self.url, b"{}")
  1290. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1291. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1292. def test_requester_is_no_admin(self):
  1293. """
  1294. If the user is not a server admin, an error is returned.
  1295. """
  1296. other_user_token = self.login("user", "pass")
  1297. channel = self.make_request("GET", self.url, access_token=other_user_token,)
  1298. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1299. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1300. def test_user_does_not_exist(self):
  1301. """
  1302. Tests that a lookup for a user that does not exist returns an empty list
  1303. """
  1304. url = "/_synapse/admin/v1/users/@unknown_person:test/joined_rooms"
  1305. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1306. self.assertEqual(200, channel.code, msg=channel.json_body)
  1307. self.assertEqual(0, channel.json_body["total"])
  1308. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1309. def test_user_is_not_local(self):
  1310. """
  1311. Tests that a lookup for a user that is not a local and participates in no conversation returns an empty list
  1312. """
  1313. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/joined_rooms"
  1314. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1315. self.assertEqual(200, channel.code, msg=channel.json_body)
  1316. self.assertEqual(0, channel.json_body["total"])
  1317. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1318. def test_no_memberships(self):
  1319. """
  1320. Tests that a normal lookup for rooms is successfully
  1321. if user has no memberships
  1322. """
  1323. # Get rooms
  1324. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  1325. self.assertEqual(200, channel.code, msg=channel.json_body)
  1326. self.assertEqual(0, channel.json_body["total"])
  1327. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  1328. def test_get_rooms(self):
  1329. """
  1330. Tests that a normal lookup for rooms is successfully
  1331. """
  1332. # Create rooms and join
  1333. other_user_tok = self.login("user", "pass")
  1334. number_rooms = 5
  1335. for n in range(number_rooms):
  1336. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  1337. # Get rooms
  1338. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  1339. self.assertEqual(200, channel.code, msg=channel.json_body)
  1340. self.assertEqual(number_rooms, channel.json_body["total"])
  1341. self.assertEqual(number_rooms, len(channel.json_body["joined_rooms"]))
  1342. def test_get_rooms_with_nonlocal_user(self):
  1343. """
  1344. Tests that a normal lookup for rooms is successful with a non-local user
  1345. """
  1346. other_user_tok = self.login("user", "pass")
  1347. event_builder_factory = self.hs.get_event_builder_factory()
  1348. event_creation_handler = self.hs.get_event_creation_handler()
  1349. storage = self.hs.get_storage()
  1350. # Create two rooms, one with a local user only and one with both a local
  1351. # and remote user.
  1352. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  1353. local_and_remote_room_id = self.helper.create_room_as(
  1354. self.other_user, tok=other_user_tok
  1355. )
  1356. # Add a remote user to the room.
  1357. builder = event_builder_factory.for_room_version(
  1358. RoomVersions.V1,
  1359. {
  1360. "type": "m.room.member",
  1361. "sender": "@joiner:remote_hs",
  1362. "state_key": "@joiner:remote_hs",
  1363. "room_id": local_and_remote_room_id,
  1364. "content": {"membership": "join"},
  1365. },
  1366. )
  1367. event, context = self.get_success(
  1368. event_creation_handler.create_new_client_event(builder)
  1369. )
  1370. self.get_success(storage.persistence.persist_event(event, context))
  1371. # Now get rooms
  1372. url = "/_synapse/admin/v1/users/@joiner:remote_hs/joined_rooms"
  1373. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1374. self.assertEqual(200, channel.code, msg=channel.json_body)
  1375. self.assertEqual(1, channel.json_body["total"])
  1376. self.assertEqual([local_and_remote_room_id], channel.json_body["joined_rooms"])
  1377. class PushersRestTestCase(unittest.HomeserverTestCase):
  1378. servlets = [
  1379. synapse.rest.admin.register_servlets,
  1380. login.register_servlets,
  1381. ]
  1382. def prepare(self, reactor, clock, hs):
  1383. self.store = hs.get_datastore()
  1384. self.admin_user = self.register_user("admin", "pass", admin=True)
  1385. self.admin_user_tok = self.login("admin", "pass")
  1386. self.other_user = self.register_user("user", "pass")
  1387. self.url = "/_synapse/admin/v1/users/%s/pushers" % urllib.parse.quote(
  1388. self.other_user
  1389. )
  1390. def test_no_auth(self):
  1391. """
  1392. Try to list pushers of an user without authentication.
  1393. """
  1394. channel = self.make_request("GET", self.url, b"{}")
  1395. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1396. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1397. def test_requester_is_no_admin(self):
  1398. """
  1399. If the user is not a server admin, an error is returned.
  1400. """
  1401. other_user_token = self.login("user", "pass")
  1402. channel = self.make_request("GET", self.url, access_token=other_user_token,)
  1403. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1404. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1405. def test_user_does_not_exist(self):
  1406. """
  1407. Tests that a lookup for a user that does not exist returns a 404
  1408. """
  1409. url = "/_synapse/admin/v1/users/@unknown_person:test/pushers"
  1410. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1411. self.assertEqual(404, channel.code, msg=channel.json_body)
  1412. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1413. def test_user_is_not_local(self):
  1414. """
  1415. Tests that a lookup for a user that is not a local returns a 400
  1416. """
  1417. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/pushers"
  1418. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1419. self.assertEqual(400, channel.code, msg=channel.json_body)
  1420. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  1421. def test_get_pushers(self):
  1422. """
  1423. Tests that a normal lookup for pushers is successfully
  1424. """
  1425. # Get pushers
  1426. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  1427. self.assertEqual(200, channel.code, msg=channel.json_body)
  1428. self.assertEqual(0, channel.json_body["total"])
  1429. # Register the pusher
  1430. other_user_token = self.login("user", "pass")
  1431. user_tuple = self.get_success(
  1432. self.store.get_user_by_access_token(other_user_token)
  1433. )
  1434. token_id = user_tuple.token_id
  1435. self.get_success(
  1436. self.hs.get_pusherpool().add_pusher(
  1437. user_id=self.other_user,
  1438. access_token=token_id,
  1439. kind="http",
  1440. app_id="m.http",
  1441. app_display_name="HTTP Push Notifications",
  1442. device_display_name="pushy push",
  1443. pushkey="a@example.com",
  1444. lang=None,
  1445. data={"url": "https://example.com/_matrix/push/v1/notify"},
  1446. )
  1447. )
  1448. # Get pushers
  1449. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  1450. self.assertEqual(200, channel.code, msg=channel.json_body)
  1451. self.assertEqual(1, channel.json_body["total"])
  1452. for p in channel.json_body["pushers"]:
  1453. self.assertIn("pushkey", p)
  1454. self.assertIn("kind", p)
  1455. self.assertIn("app_id", p)
  1456. self.assertIn("app_display_name", p)
  1457. self.assertIn("device_display_name", p)
  1458. self.assertIn("profile_tag", p)
  1459. self.assertIn("lang", p)
  1460. self.assertIn("url", p["data"])
  1461. class UserMediaRestTestCase(unittest.HomeserverTestCase):
  1462. servlets = [
  1463. synapse.rest.admin.register_servlets,
  1464. login.register_servlets,
  1465. ]
  1466. def prepare(self, reactor, clock, hs):
  1467. self.media_repo = hs.get_media_repository_resource()
  1468. self.admin_user = self.register_user("admin", "pass", admin=True)
  1469. self.admin_user_tok = self.login("admin", "pass")
  1470. self.other_user = self.register_user("user", "pass")
  1471. self.url = "/_synapse/admin/v1/users/%s/media" % urllib.parse.quote(
  1472. self.other_user
  1473. )
  1474. def test_no_auth(self):
  1475. """
  1476. Try to list media of an user without authentication.
  1477. """
  1478. channel = self.make_request("GET", self.url, b"{}")
  1479. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1480. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1481. def test_requester_is_no_admin(self):
  1482. """
  1483. If the user is not a server admin, an error is returned.
  1484. """
  1485. other_user_token = self.login("user", "pass")
  1486. channel = self.make_request("GET", self.url, access_token=other_user_token,)
  1487. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1488. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1489. def test_user_does_not_exist(self):
  1490. """
  1491. Tests that a lookup for a user that does not exist returns a 404
  1492. """
  1493. url = "/_synapse/admin/v1/users/@unknown_person:test/media"
  1494. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1495. self.assertEqual(404, channel.code, msg=channel.json_body)
  1496. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1497. def test_user_is_not_local(self):
  1498. """
  1499. Tests that a lookup for a user that is not a local returns a 400
  1500. """
  1501. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/media"
  1502. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1503. self.assertEqual(400, channel.code, msg=channel.json_body)
  1504. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  1505. def test_limit(self):
  1506. """
  1507. Testing list of media with limit
  1508. """
  1509. number_media = 20
  1510. other_user_tok = self.login("user", "pass")
  1511. self._create_media(other_user_tok, number_media)
  1512. channel = self.make_request(
  1513. "GET", self.url + "?limit=5", access_token=self.admin_user_tok,
  1514. )
  1515. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1516. self.assertEqual(channel.json_body["total"], number_media)
  1517. self.assertEqual(len(channel.json_body["media"]), 5)
  1518. self.assertEqual(channel.json_body["next_token"], 5)
  1519. self._check_fields(channel.json_body["media"])
  1520. def test_from(self):
  1521. """
  1522. Testing list of media with a defined starting point (from)
  1523. """
  1524. number_media = 20
  1525. other_user_tok = self.login("user", "pass")
  1526. self._create_media(other_user_tok, number_media)
  1527. channel = self.make_request(
  1528. "GET", self.url + "?from=5", access_token=self.admin_user_tok,
  1529. )
  1530. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1531. self.assertEqual(channel.json_body["total"], number_media)
  1532. self.assertEqual(len(channel.json_body["media"]), 15)
  1533. self.assertNotIn("next_token", channel.json_body)
  1534. self._check_fields(channel.json_body["media"])
  1535. def test_limit_and_from(self):
  1536. """
  1537. Testing list of media with a defined starting point and limit
  1538. """
  1539. number_media = 20
  1540. other_user_tok = self.login("user", "pass")
  1541. self._create_media(other_user_tok, number_media)
  1542. channel = self.make_request(
  1543. "GET", self.url + "?from=5&limit=10", access_token=self.admin_user_tok,
  1544. )
  1545. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1546. self.assertEqual(channel.json_body["total"], number_media)
  1547. self.assertEqual(channel.json_body["next_token"], 15)
  1548. self.assertEqual(len(channel.json_body["media"]), 10)
  1549. self._check_fields(channel.json_body["media"])
  1550. def test_limit_is_negative(self):
  1551. """
  1552. Testing that a negative limit parameter returns a 400
  1553. """
  1554. channel = self.make_request(
  1555. "GET", self.url + "?limit=-5", access_token=self.admin_user_tok,
  1556. )
  1557. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1558. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  1559. def test_from_is_negative(self):
  1560. """
  1561. Testing that a negative from parameter returns a 400
  1562. """
  1563. channel = self.make_request(
  1564. "GET", self.url + "?from=-5", access_token=self.admin_user_tok,
  1565. )
  1566. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1567. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  1568. def test_next_token(self):
  1569. """
  1570. Testing that `next_token` appears at the right place
  1571. """
  1572. number_media = 20
  1573. other_user_tok = self.login("user", "pass")
  1574. self._create_media(other_user_tok, number_media)
  1575. # `next_token` does not appear
  1576. # Number of results is the number of entries
  1577. channel = self.make_request(
  1578. "GET", self.url + "?limit=20", access_token=self.admin_user_tok,
  1579. )
  1580. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1581. self.assertEqual(channel.json_body["total"], number_media)
  1582. self.assertEqual(len(channel.json_body["media"]), number_media)
  1583. self.assertNotIn("next_token", channel.json_body)
  1584. # `next_token` does not appear
  1585. # Number of max results is larger than the number of entries
  1586. channel = self.make_request(
  1587. "GET", self.url + "?limit=21", access_token=self.admin_user_tok,
  1588. )
  1589. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1590. self.assertEqual(channel.json_body["total"], number_media)
  1591. self.assertEqual(len(channel.json_body["media"]), number_media)
  1592. self.assertNotIn("next_token", channel.json_body)
  1593. # `next_token` does appear
  1594. # Number of max results is smaller than the number of entries
  1595. channel = self.make_request(
  1596. "GET", self.url + "?limit=19", access_token=self.admin_user_tok,
  1597. )
  1598. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1599. self.assertEqual(channel.json_body["total"], number_media)
  1600. self.assertEqual(len(channel.json_body["media"]), 19)
  1601. self.assertEqual(channel.json_body["next_token"], 19)
  1602. # Check
  1603. # Set `from` to value of `next_token` for request remaining entries
  1604. # `next_token` does not appear
  1605. channel = self.make_request(
  1606. "GET", self.url + "?from=19", access_token=self.admin_user_tok,
  1607. )
  1608. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1609. self.assertEqual(channel.json_body["total"], number_media)
  1610. self.assertEqual(len(channel.json_body["media"]), 1)
  1611. self.assertNotIn("next_token", channel.json_body)
  1612. def test_user_has_no_media(self):
  1613. """
  1614. Tests that a normal lookup for media is successfully
  1615. if user has no media created
  1616. """
  1617. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  1618. self.assertEqual(200, channel.code, msg=channel.json_body)
  1619. self.assertEqual(0, channel.json_body["total"])
  1620. self.assertEqual(0, len(channel.json_body["media"]))
  1621. def test_get_media(self):
  1622. """
  1623. Tests that a normal lookup for media is successfully
  1624. """
  1625. number_media = 5
  1626. other_user_tok = self.login("user", "pass")
  1627. self._create_media(other_user_tok, number_media)
  1628. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  1629. self.assertEqual(200, channel.code, msg=channel.json_body)
  1630. self.assertEqual(number_media, channel.json_body["total"])
  1631. self.assertEqual(number_media, len(channel.json_body["media"]))
  1632. self.assertNotIn("next_token", channel.json_body)
  1633. self._check_fields(channel.json_body["media"])
  1634. def _create_media(self, user_token, number_media):
  1635. """
  1636. Create a number of media for a specific user
  1637. """
  1638. upload_resource = self.media_repo.children[b"upload"]
  1639. for i in range(number_media):
  1640. # file size is 67 Byte
  1641. image_data = unhexlify(
  1642. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  1643. b"0000001f15c4890000000a49444154789c63000100000500010d"
  1644. b"0a2db40000000049454e44ae426082"
  1645. )
  1646. # Upload some media into the room
  1647. self.helper.upload_media(
  1648. upload_resource, image_data, tok=user_token, expect_code=200
  1649. )
  1650. def _check_fields(self, content):
  1651. """Checks that all attributes are present in content
  1652. """
  1653. for m in content:
  1654. self.assertIn("media_id", m)
  1655. self.assertIn("media_type", m)
  1656. self.assertIn("media_length", m)
  1657. self.assertIn("upload_name", m)
  1658. self.assertIn("created_ts", m)
  1659. self.assertIn("last_access_ts", m)
  1660. self.assertIn("quarantined_by", m)
  1661. self.assertIn("safe_from_quarantine", m)
  1662. class UserTokenRestTestCase(unittest.HomeserverTestCase):
  1663. """Test for /_synapse/admin/v1/users/<user>/login
  1664. """
  1665. servlets = [
  1666. synapse.rest.admin.register_servlets,
  1667. login.register_servlets,
  1668. sync.register_servlets,
  1669. room.register_servlets,
  1670. devices.register_servlets,
  1671. logout.register_servlets,
  1672. ]
  1673. def prepare(self, reactor, clock, hs):
  1674. self.store = hs.get_datastore()
  1675. self.admin_user = self.register_user("admin", "pass", admin=True)
  1676. self.admin_user_tok = self.login("admin", "pass")
  1677. self.other_user = self.register_user("user", "pass")
  1678. self.other_user_tok = self.login("user", "pass")
  1679. self.url = "/_synapse/admin/v1/users/%s/login" % urllib.parse.quote(
  1680. self.other_user
  1681. )
  1682. def _get_token(self) -> str:
  1683. channel = self.make_request(
  1684. "POST", self.url, b"{}", access_token=self.admin_user_tok
  1685. )
  1686. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1687. return channel.json_body["access_token"]
  1688. def test_no_auth(self):
  1689. """Try to login as a user without authentication.
  1690. """
  1691. channel = self.make_request("POST", self.url, b"{}")
  1692. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1693. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1694. def test_not_admin(self):
  1695. """Try to login as a user as a non-admin user.
  1696. """
  1697. channel = self.make_request(
  1698. "POST", self.url, b"{}", access_token=self.other_user_tok
  1699. )
  1700. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1701. def test_send_event(self):
  1702. """Test that sending event as a user works.
  1703. """
  1704. # Create a room.
  1705. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  1706. # Login in as the user
  1707. puppet_token = self._get_token()
  1708. # Test that sending works, and generates the event as the right user.
  1709. resp = self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  1710. event_id = resp["event_id"]
  1711. event = self.get_success(self.store.get_event(event_id))
  1712. self.assertEqual(event.sender, self.other_user)
  1713. def test_devices(self):
  1714. """Tests that logging in as a user doesn't create a new device for them.
  1715. """
  1716. # Login in as the user
  1717. self._get_token()
  1718. # Check that we don't see a new device in our devices list
  1719. channel = self.make_request(
  1720. "GET", "devices", b"{}", access_token=self.other_user_tok
  1721. )
  1722. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1723. # We should only see the one device (from the login in `prepare`)
  1724. self.assertEqual(len(channel.json_body["devices"]), 1)
  1725. def test_logout(self):
  1726. """Test that calling `/logout` with the token works.
  1727. """
  1728. # Login in as the user
  1729. puppet_token = self._get_token()
  1730. # Test that we can successfully make a request
  1731. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1732. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1733. # Logout with the puppet token
  1734. channel = self.make_request("POST", "logout", b"{}", access_token=puppet_token)
  1735. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1736. # The puppet token should no longer work
  1737. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1738. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1739. # .. but the real user's tokens should still work
  1740. channel = self.make_request(
  1741. "GET", "devices", b"{}", access_token=self.other_user_tok
  1742. )
  1743. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1744. def test_user_logout_all(self):
  1745. """Tests that the target user calling `/logout/all` does *not* expire
  1746. the token.
  1747. """
  1748. # Login in as the user
  1749. puppet_token = self._get_token()
  1750. # Test that we can successfully make a request
  1751. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1752. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1753. # Logout all with the real user token
  1754. channel = self.make_request(
  1755. "POST", "logout/all", b"{}", access_token=self.other_user_tok
  1756. )
  1757. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1758. # The puppet token should still work
  1759. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1760. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1761. # .. but the real user's tokens shouldn't
  1762. channel = self.make_request(
  1763. "GET", "devices", b"{}", access_token=self.other_user_tok
  1764. )
  1765. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1766. def test_admin_logout_all(self):
  1767. """Tests that the admin user calling `/logout/all` does expire the
  1768. token.
  1769. """
  1770. # Login in as the user
  1771. puppet_token = self._get_token()
  1772. # Test that we can successfully make a request
  1773. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1774. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1775. # Logout all with the admin user token
  1776. channel = self.make_request(
  1777. "POST", "logout/all", b"{}", access_token=self.admin_user_tok
  1778. )
  1779. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1780. # The puppet token should no longer work
  1781. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1782. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1783. # .. but the real user's tokens should still work
  1784. channel = self.make_request(
  1785. "GET", "devices", b"{}", access_token=self.other_user_tok
  1786. )
  1787. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1788. @unittest.override_config(
  1789. {
  1790. "public_baseurl": "https://example.org/",
  1791. "user_consent": {
  1792. "version": "1.0",
  1793. "policy_name": "My Cool Privacy Policy",
  1794. "template_dir": "/",
  1795. "require_at_registration": True,
  1796. "block_events_error": "You should accept the policy",
  1797. },
  1798. "form_secret": "123secret",
  1799. }
  1800. )
  1801. def test_consent(self):
  1802. """Test that sending a message is not subject to the privacy policies.
  1803. """
  1804. # Have the admin user accept the terms.
  1805. self.get_success(self.store.user_set_consent_version(self.admin_user, "1.0"))
  1806. # First, cheekily accept the terms and create a room
  1807. self.get_success(self.store.user_set_consent_version(self.other_user, "1.0"))
  1808. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  1809. self.helper.send_event(room_id, "com.example.test", tok=self.other_user_tok)
  1810. # Now unaccept it and check that we can't send an event
  1811. self.get_success(self.store.user_set_consent_version(self.other_user, "0.0"))
  1812. self.helper.send_event(
  1813. room_id, "com.example.test", tok=self.other_user_tok, expect_code=403
  1814. )
  1815. # Login in as the user
  1816. puppet_token = self._get_token()
  1817. # Sending an event on their behalf should work fine
  1818. self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  1819. @override_config(
  1820. {"limit_usage_by_mau": True, "max_mau_value": 1, "mau_trial_days": 0}
  1821. )
  1822. def test_mau_limit(self):
  1823. # Create a room as the admin user. This will bump the monthly active users to 1.
  1824. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1825. # Trying to join as the other user should fail due to reaching MAU limit.
  1826. self.helper.join(
  1827. room_id, user=self.other_user, tok=self.other_user_tok, expect_code=403
  1828. )
  1829. # Logging in as the other user and joining a room should work, even
  1830. # though the MAU limit would stop the user doing so.
  1831. puppet_token = self._get_token()
  1832. self.helper.join(room_id, user=self.other_user, tok=puppet_token)
  1833. class WhoisRestTestCase(unittest.HomeserverTestCase):
  1834. servlets = [
  1835. synapse.rest.admin.register_servlets,
  1836. login.register_servlets,
  1837. ]
  1838. def prepare(self, reactor, clock, hs):
  1839. self.admin_user = self.register_user("admin", "pass", admin=True)
  1840. self.admin_user_tok = self.login("admin", "pass")
  1841. self.other_user = self.register_user("user", "pass")
  1842. self.url1 = "/_synapse/admin/v1/whois/%s" % urllib.parse.quote(self.other_user)
  1843. self.url2 = "/_matrix/client/r0/admin/whois/%s" % urllib.parse.quote(
  1844. self.other_user
  1845. )
  1846. def test_no_auth(self):
  1847. """
  1848. Try to get information of an user without authentication.
  1849. """
  1850. channel = self.make_request("GET", self.url1, b"{}")
  1851. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1852. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1853. channel = self.make_request("GET", self.url2, b"{}")
  1854. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1855. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1856. def test_requester_is_not_admin(self):
  1857. """
  1858. If the user is not a server admin, an error is returned.
  1859. """
  1860. self.register_user("user2", "pass")
  1861. other_user2_token = self.login("user2", "pass")
  1862. channel = self.make_request("GET", self.url1, access_token=other_user2_token,)
  1863. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1864. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1865. channel = self.make_request("GET", self.url2, access_token=other_user2_token,)
  1866. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1867. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1868. def test_user_is_not_local(self):
  1869. """
  1870. Tests that a lookup for a user that is not a local returns a 400
  1871. """
  1872. url1 = "/_synapse/admin/v1/whois/@unknown_person:unknown_domain"
  1873. url2 = "/_matrix/client/r0/admin/whois/@unknown_person:unknown_domain"
  1874. channel = self.make_request("GET", url1, access_token=self.admin_user_tok,)
  1875. self.assertEqual(400, channel.code, msg=channel.json_body)
  1876. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  1877. channel = self.make_request("GET", url2, access_token=self.admin_user_tok,)
  1878. self.assertEqual(400, channel.code, msg=channel.json_body)
  1879. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  1880. def test_get_whois_admin(self):
  1881. """
  1882. The lookup should succeed for an admin.
  1883. """
  1884. channel = self.make_request("GET", self.url1, access_token=self.admin_user_tok,)
  1885. self.assertEqual(200, channel.code, msg=channel.json_body)
  1886. self.assertEqual(self.other_user, channel.json_body["user_id"])
  1887. self.assertIn("devices", channel.json_body)
  1888. channel = self.make_request("GET", self.url2, access_token=self.admin_user_tok,)
  1889. self.assertEqual(200, channel.code, msg=channel.json_body)
  1890. self.assertEqual(self.other_user, channel.json_body["user_id"])
  1891. self.assertIn("devices", channel.json_body)
  1892. def test_get_whois_user(self):
  1893. """
  1894. The lookup should succeed for a normal user looking up their own information.
  1895. """
  1896. other_user_token = self.login("user", "pass")
  1897. channel = self.make_request("GET", self.url1, access_token=other_user_token,)
  1898. self.assertEqual(200, channel.code, msg=channel.json_body)
  1899. self.assertEqual(self.other_user, channel.json_body["user_id"])
  1900. self.assertIn("devices", channel.json_body)
  1901. channel = self.make_request("GET", self.url2, access_token=other_user_token,)
  1902. self.assertEqual(200, channel.code, msg=channel.json_body)
  1903. self.assertEqual(self.other_user, channel.json_body["user_id"])
  1904. self.assertIn("devices", channel.json_body)
  1905. class ShadowBanRestTestCase(unittest.HomeserverTestCase):
  1906. servlets = [
  1907. synapse.rest.admin.register_servlets,
  1908. login.register_servlets,
  1909. ]
  1910. def prepare(self, reactor, clock, hs):
  1911. self.store = hs.get_datastore()
  1912. self.admin_user = self.register_user("admin", "pass", admin=True)
  1913. self.admin_user_tok = self.login("admin", "pass")
  1914. self.other_user = self.register_user("user", "pass")
  1915. self.url = "/_synapse/admin/v1/users/%s/shadow_ban" % urllib.parse.quote(
  1916. self.other_user
  1917. )
  1918. def test_no_auth(self):
  1919. """
  1920. Try to get information of an user without authentication.
  1921. """
  1922. channel = self.make_request("POST", self.url)
  1923. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1924. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1925. def test_requester_is_not_admin(self):
  1926. """
  1927. If the user is not a server admin, an error is returned.
  1928. """
  1929. other_user_token = self.login("user", "pass")
  1930. channel = self.make_request("POST", self.url, access_token=other_user_token)
  1931. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1932. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1933. def test_user_is_not_local(self):
  1934. """
  1935. Tests that shadow-banning for a user that is not a local returns a 400
  1936. """
  1937. url = "/_synapse/admin/v1/whois/@unknown_person:unknown_domain"
  1938. channel = self.make_request("POST", url, access_token=self.admin_user_tok)
  1939. self.assertEqual(400, channel.code, msg=channel.json_body)
  1940. def test_success(self):
  1941. """
  1942. Shadow-banning should succeed for an admin.
  1943. """
  1944. # The user starts off as not shadow-banned.
  1945. other_user_token = self.login("user", "pass")
  1946. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  1947. self.assertFalse(result.shadow_banned)
  1948. channel = self.make_request("POST", self.url, access_token=self.admin_user_tok)
  1949. self.assertEqual(200, channel.code, msg=channel.json_body)
  1950. self.assertEqual({}, channel.json_body)
  1951. # Ensure the user is shadow-banned (and the cache was cleared).
  1952. result = self.get_success(self.store.get_user_by_access_token(other_user_token))
  1953. self.assertTrue(result.shadow_banned)