test_federation_sender.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  1. # Copyright 2019 New Vector 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. from typing import Callable, FrozenSet, List, Optional, Set
  15. from unittest.mock import Mock
  16. from signedjson import key, sign
  17. from signedjson.types import BaseKey, SigningKey
  18. from twisted.internet import defer
  19. from twisted.test.proto_helpers import MemoryReactor
  20. from synapse.api.constants import EduTypes, RoomEncryptionAlgorithms
  21. from synapse.federation.units import Transaction
  22. from synapse.handlers.device import DeviceHandler
  23. from synapse.rest import admin
  24. from synapse.rest.client import login
  25. from synapse.server import HomeServer
  26. from synapse.types import JsonDict, ReadReceipt
  27. from synapse.util import Clock
  28. from tests.test_utils import make_awaitable
  29. from tests.unittest import HomeserverTestCase
  30. class FederationSenderReceiptsTestCases(HomeserverTestCase):
  31. """
  32. Test federation sending to update receipts.
  33. By default for test cases federation sending is disabled. This Test class has it
  34. re-enabled for the main process.
  35. """
  36. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  37. self.federation_transport_client = Mock(spec=["send_transaction"])
  38. hs = self.setup_test_homeserver(
  39. federation_transport_client=self.federation_transport_client,
  40. )
  41. hs.get_storage_controllers().state.get_current_hosts_in_room = Mock( # type: ignore[assignment]
  42. return_value=make_awaitable({"test", "host2"})
  43. )
  44. hs.get_storage_controllers().state.get_current_hosts_in_room_or_partial_state_approximation = ( # type: ignore[assignment]
  45. hs.get_storage_controllers().state.get_current_hosts_in_room
  46. )
  47. return hs
  48. def default_config(self) -> JsonDict:
  49. config = super().default_config()
  50. config["federation_sender_instances"] = None
  51. return config
  52. def test_send_receipts(self) -> None:
  53. mock_send_transaction = self.federation_transport_client.send_transaction
  54. mock_send_transaction.return_value = make_awaitable({})
  55. sender = self.hs.get_federation_sender()
  56. receipt = ReadReceipt(
  57. "room_id",
  58. "m.read",
  59. "user_id",
  60. ["event_id"],
  61. thread_id=None,
  62. data={"ts": 1234},
  63. )
  64. self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt)))
  65. self.pump()
  66. # expect a call to send_transaction
  67. mock_send_transaction.assert_called_once()
  68. json_cb = mock_send_transaction.call_args[0][1]
  69. data = json_cb()
  70. self.assertEqual(
  71. data["edus"],
  72. [
  73. {
  74. "edu_type": EduTypes.RECEIPT,
  75. "content": {
  76. "room_id": {
  77. "m.read": {
  78. "user_id": {
  79. "event_ids": ["event_id"],
  80. "data": {"ts": 1234},
  81. }
  82. }
  83. }
  84. },
  85. }
  86. ],
  87. )
  88. def test_send_receipts_thread(self) -> None:
  89. mock_send_transaction = self.federation_transport_client.send_transaction
  90. mock_send_transaction.return_value = make_awaitable({})
  91. # Create receipts for:
  92. #
  93. # * The same room / user on multiple threads.
  94. # * A different user in the same room.
  95. sender = self.hs.get_federation_sender()
  96. for user, thread in (
  97. ("alice", None),
  98. ("alice", "thread"),
  99. ("bob", None),
  100. ("bob", "diff-thread"),
  101. ):
  102. receipt = ReadReceipt(
  103. "room_id",
  104. "m.read",
  105. user,
  106. ["event_id"],
  107. thread_id=thread,
  108. data={"ts": 1234},
  109. )
  110. self.successResultOf(
  111. defer.ensureDeferred(sender.send_read_receipt(receipt))
  112. )
  113. self.pump()
  114. # expect a call to send_transaction with two EDUs to separate threads.
  115. mock_send_transaction.assert_called_once()
  116. json_cb = mock_send_transaction.call_args[0][1]
  117. data = json_cb()
  118. # Note that the ordering of the EDUs doesn't matter.
  119. self.assertCountEqual(
  120. data["edus"],
  121. [
  122. {
  123. "edu_type": EduTypes.RECEIPT,
  124. "content": {
  125. "room_id": {
  126. "m.read": {
  127. "alice": {
  128. "event_ids": ["event_id"],
  129. "data": {"ts": 1234, "thread_id": "thread"},
  130. },
  131. "bob": {
  132. "event_ids": ["event_id"],
  133. "data": {"ts": 1234, "thread_id": "diff-thread"},
  134. },
  135. }
  136. }
  137. },
  138. },
  139. {
  140. "edu_type": EduTypes.RECEIPT,
  141. "content": {
  142. "room_id": {
  143. "m.read": {
  144. "alice": {
  145. "event_ids": ["event_id"],
  146. "data": {"ts": 1234},
  147. },
  148. "bob": {
  149. "event_ids": ["event_id"],
  150. "data": {"ts": 1234},
  151. },
  152. }
  153. }
  154. },
  155. },
  156. ],
  157. )
  158. def test_send_receipts_with_backoff(self) -> None:
  159. """Send two receipts in quick succession; the second should be flushed, but
  160. only after 20ms"""
  161. mock_send_transaction = self.federation_transport_client.send_transaction
  162. mock_send_transaction.return_value = make_awaitable({})
  163. sender = self.hs.get_federation_sender()
  164. receipt = ReadReceipt(
  165. "room_id",
  166. "m.read",
  167. "user_id",
  168. ["event_id"],
  169. thread_id=None,
  170. data={"ts": 1234},
  171. )
  172. self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt)))
  173. self.pump()
  174. # expect a call to send_transaction
  175. mock_send_transaction.assert_called_once()
  176. json_cb = mock_send_transaction.call_args[0][1]
  177. data = json_cb()
  178. self.assertEqual(
  179. data["edus"],
  180. [
  181. {
  182. "edu_type": EduTypes.RECEIPT,
  183. "content": {
  184. "room_id": {
  185. "m.read": {
  186. "user_id": {
  187. "event_ids": ["event_id"],
  188. "data": {"ts": 1234},
  189. }
  190. }
  191. }
  192. },
  193. }
  194. ],
  195. )
  196. mock_send_transaction.reset_mock()
  197. # send the second RR
  198. receipt = ReadReceipt(
  199. "room_id",
  200. "m.read",
  201. "user_id",
  202. ["other_id"],
  203. thread_id=None,
  204. data={"ts": 1234},
  205. )
  206. self.successResultOf(defer.ensureDeferred(sender.send_read_receipt(receipt)))
  207. self.pump()
  208. mock_send_transaction.assert_not_called()
  209. self.reactor.advance(19)
  210. mock_send_transaction.assert_not_called()
  211. self.reactor.advance(10)
  212. mock_send_transaction.assert_called_once()
  213. json_cb = mock_send_transaction.call_args[0][1]
  214. data = json_cb()
  215. self.assertEqual(
  216. data["edus"],
  217. [
  218. {
  219. "edu_type": EduTypes.RECEIPT,
  220. "content": {
  221. "room_id": {
  222. "m.read": {
  223. "user_id": {
  224. "event_ids": ["other_id"],
  225. "data": {"ts": 1234},
  226. }
  227. }
  228. }
  229. },
  230. }
  231. ],
  232. )
  233. class FederationSenderDevicesTestCases(HomeserverTestCase):
  234. """
  235. Test federation sending to update devices.
  236. By default for test cases federation sending is disabled. This Test class has it
  237. re-enabled for the main process.
  238. """
  239. servlets = [
  240. admin.register_servlets,
  241. login.register_servlets,
  242. ]
  243. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  244. self.federation_transport_client = Mock(
  245. spec=["send_transaction", "query_user_devices"]
  246. )
  247. return self.setup_test_homeserver(
  248. federation_transport_client=self.federation_transport_client,
  249. )
  250. def default_config(self) -> JsonDict:
  251. c = super().default_config()
  252. # Enable federation sending on the main process.
  253. c["federation_sender_instances"] = None
  254. return c
  255. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  256. test_room_id = "!room:host1"
  257. # stub out `get_rooms_for_user` and `get_current_hosts_in_room` so that the
  258. # server thinks the user shares a room with `@user2:host2`
  259. def get_rooms_for_user(user_id: str) -> "defer.Deferred[FrozenSet[str]]":
  260. return defer.succeed(frozenset({test_room_id}))
  261. hs.get_datastores().main.get_rooms_for_user = get_rooms_for_user # type: ignore[assignment]
  262. async def get_current_hosts_in_room(room_id: str) -> Set[str]:
  263. if room_id == test_room_id:
  264. return {"host2"}
  265. else:
  266. # TODO: We should fail the test when we encounter an unxpected room ID.
  267. # We can't just use `self.fail(...)` here because the app code is greedy
  268. # with `Exception` and will catch it before the test can see it.
  269. return set()
  270. hs.get_datastores().main.get_current_hosts_in_room = get_current_hosts_in_room # type: ignore[assignment]
  271. device_handler = hs.get_device_handler()
  272. assert isinstance(device_handler, DeviceHandler)
  273. self.device_handler = device_handler
  274. # whenever send_transaction is called, record the edu data
  275. self.edus: List[JsonDict] = []
  276. self.federation_transport_client.send_transaction.side_effect = (
  277. self.record_transaction
  278. )
  279. def record_transaction(
  280. self, txn: Transaction, json_cb: Optional[Callable[[], JsonDict]] = None
  281. ) -> "defer.Deferred[JsonDict]":
  282. assert json_cb is not None
  283. data = json_cb()
  284. self.edus.extend(data["edus"])
  285. return defer.succeed({})
  286. def test_send_device_updates(self) -> None:
  287. """Basic case: each device update should result in an EDU"""
  288. # create a device
  289. u1 = self.register_user("user", "pass")
  290. self.login(u1, "pass", device_id="D1")
  291. # expect one edu
  292. self.assertEqual(len(self.edus), 1)
  293. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  294. # We queue up device list updates to be sent over federation, so we
  295. # advance to clear the queue.
  296. self.reactor.advance(1)
  297. # a second call should produce no new device EDUs
  298. self.hs.get_federation_sender().send_device_messages("host2")
  299. self.assertEqual(self.edus, [])
  300. # a second device
  301. self.login("user", "pass", device_id="D2")
  302. self.assertEqual(len(self.edus), 1)
  303. self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  304. def test_dont_send_device_updates_for_remote_users(self) -> None:
  305. """Check that we don't send device updates for remote users"""
  306. # Send the server a device list EDU for the other user, this will cause
  307. # it to try and resync the device lists.
  308. self.federation_transport_client.query_user_devices.return_value = (
  309. make_awaitable(
  310. {
  311. "stream_id": "1",
  312. "user_id": "@user2:host2",
  313. "devices": [{"device_id": "D1"}],
  314. }
  315. )
  316. )
  317. self.get_success(
  318. self.device_handler.device_list_updater.incoming_device_list_update(
  319. "host2",
  320. {
  321. "user_id": "@user2:host2",
  322. "device_id": "D1",
  323. "stream_id": "1",
  324. "prev_ids": [],
  325. },
  326. )
  327. )
  328. self.reactor.advance(1)
  329. # We shouldn't see an EDU for that update
  330. self.assertEqual(self.edus, [])
  331. # Check that we did successfully process the inbound EDU (otherwise this
  332. # test would pass if we failed to process the EDU)
  333. devices = self.get_success(
  334. self.hs.get_datastores().main.get_cached_devices_for_user("@user2:host2")
  335. )
  336. self.assertIn("D1", devices)
  337. def test_upload_signatures(self) -> None:
  338. """Uploading signatures on some devices should produce updates for that user"""
  339. e2e_handler = self.hs.get_e2e_keys_handler()
  340. # register two devices
  341. u1 = self.register_user("user", "pass")
  342. self.login(u1, "pass", device_id="D1")
  343. self.login(u1, "pass", device_id="D2")
  344. # expect two edus
  345. self.assertEqual(len(self.edus), 2)
  346. stream_id: Optional[int] = None
  347. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", stream_id)
  348. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  349. # upload signing keys for each device
  350. device1_signing_key = self.generate_and_upload_device_signing_key(u1, "D1")
  351. device2_signing_key = self.generate_and_upload_device_signing_key(u1, "D2")
  352. # We queue up device list updates to be sent over federation, so we
  353. # advance to clear the queue.
  354. self.reactor.advance(1)
  355. # expect two more edus
  356. self.assertEqual(len(self.edus), 2)
  357. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", stream_id)
  358. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  359. # upload master key and self-signing key
  360. master_signing_key = generate_self_id_key()
  361. master_key = {
  362. "user_id": u1,
  363. "usage": ["master"],
  364. "keys": {key_id(master_signing_key): encode_pubkey(master_signing_key)},
  365. }
  366. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  367. selfsigning_signing_key = generate_self_id_key()
  368. selfsigning_key = {
  369. "user_id": u1,
  370. "usage": ["self_signing"],
  371. "keys": {
  372. key_id(selfsigning_signing_key): encode_pubkey(selfsigning_signing_key)
  373. },
  374. }
  375. sign.sign_json(selfsigning_key, u1, master_signing_key)
  376. cross_signing_keys = {
  377. "master_key": master_key,
  378. "self_signing_key": selfsigning_key,
  379. }
  380. self.get_success(
  381. e2e_handler.upload_signing_keys_for_user(u1, cross_signing_keys)
  382. )
  383. # We queue up device list updates to be sent over federation, so we
  384. # advance to clear the queue.
  385. self.reactor.advance(1)
  386. # expect signing key update edu
  387. self.assertEqual(len(self.edus), 2)
  388. self.assertEqual(self.edus.pop(0)["edu_type"], EduTypes.SIGNING_KEY_UPDATE)
  389. self.assertEqual(
  390. self.edus.pop(0)["edu_type"], EduTypes.UNSTABLE_SIGNING_KEY_UPDATE
  391. )
  392. # sign the devices
  393. d1_json = build_device_dict(u1, "D1", device1_signing_key)
  394. sign.sign_json(d1_json, u1, selfsigning_signing_key)
  395. d2_json = build_device_dict(u1, "D2", device2_signing_key)
  396. sign.sign_json(d2_json, u1, selfsigning_signing_key)
  397. ret = self.get_success(
  398. e2e_handler.upload_signatures_for_device_keys(
  399. u1,
  400. {u1: {"D1": d1_json, "D2": d2_json}},
  401. )
  402. )
  403. self.assertEqual(ret["failures"], {})
  404. # We queue up device list updates to be sent over federation, so we
  405. # advance to clear the queue.
  406. self.reactor.advance(1)
  407. # expect two edus, in one or two transactions. We don't know what order the
  408. # devices will be updated.
  409. self.assertEqual(len(self.edus), 2)
  410. stream_id = None # FIXME: there is a discontinuity in the stream IDs: see #7142
  411. for edu in self.edus:
  412. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  413. c = edu["content"]
  414. if stream_id is not None:
  415. self.assertEqual(c["prev_id"], [stream_id]) # type: ignore[unreachable]
  416. self.assertGreaterEqual(c["stream_id"], stream_id)
  417. stream_id = c["stream_id"]
  418. devices = {edu["content"]["device_id"] for edu in self.edus}
  419. self.assertEqual({"D1", "D2"}, devices)
  420. def test_delete_devices(self) -> None:
  421. """If devices are deleted, that should result in EDUs too"""
  422. # create devices
  423. u1 = self.register_user("user", "pass")
  424. self.login("user", "pass", device_id="D1")
  425. self.login("user", "pass", device_id="D2")
  426. self.login("user", "pass", device_id="D3")
  427. # We queue up device list updates to be sent over federation, so we
  428. # advance to clear the queue.
  429. self.reactor.advance(1)
  430. # expect three edus
  431. self.assertEqual(len(self.edus), 3)
  432. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  433. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  434. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D3", stream_id)
  435. # delete them again
  436. self.get_success(self.device_handler.delete_devices(u1, ["D1", "D2", "D3"]))
  437. # We queue up device list updates to be sent over federation, so we
  438. # advance to clear the queue.
  439. self.reactor.advance(1)
  440. # expect three edus, in an unknown order
  441. self.assertEqual(len(self.edus), 3)
  442. for edu in self.edus:
  443. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  444. c = edu["content"]
  445. self.assertGreaterEqual(
  446. c.items(),
  447. {"user_id": u1, "prev_id": [stream_id], "deleted": True}.items(),
  448. )
  449. self.assertGreaterEqual(c["stream_id"], stream_id)
  450. stream_id = c["stream_id"]
  451. devices = {edu["content"]["device_id"] for edu in self.edus}
  452. self.assertEqual({"D1", "D2", "D3"}, devices)
  453. def test_unreachable_server(self) -> None:
  454. """If the destination server is unreachable, all the updates should get sent on
  455. recovery
  456. """
  457. mock_send_txn = self.federation_transport_client.send_transaction
  458. mock_send_txn.side_effect = lambda t, cb: defer.fail(AssertionError("fail"))
  459. # create devices
  460. u1 = self.register_user("user", "pass")
  461. self.login("user", "pass", device_id="D1")
  462. self.login("user", "pass", device_id="D2")
  463. self.login("user", "pass", device_id="D3")
  464. # delete them again
  465. self.get_success(self.device_handler.delete_devices(u1, ["D1", "D2", "D3"]))
  466. # We queue up device list updates to be sent over federation, so we
  467. # advance to clear the queue.
  468. self.reactor.advance(1)
  469. self.assertGreaterEqual(mock_send_txn.call_count, 4)
  470. # recover the server
  471. mock_send_txn.side_effect = self.record_transaction
  472. self.hs.get_federation_sender().send_device_messages("host2")
  473. # We queue up device list updates to be sent over federation, so we
  474. # advance to clear the queue.
  475. self.reactor.advance(1)
  476. # for each device, there should be a single update
  477. self.assertEqual(len(self.edus), 3)
  478. stream_id: Optional[int] = None
  479. for edu in self.edus:
  480. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  481. c = edu["content"]
  482. self.assertEqual(c["prev_id"], [stream_id] if stream_id is not None else [])
  483. if stream_id is not None:
  484. self.assertGreaterEqual(c["stream_id"], stream_id)
  485. stream_id = c["stream_id"]
  486. devices = {edu["content"]["device_id"] for edu in self.edus}
  487. self.assertEqual({"D1", "D2", "D3"}, devices)
  488. def test_prune_outbound_device_pokes1(self) -> None:
  489. """If a destination is unreachable, and the updates are pruned, we should get
  490. a single update.
  491. This case tests the behaviour when the server has never been reachable.
  492. """
  493. mock_send_txn = self.federation_transport_client.send_transaction
  494. mock_send_txn.side_effect = lambda t, cb: defer.fail(AssertionError("fail"))
  495. # create devices
  496. u1 = self.register_user("user", "pass")
  497. self.login("user", "pass", device_id="D1")
  498. self.login("user", "pass", device_id="D2")
  499. self.login("user", "pass", device_id="D3")
  500. # delete them again
  501. self.get_success(self.device_handler.delete_devices(u1, ["D1", "D2", "D3"]))
  502. # We queue up device list updates to be sent over federation, so we
  503. # advance to clear the queue.
  504. self.reactor.advance(1)
  505. self.assertGreaterEqual(mock_send_txn.call_count, 4)
  506. # run the prune job
  507. self.reactor.advance(10)
  508. self.get_success(
  509. self.hs.get_datastores().main._prune_old_outbound_device_pokes(prune_age=1)
  510. )
  511. # recover the server
  512. mock_send_txn.side_effect = self.record_transaction
  513. self.hs.get_federation_sender().send_device_messages("host2")
  514. # We queue up device list updates to be sent over federation, so we
  515. # advance to clear the queue.
  516. self.reactor.advance(1)
  517. # there should be a single update for this user.
  518. self.assertEqual(len(self.edus), 1)
  519. edu = self.edus.pop(0)
  520. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  521. c = edu["content"]
  522. # synapse uses an empty prev_id list to indicate "needs a full resync".
  523. self.assertEqual(c["prev_id"], [])
  524. def test_prune_outbound_device_pokes2(self) -> None:
  525. """If a destination is unreachable, and the updates are pruned, we should get
  526. a single update.
  527. This case tests the behaviour when the server was reachable, but then goes
  528. offline.
  529. """
  530. # create first device
  531. u1 = self.register_user("user", "pass")
  532. self.login("user", "pass", device_id="D1")
  533. # expect the update EDU
  534. self.assertEqual(len(self.edus), 1)
  535. self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  536. # now the server goes offline
  537. mock_send_txn = self.federation_transport_client.send_transaction
  538. mock_send_txn.side_effect = lambda t, cb: defer.fail(AssertionError("fail"))
  539. self.login("user", "pass", device_id="D2")
  540. self.login("user", "pass", device_id="D3")
  541. # We queue up device list updates to be sent over federation, so we
  542. # advance to clear the queue.
  543. self.reactor.advance(1)
  544. # delete them again
  545. self.get_success(self.device_handler.delete_devices(u1, ["D1", "D2", "D3"]))
  546. self.assertGreaterEqual(mock_send_txn.call_count, 3)
  547. # run the prune job
  548. self.reactor.advance(10)
  549. self.get_success(
  550. self.hs.get_datastores().main._prune_old_outbound_device_pokes(prune_age=1)
  551. )
  552. # recover the server
  553. mock_send_txn.side_effect = self.record_transaction
  554. self.hs.get_federation_sender().send_device_messages("host2")
  555. # We queue up device list updates to be sent over federation, so we
  556. # advance to clear the queue.
  557. self.reactor.advance(1)
  558. # ... and we should get a single update for this user.
  559. self.assertEqual(len(self.edus), 1)
  560. edu = self.edus.pop(0)
  561. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  562. c = edu["content"]
  563. # synapse uses an empty prev_id list to indicate "needs a full resync".
  564. self.assertEqual(c["prev_id"], [])
  565. def check_device_update_edu(
  566. self,
  567. edu: JsonDict,
  568. user_id: str,
  569. device_id: str,
  570. prev_stream_id: Optional[int],
  571. ) -> int:
  572. """Check that the given EDU is an update for the given device
  573. Returns the stream_id.
  574. """
  575. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  576. content = edu["content"]
  577. expected = {
  578. "user_id": user_id,
  579. "device_id": device_id,
  580. "prev_id": [prev_stream_id] if prev_stream_id is not None else [],
  581. }
  582. self.assertLessEqual(expected.items(), content.items())
  583. if prev_stream_id is not None:
  584. self.assertGreaterEqual(content["stream_id"], prev_stream_id)
  585. return content["stream_id"]
  586. def check_signing_key_update_txn(
  587. self,
  588. txn: JsonDict,
  589. ) -> None:
  590. """Check that the txn has an EDU with a signing key update."""
  591. edus = txn["edus"]
  592. self.assertEqual(len(edus), 2)
  593. def generate_and_upload_device_signing_key(
  594. self, user_id: str, device_id: str
  595. ) -> SigningKey:
  596. """Generate a signing keypair for the given device, and upload it"""
  597. sk = key.generate_signing_key(device_id)
  598. device_dict = build_device_dict(user_id, device_id, sk)
  599. self.get_success(
  600. self.hs.get_e2e_keys_handler().upload_keys_for_user(
  601. user_id,
  602. device_id,
  603. {"device_keys": device_dict},
  604. )
  605. )
  606. return sk
  607. def generate_self_id_key() -> SigningKey:
  608. """generate a signing key whose version is its public key
  609. ... as used by the cross-signing-keys.
  610. """
  611. k = key.generate_signing_key("x")
  612. k.version = encode_pubkey(k)
  613. return k
  614. def key_id(k: BaseKey) -> str:
  615. return "%s:%s" % (k.alg, k.version)
  616. def encode_pubkey(sk: SigningKey) -> str:
  617. """Encode the public key corresponding to the given signing key as base64"""
  618. return key.encode_verify_key_base64(key.get_verify_key(sk))
  619. def build_device_dict(user_id: str, device_id: str, sk: SigningKey) -> JsonDict:
  620. """Build a dict representing the given device"""
  621. return {
  622. "user_id": user_id,
  623. "device_id": device_id,
  624. "algorithms": [
  625. "m.olm.curve25519-aes-sha2",
  626. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  627. ],
  628. "keys": {
  629. "curve25519:" + device_id: "curve25519+key",
  630. key_id(sk): encode_pubkey(sk),
  631. },
  632. }