e2e_keys.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. # Copyright 2016 OpenMarket Ltd
  2. # Copyright 2018-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. import logging
  17. from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple
  18. import attr
  19. from canonicaljson import encode_canonical_json
  20. from signedjson.key import VerifyKey, decode_verify_key_bytes
  21. from signedjson.sign import SignatureVerifyException, verify_signed_json
  22. from unpaddedbase64 import decode_base64
  23. from twisted.internet import defer
  24. from synapse.api.constants import EduTypes
  25. from synapse.api.errors import CodeMessageException, Codes, NotFoundError, SynapseError
  26. from synapse.logging.context import make_deferred_yieldable, run_in_background
  27. from synapse.logging.opentracing import log_kv, set_tag, tag_args, trace
  28. from synapse.replication.http.devices import ReplicationUserDevicesResyncRestServlet
  29. from synapse.types import (
  30. JsonDict,
  31. UserID,
  32. get_domain_from_id,
  33. get_verify_key_from_cross_signing_key,
  34. )
  35. from synapse.util import json_decoder, unwrapFirstError
  36. from synapse.util.async_helpers import Linearizer
  37. from synapse.util.retryutils import NotRetryingDestination
  38. if TYPE_CHECKING:
  39. from synapse.server import HomeServer
  40. logger = logging.getLogger(__name__)
  41. class E2eKeysHandler:
  42. def __init__(self, hs: "HomeServer"):
  43. self.store = hs.get_datastores().main
  44. self.federation = hs.get_federation_client()
  45. self.device_handler = hs.get_device_handler()
  46. self.is_mine = hs.is_mine
  47. self.clock = hs.get_clock()
  48. self._edu_updater = SigningKeyEduUpdater(hs, self)
  49. federation_registry = hs.get_federation_registry()
  50. self._is_master = hs.config.worker.worker_app is None
  51. if not self._is_master:
  52. self._user_device_resync_client = (
  53. ReplicationUserDevicesResyncRestServlet.make_client(hs)
  54. )
  55. else:
  56. # Only register this edu handler on master as it requires writing
  57. # device updates to the db
  58. federation_registry.register_edu_handler(
  59. EduTypes.SIGNING_KEY_UPDATE,
  60. self._edu_updater.incoming_signing_key_update,
  61. )
  62. # also handle the unstable version
  63. # FIXME: remove this when enough servers have upgraded
  64. federation_registry.register_edu_handler(
  65. EduTypes.UNSTABLE_SIGNING_KEY_UPDATE,
  66. self._edu_updater.incoming_signing_key_update,
  67. )
  68. # doesn't really work as part of the generic query API, because the
  69. # query request requires an object POST, but we abuse the
  70. # "query handler" interface.
  71. federation_registry.register_query_handler(
  72. "client_keys", self.on_federation_query_client_keys
  73. )
  74. # Limit the number of in-flight requests from a single device.
  75. self._query_devices_linearizer = Linearizer(
  76. name="query_devices",
  77. max_count=10,
  78. )
  79. @trace
  80. async def query_devices(
  81. self, query_body: JsonDict, timeout: int, from_user_id: str, from_device_id: str
  82. ) -> JsonDict:
  83. """Handle a device key query from a client
  84. {
  85. "device_keys": {
  86. "<user_id>": ["<device_id>"]
  87. }
  88. }
  89. ->
  90. {
  91. "device_keys": {
  92. "<user_id>": {
  93. "<device_id>": {
  94. ...
  95. }
  96. }
  97. }
  98. }
  99. Args:
  100. from_user_id: the user making the query. This is used when
  101. adding cross-signing signatures to limit what signatures users
  102. can see.
  103. from_device_id: the device making the query. This is used to limit
  104. the number of in-flight queries at a time.
  105. """
  106. async with self._query_devices_linearizer.queue((from_user_id, from_device_id)):
  107. device_keys_query: Dict[str, Iterable[str]] = query_body.get(
  108. "device_keys", {}
  109. )
  110. # separate users by domain.
  111. # make a map from domain to user_id to device_ids
  112. local_query = {}
  113. remote_queries = {}
  114. for user_id, device_ids in device_keys_query.items():
  115. # we use UserID.from_string to catch invalid user ids
  116. if self.is_mine(UserID.from_string(user_id)):
  117. local_query[user_id] = device_ids
  118. else:
  119. remote_queries[user_id] = device_ids
  120. set_tag("local_key_query", local_query)
  121. set_tag("remote_key_query", remote_queries)
  122. # First get local devices.
  123. # A map of destination -> failure response.
  124. failures: Dict[str, JsonDict] = {}
  125. results = {}
  126. if local_query:
  127. local_result = await self.query_local_devices(local_query)
  128. for user_id, keys in local_result.items():
  129. if user_id in local_query:
  130. results[user_id] = keys
  131. # Get cached cross-signing keys
  132. cross_signing_keys = await self.get_cross_signing_keys_from_cache(
  133. device_keys_query, from_user_id
  134. )
  135. # Now attempt to get any remote devices from our local cache.
  136. # A map of destination -> user ID -> device IDs.
  137. remote_queries_not_in_cache: Dict[str, Dict[str, Iterable[str]]] = {}
  138. if remote_queries:
  139. query_list: List[Tuple[str, Optional[str]]] = []
  140. for user_id, device_ids in remote_queries.items():
  141. if device_ids:
  142. query_list.extend(
  143. (user_id, device_id) for device_id in device_ids
  144. )
  145. else:
  146. query_list.append((user_id, None))
  147. (
  148. user_ids_not_in_cache,
  149. remote_results,
  150. ) = await self.store.get_user_devices_from_cache(query_list)
  151. for user_id, devices in remote_results.items():
  152. user_devices = results.setdefault(user_id, {})
  153. for device_id, device in devices.items():
  154. keys = device.get("keys", None)
  155. device_display_name = device.get("device_display_name", None)
  156. if keys:
  157. result = dict(keys)
  158. unsigned = result.setdefault("unsigned", {})
  159. if device_display_name:
  160. unsigned["device_display_name"] = device_display_name
  161. user_devices[device_id] = result
  162. # check for missing cross-signing keys.
  163. for user_id in remote_queries.keys():
  164. cached_cross_master = user_id in cross_signing_keys["master_keys"]
  165. cached_cross_selfsigning = (
  166. user_id in cross_signing_keys["self_signing_keys"]
  167. )
  168. # check if we are missing only one of cross-signing master or
  169. # self-signing key, but the other one is cached.
  170. # as we need both, this will issue a federation request.
  171. # if we don't have any of the keys, either the user doesn't have
  172. # cross-signing set up, or the cached device list
  173. # is not (yet) updated.
  174. if cached_cross_master ^ cached_cross_selfsigning:
  175. user_ids_not_in_cache.add(user_id)
  176. # add those users to the list to fetch over federation.
  177. for user_id in user_ids_not_in_cache:
  178. domain = get_domain_from_id(user_id)
  179. r = remote_queries_not_in_cache.setdefault(domain, {})
  180. r[user_id] = remote_queries[user_id]
  181. # Now fetch any devices that we don't have in our cache
  182. await make_deferred_yieldable(
  183. defer.gatherResults(
  184. [
  185. run_in_background(
  186. self._query_devices_for_destination,
  187. results,
  188. cross_signing_keys,
  189. failures,
  190. destination,
  191. queries,
  192. timeout,
  193. )
  194. for destination, queries in remote_queries_not_in_cache.items()
  195. ],
  196. consumeErrors=True,
  197. ).addErrback(unwrapFirstError)
  198. )
  199. ret = {"device_keys": results, "failures": failures}
  200. ret.update(cross_signing_keys)
  201. return ret
  202. @trace
  203. async def _query_devices_for_destination(
  204. self,
  205. results: JsonDict,
  206. cross_signing_keys: JsonDict,
  207. failures: Dict[str, JsonDict],
  208. destination: str,
  209. destination_query: Dict[str, Iterable[str]],
  210. timeout: int,
  211. ) -> None:
  212. """This is called when we are querying the device list of a user on
  213. a remote homeserver and their device list is not in the device list
  214. cache. If we share a room with this user and we're not querying for
  215. specific user we will update the cache with their device list.
  216. Args:
  217. results: A map from user ID to their device keys, which gets
  218. updated with the newly fetched keys.
  219. cross_signing_keys: Map from user ID to their cross signing keys,
  220. which gets updated with the newly fetched keys.
  221. failures: Map of destinations to failures that have occurred while
  222. attempting to fetch keys.
  223. destination: The remote server to query
  224. destination_query: The query dict of devices to query the remote
  225. server for.
  226. timeout: The timeout for remote HTTP requests.
  227. """
  228. # We first consider whether we wish to update the device list cache with
  229. # the users device list. We want to track a user's devices when the
  230. # authenticated user shares a room with the queried user and the query
  231. # has not specified a particular device.
  232. # If we update the cache for the queried user we remove them from further
  233. # queries. We use the more efficient batched query_client_keys for all
  234. # remaining users
  235. user_ids_updated = []
  236. for (user_id, device_list) in destination_query.items():
  237. if user_id in user_ids_updated:
  238. continue
  239. if device_list:
  240. continue
  241. room_ids = await self.store.get_rooms_for_user(user_id)
  242. if not room_ids:
  243. continue
  244. # We've decided we're sharing a room with this user and should
  245. # probably be tracking their device lists. However, we haven't
  246. # done an initial sync on the device list so we do it now.
  247. try:
  248. if self._is_master:
  249. resync_results = await self.device_handler.device_list_updater.user_device_resync(
  250. user_id
  251. )
  252. else:
  253. resync_results = await self._user_device_resync_client(
  254. user_id=user_id
  255. )
  256. # Add the device keys to the results.
  257. user_devices = resync_results["devices"]
  258. user_results = results.setdefault(user_id, {})
  259. for device in user_devices:
  260. user_results[device["device_id"]] = device["keys"]
  261. user_ids_updated.append(user_id)
  262. # Add any cross signing keys to the results.
  263. master_key = resync_results.get("master_key")
  264. self_signing_key = resync_results.get("self_signing_key")
  265. if master_key:
  266. cross_signing_keys["master_keys"][user_id] = master_key
  267. if self_signing_key:
  268. cross_signing_keys["self_signing_keys"][user_id] = self_signing_key
  269. except Exception as e:
  270. failures[destination] = _exception_to_failure(e)
  271. if len(destination_query) == len(user_ids_updated):
  272. # We've updated all the users in the query and we do not need to
  273. # make any further remote calls.
  274. return
  275. # Remove all the users from the query which we have updated
  276. for user_id in user_ids_updated:
  277. destination_query.pop(user_id)
  278. try:
  279. remote_result = await self.federation.query_client_keys(
  280. destination, {"device_keys": destination_query}, timeout=timeout
  281. )
  282. for user_id, keys in remote_result["device_keys"].items():
  283. if user_id in destination_query:
  284. results[user_id] = keys
  285. if "master_keys" in remote_result:
  286. for user_id, key in remote_result["master_keys"].items():
  287. if user_id in destination_query:
  288. cross_signing_keys["master_keys"][user_id] = key
  289. if "self_signing_keys" in remote_result:
  290. for user_id, key in remote_result["self_signing_keys"].items():
  291. if user_id in destination_query:
  292. cross_signing_keys["self_signing_keys"][user_id] = key
  293. except Exception as e:
  294. failure = _exception_to_failure(e)
  295. failures[destination] = failure
  296. set_tag("error", True)
  297. set_tag("reason", failure)
  298. return
  299. async def get_cross_signing_keys_from_cache(
  300. self, query: Iterable[str], from_user_id: Optional[str]
  301. ) -> Dict[str, Dict[str, dict]]:
  302. """Get cross-signing keys for users from the database
  303. Args:
  304. query: an iterable of user IDs. A dict whose keys
  305. are user IDs satisfies this, so the query format used for
  306. query_devices can be used here.
  307. from_user_id: the user making the query. This is used when
  308. adding cross-signing signatures to limit what signatures users
  309. can see.
  310. Returns:
  311. A map from (master_keys|self_signing_keys|user_signing_keys) -> user_id -> key
  312. """
  313. master_keys = {}
  314. self_signing_keys = {}
  315. user_signing_keys = {}
  316. user_ids = list(query)
  317. keys = await self.store.get_e2e_cross_signing_keys_bulk(user_ids, from_user_id)
  318. for user_id, user_info in keys.items():
  319. if user_info is None:
  320. continue
  321. if "master" in user_info:
  322. master_keys[user_id] = user_info["master"]
  323. if "self_signing" in user_info:
  324. self_signing_keys[user_id] = user_info["self_signing"]
  325. # users can see other users' master and self-signing keys, but can
  326. # only see their own user-signing keys
  327. if from_user_id:
  328. from_user_key = keys.get(from_user_id)
  329. if from_user_key and "user_signing" in from_user_key:
  330. user_signing_keys[from_user_id] = from_user_key["user_signing"]
  331. return {
  332. "master_keys": master_keys,
  333. "self_signing_keys": self_signing_keys,
  334. "user_signing_keys": user_signing_keys,
  335. }
  336. @trace
  337. async def query_local_devices(
  338. self, query: Dict[str, Optional[List[str]]]
  339. ) -> Dict[str, Dict[str, dict]]:
  340. """Get E2E device keys for local users
  341. Args:
  342. query: map from user_id to a list
  343. of devices to query (None for all devices)
  344. Returns:
  345. A map from user_id -> device_id -> device details
  346. """
  347. set_tag("local_query", query)
  348. local_query: List[Tuple[str, Optional[str]]] = []
  349. result_dict: Dict[str, Dict[str, dict]] = {}
  350. for user_id, device_ids in query.items():
  351. # we use UserID.from_string to catch invalid user ids
  352. if not self.is_mine(UserID.from_string(user_id)):
  353. logger.warning("Request for keys for non-local user %s", user_id)
  354. log_kv(
  355. {
  356. "message": "Requested a local key for a user which"
  357. " was not local to the homeserver",
  358. "user_id": user_id,
  359. }
  360. )
  361. set_tag("error", True)
  362. raise SynapseError(400, "Not a user here")
  363. if not device_ids:
  364. local_query.append((user_id, None))
  365. else:
  366. for device_id in device_ids:
  367. local_query.append((user_id, device_id))
  368. # make sure that each queried user appears in the result dict
  369. result_dict[user_id] = {}
  370. results = await self.store.get_e2e_device_keys_for_cs_api(local_query)
  371. # Build the result structure
  372. for user_id, device_keys in results.items():
  373. for device_id, device_info in device_keys.items():
  374. result_dict[user_id][device_id] = device_info
  375. log_kv(results)
  376. return result_dict
  377. async def on_federation_query_client_keys(
  378. self, query_body: Dict[str, Dict[str, Optional[List[str]]]]
  379. ) -> JsonDict:
  380. """Handle a device key query from a federated server"""
  381. device_keys_query: Dict[str, Optional[List[str]]] = query_body.get(
  382. "device_keys", {}
  383. )
  384. res = await self.query_local_devices(device_keys_query)
  385. ret = {"device_keys": res}
  386. # add in the cross-signing keys
  387. cross_signing_keys = await self.get_cross_signing_keys_from_cache(
  388. device_keys_query, None
  389. )
  390. ret.update(cross_signing_keys)
  391. return ret
  392. @trace
  393. async def claim_one_time_keys(
  394. self, query: Dict[str, Dict[str, Dict[str, str]]], timeout: int
  395. ) -> JsonDict:
  396. local_query: List[Tuple[str, str, str]] = []
  397. remote_queries: Dict[str, Dict[str, Dict[str, str]]] = {}
  398. for user_id, one_time_keys in query.get("one_time_keys", {}).items():
  399. # we use UserID.from_string to catch invalid user ids
  400. if self.is_mine(UserID.from_string(user_id)):
  401. for device_id, algorithm in one_time_keys.items():
  402. local_query.append((user_id, device_id, algorithm))
  403. else:
  404. domain = get_domain_from_id(user_id)
  405. remote_queries.setdefault(domain, {})[user_id] = one_time_keys
  406. set_tag("local_key_query", local_query)
  407. set_tag("remote_key_query", remote_queries)
  408. results = await self.store.claim_e2e_one_time_keys(local_query)
  409. # A map of user ID -> device ID -> key ID -> key.
  410. json_result: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
  411. failures: Dict[str, JsonDict] = {}
  412. for user_id, device_keys in results.items():
  413. for device_id, keys in device_keys.items():
  414. for key_id, json_str in keys.items():
  415. json_result.setdefault(user_id, {})[device_id] = {
  416. key_id: json_decoder.decode(json_str)
  417. }
  418. @trace
  419. async def claim_client_keys(destination: str) -> None:
  420. set_tag("destination", destination)
  421. device_keys = remote_queries[destination]
  422. try:
  423. remote_result = await self.federation.claim_client_keys(
  424. destination, {"one_time_keys": device_keys}, timeout=timeout
  425. )
  426. for user_id, keys in remote_result["one_time_keys"].items():
  427. if user_id in device_keys:
  428. json_result[user_id] = keys
  429. except Exception as e:
  430. failure = _exception_to_failure(e)
  431. failures[destination] = failure
  432. set_tag("error", True)
  433. set_tag("reason", failure)
  434. await make_deferred_yieldable(
  435. defer.gatherResults(
  436. [
  437. run_in_background(claim_client_keys, destination)
  438. for destination in remote_queries
  439. ],
  440. consumeErrors=True,
  441. )
  442. )
  443. logger.info(
  444. "Claimed one-time-keys: %s",
  445. ",".join(
  446. (
  447. "%s for %s:%s" % (key_id, user_id, device_id)
  448. for user_id, user_keys in json_result.items()
  449. for device_id, device_keys in user_keys.items()
  450. for key_id, _ in device_keys.items()
  451. )
  452. ),
  453. )
  454. log_kv({"one_time_keys": json_result, "failures": failures})
  455. return {"one_time_keys": json_result, "failures": failures}
  456. @tag_args
  457. async def upload_keys_for_user(
  458. self, user_id: str, device_id: str, keys: JsonDict
  459. ) -> JsonDict:
  460. time_now = self.clock.time_msec()
  461. # TODO: Validate the JSON to make sure it has the right keys.
  462. device_keys = keys.get("device_keys", None)
  463. if device_keys:
  464. logger.info(
  465. "Updating device_keys for device %r for user %s at %d",
  466. device_id,
  467. user_id,
  468. time_now,
  469. )
  470. log_kv(
  471. {
  472. "message": "Updating device_keys for user.",
  473. "user_id": user_id,
  474. "device_id": device_id,
  475. }
  476. )
  477. # TODO: Sign the JSON with the server key
  478. changed = await self.store.set_e2e_device_keys(
  479. user_id, device_id, time_now, device_keys
  480. )
  481. if changed:
  482. # Only notify about device updates *if* the keys actually changed
  483. await self.device_handler.notify_device_update(user_id, [device_id])
  484. else:
  485. log_kv({"message": "Not updating device_keys for user", "user_id": user_id})
  486. one_time_keys = keys.get("one_time_keys", None)
  487. if one_time_keys:
  488. log_kv(
  489. {
  490. "message": "Updating one_time_keys for device.",
  491. "user_id": user_id,
  492. "device_id": device_id,
  493. }
  494. )
  495. await self._upload_one_time_keys_for_user(
  496. user_id, device_id, time_now, one_time_keys
  497. )
  498. else:
  499. log_kv(
  500. {"message": "Did not update one_time_keys", "reason": "no keys given"}
  501. )
  502. fallback_keys = keys.get("fallback_keys") or keys.get(
  503. "org.matrix.msc2732.fallback_keys"
  504. )
  505. if fallback_keys and isinstance(fallback_keys, dict):
  506. log_kv(
  507. {
  508. "message": "Updating fallback_keys for device.",
  509. "user_id": user_id,
  510. "device_id": device_id,
  511. }
  512. )
  513. await self.store.set_e2e_fallback_keys(user_id, device_id, fallback_keys)
  514. elif fallback_keys:
  515. log_kv({"message": "Did not update fallback_keys", "reason": "not a dict"})
  516. else:
  517. log_kv(
  518. {"message": "Did not update fallback_keys", "reason": "no keys given"}
  519. )
  520. # the device should have been registered already, but it may have been
  521. # deleted due to a race with a DELETE request. Or we may be using an
  522. # old access_token without an associated device_id. Either way, we
  523. # need to double-check the device is registered to avoid ending up with
  524. # keys without a corresponding device.
  525. await self.device_handler.check_device_registered(user_id, device_id)
  526. result = await self.store.count_e2e_one_time_keys(user_id, device_id)
  527. set_tag("one_time_key_counts", result)
  528. return {"one_time_key_counts": result}
  529. async def _upload_one_time_keys_for_user(
  530. self, user_id: str, device_id: str, time_now: int, one_time_keys: JsonDict
  531. ) -> None:
  532. logger.info(
  533. "Adding one_time_keys %r for device %r for user %r at %d",
  534. one_time_keys.keys(),
  535. device_id,
  536. user_id,
  537. time_now,
  538. )
  539. # make a list of (alg, id, key) tuples
  540. key_list = []
  541. for key_id, key_obj in one_time_keys.items():
  542. algorithm, key_id = key_id.split(":")
  543. key_list.append((algorithm, key_id, key_obj))
  544. # First we check if we have already persisted any of the keys.
  545. existing_key_map = await self.store.get_e2e_one_time_keys(
  546. user_id, device_id, [k_id for _, k_id, _ in key_list]
  547. )
  548. new_keys = [] # Keys that we need to insert. (alg, id, json) tuples.
  549. for algorithm, key_id, key in key_list:
  550. ex_json = existing_key_map.get((algorithm, key_id), None)
  551. if ex_json:
  552. if not _one_time_keys_match(ex_json, key):
  553. raise SynapseError(
  554. 400,
  555. (
  556. "One time key %s:%s already exists. "
  557. "Old key: %s; new key: %r"
  558. )
  559. % (algorithm, key_id, ex_json, key),
  560. )
  561. else:
  562. new_keys.append(
  563. (algorithm, key_id, encode_canonical_json(key).decode("ascii"))
  564. )
  565. log_kv({"message": "Inserting new one_time_keys.", "keys": new_keys})
  566. await self.store.add_e2e_one_time_keys(user_id, device_id, time_now, new_keys)
  567. async def upload_signing_keys_for_user(
  568. self, user_id: str, keys: JsonDict
  569. ) -> JsonDict:
  570. """Upload signing keys for cross-signing
  571. Args:
  572. user_id: the user uploading the keys
  573. keys: the signing keys
  574. """
  575. # if a master key is uploaded, then check it. Otherwise, load the
  576. # stored master key, to check signatures on other keys
  577. if "master_key" in keys:
  578. master_key = keys["master_key"]
  579. _check_cross_signing_key(master_key, user_id, "master")
  580. else:
  581. master_key = await self.store.get_e2e_cross_signing_key(user_id, "master")
  582. # if there is no master key, then we can't do anything, because all the
  583. # other cross-signing keys need to be signed by the master key
  584. if not master_key:
  585. raise SynapseError(400, "No master key available", Codes.MISSING_PARAM)
  586. try:
  587. master_key_id, master_verify_key = get_verify_key_from_cross_signing_key(
  588. master_key
  589. )
  590. except ValueError:
  591. if "master_key" in keys:
  592. # the invalid key came from the request
  593. raise SynapseError(400, "Invalid master key", Codes.INVALID_PARAM)
  594. else:
  595. # the invalid key came from the database
  596. logger.error("Invalid master key found for user %s", user_id)
  597. raise SynapseError(500, "Invalid master key")
  598. # for the other cross-signing keys, make sure that they have valid
  599. # signatures from the master key
  600. if "self_signing_key" in keys:
  601. self_signing_key = keys["self_signing_key"]
  602. _check_cross_signing_key(
  603. self_signing_key, user_id, "self_signing", master_verify_key
  604. )
  605. if "user_signing_key" in keys:
  606. user_signing_key = keys["user_signing_key"]
  607. _check_cross_signing_key(
  608. user_signing_key, user_id, "user_signing", master_verify_key
  609. )
  610. # if everything checks out, then store the keys and send notifications
  611. deviceids = []
  612. if "master_key" in keys:
  613. await self.store.set_e2e_cross_signing_key(user_id, "master", master_key)
  614. deviceids.append(master_verify_key.version)
  615. if "self_signing_key" in keys:
  616. await self.store.set_e2e_cross_signing_key(
  617. user_id, "self_signing", self_signing_key
  618. )
  619. try:
  620. deviceids.append(
  621. get_verify_key_from_cross_signing_key(self_signing_key)[1].version
  622. )
  623. except ValueError:
  624. raise SynapseError(400, "Invalid self-signing key", Codes.INVALID_PARAM)
  625. if "user_signing_key" in keys:
  626. await self.store.set_e2e_cross_signing_key(
  627. user_id, "user_signing", user_signing_key
  628. )
  629. # the signature stream matches the semantics that we want for
  630. # user-signing key updates: only the user themselves is notified of
  631. # their own user-signing key updates
  632. await self.device_handler.notify_user_signature_update(user_id, [user_id])
  633. # master key and self-signing key updates match the semantics of device
  634. # list updates: all users who share an encrypted room are notified
  635. if len(deviceids):
  636. await self.device_handler.notify_device_update(user_id, deviceids)
  637. return {}
  638. async def upload_signatures_for_device_keys(
  639. self, user_id: str, signatures: JsonDict
  640. ) -> JsonDict:
  641. """Upload device signatures for cross-signing
  642. Args:
  643. user_id: the user uploading the signatures
  644. signatures: map of users to devices to signed keys. This is the submission
  645. from the user; an exception will be raised if it is malformed.
  646. Returns:
  647. The response to be sent back to the client. The response will have
  648. a "failures" key, which will be a dict mapping users to devices
  649. to errors for the signatures that failed.
  650. Raises:
  651. SynapseError: if the signatures dict is not valid.
  652. """
  653. failures = {}
  654. # signatures to be stored. Each item will be a SignatureListItem
  655. signature_list = []
  656. # split between checking signatures for own user and signatures for
  657. # other users, since we verify them with different keys
  658. self_signatures = signatures.get(user_id, {})
  659. other_signatures = {k: v for k, v in signatures.items() if k != user_id}
  660. self_signature_list, self_failures = await self._process_self_signatures(
  661. user_id, self_signatures
  662. )
  663. signature_list.extend(self_signature_list)
  664. failures.update(self_failures)
  665. other_signature_list, other_failures = await self._process_other_signatures(
  666. user_id, other_signatures
  667. )
  668. signature_list.extend(other_signature_list)
  669. failures.update(other_failures)
  670. # store the signature, and send the appropriate notifications for sync
  671. logger.debug("upload signature failures: %r", failures)
  672. await self.store.store_e2e_cross_signing_signatures(user_id, signature_list)
  673. self_device_ids = [item.target_device_id for item in self_signature_list]
  674. if self_device_ids:
  675. await self.device_handler.notify_device_update(user_id, self_device_ids)
  676. signed_users = [item.target_user_id for item in other_signature_list]
  677. if signed_users:
  678. await self.device_handler.notify_user_signature_update(
  679. user_id, signed_users
  680. )
  681. return {"failures": failures}
  682. async def _process_self_signatures(
  683. self, user_id: str, signatures: JsonDict
  684. ) -> Tuple[List["SignatureListItem"], Dict[str, Dict[str, dict]]]:
  685. """Process uploaded signatures of the user's own keys.
  686. Signatures of the user's own keys from this API come in two forms:
  687. - signatures of the user's devices by the user's self-signing key,
  688. - signatures of the user's master key by the user's devices.
  689. Args:
  690. user_id (string): the user uploading the keys
  691. signatures (dict[string, dict]): map of devices to signed keys
  692. Returns:
  693. A tuple of a list of signatures to store, and a map of users to
  694. devices to failure reasons
  695. Raises:
  696. SynapseError: if the input is malformed
  697. """
  698. signature_list: List["SignatureListItem"] = []
  699. failures: Dict[str, Dict[str, JsonDict]] = {}
  700. if not signatures:
  701. return signature_list, failures
  702. if not isinstance(signatures, dict):
  703. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  704. try:
  705. # get our self-signing key to verify the signatures
  706. (
  707. _,
  708. self_signing_key_id,
  709. self_signing_verify_key,
  710. ) = await self._get_e2e_cross_signing_verify_key(user_id, "self_signing")
  711. # get our master key, since we may have received a signature of it.
  712. # We need to fetch it here so that we know what its key ID is, so
  713. # that we can check if a signature that was sent is a signature of
  714. # the master key or of a device
  715. (
  716. master_key,
  717. _,
  718. master_verify_key,
  719. ) = await self._get_e2e_cross_signing_verify_key(user_id, "master")
  720. # fetch our stored devices. This is used to 1. verify
  721. # signatures on the master key, and 2. to compare with what
  722. # was sent if the device was signed
  723. devices = await self.store.get_e2e_device_keys_for_cs_api([(user_id, None)])
  724. if user_id not in devices:
  725. raise NotFoundError("No device keys found")
  726. devices = devices[user_id]
  727. except SynapseError as e:
  728. failure = _exception_to_failure(e)
  729. failures[user_id] = {device: failure for device in signatures.keys()}
  730. return signature_list, failures
  731. for device_id, device in signatures.items():
  732. # make sure submitted data is in the right form
  733. if not isinstance(device, dict):
  734. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  735. try:
  736. if "signatures" not in device or user_id not in device["signatures"]:
  737. # no signature was sent
  738. raise SynapseError(
  739. 400, "Invalid signature", Codes.INVALID_SIGNATURE
  740. )
  741. if device_id == master_verify_key.version:
  742. # The signature is of the master key. This needs to be
  743. # handled differently from signatures of normal devices.
  744. master_key_signature_list = self._check_master_key_signature(
  745. user_id, device_id, device, master_key, devices
  746. )
  747. signature_list.extend(master_key_signature_list)
  748. continue
  749. # at this point, we have a device that should be signed
  750. # by the self-signing key
  751. if self_signing_key_id not in device["signatures"][user_id]:
  752. # no signature was sent
  753. raise SynapseError(
  754. 400, "Invalid signature", Codes.INVALID_SIGNATURE
  755. )
  756. try:
  757. stored_device = devices[device_id]
  758. except KeyError:
  759. raise NotFoundError("Unknown device")
  760. if self_signing_key_id in stored_device.get("signatures", {}).get(
  761. user_id, {}
  762. ):
  763. # we already have a signature on this device, so we
  764. # can skip it, since it should be exactly the same
  765. continue
  766. _check_device_signature(
  767. user_id, self_signing_verify_key, device, stored_device
  768. )
  769. signature = device["signatures"][user_id][self_signing_key_id]
  770. signature_list.append(
  771. SignatureListItem(
  772. self_signing_key_id, user_id, device_id, signature
  773. )
  774. )
  775. except SynapseError as e:
  776. failures.setdefault(user_id, {})[device_id] = _exception_to_failure(e)
  777. return signature_list, failures
  778. def _check_master_key_signature(
  779. self,
  780. user_id: str,
  781. master_key_id: str,
  782. signed_master_key: JsonDict,
  783. stored_master_key: JsonDict,
  784. devices: Dict[str, Dict[str, JsonDict]],
  785. ) -> List["SignatureListItem"]:
  786. """Check signatures of a user's master key made by their devices.
  787. Args:
  788. user_id: the user whose master key is being checked
  789. master_key_id: the ID of the user's master key
  790. signed_master_key: the user's signed master key that was uploaded
  791. stored_master_key: our previously-stored copy of the user's master key
  792. devices: the user's devices
  793. Returns:
  794. A list of signatures to store
  795. Raises:
  796. SynapseError: if a signature is invalid
  797. """
  798. # for each device that signed the master key, check the signature.
  799. master_key_signature_list = []
  800. sigs = signed_master_key["signatures"]
  801. for signing_key_id, signature in sigs[user_id].items():
  802. _, signing_device_id = signing_key_id.split(":", 1)
  803. if (
  804. signing_device_id not in devices
  805. or signing_key_id not in devices[signing_device_id]["keys"]
  806. ):
  807. # signed by an unknown device, or the
  808. # device does not have the key
  809. raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
  810. # get the key and check the signature
  811. pubkey = devices[signing_device_id]["keys"][signing_key_id]
  812. verify_key = decode_verify_key_bytes(signing_key_id, decode_base64(pubkey))
  813. _check_device_signature(
  814. user_id, verify_key, signed_master_key, stored_master_key
  815. )
  816. master_key_signature_list.append(
  817. SignatureListItem(signing_key_id, user_id, master_key_id, signature)
  818. )
  819. return master_key_signature_list
  820. async def _process_other_signatures(
  821. self, user_id: str, signatures: Dict[str, dict]
  822. ) -> Tuple[List["SignatureListItem"], Dict[str, Dict[str, dict]]]:
  823. """Process uploaded signatures of other users' keys. These will be the
  824. target user's master keys, signed by the uploading user's user-signing
  825. key.
  826. Args:
  827. user_id: the user uploading the keys
  828. signatures: map of users to devices to signed keys
  829. Returns:
  830. A list of signatures to store, and a map of users to devices to failure
  831. reasons
  832. Raises:
  833. SynapseError: if the input is malformed
  834. """
  835. signature_list: List["SignatureListItem"] = []
  836. failures: Dict[str, Dict[str, JsonDict]] = {}
  837. if not signatures:
  838. return signature_list, failures
  839. try:
  840. # get our user-signing key to verify the signatures
  841. (
  842. user_signing_key,
  843. user_signing_key_id,
  844. user_signing_verify_key,
  845. ) = await self._get_e2e_cross_signing_verify_key(user_id, "user_signing")
  846. except SynapseError as e:
  847. failure = _exception_to_failure(e)
  848. for user, devicemap in signatures.items():
  849. failures[user] = {device_id: failure for device_id in devicemap.keys()}
  850. return signature_list, failures
  851. for target_user, devicemap in signatures.items():
  852. # make sure submitted data is in the right form
  853. if not isinstance(devicemap, dict):
  854. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  855. for device in devicemap.values():
  856. if not isinstance(device, dict):
  857. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  858. device_id = None
  859. try:
  860. # get the target user's master key, to make sure it matches
  861. # what was sent
  862. (
  863. master_key,
  864. master_key_id,
  865. _,
  866. ) = await self._get_e2e_cross_signing_verify_key(
  867. target_user, "master", user_id
  868. )
  869. # make sure that the target user's master key is the one that
  870. # was signed (and no others)
  871. device_id = master_key_id.split(":", 1)[1]
  872. if device_id not in devicemap:
  873. logger.debug(
  874. "upload signature: could not find signature for device %s",
  875. device_id,
  876. )
  877. # set device to None so that the failure gets
  878. # marked on all the signatures
  879. device_id = None
  880. raise NotFoundError("Unknown device")
  881. key = devicemap[device_id]
  882. other_devices = [k for k in devicemap.keys() if k != device_id]
  883. if other_devices:
  884. # other devices were signed -- mark those as failures
  885. logger.debug("upload signature: too many devices specified")
  886. failure = _exception_to_failure(NotFoundError("Unknown device"))
  887. failures[target_user] = {
  888. device: failure for device in other_devices
  889. }
  890. if user_signing_key_id in master_key.get("signatures", {}).get(
  891. user_id, {}
  892. ):
  893. # we already have the signature, so we can skip it
  894. continue
  895. _check_device_signature(
  896. user_id, user_signing_verify_key, key, master_key
  897. )
  898. signature = key["signatures"][user_id][user_signing_key_id]
  899. signature_list.append(
  900. SignatureListItem(
  901. user_signing_key_id, target_user, device_id, signature
  902. )
  903. )
  904. except SynapseError as e:
  905. failure = _exception_to_failure(e)
  906. if device_id is None:
  907. failures[target_user] = {
  908. device_id: failure for device_id in devicemap.keys()
  909. }
  910. else:
  911. failures.setdefault(target_user, {})[device_id] = failure
  912. return signature_list, failures
  913. async def _get_e2e_cross_signing_verify_key(
  914. self, user_id: str, key_type: str, from_user_id: Optional[str] = None
  915. ) -> Tuple[JsonDict, str, VerifyKey]:
  916. """Fetch locally or remotely query for a cross-signing public key.
  917. First, attempt to fetch the cross-signing public key from storage.
  918. If that fails, query the keys from the homeserver they belong to
  919. and update our local copy.
  920. Args:
  921. user_id: the user whose key should be fetched
  922. key_type: the type of key to fetch
  923. from_user_id: the user that we are fetching the keys for.
  924. This affects what signatures are fetched.
  925. Returns:
  926. The raw key data, the key ID, and the signedjson verify key
  927. Raises:
  928. NotFoundError: if the key is not found
  929. SynapseError: if `user_id` is invalid
  930. """
  931. user = UserID.from_string(user_id)
  932. key = await self.store.get_e2e_cross_signing_key(
  933. user_id, key_type, from_user_id
  934. )
  935. if key:
  936. # We found a copy of this key in our database. Decode and return it
  937. key_id, verify_key = get_verify_key_from_cross_signing_key(key)
  938. return key, key_id, verify_key
  939. # If we couldn't find the key locally, and we're looking for keys of
  940. # another user then attempt to fetch the missing key from the remote
  941. # user's server.
  942. #
  943. # We may run into this in possible edge cases where a user tries to
  944. # cross-sign a remote user, but does not share any rooms with them yet.
  945. # Thus, we would not have their key list yet. We instead fetch the key,
  946. # store it and notify clients of new, associated device IDs.
  947. if self.is_mine(user) or key_type not in ["master", "self_signing"]:
  948. # Note that master and self_signing keys are the only cross-signing keys we
  949. # can request over federation
  950. raise NotFoundError("No %s key found for %s" % (key_type, user_id))
  951. cross_signing_keys = await self._retrieve_cross_signing_keys_for_remote_user(
  952. user, key_type
  953. )
  954. if cross_signing_keys is None:
  955. raise NotFoundError("No %s key found for %s" % (key_type, user_id))
  956. return cross_signing_keys
  957. async def _retrieve_cross_signing_keys_for_remote_user(
  958. self,
  959. user: UserID,
  960. desired_key_type: str,
  961. ) -> Optional[Tuple[Dict[str, Any], str, VerifyKey]]:
  962. """Queries cross-signing keys for a remote user and saves them to the database
  963. Only the key specified by `key_type` will be returned, while all retrieved keys
  964. will be saved regardless
  965. Args:
  966. user: The user to query remote keys for
  967. desired_key_type: The type of key to receive. One of "master", "self_signing"
  968. Returns:
  969. A tuple of the retrieved key content, the key's ID and the matching VerifyKey.
  970. If the key cannot be retrieved, all values in the tuple will instead be None.
  971. """
  972. try:
  973. remote_result = await self.federation.query_user_devices(
  974. user.domain, user.to_string()
  975. )
  976. except Exception as e:
  977. logger.warning(
  978. "Unable to query %s for cross-signing keys of user %s: %s %s",
  979. user.domain,
  980. user.to_string(),
  981. type(e),
  982. e,
  983. )
  984. return None
  985. # Process each of the retrieved cross-signing keys
  986. desired_key_data = None
  987. retrieved_device_ids = []
  988. for key_type in ["master", "self_signing"]:
  989. key_content = remote_result.get(key_type + "_key")
  990. if not key_content:
  991. continue
  992. # Ensure these keys belong to the correct user
  993. if "user_id" not in key_content:
  994. logger.warning(
  995. "Invalid %s key retrieved, missing user_id field: %s",
  996. key_type,
  997. key_content,
  998. )
  999. continue
  1000. if user.to_string() != key_content["user_id"]:
  1001. logger.warning(
  1002. "Found %s key of user %s when querying for keys of user %s",
  1003. key_type,
  1004. key_content["user_id"],
  1005. user.to_string(),
  1006. )
  1007. continue
  1008. # Validate the key contents
  1009. try:
  1010. # verify_key is a VerifyKey from signedjson, which uses
  1011. # .version to denote the portion of the key ID after the
  1012. # algorithm and colon, which is the device ID
  1013. key_id, verify_key = get_verify_key_from_cross_signing_key(key_content)
  1014. except ValueError as e:
  1015. logger.warning(
  1016. "Invalid %s key retrieved: %s - %s %s",
  1017. key_type,
  1018. key_content,
  1019. type(e),
  1020. e,
  1021. )
  1022. continue
  1023. # Note down the device ID attached to this key
  1024. retrieved_device_ids.append(verify_key.version)
  1025. # If this is the desired key type, save it and its ID/VerifyKey
  1026. if key_type == desired_key_type:
  1027. desired_key_data = key_content, key_id, verify_key
  1028. # At the same time, store this key in the db for subsequent queries
  1029. await self.store.set_e2e_cross_signing_key(
  1030. user.to_string(), key_type, key_content
  1031. )
  1032. # Notify clients that new devices for this user have been discovered
  1033. if retrieved_device_ids:
  1034. # XXX is this necessary?
  1035. await self.device_handler.notify_device_update(
  1036. user.to_string(), retrieved_device_ids
  1037. )
  1038. return desired_key_data
  1039. def _check_cross_signing_key(
  1040. key: JsonDict, user_id: str, key_type: str, signing_key: Optional[VerifyKey] = None
  1041. ) -> None:
  1042. """Check a cross-signing key uploaded by a user. Performs some basic sanity
  1043. checking, and ensures that it is signed, if a signature is required.
  1044. Args:
  1045. key: the key data to verify
  1046. user_id: the user whose key is being checked
  1047. key_type: the type of key that the key should be
  1048. signing_key: the signing key that the key should be signed with. If
  1049. omitted, signatures will not be checked.
  1050. """
  1051. if (
  1052. key.get("user_id") != user_id
  1053. or key_type not in key.get("usage", [])
  1054. or len(key.get("keys", {})) != 1
  1055. ):
  1056. raise SynapseError(400, ("Invalid %s key" % (key_type,)), Codes.INVALID_PARAM)
  1057. if signing_key:
  1058. try:
  1059. verify_signed_json(key, user_id, signing_key)
  1060. except SignatureVerifyException:
  1061. raise SynapseError(
  1062. 400, ("Invalid signature on %s key" % key_type), Codes.INVALID_SIGNATURE
  1063. )
  1064. def _check_device_signature(
  1065. user_id: str,
  1066. verify_key: VerifyKey,
  1067. signed_device: JsonDict,
  1068. stored_device: JsonDict,
  1069. ) -> None:
  1070. """Check that a signature on a device or cross-signing key is correct and
  1071. matches the copy of the device/key that we have stored. Throws an
  1072. exception if an error is detected.
  1073. Args:
  1074. user_id: the user ID whose signature is being checked
  1075. verify_key: the key to verify the device with
  1076. signed_device: the uploaded signed device data
  1077. stored_device: our previously stored copy of the device
  1078. Raises:
  1079. SynapseError: if the signature was invalid or the sent device is not the
  1080. same as the stored device
  1081. """
  1082. # make sure that the device submitted matches what we have stored
  1083. stripped_signed_device = {
  1084. k: v for k, v in signed_device.items() if k not in ["signatures", "unsigned"]
  1085. }
  1086. stripped_stored_device = {
  1087. k: v for k, v in stored_device.items() if k not in ["signatures", "unsigned"]
  1088. }
  1089. if stripped_signed_device != stripped_stored_device:
  1090. logger.debug(
  1091. "upload signatures: key does not match %s vs %s",
  1092. signed_device,
  1093. stored_device,
  1094. )
  1095. raise SynapseError(400, "Key does not match")
  1096. try:
  1097. verify_signed_json(signed_device, user_id, verify_key)
  1098. except SignatureVerifyException:
  1099. logger.debug("invalid signature on key")
  1100. raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
  1101. def _exception_to_failure(e: Exception) -> JsonDict:
  1102. if isinstance(e, SynapseError):
  1103. return {"status": e.code, "errcode": e.errcode, "message": str(e)}
  1104. if isinstance(e, CodeMessageException):
  1105. return {"status": e.code, "message": str(e)}
  1106. if isinstance(e, NotRetryingDestination):
  1107. return {"status": 503, "message": "Not ready for retry"}
  1108. # include ConnectionRefused and other errors
  1109. #
  1110. # Note that some Exceptions (notably twisted's ResponseFailed etc) don't
  1111. # give a string for e.message, which json then fails to serialize.
  1112. return {"status": 503, "message": str(e)}
  1113. def _one_time_keys_match(old_key_json: str, new_key: JsonDict) -> bool:
  1114. old_key = json_decoder.decode(old_key_json)
  1115. # if either is a string rather than an object, they must match exactly
  1116. if not isinstance(old_key, dict) or not isinstance(new_key, dict):
  1117. return old_key == new_key
  1118. # otherwise, we strip off the 'signatures' if any, because it's legitimate
  1119. # for different upload attempts to have different signatures.
  1120. old_key.pop("signatures", None)
  1121. new_key_copy = dict(new_key)
  1122. new_key_copy.pop("signatures", None)
  1123. return old_key == new_key_copy
  1124. @attr.s(slots=True, auto_attribs=True)
  1125. class SignatureListItem:
  1126. """An item in the signature list as used by upload_signatures_for_device_keys."""
  1127. signing_key_id: str
  1128. target_user_id: str
  1129. target_device_id: str
  1130. signature: JsonDict
  1131. class SigningKeyEduUpdater:
  1132. """Handles incoming signing key updates from federation and updates the DB"""
  1133. def __init__(self, hs: "HomeServer", e2e_keys_handler: E2eKeysHandler):
  1134. self.store = hs.get_datastores().main
  1135. self.federation = hs.get_federation_client()
  1136. self.clock = hs.get_clock()
  1137. self.e2e_keys_handler = e2e_keys_handler
  1138. self._remote_edu_linearizer = Linearizer(name="remote_signing_key")
  1139. # user_id -> list of updates waiting to be handled.
  1140. self._pending_updates: Dict[str, List[Tuple[JsonDict, JsonDict]]] = {}
  1141. async def incoming_signing_key_update(
  1142. self, origin: str, edu_content: JsonDict
  1143. ) -> None:
  1144. """Called on incoming signing key update from federation. Responsible for
  1145. parsing the EDU and adding to pending updates list.
  1146. Args:
  1147. origin: the server that sent the EDU
  1148. edu_content: the contents of the EDU
  1149. """
  1150. user_id = edu_content.pop("user_id")
  1151. master_key = edu_content.pop("master_key", None)
  1152. self_signing_key = edu_content.pop("self_signing_key", None)
  1153. if get_domain_from_id(user_id) != origin:
  1154. logger.warning("Got signing key update edu for %r from %r", user_id, origin)
  1155. return
  1156. room_ids = await self.store.get_rooms_for_user(user_id)
  1157. if not room_ids:
  1158. # We don't share any rooms with this user. Ignore update, as we
  1159. # probably won't get any further updates.
  1160. return
  1161. self._pending_updates.setdefault(user_id, []).append(
  1162. (master_key, self_signing_key)
  1163. )
  1164. await self._handle_signing_key_updates(user_id)
  1165. async def _handle_signing_key_updates(self, user_id: str) -> None:
  1166. """Actually handle pending updates.
  1167. Args:
  1168. user_id: the user whose updates we are processing
  1169. """
  1170. device_handler = self.e2e_keys_handler.device_handler
  1171. device_list_updater = device_handler.device_list_updater
  1172. async with self._remote_edu_linearizer.queue(user_id):
  1173. pending_updates = self._pending_updates.pop(user_id, [])
  1174. if not pending_updates:
  1175. # This can happen since we batch updates
  1176. return
  1177. device_ids: List[str] = []
  1178. logger.info("pending updates: %r", pending_updates)
  1179. for master_key, self_signing_key in pending_updates:
  1180. new_device_ids = (
  1181. await device_list_updater.process_cross_signing_key_update(
  1182. user_id,
  1183. master_key,
  1184. self_signing_key,
  1185. )
  1186. )
  1187. device_ids = device_ids + new_device_ids
  1188. await device_handler.notify_device_update(user_id, device_ids)