test_e2e_keys.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. # Copyright 2016 OpenMarket Ltd
  2. # Copyright 2019 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from typing import Iterable
  17. from unittest import mock
  18. from parameterized import parameterized
  19. from signedjson import key as key, sign as sign
  20. from twisted.internet import defer
  21. from twisted.test.proto_helpers import MemoryReactor
  22. from synapse.api.constants import RoomEncryptionAlgorithms
  23. from synapse.api.errors import Codes, SynapseError
  24. from synapse.server import HomeServer
  25. from synapse.types import JsonDict
  26. from synapse.util import Clock
  27. from tests import unittest
  28. from tests.test_utils import make_awaitable
  29. class E2eKeysHandlerTestCase(unittest.HomeserverTestCase):
  30. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  31. return self.setup_test_homeserver(federation_client=mock.Mock())
  32. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  33. self.handler = hs.get_e2e_keys_handler()
  34. self.store = self.hs.get_datastores().main
  35. def test_query_local_devices_no_devices(self) -> None:
  36. """If the user has no devices, we expect an empty list."""
  37. local_user = "@boris:" + self.hs.hostname
  38. res = self.get_success(self.handler.query_local_devices({local_user: None}))
  39. self.assertDictEqual(res, {local_user: {}})
  40. def test_reupload_one_time_keys(self) -> None:
  41. """we should be able to re-upload the same keys"""
  42. local_user = "@boris:" + self.hs.hostname
  43. device_id = "xyz"
  44. keys: JsonDict = {
  45. "alg1:k1": "key1",
  46. "alg2:k2": {"key": "key2", "signatures": {"k1": "sig1"}},
  47. "alg2:k3": {"key": "key3"},
  48. }
  49. # Note that "signed_curve25519" is always returned in key count responses. This is necessary until
  50. # https://github.com/matrix-org/matrix-doc/issues/3298 is fixed.
  51. res = self.get_success(
  52. self.handler.upload_keys_for_user(
  53. local_user, device_id, {"one_time_keys": keys}
  54. )
  55. )
  56. self.assertDictEqual(
  57. res, {"one_time_key_counts": {"alg1": 1, "alg2": 2, "signed_curve25519": 0}}
  58. )
  59. # we should be able to change the signature without a problem
  60. keys["alg2:k2"]["signatures"]["k1"] = "sig2"
  61. res = self.get_success(
  62. self.handler.upload_keys_for_user(
  63. local_user, device_id, {"one_time_keys": keys}
  64. )
  65. )
  66. self.assertDictEqual(
  67. res, {"one_time_key_counts": {"alg1": 1, "alg2": 2, "signed_curve25519": 0}}
  68. )
  69. def test_change_one_time_keys(self) -> None:
  70. """attempts to change one-time-keys should be rejected"""
  71. local_user = "@boris:" + self.hs.hostname
  72. device_id = "xyz"
  73. keys = {
  74. "alg1:k1": "key1",
  75. "alg2:k2": {"key": "key2", "signatures": {"k1": "sig1"}},
  76. "alg2:k3": {"key": "key3"},
  77. }
  78. res = self.get_success(
  79. self.handler.upload_keys_for_user(
  80. local_user, device_id, {"one_time_keys": keys}
  81. )
  82. )
  83. self.assertDictEqual(
  84. res, {"one_time_key_counts": {"alg1": 1, "alg2": 2, "signed_curve25519": 0}}
  85. )
  86. # Error when changing string key
  87. self.get_failure(
  88. self.handler.upload_keys_for_user(
  89. local_user, device_id, {"one_time_keys": {"alg1:k1": "key2"}}
  90. ),
  91. SynapseError,
  92. )
  93. # Error when replacing dict key with string
  94. self.get_failure(
  95. self.handler.upload_keys_for_user(
  96. local_user, device_id, {"one_time_keys": {"alg2:k3": "key2"}}
  97. ),
  98. SynapseError,
  99. )
  100. # Error when replacing string key with dict
  101. self.get_failure(
  102. self.handler.upload_keys_for_user(
  103. local_user,
  104. device_id,
  105. {"one_time_keys": {"alg1:k1": {"key": "key"}}},
  106. ),
  107. SynapseError,
  108. )
  109. # Error when replacing dict key
  110. self.get_failure(
  111. self.handler.upload_keys_for_user(
  112. local_user,
  113. device_id,
  114. {
  115. "one_time_keys": {
  116. "alg2:k2": {"key": "key3", "signatures": {"k1": "sig1"}}
  117. }
  118. },
  119. ),
  120. SynapseError,
  121. )
  122. def test_claim_one_time_key(self) -> None:
  123. local_user = "@boris:" + self.hs.hostname
  124. device_id = "xyz"
  125. keys = {"alg1:k1": "key1"}
  126. res = self.get_success(
  127. self.handler.upload_keys_for_user(
  128. local_user, device_id, {"one_time_keys": keys}
  129. )
  130. )
  131. self.assertDictEqual(
  132. res, {"one_time_key_counts": {"alg1": 1, "signed_curve25519": 0}}
  133. )
  134. res2 = self.get_success(
  135. self.handler.claim_one_time_keys(
  136. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  137. )
  138. )
  139. self.assertEqual(
  140. res2,
  141. {
  142. "failures": {},
  143. "one_time_keys": {local_user: {device_id: {"alg1:k1": "key1"}}},
  144. },
  145. )
  146. def test_fallback_key(self) -> None:
  147. local_user = "@boris:" + self.hs.hostname
  148. device_id = "xyz"
  149. fallback_key = {"alg1:k1": "fallback_key1"}
  150. fallback_key2 = {"alg1:k2": "fallback_key2"}
  151. fallback_key3 = {"alg1:k2": "fallback_key3"}
  152. otk = {"alg1:k2": "key2"}
  153. # we shouldn't have any unused fallback keys yet
  154. res = self.get_success(
  155. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  156. )
  157. self.assertEqual(res, [])
  158. self.get_success(
  159. self.handler.upload_keys_for_user(
  160. local_user,
  161. device_id,
  162. {"fallback_keys": fallback_key},
  163. )
  164. )
  165. # we should now have an unused alg1 key
  166. res = self.get_success(
  167. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  168. )
  169. self.assertEqual(res, ["alg1"])
  170. # claiming an OTK when no OTKs are available should return the fallback
  171. # key
  172. res = self.get_success(
  173. self.handler.claim_one_time_keys(
  174. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  175. )
  176. )
  177. self.assertEqual(
  178. res,
  179. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key}}},
  180. )
  181. # we shouldn't have any unused fallback keys again
  182. res = self.get_success(
  183. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  184. )
  185. self.assertEqual(res, [])
  186. # claiming an OTK again should return the same fallback key
  187. res = self.get_success(
  188. self.handler.claim_one_time_keys(
  189. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  190. )
  191. )
  192. self.assertEqual(
  193. res,
  194. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key}}},
  195. )
  196. # re-uploading the same fallback key should still result in no unused fallback
  197. # keys
  198. self.get_success(
  199. self.handler.upload_keys_for_user(
  200. local_user,
  201. device_id,
  202. {"fallback_keys": fallback_key},
  203. )
  204. )
  205. res = self.get_success(
  206. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  207. )
  208. self.assertEqual(res, [])
  209. # uploading a new fallback key should result in an unused fallback key
  210. self.get_success(
  211. self.handler.upload_keys_for_user(
  212. local_user,
  213. device_id,
  214. {"fallback_keys": fallback_key2},
  215. )
  216. )
  217. res = self.get_success(
  218. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  219. )
  220. self.assertEqual(res, ["alg1"])
  221. # if the user uploads a one-time key, the next claim should fetch the
  222. # one-time key, and then go back to the fallback
  223. self.get_success(
  224. self.handler.upload_keys_for_user(
  225. local_user, device_id, {"one_time_keys": otk}
  226. )
  227. )
  228. res = self.get_success(
  229. self.handler.claim_one_time_keys(
  230. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  231. )
  232. )
  233. self.assertEqual(
  234. res,
  235. {"failures": {}, "one_time_keys": {local_user: {device_id: otk}}},
  236. )
  237. res = self.get_success(
  238. self.handler.claim_one_time_keys(
  239. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  240. )
  241. )
  242. self.assertEqual(
  243. res,
  244. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key2}}},
  245. )
  246. # using the unstable prefix should also set the fallback key
  247. self.get_success(
  248. self.handler.upload_keys_for_user(
  249. local_user,
  250. device_id,
  251. {"org.matrix.msc2732.fallback_keys": fallback_key3},
  252. )
  253. )
  254. res = self.get_success(
  255. self.handler.claim_one_time_keys(
  256. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  257. )
  258. )
  259. self.assertEqual(
  260. res,
  261. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key3}}},
  262. )
  263. def test_replace_master_key(self) -> None:
  264. """uploading a new signing key should make the old signing key unavailable"""
  265. local_user = "@boris:" + self.hs.hostname
  266. keys1 = {
  267. "master_key": {
  268. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  269. "user_id": local_user,
  270. "usage": ["master"],
  271. "keys": {
  272. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  273. },
  274. }
  275. }
  276. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  277. keys2 = {
  278. "master_key": {
  279. # private key: 4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs
  280. "user_id": local_user,
  281. "usage": ["master"],
  282. "keys": {
  283. "ed25519:Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw": "Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw"
  284. },
  285. }
  286. }
  287. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys2))
  288. devices = self.get_success(
  289. self.handler.query_devices(
  290. {"device_keys": {local_user: []}}, 0, local_user, "device123"
  291. )
  292. )
  293. self.assertDictEqual(devices["master_keys"], {local_user: keys2["master_key"]})
  294. def test_reupload_signatures(self) -> None:
  295. """re-uploading a signature should not fail"""
  296. local_user = "@boris:" + self.hs.hostname
  297. keys1 = {
  298. "master_key": {
  299. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  300. "user_id": local_user,
  301. "usage": ["master"],
  302. "keys": {
  303. "ed25519:EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ": "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ"
  304. },
  305. },
  306. "self_signing_key": {
  307. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  308. "user_id": local_user,
  309. "usage": ["self_signing"],
  310. "keys": {
  311. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  312. },
  313. },
  314. }
  315. master_signing_key = key.decode_signing_key_base64(
  316. "ed25519",
  317. "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ",
  318. "HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8",
  319. )
  320. sign.sign_json(keys1["self_signing_key"], local_user, master_signing_key)
  321. signing_key = key.decode_signing_key_base64(
  322. "ed25519",
  323. "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk",
  324. "2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0",
  325. )
  326. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  327. # upload two device keys, which will be signed later by the self-signing key
  328. device_key_1 = {
  329. "user_id": local_user,
  330. "device_id": "abc",
  331. "algorithms": [
  332. "m.olm.curve25519-aes-sha2",
  333. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  334. ],
  335. "keys": {
  336. "ed25519:abc": "base64+ed25519+key",
  337. "curve25519:abc": "base64+curve25519+key",
  338. },
  339. "signatures": {local_user: {"ed25519:abc": "base64+signature"}},
  340. }
  341. device_key_2 = {
  342. "user_id": local_user,
  343. "device_id": "def",
  344. "algorithms": [
  345. "m.olm.curve25519-aes-sha2",
  346. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  347. ],
  348. "keys": {
  349. "ed25519:def": "base64+ed25519+key",
  350. "curve25519:def": "base64+curve25519+key",
  351. },
  352. "signatures": {local_user: {"ed25519:def": "base64+signature"}},
  353. }
  354. self.get_success(
  355. self.handler.upload_keys_for_user(
  356. local_user, "abc", {"device_keys": device_key_1}
  357. )
  358. )
  359. self.get_success(
  360. self.handler.upload_keys_for_user(
  361. local_user, "def", {"device_keys": device_key_2}
  362. )
  363. )
  364. # sign the first device key and upload it
  365. del device_key_1["signatures"]
  366. sign.sign_json(device_key_1, local_user, signing_key)
  367. self.get_success(
  368. self.handler.upload_signatures_for_device_keys(
  369. local_user, {local_user: {"abc": device_key_1}}
  370. )
  371. )
  372. # sign the second device key and upload both device keys. The server
  373. # should ignore the first device key since it already has a valid
  374. # signature for it
  375. del device_key_2["signatures"]
  376. sign.sign_json(device_key_2, local_user, signing_key)
  377. self.get_success(
  378. self.handler.upload_signatures_for_device_keys(
  379. local_user, {local_user: {"abc": device_key_1, "def": device_key_2}}
  380. )
  381. )
  382. device_key_1["signatures"][local_user]["ed25519:abc"] = "base64+signature"
  383. device_key_2["signatures"][local_user]["ed25519:def"] = "base64+signature"
  384. devices = self.get_success(
  385. self.handler.query_devices(
  386. {"device_keys": {local_user: []}}, 0, local_user, "device123"
  387. )
  388. )
  389. del devices["device_keys"][local_user]["abc"]["unsigned"]
  390. del devices["device_keys"][local_user]["def"]["unsigned"]
  391. self.assertDictEqual(devices["device_keys"][local_user]["abc"], device_key_1)
  392. self.assertDictEqual(devices["device_keys"][local_user]["def"], device_key_2)
  393. def test_self_signing_key_doesnt_show_up_as_device(self) -> None:
  394. """signing keys should be hidden when fetching a user's devices"""
  395. local_user = "@boris:" + self.hs.hostname
  396. keys1 = {
  397. "master_key": {
  398. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  399. "user_id": local_user,
  400. "usage": ["master"],
  401. "keys": {
  402. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  403. },
  404. }
  405. }
  406. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  407. e = self.get_failure(
  408. self.hs.get_device_handler().check_device_registered(
  409. user_id=local_user,
  410. device_id="nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk",
  411. initial_device_display_name="new display name",
  412. ),
  413. SynapseError,
  414. )
  415. res = e.value.code
  416. self.assertEqual(res, 400)
  417. res = self.get_success(self.handler.query_local_devices({local_user: None}))
  418. self.assertDictEqual(res, {local_user: {}})
  419. def test_upload_signatures(self) -> None:
  420. """should check signatures that are uploaded"""
  421. # set up a user with cross-signing keys and a device. This user will
  422. # try uploading signatures
  423. local_user = "@boris:" + self.hs.hostname
  424. device_id = "xyz"
  425. # private key: OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA
  426. device_pubkey = "NnHhnqiMFQkq969szYkooLaBAXW244ZOxgukCvm2ZeY"
  427. device_key = {
  428. "user_id": local_user,
  429. "device_id": device_id,
  430. "algorithms": [
  431. "m.olm.curve25519-aes-sha2",
  432. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  433. ],
  434. "keys": {"curve25519:xyz": "curve25519+key", "ed25519:xyz": device_pubkey},
  435. "signatures": {local_user: {"ed25519:xyz": "something"}},
  436. }
  437. device_signing_key = key.decode_signing_key_base64(
  438. "ed25519", "xyz", "OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA"
  439. )
  440. self.get_success(
  441. self.handler.upload_keys_for_user(
  442. local_user, device_id, {"device_keys": device_key}
  443. )
  444. )
  445. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  446. master_pubkey = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  447. master_key = {
  448. "user_id": local_user,
  449. "usage": ["master"],
  450. "keys": {"ed25519:" + master_pubkey: master_pubkey},
  451. }
  452. master_signing_key = key.decode_signing_key_base64(
  453. "ed25519", master_pubkey, "2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0"
  454. )
  455. usersigning_pubkey = "Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw"
  456. usersigning_key = {
  457. # private key: 4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs
  458. "user_id": local_user,
  459. "usage": ["user_signing"],
  460. "keys": {"ed25519:" + usersigning_pubkey: usersigning_pubkey},
  461. }
  462. usersigning_signing_key = key.decode_signing_key_base64(
  463. "ed25519", usersigning_pubkey, "4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs"
  464. )
  465. sign.sign_json(usersigning_key, local_user, master_signing_key)
  466. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  467. selfsigning_pubkey = "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ"
  468. selfsigning_key = {
  469. "user_id": local_user,
  470. "usage": ["self_signing"],
  471. "keys": {"ed25519:" + selfsigning_pubkey: selfsigning_pubkey},
  472. }
  473. selfsigning_signing_key = key.decode_signing_key_base64(
  474. "ed25519", selfsigning_pubkey, "HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8"
  475. )
  476. sign.sign_json(selfsigning_key, local_user, master_signing_key)
  477. cross_signing_keys = {
  478. "master_key": master_key,
  479. "user_signing_key": usersigning_key,
  480. "self_signing_key": selfsigning_key,
  481. }
  482. self.get_success(
  483. self.handler.upload_signing_keys_for_user(local_user, cross_signing_keys)
  484. )
  485. # set up another user with a master key. This user will be signed by
  486. # the first user
  487. other_user = "@otherboris:" + self.hs.hostname
  488. other_master_pubkey = "fHZ3NPiKxoLQm5OoZbKa99SYxprOjNs4TwJUKP+twCM"
  489. other_master_key = {
  490. # private key: oyw2ZUx0O4GifbfFYM0nQvj9CL0b8B7cyN4FprtK8OI
  491. "user_id": other_user,
  492. "usage": ["master"],
  493. "keys": {"ed25519:" + other_master_pubkey: other_master_pubkey},
  494. }
  495. self.get_success(
  496. self.handler.upload_signing_keys_for_user(
  497. other_user, {"master_key": other_master_key}
  498. )
  499. )
  500. # test various signature failures (see below)
  501. ret = self.get_success(
  502. self.handler.upload_signatures_for_device_keys(
  503. local_user,
  504. {
  505. local_user: {
  506. # fails because the signature is invalid
  507. # should fail with INVALID_SIGNATURE
  508. device_id: {
  509. "user_id": local_user,
  510. "device_id": device_id,
  511. "algorithms": [
  512. "m.olm.curve25519-aes-sha2",
  513. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  514. ],
  515. "keys": {
  516. "curve25519:xyz": "curve25519+key",
  517. # private key: OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA
  518. "ed25519:xyz": device_pubkey,
  519. },
  520. "signatures": {
  521. local_user: {
  522. "ed25519:" + selfsigning_pubkey: "something"
  523. }
  524. },
  525. },
  526. # fails because device is unknown
  527. # should fail with NOT_FOUND
  528. "unknown": {
  529. "user_id": local_user,
  530. "device_id": "unknown",
  531. "signatures": {
  532. local_user: {
  533. "ed25519:" + selfsigning_pubkey: "something"
  534. }
  535. },
  536. },
  537. # fails because the signature is invalid
  538. # should fail with INVALID_SIGNATURE
  539. master_pubkey: {
  540. "user_id": local_user,
  541. "usage": ["master"],
  542. "keys": {"ed25519:" + master_pubkey: master_pubkey},
  543. "signatures": {
  544. local_user: {"ed25519:" + device_pubkey: "something"}
  545. },
  546. },
  547. },
  548. other_user: {
  549. # fails because the device is not the user's master-signing key
  550. # should fail with NOT_FOUND
  551. "unknown": {
  552. "user_id": other_user,
  553. "device_id": "unknown",
  554. "signatures": {
  555. local_user: {
  556. "ed25519:" + usersigning_pubkey: "something"
  557. }
  558. },
  559. },
  560. other_master_pubkey: {
  561. # fails because the key doesn't match what the server has
  562. # should fail with UNKNOWN
  563. "user_id": other_user,
  564. "usage": ["master"],
  565. "keys": {
  566. "ed25519:" + other_master_pubkey: other_master_pubkey
  567. },
  568. "something": "random",
  569. "signatures": {
  570. local_user: {
  571. "ed25519:" + usersigning_pubkey: "something"
  572. }
  573. },
  574. },
  575. },
  576. },
  577. )
  578. )
  579. user_failures = ret["failures"][local_user]
  580. self.assertEqual(user_failures[device_id]["errcode"], Codes.INVALID_SIGNATURE)
  581. self.assertEqual(
  582. user_failures[master_pubkey]["errcode"], Codes.INVALID_SIGNATURE
  583. )
  584. self.assertEqual(user_failures["unknown"]["errcode"], Codes.NOT_FOUND)
  585. other_user_failures = ret["failures"][other_user]
  586. self.assertEqual(other_user_failures["unknown"]["errcode"], Codes.NOT_FOUND)
  587. self.assertEqual(
  588. other_user_failures[other_master_pubkey]["errcode"], Codes.UNKNOWN
  589. )
  590. # test successful signatures
  591. del device_key["signatures"]
  592. sign.sign_json(device_key, local_user, selfsigning_signing_key)
  593. sign.sign_json(master_key, local_user, device_signing_key)
  594. sign.sign_json(other_master_key, local_user, usersigning_signing_key)
  595. ret = self.get_success(
  596. self.handler.upload_signatures_for_device_keys(
  597. local_user,
  598. {
  599. local_user: {device_id: device_key, master_pubkey: master_key},
  600. other_user: {other_master_pubkey: other_master_key},
  601. },
  602. )
  603. )
  604. self.assertEqual(ret["failures"], {})
  605. # fetch the signed keys/devices and make sure that the signatures are there
  606. ret = self.get_success(
  607. self.handler.query_devices(
  608. {"device_keys": {local_user: [], other_user: []}},
  609. 0,
  610. local_user,
  611. "device123",
  612. )
  613. )
  614. self.assertEqual(
  615. ret["device_keys"][local_user]["xyz"]["signatures"][local_user][
  616. "ed25519:" + selfsigning_pubkey
  617. ],
  618. device_key["signatures"][local_user]["ed25519:" + selfsigning_pubkey],
  619. )
  620. self.assertEqual(
  621. ret["master_keys"][local_user]["signatures"][local_user][
  622. "ed25519:" + device_id
  623. ],
  624. master_key["signatures"][local_user]["ed25519:" + device_id],
  625. )
  626. self.assertEqual(
  627. ret["master_keys"][other_user]["signatures"][local_user][
  628. "ed25519:" + usersigning_pubkey
  629. ],
  630. other_master_key["signatures"][local_user]["ed25519:" + usersigning_pubkey],
  631. )
  632. def test_query_devices_remote_no_sync(self) -> None:
  633. """Tests that querying keys for a remote user that we don't share a room
  634. with returns the cross signing keys correctly.
  635. """
  636. remote_user_id = "@test:other"
  637. local_user_id = "@test:test"
  638. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  639. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  640. self.hs.get_federation_client().query_client_keys = mock.Mock(
  641. return_value=defer.succeed(
  642. {
  643. "device_keys": {remote_user_id: {}},
  644. "master_keys": {
  645. remote_user_id: {
  646. "user_id": remote_user_id,
  647. "usage": ["master"],
  648. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  649. },
  650. },
  651. "self_signing_keys": {
  652. remote_user_id: {
  653. "user_id": remote_user_id,
  654. "usage": ["self_signing"],
  655. "keys": {
  656. "ed25519:"
  657. + remote_self_signing_key: remote_self_signing_key
  658. },
  659. }
  660. },
  661. }
  662. )
  663. )
  664. e2e_handler = self.hs.get_e2e_keys_handler()
  665. query_result = self.get_success(
  666. e2e_handler.query_devices(
  667. {
  668. "device_keys": {remote_user_id: []},
  669. },
  670. timeout=10,
  671. from_user_id=local_user_id,
  672. from_device_id="some_device_id",
  673. )
  674. )
  675. self.assertEqual(query_result["failures"], {})
  676. self.assertEqual(
  677. query_result["master_keys"],
  678. {
  679. remote_user_id: {
  680. "user_id": remote_user_id,
  681. "usage": ["master"],
  682. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  683. },
  684. },
  685. )
  686. self.assertEqual(
  687. query_result["self_signing_keys"],
  688. {
  689. remote_user_id: {
  690. "user_id": remote_user_id,
  691. "usage": ["self_signing"],
  692. "keys": {
  693. "ed25519:" + remote_self_signing_key: remote_self_signing_key
  694. },
  695. }
  696. },
  697. )
  698. def test_query_devices_remote_sync(self) -> None:
  699. """Tests that querying keys for a remote user that we share a room with,
  700. but haven't yet fetched the keys for, returns the cross signing keys
  701. correctly.
  702. """
  703. remote_user_id = "@test:other"
  704. local_user_id = "@test:test"
  705. # Pretend we're sharing a room with the user we're querying. If not,
  706. # `_query_devices_for_destination` will return early.
  707. self.store.get_rooms_for_user = mock.Mock(
  708. return_value=defer.succeed({"some_room_id"})
  709. )
  710. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  711. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  712. self.hs.get_federation_client().query_user_devices = mock.Mock(
  713. return_value=defer.succeed(
  714. {
  715. "user_id": remote_user_id,
  716. "stream_id": 1,
  717. "devices": [],
  718. "master_key": {
  719. "user_id": remote_user_id,
  720. "usage": ["master"],
  721. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  722. },
  723. "self_signing_key": {
  724. "user_id": remote_user_id,
  725. "usage": ["self_signing"],
  726. "keys": {
  727. "ed25519:"
  728. + remote_self_signing_key: remote_self_signing_key
  729. },
  730. },
  731. }
  732. )
  733. )
  734. e2e_handler = self.hs.get_e2e_keys_handler()
  735. query_result = self.get_success(
  736. e2e_handler.query_devices(
  737. {
  738. "device_keys": {remote_user_id: []},
  739. },
  740. timeout=10,
  741. from_user_id=local_user_id,
  742. from_device_id="some_device_id",
  743. )
  744. )
  745. self.assertEqual(query_result["failures"], {})
  746. self.assertEqual(
  747. query_result["master_keys"],
  748. {
  749. remote_user_id: {
  750. "user_id": remote_user_id,
  751. "usage": ["master"],
  752. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  753. }
  754. },
  755. )
  756. self.assertEqual(
  757. query_result["self_signing_keys"],
  758. {
  759. remote_user_id: {
  760. "user_id": remote_user_id,
  761. "usage": ["self_signing"],
  762. "keys": {
  763. "ed25519:" + remote_self_signing_key: remote_self_signing_key
  764. },
  765. }
  766. },
  767. )
  768. @parameterized.expand(
  769. [
  770. # The remote homeserver's response indicates that this user has 0/1/2 devices.
  771. ([],),
  772. (["device_1"],),
  773. (["device_1", "device_2"],),
  774. ]
  775. )
  776. def test_query_all_devices_caches_result(self, device_ids: Iterable[str]) -> None:
  777. """Test that requests for all of a remote user's devices are cached.
  778. We do this by asserting that only one call over federation was made, and that
  779. the two queries to the local homeserver produce the same response.
  780. """
  781. local_user_id = "@test:test"
  782. remote_user_id = "@test:other"
  783. request_body: JsonDict = {"device_keys": {remote_user_id: []}}
  784. response_devices = [
  785. {
  786. "device_id": device_id,
  787. "keys": {
  788. "algorithms": ["dummy"],
  789. "device_id": device_id,
  790. "keys": {f"dummy:{device_id}": "dummy"},
  791. "signatures": {device_id: {f"dummy:{device_id}": "dummy"}},
  792. "unsigned": {},
  793. "user_id": "@test:other",
  794. },
  795. }
  796. for device_id in device_ids
  797. ]
  798. response_body = {
  799. "devices": response_devices,
  800. "user_id": remote_user_id,
  801. "stream_id": 12345, # an integer, according to the spec
  802. }
  803. e2e_handler = self.hs.get_e2e_keys_handler()
  804. # Pretend we're sharing a room with the user we're querying. If not,
  805. # `_query_devices_for_destination` will return early.
  806. mock_get_rooms = mock.patch.object(
  807. self.store,
  808. "get_rooms_for_user",
  809. new_callable=mock.MagicMock,
  810. return_value=make_awaitable(["some_room_id"]),
  811. )
  812. mock_request = mock.patch.object(
  813. self.hs.get_federation_client(),
  814. "query_user_devices",
  815. new_callable=mock.MagicMock,
  816. return_value=make_awaitable(response_body),
  817. )
  818. with mock_get_rooms, mock_request as mocked_federation_request:
  819. # Make the first query and sanity check it succeeds.
  820. response_1 = self.get_success(
  821. e2e_handler.query_devices(
  822. request_body,
  823. timeout=10,
  824. from_user_id=local_user_id,
  825. from_device_id="some_device_id",
  826. )
  827. )
  828. self.assertEqual(response_1["failures"], {})
  829. # We should have made a federation request to do so.
  830. mocked_federation_request.assert_called_once()
  831. # Reset the mock so we can prove we don't make a second federation request.
  832. mocked_federation_request.reset_mock()
  833. # Repeat the query.
  834. response_2 = self.get_success(
  835. e2e_handler.query_devices(
  836. request_body,
  837. timeout=10,
  838. from_user_id=local_user_id,
  839. from_device_id="some_device_id",
  840. )
  841. )
  842. self.assertEqual(response_2["failures"], {})
  843. # We should not have made a second federation request.
  844. mocked_federation_request.assert_not_called()
  845. # The two requests to the local homeserver should be identical.
  846. self.assertEqual(response_1, response_2)