You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

4772 lines
170 KiB

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