1
0

test_server_notice.py 22 KB

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