e2e_keys.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  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 simplejson as json
  17. import logging
  18. from canonicaljson import encode_canonical_json
  19. from twisted.internet import defer
  20. from six import iteritems
  21. from synapse.api.errors import (
  22. SynapseError, CodeMessageException, FederationDeniedError,
  23. )
  24. from synapse.types import get_domain_from_id, UserID
  25. from synapse.util.logcontext import make_deferred_yieldable, run_in_background
  26. from synapse.util.retryutils import NotRetryingDestination
  27. logger = logging.getLogger(__name__)
  28. class E2eKeysHandler(object):
  29. def __init__(self, hs):
  30. self.store = hs.get_datastore()
  31. self.federation = hs.get_federation_client()
  32. self.device_handler = hs.get_device_handler()
  33. self.is_mine = hs.is_mine
  34. self.clock = hs.get_clock()
  35. # doesn't really work as part of the generic query API, because the
  36. # query request requires an object POST, but we abuse the
  37. # "query handler" interface.
  38. hs.get_federation_registry().register_query_handler(
  39. "client_keys", self.on_federation_query_client_keys
  40. )
  41. @defer.inlineCallbacks
  42. def query_devices(self, query_body, timeout):
  43. """ Handle a device key query from a client
  44. {
  45. "device_keys": {
  46. "<user_id>": ["<device_id>"]
  47. }
  48. }
  49. ->
  50. {
  51. "device_keys": {
  52. "<user_id>": {
  53. "<device_id>": {
  54. ...
  55. }
  56. }
  57. }
  58. }
  59. """
  60. device_keys_query = query_body.get("device_keys", {})
  61. # separate users by domain.
  62. # make a map from domain to user_id to device_ids
  63. local_query = {}
  64. remote_queries = {}
  65. for user_id, device_ids in device_keys_query.items():
  66. # we use UserID.from_string to catch invalid user ids
  67. if self.is_mine(UserID.from_string(user_id)):
  68. local_query[user_id] = device_ids
  69. else:
  70. remote_queries[user_id] = device_ids
  71. # Firt get local devices.
  72. failures = {}
  73. results = {}
  74. if local_query:
  75. local_result = yield self.query_local_devices(local_query)
  76. for user_id, keys in local_result.items():
  77. if user_id in local_query:
  78. results[user_id] = keys
  79. # Now attempt to get any remote devices from our local cache.
  80. remote_queries_not_in_cache = {}
  81. if remote_queries:
  82. query_list = []
  83. for user_id, device_ids in iteritems(remote_queries):
  84. if device_ids:
  85. query_list.extend((user_id, device_id) for device_id in device_ids)
  86. else:
  87. query_list.append((user_id, None))
  88. user_ids_not_in_cache, remote_results = (
  89. yield self.store.get_user_devices_from_cache(
  90. query_list
  91. )
  92. )
  93. for user_id, devices in iteritems(remote_results):
  94. user_devices = results.setdefault(user_id, {})
  95. for device_id, device in iteritems(devices):
  96. keys = device.get("keys", None)
  97. device_display_name = device.get("device_display_name", None)
  98. if keys:
  99. result = dict(keys)
  100. unsigned = result.setdefault("unsigned", {})
  101. if device_display_name:
  102. unsigned["device_display_name"] = device_display_name
  103. user_devices[device_id] = result
  104. for user_id in user_ids_not_in_cache:
  105. domain = get_domain_from_id(user_id)
  106. r = remote_queries_not_in_cache.setdefault(domain, {})
  107. r[user_id] = remote_queries[user_id]
  108. # Now fetch any devices that we don't have in our cache
  109. @defer.inlineCallbacks
  110. def do_remote_query(destination):
  111. destination_query = remote_queries_not_in_cache[destination]
  112. try:
  113. remote_result = yield self.federation.query_client_keys(
  114. destination,
  115. {"device_keys": destination_query},
  116. timeout=timeout
  117. )
  118. for user_id, keys in remote_result["device_keys"].items():
  119. if user_id in destination_query:
  120. results[user_id] = keys
  121. except Exception as e:
  122. failures[destination] = _exception_to_failure(e)
  123. yield make_deferred_yieldable(defer.gatherResults([
  124. run_in_background(do_remote_query, destination)
  125. for destination in remote_queries_not_in_cache
  126. ], consumeErrors=True))
  127. defer.returnValue({
  128. "device_keys": results, "failures": failures,
  129. })
  130. @defer.inlineCallbacks
  131. def query_local_devices(self, query):
  132. """Get E2E device keys for local users
  133. Args:
  134. query (dict[string, list[string]|None): map from user_id to a list
  135. of devices to query (None for all devices)
  136. Returns:
  137. defer.Deferred: (resolves to dict[string, dict[string, dict]]):
  138. map from user_id -> device_id -> device details
  139. """
  140. local_query = []
  141. result_dict = {}
  142. for user_id, device_ids in query.items():
  143. # we use UserID.from_string to catch invalid user ids
  144. if not self.is_mine(UserID.from_string(user_id)):
  145. logger.warning("Request for keys for non-local user %s",
  146. user_id)
  147. raise SynapseError(400, "Not a user here")
  148. if not device_ids:
  149. local_query.append((user_id, None))
  150. else:
  151. for device_id in device_ids:
  152. local_query.append((user_id, device_id))
  153. # make sure that each queried user appears in the result dict
  154. result_dict[user_id] = {}
  155. results = yield self.store.get_e2e_device_keys(local_query)
  156. # Build the result structure, un-jsonify the results, and add the
  157. # "unsigned" section
  158. for user_id, device_keys in results.items():
  159. for device_id, device_info in device_keys.items():
  160. r = dict(device_info["keys"])
  161. r["unsigned"] = {}
  162. display_name = device_info["device_display_name"]
  163. if display_name is not None:
  164. r["unsigned"]["device_display_name"] = display_name
  165. result_dict[user_id][device_id] = r
  166. defer.returnValue(result_dict)
  167. @defer.inlineCallbacks
  168. def on_federation_query_client_keys(self, query_body):
  169. """ Handle a device key query from a federated server
  170. """
  171. device_keys_query = query_body.get("device_keys", {})
  172. res = yield self.query_local_devices(device_keys_query)
  173. defer.returnValue({"device_keys": res})
  174. @defer.inlineCallbacks
  175. def claim_one_time_keys(self, query, timeout):
  176. local_query = []
  177. remote_queries = {}
  178. for user_id, device_keys in query.get("one_time_keys", {}).items():
  179. # we use UserID.from_string to catch invalid user ids
  180. if self.is_mine(UserID.from_string(user_id)):
  181. for device_id, algorithm in device_keys.items():
  182. local_query.append((user_id, device_id, algorithm))
  183. else:
  184. domain = get_domain_from_id(user_id)
  185. remote_queries.setdefault(domain, {})[user_id] = device_keys
  186. results = yield self.store.claim_e2e_one_time_keys(local_query)
  187. json_result = {}
  188. failures = {}
  189. for user_id, device_keys in results.items():
  190. for device_id, keys in device_keys.items():
  191. for key_id, json_bytes in keys.items():
  192. json_result.setdefault(user_id, {})[device_id] = {
  193. key_id: json.loads(json_bytes)
  194. }
  195. @defer.inlineCallbacks
  196. def claim_client_keys(destination):
  197. device_keys = remote_queries[destination]
  198. try:
  199. remote_result = yield self.federation.claim_client_keys(
  200. destination,
  201. {"one_time_keys": device_keys},
  202. timeout=timeout
  203. )
  204. for user_id, keys in remote_result["one_time_keys"].items():
  205. if user_id in device_keys:
  206. json_result[user_id] = keys
  207. except Exception as e:
  208. failures[destination] = _exception_to_failure(e)
  209. yield make_deferred_yieldable(defer.gatherResults([
  210. run_in_background(claim_client_keys, destination)
  211. for destination in remote_queries
  212. ], consumeErrors=True))
  213. logger.info(
  214. "Claimed one-time-keys: %s",
  215. ",".join((
  216. "%s for %s:%s" % (key_id, user_id, device_id)
  217. for user_id, user_keys in iteritems(json_result)
  218. for device_id, device_keys in iteritems(user_keys)
  219. for key_id, _ in iteritems(device_keys)
  220. )),
  221. )
  222. defer.returnValue({
  223. "one_time_keys": json_result,
  224. "failures": failures
  225. })
  226. @defer.inlineCallbacks
  227. def upload_keys_for_user(self, user_id, device_id, keys):
  228. time_now = self.clock.time_msec()
  229. # TODO: Validate the JSON to make sure it has the right keys.
  230. device_keys = keys.get("device_keys", None)
  231. if device_keys:
  232. logger.info(
  233. "Updating device_keys for device %r for user %s at %d",
  234. device_id, user_id, time_now
  235. )
  236. # TODO: Sign the JSON with the server key
  237. changed = yield self.store.set_e2e_device_keys(
  238. user_id, device_id, time_now, device_keys,
  239. )
  240. if changed:
  241. # Only notify about device updates *if* the keys actually changed
  242. yield self.device_handler.notify_device_update(user_id, [device_id])
  243. one_time_keys = keys.get("one_time_keys", None)
  244. if one_time_keys:
  245. yield self._upload_one_time_keys_for_user(
  246. user_id, device_id, time_now, one_time_keys,
  247. )
  248. # the device should have been registered already, but it may have been
  249. # deleted due to a race with a DELETE request. Or we may be using an
  250. # old access_token without an associated device_id. Either way, we
  251. # need to double-check the device is registered to avoid ending up with
  252. # keys without a corresponding device.
  253. yield self.device_handler.check_device_registered(user_id, device_id)
  254. result = yield self.store.count_e2e_one_time_keys(user_id, device_id)
  255. defer.returnValue({"one_time_key_counts": result})
  256. @defer.inlineCallbacks
  257. def _upload_one_time_keys_for_user(self, user_id, device_id, time_now,
  258. one_time_keys):
  259. logger.info(
  260. "Adding one_time_keys %r for device %r for user %r at %d",
  261. one_time_keys.keys(), device_id, user_id, time_now,
  262. )
  263. # make a list of (alg, id, key) tuples
  264. key_list = []
  265. for key_id, key_obj in one_time_keys.items():
  266. algorithm, key_id = key_id.split(":")
  267. key_list.append((
  268. algorithm, key_id, key_obj
  269. ))
  270. # First we check if we have already persisted any of the keys.
  271. existing_key_map = yield self.store.get_e2e_one_time_keys(
  272. user_id, device_id, [k_id for _, k_id, _ in key_list]
  273. )
  274. new_keys = [] # Keys that we need to insert. (alg, id, json) tuples.
  275. for algorithm, key_id, key in key_list:
  276. ex_json = existing_key_map.get((algorithm, key_id), None)
  277. if ex_json:
  278. if not _one_time_keys_match(ex_json, key):
  279. raise SynapseError(
  280. 400,
  281. ("One time key %s:%s already exists. "
  282. "Old key: %s; new key: %r") %
  283. (algorithm, key_id, ex_json, key)
  284. )
  285. else:
  286. new_keys.append((algorithm, key_id, encode_canonical_json(key)))
  287. yield self.store.add_e2e_one_time_keys(
  288. user_id, device_id, time_now, new_keys
  289. )
  290. def _exception_to_failure(e):
  291. if isinstance(e, CodeMessageException):
  292. return {
  293. "status": e.code, "message": e.message,
  294. }
  295. if isinstance(e, NotRetryingDestination):
  296. return {
  297. "status": 503, "message": "Not ready for retry",
  298. }
  299. if isinstance(e, FederationDeniedError):
  300. return {
  301. "status": 403, "message": "Federation Denied",
  302. }
  303. # include ConnectionRefused and other errors
  304. #
  305. # Note that some Exceptions (notably twisted's ResponseFailed etc) don't
  306. # give a string for e.message, which simplejson then fails to serialize.
  307. return {
  308. "status": 503, "message": str(e.message),
  309. }
  310. def _one_time_keys_match(old_key_json, new_key):
  311. old_key = json.loads(old_key_json)
  312. # if either is a string rather than an object, they must match exactly
  313. if not isinstance(old_key, dict) or not isinstance(new_key, dict):
  314. return old_key == new_key
  315. # otherwise, we strip off the 'signatures' if any, because it's legitimate
  316. # for different upload attempts to have different signatures.
  317. old_key.pop("signatures", None)
  318. new_key_copy = dict(new_key)
  319. new_key_copy.pop("signatures", None)
  320. return old_key == new_key_copy