1
0

test_typing.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. # Copyright 2014-2016 OpenMarket Ltd
  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 json
  15. from typing import Dict, List, Set
  16. from unittest.mock import ANY, AsyncMock, Mock, call
  17. from netaddr import IPSet
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from twisted.web.resource import Resource
  20. from synapse.api.constants import EduTypes
  21. from synapse.api.errors import AuthError
  22. from synapse.federation.transport.server import TransportLayerServer
  23. from synapse.handlers.typing import TypingWriterHandler
  24. from synapse.http.federation.matrix_federation_agent import MatrixFederationAgent
  25. from synapse.server import HomeServer
  26. from synapse.types import JsonDict, Requester, StreamKeyType, UserID, create_requester
  27. from synapse.util import Clock
  28. from tests import unittest
  29. from tests.server import ThreadedMemoryReactorClock
  30. from tests.unittest import override_config
  31. # Some local users to test with
  32. U_APPLE = UserID.from_string("@apple:test")
  33. U_BANANA = UserID.from_string("@banana:test")
  34. # Remote user
  35. U_ONION = UserID.from_string("@onion:farm")
  36. # Test room id
  37. ROOM_ID = "a-room"
  38. # Room we're not in
  39. OTHER_ROOM_ID = "another-room"
  40. def _expect_edu_transaction(
  41. edu_type: str, content: JsonDict, origin: str = "test"
  42. ) -> JsonDict:
  43. return {
  44. "origin": origin,
  45. "origin_server_ts": 1000000,
  46. "pdus": [],
  47. "edus": [{"edu_type": edu_type, "content": content}],
  48. }
  49. def _make_edu_transaction_json(edu_type: str, content: JsonDict) -> bytes:
  50. return json.dumps(_expect_edu_transaction(edu_type, content)).encode("utf8")
  51. class TypingNotificationsTestCase(unittest.HomeserverTestCase):
  52. def make_homeserver(
  53. self,
  54. reactor: ThreadedMemoryReactorClock,
  55. clock: Clock,
  56. ) -> HomeServer:
  57. # we mock out the keyring so as to skip the authentication check on the
  58. # federation API call.
  59. mock_keyring = Mock(spec=["verify_json_for_server"])
  60. mock_keyring.verify_json_for_server = AsyncMock(return_value=True)
  61. # we mock out the federation client too
  62. self.mock_federation_client = AsyncMock(spec=["put_json"])
  63. self.mock_federation_client.put_json.return_value = (200, "OK")
  64. self.mock_federation_client.agent = MatrixFederationAgent(
  65. reactor,
  66. tls_client_options_factory=None,
  67. user_agent=b"SynapseInTrialTest/0.0.0",
  68. ip_allowlist=None,
  69. ip_blocklist=IPSet(),
  70. )
  71. # the tests assume that we are starting at unix time 1000
  72. reactor.pump((1000,))
  73. self.mock_hs_notifier = Mock()
  74. hs = self.setup_test_homeserver(
  75. notifier=self.mock_hs_notifier,
  76. federation_http_client=self.mock_federation_client,
  77. keyring=mock_keyring,
  78. replication_streams={},
  79. )
  80. return hs
  81. def create_resource_dict(self) -> Dict[str, Resource]:
  82. d = super().create_resource_dict()
  83. d["/_matrix/federation"] = TransportLayerServer(self.hs)
  84. return d
  85. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  86. self.on_new_event = self.mock_hs_notifier.on_new_event
  87. # hs.get_typing_handler will return a TypingWriterHandler when calling it
  88. # from the main process, and a FollowerTypingHandler on workers.
  89. # We rely on methods only available on the former, so assert we have the
  90. # correct type here. We have to assign self.handler after the assert,
  91. # otherwise mypy will treat it as a FollowerTypingHandler
  92. handler = hs.get_typing_handler()
  93. assert isinstance(handler, TypingWriterHandler)
  94. self.handler = handler
  95. self.event_source = hs.get_event_sources().sources.typing
  96. self.datastore = hs.get_datastores().main
  97. self.datastore.get_device_updates_by_remote = AsyncMock( # type: ignore[method-assign]
  98. return_value=(0, [])
  99. )
  100. self.datastore.get_destination_last_successful_stream_ordering = AsyncMock( # type: ignore[method-assign]
  101. return_value=None
  102. )
  103. self.datastore.get_received_txn_response = AsyncMock( # type: ignore[method-assign]
  104. return_value=None
  105. )
  106. self.room_members: List[UserID] = []
  107. async def check_user_in_room(room_id: str, requester: Requester) -> None:
  108. if requester.user.to_string() not in [
  109. u.to_string() for u in self.room_members
  110. ]:
  111. raise AuthError(401, "User is not in the room")
  112. return None
  113. hs.get_auth().check_user_in_room = Mock( # type: ignore[method-assign]
  114. side_effect=check_user_in_room
  115. )
  116. async def check_host_in_room(room_id: str, server_name: str) -> bool:
  117. return room_id == ROOM_ID
  118. hs.get_event_auth_handler().is_host_in_room = Mock( # type: ignore[method-assign]
  119. side_effect=check_host_in_room
  120. )
  121. async def get_current_hosts_in_room(room_id: str) -> Set[str]:
  122. return {member.domain for member in self.room_members}
  123. hs.get_storage_controllers().state.get_current_hosts_in_room = Mock( # type: ignore[method-assign]
  124. side_effect=get_current_hosts_in_room
  125. )
  126. hs.get_storage_controllers().state.get_current_hosts_in_room_or_partial_state_approximation = Mock( # type: ignore[method-assign]
  127. side_effect=get_current_hosts_in_room
  128. )
  129. async def get_users_in_room(room_id: str) -> Set[str]:
  130. return {str(u) for u in self.room_members}
  131. self.datastore.get_users_in_room = Mock(side_effect=get_users_in_room)
  132. self.datastore.get_user_directory_stream_pos = AsyncMock( # type: ignore[method-assign]
  133. # we deliberately return a non-None stream pos to avoid
  134. # doing an initial_sync
  135. return_value=1
  136. )
  137. self.datastore.get_partial_current_state_deltas = Mock(return_value=(0, None)) # type: ignore[method-assign]
  138. self.datastore.get_to_device_stream_token = Mock( # type: ignore[method-assign]
  139. return_value=0
  140. )
  141. self.datastore.get_new_device_msgs_for_remote = AsyncMock( # type: ignore[method-assign]
  142. return_value=([], 0)
  143. )
  144. self.datastore.delete_device_msgs_for_remote = AsyncMock( # type: ignore[method-assign]
  145. return_value=None
  146. )
  147. self.datastore.set_received_txn_response = AsyncMock( # type: ignore[method-assign]
  148. return_value=None
  149. )
  150. def test_started_typing_local(self) -> None:
  151. self.room_members = [U_APPLE, U_BANANA]
  152. self.assertEqual(self.event_source.get_current_key(), 0)
  153. self.get_success(
  154. self.handler.started_typing(
  155. target_user=U_APPLE,
  156. requester=create_requester(U_APPLE),
  157. room_id=ROOM_ID,
  158. timeout=20000,
  159. )
  160. )
  161. self.on_new_event.assert_has_calls(
  162. [call(StreamKeyType.TYPING, 1, rooms=[ROOM_ID])]
  163. )
  164. self.assertEqual(self.event_source.get_current_key(), 1)
  165. events = self.get_success(
  166. self.event_source.get_new_events(
  167. user=U_APPLE, from_key=0, limit=0, room_ids=[ROOM_ID], is_guest=False
  168. )
  169. )
  170. self.assertEqual(
  171. events[0],
  172. [
  173. {
  174. "type": EduTypes.TYPING,
  175. "room_id": ROOM_ID,
  176. "content": {"user_ids": [U_APPLE.to_string()]},
  177. }
  178. ],
  179. )
  180. # Enable federation sending on the main process.
  181. @override_config({"federation_sender_instances": None})
  182. def test_started_typing_remote_send(self) -> None:
  183. self.room_members = [U_APPLE, U_ONION]
  184. self.get_success(
  185. self.handler.started_typing(
  186. target_user=U_APPLE,
  187. requester=create_requester(U_APPLE),
  188. room_id=ROOM_ID,
  189. timeout=20000,
  190. )
  191. )
  192. self.mock_federation_client.put_json.assert_called_once_with(
  193. "farm",
  194. path="/_matrix/federation/v1/send/1000000",
  195. data=_expect_edu_transaction(
  196. EduTypes.TYPING,
  197. content={
  198. "room_id": ROOM_ID,
  199. "user_id": U_APPLE.to_string(),
  200. "typing": True,
  201. },
  202. ),
  203. json_data_callback=ANY,
  204. long_retries=True,
  205. try_trailing_slash_on_400=True,
  206. backoff_on_all_error_codes=True,
  207. )
  208. def test_started_typing_remote_recv(self) -> None:
  209. self.room_members = [U_APPLE, U_ONION]
  210. self.assertEqual(self.event_source.get_current_key(), 0)
  211. channel = self.make_request(
  212. "PUT",
  213. "/_matrix/federation/v1/send/1000000",
  214. _make_edu_transaction_json(
  215. EduTypes.TYPING,
  216. content={
  217. "room_id": ROOM_ID,
  218. "user_id": U_ONION.to_string(),
  219. "typing": True,
  220. },
  221. ),
  222. federation_auth_origin=b"farm",
  223. )
  224. self.assertEqual(channel.code, 200)
  225. self.on_new_event.assert_has_calls(
  226. [call(StreamKeyType.TYPING, 1, rooms=[ROOM_ID])]
  227. )
  228. self.assertEqual(self.event_source.get_current_key(), 1)
  229. events = self.get_success(
  230. self.event_source.get_new_events(
  231. user=U_APPLE, from_key=0, limit=0, room_ids=[ROOM_ID], is_guest=False
  232. )
  233. )
  234. self.assertEqual(
  235. events[0],
  236. [
  237. {
  238. "type": EduTypes.TYPING,
  239. "room_id": ROOM_ID,
  240. "content": {"user_ids": [U_ONION.to_string()]},
  241. }
  242. ],
  243. )
  244. def test_started_typing_remote_recv_not_in_room(self) -> None:
  245. self.room_members = [U_APPLE, U_ONION]
  246. self.assertEqual(self.event_source.get_current_key(), 0)
  247. channel = self.make_request(
  248. "PUT",
  249. "/_matrix/federation/v1/send/1000000",
  250. _make_edu_transaction_json(
  251. EduTypes.TYPING,
  252. content={
  253. "room_id": OTHER_ROOM_ID,
  254. "user_id": U_ONION.to_string(),
  255. "typing": True,
  256. },
  257. ),
  258. federation_auth_origin=b"farm",
  259. )
  260. self.assertEqual(channel.code, 200)
  261. self.on_new_event.assert_not_called()
  262. self.assertEqual(self.event_source.get_current_key(), 0)
  263. events = self.get_success(
  264. self.event_source.get_new_events(
  265. user=U_APPLE,
  266. from_key=0,
  267. limit=0,
  268. room_ids=[OTHER_ROOM_ID],
  269. is_guest=False,
  270. )
  271. )
  272. self.assertEqual(events[0], [])
  273. self.assertEqual(events[1], 0)
  274. # Enable federation sending on the main process.
  275. @override_config({"federation_sender_instances": None})
  276. def test_stopped_typing(self) -> None:
  277. self.room_members = [U_APPLE, U_BANANA, U_ONION]
  278. # Gut-wrenching
  279. from synapse.handlers.typing import RoomMember
  280. member = RoomMember(ROOM_ID, U_APPLE.to_string())
  281. self.handler._member_typing_until[member] = 1002000
  282. self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()}
  283. self.assertEqual(self.event_source.get_current_key(), 0)
  284. self.get_success(
  285. self.handler.stopped_typing(
  286. target_user=U_APPLE,
  287. requester=create_requester(U_APPLE),
  288. room_id=ROOM_ID,
  289. )
  290. )
  291. self.on_new_event.assert_has_calls(
  292. [call(StreamKeyType.TYPING, 1, rooms=[ROOM_ID])]
  293. )
  294. self.mock_federation_client.put_json.assert_called_once_with(
  295. "farm",
  296. path="/_matrix/federation/v1/send/1000000",
  297. data=_expect_edu_transaction(
  298. EduTypes.TYPING,
  299. content={
  300. "room_id": ROOM_ID,
  301. "user_id": U_APPLE.to_string(),
  302. "typing": False,
  303. },
  304. ),
  305. json_data_callback=ANY,
  306. long_retries=True,
  307. backoff_on_all_error_codes=True,
  308. try_trailing_slash_on_400=True,
  309. )
  310. self.assertEqual(self.event_source.get_current_key(), 1)
  311. events = self.get_success(
  312. self.event_source.get_new_events(
  313. user=U_APPLE, from_key=0, limit=0, room_ids=[ROOM_ID], is_guest=False
  314. )
  315. )
  316. self.assertEqual(
  317. events[0],
  318. [
  319. {
  320. "type": EduTypes.TYPING,
  321. "room_id": ROOM_ID,
  322. "content": {"user_ids": []},
  323. }
  324. ],
  325. )
  326. def test_typing_timeout(self) -> None:
  327. self.room_members = [U_APPLE, U_BANANA]
  328. self.assertEqual(self.event_source.get_current_key(), 0)
  329. self.get_success(
  330. self.handler.started_typing(
  331. target_user=U_APPLE,
  332. requester=create_requester(U_APPLE),
  333. room_id=ROOM_ID,
  334. timeout=10000,
  335. )
  336. )
  337. self.on_new_event.assert_has_calls(
  338. [call(StreamKeyType.TYPING, 1, rooms=[ROOM_ID])]
  339. )
  340. self.on_new_event.reset_mock()
  341. self.assertEqual(self.event_source.get_current_key(), 1)
  342. events = self.get_success(
  343. self.event_source.get_new_events(
  344. user=U_APPLE,
  345. from_key=0,
  346. limit=0,
  347. room_ids=[ROOM_ID],
  348. is_guest=False,
  349. )
  350. )
  351. self.assertEqual(
  352. events[0],
  353. [
  354. {
  355. "type": EduTypes.TYPING,
  356. "room_id": ROOM_ID,
  357. "content": {"user_ids": [U_APPLE.to_string()]},
  358. }
  359. ],
  360. )
  361. self.reactor.pump([16])
  362. self.on_new_event.assert_has_calls(
  363. [call(StreamKeyType.TYPING, 2, rooms=[ROOM_ID])]
  364. )
  365. self.assertEqual(self.event_source.get_current_key(), 2)
  366. events = self.get_success(
  367. self.event_source.get_new_events(
  368. user=U_APPLE,
  369. from_key=1,
  370. limit=0,
  371. room_ids=[ROOM_ID],
  372. is_guest=False,
  373. )
  374. )
  375. self.assertEqual(
  376. events[0],
  377. [
  378. {
  379. "type": EduTypes.TYPING,
  380. "room_id": ROOM_ID,
  381. "content": {"user_ids": []},
  382. }
  383. ],
  384. )
  385. # SYN-230 - see if we can still set after timeout
  386. self.get_success(
  387. self.handler.started_typing(
  388. target_user=U_APPLE,
  389. requester=create_requester(U_APPLE),
  390. room_id=ROOM_ID,
  391. timeout=10000,
  392. )
  393. )
  394. self.on_new_event.assert_has_calls(
  395. [call(StreamKeyType.TYPING, 3, rooms=[ROOM_ID])]
  396. )
  397. self.on_new_event.reset_mock()
  398. self.assertEqual(self.event_source.get_current_key(), 3)
  399. events = self.get_success(
  400. self.event_source.get_new_events(
  401. user=U_APPLE,
  402. from_key=0,
  403. limit=0,
  404. room_ids=[ROOM_ID],
  405. is_guest=False,
  406. )
  407. )
  408. self.assertEqual(
  409. events[0],
  410. [
  411. {
  412. "type": EduTypes.TYPING,
  413. "room_id": ROOM_ID,
  414. "content": {"user_ids": [U_APPLE.to_string()]},
  415. }
  416. ],
  417. )