test_e2e_keys.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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 Dict, 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, UserID
  28. from synapse.util import Clock
  29. from tests import unittest
  30. from tests.unittest import override_config
  31. class E2eKeysHandlerTestCase(unittest.HomeserverTestCase):
  32. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  33. self.appservice_api = mock.AsyncMock()
  34. return self.setup_test_homeserver(
  35. federation_client=mock.Mock(), application_service_api=self.appservice_api
  36. )
  37. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  38. self.handler = hs.get_e2e_keys_handler()
  39. self.store = self.hs.get_datastores().main
  40. self.requester = UserID.from_string(f"@test_requester:{self.hs.hostname}")
  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. {local_user: {device_id: {"alg1": 1}}},
  143. self.requester,
  144. timeout=None,
  145. always_include_fallback_keys=False,
  146. )
  147. )
  148. self.assertEqual(
  149. res2,
  150. {
  151. "failures": {},
  152. "one_time_keys": {local_user: {device_id: {"alg1:k1": "key1"}}},
  153. },
  154. )
  155. def test_fallback_key(self) -> None:
  156. local_user = "@boris:" + self.hs.hostname
  157. device_id = "xyz"
  158. fallback_key = {"alg1:k1": "fallback_key1"}
  159. fallback_key2 = {"alg1:k2": "fallback_key2"}
  160. fallback_key3 = {"alg1:k2": "fallback_key3"}
  161. otk = {"alg1:k2": "key2"}
  162. # we shouldn't have any unused fallback keys yet
  163. res = self.get_success(
  164. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  165. )
  166. self.assertEqual(res, [])
  167. self.get_success(
  168. self.handler.upload_keys_for_user(
  169. local_user,
  170. device_id,
  171. {"fallback_keys": fallback_key},
  172. )
  173. )
  174. # we should now have an unused alg1 key
  175. fallback_res = self.get_success(
  176. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  177. )
  178. self.assertEqual(fallback_res, ["alg1"])
  179. # claiming an OTK when no OTKs are available should return the fallback
  180. # key
  181. claim_res = self.get_success(
  182. self.handler.claim_one_time_keys(
  183. {local_user: {device_id: {"alg1": 1}}},
  184. self.requester,
  185. timeout=None,
  186. always_include_fallback_keys=False,
  187. )
  188. )
  189. self.assertEqual(
  190. claim_res,
  191. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key}}},
  192. )
  193. # we shouldn't have any unused fallback keys again
  194. unused_res = self.get_success(
  195. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  196. )
  197. self.assertEqual(unused_res, [])
  198. # claiming an OTK again should return the same fallback key
  199. claim_res = self.get_success(
  200. self.handler.claim_one_time_keys(
  201. {local_user: {device_id: {"alg1": 1}}},
  202. self.requester,
  203. timeout=None,
  204. always_include_fallback_keys=False,
  205. )
  206. )
  207. self.assertEqual(
  208. claim_res,
  209. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key}}},
  210. )
  211. # re-uploading the same fallback key should still result in no unused fallback
  212. # keys
  213. self.get_success(
  214. self.handler.upload_keys_for_user(
  215. local_user,
  216. device_id,
  217. {"fallback_keys": fallback_key},
  218. )
  219. )
  220. unused_res = self.get_success(
  221. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  222. )
  223. self.assertEqual(unused_res, [])
  224. # uploading a new fallback key should result in an unused fallback key
  225. self.get_success(
  226. self.handler.upload_keys_for_user(
  227. local_user,
  228. device_id,
  229. {"fallback_keys": fallback_key2},
  230. )
  231. )
  232. unused_res = self.get_success(
  233. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  234. )
  235. self.assertEqual(unused_res, ["alg1"])
  236. # if the user uploads a one-time key, the next claim should fetch the
  237. # one-time key, and then go back to the fallback
  238. self.get_success(
  239. self.handler.upload_keys_for_user(
  240. local_user, device_id, {"one_time_keys": otk}
  241. )
  242. )
  243. claim_res = self.get_success(
  244. self.handler.claim_one_time_keys(
  245. {local_user: {device_id: {"alg1": 1}}},
  246. self.requester,
  247. timeout=None,
  248. always_include_fallback_keys=False,
  249. )
  250. )
  251. self.assertEqual(
  252. claim_res,
  253. {"failures": {}, "one_time_keys": {local_user: {device_id: otk}}},
  254. )
  255. claim_res = self.get_success(
  256. self.handler.claim_one_time_keys(
  257. {local_user: {device_id: {"alg1": 1}}},
  258. self.requester,
  259. timeout=None,
  260. always_include_fallback_keys=False,
  261. )
  262. )
  263. self.assertEqual(
  264. claim_res,
  265. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key2}}},
  266. )
  267. # using the unstable prefix should also set the fallback key
  268. self.get_success(
  269. self.handler.upload_keys_for_user(
  270. local_user,
  271. device_id,
  272. {"org.matrix.msc2732.fallback_keys": fallback_key3},
  273. )
  274. )
  275. claim_res = self.get_success(
  276. self.handler.claim_one_time_keys(
  277. {local_user: {device_id: {"alg1": 1}}},
  278. self.requester,
  279. timeout=None,
  280. always_include_fallback_keys=False,
  281. )
  282. )
  283. self.assertEqual(
  284. claim_res,
  285. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key3}}},
  286. )
  287. def test_fallback_key_always_returned(self) -> None:
  288. local_user = "@boris:" + self.hs.hostname
  289. device_id = "xyz"
  290. fallback_key = {"alg1:k1": "fallback_key1"}
  291. otk = {"alg1:k2": "key2"}
  292. # we shouldn't have any unused fallback keys yet
  293. res = self.get_success(
  294. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  295. )
  296. self.assertEqual(res, [])
  297. # Upload a OTK & fallback key.
  298. self.get_success(
  299. self.handler.upload_keys_for_user(
  300. local_user,
  301. device_id,
  302. {"one_time_keys": otk, "fallback_keys": fallback_key},
  303. )
  304. )
  305. # we should now have an unused alg1 key
  306. fallback_res = self.get_success(
  307. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  308. )
  309. self.assertEqual(fallback_res, ["alg1"])
  310. # Claiming an OTK and requesting to always return the fallback key should
  311. # return both.
  312. claim_res = self.get_success(
  313. self.handler.claim_one_time_keys(
  314. {local_user: {device_id: {"alg1": 1}}},
  315. self.requester,
  316. timeout=None,
  317. always_include_fallback_keys=True,
  318. )
  319. )
  320. self.assertEqual(
  321. claim_res,
  322. {
  323. "failures": {},
  324. "one_time_keys": {local_user: {device_id: {**fallback_key, **otk}}},
  325. },
  326. )
  327. # This should not mark the key as used.
  328. fallback_res = self.get_success(
  329. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  330. )
  331. self.assertEqual(fallback_res, ["alg1"])
  332. # Claiming an OTK again should return only the fallback key.
  333. claim_res = self.get_success(
  334. self.handler.claim_one_time_keys(
  335. {local_user: {device_id: {"alg1": 1}}},
  336. self.requester,
  337. timeout=None,
  338. always_include_fallback_keys=True,
  339. )
  340. )
  341. self.assertEqual(
  342. claim_res,
  343. {"failures": {}, "one_time_keys": {local_user: {device_id: fallback_key}}},
  344. )
  345. # And mark it as used.
  346. fallback_res = self.get_success(
  347. self.store.get_e2e_unused_fallback_key_types(local_user, device_id)
  348. )
  349. self.assertEqual(fallback_res, [])
  350. def test_replace_master_key(self) -> None:
  351. """uploading a new signing key should make the old signing key unavailable"""
  352. local_user = "@boris:" + self.hs.hostname
  353. keys1 = {
  354. "master_key": {
  355. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  356. "user_id": local_user,
  357. "usage": ["master"],
  358. "keys": {
  359. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  360. },
  361. }
  362. }
  363. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  364. keys2 = {
  365. "master_key": {
  366. # private key: 4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs
  367. "user_id": local_user,
  368. "usage": ["master"],
  369. "keys": {
  370. "ed25519:Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw": "Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw"
  371. },
  372. }
  373. }
  374. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys2))
  375. devices = self.get_success(
  376. self.handler.query_devices(
  377. {"device_keys": {local_user: []}}, 0, local_user, "device123"
  378. )
  379. )
  380. self.assertDictEqual(devices["master_keys"], {local_user: keys2["master_key"]})
  381. def test_reupload_signatures(self) -> None:
  382. """re-uploading a signature should not fail"""
  383. local_user = "@boris:" + self.hs.hostname
  384. keys1 = {
  385. "master_key": {
  386. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  387. "user_id": local_user,
  388. "usage": ["master"],
  389. "keys": {
  390. "ed25519:EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ": "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ"
  391. },
  392. },
  393. "self_signing_key": {
  394. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  395. "user_id": local_user,
  396. "usage": ["self_signing"],
  397. "keys": {
  398. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  399. },
  400. },
  401. }
  402. master_signing_key = key.decode_signing_key_base64(
  403. "ed25519",
  404. "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ",
  405. "HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8",
  406. )
  407. sign.sign_json(keys1["self_signing_key"], local_user, master_signing_key)
  408. signing_key = key.decode_signing_key_base64(
  409. "ed25519",
  410. "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk",
  411. "2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0",
  412. )
  413. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  414. # upload two device keys, which will be signed later by the self-signing key
  415. device_key_1: JsonDict = {
  416. "user_id": local_user,
  417. "device_id": "abc",
  418. "algorithms": [
  419. "m.olm.curve25519-aes-sha2",
  420. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  421. ],
  422. "keys": {
  423. "ed25519:abc": "base64+ed25519+key",
  424. "curve25519:abc": "base64+curve25519+key",
  425. },
  426. "signatures": {local_user: {"ed25519:abc": "base64+signature"}},
  427. }
  428. device_key_2: JsonDict = {
  429. "user_id": local_user,
  430. "device_id": "def",
  431. "algorithms": [
  432. "m.olm.curve25519-aes-sha2",
  433. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  434. ],
  435. "keys": {
  436. "ed25519:def": "base64+ed25519+key",
  437. "curve25519:def": "base64+curve25519+key",
  438. },
  439. "signatures": {local_user: {"ed25519:def": "base64+signature"}},
  440. }
  441. self.get_success(
  442. self.handler.upload_keys_for_user(
  443. local_user, "abc", {"device_keys": device_key_1}
  444. )
  445. )
  446. self.get_success(
  447. self.handler.upload_keys_for_user(
  448. local_user, "def", {"device_keys": device_key_2}
  449. )
  450. )
  451. # sign the first device key and upload it
  452. del device_key_1["signatures"]
  453. sign.sign_json(device_key_1, local_user, signing_key)
  454. self.get_success(
  455. self.handler.upload_signatures_for_device_keys(
  456. local_user, {local_user: {"abc": device_key_1}}
  457. )
  458. )
  459. # sign the second device key and upload both device keys. The server
  460. # should ignore the first device key since it already has a valid
  461. # signature for it
  462. del device_key_2["signatures"]
  463. sign.sign_json(device_key_2, local_user, signing_key)
  464. self.get_success(
  465. self.handler.upload_signatures_for_device_keys(
  466. local_user, {local_user: {"abc": device_key_1, "def": device_key_2}}
  467. )
  468. )
  469. device_key_1["signatures"][local_user]["ed25519:abc"] = "base64+signature"
  470. device_key_2["signatures"][local_user]["ed25519:def"] = "base64+signature"
  471. devices = self.get_success(
  472. self.handler.query_devices(
  473. {"device_keys": {local_user: []}}, 0, local_user, "device123"
  474. )
  475. )
  476. del devices["device_keys"][local_user]["abc"]["unsigned"]
  477. del devices["device_keys"][local_user]["def"]["unsigned"]
  478. self.assertDictEqual(devices["device_keys"][local_user]["abc"], device_key_1)
  479. self.assertDictEqual(devices["device_keys"][local_user]["def"], device_key_2)
  480. def test_self_signing_key_doesnt_show_up_as_device(self) -> None:
  481. """signing keys should be hidden when fetching a user's devices"""
  482. local_user = "@boris:" + self.hs.hostname
  483. keys1 = {
  484. "master_key": {
  485. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  486. "user_id": local_user,
  487. "usage": ["master"],
  488. "keys": {
  489. "ed25519:nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk": "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  490. },
  491. }
  492. }
  493. self.get_success(self.handler.upload_signing_keys_for_user(local_user, keys1))
  494. device_handler = self.hs.get_device_handler()
  495. assert isinstance(device_handler, DeviceHandler)
  496. e = self.get_failure(
  497. device_handler.check_device_registered(
  498. user_id=local_user,
  499. device_id="nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk",
  500. initial_device_display_name="new display name",
  501. ),
  502. SynapseError,
  503. )
  504. res = e.value.code
  505. self.assertEqual(res, 400)
  506. query_res = self.get_success(
  507. self.handler.query_local_devices({local_user: None})
  508. )
  509. self.assertDictEqual(query_res, {local_user: {}})
  510. def test_upload_signatures(self) -> None:
  511. """should check signatures that are uploaded"""
  512. # set up a user with cross-signing keys and a device. This user will
  513. # try uploading signatures
  514. local_user = "@boris:" + self.hs.hostname
  515. device_id = "xyz"
  516. # private key: OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA
  517. device_pubkey = "NnHhnqiMFQkq969szYkooLaBAXW244ZOxgukCvm2ZeY"
  518. device_key: JsonDict = {
  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": {"curve25519:xyz": "curve25519+key", "ed25519:xyz": device_pubkey},
  526. "signatures": {local_user: {"ed25519:xyz": "something"}},
  527. }
  528. device_signing_key = key.decode_signing_key_base64(
  529. "ed25519", "xyz", "OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA"
  530. )
  531. self.get_success(
  532. self.handler.upload_keys_for_user(
  533. local_user, device_id, {"device_keys": device_key}
  534. )
  535. )
  536. # private key: 2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0
  537. master_pubkey = "nqOvzeuGWT/sRx3h7+MHoInYj3Uk2LD/unI9kDYcHwk"
  538. master_key: JsonDict = {
  539. "user_id": local_user,
  540. "usage": ["master"],
  541. "keys": {"ed25519:" + master_pubkey: master_pubkey},
  542. }
  543. master_signing_key = key.decode_signing_key_base64(
  544. "ed25519", master_pubkey, "2lonYOM6xYKdEsO+6KrC766xBcHnYnim1x/4LFGF8B0"
  545. )
  546. usersigning_pubkey = "Hq6gL+utB4ET+UvD5ci0kgAwsX6qP/zvf8v6OInU5iw"
  547. usersigning_key = {
  548. # private key: 4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs
  549. "user_id": local_user,
  550. "usage": ["user_signing"],
  551. "keys": {"ed25519:" + usersigning_pubkey: usersigning_pubkey},
  552. }
  553. usersigning_signing_key = key.decode_signing_key_base64(
  554. "ed25519", usersigning_pubkey, "4TL4AjRYwDVwD3pqQzcor+ez/euOB1/q78aTJ+czDNs"
  555. )
  556. sign.sign_json(usersigning_key, local_user, master_signing_key)
  557. # private key: HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8
  558. selfsigning_pubkey = "EmkqvokUn8p+vQAGZitOk4PWjp7Ukp3txV2TbMPEiBQ"
  559. selfsigning_key = {
  560. "user_id": local_user,
  561. "usage": ["self_signing"],
  562. "keys": {"ed25519:" + selfsigning_pubkey: selfsigning_pubkey},
  563. }
  564. selfsigning_signing_key = key.decode_signing_key_base64(
  565. "ed25519", selfsigning_pubkey, "HvQBbU+hc2Zr+JP1sE0XwBe1pfZZEYtJNPJLZJtS+F8"
  566. )
  567. sign.sign_json(selfsigning_key, local_user, master_signing_key)
  568. cross_signing_keys = {
  569. "master_key": master_key,
  570. "user_signing_key": usersigning_key,
  571. "self_signing_key": selfsigning_key,
  572. }
  573. self.get_success(
  574. self.handler.upload_signing_keys_for_user(local_user, cross_signing_keys)
  575. )
  576. # set up another user with a master key. This user will be signed by
  577. # the first user
  578. other_user = "@otherboris:" + self.hs.hostname
  579. other_master_pubkey = "fHZ3NPiKxoLQm5OoZbKa99SYxprOjNs4TwJUKP+twCM"
  580. other_master_key: JsonDict = {
  581. # private key: oyw2ZUx0O4GifbfFYM0nQvj9CL0b8B7cyN4FprtK8OI
  582. "user_id": other_user,
  583. "usage": ["master"],
  584. "keys": {"ed25519:" + other_master_pubkey: other_master_pubkey},
  585. }
  586. self.get_success(
  587. self.handler.upload_signing_keys_for_user(
  588. other_user, {"master_key": other_master_key}
  589. )
  590. )
  591. # test various signature failures (see below)
  592. ret = self.get_success(
  593. self.handler.upload_signatures_for_device_keys(
  594. local_user,
  595. {
  596. local_user: {
  597. # fails because the signature is invalid
  598. # should fail with INVALID_SIGNATURE
  599. device_id: {
  600. "user_id": local_user,
  601. "device_id": device_id,
  602. "algorithms": [
  603. "m.olm.curve25519-aes-sha2",
  604. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  605. ],
  606. "keys": {
  607. "curve25519:xyz": "curve25519+key",
  608. # private key: OMkooTr76ega06xNvXIGPbgvvxAOzmQncN8VObS7aBA
  609. "ed25519:xyz": device_pubkey,
  610. },
  611. "signatures": {
  612. local_user: {
  613. "ed25519:" + selfsigning_pubkey: "something"
  614. }
  615. },
  616. },
  617. # fails because device is unknown
  618. # should fail with NOT_FOUND
  619. "unknown": {
  620. "user_id": local_user,
  621. "device_id": "unknown",
  622. "signatures": {
  623. local_user: {
  624. "ed25519:" + selfsigning_pubkey: "something"
  625. }
  626. },
  627. },
  628. # fails because the signature is invalid
  629. # should fail with INVALID_SIGNATURE
  630. master_pubkey: {
  631. "user_id": local_user,
  632. "usage": ["master"],
  633. "keys": {"ed25519:" + master_pubkey: master_pubkey},
  634. "signatures": {
  635. local_user: {"ed25519:" + device_pubkey: "something"}
  636. },
  637. },
  638. },
  639. other_user: {
  640. # fails because the device is not the user's master-signing key
  641. # should fail with NOT_FOUND
  642. "unknown": {
  643. "user_id": other_user,
  644. "device_id": "unknown",
  645. "signatures": {
  646. local_user: {
  647. "ed25519:" + usersigning_pubkey: "something"
  648. }
  649. },
  650. },
  651. other_master_pubkey: {
  652. # fails because the key doesn't match what the server has
  653. # should fail with UNKNOWN
  654. "user_id": other_user,
  655. "usage": ["master"],
  656. "keys": {
  657. "ed25519:" + other_master_pubkey: other_master_pubkey
  658. },
  659. "something": "random",
  660. "signatures": {
  661. local_user: {
  662. "ed25519:" + usersigning_pubkey: "something"
  663. }
  664. },
  665. },
  666. },
  667. },
  668. )
  669. )
  670. user_failures = ret["failures"][local_user]
  671. self.assertEqual(user_failures[device_id]["errcode"], Codes.INVALID_SIGNATURE)
  672. self.assertEqual(
  673. user_failures[master_pubkey]["errcode"], Codes.INVALID_SIGNATURE
  674. )
  675. self.assertEqual(user_failures["unknown"]["errcode"], Codes.NOT_FOUND)
  676. other_user_failures = ret["failures"][other_user]
  677. self.assertEqual(other_user_failures["unknown"]["errcode"], Codes.NOT_FOUND)
  678. self.assertEqual(
  679. other_user_failures[other_master_pubkey]["errcode"], Codes.UNKNOWN
  680. )
  681. # test successful signatures
  682. del device_key["signatures"]
  683. sign.sign_json(device_key, local_user, selfsigning_signing_key)
  684. sign.sign_json(master_key, local_user, device_signing_key)
  685. sign.sign_json(other_master_key, local_user, usersigning_signing_key)
  686. ret = self.get_success(
  687. self.handler.upload_signatures_for_device_keys(
  688. local_user,
  689. {
  690. local_user: {device_id: device_key, master_pubkey: master_key},
  691. other_user: {other_master_pubkey: other_master_key},
  692. },
  693. )
  694. )
  695. self.assertEqual(ret["failures"], {})
  696. # fetch the signed keys/devices and make sure that the signatures are there
  697. ret = self.get_success(
  698. self.handler.query_devices(
  699. {"device_keys": {local_user: [], other_user: []}},
  700. 0,
  701. local_user,
  702. "device123",
  703. )
  704. )
  705. self.assertEqual(
  706. ret["device_keys"][local_user]["xyz"]["signatures"][local_user][
  707. "ed25519:" + selfsigning_pubkey
  708. ],
  709. device_key["signatures"][local_user]["ed25519:" + selfsigning_pubkey],
  710. )
  711. self.assertEqual(
  712. ret["master_keys"][local_user]["signatures"][local_user][
  713. "ed25519:" + device_id
  714. ],
  715. master_key["signatures"][local_user]["ed25519:" + device_id],
  716. )
  717. self.assertEqual(
  718. ret["master_keys"][other_user]["signatures"][local_user][
  719. "ed25519:" + usersigning_pubkey
  720. ],
  721. other_master_key["signatures"][local_user]["ed25519:" + usersigning_pubkey],
  722. )
  723. def test_query_devices_remote_no_sync(self) -> None:
  724. """Tests that querying keys for a remote user that we don't share a room
  725. with returns the cross signing keys correctly.
  726. """
  727. remote_user_id = "@test:other"
  728. local_user_id = "@test:test"
  729. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  730. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  731. self.hs.get_federation_client().query_client_keys = mock.AsyncMock( # type: ignore[method-assign]
  732. return_value={
  733. "device_keys": {remote_user_id: {}},
  734. "master_keys": {
  735. remote_user_id: {
  736. "user_id": remote_user_id,
  737. "usage": ["master"],
  738. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  739. },
  740. },
  741. "self_signing_keys": {
  742. remote_user_id: {
  743. "user_id": remote_user_id,
  744. "usage": ["self_signing"],
  745. "keys": {
  746. "ed25519:"
  747. + remote_self_signing_key: remote_self_signing_key
  748. },
  749. }
  750. },
  751. }
  752. )
  753. e2e_handler = self.hs.get_e2e_keys_handler()
  754. query_result = self.get_success(
  755. e2e_handler.query_devices(
  756. {
  757. "device_keys": {remote_user_id: []},
  758. },
  759. timeout=10,
  760. from_user_id=local_user_id,
  761. from_device_id="some_device_id",
  762. )
  763. )
  764. self.assertEqual(query_result["failures"], {})
  765. self.assertEqual(
  766. query_result["master_keys"],
  767. {
  768. remote_user_id: {
  769. "user_id": remote_user_id,
  770. "usage": ["master"],
  771. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  772. },
  773. },
  774. )
  775. self.assertEqual(
  776. query_result["self_signing_keys"],
  777. {
  778. remote_user_id: {
  779. "user_id": remote_user_id,
  780. "usage": ["self_signing"],
  781. "keys": {
  782. "ed25519:" + remote_self_signing_key: remote_self_signing_key
  783. },
  784. }
  785. },
  786. )
  787. def test_query_devices_remote_sync(self) -> None:
  788. """Tests that querying keys for a remote user that we share a room with,
  789. but haven't yet fetched the keys for, returns the cross signing keys
  790. correctly.
  791. """
  792. remote_user_id = "@test:other"
  793. local_user_id = "@test:test"
  794. # Pretend we're sharing a room with the user we're querying. If not,
  795. # `_query_devices_for_destination` will return early.
  796. self.store.get_rooms_for_user = mock.AsyncMock(return_value={"some_room_id"})
  797. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  798. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  799. self.hs.get_federation_client().query_user_devices = mock.AsyncMock( # type: ignore[method-assign]
  800. return_value={
  801. "user_id": remote_user_id,
  802. "stream_id": 1,
  803. "devices": [],
  804. "master_key": {
  805. "user_id": remote_user_id,
  806. "usage": ["master"],
  807. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  808. },
  809. "self_signing_key": {
  810. "user_id": remote_user_id,
  811. "usage": ["self_signing"],
  812. "keys": {
  813. "ed25519:" + remote_self_signing_key: remote_self_signing_key
  814. },
  815. },
  816. }
  817. )
  818. e2e_handler = self.hs.get_e2e_keys_handler()
  819. query_result = self.get_success(
  820. e2e_handler.query_devices(
  821. {
  822. "device_keys": {remote_user_id: []},
  823. },
  824. timeout=10,
  825. from_user_id=local_user_id,
  826. from_device_id="some_device_id",
  827. )
  828. )
  829. self.assertEqual(query_result["failures"], {})
  830. self.assertEqual(
  831. query_result["master_keys"],
  832. {
  833. remote_user_id: {
  834. "user_id": remote_user_id,
  835. "usage": ["master"],
  836. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  837. }
  838. },
  839. )
  840. self.assertEqual(
  841. query_result["self_signing_keys"],
  842. {
  843. remote_user_id: {
  844. "user_id": remote_user_id,
  845. "usage": ["self_signing"],
  846. "keys": {
  847. "ed25519:" + remote_self_signing_key: remote_self_signing_key
  848. },
  849. }
  850. },
  851. )
  852. @parameterized.expand(
  853. [
  854. # The remote homeserver's response indicates that this user has 0/1/2 devices.
  855. ([],),
  856. (["device_1"],),
  857. (["device_1", "device_2"],),
  858. ]
  859. )
  860. def test_query_all_devices_caches_result(self, device_ids: Iterable[str]) -> None:
  861. """Test that requests for all of a remote user's devices are cached.
  862. We do this by asserting that only one call over federation was made, and that
  863. the two queries to the local homeserver produce the same response.
  864. """
  865. local_user_id = "@test:test"
  866. remote_user_id = "@test:other"
  867. request_body: JsonDict = {"device_keys": {remote_user_id: []}}
  868. response_devices = [
  869. {
  870. "device_id": device_id,
  871. "keys": {
  872. "algorithms": ["dummy"],
  873. "device_id": device_id,
  874. "keys": {f"dummy:{device_id}": "dummy"},
  875. "signatures": {device_id: {f"dummy:{device_id}": "dummy"}},
  876. "unsigned": {},
  877. "user_id": "@test:other",
  878. },
  879. }
  880. for device_id in device_ids
  881. ]
  882. response_body = {
  883. "devices": response_devices,
  884. "user_id": remote_user_id,
  885. "stream_id": 12345, # an integer, according to the spec
  886. }
  887. e2e_handler = self.hs.get_e2e_keys_handler()
  888. # Pretend we're sharing a room with the user we're querying. If not,
  889. # `_query_devices_for_destination` will return early.
  890. mock_get_rooms = mock.patch.object(
  891. self.store,
  892. "get_rooms_for_user",
  893. new_callable=mock.AsyncMock,
  894. return_value=["some_room_id"],
  895. )
  896. mock_get_users = mock.patch.object(
  897. self.store,
  898. "get_users_server_still_shares_room_with",
  899. new_callable=mock.AsyncMock,
  900. return_value={remote_user_id},
  901. )
  902. mock_request = mock.patch.object(
  903. self.hs.get_federation_client(),
  904. "query_user_devices",
  905. new_callable=mock.AsyncMock,
  906. return_value=response_body,
  907. )
  908. with mock_get_rooms, mock_get_users, mock_request as mocked_federation_request:
  909. # Make the first query and sanity check it succeeds.
  910. response_1 = self.get_success(
  911. e2e_handler.query_devices(
  912. request_body,
  913. timeout=10,
  914. from_user_id=local_user_id,
  915. from_device_id="some_device_id",
  916. )
  917. )
  918. self.assertEqual(response_1["failures"], {})
  919. # We should have made a federation request to do so.
  920. mocked_federation_request.assert_called_once()
  921. # Reset the mock so we can prove we don't make a second federation request.
  922. mocked_federation_request.reset_mock()
  923. # Repeat the query.
  924. response_2 = self.get_success(
  925. e2e_handler.query_devices(
  926. request_body,
  927. timeout=10,
  928. from_user_id=local_user_id,
  929. from_device_id="some_device_id",
  930. )
  931. )
  932. self.assertEqual(response_2["failures"], {})
  933. # We should not have made a second federation request.
  934. mocked_federation_request.assert_not_called()
  935. # The two requests to the local homeserver should be identical.
  936. self.assertEqual(response_1, response_2)
  937. @override_config({"experimental_features": {"msc3983_appservice_otk_claims": True}})
  938. def test_query_appservice(self) -> None:
  939. local_user = "@boris:" + self.hs.hostname
  940. device_id_1 = "xyz"
  941. fallback_key = {"alg1:k1": "fallback_key1"}
  942. device_id_2 = "abc"
  943. otk = {"alg1:k2": "key2"}
  944. # Inject an appservice interested in this user.
  945. appservice = ApplicationService(
  946. token="i_am_an_app_service",
  947. id="1234",
  948. namespaces={"users": [{"regex": r"@boris:.+", "exclusive": True}]},
  949. # Note: this user does not have to match the regex above
  950. sender="@as_main:test",
  951. )
  952. self.hs.get_datastores().main.services_cache = [appservice]
  953. self.hs.get_datastores().main.exclusive_user_regex = _make_exclusive_regex(
  954. [appservice]
  955. )
  956. # Setup a response, but only for device 2.
  957. self.appservice_api.claim_client_keys.return_value = (
  958. {local_user: {device_id_2: otk}},
  959. [(local_user, device_id_1, "alg1", 1)],
  960. )
  961. # we shouldn't have any unused fallback keys yet
  962. res = self.get_success(
  963. self.store.get_e2e_unused_fallback_key_types(local_user, device_id_1)
  964. )
  965. self.assertEqual(res, [])
  966. self.get_success(
  967. self.handler.upload_keys_for_user(
  968. local_user,
  969. device_id_1,
  970. {"fallback_keys": fallback_key},
  971. )
  972. )
  973. # we should now have an unused alg1 key
  974. fallback_res = self.get_success(
  975. self.store.get_e2e_unused_fallback_key_types(local_user, device_id_1)
  976. )
  977. self.assertEqual(fallback_res, ["alg1"])
  978. # claiming an OTK when no OTKs are available should ask the appservice, then
  979. # query the fallback keys.
  980. claim_res = self.get_success(
  981. self.handler.claim_one_time_keys(
  982. {local_user: {device_id_1: {"alg1": 1}, device_id_2: {"alg1": 1}}},
  983. self.requester,
  984. timeout=None,
  985. always_include_fallback_keys=False,
  986. )
  987. )
  988. self.assertEqual(
  989. claim_res,
  990. {
  991. "failures": {},
  992. "one_time_keys": {
  993. local_user: {device_id_1: fallback_key, device_id_2: otk}
  994. },
  995. },
  996. )
  997. @override_config({"experimental_features": {"msc3983_appservice_otk_claims": True}})
  998. def test_query_appservice_with_fallback(self) -> None:
  999. local_user = "@boris:" + self.hs.hostname
  1000. device_id_1 = "xyz"
  1001. fallback_key = {"alg1:k1": {"desc": "fallback_key1", "fallback": True}}
  1002. otk = {"alg1:k2": {"desc": "key2"}}
  1003. as_fallback_key = {"alg1:k3": {"desc": "fallback_key3", "fallback": True}}
  1004. as_otk = {"alg1:k4": {"desc": "key4"}}
  1005. # Inject an appservice interested in this user.
  1006. appservice = ApplicationService(
  1007. token="i_am_an_app_service",
  1008. id="1234",
  1009. namespaces={"users": [{"regex": r"@boris:.+", "exclusive": True}]},
  1010. # Note: this user does not have to match the regex above
  1011. sender="@as_main:test",
  1012. )
  1013. self.hs.get_datastores().main.services_cache = [appservice]
  1014. self.hs.get_datastores().main.exclusive_user_regex = _make_exclusive_regex(
  1015. [appservice]
  1016. )
  1017. # Setup a response.
  1018. response: Dict[str, Dict[str, Dict[str, JsonDict]]] = {
  1019. local_user: {device_id_1: {**as_otk, **as_fallback_key}}
  1020. }
  1021. self.appservice_api.claim_client_keys.return_value = (response, [])
  1022. # Claim OTKs, which will ask the appservice and do nothing else.
  1023. claim_res = self.get_success(
  1024. self.handler.claim_one_time_keys(
  1025. {local_user: {device_id_1: {"alg1": 1}}},
  1026. self.requester,
  1027. timeout=None,
  1028. always_include_fallback_keys=True,
  1029. )
  1030. )
  1031. self.assertEqual(
  1032. claim_res,
  1033. {
  1034. "failures": {},
  1035. "one_time_keys": {
  1036. local_user: {device_id_1: {**as_otk, **as_fallback_key}}
  1037. },
  1038. },
  1039. )
  1040. # Now upload a fallback key.
  1041. res = self.get_success(
  1042. self.store.get_e2e_unused_fallback_key_types(local_user, device_id_1)
  1043. )
  1044. self.assertEqual(res, [])
  1045. self.get_success(
  1046. self.handler.upload_keys_for_user(
  1047. local_user,
  1048. device_id_1,
  1049. {"fallback_keys": fallback_key},
  1050. )
  1051. )
  1052. # we should now have an unused alg1 key
  1053. fallback_res = self.get_success(
  1054. self.store.get_e2e_unused_fallback_key_types(local_user, device_id_1)
  1055. )
  1056. self.assertEqual(fallback_res, ["alg1"])
  1057. # The appservice will return only the OTK.
  1058. self.appservice_api.claim_client_keys.return_value = (
  1059. {local_user: {device_id_1: as_otk}},
  1060. [],
  1061. )
  1062. # Claim OTKs, which should return the OTK from the appservice and the
  1063. # uploaded fallback key.
  1064. claim_res = self.get_success(
  1065. self.handler.claim_one_time_keys(
  1066. {local_user: {device_id_1: {"alg1": 1}}},
  1067. self.requester,
  1068. timeout=None,
  1069. always_include_fallback_keys=True,
  1070. )
  1071. )
  1072. self.assertEqual(
  1073. claim_res,
  1074. {
  1075. "failures": {},
  1076. "one_time_keys": {
  1077. local_user: {device_id_1: {**as_otk, **fallback_key}}
  1078. },
  1079. },
  1080. )
  1081. # But the fallback key should not be marked as used.
  1082. fallback_res = self.get_success(
  1083. self.store.get_e2e_unused_fallback_key_types(local_user, device_id_1)
  1084. )
  1085. self.assertEqual(fallback_res, ["alg1"])
  1086. # Now upload a OTK.
  1087. self.get_success(
  1088. self.handler.upload_keys_for_user(
  1089. local_user,
  1090. device_id_1,
  1091. {"one_time_keys": otk},
  1092. )
  1093. )
  1094. # Claim OTKs, which will return information only from the database.
  1095. claim_res = self.get_success(
  1096. self.handler.claim_one_time_keys(
  1097. {local_user: {device_id_1: {"alg1": 1}}},
  1098. self.requester,
  1099. timeout=None,
  1100. always_include_fallback_keys=True,
  1101. )
  1102. )
  1103. self.assertEqual(
  1104. claim_res,
  1105. {
  1106. "failures": {},
  1107. "one_time_keys": {local_user: {device_id_1: {**otk, **fallback_key}}},
  1108. },
  1109. )
  1110. # But the fallback key should not be marked as used.
  1111. fallback_res = self.get_success(
  1112. self.store.get_e2e_unused_fallback_key_types(local_user, device_id_1)
  1113. )
  1114. self.assertEqual(fallback_res, ["alg1"])
  1115. # Finally, return only the fallback key from the appservice.
  1116. self.appservice_api.claim_client_keys.return_value = (
  1117. {local_user: {device_id_1: as_fallback_key}},
  1118. [],
  1119. )
  1120. # Claim OTKs, which will return only the fallback key from the database.
  1121. claim_res = self.get_success(
  1122. self.handler.claim_one_time_keys(
  1123. {local_user: {device_id_1: {"alg1": 1}}},
  1124. self.requester,
  1125. timeout=None,
  1126. always_include_fallback_keys=True,
  1127. )
  1128. )
  1129. self.assertEqual(
  1130. claim_res,
  1131. {
  1132. "failures": {},
  1133. "one_time_keys": {local_user: {device_id_1: as_fallback_key}},
  1134. },
  1135. )
  1136. @override_config({"experimental_features": {"msc3984_appservice_key_query": True}})
  1137. def test_query_local_devices_appservice(self) -> None:
  1138. """Test that querying of appservices for keys overrides responses from the database."""
  1139. local_user = "@boris:" + self.hs.hostname
  1140. device_1 = "abc"
  1141. device_2 = "def"
  1142. device_3 = "ghi"
  1143. # There are 3 devices:
  1144. #
  1145. # 1. One which is uploaded to the homeserver.
  1146. # 2. One which is uploaded to the homeserver, but a newer copy is returned
  1147. # by the appservice.
  1148. # 3. One which is only returned by the appservice.
  1149. device_key_1: JsonDict = {
  1150. "user_id": local_user,
  1151. "device_id": device_1,
  1152. "algorithms": [
  1153. "m.olm.curve25519-aes-sha2",
  1154. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  1155. ],
  1156. "keys": {
  1157. "ed25519:abc": "base64+ed25519+key",
  1158. "curve25519:abc": "base64+curve25519+key",
  1159. },
  1160. "signatures": {local_user: {"ed25519:abc": "base64+signature"}},
  1161. }
  1162. device_key_2a: JsonDict = {
  1163. "user_id": local_user,
  1164. "device_id": device_2,
  1165. "algorithms": [
  1166. "m.olm.curve25519-aes-sha2",
  1167. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  1168. ],
  1169. "keys": {
  1170. "ed25519:def": "base64+ed25519+key",
  1171. "curve25519:def": "base64+curve25519+key",
  1172. },
  1173. "signatures": {local_user: {"ed25519:def": "base64+signature"}},
  1174. }
  1175. device_key_2b: JsonDict = {
  1176. "user_id": local_user,
  1177. "device_id": device_2,
  1178. "algorithms": [
  1179. "m.olm.curve25519-aes-sha2",
  1180. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  1181. ],
  1182. # The device ID is the same (above), but the keys are different.
  1183. "keys": {
  1184. "ed25519:xyz": "base64+ed25519+key",
  1185. "curve25519:xyz": "base64+curve25519+key",
  1186. },
  1187. "signatures": {local_user: {"ed25519:xyz": "base64+signature"}},
  1188. }
  1189. device_key_3: JsonDict = {
  1190. "user_id": local_user,
  1191. "device_id": device_3,
  1192. "algorithms": [
  1193. "m.olm.curve25519-aes-sha2",
  1194. RoomEncryptionAlgorithms.MEGOLM_V1_AES_SHA2,
  1195. ],
  1196. "keys": {
  1197. "ed25519:jkl": "base64+ed25519+key",
  1198. "curve25519:jkl": "base64+curve25519+key",
  1199. },
  1200. "signatures": {local_user: {"ed25519:jkl": "base64+signature"}},
  1201. }
  1202. # Upload keys for devices 1 & 2a.
  1203. self.get_success(
  1204. self.handler.upload_keys_for_user(
  1205. local_user, device_1, {"device_keys": device_key_1}
  1206. )
  1207. )
  1208. self.get_success(
  1209. self.handler.upload_keys_for_user(
  1210. local_user, device_2, {"device_keys": device_key_2a}
  1211. )
  1212. )
  1213. # Inject an appservice interested in this user.
  1214. appservice = ApplicationService(
  1215. token="i_am_an_app_service",
  1216. id="1234",
  1217. namespaces={"users": [{"regex": r"@boris:.+", "exclusive": True}]},
  1218. # Note: this user does not have to match the regex above
  1219. sender="@as_main:test",
  1220. )
  1221. self.hs.get_datastores().main.services_cache = [appservice]
  1222. self.hs.get_datastores().main.exclusive_user_regex = _make_exclusive_regex(
  1223. [appservice]
  1224. )
  1225. # Setup a response.
  1226. self.appservice_api.query_keys.return_value = {
  1227. "device_keys": {
  1228. local_user: {device_2: device_key_2b, device_3: device_key_3}
  1229. }
  1230. }
  1231. # Request all devices.
  1232. res = self.get_success(self.handler.query_local_devices({local_user: None}))
  1233. self.assertIn(local_user, res)
  1234. for res_key in res[local_user].values():
  1235. res_key.pop("unsigned", None)
  1236. self.assertDictEqual(
  1237. res,
  1238. {
  1239. local_user: {
  1240. device_1: device_key_1,
  1241. device_2: device_key_2b,
  1242. device_3: device_key_3,
  1243. }
  1244. },
  1245. )