test_federation_sender.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from typing import Optional
  16. from mock import Mock
  17. from signedjson import key, sign
  18. from signedjson.types import BaseKey, SigningKey
  19. from twisted.internet import defer
  20. from synapse.api.constants import RoomEncryptionAlgorithms
  21. from synapse.rest import admin
  22. from synapse.rest.client.v1 import login
  23. from synapse.types import JsonDict, ReadReceipt
  24. from tests.test_utils import make_awaitable
  25. from tests.unittest import HomeserverTestCase, override_config
  26. class FederationSenderReceiptsTestCases(HomeserverTestCase):
  27. def make_homeserver(self, reactor, clock):
  28. mock_state_handler = Mock(spec=["get_current_hosts_in_room"])
  29. # Ensure a new Awaitable is created for each call.
  30. mock_state_handler.get_current_hosts_in_room.return_value = make_awaitable(
  31. ["test", "host2"]
  32. )
  33. return self.setup_test_homeserver(
  34. state_handler=mock_state_handler,
  35. federation_transport_client=Mock(spec=["send_transaction"]),
  36. )
  37. @override_config({"send_federation": True})
  38. def test_send_receipts(self):
  39. mock_send_transaction = (
  40. self.hs.get_federation_transport_client().send_transaction
  41. )
  42. mock_send_transaction.return_value = make_awaitable({})
  43. sender = self.hs.get_federation_sender()
  44. receipt = ReadReceipt(
  45. "room_id", "m.read", "user_id", ["event_id"], {"ts": 1234}
  46. )
  47. self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt)))
  48. self.pump()
  49. # expect a call to send_transaction
  50. mock_send_transaction.assert_called_once()
  51. json_cb = mock_send_transaction.call_args[0][1]
  52. data = json_cb()
  53. self.assertEqual(
  54. data["edus"],
  55. [
  56. {
  57. "edu_type": "m.receipt",
  58. "content": {
  59. "room_id": {
  60. "m.read": {
  61. "user_id": {
  62. "event_ids": ["event_id"],
  63. "data": {"ts": 1234},
  64. }
  65. }
  66. }
  67. },
  68. }
  69. ],
  70. )
  71. @override_config({"send_federation": True})
  72. def test_send_receipts_with_backoff(self):
  73. """Send two receipts in quick succession; the second should be flushed, but
  74. only after 20ms"""
  75. mock_send_transaction = (
  76. self.hs.get_federation_transport_client().send_transaction
  77. )
  78. mock_send_transaction.return_value = make_awaitable({})
  79. sender = self.hs.get_federation_sender()
  80. receipt = ReadReceipt(
  81. "room_id", "m.read", "user_id", ["event_id"], {"ts": 1234}
  82. )
  83. self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt)))
  84. self.pump()
  85. # expect a call to send_transaction
  86. mock_send_transaction.assert_called_once()
  87. json_cb = mock_send_transaction.call_args[0][1]
  88. data = json_cb()
  89. self.assertEqual(
  90. data["edus"],
  91. [
  92. {
  93. "edu_type": "m.receipt",
  94. "content": {
  95. "room_id": {
  96. "m.read": {
  97. "user_id": {
  98. "event_ids": ["event_id"],
  99. "data": {"ts": 1234},
  100. }
  101. }
  102. }
  103. },
  104. }
  105. ],
  106. )
  107. mock_send_transaction.reset_mock()
  108. # send the second RR
  109. receipt = ReadReceipt(
  110. "room_id", "m.read", "user_id", ["other_id"], {"ts": 1234}
  111. )
  112. self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt)))
  113. self.pump()
  114. mock_send_transaction.assert_not_called()
  115. self.reactor.advance(19)
  116. mock_send_transaction.assert_not_called()
  117. self.reactor.advance(10)
  118. mock_send_transaction.assert_called_once()
  119. json_cb = mock_send_transaction.call_args[0][1]
  120. data = json_cb()
  121. self.assertEqual(
  122. data["edus"],
  123. [
  124. {
  125. "edu_type": "m.receipt",
  126. "content": {
  127. "room_id": {
  128. "m.read": {
  129. "user_id": {
  130. "event_ids": ["other_id"],
  131. "data": {"ts": 1234},
  132. }
  133. }
  134. }
  135. },
  136. }
  137. ],
  138. )
  139. class FederationSenderDevicesTestCases(HomeserverTestCase):
  140. servlets = [
  141. admin.register_servlets,
  142. login.register_servlets,
  143. ]
  144. def make_homeserver(self, reactor, clock):
  145. return self.setup_test_homeserver(
  146. federation_transport_client=Mock(spec=["send_transaction"]),
  147. )
  148. def default_config(self):
  149. c = super().default_config()
  150. c["send_federation"] = True
  151. return c
  152. def prepare(self, reactor, clock, hs):
  153. # stub out get_users_who_share_room_with_user so that it claims that
  154. # `@user2:host2` is in the room
  155. def get_users_who_share_room_with_user(user_id):
  156. return defer.succeed({"@user2:host2"})
  157. hs.get_datastore().get_users_who_share_room_with_user = (
  158. get_users_who_share_room_with_user
  159. )
  160. # whenever send_transaction is called, record the edu data
  161. self.edus = []
  162. self.hs.get_federation_transport_client().send_transaction.side_effect = (
  163. self.record_transaction
  164. )
  165. def record_transaction(self, txn, json_cb):
  166. data = json_cb()
  167. self.edus.extend(data["edus"])
  168. return defer.succeed({})
  169. def test_send_device_updates(self):
  170. """Basic case: each device update should result in an EDU"""
  171. # create a device
  172. u1 = self.register_user("user", "pass")
  173. self.login(u1, "pass", device_id="D1")
  174. # expect one edu
  175. self.assertEqual(len(self.edus), 1)
  176. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  177. # a second call should produce no new device EDUs
  178. self.hs.get_federation_sender().send_device_messages("host2")
  179. self.pump()
  180. self.assertEqual(self.edus, [])
  181. # a second device
  182. self.login("user", "pass", device_id="D2")
  183. self.assertEqual(len(self.edus), 1)
  184. self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  185. def test_upload_signatures(self):
  186. """Uploading signatures on some devices should produce updates for that user"""
  187. e2e_handler = self.hs.get_e2e_keys_handler()
  188. # register two devices
  189. u1 = self.register_user("user", "pass")
  190. self.login(u1, "pass", device_id="D1")
  191. self.login(u1, "pass", device_id="D2")
  192. # expect two edus
  193. self.assertEqual(len(self.edus), 2)
  194. stream_id = None
  195. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", stream_id)
  196. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  197. # upload signing keys for each device
  198. device1_signing_key = self.generate_and_upload_device_signing_key(u1, "D1")
  199. device2_signing_key = self.generate_and_upload_device_signing_key(u1, "D2")
  200. # expect two more edus
  201. self.assertEqual(len(self.edus), 2)
  202. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", stream_id)
  203. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  204. # upload master key and self-signing key
  205. master_signing_key = generate_self_id_key()
  206. master_key = {
  207. "user_id": u1,
  208. "usage": ["master"],
  209. "keys": {key_id(master_signing_key): encode_pubkey(master_signing_key)},
  210. }
  211. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  212. selfsigning_signing_key = generate_self_id_key()
  213. selfsigning_key = {
  214. "user_id": u1,
  215. "usage": ["self_signing"],
  216. "keys": {
  217. key_id(selfsigning_signing_key): encode_pubkey(selfsigning_signing_key)
  218. },
  219. }
  220. sign.sign_json(selfsigning_key, u1, master_signing_key)
  221. cross_signing_keys = {
  222. "master_key": master_key,
  223. "self_signing_key": selfsigning_key,
  224. }
  225. self.get_success(
  226. e2e_handler.upload_signing_keys_for_user(u1, cross_signing_keys)
  227. )
  228. # expect signing key update edu
  229. self.assertEqual(len(self.edus), 1)
  230. self.assertEqual(self.edus.pop(0)["edu_type"], "org.matrix.signing_key_update")
  231. # sign the devices
  232. d1_json = build_device_dict(u1, "D1", device1_signing_key)
  233. sign.sign_json(d1_json, u1, selfsigning_signing_key)
  234. d2_json = build_device_dict(u1, "D2", device2_signing_key)
  235. sign.sign_json(d2_json, u1, selfsigning_signing_key)
  236. ret = self.get_success(
  237. e2e_handler.upload_signatures_for_device_keys(
  238. u1, {u1: {"D1": d1_json, "D2": d2_json}},
  239. )
  240. )
  241. self.assertEqual(ret["failures"], {})
  242. # expect two edus, in one or two transactions. We don't know what order the
  243. # devices will be updated.
  244. self.assertEqual(len(self.edus), 2)
  245. stream_id = None # FIXME: there is a discontinuity in the stream IDs: see #7142
  246. for edu in self.edus:
  247. self.assertEqual(edu["edu_type"], "m.device_list_update")
  248. c = edu["content"]
  249. if stream_id is not None:
  250. self.assertEqual(c["prev_id"], [stream_id])
  251. self.assertGreaterEqual(c["stream_id"], stream_id)
  252. stream_id = c["stream_id"]
  253. devices = {edu["content"]["device_id"] for edu in self.edus}
  254. self.assertEqual({"D1", "D2"}, devices)
  255. def test_delete_devices(self):
  256. """If devices are deleted, that should result in EDUs too"""
  257. # create devices
  258. u1 = self.register_user("user", "pass")
  259. self.login("user", "pass", device_id="D1")
  260. self.login("user", "pass", device_id="D2")
  261. self.login("user", "pass", device_id="D3")
  262. # expect three edus
  263. self.assertEqual(len(self.edus), 3)
  264. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  265. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  266. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D3", stream_id)
  267. # delete them again
  268. self.get_success(
  269. self.hs.get_device_handler().delete_devices(u1, ["D1", "D2", "D3"])
  270. )
  271. # expect three edus, in an unknown order
  272. self.assertEqual(len(self.edus), 3)
  273. for edu in self.edus:
  274. self.assertEqual(edu["edu_type"], "m.device_list_update")
  275. c = edu["content"]
  276. self.assertGreaterEqual(
  277. c.items(),
  278. {"user_id": u1, "prev_id": [stream_id], "deleted": True}.items(),
  279. )
  280. self.assertGreaterEqual(c["stream_id"], stream_id)
  281. stream_id = c["stream_id"]
  282. devices = {edu["content"]["device_id"] for edu in self.edus}
  283. self.assertEqual({"D1", "D2", "D3"}, devices)
  284. def test_unreachable_server(self):
  285. """If the destination server is unreachable, all the updates should get sent on
  286. recovery
  287. """
  288. mock_send_txn = self.hs.get_federation_transport_client().send_transaction
  289. mock_send_txn.side_effect = lambda t, cb: defer.fail("fail")
  290. # create devices
  291. u1 = self.register_user("user", "pass")
  292. self.login("user", "pass", device_id="D1")
  293. self.login("user", "pass", device_id="D2")
  294. self.login("user", "pass", device_id="D3")
  295. # delete them again
  296. self.get_success(
  297. self.hs.get_device_handler().delete_devices(u1, ["D1", "D2", "D3"])
  298. )
  299. self.assertGreaterEqual(mock_send_txn.call_count, 4)
  300. # recover the server
  301. mock_send_txn.side_effect = self.record_transaction
  302. self.hs.get_federation_sender().send_device_messages("host2")
  303. self.pump()
  304. # for each device, there should be a single update
  305. self.assertEqual(len(self.edus), 3)
  306. stream_id = None
  307. for edu in self.edus:
  308. self.assertEqual(edu["edu_type"], "m.device_list_update")
  309. c = edu["content"]
  310. self.assertEqual(c["prev_id"], [stream_id] if stream_id is not None else [])
  311. if stream_id is not None:
  312. self.assertGreaterEqual(c["stream_id"], stream_id)
  313. stream_id = c["stream_id"]
  314. devices = {edu["content"]["device_id"] for edu in self.edus}
  315. self.assertEqual({"D1", "D2", "D3"}, devices)
  316. def test_prune_outbound_device_pokes1(self):
  317. """If a destination is unreachable, and the updates are pruned, we should get
  318. a single update.
  319. This case tests the behaviour when the server has never been reachable.
  320. """
  321. mock_send_txn = self.hs.get_federation_transport_client().send_transaction
  322. mock_send_txn.side_effect = lambda t, cb: defer.fail("fail")
  323. # create devices
  324. u1 = self.register_user("user", "pass")
  325. self.login("user", "pass", device_id="D1")
  326. self.login("user", "pass", device_id="D2")
  327. self.login("user", "pass", device_id="D3")
  328. # delete them again
  329. self.get_success(
  330. self.hs.get_device_handler().delete_devices(u1, ["D1", "D2", "D3"])
  331. )
  332. self.assertGreaterEqual(mock_send_txn.call_count, 4)
  333. # run the prune job
  334. self.reactor.advance(10)
  335. self.get_success(
  336. self.hs.get_datastore()._prune_old_outbound_device_pokes(prune_age=1)
  337. )
  338. # recover the server
  339. mock_send_txn.side_effect = self.record_transaction
  340. self.hs.get_federation_sender().send_device_messages("host2")
  341. self.pump()
  342. # there should be a single update for this user.
  343. self.assertEqual(len(self.edus), 1)
  344. edu = self.edus.pop(0)
  345. self.assertEqual(edu["edu_type"], "m.device_list_update")
  346. c = edu["content"]
  347. # synapse uses an empty prev_id list to indicate "needs a full resync".
  348. self.assertEqual(c["prev_id"], [])
  349. def test_prune_outbound_device_pokes2(self):
  350. """If a destination is unreachable, and the updates are pruned, we should get
  351. a single update.
  352. This case tests the behaviour when the server was reachable, but then goes
  353. offline.
  354. """
  355. # create first device
  356. u1 = self.register_user("user", "pass")
  357. self.login("user", "pass", device_id="D1")
  358. # expect the update EDU
  359. self.assertEqual(len(self.edus), 1)
  360. self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  361. # now the server goes offline
  362. mock_send_txn = self.hs.get_federation_transport_client().send_transaction
  363. mock_send_txn.side_effect = lambda t, cb: defer.fail("fail")
  364. self.login("user", "pass", device_id="D2")
  365. self.login("user", "pass", device_id="D3")
  366. # delete them again
  367. self.get_success(
  368. self.hs.get_device_handler().delete_devices(u1, ["D1", "D2", "D3"])
  369. )
  370. self.assertGreaterEqual(mock_send_txn.call_count, 3)
  371. # run the prune job
  372. self.reactor.advance(10)
  373. self.get_success(
  374. self.hs.get_datastore()._prune_old_outbound_device_pokes(prune_age=1)
  375. )
  376. # recover the server
  377. mock_send_txn.side_effect = self.record_transaction
  378. self.hs.get_federation_sender().send_device_messages("host2")
  379. self.pump()
  380. # ... and we should get a single update for this user.
  381. self.assertEqual(len(self.edus), 1)
  382. edu = self.edus.pop(0)
  383. self.assertEqual(edu["edu_type"], "m.device_list_update")
  384. c = edu["content"]
  385. # synapse uses an empty prev_id list to indicate "needs a full resync".
  386. self.assertEqual(c["prev_id"], [])
  387. def check_device_update_edu(
  388. self,
  389. edu: JsonDict,
  390. user_id: str,
  391. device_id: str,
  392. prev_stream_id: Optional[int],
  393. ) -> int:
  394. """Check that the given EDU is an update for the given device
  395. Returns the stream_id.
  396. """
  397. self.assertEqual(edu["edu_type"], "m.device_list_update")
  398. content = edu["content"]
  399. expected = {
  400. "user_id": user_id,
  401. "device_id": device_id,
  402. "prev_id": [prev_stream_id] if prev_stream_id is not None else [],
  403. }
  404. self.assertLessEqual(expected.items(), content.items())
  405. if prev_stream_id is not None:
  406. self.assertGreaterEqual(content["stream_id"], prev_stream_id)
  407. return content["stream_id"]
  408. def check_signing_key_update_txn(self, txn: JsonDict,) -> None:
  409. """Check that the txn has an EDU with a signing key update.
  410. """
  411. edus = txn["edus"]
  412. self.assertEqual(len(edus), 1)
  413. def generate_and_upload_device_signing_key(
  414. self, user_id: str, device_id: str
  415. ) -> SigningKey:
  416. """Generate a signing keypair for the given device, and upload it"""
  417. sk = key.generate_signing_key(device_id)
  418. device_dict = build_device_dict(user_id, device_id, sk)
  419. self.get_success(
  420. self.hs.get_e2e_keys_handler().upload_keys_for_user(
  421. user_id, device_id, {"device_keys": device_dict},
  422. )
  423. )
  424. return sk
  425. def generate_self_id_key() -> SigningKey:
  426. """generate a signing key whose version is its public key
  427. ... as used by the cross-signing-keys.
  428. """
  429. k = key.generate_signing_key("x")
  430. k.version = encode_pubkey(k)
  431. return k
  432. def key_id(k: BaseKey) -> str:
  433. return "%s:%s" % (k.alg, k.version)
  434. def encode_pubkey(sk: SigningKey) -> str:
  435. """Encode the public key corresponding to the given signing key as base64"""
  436. return key.encode_verify_key_base64(key.get_verify_key(sk))
  437. def build_device_dict(user_id: str, device_id: str, sk: SigningKey):
  438. """Build a dict representing the given device"""
  439. return {
  440. "user_id": user_id,
  441. "device_id": device_id,
  442. "algorithms": [
  443. "m.olm.curve25519-aes-sha2",
  444. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  445. ],
  446. "keys": {
  447. "curve25519:" + device_id: "curve25519+key",
  448. key_id(sk): encode_pubkey(sk),
  449. },
  450. }