test_server_notice.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. # Copyright 2021 Dirk Klimpel
  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. from typing import List, Sequence
  15. from twisted.test.proto_helpers import MemoryReactor
  16. import synapse.rest.admin
  17. from synapse.api.errors import Codes
  18. from synapse.rest.client import login, room, sync
  19. from synapse.server import HomeServer
  20. from synapse.storage.roommember import RoomsForUser
  21. from synapse.types import JsonDict
  22. from synapse.util import Clock
  23. from synapse.util.stringutils import random_string
  24. from tests import unittest
  25. from tests.unittest import override_config
  26. class ServerNoticeTestCase(unittest.HomeserverTestCase):
  27. servlets = [
  28. synapse.rest.admin.register_servlets,
  29. login.register_servlets,
  30. room.register_servlets,
  31. sync.register_servlets,
  32. ]
  33. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  34. self.store = hs.get_datastores().main
  35. self.room_shutdown_handler = hs.get_room_shutdown_handler()
  36. self.pagination_handler = hs.get_pagination_handler()
  37. self.server_notices_manager = self.hs.get_server_notices_manager()
  38. # Create user
  39. self.admin_user = self.register_user("admin", "pass", admin=True)
  40. self.admin_user_tok = self.login("admin", "pass")
  41. self.other_user = self.register_user("user", "pass")
  42. self.other_user_token = self.login("user", "pass")
  43. self.url = "/_synapse/admin/v1/send_server_notice"
  44. def test_no_auth(self) -> None:
  45. """Try to send a server notice without authentication."""
  46. channel = self.make_request("POST", self.url)
  47. self.assertEqual(
  48. 401,
  49. channel.code,
  50. msg=channel.json_body,
  51. )
  52. self.assertEqual(Codes.MISSING_TOKEN, channel.json_body["errcode"])
  53. def test_requester_is_no_admin(self) -> None:
  54. """If the user is not a server admin, an error is returned."""
  55. channel = self.make_request(
  56. "POST",
  57. self.url,
  58. access_token=self.other_user_token,
  59. )
  60. self.assertEqual(
  61. 403,
  62. channel.code,
  63. msg=channel.json_body,
  64. )
  65. self.assertEqual(Codes.FORBIDDEN, channel.json_body["errcode"])
  66. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  67. def test_user_does_not_exist(self) -> None:
  68. """Tests that a lookup for a user that does not exist returns a 404"""
  69. channel = self.make_request(
  70. "POST",
  71. self.url,
  72. access_token=self.admin_user_tok,
  73. content={"user_id": "@unknown_person:test", "content": ""},
  74. )
  75. self.assertEqual(404, channel.code, msg=channel.json_body)
  76. self.assertEqual(Codes.NOT_FOUND, channel.json_body["errcode"])
  77. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  78. def test_user_is_not_local(self) -> None:
  79. """
  80. Tests that a lookup for a user that is not a local returns a 400
  81. """
  82. channel = self.make_request(
  83. "POST",
  84. self.url,
  85. access_token=self.admin_user_tok,
  86. content={
  87. "user_id": "@unknown_person:unknown_domain",
  88. "content": "",
  89. },
  90. )
  91. self.assertEqual(400, channel.code, msg=channel.json_body)
  92. self.assertEqual(
  93. "Server notices can only be sent to local users", channel.json_body["error"]
  94. )
  95. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  96. def test_invalid_parameter(self) -> None:
  97. """If parameters are invalid, an error is returned."""
  98. # no content, no user
  99. channel = self.make_request(
  100. "POST",
  101. self.url,
  102. access_token=self.admin_user_tok,
  103. )
  104. self.assertEqual(400, channel.code, msg=channel.json_body)
  105. self.assertEqual(Codes.NOT_JSON, channel.json_body["errcode"])
  106. # no content
  107. channel = self.make_request(
  108. "POST",
  109. self.url,
  110. access_token=self.admin_user_tok,
  111. content={"user_id": self.other_user},
  112. )
  113. self.assertEqual(400, channel.code, msg=channel.json_body)
  114. self.assertEqual(Codes.MISSING_PARAM, channel.json_body["errcode"])
  115. # no body
  116. channel = self.make_request(
  117. "POST",
  118. self.url,
  119. access_token=self.admin_user_tok,
  120. content={"user_id": self.other_user, "content": ""},
  121. )
  122. self.assertEqual(400, channel.code, msg=channel.json_body)
  123. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  124. self.assertEqual("'body' not in content", channel.json_body["error"])
  125. # no msgtype
  126. channel = self.make_request(
  127. "POST",
  128. self.url,
  129. access_token=self.admin_user_tok,
  130. content={"user_id": self.other_user, "content": {"body": ""}},
  131. )
  132. self.assertEqual(400, channel.code, msg=channel.json_body)
  133. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  134. self.assertEqual("'msgtype' not in content", channel.json_body["error"])
  135. @override_config(
  136. {
  137. "server_notices": {
  138. "system_mxid_localpart": "notices",
  139. "system_mxid_avatar_url": "somthingwrong",
  140. },
  141. "max_avatar_size": "10M",
  142. }
  143. )
  144. def test_invalid_avatar_url(self) -> None:
  145. """If avatar url in homeserver.yaml is invalid and
  146. "check avatar size and mime type" is set, an error is returned.
  147. TODO: Should be checked when reading the configuration."""
  148. channel = self.make_request(
  149. "POST",
  150. self.url,
  151. access_token=self.admin_user_tok,
  152. content={
  153. "user_id": self.other_user,
  154. "content": {"msgtype": "m.text", "body": "test msg"},
  155. },
  156. )
  157. self.assertEqual(500, channel.code, msg=channel.json_body)
  158. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  159. @override_config(
  160. {
  161. "server_notices": {
  162. "system_mxid_localpart": "notices",
  163. "system_mxid_display_name": "test display name",
  164. "system_mxid_avatar_url": None,
  165. },
  166. "max_avatar_size": "10M",
  167. }
  168. )
  169. def test_displayname_is_set_avatar_is_none(self) -> None:
  170. """
  171. Tests that sending a server notices is successfully,
  172. if a display_name is set, avatar_url is `None` and
  173. "check avatar size and mime type" is set.
  174. """
  175. channel = self.make_request(
  176. "POST",
  177. self.url,
  178. access_token=self.admin_user_tok,
  179. content={
  180. "user_id": self.other_user,
  181. "content": {"msgtype": "m.text", "body": "test msg"},
  182. },
  183. )
  184. self.assertEqual(200, channel.code, msg=channel.json_body)
  185. # user has one invite
  186. self._check_invite_and_join_status(self.other_user, 1, 0)
  187. def test_server_notice_disabled(self) -> None:
  188. """Tests that server returns error if server notice is disabled"""
  189. channel = self.make_request(
  190. "POST",
  191. self.url,
  192. access_token=self.admin_user_tok,
  193. content={
  194. "user_id": self.other_user,
  195. "content": "",
  196. },
  197. )
  198. self.assertEqual(400, channel.code, msg=channel.json_body)
  199. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  200. self.assertEqual(
  201. "Server notices are not enabled on this server", channel.json_body["error"]
  202. )
  203. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  204. def test_send_server_notice(self) -> None:
  205. """
  206. Tests that sending two server notices is successfully,
  207. the server uses the same room and do not send messages twice.
  208. """
  209. # user has no room memberships
  210. self._check_invite_and_join_status(self.other_user, 0, 0)
  211. # send first message
  212. channel = self.make_request(
  213. "POST",
  214. self.url,
  215. access_token=self.admin_user_tok,
  216. content={
  217. "user_id": self.other_user,
  218. "content": {"msgtype": "m.text", "body": "test msg one"},
  219. },
  220. )
  221. self.assertEqual(200, channel.code, msg=channel.json_body)
  222. # user has one invite
  223. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  224. room_id = invited_rooms[0].room_id
  225. # user joins the room and is member now
  226. self.helper.join(room=room_id, user=self.other_user, tok=self.other_user_token)
  227. self._check_invite_and_join_status(self.other_user, 0, 1)
  228. # get messages
  229. messages = self._sync_and_get_messages(room_id, self.other_user_token)
  230. self.assertEqual(len(messages), 1)
  231. self.assertEqual(messages[0]["content"]["body"], "test msg one")
  232. self.assertEqual(messages[0]["sender"], "@notices:test")
  233. # invalidate cache of server notices room_ids
  234. self.server_notices_manager.get_or_create_notice_room_for_user.invalidate_all()
  235. # send second message
  236. channel = self.make_request(
  237. "POST",
  238. self.url,
  239. access_token=self.admin_user_tok,
  240. content={
  241. "user_id": self.other_user,
  242. "content": {"msgtype": "m.text", "body": "test msg two"},
  243. },
  244. )
  245. self.assertEqual(200, channel.code, msg=channel.json_body)
  246. # user has no new invites or memberships
  247. self._check_invite_and_join_status(self.other_user, 0, 1)
  248. # get messages
  249. messages = self._sync_and_get_messages(room_id, self.other_user_token)
  250. self.assertEqual(len(messages), 2)
  251. self.assertEqual(messages[0]["content"]["body"], "test msg one")
  252. self.assertEqual(messages[0]["sender"], "@notices:test")
  253. self.assertEqual(messages[1]["content"]["body"], "test msg two")
  254. self.assertEqual(messages[1]["sender"], "@notices:test")
  255. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  256. def test_send_server_notice_leave_room(self) -> None:
  257. """
  258. Tests that sending a server notices is successfully.
  259. The user leaves the room and the second message appears
  260. in a new room.
  261. """
  262. # user has no room memberships
  263. self._check_invite_and_join_status(self.other_user, 0, 0)
  264. # send first message
  265. channel = self.make_request(
  266. "POST",
  267. self.url,
  268. access_token=self.admin_user_tok,
  269. content={
  270. "user_id": self.other_user,
  271. "content": {"msgtype": "m.text", "body": "test msg one"},
  272. },
  273. )
  274. self.assertEqual(200, channel.code, msg=channel.json_body)
  275. # user has one invite
  276. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  277. first_room_id = invited_rooms[0].room_id
  278. # user joins the room and is member now
  279. self.helper.join(
  280. room=first_room_id, user=self.other_user, tok=self.other_user_token
  281. )
  282. self._check_invite_and_join_status(self.other_user, 0, 1)
  283. # get messages
  284. messages = self._sync_and_get_messages(first_room_id, self.other_user_token)
  285. self.assertEqual(len(messages), 1)
  286. self.assertEqual(messages[0]["content"]["body"], "test msg one")
  287. self.assertEqual(messages[0]["sender"], "@notices:test")
  288. # user leaves the romm
  289. self.helper.leave(
  290. room=first_room_id, user=self.other_user, tok=self.other_user_token
  291. )
  292. # user is not member anymore
  293. self._check_invite_and_join_status(self.other_user, 0, 0)
  294. # invalidate cache of server notices room_ids
  295. # if server tries to send to a cached room_id the user gets the message
  296. # in old room
  297. self.server_notices_manager.get_or_create_notice_room_for_user.invalidate_all()
  298. # send second message
  299. channel = self.make_request(
  300. "POST",
  301. self.url,
  302. access_token=self.admin_user_tok,
  303. content={
  304. "user_id": self.other_user,
  305. "content": {"msgtype": "m.text", "body": "test msg two"},
  306. },
  307. )
  308. self.assertEqual(200, channel.code, msg=channel.json_body)
  309. # user has one invite
  310. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  311. second_room_id = invited_rooms[0].room_id
  312. # user joins the room and is member now
  313. self.helper.join(
  314. room=second_room_id, user=self.other_user, tok=self.other_user_token
  315. )
  316. self._check_invite_and_join_status(self.other_user, 0, 1)
  317. # get messages
  318. messages = self._sync_and_get_messages(second_room_id, self.other_user_token)
  319. self.assertEqual(len(messages), 1)
  320. self.assertEqual(messages[0]["content"]["body"], "test msg two")
  321. self.assertEqual(messages[0]["sender"], "@notices:test")
  322. # room has the same id
  323. self.assertNotEqual(first_room_id, second_room_id)
  324. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  325. def test_send_server_notice_delete_room(self) -> None:
  326. """
  327. Tests that the user get server notice in a new room
  328. after the first server notice room was deleted.
  329. """
  330. # user has no room memberships
  331. self._check_invite_and_join_status(self.other_user, 0, 0)
  332. # send first message
  333. channel = self.make_request(
  334. "POST",
  335. self.url,
  336. access_token=self.admin_user_tok,
  337. content={
  338. "user_id": self.other_user,
  339. "content": {"msgtype": "m.text", "body": "test msg one"},
  340. },
  341. )
  342. self.assertEqual(200, channel.code, msg=channel.json_body)
  343. # user has one invite
  344. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  345. first_room_id = invited_rooms[0].room_id
  346. # user joins the room and is member now
  347. self.helper.join(
  348. room=first_room_id, user=self.other_user, tok=self.other_user_token
  349. )
  350. self._check_invite_and_join_status(self.other_user, 0, 1)
  351. # get messages
  352. messages = self._sync_and_get_messages(first_room_id, self.other_user_token)
  353. self.assertEqual(len(messages), 1)
  354. self.assertEqual(messages[0]["content"]["body"], "test msg one")
  355. self.assertEqual(messages[0]["sender"], "@notices:test")
  356. random_string(16)
  357. # shut down and purge room
  358. self.get_success(
  359. self.room_shutdown_handler.shutdown_room(
  360. first_room_id,
  361. {
  362. "requester_user_id": self.admin_user,
  363. "new_room_user_id": None,
  364. "new_room_name": None,
  365. "message": None,
  366. "block": False,
  367. "purge": True,
  368. "force_purge": False,
  369. },
  370. )
  371. )
  372. self.get_success(self.pagination_handler.purge_room(first_room_id, force=False))
  373. # user is not member anymore
  374. self._check_invite_and_join_status(self.other_user, 0, 0)
  375. # It doesn't really matter what API we use here, we just want to assert
  376. # that the room doesn't exist.
  377. summary = self.get_success(self.store.get_room_summary(first_room_id))
  378. # The summary should be empty since the room doesn't exist.
  379. self.assertEqual(summary, {})
  380. # invalidate cache of server notices room_ids
  381. # if server tries to send to a cached room_id it gives an error
  382. self.server_notices_manager.get_or_create_notice_room_for_user.invalidate_all()
  383. # send second message
  384. channel = self.make_request(
  385. "POST",
  386. self.url,
  387. access_token=self.admin_user_tok,
  388. content={
  389. "user_id": self.other_user,
  390. "content": {"msgtype": "m.text", "body": "test msg two"},
  391. },
  392. )
  393. self.assertEqual(200, channel.code, msg=channel.json_body)
  394. # user has one invite
  395. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  396. second_room_id = invited_rooms[0].room_id
  397. # user joins the room and is member now
  398. self.helper.join(
  399. room=second_room_id, user=self.other_user, tok=self.other_user_token
  400. )
  401. self._check_invite_and_join_status(self.other_user, 0, 1)
  402. # get message
  403. messages = self._sync_and_get_messages(second_room_id, self.other_user_token)
  404. self.assertEqual(len(messages), 1)
  405. self.assertEqual(messages[0]["content"]["body"], "test msg two")
  406. self.assertEqual(messages[0]["sender"], "@notices:test")
  407. # second room has new ID
  408. self.assertNotEqual(first_room_id, second_room_id)
  409. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  410. def test_update_notice_user_name_when_changed(self) -> None:
  411. """
  412. Tests that existing server notices user name in room is updated after
  413. server notice config changes.
  414. """
  415. server_notice_request_content = {
  416. "user_id": self.other_user,
  417. "content": {"msgtype": "m.text", "body": "test msg one"},
  418. }
  419. self.make_request(
  420. "POST",
  421. self.url,
  422. access_token=self.admin_user_tok,
  423. content=server_notice_request_content,
  424. )
  425. # simulate a change in server config after a server restart.
  426. new_display_name = "new display name"
  427. self.server_notices_manager._config.servernotices.server_notices_mxid_display_name = (
  428. new_display_name
  429. )
  430. self.server_notices_manager.get_or_create_notice_room_for_user.cache.invalidate_all()
  431. self.make_request(
  432. "POST",
  433. self.url,
  434. access_token=self.admin_user_tok,
  435. content=server_notice_request_content,
  436. )
  437. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  438. notice_room_id = invited_rooms[0].room_id
  439. self.helper.join(
  440. room=notice_room_id, user=self.other_user, tok=self.other_user_token
  441. )
  442. notice_user_state_in_room = self.helper.get_state(
  443. notice_room_id,
  444. "m.room.member",
  445. self.other_user_token,
  446. state_key="@notices:test",
  447. )
  448. self.assertEqual(notice_user_state_in_room["displayname"], new_display_name)
  449. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  450. def test_update_notice_user_avatar_when_changed(self) -> None:
  451. """
  452. Tests that existing server notices user avatar in room is updated when is
  453. different from the one in homeserver config.
  454. """
  455. server_notice_request_content = {
  456. "user_id": self.other_user,
  457. "content": {"msgtype": "m.text", "body": "test msg one"},
  458. }
  459. self.make_request(
  460. "POST",
  461. self.url,
  462. access_token=self.admin_user_tok,
  463. content=server_notice_request_content,
  464. )
  465. # simulate a change in server config after a server restart.
  466. new_avatar_url = "test/new-url"
  467. self.server_notices_manager._config.servernotices.server_notices_mxid_avatar_url = (
  468. new_avatar_url
  469. )
  470. self.server_notices_manager.get_or_create_notice_room_for_user.cache.invalidate_all()
  471. self.make_request(
  472. "POST",
  473. self.url,
  474. access_token=self.admin_user_tok,
  475. content=server_notice_request_content,
  476. )
  477. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  478. notice_room_id = invited_rooms[0].room_id
  479. self.helper.join(
  480. room=notice_room_id, user=self.other_user, tok=self.other_user_token
  481. )
  482. notice_user_state = self.helper.get_state(
  483. notice_room_id,
  484. "m.room.member",
  485. self.other_user_token,
  486. state_key="@notices:test",
  487. )
  488. self.assertEqual(notice_user_state["avatar_url"], new_avatar_url)
  489. def _check_invite_and_join_status(
  490. self, user_id: str, expected_invites: int, expected_memberships: int
  491. ) -> Sequence[RoomsForUser]:
  492. """Check invite and room membership status of a user.
  493. Args
  494. user_id: user to check
  495. expected_invites: number of expected invites of this user
  496. expected_memberships: number of expected room memberships of this user
  497. Returns
  498. room_ids from the rooms that the user is invited
  499. """
  500. invited_rooms = self.get_success(
  501. self.store.get_invited_rooms_for_local_user(user_id)
  502. )
  503. self.assertEqual(expected_invites, len(invited_rooms))
  504. room_ids = self.get_success(self.store.get_rooms_for_user(user_id))
  505. self.assertEqual(expected_memberships, len(room_ids))
  506. return invited_rooms
  507. def _sync_and_get_messages(self, room_id: str, token: str) -> List[JsonDict]:
  508. """
  509. Do a sync and get messages of a room.
  510. Args
  511. room_id: room that contains the messages
  512. token: access token of user
  513. Returns
  514. list of messages contained in the room
  515. """
  516. channel = self.make_request(
  517. "GET", "/_matrix/client/r0/sync", access_token=token
  518. )
  519. self.assertEqual(channel.code, 200)
  520. # Get the messages
  521. room = channel.json_body["rooms"]["join"][room_id]
  522. messages = [
  523. x for x in room["timeline"]["events"] if x["type"] == "m.room.message"
  524. ]
  525. return messages