You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

757 lines
27 KiB

  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 AsyncMock, 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.unittest import HomeserverTestCase
  29. class FederationSenderReceiptsTestCases(HomeserverTestCase):
  30. """
  31. Test federation sending to update receipts.
  32. By default for test cases federation sending is disabled. This Test class has it
  33. re-enabled for the main process.
  34. """
  35. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  36. self.federation_transport_client = Mock(spec=["send_transaction"])
  37. self.federation_transport_client.send_transaction = AsyncMock()
  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 = AsyncMock( # type: ignore[method-assign]
  42. return_value={"test", "host2"}
  43. )
  44. hs.get_storage_controllers().state.get_current_hosts_in_room_or_partial_state_approximation = ( # type: ignore[method-assign]
  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 = {}
  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 = {}
  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 = {}
  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. self.federation_transport_client.send_transaction = AsyncMock()
  248. self.federation_transport_client.query_user_devices = AsyncMock()
  249. return self.setup_test_homeserver(
  250. federation_transport_client=self.federation_transport_client,
  251. )
  252. def default_config(self) -> JsonDict:
  253. c = super().default_config()
  254. # Enable federation sending on the main process.
  255. c["federation_sender_instances"] = None
  256. return c
  257. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  258. test_room_id = "!room:host1"
  259. # stub out `get_rooms_for_user` and `get_current_hosts_in_room` so that the
  260. # server thinks the user shares a room with `@user2:host2`
  261. def get_rooms_for_user(user_id: str) -> "defer.Deferred[FrozenSet[str]]":
  262. return defer.succeed(frozenset({test_room_id}))
  263. hs.get_datastores().main.get_rooms_for_user = get_rooms_for_user # type: ignore[assignment]
  264. async def get_current_hosts_in_room(room_id: str) -> Set[str]:
  265. if room_id == test_room_id:
  266. return {"host2"}
  267. else:
  268. # TODO: We should fail the test when we encounter an unxpected room ID.
  269. # We can't just use `self.fail(...)` here because the app code is greedy
  270. # with `Exception` and will catch it before the test can see it.
  271. return set()
  272. hs.get_datastores().main.get_current_hosts_in_room = get_current_hosts_in_room # type: ignore[assignment]
  273. device_handler = hs.get_device_handler()
  274. assert isinstance(device_handler, DeviceHandler)
  275. self.device_handler = device_handler
  276. # whenever send_transaction is called, record the edu data
  277. self.edus: List[JsonDict] = []
  278. self.federation_transport_client.send_transaction.side_effect = (
  279. self.record_transaction
  280. )
  281. async def record_transaction(
  282. self, txn: Transaction, json_cb: Optional[Callable[[], JsonDict]] = None
  283. ) -> JsonDict:
  284. assert json_cb is not None
  285. data = json_cb()
  286. self.edus.extend(data["edus"])
  287. return {}
  288. def test_send_device_updates(self) -> None:
  289. """Basic case: each device update should result in an EDU"""
  290. # create a device
  291. u1 = self.register_user("user", "pass")
  292. self.login(u1, "pass", device_id="D1")
  293. # expect one edu
  294. self.assertEqual(len(self.edus), 1)
  295. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  296. # We queue up device list updates to be sent over federation, so we
  297. # advance to clear the queue.
  298. self.reactor.advance(1)
  299. # a second call should produce no new device EDUs
  300. self.hs.get_federation_sender().send_device_messages("host2")
  301. self.assertEqual(self.edus, [])
  302. # a second device
  303. self.login("user", "pass", device_id="D2")
  304. self.assertEqual(len(self.edus), 1)
  305. self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  306. def test_dont_send_device_updates_for_remote_users(self) -> None:
  307. """Check that we don't send device updates for remote users"""
  308. # Send the server a device list EDU for the other user, this will cause
  309. # it to try and resync the device lists.
  310. self.federation_transport_client.query_user_devices.return_value = {
  311. "stream_id": "1",
  312. "user_id": "@user2:host2",
  313. "devices": [{"device_id": "D1"}],
  314. }
  315. self.get_success(
  316. self.device_handler.device_list_updater.incoming_device_list_update(
  317. "host2",
  318. {
  319. "user_id": "@user2:host2",
  320. "device_id": "D1",
  321. "stream_id": "1",
  322. "prev_ids": [],
  323. },
  324. )
  325. )
  326. self.reactor.advance(1)
  327. # We shouldn't see an EDU for that update
  328. self.assertEqual(self.edus, [])
  329. # Check that we did successfully process the inbound EDU (otherwise this
  330. # test would pass if we failed to process the EDU)
  331. devices = self.get_success(
  332. self.hs.get_datastores().main.get_cached_devices_for_user("@user2:host2")
  333. )
  334. self.assertIn("D1", devices)
  335. def test_upload_signatures(self) -> None:
  336. """Uploading signatures on some devices should produce updates for that user"""
  337. e2e_handler = self.hs.get_e2e_keys_handler()
  338. # register two devices
  339. u1 = self.register_user("user", "pass")
  340. self.login(u1, "pass", device_id="D1")
  341. self.login(u1, "pass", device_id="D2")
  342. # expect two edus
  343. self.assertEqual(len(self.edus), 2)
  344. stream_id: Optional[int] = None
  345. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", stream_id)
  346. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  347. # upload signing keys for each device
  348. device1_signing_key = self.generate_and_upload_device_signing_key(u1, "D1")
  349. device2_signing_key = self.generate_and_upload_device_signing_key(u1, "D2")
  350. # We queue up device list updates to be sent over federation, so we
  351. # advance to clear the queue.
  352. self.reactor.advance(1)
  353. # expect two more edus
  354. self.assertEqual(len(self.edus), 2)
  355. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", stream_id)
  356. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  357. # upload master key and self-signing key
  358. master_signing_key = generate_self_id_key()
  359. master_key = {
  360. "user_id": u1,
  361. "usage": ["master"],
  362. "keys": {key_id(master_signing_key): encode_pubkey(master_signing_key)},
  363. }
  364. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  365. selfsigning_signing_key = generate_self_id_key()
  366. selfsigning_key = {
  367. "user_id": u1,
  368. "usage": ["self_signing"],
  369. "keys": {
  370. key_id(selfsigning_signing_key): encode_pubkey(selfsigning_signing_key)
  371. },
  372. }
  373. sign.sign_json(selfsigning_key, u1, master_signing_key)
  374. cross_signing_keys = {
  375. "master_key": master_key,
  376. "self_signing_key": selfsigning_key,
  377. }
  378. self.get_success(
  379. e2e_handler.upload_signing_keys_for_user(u1, cross_signing_keys)
  380. )
  381. # We queue up device list updates to be sent over federation, so we
  382. # advance to clear the queue.
  383. self.reactor.advance(1)
  384. # expect signing key update edu
  385. self.assertEqual(len(self.edus), 2)
  386. self.assertEqual(self.edus.pop(0)["edu_type"], EduTypes.SIGNING_KEY_UPDATE)
  387. self.assertEqual(
  388. self.edus.pop(0)["edu_type"], EduTypes.UNSTABLE_SIGNING_KEY_UPDATE
  389. )
  390. # sign the devices
  391. d1_json = build_device_dict(u1, "D1", device1_signing_key)
  392. sign.sign_json(d1_json, u1, selfsigning_signing_key)
  393. d2_json = build_device_dict(u1, "D2", device2_signing_key)
  394. sign.sign_json(d2_json, u1, selfsigning_signing_key)
  395. ret = self.get_success(
  396. e2e_handler.upload_signatures_for_device_keys(
  397. u1,
  398. {u1: {"D1": d1_json, "D2": d2_json}},
  399. )
  400. )
  401. self.assertEqual(ret["failures"], {})
  402. # We queue up device list updates to be sent over federation, so we
  403. # advance to clear the queue.
  404. self.reactor.advance(1)
  405. # expect two edus, in one or two transactions. We don't know what order the
  406. # devices will be updated.
  407. self.assertEqual(len(self.edus), 2)
  408. stream_id = None # FIXME: there is a discontinuity in the stream IDs: see #7142
  409. for edu in self.edus:
  410. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  411. c = edu["content"]
  412. if stream_id is not None:
  413. self.assertEqual(c["prev_id"], [stream_id]) # type: ignore[unreachable]
  414. self.assertGreaterEqual(c["stream_id"], stream_id)
  415. stream_id = c["stream_id"]
  416. devices = {edu["content"]["device_id"] for edu in self.edus}
  417. self.assertEqual({"D1", "D2"}, devices)
  418. def test_delete_devices(self) -> None:
  419. """If devices are deleted, that should result in EDUs too"""
  420. # create devices
  421. u1 = self.register_user("user", "pass")
  422. self.login("user", "pass", device_id="D1")
  423. self.login("user", "pass", device_id="D2")
  424. self.login("user", "pass", device_id="D3")
  425. # We queue up device list updates to be sent over federation, so we
  426. # advance to clear the queue.
  427. self.reactor.advance(1)
  428. # expect three edus
  429. self.assertEqual(len(self.edus), 3)
  430. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  431. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D2", stream_id)
  432. stream_id = self.check_device_update_edu(self.edus.pop(0), u1, "D3", stream_id)
  433. # delete them again
  434. self.get_success(self.device_handler.delete_devices(u1, ["D1", "D2", "D3"]))
  435. # We queue up device list updates to be sent over federation, so we
  436. # advance to clear the queue.
  437. self.reactor.advance(1)
  438. # expect three edus, in an unknown order
  439. self.assertEqual(len(self.edus), 3)
  440. for edu in self.edus:
  441. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  442. c = edu["content"]
  443. self.assertGreaterEqual(
  444. c.items(),
  445. {"user_id": u1, "prev_id": [stream_id], "deleted": True}.items(),
  446. )
  447. self.assertGreaterEqual(c["stream_id"], stream_id)
  448. stream_id = c["stream_id"]
  449. devices = {edu["content"]["device_id"] for edu in self.edus}
  450. self.assertEqual({"D1", "D2", "D3"}, devices)
  451. def test_unreachable_server(self) -> None:
  452. """If the destination server is unreachable, all the updates should get sent on
  453. recovery
  454. """
  455. mock_send_txn = self.federation_transport_client.send_transaction
  456. mock_send_txn.side_effect = AssertionError("fail")
  457. # create devices
  458. u1 = self.register_user("user", "pass")
  459. self.login("user", "pass", device_id="D1")
  460. self.login("user", "pass", device_id="D2")
  461. self.login("user", "pass", device_id="D3")
  462. # delete them again
  463. self.get_success(self.device_handler.delete_devices(u1, ["D1", "D2", "D3"]))
  464. # We queue up device list updates to be sent over federation, so we
  465. # advance to clear the queue.
  466. self.reactor.advance(1)
  467. self.assertGreaterEqual(mock_send_txn.call_count, 4)
  468. # recover the server
  469. mock_send_txn.side_effect = self.record_transaction
  470. self.hs.get_federation_sender().send_device_messages("host2")
  471. # We queue up device list updates to be sent over federation, so we
  472. # advance to clear the queue.
  473. self.reactor.advance(1)
  474. # for each device, there should be a single update
  475. self.assertEqual(len(self.edus), 3)
  476. stream_id: Optional[int] = None
  477. for edu in self.edus:
  478. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  479. c = edu["content"]
  480. self.assertEqual(c["prev_id"], [stream_id] if stream_id is not None else [])
  481. if stream_id is not None:
  482. self.assertGreaterEqual(c["stream_id"], stream_id)
  483. stream_id = c["stream_id"]
  484. devices = {edu["content"]["device_id"] for edu in self.edus}
  485. self.assertEqual({"D1", "D2", "D3"}, devices)
  486. def test_prune_outbound_device_pokes1(self) -> None:
  487. """If a destination is unreachable, and the updates are pruned, we should get
  488. a single update.
  489. This case tests the behaviour when the server has never been reachable.
  490. """
  491. mock_send_txn = self.federation_transport_client.send_transaction
  492. mock_send_txn.side_effect = AssertionError("fail")
  493. # create devices
  494. u1 = self.register_user("user", "pass")
  495. self.login("user", "pass", device_id="D1")
  496. self.login("user", "pass", device_id="D2")
  497. self.login("user", "pass", device_id="D3")
  498. # delete them again
  499. self.get_success(self.device_handler.delete_devices(u1, ["D1", "D2", "D3"]))
  500. # We queue up device list updates to be sent over federation, so we
  501. # advance to clear the queue.
  502. self.reactor.advance(1)
  503. self.assertGreaterEqual(mock_send_txn.call_count, 4)
  504. # run the prune job
  505. self.reactor.advance(10)
  506. self.get_success(
  507. self.hs.get_datastores().main._prune_old_outbound_device_pokes(prune_age=1)
  508. )
  509. # recover the server
  510. mock_send_txn.side_effect = self.record_transaction
  511. self.hs.get_federation_sender().send_device_messages("host2")
  512. # We queue up device list updates to be sent over federation, so we
  513. # advance to clear the queue.
  514. self.reactor.advance(1)
  515. # there should be a single update for this user.
  516. self.assertEqual(len(self.edus), 1)
  517. edu = self.edus.pop(0)
  518. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  519. c = edu["content"]
  520. # synapse uses an empty prev_id list to indicate "needs a full resync".
  521. self.assertEqual(c["prev_id"], [])
  522. def test_prune_outbound_device_pokes2(self) -> None:
  523. """If a destination is unreachable, and the updates are pruned, we should get
  524. a single update.
  525. This case tests the behaviour when the server was reachable, but then goes
  526. offline.
  527. """
  528. # create first device
  529. u1 = self.register_user("user", "pass")
  530. self.login("user", "pass", device_id="D1")
  531. # expect the update EDU
  532. self.assertEqual(len(self.edus), 1)
  533. self.check_device_update_edu(self.edus.pop(0), u1, "D1", None)
  534. # now the server goes offline
  535. mock_send_txn = self.federation_transport_client.send_transaction
  536. mock_send_txn.side_effect = AssertionError("fail")
  537. self.login("user", "pass", device_id="D2")
  538. self.login("user", "pass", device_id="D3")
  539. # We queue up device list updates to be sent over federation, so we
  540. # advance to clear the queue.
  541. self.reactor.advance(1)
  542. # delete them again
  543. self.get_success(self.device_handler.delete_devices(u1, ["D1", "D2", "D3"]))
  544. self.assertGreaterEqual(mock_send_txn.call_count, 3)
  545. # run the prune job
  546. self.reactor.advance(10)
  547. self.get_success(
  548. self.hs.get_datastores().main._prune_old_outbound_device_pokes(prune_age=1)
  549. )
  550. # recover the server
  551. mock_send_txn.side_effect = self.record_transaction
  552. self.hs.get_federation_sender().send_device_messages("host2")
  553. # We queue up device list updates to be sent over federation, so we
  554. # advance to clear the queue.
  555. self.reactor.advance(1)
  556. # ... and we should get a single update for this user.
  557. self.assertEqual(len(self.edus), 1)
  558. edu = self.edus.pop(0)
  559. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  560. c = edu["content"]
  561. # synapse uses an empty prev_id list to indicate "needs a full resync".
  562. self.assertEqual(c["prev_id"], [])
  563. def check_device_update_edu(
  564. self,
  565. edu: JsonDict,
  566. user_id: str,
  567. device_id: str,
  568. prev_stream_id: Optional[int],
  569. ) -> int:
  570. """Check that the given EDU is an update for the given device
  571. Returns the stream_id.
  572. """
  573. self.assertEqual(edu["edu_type"], EduTypes.DEVICE_LIST_UPDATE)
  574. content = edu["content"]
  575. expected = {
  576. "user_id": user_id,
  577. "device_id": device_id,
  578. "prev_id": [prev_stream_id] if prev_stream_id is not None else [],
  579. }
  580. self.assertLessEqual(expected.items(), content.items())
  581. if prev_stream_id is not None:
  582. self.assertGreaterEqual(content["stream_id"], prev_stream_id)
  583. return content["stream_id"]
  584. def check_signing_key_update_txn(
  585. self,
  586. txn: JsonDict,
  587. ) -> None:
  588. """Check that the txn has an EDU with a signing key update."""
  589. edus = txn["edus"]
  590. self.assertEqual(len(edus), 2)
  591. def generate_and_upload_device_signing_key(
  592. self, user_id: str, device_id: str
  593. ) -> SigningKey:
  594. """Generate a signing keypair for the given device, and upload it"""
  595. sk = key.generate_signing_key(device_id)
  596. device_dict = build_device_dict(user_id, device_id, sk)
  597. self.get_success(
  598. self.hs.get_e2e_keys_handler().upload_keys_for_user(
  599. user_id,
  600. device_id,
  601. {"device_keys": device_dict},
  602. )
  603. )
  604. return sk
  605. def generate_self_id_key() -> SigningKey:
  606. """generate a signing key whose version is its public key
  607. ... as used by the cross-signing-keys.
  608. """
  609. k = key.generate_signing_key("x")
  610. k.version = encode_pubkey(k)
  611. return k
  612. def key_id(k: BaseKey) -> str:
  613. return "%s:%s" % (k.alg, k.version)
  614. def encode_pubkey(sk: SigningKey) -> str:
  615. """Encode the public key corresponding to the given signing key as base64"""
  616. return key.encode_verify_key_base64(key.get_verify_key(sk))
  617. def build_device_dict(user_id: str, device_id: str, sk: SigningKey) -> JsonDict:
  618. """Build a dict representing the given device"""
  619. return {
  620. "user_id": user_id,
  621. "device_id": device_id,
  622. "algorithms": [
  623. "m.olm.curve25519-aes-sha2",
  624. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  625. ],
  626. "keys": {
  627. "curve25519:" + device_id: "curve25519+key",
  628. key_id(sk): encode_pubkey(sk),
  629. },
  630. }