test_server_notice.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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 http import HTTPStatus
  15. from typing import List
  16. from twisted.test.proto_helpers import MemoryReactor
  17. import synapse.rest.admin
  18. from synapse.api.errors import Codes
  19. from synapse.rest.client import login, room, sync
  20. from synapse.server import HomeServer
  21. from synapse.storage.roommember import RoomsForUser
  22. from synapse.types import JsonDict
  23. from synapse.util import Clock
  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. HTTPStatus.UNAUTHORIZED,
  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. HTTPStatus.FORBIDDEN,
  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 HTTPStatus.NOT_FOUND"""
  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(HTTPStatus.NOT_FOUND, 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 HTTPStatus.BAD_REQUEST
  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(HTTPStatus.BAD_REQUEST, 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(HTTPStatus.BAD_REQUEST, 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(HTTPStatus.BAD_REQUEST, 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(HTTPStatus.BAD_REQUEST, 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(HTTPStatus.BAD_REQUEST, 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. def test_server_notice_disabled(self) -> None:
  136. """Tests that server returns error if server notice is disabled"""
  137. channel = self.make_request(
  138. "POST",
  139. self.url,
  140. access_token=self.admin_user_tok,
  141. content={
  142. "user_id": self.other_user,
  143. "content": "",
  144. },
  145. )
  146. self.assertEqual(HTTPStatus.BAD_REQUEST, channel.code, msg=channel.json_body)
  147. self.assertEqual(Codes.UNKNOWN, channel.json_body["errcode"])
  148. self.assertEqual(
  149. "Server notices are not enabled on this server", channel.json_body["error"]
  150. )
  151. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  152. def test_send_server_notice(self) -> None:
  153. """
  154. Tests that sending two server notices is successfully,
  155. the server uses the same room and do not send messages twice.
  156. """
  157. # user has no room memberships
  158. self._check_invite_and_join_status(self.other_user, 0, 0)
  159. # send first message
  160. channel = self.make_request(
  161. "POST",
  162. self.url,
  163. access_token=self.admin_user_tok,
  164. content={
  165. "user_id": self.other_user,
  166. "content": {"msgtype": "m.text", "body": "test msg one"},
  167. },
  168. )
  169. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  170. # user has one invite
  171. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  172. room_id = invited_rooms[0].room_id
  173. # user joins the room and is member now
  174. self.helper.join(room=room_id, user=self.other_user, tok=self.other_user_token)
  175. self._check_invite_and_join_status(self.other_user, 0, 1)
  176. # get messages
  177. messages = self._sync_and_get_messages(room_id, self.other_user_token)
  178. self.assertEqual(len(messages), 1)
  179. self.assertEqual(messages[0]["content"]["body"], "test msg one")
  180. self.assertEqual(messages[0]["sender"], "@notices:test")
  181. # invalidate cache of server notices room_ids
  182. self.server_notices_manager.get_or_create_notice_room_for_user.invalidate_all()
  183. # send second message
  184. channel = self.make_request(
  185. "POST",
  186. self.url,
  187. access_token=self.admin_user_tok,
  188. content={
  189. "user_id": self.other_user,
  190. "content": {"msgtype": "m.text", "body": "test msg two"},
  191. },
  192. )
  193. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  194. # user has no new invites or memberships
  195. self._check_invite_and_join_status(self.other_user, 0, 1)
  196. # get messages
  197. messages = self._sync_and_get_messages(room_id, self.other_user_token)
  198. self.assertEqual(len(messages), 2)
  199. self.assertEqual(messages[0]["content"]["body"], "test msg one")
  200. self.assertEqual(messages[0]["sender"], "@notices:test")
  201. self.assertEqual(messages[1]["content"]["body"], "test msg two")
  202. self.assertEqual(messages[1]["sender"], "@notices:test")
  203. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  204. def test_send_server_notice_leave_room(self) -> None:
  205. """
  206. Tests that sending a server notices is successfully.
  207. The user leaves the room and the second message appears
  208. in a new room.
  209. """
  210. # user has no room memberships
  211. self._check_invite_and_join_status(self.other_user, 0, 0)
  212. # send first message
  213. channel = self.make_request(
  214. "POST",
  215. self.url,
  216. access_token=self.admin_user_tok,
  217. content={
  218. "user_id": self.other_user,
  219. "content": {"msgtype": "m.text", "body": "test msg one"},
  220. },
  221. )
  222. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  223. # user has one invite
  224. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  225. first_room_id = invited_rooms[0].room_id
  226. # user joins the room and is member now
  227. self.helper.join(
  228. room=first_room_id, user=self.other_user, tok=self.other_user_token
  229. )
  230. self._check_invite_and_join_status(self.other_user, 0, 1)
  231. # get messages
  232. messages = self._sync_and_get_messages(first_room_id, self.other_user_token)
  233. self.assertEqual(len(messages), 1)
  234. self.assertEqual(messages[0]["content"]["body"], "test msg one")
  235. self.assertEqual(messages[0]["sender"], "@notices:test")
  236. # user leaves the romm
  237. self.helper.leave(
  238. room=first_room_id, user=self.other_user, tok=self.other_user_token
  239. )
  240. # user is not member anymore
  241. self._check_invite_and_join_status(self.other_user, 0, 0)
  242. # invalidate cache of server notices room_ids
  243. # if server tries to send to a cached room_id the user gets the message
  244. # in old room
  245. self.server_notices_manager.get_or_create_notice_room_for_user.invalidate_all()
  246. # send second message
  247. channel = self.make_request(
  248. "POST",
  249. self.url,
  250. access_token=self.admin_user_tok,
  251. content={
  252. "user_id": self.other_user,
  253. "content": {"msgtype": "m.text", "body": "test msg two"},
  254. },
  255. )
  256. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  257. # user has one invite
  258. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  259. second_room_id = invited_rooms[0].room_id
  260. # user joins the room and is member now
  261. self.helper.join(
  262. room=second_room_id, user=self.other_user, tok=self.other_user_token
  263. )
  264. self._check_invite_and_join_status(self.other_user, 0, 1)
  265. # get messages
  266. messages = self._sync_and_get_messages(second_room_id, self.other_user_token)
  267. self.assertEqual(len(messages), 1)
  268. self.assertEqual(messages[0]["content"]["body"], "test msg two")
  269. self.assertEqual(messages[0]["sender"], "@notices:test")
  270. # room has the same id
  271. self.assertNotEqual(first_room_id, second_room_id)
  272. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  273. def test_send_server_notice_delete_room(self) -> None:
  274. """
  275. Tests that the user get server notice in a new room
  276. after the first server notice room was deleted.
  277. """
  278. # user has no room memberships
  279. self._check_invite_and_join_status(self.other_user, 0, 0)
  280. # send first message
  281. channel = self.make_request(
  282. "POST",
  283. self.url,
  284. access_token=self.admin_user_tok,
  285. content={
  286. "user_id": self.other_user,
  287. "content": {"msgtype": "m.text", "body": "test msg one"},
  288. },
  289. )
  290. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  291. # user has one invite
  292. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  293. first_room_id = invited_rooms[0].room_id
  294. # user joins the room and is member now
  295. self.helper.join(
  296. room=first_room_id, user=self.other_user, tok=self.other_user_token
  297. )
  298. self._check_invite_and_join_status(self.other_user, 0, 1)
  299. # get messages
  300. messages = self._sync_and_get_messages(first_room_id, self.other_user_token)
  301. self.assertEqual(len(messages), 1)
  302. self.assertEqual(messages[0]["content"]["body"], "test msg one")
  303. self.assertEqual(messages[0]["sender"], "@notices:test")
  304. # shut down and purge room
  305. self.get_success(
  306. self.room_shutdown_handler.shutdown_room(first_room_id, self.admin_user)
  307. )
  308. self.get_success(self.pagination_handler.purge_room(first_room_id))
  309. # user is not member anymore
  310. self._check_invite_and_join_status(self.other_user, 0, 0)
  311. # It doesn't really matter what API we use here, we just want to assert
  312. # that the room doesn't exist.
  313. summary = self.get_success(self.store.get_room_summary(first_room_id))
  314. # The summary should be empty since the room doesn't exist.
  315. self.assertEqual(summary, {})
  316. # invalidate cache of server notices room_ids
  317. # if server tries to send to a cached room_id it gives an error
  318. self.server_notices_manager.get_or_create_notice_room_for_user.invalidate_all()
  319. # send second message
  320. channel = self.make_request(
  321. "POST",
  322. self.url,
  323. access_token=self.admin_user_tok,
  324. content={
  325. "user_id": self.other_user,
  326. "content": {"msgtype": "m.text", "body": "test msg two"},
  327. },
  328. )
  329. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  330. # user has one invite
  331. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  332. second_room_id = invited_rooms[0].room_id
  333. # user joins the room and is member now
  334. self.helper.join(
  335. room=second_room_id, user=self.other_user, tok=self.other_user_token
  336. )
  337. self._check_invite_and_join_status(self.other_user, 0, 1)
  338. # get message
  339. messages = self._sync_and_get_messages(second_room_id, self.other_user_token)
  340. self.assertEqual(len(messages), 1)
  341. self.assertEqual(messages[0]["content"]["body"], "test msg two")
  342. self.assertEqual(messages[0]["sender"], "@notices:test")
  343. # second room has new ID
  344. self.assertNotEqual(first_room_id, second_room_id)
  345. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  346. def test_update_notice_user_name_when_changed(self) -> None:
  347. """
  348. Tests that existing server notices user name in room is updated after
  349. server notice config changes.
  350. """
  351. server_notice_request_content = {
  352. "user_id": self.other_user,
  353. "content": {"msgtype": "m.text", "body": "test msg one"},
  354. }
  355. self.make_request(
  356. "POST",
  357. self.url,
  358. access_token=self.admin_user_tok,
  359. content=server_notice_request_content,
  360. )
  361. # simulate a change in server config after a server restart.
  362. new_display_name = "new display name"
  363. self.server_notices_manager._config.servernotices.server_notices_mxid_display_name = (
  364. new_display_name
  365. )
  366. self.server_notices_manager.get_or_create_notice_room_for_user.cache.invalidate_all()
  367. self.make_request(
  368. "POST",
  369. self.url,
  370. access_token=self.admin_user_tok,
  371. content=server_notice_request_content,
  372. )
  373. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  374. notice_room_id = invited_rooms[0].room_id
  375. self.helper.join(
  376. room=notice_room_id, user=self.other_user, tok=self.other_user_token
  377. )
  378. notice_user_state_in_room = self.helper.get_state(
  379. notice_room_id,
  380. "m.room.member",
  381. self.other_user_token,
  382. state_key="@notices:test",
  383. )
  384. self.assertEqual(notice_user_state_in_room["displayname"], new_display_name)
  385. @override_config({"server_notices": {"system_mxid_localpart": "notices"}})
  386. def test_update_notice_user_avatar_when_changed(self) -> None:
  387. """
  388. Tests that existing server notices user avatar in room is updated when is
  389. different from the one in homeserver config.
  390. """
  391. server_notice_request_content = {
  392. "user_id": self.other_user,
  393. "content": {"msgtype": "m.text", "body": "test msg one"},
  394. }
  395. self.make_request(
  396. "POST",
  397. self.url,
  398. access_token=self.admin_user_tok,
  399. content=server_notice_request_content,
  400. )
  401. # simulate a change in server config after a server restart.
  402. new_avatar_url = "test/new-url"
  403. self.server_notices_manager._config.servernotices.server_notices_mxid_avatar_url = (
  404. new_avatar_url
  405. )
  406. self.server_notices_manager.get_or_create_notice_room_for_user.cache.invalidate_all()
  407. self.make_request(
  408. "POST",
  409. self.url,
  410. access_token=self.admin_user_tok,
  411. content=server_notice_request_content,
  412. )
  413. invited_rooms = self._check_invite_and_join_status(self.other_user, 1, 0)
  414. notice_room_id = invited_rooms[0].room_id
  415. self.helper.join(
  416. room=notice_room_id, user=self.other_user, tok=self.other_user_token
  417. )
  418. notice_user_state = self.helper.get_state(
  419. notice_room_id,
  420. "m.room.member",
  421. self.other_user_token,
  422. state_key="@notices:test",
  423. )
  424. self.assertEqual(notice_user_state["avatar_url"], new_avatar_url)
  425. def _check_invite_and_join_status(
  426. self, user_id: str, expected_invites: int, expected_memberships: int
  427. ) -> List[RoomsForUser]:
  428. """Check invite and room membership status of a user.
  429. Args
  430. user_id: user to check
  431. expected_invites: number of expected invites of this user
  432. expected_memberships: number of expected room memberships of this user
  433. Returns
  434. room_ids from the rooms that the user is invited
  435. """
  436. invited_rooms = self.get_success(
  437. self.store.get_invited_rooms_for_local_user(user_id)
  438. )
  439. self.assertEqual(expected_invites, len(invited_rooms))
  440. room_ids = self.get_success(self.store.get_rooms_for_user(user_id))
  441. self.assertEqual(expected_memberships, len(room_ids))
  442. return invited_rooms
  443. def _sync_and_get_messages(self, room_id: str, token: str) -> List[JsonDict]:
  444. """
  445. Do a sync and get messages of a room.
  446. Args
  447. room_id: room that contains the messages
  448. token: access token of user
  449. Returns
  450. list of messages contained in the room
  451. """
  452. channel = self.make_request(
  453. "GET", "/_matrix/client/r0/sync", access_token=token
  454. )
  455. self.assertEqual(channel.code, HTTPStatus.OK)
  456. # Get the messages
  457. room = channel.json_body["rooms"]["join"][room_id]
  458. messages = [
  459. x for x in room["timeline"]["events"] if x["type"] == "m.room.message"
  460. ]
  461. return messages