test_user.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  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 mock import Mock
  21. import synapse.rest.admin
  22. from synapse.api.constants import UserTypes
  23. from synapse.api.errors import Codes, HttpResponseException, ResourceLimitError
  24. from synapse.rest.client.v1 import login, logout, profile, room
  25. from synapse.rest.client.v2_alpha import devices, sync
  26. from tests import unittest
  27. from tests.test_utils import make_awaitable
  28. from tests.unittest import override_config
  29. class UserRegisterTestCase(unittest.HomeserverTestCase):
  30. servlets = [
  31. synapse.rest.admin.register_servlets_for_client_rest_resource,
  32. profile.register_servlets,
  33. ]
  34. def make_homeserver(self, reactor, clock):
  35. self.url = "/_synapse/admin/v1/register"
  36. self.registration_handler = Mock()
  37. self.identity_handler = Mock()
  38. self.login_handler = Mock()
  39. self.device_handler = Mock()
  40. self.device_handler.check_device_registered = Mock(return_value="FAKE")
  41. self.datastore = Mock(return_value=Mock())
  42. self.datastore.get_current_state_deltas = Mock(return_value=(0, []))
  43. self.secrets = Mock()
  44. self.hs = self.setup_test_homeserver()
  45. self.hs.config.registration_shared_secret = "shared"
  46. self.hs.get_media_repository = Mock()
  47. self.hs.get_deactivate_account_handler = Mock()
  48. return self.hs
  49. def test_disabled(self):
  50. """
  51. If there is no shared secret, registration through this method will be
  52. prevented.
  53. """
  54. self.hs.config.registration_shared_secret = None
  55. channel = self.make_request("POST", self.url, b"{}")
  56. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  57. self.assertEqual(
  58. "Shared secret registration is not enabled", channel.json_body["error"]
  59. )
  60. def test_get_nonce(self):
  61. """
  62. Calling GET on the endpoint will return a randomised nonce, using the
  63. homeserver's secrets provider.
  64. """
  65. secrets = Mock()
  66. secrets.token_hex = Mock(return_value="abcd")
  67. self.hs.get_secrets = Mock(return_value=secrets)
  68. channel = self.make_request("GET", self.url)
  69. self.assertEqual(channel.json_body, {"nonce": "abcd"})
  70. def test_expired_nonce(self):
  71. """
  72. Calling GET on the endpoint will return a randomised nonce, which will
  73. only last for SALT_TIMEOUT (60s).
  74. """
  75. channel = self.make_request("GET", self.url)
  76. nonce = channel.json_body["nonce"]
  77. # 59 seconds
  78. self.reactor.advance(59)
  79. body = json.dumps({"nonce": nonce})
  80. channel = self.make_request("POST", self.url, body.encode("utf8"))
  81. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  82. self.assertEqual("username must be specified", channel.json_body["error"])
  83. # 61 seconds
  84. self.reactor.advance(2)
  85. channel = self.make_request("POST", self.url, body.encode("utf8"))
  86. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  87. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  88. def test_register_incorrect_nonce(self):
  89. """
  90. Only the provided nonce can be used, as it's checked in the MAC.
  91. """
  92. channel = self.make_request("GET", self.url)
  93. nonce = channel.json_body["nonce"]
  94. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  95. want_mac.update(b"notthenonce\x00bob\x00abc123\x00admin")
  96. want_mac = want_mac.hexdigest()
  97. body = json.dumps(
  98. {
  99. "nonce": nonce,
  100. "username": "bob",
  101. "password": "abc123",
  102. "admin": True,
  103. "mac": want_mac,
  104. }
  105. )
  106. channel = self.make_request("POST", self.url, body.encode("utf8"))
  107. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  108. self.assertEqual("HMAC incorrect", channel.json_body["error"])
  109. def test_register_correct_nonce(self):
  110. """
  111. When the correct nonce is provided, and the right key is provided, the
  112. user is registered.
  113. """
  114. channel = self.make_request("GET", self.url)
  115. nonce = channel.json_body["nonce"]
  116. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  117. want_mac.update(
  118. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  119. )
  120. want_mac = want_mac.hexdigest()
  121. body = json.dumps(
  122. {
  123. "nonce": nonce,
  124. "username": "bob",
  125. "password": "abc123",
  126. "admin": True,
  127. "user_type": UserTypes.SUPPORT,
  128. "mac": want_mac,
  129. }
  130. )
  131. channel = self.make_request("POST", self.url, body.encode("utf8"))
  132. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  133. self.assertEqual("@bob:test", channel.json_body["user_id"])
  134. def test_nonce_reuse(self):
  135. """
  136. A valid unrecognised nonce.
  137. """
  138. channel = self.make_request("GET", self.url)
  139. nonce = channel.json_body["nonce"]
  140. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  141. want_mac.update(nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin")
  142. want_mac = want_mac.hexdigest()
  143. body = json.dumps(
  144. {
  145. "nonce": nonce,
  146. "username": "bob",
  147. "password": "abc123",
  148. "admin": True,
  149. "mac": want_mac,
  150. }
  151. )
  152. channel = self.make_request("POST", self.url, body.encode("utf8"))
  153. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  154. self.assertEqual("@bob:test", channel.json_body["user_id"])
  155. # Now, try and reuse it
  156. channel = self.make_request("POST", self.url, body.encode("utf8"))
  157. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  158. self.assertEqual("unrecognised nonce", channel.json_body["error"])
  159. def test_missing_parts(self):
  160. """
  161. Synapse will complain if you don't give nonce, username, password, and
  162. mac. Admin and user_types are optional. Additional checks are done for length
  163. and type.
  164. """
  165. def nonce():
  166. channel = self.make_request("GET", self.url)
  167. return channel.json_body["nonce"]
  168. #
  169. # Nonce check
  170. #
  171. # Must be present
  172. body = json.dumps({})
  173. channel = self.make_request("POST", self.url, body.encode("utf8"))
  174. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  175. self.assertEqual("nonce must be specified", channel.json_body["error"])
  176. #
  177. # Username checks
  178. #
  179. # Must be present
  180. body = json.dumps({"nonce": nonce()})
  181. channel = self.make_request("POST", self.url, body.encode("utf8"))
  182. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  183. self.assertEqual("username must be specified", channel.json_body["error"])
  184. # Must be a string
  185. body = json.dumps({"nonce": nonce(), "username": 1234})
  186. channel = self.make_request("POST", self.url, body.encode("utf8"))
  187. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  188. self.assertEqual("Invalid username", channel.json_body["error"])
  189. # Must not have null bytes
  190. body = json.dumps({"nonce": nonce(), "username": "abcd\u0000"})
  191. channel = self.make_request("POST", self.url, body.encode("utf8"))
  192. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  193. self.assertEqual("Invalid username", channel.json_body["error"])
  194. # Must not have null bytes
  195. body = json.dumps({"nonce": nonce(), "username": "a" * 1000})
  196. channel = self.make_request("POST", self.url, body.encode("utf8"))
  197. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  198. self.assertEqual("Invalid username", channel.json_body["error"])
  199. #
  200. # Password checks
  201. #
  202. # Must be present
  203. body = json.dumps({"nonce": nonce(), "username": "a"})
  204. channel = self.make_request("POST", self.url, body.encode("utf8"))
  205. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  206. self.assertEqual("password must be specified", channel.json_body["error"])
  207. # Must be a string
  208. body = json.dumps({"nonce": nonce(), "username": "a", "password": 1234})
  209. channel = self.make_request("POST", self.url, body.encode("utf8"))
  210. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  211. self.assertEqual("Invalid password", channel.json_body["error"])
  212. # Must not have null bytes
  213. body = json.dumps({"nonce": nonce(), "username": "a", "password": "abcd\u0000"})
  214. channel = self.make_request("POST", self.url, body.encode("utf8"))
  215. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  216. self.assertEqual("Invalid password", channel.json_body["error"])
  217. # Super long
  218. body = json.dumps({"nonce": nonce(), "username": "a", "password": "A" * 1000})
  219. channel = self.make_request("POST", self.url, body.encode("utf8"))
  220. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  221. self.assertEqual("Invalid password", channel.json_body["error"])
  222. #
  223. # user_type check
  224. #
  225. # Invalid user_type
  226. body = json.dumps(
  227. {
  228. "nonce": nonce(),
  229. "username": "a",
  230. "password": "1234",
  231. "user_type": "invalid",
  232. }
  233. )
  234. channel = self.make_request("POST", self.url, body.encode("utf8"))
  235. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  236. self.assertEqual("Invalid user type", channel.json_body["error"])
  237. def test_displayname(self):
  238. """
  239. Test that displayname of new user is set
  240. """
  241. # set no displayname
  242. channel = self.make_request("GET", self.url)
  243. nonce = channel.json_body["nonce"]
  244. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  245. want_mac.update(nonce.encode("ascii") + b"\x00bob1\x00abc123\x00notadmin")
  246. want_mac = want_mac.hexdigest()
  247. body = json.dumps(
  248. {"nonce": nonce, "username": "bob1", "password": "abc123", "mac": want_mac}
  249. )
  250. channel = self.make_request("POST", self.url, body.encode("utf8"))
  251. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  252. self.assertEqual("@bob1:test", channel.json_body["user_id"])
  253. channel = self.make_request("GET", "/profile/@bob1:test/displayname")
  254. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  255. self.assertEqual("bob1", channel.json_body["displayname"])
  256. # displayname is None
  257. channel = self.make_request("GET", self.url)
  258. nonce = channel.json_body["nonce"]
  259. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  260. want_mac.update(nonce.encode("ascii") + b"\x00bob2\x00abc123\x00notadmin")
  261. want_mac = want_mac.hexdigest()
  262. body = json.dumps(
  263. {
  264. "nonce": nonce,
  265. "username": "bob2",
  266. "displayname": None,
  267. "password": "abc123",
  268. "mac": want_mac,
  269. }
  270. )
  271. channel = self.make_request("POST", self.url, body.encode("utf8"))
  272. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  273. self.assertEqual("@bob2:test", channel.json_body["user_id"])
  274. channel = self.make_request("GET", "/profile/@bob2:test/displayname")
  275. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  276. self.assertEqual("bob2", channel.json_body["displayname"])
  277. # displayname is empty
  278. channel = self.make_request("GET", self.url)
  279. nonce = channel.json_body["nonce"]
  280. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  281. want_mac.update(nonce.encode("ascii") + b"\x00bob3\x00abc123\x00notadmin")
  282. want_mac = want_mac.hexdigest()
  283. body = json.dumps(
  284. {
  285. "nonce": nonce,
  286. "username": "bob3",
  287. "displayname": "",
  288. "password": "abc123",
  289. "mac": want_mac,
  290. }
  291. )
  292. channel = self.make_request("POST", self.url, body.encode("utf8"))
  293. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  294. self.assertEqual("@bob3:test", channel.json_body["user_id"])
  295. channel = self.make_request("GET", "/profile/@bob3:test/displayname")
  296. self.assertEqual(404, int(channel.result["code"]), msg=channel.result["body"])
  297. # set displayname
  298. channel = self.make_request("GET", self.url)
  299. nonce = channel.json_body["nonce"]
  300. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  301. want_mac.update(nonce.encode("ascii") + b"\x00bob4\x00abc123\x00notadmin")
  302. want_mac = want_mac.hexdigest()
  303. body = json.dumps(
  304. {
  305. "nonce": nonce,
  306. "username": "bob4",
  307. "displayname": "Bob's Name",
  308. "password": "abc123",
  309. "mac": want_mac,
  310. }
  311. )
  312. channel = self.make_request("POST", self.url, body.encode("utf8"))
  313. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  314. self.assertEqual("@bob4:test", channel.json_body["user_id"])
  315. channel = self.make_request("GET", "/profile/@bob4:test/displayname")
  316. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  317. self.assertEqual("Bob's Name", channel.json_body["displayname"])
  318. @override_config(
  319. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  320. )
  321. def test_register_mau_limit_reached(self):
  322. """
  323. Check we can register a user via the shared secret registration API
  324. even if the MAU limit is reached.
  325. """
  326. handler = self.hs.get_registration_handler()
  327. store = self.hs.get_datastore()
  328. # Set monthly active users to the limit
  329. store.get_monthly_active_count = Mock(
  330. return_value=make_awaitable(self.hs.config.max_mau_value)
  331. )
  332. # Check that the blocking of monthly active users is working as expected
  333. # The registration of a new user fails due to the limit
  334. self.get_failure(
  335. handler.register_user(localpart="local_part"), ResourceLimitError
  336. )
  337. # Register new user with admin API
  338. channel = self.make_request("GET", self.url)
  339. nonce = channel.json_body["nonce"]
  340. want_mac = hmac.new(key=b"shared", digestmod=hashlib.sha1)
  341. want_mac.update(
  342. nonce.encode("ascii") + b"\x00bob\x00abc123\x00admin\x00support"
  343. )
  344. want_mac = want_mac.hexdigest()
  345. body = json.dumps(
  346. {
  347. "nonce": nonce,
  348. "username": "bob",
  349. "password": "abc123",
  350. "admin": True,
  351. "user_type": UserTypes.SUPPORT,
  352. "mac": want_mac,
  353. }
  354. )
  355. channel = self.make_request("POST", self.url, body.encode("utf8"))
  356. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  357. self.assertEqual("@bob:test", channel.json_body["user_id"])
  358. class UsersListTestCase(unittest.HomeserverTestCase):
  359. servlets = [
  360. synapse.rest.admin.register_servlets,
  361. login.register_servlets,
  362. ]
  363. url = "/_synapse/admin/v2/users"
  364. def prepare(self, reactor, clock, hs):
  365. self.admin_user = self.register_user("admin", "pass", admin=True)
  366. self.admin_user_tok = self.login("admin", "pass")
  367. self.register_user("user1", "pass1", admin=False)
  368. self.register_user("user2", "pass2", admin=False)
  369. def test_no_auth(self):
  370. """
  371. Try to list users without authentication.
  372. """
  373. channel = self.make_request("GET", self.url, b"{}")
  374. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  375. self.assertEqual("M_MISSING_TOKEN", channel.json_body["errcode"])
  376. def test_all_users(self):
  377. """
  378. List all users, including deactivated users.
  379. """
  380. channel = self.make_request(
  381. "GET",
  382. self.url + "?deactivated=true",
  383. b"{}",
  384. access_token=self.admin_user_tok,
  385. )
  386. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  387. self.assertEqual(3, len(channel.json_body["users"]))
  388. self.assertEqual(3, channel.json_body["total"])
  389. class UserRestTestCase(unittest.HomeserverTestCase):
  390. servlets = [
  391. synapse.rest.admin.register_servlets,
  392. login.register_servlets,
  393. sync.register_servlets,
  394. ]
  395. def prepare(self, reactor, clock, hs):
  396. self.store = hs.get_datastore()
  397. self.admin_user = self.register_user("admin", "pass", admin=True)
  398. self.admin_user_tok = self.login("admin", "pass")
  399. self.other_user = self.register_user("user", "pass")
  400. self.other_user_token = self.login("user", "pass")
  401. self.url_other_user = "/_synapse/admin/v2/users/%s" % urllib.parse.quote(
  402. self.other_user
  403. )
  404. def test_requester_is_no_admin(self):
  405. """
  406. If the user is not a server admin, an error is returned.
  407. """
  408. url = "/_synapse/admin/v2/users/@bob:test"
  409. channel = self.make_request("GET", url, access_token=self.other_user_token,)
  410. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  411. self.assertEqual("You are not a server admin", channel.json_body["error"])
  412. channel = self.make_request(
  413. "PUT", url, access_token=self.other_user_token, content=b"{}",
  414. )
  415. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  416. self.assertEqual("You are not a server admin", channel.json_body["error"])
  417. def test_user_does_not_exist(self):
  418. """
  419. Tests that a lookup for a user that does not exist returns a 404
  420. """
  421. channel = self.make_request(
  422. "GET",
  423. "/_synapse/admin/v2/users/@unknown_person:test",
  424. access_token=self.admin_user_tok,
  425. )
  426. self.assertEqual(404, channel.code, msg=channel.json_body)
  427. self.assertEqual("M_NOT_FOUND", channel.json_body["errcode"])
  428. def test_create_server_admin(self):
  429. """
  430. Check that a new admin user is created successfully.
  431. """
  432. url = "/_synapse/admin/v2/users/@bob:test"
  433. # Create user (server admin)
  434. body = json.dumps(
  435. {
  436. "password": "abc123",
  437. "admin": True,
  438. "displayname": "Bob's name",
  439. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  440. "avatar_url": "mxc://fibble/wibble",
  441. }
  442. )
  443. channel = self.make_request(
  444. "PUT",
  445. url,
  446. access_token=self.admin_user_tok,
  447. content=body.encode(encoding="utf_8"),
  448. )
  449. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  450. self.assertEqual("@bob:test", channel.json_body["name"])
  451. self.assertEqual("Bob's name", channel.json_body["displayname"])
  452. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  453. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  454. self.assertEqual(True, channel.json_body["admin"])
  455. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  456. # Get user
  457. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  458. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  459. self.assertEqual("@bob:test", channel.json_body["name"])
  460. self.assertEqual("Bob's name", channel.json_body["displayname"])
  461. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  462. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  463. self.assertEqual(True, channel.json_body["admin"])
  464. self.assertEqual(False, channel.json_body["is_guest"])
  465. self.assertEqual(False, channel.json_body["deactivated"])
  466. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  467. def test_create_user(self):
  468. """
  469. Check that a new regular user is created successfully.
  470. """
  471. url = "/_synapse/admin/v2/users/@bob:test"
  472. # Create user
  473. body = json.dumps(
  474. {
  475. "password": "abc123",
  476. "admin": False,
  477. "displayname": "Bob's name",
  478. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  479. "avatar_url": "mxc://fibble/wibble",
  480. }
  481. )
  482. channel = self.make_request(
  483. "PUT",
  484. url,
  485. access_token=self.admin_user_tok,
  486. content=body.encode(encoding="utf_8"),
  487. )
  488. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  489. self.assertEqual("@bob:test", channel.json_body["name"])
  490. self.assertEqual("Bob's name", channel.json_body["displayname"])
  491. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  492. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  493. self.assertEqual(False, channel.json_body["admin"])
  494. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  495. # Get user
  496. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  497. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  498. self.assertEqual("@bob:test", channel.json_body["name"])
  499. self.assertEqual("Bob's name", channel.json_body["displayname"])
  500. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  501. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  502. self.assertEqual(False, channel.json_body["admin"])
  503. self.assertEqual(False, channel.json_body["is_guest"])
  504. self.assertEqual(False, channel.json_body["deactivated"])
  505. self.assertEqual("mxc://fibble/wibble", channel.json_body["avatar_url"])
  506. @override_config(
  507. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  508. )
  509. def test_create_user_mau_limit_reached_active_admin(self):
  510. """
  511. Check that an admin can register a new user via the admin API
  512. even if the MAU limit is reached.
  513. Admin user was active before creating user.
  514. """
  515. handler = self.hs.get_registration_handler()
  516. # Sync to set admin user to active
  517. # before limit of monthly active users is reached
  518. channel = self.make_request("GET", "/sync", access_token=self.admin_user_tok)
  519. if channel.code != 200:
  520. raise HttpResponseException(
  521. channel.code, channel.result["reason"], channel.result["body"]
  522. )
  523. # Set monthly active users to the limit
  524. self.store.get_monthly_active_count = Mock(
  525. return_value=make_awaitable(self.hs.config.max_mau_value)
  526. )
  527. # Check that the blocking of monthly active users is working as expected
  528. # The registration of a new user fails due to the limit
  529. self.get_failure(
  530. handler.register_user(localpart="local_part"), ResourceLimitError
  531. )
  532. # Register new user with admin API
  533. url = "/_synapse/admin/v2/users/@bob:test"
  534. # Create user
  535. body = json.dumps({"password": "abc123", "admin": False})
  536. channel = self.make_request(
  537. "PUT",
  538. url,
  539. access_token=self.admin_user_tok,
  540. content=body.encode(encoding="utf_8"),
  541. )
  542. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  543. self.assertEqual("@bob:test", channel.json_body["name"])
  544. self.assertEqual(False, channel.json_body["admin"])
  545. @override_config(
  546. {"limit_usage_by_mau": True, "max_mau_value": 2, "mau_trial_days": 0}
  547. )
  548. def test_create_user_mau_limit_reached_passive_admin(self):
  549. """
  550. Check that an admin can register a new user via the admin API
  551. even if the MAU limit is reached.
  552. Admin user was not active before creating user.
  553. """
  554. handler = self.hs.get_registration_handler()
  555. # Set monthly active users to the limit
  556. self.store.get_monthly_active_count = Mock(
  557. return_value=make_awaitable(self.hs.config.max_mau_value)
  558. )
  559. # Check that the blocking of monthly active users is working as expected
  560. # The registration of a new user fails due to the limit
  561. self.get_failure(
  562. handler.register_user(localpart="local_part"), ResourceLimitError
  563. )
  564. # Register new user with admin API
  565. url = "/_synapse/admin/v2/users/@bob:test"
  566. # Create user
  567. body = json.dumps({"password": "abc123", "admin": False})
  568. channel = self.make_request(
  569. "PUT",
  570. url,
  571. access_token=self.admin_user_tok,
  572. content=body.encode(encoding="utf_8"),
  573. )
  574. # Admin user is not blocked by mau anymore
  575. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  576. self.assertEqual("@bob:test", channel.json_body["name"])
  577. self.assertEqual(False, channel.json_body["admin"])
  578. @override_config(
  579. {
  580. "email": {
  581. "enable_notifs": True,
  582. "notif_for_new_users": True,
  583. "notif_from": "test@example.com",
  584. },
  585. "public_baseurl": "https://example.com",
  586. }
  587. )
  588. def test_create_user_email_notif_for_new_users(self):
  589. """
  590. Check that a new regular user is created successfully and
  591. got an email pusher.
  592. """
  593. url = "/_synapse/admin/v2/users/@bob:test"
  594. # Create user
  595. body = json.dumps(
  596. {
  597. "password": "abc123",
  598. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  599. }
  600. )
  601. channel = self.make_request(
  602. "PUT",
  603. url,
  604. access_token=self.admin_user_tok,
  605. content=body.encode(encoding="utf_8"),
  606. )
  607. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  608. self.assertEqual("@bob:test", channel.json_body["name"])
  609. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  610. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  611. pushers = self.get_success(
  612. self.store.get_pushers_by({"user_name": "@bob:test"})
  613. )
  614. pushers = list(pushers)
  615. self.assertEqual(len(pushers), 1)
  616. self.assertEqual("@bob:test", pushers[0].user_name)
  617. @override_config(
  618. {
  619. "email": {
  620. "enable_notifs": False,
  621. "notif_for_new_users": False,
  622. "notif_from": "test@example.com",
  623. },
  624. "public_baseurl": "https://example.com",
  625. }
  626. )
  627. def test_create_user_email_no_notif_for_new_users(self):
  628. """
  629. Check that a new regular user is created successfully and
  630. got not an email pusher.
  631. """
  632. url = "/_synapse/admin/v2/users/@bob:test"
  633. # Create user
  634. body = json.dumps(
  635. {
  636. "password": "abc123",
  637. "threepids": [{"medium": "email", "address": "bob@bob.bob"}],
  638. }
  639. )
  640. channel = self.make_request(
  641. "PUT",
  642. url,
  643. access_token=self.admin_user_tok,
  644. content=body.encode(encoding="utf_8"),
  645. )
  646. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  647. self.assertEqual("@bob:test", channel.json_body["name"])
  648. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  649. self.assertEqual("bob@bob.bob", channel.json_body["threepids"][0]["address"])
  650. pushers = self.get_success(
  651. self.store.get_pushers_by({"user_name": "@bob:test"})
  652. )
  653. pushers = list(pushers)
  654. self.assertEqual(len(pushers), 0)
  655. def test_set_password(self):
  656. """
  657. Test setting a new password for another user.
  658. """
  659. # Change password
  660. body = json.dumps({"password": "hahaha"})
  661. channel = self.make_request(
  662. "PUT",
  663. self.url_other_user,
  664. access_token=self.admin_user_tok,
  665. content=body.encode(encoding="utf_8"),
  666. )
  667. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  668. def test_set_displayname(self):
  669. """
  670. Test setting the displayname of another user.
  671. """
  672. # Modify user
  673. body = json.dumps({"displayname": "foobar"})
  674. channel = self.make_request(
  675. "PUT",
  676. self.url_other_user,
  677. access_token=self.admin_user_tok,
  678. content=body.encode(encoding="utf_8"),
  679. )
  680. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  681. self.assertEqual("@user:test", channel.json_body["name"])
  682. self.assertEqual("foobar", channel.json_body["displayname"])
  683. # Get user
  684. channel = self.make_request(
  685. "GET", self.url_other_user, access_token=self.admin_user_tok,
  686. )
  687. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  688. self.assertEqual("@user:test", channel.json_body["name"])
  689. self.assertEqual("foobar", channel.json_body["displayname"])
  690. def test_set_threepid(self):
  691. """
  692. Test setting threepid for an other user.
  693. """
  694. # Delete old and add new threepid to user
  695. body = json.dumps(
  696. {"threepids": [{"medium": "email", "address": "bob3@bob.bob"}]}
  697. )
  698. channel = self.make_request(
  699. "PUT",
  700. self.url_other_user,
  701. access_token=self.admin_user_tok,
  702. content=body.encode(encoding="utf_8"),
  703. )
  704. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  705. self.assertEqual("@user:test", channel.json_body["name"])
  706. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  707. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  708. # Get user
  709. channel = self.make_request(
  710. "GET", self.url_other_user, access_token=self.admin_user_tok,
  711. )
  712. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  713. self.assertEqual("@user:test", channel.json_body["name"])
  714. self.assertEqual("email", channel.json_body["threepids"][0]["medium"])
  715. self.assertEqual("bob3@bob.bob", channel.json_body["threepids"][0]["address"])
  716. def test_deactivate_user(self):
  717. """
  718. Test deactivating another user.
  719. """
  720. # Deactivate user
  721. body = json.dumps({"deactivated": True})
  722. channel = self.make_request(
  723. "PUT",
  724. self.url_other_user,
  725. access_token=self.admin_user_tok,
  726. content=body.encode(encoding="utf_8"),
  727. )
  728. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  729. self.assertEqual("@user:test", channel.json_body["name"])
  730. self.assertEqual(True, channel.json_body["deactivated"])
  731. # the user is deactivated, the threepid will be deleted
  732. # Get user
  733. channel = self.make_request(
  734. "GET", self.url_other_user, access_token=self.admin_user_tok,
  735. )
  736. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  737. self.assertEqual("@user:test", channel.json_body["name"])
  738. self.assertEqual(True, channel.json_body["deactivated"])
  739. def test_reactivate_user(self):
  740. """
  741. Test reactivating another user.
  742. """
  743. # Deactivate the user.
  744. channel = self.make_request(
  745. "PUT",
  746. self.url_other_user,
  747. access_token=self.admin_user_tok,
  748. content=json.dumps({"deactivated": True}).encode(encoding="utf_8"),
  749. )
  750. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  751. self._is_erased("@user:test", False)
  752. d = self.store.mark_user_erased("@user:test")
  753. self.assertIsNone(self.get_success(d))
  754. self._is_erased("@user:test", True)
  755. # Attempt to reactivate the user (without a password).
  756. channel = self.make_request(
  757. "PUT",
  758. self.url_other_user,
  759. access_token=self.admin_user_tok,
  760. content=json.dumps({"deactivated": False}).encode(encoding="utf_8"),
  761. )
  762. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  763. # Reactivate the user.
  764. channel = self.make_request(
  765. "PUT",
  766. self.url_other_user,
  767. access_token=self.admin_user_tok,
  768. content=json.dumps({"deactivated": False, "password": "foo"}).encode(
  769. encoding="utf_8"
  770. ),
  771. )
  772. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  773. # Get user
  774. channel = self.make_request(
  775. "GET", self.url_other_user, access_token=self.admin_user_tok,
  776. )
  777. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  778. self.assertEqual("@user:test", channel.json_body["name"])
  779. self.assertEqual(False, channel.json_body["deactivated"])
  780. self._is_erased("@user:test", False)
  781. def test_set_user_as_admin(self):
  782. """
  783. Test setting the admin flag on a user.
  784. """
  785. # Set a user as an admin
  786. body = json.dumps({"admin": True})
  787. channel = self.make_request(
  788. "PUT",
  789. self.url_other_user,
  790. access_token=self.admin_user_tok,
  791. content=body.encode(encoding="utf_8"),
  792. )
  793. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  794. self.assertEqual("@user:test", channel.json_body["name"])
  795. self.assertEqual(True, channel.json_body["admin"])
  796. # Get user
  797. channel = self.make_request(
  798. "GET", self.url_other_user, access_token=self.admin_user_tok,
  799. )
  800. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  801. self.assertEqual("@user:test", channel.json_body["name"])
  802. self.assertEqual(True, channel.json_body["admin"])
  803. def test_accidental_deactivation_prevention(self):
  804. """
  805. Ensure an account can't accidentally be deactivated by using a str value
  806. for the deactivated body parameter
  807. """
  808. url = "/_synapse/admin/v2/users/@bob:test"
  809. # Create user
  810. body = json.dumps({"password": "abc123"})
  811. channel = self.make_request(
  812. "PUT",
  813. url,
  814. access_token=self.admin_user_tok,
  815. content=body.encode(encoding="utf_8"),
  816. )
  817. self.assertEqual(201, int(channel.result["code"]), msg=channel.result["body"])
  818. self.assertEqual("@bob:test", channel.json_body["name"])
  819. self.assertEqual("bob", channel.json_body["displayname"])
  820. # Get user
  821. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  822. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  823. self.assertEqual("@bob:test", channel.json_body["name"])
  824. self.assertEqual("bob", channel.json_body["displayname"])
  825. self.assertEqual(0, channel.json_body["deactivated"])
  826. # Change password (and use a str for deactivate instead of a bool)
  827. body = json.dumps({"password": "abc123", "deactivated": "false"}) # oops!
  828. channel = self.make_request(
  829. "PUT",
  830. url,
  831. access_token=self.admin_user_tok,
  832. content=body.encode(encoding="utf_8"),
  833. )
  834. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  835. # Check user is not deactivated
  836. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  837. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  838. self.assertEqual("@bob:test", channel.json_body["name"])
  839. self.assertEqual("bob", channel.json_body["displayname"])
  840. # Ensure they're still alive
  841. self.assertEqual(0, channel.json_body["deactivated"])
  842. def _is_erased(self, user_id, expect):
  843. """Assert that the user is erased or not
  844. """
  845. d = self.store.is_user_erased(user_id)
  846. if expect:
  847. self.assertTrue(self.get_success(d))
  848. else:
  849. self.assertFalse(self.get_success(d))
  850. class UserMembershipRestTestCase(unittest.HomeserverTestCase):
  851. servlets = [
  852. synapse.rest.admin.register_servlets,
  853. login.register_servlets,
  854. room.register_servlets,
  855. ]
  856. def prepare(self, reactor, clock, hs):
  857. self.store = hs.get_datastore()
  858. self.admin_user = self.register_user("admin", "pass", admin=True)
  859. self.admin_user_tok = self.login("admin", "pass")
  860. self.other_user = self.register_user("user", "pass")
  861. self.url = "/_synapse/admin/v1/users/%s/joined_rooms" % urllib.parse.quote(
  862. self.other_user
  863. )
  864. def test_no_auth(self):
  865. """
  866. Try to list rooms of an user without authentication.
  867. """
  868. channel = self.make_request("GET", self.url, b"{}")
  869. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  870. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  871. def test_requester_is_no_admin(self):
  872. """
  873. If the user is not a server admin, an error is returned.
  874. """
  875. other_user_token = self.login("user", "pass")
  876. channel = self.make_request("GET", self.url, access_token=other_user_token,)
  877. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  878. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  879. def test_user_does_not_exist(self):
  880. """
  881. Tests that a lookup for a user that does not exist returns a 404
  882. """
  883. url = "/_synapse/admin/v1/users/@unknown_person:test/joined_rooms"
  884. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  885. self.assertEqual(404, channel.code, msg=channel.json_body)
  886. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  887. def test_user_is_not_local(self):
  888. """
  889. Tests that a lookup for a user that is not a local returns a 400
  890. """
  891. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/joined_rooms"
  892. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  893. self.assertEqual(400, channel.code, msg=channel.json_body)
  894. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  895. def test_no_memberships(self):
  896. """
  897. Tests that a normal lookup for rooms is successfully
  898. if user has no memberships
  899. """
  900. # Get rooms
  901. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  902. self.assertEqual(200, channel.code, msg=channel.json_body)
  903. self.assertEqual(0, channel.json_body["total"])
  904. self.assertEqual(0, len(channel.json_body["joined_rooms"]))
  905. def test_get_rooms(self):
  906. """
  907. Tests that a normal lookup for rooms is successfully
  908. """
  909. # Create rooms and join
  910. other_user_tok = self.login("user", "pass")
  911. number_rooms = 5
  912. for n in range(number_rooms):
  913. self.helper.create_room_as(self.other_user, tok=other_user_tok)
  914. # Get rooms
  915. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  916. self.assertEqual(200, channel.code, msg=channel.json_body)
  917. self.assertEqual(number_rooms, channel.json_body["total"])
  918. self.assertEqual(number_rooms, len(channel.json_body["joined_rooms"]))
  919. class PushersRestTestCase(unittest.HomeserverTestCase):
  920. servlets = [
  921. synapse.rest.admin.register_servlets,
  922. login.register_servlets,
  923. ]
  924. def prepare(self, reactor, clock, hs):
  925. self.store = hs.get_datastore()
  926. self.admin_user = self.register_user("admin", "pass", admin=True)
  927. self.admin_user_tok = self.login("admin", "pass")
  928. self.other_user = self.register_user("user", "pass")
  929. self.url = "/_synapse/admin/v1/users/%s/pushers" % urllib.parse.quote(
  930. self.other_user
  931. )
  932. def test_no_auth(self):
  933. """
  934. Try to list pushers of an user without authentication.
  935. """
  936. channel = self.make_request("GET", self.url, b"{}")
  937. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  938. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  939. def test_requester_is_no_admin(self):
  940. """
  941. If the user is not a server admin, an error is returned.
  942. """
  943. other_user_token = self.login("user", "pass")
  944. channel = self.make_request("GET", self.url, access_token=other_user_token,)
  945. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  946. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  947. def test_user_does_not_exist(self):
  948. """
  949. Tests that a lookup for a user that does not exist returns a 404
  950. """
  951. url = "/_synapse/admin/v1/users/@unknown_person:test/pushers"
  952. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  953. self.assertEqual(404, channel.code, msg=channel.json_body)
  954. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  955. def test_user_is_not_local(self):
  956. """
  957. Tests that a lookup for a user that is not a local returns a 400
  958. """
  959. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/pushers"
  960. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  961. self.assertEqual(400, channel.code, msg=channel.json_body)
  962. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  963. def test_get_pushers(self):
  964. """
  965. Tests that a normal lookup for pushers is successfully
  966. """
  967. # Get pushers
  968. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  969. self.assertEqual(200, channel.code, msg=channel.json_body)
  970. self.assertEqual(0, channel.json_body["total"])
  971. # Register the pusher
  972. other_user_token = self.login("user", "pass")
  973. user_tuple = self.get_success(
  974. self.store.get_user_by_access_token(other_user_token)
  975. )
  976. token_id = user_tuple.token_id
  977. self.get_success(
  978. self.hs.get_pusherpool().add_pusher(
  979. user_id=self.other_user,
  980. access_token=token_id,
  981. kind="http",
  982. app_id="m.http",
  983. app_display_name="HTTP Push Notifications",
  984. device_display_name="pushy push",
  985. pushkey="a@example.com",
  986. lang=None,
  987. data={"url": "https://example.com/_matrix/push/v1/notify"},
  988. )
  989. )
  990. # Get pushers
  991. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  992. self.assertEqual(200, channel.code, msg=channel.json_body)
  993. self.assertEqual(1, channel.json_body["total"])
  994. for p in channel.json_body["pushers"]:
  995. self.assertIn("pushkey", p)
  996. self.assertIn("kind", p)
  997. self.assertIn("app_id", p)
  998. self.assertIn("app_display_name", p)
  999. self.assertIn("device_display_name", p)
  1000. self.assertIn("profile_tag", p)
  1001. self.assertIn("lang", p)
  1002. self.assertIn("url", p["data"])
  1003. class UserMediaRestTestCase(unittest.HomeserverTestCase):
  1004. servlets = [
  1005. synapse.rest.admin.register_servlets,
  1006. login.register_servlets,
  1007. ]
  1008. def prepare(self, reactor, clock, hs):
  1009. self.store = hs.get_datastore()
  1010. self.media_repo = hs.get_media_repository_resource()
  1011. self.admin_user = self.register_user("admin", "pass", admin=True)
  1012. self.admin_user_tok = self.login("admin", "pass")
  1013. self.other_user = self.register_user("user", "pass")
  1014. self.url = "/_synapse/admin/v1/users/%s/media" % urllib.parse.quote(
  1015. self.other_user
  1016. )
  1017. def test_no_auth(self):
  1018. """
  1019. Try to list media of an user without authentication.
  1020. """
  1021. channel = self.make_request("GET", self.url, b"{}")
  1022. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1023. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1024. def test_requester_is_no_admin(self):
  1025. """
  1026. If the user is not a server admin, an error is returned.
  1027. """
  1028. other_user_token = self.login("user", "pass")
  1029. channel = self.make_request("GET", self.url, access_token=other_user_token,)
  1030. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1031. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1032. def test_user_does_not_exist(self):
  1033. """
  1034. Tests that a lookup for a user that does not exist returns a 404
  1035. """
  1036. url = "/_synapse/admin/v1/users/@unknown_person:test/media"
  1037. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1038. self.assertEqual(404, channel.code, msg=channel.json_body)
  1039. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  1040. def test_user_is_not_local(self):
  1041. """
  1042. Tests that a lookup for a user that is not a local returns a 400
  1043. """
  1044. url = "/_synapse/admin/v1/users/@unknown_person:unknown_domain/media"
  1045. channel = self.make_request("GET", url, access_token=self.admin_user_tok,)
  1046. self.assertEqual(400, channel.code, msg=channel.json_body)
  1047. self.assertEqual("Can only lookup local users", channel.json_body["error"])
  1048. def test_limit(self):
  1049. """
  1050. Testing list of media with limit
  1051. """
  1052. number_media = 20
  1053. other_user_tok = self.login("user", "pass")
  1054. self._create_media(other_user_tok, number_media)
  1055. channel = self.make_request(
  1056. "GET", self.url + "?limit=5", access_token=self.admin_user_tok,
  1057. )
  1058. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1059. self.assertEqual(channel.json_body["total"], number_media)
  1060. self.assertEqual(len(channel.json_body["media"]), 5)
  1061. self.assertEqual(channel.json_body["next_token"], 5)
  1062. self._check_fields(channel.json_body["media"])
  1063. def test_from(self):
  1064. """
  1065. Testing list of media with a defined starting point (from)
  1066. """
  1067. number_media = 20
  1068. other_user_tok = self.login("user", "pass")
  1069. self._create_media(other_user_tok, number_media)
  1070. channel = self.make_request(
  1071. "GET", self.url + "?from=5", access_token=self.admin_user_tok,
  1072. )
  1073. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1074. self.assertEqual(channel.json_body["total"], number_media)
  1075. self.assertEqual(len(channel.json_body["media"]), 15)
  1076. self.assertNotIn("next_token", channel.json_body)
  1077. self._check_fields(channel.json_body["media"])
  1078. def test_limit_and_from(self):
  1079. """
  1080. Testing list of media with a defined starting point and limit
  1081. """
  1082. number_media = 20
  1083. other_user_tok = self.login("user", "pass")
  1084. self._create_media(other_user_tok, number_media)
  1085. channel = self.make_request(
  1086. "GET", self.url + "?from=5&limit=10", access_token=self.admin_user_tok,
  1087. )
  1088. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1089. self.assertEqual(channel.json_body["total"], number_media)
  1090. self.assertEqual(channel.json_body["next_token"], 15)
  1091. self.assertEqual(len(channel.json_body["media"]), 10)
  1092. self._check_fields(channel.json_body["media"])
  1093. def test_limit_is_negative(self):
  1094. """
  1095. Testing that a negative limit parameter returns a 400
  1096. """
  1097. channel = self.make_request(
  1098. "GET", self.url + "?limit=-5", access_token=self.admin_user_tok,
  1099. )
  1100. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1101. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  1102. def test_from_is_negative(self):
  1103. """
  1104. Testing that a negative from parameter returns a 400
  1105. """
  1106. channel = self.make_request(
  1107. "GET", self.url + "?from=-5", access_token=self.admin_user_tok,
  1108. )
  1109. self.assertEqual(400, int(channel.result["code"]), msg=channel.result["body"])
  1110. self.assertEqual(Codes.INVALID_PARAM, channel.json_body["errcode"])
  1111. def test_next_token(self):
  1112. """
  1113. Testing that `next_token` appears at the right place
  1114. """
  1115. number_media = 20
  1116. other_user_tok = self.login("user", "pass")
  1117. self._create_media(other_user_tok, number_media)
  1118. # `next_token` does not appear
  1119. # Number of results is the number of entries
  1120. channel = self.make_request(
  1121. "GET", self.url + "?limit=20", access_token=self.admin_user_tok,
  1122. )
  1123. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1124. self.assertEqual(channel.json_body["total"], number_media)
  1125. self.assertEqual(len(channel.json_body["media"]), number_media)
  1126. self.assertNotIn("next_token", channel.json_body)
  1127. # `next_token` does not appear
  1128. # Number of max results is larger than the number of entries
  1129. channel = self.make_request(
  1130. "GET", self.url + "?limit=21", access_token=self.admin_user_tok,
  1131. )
  1132. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1133. self.assertEqual(channel.json_body["total"], number_media)
  1134. self.assertEqual(len(channel.json_body["media"]), number_media)
  1135. self.assertNotIn("next_token", channel.json_body)
  1136. # `next_token` does appear
  1137. # Number of max results is smaller than the number of entries
  1138. channel = self.make_request(
  1139. "GET", self.url + "?limit=19", access_token=self.admin_user_tok,
  1140. )
  1141. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1142. self.assertEqual(channel.json_body["total"], number_media)
  1143. self.assertEqual(len(channel.json_body["media"]), 19)
  1144. self.assertEqual(channel.json_body["next_token"], 19)
  1145. # Check
  1146. # Set `from` to value of `next_token` for request remaining entries
  1147. # `next_token` does not appear
  1148. channel = self.make_request(
  1149. "GET", self.url + "?from=19", access_token=self.admin_user_tok,
  1150. )
  1151. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1152. self.assertEqual(channel.json_body["total"], number_media)
  1153. self.assertEqual(len(channel.json_body["media"]), 1)
  1154. self.assertNotIn("next_token", channel.json_body)
  1155. def test_user_has_no_media(self):
  1156. """
  1157. Tests that a normal lookup for media is successfully
  1158. if user has no media created
  1159. """
  1160. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  1161. self.assertEqual(200, channel.code, msg=channel.json_body)
  1162. self.assertEqual(0, channel.json_body["total"])
  1163. self.assertEqual(0, len(channel.json_body["media"]))
  1164. def test_get_media(self):
  1165. """
  1166. Tests that a normal lookup for media is successfully
  1167. """
  1168. number_media = 5
  1169. other_user_tok = self.login("user", "pass")
  1170. self._create_media(other_user_tok, number_media)
  1171. channel = self.make_request("GET", self.url, access_token=self.admin_user_tok,)
  1172. self.assertEqual(200, channel.code, msg=channel.json_body)
  1173. self.assertEqual(number_media, channel.json_body["total"])
  1174. self.assertEqual(number_media, len(channel.json_body["media"]))
  1175. self.assertNotIn("next_token", channel.json_body)
  1176. self._check_fields(channel.json_body["media"])
  1177. def _create_media(self, user_token, number_media):
  1178. """
  1179. Create a number of media for a specific user
  1180. """
  1181. upload_resource = self.media_repo.children[b"upload"]
  1182. for i in range(number_media):
  1183. # file size is 67 Byte
  1184. image_data = unhexlify(
  1185. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  1186. b"0000001f15c4890000000a49444154789c63000100000500010d"
  1187. b"0a2db40000000049454e44ae426082"
  1188. )
  1189. # Upload some media into the room
  1190. self.helper.upload_media(
  1191. upload_resource, image_data, tok=user_token, expect_code=200
  1192. )
  1193. def _check_fields(self, content):
  1194. """Checks that all attributes are present in content
  1195. """
  1196. for m in content:
  1197. self.assertIn("media_id", m)
  1198. self.assertIn("media_type", m)
  1199. self.assertIn("media_length", m)
  1200. self.assertIn("upload_name", m)
  1201. self.assertIn("created_ts", m)
  1202. self.assertIn("last_access_ts", m)
  1203. self.assertIn("quarantined_by", m)
  1204. self.assertIn("safe_from_quarantine", m)
  1205. class UserTokenRestTestCase(unittest.HomeserverTestCase):
  1206. """Test for /_synapse/admin/v1/users/<user>/login
  1207. """
  1208. servlets = [
  1209. synapse.rest.admin.register_servlets,
  1210. login.register_servlets,
  1211. sync.register_servlets,
  1212. room.register_servlets,
  1213. devices.register_servlets,
  1214. logout.register_servlets,
  1215. ]
  1216. def prepare(self, reactor, clock, hs):
  1217. self.store = hs.get_datastore()
  1218. self.admin_user = self.register_user("admin", "pass", admin=True)
  1219. self.admin_user_tok = self.login("admin", "pass")
  1220. self.other_user = self.register_user("user", "pass")
  1221. self.other_user_tok = self.login("user", "pass")
  1222. self.url = "/_synapse/admin/v1/users/%s/login" % urllib.parse.quote(
  1223. self.other_user
  1224. )
  1225. def _get_token(self) -> str:
  1226. channel = self.make_request(
  1227. "POST", self.url, b"{}", access_token=self.admin_user_tok
  1228. )
  1229. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1230. return channel.json_body["access_token"]
  1231. def test_no_auth(self):
  1232. """Try to login as a user without authentication.
  1233. """
  1234. channel = self.make_request("POST", self.url, b"{}")
  1235. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1236. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1237. def test_not_admin(self):
  1238. """Try to login as a user as a non-admin user.
  1239. """
  1240. channel = self.make_request(
  1241. "POST", self.url, b"{}", access_token=self.other_user_tok
  1242. )
  1243. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1244. def test_send_event(self):
  1245. """Test that sending event as a user works.
  1246. """
  1247. # Create a room.
  1248. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  1249. # Login in as the user
  1250. puppet_token = self._get_token()
  1251. # Test that sending works, and generates the event as the right user.
  1252. resp = self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  1253. event_id = resp["event_id"]
  1254. event = self.get_success(self.store.get_event(event_id))
  1255. self.assertEqual(event.sender, self.other_user)
  1256. def test_devices(self):
  1257. """Tests that logging in as a user doesn't create a new device for them.
  1258. """
  1259. # Login in as the user
  1260. self._get_token()
  1261. # Check that we don't see a new device in our devices list
  1262. channel = self.make_request(
  1263. "GET", "devices", b"{}", access_token=self.other_user_tok
  1264. )
  1265. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1266. # We should only see the one device (from the login in `prepare`)
  1267. self.assertEqual(len(channel.json_body["devices"]), 1)
  1268. def test_logout(self):
  1269. """Test that calling `/logout` with the token works.
  1270. """
  1271. # Login in as the user
  1272. puppet_token = self._get_token()
  1273. # Test that we can successfully make a request
  1274. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1275. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1276. # Logout with the puppet token
  1277. channel = self.make_request("POST", "logout", b"{}", access_token=puppet_token)
  1278. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1279. # The puppet token should no longer work
  1280. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1281. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1282. # .. but the real user's tokens should still work
  1283. channel = self.make_request(
  1284. "GET", "devices", b"{}", access_token=self.other_user_tok
  1285. )
  1286. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1287. def test_user_logout_all(self):
  1288. """Tests that the target user calling `/logout/all` does *not* expire
  1289. the token.
  1290. """
  1291. # Login in as the user
  1292. puppet_token = self._get_token()
  1293. # Test that we can successfully make a request
  1294. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1295. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1296. # Logout all with the real user token
  1297. channel = self.make_request(
  1298. "POST", "logout/all", b"{}", access_token=self.other_user_tok
  1299. )
  1300. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1301. # The puppet token should still work
  1302. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1303. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1304. # .. but the real user's tokens shouldn't
  1305. channel = self.make_request(
  1306. "GET", "devices", b"{}", access_token=self.other_user_tok
  1307. )
  1308. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1309. def test_admin_logout_all(self):
  1310. """Tests that the admin user calling `/logout/all` does expire the
  1311. token.
  1312. """
  1313. # Login in as the user
  1314. puppet_token = self._get_token()
  1315. # Test that we can successfully make a request
  1316. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1317. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1318. # Logout all with the admin user token
  1319. channel = self.make_request(
  1320. "POST", "logout/all", b"{}", access_token=self.admin_user_tok
  1321. )
  1322. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1323. # The puppet token should no longer work
  1324. channel = self.make_request("GET", "devices", b"{}", access_token=puppet_token)
  1325. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1326. # .. but the real user's tokens should still work
  1327. channel = self.make_request(
  1328. "GET", "devices", b"{}", access_token=self.other_user_tok
  1329. )
  1330. self.assertEqual(200, int(channel.result["code"]), msg=channel.result["body"])
  1331. @unittest.override_config(
  1332. {
  1333. "public_baseurl": "https://example.org/",
  1334. "user_consent": {
  1335. "version": "1.0",
  1336. "policy_name": "My Cool Privacy Policy",
  1337. "template_dir": "/",
  1338. "require_at_registration": True,
  1339. "block_events_error": "You should accept the policy",
  1340. },
  1341. "form_secret": "123secret",
  1342. }
  1343. )
  1344. def test_consent(self):
  1345. """Test that sending a message is not subject to the privacy policies.
  1346. """
  1347. # Have the admin user accept the terms.
  1348. self.get_success(self.store.user_set_consent_version(self.admin_user, "1.0"))
  1349. # First, cheekily accept the terms and create a room
  1350. self.get_success(self.store.user_set_consent_version(self.other_user, "1.0"))
  1351. room_id = self.helper.create_room_as(self.other_user, tok=self.other_user_tok)
  1352. self.helper.send_event(room_id, "com.example.test", tok=self.other_user_tok)
  1353. # Now unaccept it and check that we can't send an event
  1354. self.get_success(self.store.user_set_consent_version(self.other_user, "0.0"))
  1355. self.helper.send_event(
  1356. room_id, "com.example.test", tok=self.other_user_tok, expect_code=403
  1357. )
  1358. # Login in as the user
  1359. puppet_token = self._get_token()
  1360. # Sending an event on their behalf should work fine
  1361. self.helper.send_event(room_id, "com.example.test", tok=puppet_token)
  1362. @override_config(
  1363. {"limit_usage_by_mau": True, "max_mau_value": 1, "mau_trial_days": 0}
  1364. )
  1365. def test_mau_limit(self):
  1366. # Create a room as the admin user. This will bump the monthly active users to 1.
  1367. room_id = self.helper.create_room_as(self.admin_user, tok=self.admin_user_tok)
  1368. # Trying to join as the other user should fail due to reaching MAU limit.
  1369. self.helper.join(
  1370. room_id, user=self.other_user, tok=self.other_user_tok, expect_code=403
  1371. )
  1372. # Logging in as the other user and joining a room should work, even
  1373. # though the MAU limit would stop the user doing so.
  1374. puppet_token = self._get_token()
  1375. self.helper.join(room_id, user=self.other_user, tok=puppet_token)
  1376. class WhoisRestTestCase(unittest.HomeserverTestCase):
  1377. servlets = [
  1378. synapse.rest.admin.register_servlets,
  1379. login.register_servlets,
  1380. ]
  1381. def prepare(self, reactor, clock, hs):
  1382. self.store = hs.get_datastore()
  1383. self.admin_user = self.register_user("admin", "pass", admin=True)
  1384. self.admin_user_tok = self.login("admin", "pass")
  1385. self.other_user = self.register_user("user", "pass")
  1386. self.url1 = "/_synapse/admin/v1/whois/%s" % urllib.parse.quote(self.other_user)
  1387. self.url2 = "/_matrix/client/r0/admin/whois/%s" % urllib.parse.quote(
  1388. self.other_user
  1389. )
  1390. def test_no_auth(self):
  1391. """
  1392. Try to get information of an user without authentication.
  1393. """
  1394. channel = self.make_request("GET", self.url1, b"{}")
  1395. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1396. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1397. channel = self.make_request("GET", self.url2, b"{}")
  1398. self.assertEqual(401, int(channel.result["code"]), msg=channel.result["body"])
  1399. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  1400. def test_requester_is_not_admin(self):
  1401. """
  1402. If the user is not a server admin, an error is returned.
  1403. """
  1404. self.register_user("user2", "pass")
  1405. other_user2_token = self.login("user2", "pass")
  1406. channel = self.make_request("GET", self.url1, access_token=other_user2_token,)
  1407. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1408. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1409. channel = self.make_request("GET", self.url2, access_token=other_user2_token,)
  1410. self.assertEqual(403, int(channel.result["code"]), msg=channel.result["body"])
  1411. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  1412. def test_user_is_not_local(self):
  1413. """
  1414. Tests that a lookup for a user that is not a local returns a 400
  1415. """
  1416. url1 = "/_synapse/admin/v1/whois/@unknown_person:unknown_domain"
  1417. url2 = "/_matrix/client/r0/admin/whois/@unknown_person:unknown_domain"
  1418. channel = self.make_request("GET", url1, access_token=self.admin_user_tok,)
  1419. self.assertEqual(400, channel.code, msg=channel.json_body)
  1420. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  1421. channel = self.make_request("GET", url2, access_token=self.admin_user_tok,)
  1422. self.assertEqual(400, channel.code, msg=channel.json_body)
  1423. self.assertEqual("Can only whois a local user", channel.json_body["error"])
  1424. def test_get_whois_admin(self):
  1425. """
  1426. The lookup should succeed for an admin.
  1427. """
  1428. channel = self.make_request("GET", self.url1, access_token=self.admin_user_tok,)
  1429. self.assertEqual(200, channel.code, msg=channel.json_body)
  1430. self.assertEqual(self.other_user, channel.json_body["user_id"])
  1431. self.assertIn("devices", channel.json_body)
  1432. channel = self.make_request("GET", self.url2, access_token=self.admin_user_tok,)
  1433. self.assertEqual(200, channel.code, msg=channel.json_body)
  1434. self.assertEqual(self.other_user, channel.json_body["user_id"])
  1435. self.assertIn("devices", channel.json_body)
  1436. def test_get_whois_user(self):
  1437. """
  1438. The lookup should succeed for a normal user looking up their own information.
  1439. """
  1440. other_user_token = self.login("user", "pass")
  1441. channel = self.make_request("GET", self.url1, access_token=other_user_token,)
  1442. self.assertEqual(200, channel.code, msg=channel.json_body)
  1443. self.assertEqual(self.other_user, channel.json_body["user_id"])
  1444. self.assertIn("devices", channel.json_body)
  1445. channel = self.make_request("GET", self.url2, access_token=other_user_token,)
  1446. self.assertEqual(200, channel.code, msg=channel.json_body)
  1447. self.assertEqual(self.other_user, channel.json_body["user_id"])
  1448. self.assertIn("devices", channel.json_body)