test_typing.py 15 KB

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