test_e2e_keys.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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.test.proto_helpers import MemoryReactor
  21. from synapse.api.constants import RoomEncryptionAlgorithms
  22. from synapse.api.errors import Codes, SynapseError
  23. from synapse.appservice import ApplicationService
  24. from synapse.handlers.device import DeviceHandler
  25. from synapse.server import HomeServer
  26. from synapse.storage.databases.main.appservice import _make_exclusive_regex
  27. from synapse.types import JsonDict
  28. from synapse.util import Clock
  29. from tests import unittest
  30. from tests.test_utils import make_awaitable
  31. from tests.unittest import override_config
  32. class E2eKeysHandlerTestCase(unittest.HomeserverTestCase):
  33. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  34. self.appservice_api = mock.Mock()
  35. return self.setup_test_homeserver(
  36. federation_client=mock.Mock(), application_service_api=self.appservice_api
  37. )
  38. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  39. self.handler = hs.get_e2e_keys_handler()
  40. self.store = self.hs.get_datastores().main
  41. def test_query_local_devices_no_devices(self) -> None:
  42. """If the user has no devices, we expect an empty list."""
  43. local_user = "@boris:" + self.hs.hostname
  44. res = self.get_success(self.handler.query_local_devices({local_user: None}))
  45. self.assertDictEqual(res, {local_user: {}})
  46. def test_reupload_one_time_keys(self) -> None:
  47. """we should be able to re-upload the same keys"""
  48. local_user = "@boris:" + self.hs.hostname
  49. device_id = "xyz"
  50. keys: JsonDict = {
  51. "alg1:k1": "key1",
  52. "alg2:k2": {"key": "key2", "signatures": {"k1": "sig1"}},
  53. "alg2:k3": {"key": "key3"},
  54. }
  55. # Note that "signed_curve25519" is always returned in key count responses. This is necessary until
  56. # https://github.com/matrix-org/matrix-doc/issues/3298 is fixed.
  57. res = self.get_success(
  58. self.handler.upload_keys_for_user(
  59. local_user, device_id, {"one_time_keys": keys}
  60. )
  61. )
  62. self.assertDictEqual(
  63. res, {"one_time_key_counts": {"alg1": 1, "alg2": 2, "signed_curve25519": 0}}
  64. )
  65. # we should be able to change the signature without a problem
  66. keys["alg2:k2"]["signatures"]["k1"] = "sig2"
  67. res = self.get_success(
  68. self.handler.upload_keys_for_user(
  69. local_user, device_id, {"one_time_keys": keys}
  70. )
  71. )
  72. self.assertDictEqual(
  73. res, {"one_time_key_counts": {"alg1": 1, "alg2": 2, "signed_curve25519": 0}}
  74. )
  75. def test_change_one_time_keys(self) -> None:
  76. """attempts to change one-time-keys should be rejected"""
  77. local_user = "@boris:" + self.hs.hostname
  78. device_id = "xyz"
  79. keys = {
  80. "alg1:k1": "key1",
  81. "alg2:k2": {"key": "key2", "signatures": {"k1": "sig1"}},
  82. "alg2:k3": {"key": "key3"},
  83. }
  84. res = self.get_success(
  85. self.handler.upload_keys_for_user(
  86. local_user, device_id, {"one_time_keys": keys}
  87. )
  88. )
  89. self.assertDictEqual(
  90. res, {"one_time_key_counts": {"alg1": 1, "alg2": 2, "signed_curve25519": 0}}
  91. )
  92. # Error when changing string key
  93. self.get_failure(
  94. self.handler.upload_keys_for_user(
  95. local_user, device_id, {"one_time_keys": {"alg1:k1": "key2"}}
  96. ),
  97. SynapseError,
  98. )
  99. # Error when replacing dict key with string
  100. self.get_failure(
  101. self.handler.upload_keys_for_user(
  102. local_user, device_id, {"one_time_keys": {"alg2:k3": "key2"}}
  103. ),
  104. SynapseError,
  105. )
  106. # Error when replacing string key with dict
  107. self.get_failure(
  108. self.handler.upload_keys_for_user(
  109. local_user,
  110. device_id,
  111. {"one_time_keys": {"alg1:k1": {"key": "key"}}},
  112. ),
  113. SynapseError,
  114. )
  115. # Error when replacing dict key
  116. self.get_failure(
  117. self.handler.upload_keys_for_user(
  118. local_user,
  119. device_id,
  120. {
  121. "one_time_keys": {
  122. "alg2:k2": {"key": "key3", "signatures": {"k1": "sig1"}}
  123. }
  124. },
  125. ),
  126. SynapseError,
  127. )
  128. def test_claim_one_time_key(self) -> None:
  129. local_user = "@boris:" + self.hs.hostname
  130. device_id = "xyz"
  131. keys = {"alg1:k1": "key1"}
  132. res = self.get_success(
  133. self.handler.upload_keys_for_user(
  134. local_user, device_id, {"one_time_keys": keys}
  135. )
  136. )
  137. self.assertDictEqual(
  138. res, {"one_time_key_counts": {"alg1": 1, "signed_curve25519": 0}}
  139. )
  140. res2 = self.get_success(
  141. self.handler.claim_one_time_keys(
  142. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  143. )
  144. )
  145. self.assertEqual(
  146. res2,
  147. {
  148. "failures": {},
  149. "one_time_keys": {local_user: {device_id: {"alg1:k1": "key1"}}},
  150. },
  151. )
  152. def test_fallback_key(self) -> None:
  153. local_user = "@boris:" + self.hs.hostname
  154. device_id = "xyz"
  155. fallback_key = {"alg1:k1": "fallback_key1"}
  156. fallback_key2 = {"alg1:k2": "fallback_key2"}
  157. fallback_key3 = {"alg1:k2": "fallback_key3"}
  158. otk = {"alg1:k2": "key2"}
  159. # we shouldn't have any unused fallback keys yet
  160. res = self.get_success(
  161. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  162. )
  163. self.assertEqual(res, [])
  164. self.get_success(
  165. self.handler.upload_keys_for_user(
  166. local_user,
  167. device_id,
  168. {"fallback_keys": fallback_key},
  169. )
  170. )
  171. # we should now have an unused alg1 key
  172. fallback_res = self.get_success(
  173. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  174. )
  175. self.assertEqual(fallback_res, ["alg1"])
  176. # claiming an OTK when no OTKs are available should return the fallback
  177. # key
  178. claim_res = self.get_success(
  179. self.handler.claim_one_time_keys(
  180. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  181. )
  182. )
  183. self.assertEqual(
  184. claim_res,
  185. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key}}},
  186. )
  187. # we shouldn't have any unused fallback keys again
  188. unused_res = self.get_success(
  189. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  190. )
  191. self.assertEqual(unused_res, [])
  192. # claiming an OTK again should return the same fallback key
  193. claim_res = self.get_success(
  194. self.handler.claim_one_time_keys(
  195. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  196. )
  197. )
  198. self.assertEqual(
  199. claim_res,
  200. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key}}},
  201. )
  202. # re-uploading the same fallback key should still result in no unused fallback
  203. # keys
  204. self.get_success(
  205. self.handler.upload_keys_for_user(
  206. local_user,
  207. device_id,
  208. {"fallback_keys": fallback_key},
  209. )
  210. )
  211. unused_res = self.get_success(
  212. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  213. )
  214. self.assertEqual(unused_res, [])
  215. # uploading a new fallback key should result in an unused fallback key
  216. self.get_success(
  217. self.handler.upload_keys_for_user(
  218. local_user,
  219. device_id,
  220. {"fallback_keys": fallback_key2},
  221. )
  222. )
  223. unused_res = self.get_success(
  224. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  225. )
  226. self.assertEqual(unused_res, ["alg1"])
  227. # if the user uploads a one-time key, the next claim should fetch the
  228. # one-time key, and then go back to the fallback
  229. self.get_success(
  230. self.handler.upload_keys_for_user(
  231. local_user, device_id, {"one_time_keys": otk}
  232. )
  233. )
  234. claim_res = self.get_success(
  235. self.handler.claim_one_time_keys(
  236. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  237. )
  238. )
  239. self.assertEqual(
  240. claim_res,
  241. {"failures": {}, "one_time_keys": {local_user: {device_id: otk}}},
  242. )
  243. claim_res = self.get_success(
  244. self.handler.claim_one_time_keys(
  245. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  246. )
  247. )
  248. self.assertEqual(
  249. claim_res,
  250. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key2}}},
  251. )
  252. # using the unstable prefix should also set the fallback key
  253. self.get_success(
  254. self.handler.upload_keys_for_user(
  255. local_user,
  256. device_id,
  257. {"org.matrix.msc2732.fallback_keys": fallback_key3},
  258. )
  259. )
  260. claim_res = self.get_success(
  261. self.handler.claim_one_time_keys(
  262. {"one_time_keys": {local_user: {device_id: "alg1"}}}, timeout=None
  263. )
  264. )
  265. self.assertEqual(
  266. claim_res,
  267. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key3}}},
  268. )
  269. def test_replace_master_key(self) -> None:
  270. """uploading a new signing key should make the old signing key unavailable"""
  271. local_user = "@boris:" + self.hs.hostname
  272. keys1 = {
  273. "master_key": {
  274. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  275. "user_id": local_user,
  276. "usage": ["master"],
  277. "keys": {
  278. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  279. },
  280. }
  281. }
  282. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  283. keys2 = {
  284. "master_key": {
  285. # private key: 4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs
  286. "user_id": local_user,
  287. "usage": ["master"],
  288. "keys": {
  289. "ed25519:Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw": "Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw"
  290. },
  291. }
  292. }
  293. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys2))
  294. devices = self.get_success(
  295. self.handler.query_devices(
  296. {"device_keys": {local_user: []}}, 0, local_user, "device123"
  297. )
  298. )
  299. self.assertDictEqual(devices["master_keys"], {local_user: keys2["master_key"]})
  300. def test_reupload_signatures(self) -> None:
  301. """re-uploading a signature should not fail"""
  302. local_user = "@boris:" + self.hs.hostname
  303. keys1 = {
  304. "master_key": {
  305. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  306. "user_id": local_user,
  307. "usage": ["master"],
  308. "keys": {
  309. "ed25519:EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ": "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ"
  310. },
  311. },
  312. "self_signing_key": {
  313. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  314. "user_id": local_user,
  315. "usage": ["self_signing"],
  316. "keys": {
  317. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  318. },
  319. },
  320. }
  321. master_signing_key = key.decode_signing_key_base64(
  322. "ed25519",
  323. "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ",
  324. "HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8",
  325. )
  326. sign.sign_json(keys1["self_signing_key"], local_user, master_signing_key)
  327. signing_key = key.decode_signing_key_base64(
  328. "ed25519",
  329. "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk",
  330. "2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0",
  331. )
  332. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  333. # upload two device keys, which will be signed later by the self-signing key
  334. device_key_1: JsonDict = {
  335. "user_id": local_user,
  336. "device_id": "abc",
  337. "algorithms": [
  338. "m.olm.curve25519-aes-sha2",
  339. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  340. ],
  341. "keys": {
  342. "ed25519:abc": "base64+ed25519+key",
  343. "curve25519:abc": "base64+curve25519+key",
  344. },
  345. "signatures": {local_user: {"ed25519:abc": "base64+signature"}},
  346. }
  347. device_key_2: JsonDict = {
  348. "user_id": local_user,
  349. "device_id": "def",
  350. "algorithms": [
  351. "m.olm.curve25519-aes-sha2",
  352. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  353. ],
  354. "keys": {
  355. "ed25519:def": "base64+ed25519+key",
  356. "curve25519:def": "base64+curve25519+key",
  357. },
  358. "signatures": {local_user: {"ed25519:def": "base64+signature"}},
  359. }
  360. self.get_success(
  361. self.handler.upload_keys_for_user(
  362. local_user, "abc", {"device_keys": device_key_1}
  363. )
  364. )
  365. self.get_success(
  366. self.handler.upload_keys_for_user(
  367. local_user, "def", {"device_keys": device_key_2}
  368. )
  369. )
  370. # sign the first device key and upload it
  371. del device_key_1["signatures"]
  372. sign.sign_json(device_key_1, local_user, signing_key)
  373. self.get_success(
  374. self.handler.upload_signatures_for_device_keys(
  375. local_user, {local_user: {"abc": device_key_1}}
  376. )
  377. )
  378. # sign the second device key and upload both device keys. The server
  379. # should ignore the first device key since it already has a valid
  380. # signature for it
  381. del device_key_2["signatures"]
  382. sign.sign_json(device_key_2, local_user, signing_key)
  383. self.get_success(
  384. self.handler.upload_signatures_for_device_keys(
  385. local_user, {local_user: {"abc": device_key_1, "def": device_key_2}}
  386. )
  387. )
  388. device_key_1["signatures"][local_user]["ed25519:abc"] = "base64+signature"
  389. device_key_2["signatures"][local_user]["ed25519:def"] = "base64+signature"
  390. devices = self.get_success(
  391. self.handler.query_devices(
  392. {"device_keys": {local_user: []}}, 0, local_user, "device123"
  393. )
  394. )
  395. del devices["device_keys"][local_user]["abc"]["unsigned"]
  396. del devices["device_keys"][local_user]["def"]["unsigned"]
  397. self.assertDictEqual(devices["device_keys"][local_user]["abc"], device_key_1)
  398. self.assertDictEqual(devices["device_keys"][local_user]["def"], device_key_2)
  399. def test_self_signing_key_doesnt_show_up_as_device(self) -> None:
  400. """signing keys should be hidden when fetching a user's devices"""
  401. local_user = "@boris:" + self.hs.hostname
  402. keys1 = {
  403. "master_key": {
  404. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  405. "user_id": local_user,
  406. "usage": ["master"],
  407. "keys": {
  408. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  409. },
  410. }
  411. }
  412. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  413. device_handler = self.hs.get_device_handler()
  414. assert isinstance(device_handler, DeviceHandler)
  415. e = self.get_failure(
  416. device_handler.check_device_registered(
  417. user_id=local_user,
  418. device_id="nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk",
  419. initial_device_display_name="new display name",
  420. ),
  421. SynapseError,
  422. )
  423. res = e.value.code
  424. self.assertEqual(res, 400)
  425. query_res = self.get_success(
  426. self.handler.query_local_devices({local_user: None})
  427. )
  428. self.assertDictEqual(query_res, {local_user: {}})
  429. def test_upload_signatures(self) -> None:
  430. """should check signatures that are uploaded"""
  431. # set up a user with cross-signing keys and a device. This user will
  432. # try uploading signatures
  433. local_user = "@boris:" + self.hs.hostname
  434. device_id = "xyz"
  435. # private key: OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA
  436. device_pubkey = "NnHhnqiMFQkq969szYkooLaBAXW244ZOxgukCvm2ZeY"
  437. device_key: JsonDict = {
  438. "user_id": local_user,
  439. "device_id": device_id,
  440. "algorithms": [
  441. "m.olm.curve25519-aes-sha2",
  442. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  443. ],
  444. "keys": {"curve25519:xyz": "curve25519+key", "ed25519:xyz": device_pubkey},
  445. "signatures": {local_user: {"ed25519:xyz": "something"}},
  446. }
  447. device_signing_key = key.decode_signing_key_base64(
  448. "ed25519", "xyz", "OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA"
  449. )
  450. self.get_success(
  451. self.handler.upload_keys_for_user(
  452. local_user, device_id, {"device_keys": device_key}
  453. )
  454. )
  455. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  456. master_pubkey = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  457. master_key: JsonDict = {
  458. "user_id": local_user,
  459. "usage": ["master"],
  460. "keys": {"ed25519:" + master_pubkey: master_pubkey},
  461. }
  462. master_signing_key = key.decode_signing_key_base64(
  463. "ed25519", master_pubkey, "2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0"
  464. )
  465. usersigning_pubkey = "Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw"
  466. usersigning_key = {
  467. # private key: 4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs
  468. "user_id": local_user,
  469. "usage": ["user_signing"],
  470. "keys": {"ed25519:" + usersigning_pubkey: usersigning_pubkey},
  471. }
  472. usersigning_signing_key = key.decode_signing_key_base64(
  473. "ed25519", usersigning_pubkey, "4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs"
  474. )
  475. sign.sign_json(usersigning_key, local_user, master_signing_key)
  476. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  477. selfsigning_pubkey = "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ"
  478. selfsigning_key = {
  479. "user_id": local_user,
  480. "usage": ["self_signing"],
  481. "keys": {"ed25519:" + selfsigning_pubkey: selfsigning_pubkey},
  482. }
  483. selfsigning_signing_key = key.decode_signing_key_base64(
  484. "ed25519", selfsigning_pubkey, "HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8"
  485. )
  486. sign.sign_json(selfsigning_key, local_user, master_signing_key)
  487. cross_signing_keys = {
  488. "master_key": master_key,
  489. "user_signing_key": usersigning_key,
  490. "self_signing_key": selfsigning_key,
  491. }
  492. self.get_success(
  493. self.handler.upload_signing_keys_for_user(local_user, cross_signing_keys)
  494. )
  495. # set up another user with a master key. This user will be signed by
  496. # the first user
  497. other_user = "@otherboris:" + self.hs.hostname
  498. other_master_pubkey = "fHZ3NPiKxoLQm5OoZbKa99SYxprOjNs4TwJUKP+twCM"
  499. other_master_key: JsonDict = {
  500. # private key: oyw2ZUx0O4GifbfFYM0nQvj9CL0b8B7cyN4FprtK8OI
  501. "user_id": other_user,
  502. "usage": ["master"],
  503. "keys": {"ed25519:" + other_master_pubkey: other_master_pubkey},
  504. }
  505. self.get_success(
  506. self.handler.upload_signing_keys_for_user(
  507. other_user, {"master_key": other_master_key}
  508. )
  509. )
  510. # test various signature failures (see below)
  511. ret = self.get_success(
  512. self.handler.upload_signatures_for_device_keys(
  513. local_user,
  514. {
  515. local_user: {
  516. # fails because the signature is invalid
  517. # should fail with INVALID_SIGNATURE
  518. device_id: {
  519. "user_id": local_user,
  520. "device_id": device_id,
  521. "algorithms": [
  522. "m.olm.curve25519-aes-sha2",
  523. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  524. ],
  525. "keys": {
  526. "curve25519:xyz": "curve25519+key",
  527. # private key: OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA
  528. "ed25519:xyz": device_pubkey,
  529. },
  530. "signatures": {
  531. local_user: {
  532. "ed25519:" + selfsigning_pubkey: "something"
  533. }
  534. },
  535. },
  536. # fails because device is unknown
  537. # should fail with NOT_FOUND
  538. "unknown": {
  539. "user_id": local_user,
  540. "device_id": "unknown",
  541. "signatures": {
  542. local_user: {
  543. "ed25519:" + selfsigning_pubkey: "something"
  544. }
  545. },
  546. },
  547. # fails because the signature is invalid
  548. # should fail with INVALID_SIGNATURE
  549. master_pubkey: {
  550. "user_id": local_user,
  551. "usage": ["master"],
  552. "keys": {"ed25519:" + master_pubkey: master_pubkey},
  553. "signatures": {
  554. local_user: {"ed25519:" + device_pubkey: "something"}
  555. },
  556. },
  557. },
  558. other_user: {
  559. # fails because the device is not the user's master-signing key
  560. # should fail with NOT_FOUND
  561. "unknown": {
  562. "user_id": other_user,
  563. "device_id": "unknown",
  564. "signatures": {
  565. local_user: {
  566. "ed25519:" + usersigning_pubkey: "something"
  567. }
  568. },
  569. },
  570. other_master_pubkey: {
  571. # fails because the key doesn't match what the server has
  572. # should fail with UNKNOWN
  573. "user_id": other_user,
  574. "usage": ["master"],
  575. "keys": {
  576. "ed25519:" + other_master_pubkey: other_master_pubkey
  577. },
  578. "something": "random",
  579. "signatures": {
  580. local_user: {
  581. "ed25519:" + usersigning_pubkey: "something"
  582. }
  583. },
  584. },
  585. },
  586. },
  587. )
  588. )
  589. user_failures = ret["failures"][local_user]
  590. self.assertEqual(user_failures[device_id]["errcode"], Codes.INVALID_SIGNATURE)
  591. self.assertEqual(
  592. user_failures[master_pubkey]["errcode"], Codes.INVALID_SIGNATURE
  593. )
  594. self.assertEqual(user_failures["unknown"]["errcode"], Codes.NOT_FOUND)
  595. other_user_failures = ret["failures"][other_user]
  596. self.assertEqual(other_user_failures["unknown"]["errcode"], Codes.NOT_FOUND)
  597. self.assertEqual(
  598. other_user_failures[other_master_pubkey]["errcode"], Codes.UNKNOWN
  599. )
  600. # test successful signatures
  601. del device_key["signatures"]
  602. sign.sign_json(device_key, local_user, selfsigning_signing_key)
  603. sign.sign_json(master_key, local_user, device_signing_key)
  604. sign.sign_json(other_master_key, local_user, usersigning_signing_key)
  605. ret = self.get_success(
  606. self.handler.upload_signatures_for_device_keys(
  607. local_user,
  608. {
  609. local_user: {device_id: device_key, master_pubkey: master_key},
  610. other_user: {other_master_pubkey: other_master_key},
  611. },
  612. )
  613. )
  614. self.assertEqual(ret["failures"], {})
  615. # fetch the signed keys/devices and make sure that the signatures are there
  616. ret = self.get_success(
  617. self.handler.query_devices(
  618. {"device_keys": {local_user: [], other_user: []}},
  619. 0,
  620. local_user,
  621. "device123",
  622. )
  623. )
  624. self.assertEqual(
  625. ret["device_keys"][local_user]["xyz"]["signatures"][local_user][
  626. "ed25519:" + selfsigning_pubkey
  627. ],
  628. device_key["signatures"][local_user]["ed25519:" + selfsigning_pubkey],
  629. )
  630. self.assertEqual(
  631. ret["master_keys"][local_user]["signatures"][local_user][
  632. "ed25519:" + device_id
  633. ],
  634. master_key["signatures"][local_user]["ed25519:" + device_id],
  635. )
  636. self.assertEqual(
  637. ret["master_keys"][other_user]["signatures"][local_user][
  638. "ed25519:" + usersigning_pubkey
  639. ],
  640. other_master_key["signatures"][local_user]["ed25519:" + usersigning_pubkey],
  641. )
  642. def test_query_devices_remote_no_sync(self) -> None:
  643. """Tests that querying keys for a remote user that we don't share a room
  644. with returns the cross signing keys correctly.
  645. """
  646. remote_user_id = "@test:other"
  647. local_user_id = "@test:test"
  648. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  649. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  650. self.hs.get_federation_client().query_client_keys = mock.Mock( # type: ignore[assignment]
  651. return_value=make_awaitable(
  652. {
  653. "device_keys": {remote_user_id: {}},
  654. "master_keys": {
  655. remote_user_id: {
  656. "user_id": remote_user_id,
  657. "usage": ["master"],
  658. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  659. },
  660. },
  661. "self_signing_keys": {
  662. remote_user_id: {
  663. "user_id": remote_user_id,
  664. "usage": ["self_signing"],
  665. "keys": {
  666. "ed25519:"
  667. + remote_self_signing_key: remote_self_signing_key
  668. },
  669. }
  670. },
  671. }
  672. )
  673. )
  674. e2e_handler = self.hs.get_e2e_keys_handler()
  675. query_result = self.get_success(
  676. e2e_handler.query_devices(
  677. {
  678. "device_keys": {remote_user_id: []},
  679. },
  680. timeout=10,
  681. from_user_id=local_user_id,
  682. from_device_id="some_device_id",
  683. )
  684. )
  685. self.assertEqual(query_result["failures"], {})
  686. self.assertEqual(
  687. query_result["master_keys"],
  688. {
  689. remote_user_id: {
  690. "user_id": remote_user_id,
  691. "usage": ["master"],
  692. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  693. },
  694. },
  695. )
  696. self.assertEqual(
  697. query_result["self_signing_keys"],
  698. {
  699. remote_user_id: {
  700. "user_id": remote_user_id,
  701. "usage": ["self_signing"],
  702. "keys": {
  703. "ed25519:" + remote_self_signing_key: remote_self_signing_key
  704. },
  705. }
  706. },
  707. )
  708. def test_query_devices_remote_sync(self) -> None:
  709. """Tests that querying keys for a remote user that we share a room with,
  710. but haven't yet fetched the keys for, returns the cross signing keys
  711. correctly.
  712. """
  713. remote_user_id = "@test:other"
  714. local_user_id = "@test:test"
  715. # Pretend we're sharing a room with the user we're querying. If not,
  716. # `_query_devices_for_destination` will return early.
  717. self.store.get_rooms_for_user = mock.Mock(
  718. return_value=make_awaitable({"some_room_id"})
  719. )
  720. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  721. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  722. self.hs.get_federation_client().query_user_devices = mock.Mock( # type: ignore[assignment]
  723. return_value=make_awaitable(
  724. {
  725. "user_id": remote_user_id,
  726. "stream_id": 1,
  727. "devices": [],
  728. "master_key": {
  729. "user_id": remote_user_id,
  730. "usage": ["master"],
  731. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  732. },
  733. "self_signing_key": {
  734. "user_id": remote_user_id,
  735. "usage": ["self_signing"],
  736. "keys": {
  737. "ed25519:"
  738. + remote_self_signing_key: remote_self_signing_key
  739. },
  740. },
  741. }
  742. )
  743. )
  744. e2e_handler = self.hs.get_e2e_keys_handler()
  745. query_result = self.get_success(
  746. e2e_handler.query_devices(
  747. {
  748. "device_keys": {remote_user_id: []},
  749. },
  750. timeout=10,
  751. from_user_id=local_user_id,
  752. from_device_id="some_device_id",
  753. )
  754. )
  755. self.assertEqual(query_result["failures"], {})
  756. self.assertEqual(
  757. query_result["master_keys"],
  758. {
  759. remote_user_id: {
  760. "user_id": remote_user_id,
  761. "usage": ["master"],
  762. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  763. }
  764. },
  765. )
  766. self.assertEqual(
  767. query_result["self_signing_keys"],
  768. {
  769. remote_user_id: {
  770. "user_id": remote_user_id,
  771. "usage": ["self_signing"],
  772. "keys": {
  773. "ed25519:" + remote_self_signing_key: remote_self_signing_key
  774. },
  775. }
  776. },
  777. )
  778. @parameterized.expand(
  779. [
  780. # The remote homeserver's response indicates that this user has 0/1/2 devices.
  781. ([],),
  782. (["device_1"],),
  783. (["device_1", "device_2"],),
  784. ]
  785. )
  786. def test_query_all_devices_caches_result(self, device_ids: Iterable[str]) -> None:
  787. """Test that requests for all of a remote user's devices are cached.
  788. We do this by asserting that only one call over federation was made, and that
  789. the two queries to the local homeserver produce the same response.
  790. """
  791. local_user_id = "@test:test"
  792. remote_user_id = "@test:other"
  793. request_body: JsonDict = {"device_keys": {remote_user_id: []}}
  794. response_devices = [
  795. {
  796. "device_id": device_id,
  797. "keys": {
  798. "algorithms": ["dummy"],
  799. "device_id": device_id,
  800. "keys": {f"dummy:{device_id}": "dummy"},
  801. "signatures": {device_id: {f"dummy:{device_id}": "dummy"}},
  802. "unsigned": {},
  803. "user_id": "@test:other",
  804. },
  805. }
  806. for device_id in device_ids
  807. ]
  808. response_body = {
  809. "devices": response_devices,
  810. "user_id": remote_user_id,
  811. "stream_id": 12345, # an integer, according to the spec
  812. }
  813. e2e_handler = self.hs.get_e2e_keys_handler()
  814. # Pretend we're sharing a room with the user we're querying. If not,
  815. # `_query_devices_for_destination` will return early.
  816. mock_get_rooms = mock.patch.object(
  817. self.store,
  818. "get_rooms_for_user",
  819. new_callable=mock.MagicMock,
  820. return_value=make_awaitable(["some_room_id"]),
  821. )
  822. mock_get_users = mock.patch.object(
  823. self.store,
  824. "get_users_server_still_shares_room_with",
  825. new_callable=mock.MagicMock,
  826. return_value=make_awaitable({remote_user_id}),
  827. )
  828. mock_request = mock.patch.object(
  829. self.hs.get_federation_client(),
  830. "query_user_devices",
  831. new_callable=mock.MagicMock,
  832. return_value=make_awaitable(response_body),
  833. )
  834. with mock_get_rooms, mock_get_users, mock_request as mocked_federation_request:
  835. # Make the first query and sanity check it succeeds.
  836. response_1 = self.get_success(
  837. e2e_handler.query_devices(
  838. request_body,
  839. timeout=10,
  840. from_user_id=local_user_id,
  841. from_device_id="some_device_id",
  842. )
  843. )
  844. self.assertEqual(response_1["failures"], {})
  845. # We should have made a federation request to do so.
  846. mocked_federation_request.assert_called_once()
  847. # Reset the mock so we can prove we don't make a second federation request.
  848. mocked_federation_request.reset_mock()
  849. # Repeat the query.
  850. response_2 = self.get_success(
  851. e2e_handler.query_devices(
  852. request_body,
  853. timeout=10,
  854. from_user_id=local_user_id,
  855. from_device_id="some_device_id",
  856. )
  857. )
  858. self.assertEqual(response_2["failures"], {})
  859. # We should not have made a second federation request.
  860. mocked_federation_request.assert_not_called()
  861. # The two requests to the local homeserver should be identical.
  862. self.assertEqual(response_1, response_2)
  863. @override_config({"experimental_features": {"msc3983_appservice_otk_claims": True}})
  864. def test_query_appservice(self) -> None:
  865. local_user = "@boris:" + self.hs.hostname
  866. device_id_1 = "xyz"
  867. fallback_key = {"alg1:k1": "fallback_key1"}
  868. device_id_2 = "abc"
  869. otk = {"alg1:k2": "key2"}
  870. # Inject an appservice interested in this user.
  871. appservice = ApplicationService(
  872. token="i_am_an_app_service",
  873. id="1234",
  874. namespaces={"users": [{"regex": r"@boris:.+", "exclusive": True}]},
  875. # Note: this user does not have to match the regex above
  876. sender="@as_main:test",
  877. )
  878. self.hs.get_datastores().main.services_cache = [appservice]
  879. self.hs.get_datastores().main.exclusive_user_regex = _make_exclusive_regex(
  880. [appservice]
  881. )
  882. # Setup a response, but only for device 2.
  883. self.appservice_api.claim_client_keys.return_value = make_awaitable(
  884. ({local_user: {device_id_2: otk}}, [(local_user, device_id_1, "alg1")])
  885. )
  886. # we shouldn't have any unused fallback keys yet
  887. res = self.get_success(
  888. self.store.get_e2e_unused_fallback_key_types(local_user, device_id_1)
  889. )
  890. self.assertEqual(res, [])
  891. self.get_success(
  892. self.handler.upload_keys_for_user(
  893. local_user,
  894. device_id_1,
  895. {"fallback_keys": fallback_key},
  896. )
  897. )
  898. # we should now have an unused alg1 key
  899. fallback_res = self.get_success(
  900. self.store.get_e2e_unused_fallback_key_types(local_user, device_id_1)
  901. )
  902. self.assertEqual(fallback_res, ["alg1"])
  903. # claiming an OTK when no OTKs are available should ask the appservice, then
  904. # query the fallback keys.
  905. claim_res = self.get_success(
  906. self.handler.claim_one_time_keys(
  907. {
  908. "one_time_keys": {
  909. local_user: {device_id_1: "alg1", device_id_2: "alg1"}
  910. }
  911. },
  912. timeout=None,
  913. )
  914. )
  915. self.assertEqual(
  916. claim_res,
  917. {
  918. "failures": {},
  919. "one_time_keys": {
  920. local_user: {device_id_1: fallback_key, device_id_2: otk}
  921. },
  922. },
  923. )
  924. @override_config({"experimental_features": {"msc3984_appservice_key_query": True}})
  925. def test_query_local_devices_appservice(self) -> None:
  926. """Test that querying of appservices for keys overrides responses from the database."""
  927. local_user = "@boris:" + self.hs.hostname
  928. device_1 = "abc"
  929. device_2 = "def"
  930. device_3 = "ghi"
  931. # There are 3 devices:
  932. #
  933. # 1. One which is uploaded to the homeserver.
  934. # 2. One which is uploaded to the homeserver, but a newer copy is returned
  935. # by the appservice.
  936. # 3. One which is only returned by the appservice.
  937. device_key_1: JsonDict = {
  938. "user_id": local_user,
  939. "device_id": device_1,
  940. "algorithms": [
  941. "m.olm.curve25519-aes-sha2",
  942. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  943. ],
  944. "keys": {
  945. "ed25519:abc": "base64+ed25519+key",
  946. "curve25519:abc": "base64+curve25519+key",
  947. },
  948. "signatures": {local_user: {"ed25519:abc": "base64+signature"}},
  949. }
  950. device_key_2a: JsonDict = {
  951. "user_id": local_user,
  952. "device_id": device_2,
  953. "algorithms": [
  954. "m.olm.curve25519-aes-sha2",
  955. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  956. ],
  957. "keys": {
  958. "ed25519:def": "base64+ed25519+key",
  959. "curve25519:def": "base64+curve25519+key",
  960. },
  961. "signatures": {local_user: {"ed25519:def": "base64+signature"}},
  962. }
  963. device_key_2b: JsonDict = {
  964. "user_id": local_user,
  965. "device_id": device_2,
  966. "algorithms": [
  967. "m.olm.curve25519-aes-sha2",
  968. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  969. ],
  970. # The device ID is the same (above), but the keys are different.
  971. "keys": {
  972. "ed25519:xyz": "base64+ed25519+key",
  973. "curve25519:xyz": "base64+curve25519+key",
  974. },
  975. "signatures": {local_user: {"ed25519:xyz": "base64+signature"}},
  976. }
  977. device_key_3: JsonDict = {
  978. "user_id": local_user,
  979. "device_id": device_3,
  980. "algorithms": [
  981. "m.olm.curve25519-aes-sha2",
  982. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  983. ],
  984. "keys": {
  985. "ed25519:jkl": "base64+ed25519+key",
  986. "curve25519:jkl": "base64+curve25519+key",
  987. },
  988. "signatures": {local_user: {"ed25519:jkl": "base64+signature"}},
  989. }
  990. # Upload keys for devices 1 & 2a.
  991. self.get_success(
  992. self.handler.upload_keys_for_user(
  993. local_user, device_1, {"device_keys": device_key_1}
  994. )
  995. )
  996. self.get_success(
  997. self.handler.upload_keys_for_user(
  998. local_user, device_2, {"device_keys": device_key_2a}
  999. )
  1000. )
  1001. # Inject an appservice interested in this user.
  1002. appservice = ApplicationService(
  1003. token="i_am_an_app_service",
  1004. id="1234",
  1005. namespaces={"users": [{"regex": r"@boris:.+", "exclusive": True}]},
  1006. # Note: this user does not have to match the regex above
  1007. sender="@as_main:test",
  1008. )
  1009. self.hs.get_datastores().main.services_cache = [appservice]
  1010. self.hs.get_datastores().main.exclusive_user_regex = _make_exclusive_regex(
  1011. [appservice]
  1012. )
  1013. # Setup a response.
  1014. self.appservice_api.query_keys.return_value = make_awaitable(
  1015. {
  1016. "device_keys": {
  1017. local_user: {device_2: device_key_2b, device_3: device_key_3}
  1018. }
  1019. }
  1020. )
  1021. # Request all devices.
  1022. res = self.get_success(self.handler.query_local_devices({local_user: None}))
  1023. self.assertIn(local_user, res)
  1024. for res_key in res[local_user].values():
  1025. res_key.pop("unsigned", None)
  1026. self.assertDictEqual(
  1027. res,
  1028. {
  1029. local_user: {
  1030. device_1: device_key_1,
  1031. device_2: device_key_2b,
  1032. device_3: device_key_3,
  1033. }
  1034. },
  1035. )