device.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket Ltd
  3. # Copyright 2019 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. from typing import Any, Dict, Optional
  19. from six import iteritems, itervalues
  20. from twisted.internet import defer
  21. from synapse.api import errors
  22. from synapse.api.constants import EventTypes
  23. from synapse.api.errors import (
  24. FederationDeniedError,
  25. HttpResponseException,
  26. RequestSendFailed,
  27. SynapseError,
  28. )
  29. from synapse.logging.opentracing import log_kv, set_tag, trace
  30. from synapse.metrics.background_process_metrics import run_as_background_process
  31. from synapse.types import (
  32. RoomStreamToken,
  33. get_domain_from_id,
  34. get_verify_key_from_cross_signing_key,
  35. )
  36. from synapse.util import stringutils
  37. from synapse.util.async_helpers import Linearizer
  38. from synapse.util.caches.expiringcache import ExpiringCache
  39. from synapse.util.metrics import measure_func
  40. from synapse.util.retryutils import NotRetryingDestination
  41. from ._base import BaseHandler
  42. logger = logging.getLogger(__name__)
  43. MAX_DEVICE_DISPLAY_NAME_LEN = 100
  44. class DeviceWorkerHandler(BaseHandler):
  45. def __init__(self, hs):
  46. super(DeviceWorkerHandler, self).__init__(hs)
  47. self.hs = hs
  48. self.state = hs.get_state_handler()
  49. self.state_store = hs.get_storage().state
  50. self._auth_handler = hs.get_auth_handler()
  51. @trace
  52. @defer.inlineCallbacks
  53. def get_devices_by_user(self, user_id):
  54. """
  55. Retrieve the given user's devices
  56. Args:
  57. user_id (str):
  58. Returns:
  59. defer.Deferred: list[dict[str, X]]: info on each device
  60. """
  61. set_tag("user_id", user_id)
  62. device_map = yield self.store.get_devices_by_user(user_id)
  63. ips = yield self.store.get_last_client_ip_by_device(user_id, device_id=None)
  64. devices = list(device_map.values())
  65. for device in devices:
  66. _update_device_from_client_ips(device, ips)
  67. log_kv(device_map)
  68. return devices
  69. @trace
  70. @defer.inlineCallbacks
  71. def get_device(self, user_id, device_id):
  72. """ Retrieve the given device
  73. Args:
  74. user_id (str):
  75. device_id (str):
  76. Returns:
  77. defer.Deferred: dict[str, X]: info on the device
  78. Raises:
  79. errors.NotFoundError: if the device was not found
  80. """
  81. try:
  82. device = yield self.store.get_device(user_id, device_id)
  83. except errors.StoreError:
  84. raise errors.NotFoundError
  85. ips = yield self.store.get_last_client_ip_by_device(user_id, device_id)
  86. _update_device_from_client_ips(device, ips)
  87. set_tag("device", device)
  88. set_tag("ips", ips)
  89. return device
  90. @measure_func("device.get_user_ids_changed")
  91. @trace
  92. @defer.inlineCallbacks
  93. def get_user_ids_changed(self, user_id, from_token):
  94. """Get list of users that have had the devices updated, or have newly
  95. joined a room, that `user_id` may be interested in.
  96. Args:
  97. user_id (str)
  98. from_token (StreamToken)
  99. """
  100. set_tag("user_id", user_id)
  101. set_tag("from_token", from_token)
  102. now_room_key = yield self.store.get_room_events_max_id()
  103. room_ids = yield self.store.get_rooms_for_user(user_id)
  104. # First we check if any devices have changed for users that we share
  105. # rooms with.
  106. users_who_share_room = yield self.store.get_users_who_share_room_with_user(
  107. user_id
  108. )
  109. tracked_users = set(users_who_share_room)
  110. # Always tell the user about their own devices
  111. tracked_users.add(user_id)
  112. changed = yield self.store.get_users_whose_devices_changed(
  113. from_token.device_list_key, tracked_users
  114. )
  115. # Then work out if any users have since joined
  116. rooms_changed = self.store.get_rooms_that_changed(room_ids, from_token.room_key)
  117. member_events = yield self.store.get_membership_changes_for_user(
  118. user_id, from_token.room_key, now_room_key
  119. )
  120. rooms_changed.update(event.room_id for event in member_events)
  121. stream_ordering = RoomStreamToken.parse_stream_token(from_token.room_key).stream
  122. possibly_changed = set(changed)
  123. possibly_left = set()
  124. for room_id in rooms_changed:
  125. current_state_ids = yield self.store.get_current_state_ids(room_id)
  126. # The user may have left the room
  127. # TODO: Check if they actually did or if we were just invited.
  128. if room_id not in room_ids:
  129. for key, event_id in iteritems(current_state_ids):
  130. etype, state_key = key
  131. if etype != EventTypes.Member:
  132. continue
  133. possibly_left.add(state_key)
  134. continue
  135. # Fetch the current state at the time.
  136. try:
  137. event_ids = yield self.store.get_forward_extremeties_for_room(
  138. room_id, stream_ordering=stream_ordering
  139. )
  140. except errors.StoreError:
  141. # we have purged the stream_ordering index since the stream
  142. # ordering: treat it the same as a new room
  143. event_ids = []
  144. # special-case for an empty prev state: include all members
  145. # in the changed list
  146. if not event_ids:
  147. log_kv(
  148. {"event": "encountered empty previous state", "room_id": room_id}
  149. )
  150. for key, event_id in iteritems(current_state_ids):
  151. etype, state_key = key
  152. if etype != EventTypes.Member:
  153. continue
  154. possibly_changed.add(state_key)
  155. continue
  156. current_member_id = current_state_ids.get((EventTypes.Member, user_id))
  157. if not current_member_id:
  158. continue
  159. # mapping from event_id -> state_dict
  160. prev_state_ids = yield self.state_store.get_state_ids_for_events(event_ids)
  161. # Check if we've joined the room? If so we just blindly add all the users to
  162. # the "possibly changed" users.
  163. for state_dict in itervalues(prev_state_ids):
  164. member_event = state_dict.get((EventTypes.Member, user_id), None)
  165. if not member_event or member_event != current_member_id:
  166. for key, event_id in iteritems(current_state_ids):
  167. etype, state_key = key
  168. if etype != EventTypes.Member:
  169. continue
  170. possibly_changed.add(state_key)
  171. break
  172. # If there has been any change in membership, include them in the
  173. # possibly changed list. We'll check if they are joined below,
  174. # and we're not toooo worried about spuriously adding users.
  175. for key, event_id in iteritems(current_state_ids):
  176. etype, state_key = key
  177. if etype != EventTypes.Member:
  178. continue
  179. # check if this member has changed since any of the extremities
  180. # at the stream_ordering, and add them to the list if so.
  181. for state_dict in itervalues(prev_state_ids):
  182. prev_event_id = state_dict.get(key, None)
  183. if not prev_event_id or prev_event_id != event_id:
  184. if state_key != user_id:
  185. possibly_changed.add(state_key)
  186. break
  187. if possibly_changed or possibly_left:
  188. # Take the intersection of the users whose devices may have changed
  189. # and those that actually still share a room with the user
  190. possibly_joined = possibly_changed & users_who_share_room
  191. possibly_left = (possibly_changed | possibly_left) - users_who_share_room
  192. else:
  193. possibly_joined = []
  194. possibly_left = []
  195. result = {"changed": list(possibly_joined), "left": list(possibly_left)}
  196. log_kv(result)
  197. return result
  198. @defer.inlineCallbacks
  199. def on_federation_query_user_devices(self, user_id):
  200. stream_id, devices = yield self.store.get_devices_with_keys_by_user(user_id)
  201. master_key = yield self.store.get_e2e_cross_signing_key(user_id, "master")
  202. self_signing_key = yield self.store.get_e2e_cross_signing_key(
  203. user_id, "self_signing"
  204. )
  205. return {
  206. "user_id": user_id,
  207. "stream_id": stream_id,
  208. "devices": devices,
  209. "master_key": master_key,
  210. "self_signing_key": self_signing_key,
  211. }
  212. class DeviceHandler(DeviceWorkerHandler):
  213. def __init__(self, hs):
  214. super(DeviceHandler, self).__init__(hs)
  215. self.federation_sender = hs.get_federation_sender()
  216. self.device_list_updater = DeviceListUpdater(hs, self)
  217. federation_registry = hs.get_federation_registry()
  218. federation_registry.register_edu_handler(
  219. "m.device_list_update", self.device_list_updater.incoming_device_list_update
  220. )
  221. hs.get_distributor().observe("user_left_room", self.user_left_room)
  222. @defer.inlineCallbacks
  223. def check_device_registered(
  224. self, user_id, device_id, initial_device_display_name=None
  225. ):
  226. """
  227. If the given device has not been registered, register it with the
  228. supplied display name.
  229. If no device_id is supplied, we make one up.
  230. Args:
  231. user_id (str): @user:id
  232. device_id (str | None): device id supplied by client
  233. initial_device_display_name (str | None): device display name from
  234. client
  235. Returns:
  236. str: device id (generated if none was supplied)
  237. """
  238. if device_id is not None:
  239. new_device = yield self.store.store_device(
  240. user_id=user_id,
  241. device_id=device_id,
  242. initial_device_display_name=initial_device_display_name,
  243. )
  244. if new_device:
  245. yield self.notify_device_update(user_id, [device_id])
  246. return device_id
  247. # if the device id is not specified, we'll autogen one, but loop a few
  248. # times in case of a clash.
  249. attempts = 0
  250. while attempts < 5:
  251. device_id = stringutils.random_string(10).upper()
  252. new_device = yield self.store.store_device(
  253. user_id=user_id,
  254. device_id=device_id,
  255. initial_device_display_name=initial_device_display_name,
  256. )
  257. if new_device:
  258. yield self.notify_device_update(user_id, [device_id])
  259. return device_id
  260. attempts += 1
  261. raise errors.StoreError(500, "Couldn't generate a device ID.")
  262. @trace
  263. @defer.inlineCallbacks
  264. def delete_device(self, user_id, device_id):
  265. """ Delete the given device
  266. Args:
  267. user_id (str):
  268. device_id (str):
  269. Returns:
  270. defer.Deferred:
  271. """
  272. try:
  273. yield self.store.delete_device(user_id, device_id)
  274. except errors.StoreError as e:
  275. if e.code == 404:
  276. # no match
  277. set_tag("error", True)
  278. log_kv(
  279. {"reason": "User doesn't have device id.", "device_id": device_id}
  280. )
  281. pass
  282. else:
  283. raise
  284. yield defer.ensureDeferred(
  285. self._auth_handler.delete_access_tokens_for_user(
  286. user_id, device_id=device_id
  287. )
  288. )
  289. yield self.store.delete_e2e_keys_by_device(user_id=user_id, device_id=device_id)
  290. yield self.notify_device_update(user_id, [device_id])
  291. @trace
  292. @defer.inlineCallbacks
  293. def delete_all_devices_for_user(self, user_id, except_device_id=None):
  294. """Delete all of the user's devices
  295. Args:
  296. user_id (str):
  297. except_device_id (str|None): optional device id which should not
  298. be deleted
  299. Returns:
  300. defer.Deferred:
  301. """
  302. device_map = yield self.store.get_devices_by_user(user_id)
  303. device_ids = list(device_map)
  304. if except_device_id is not None:
  305. device_ids = [d for d in device_ids if d != except_device_id]
  306. yield self.delete_devices(user_id, device_ids)
  307. @defer.inlineCallbacks
  308. def delete_devices(self, user_id, device_ids):
  309. """ Delete several devices
  310. Args:
  311. user_id (str):
  312. device_ids (List[str]): The list of device IDs to delete
  313. Returns:
  314. defer.Deferred:
  315. """
  316. try:
  317. yield self.store.delete_devices(user_id, device_ids)
  318. except errors.StoreError as e:
  319. if e.code == 404:
  320. # no match
  321. set_tag("error", True)
  322. set_tag("reason", "User doesn't have that device id.")
  323. pass
  324. else:
  325. raise
  326. # Delete access tokens and e2e keys for each device. Not optimised as it is not
  327. # considered as part of a critical path.
  328. for device_id in device_ids:
  329. yield defer.ensureDeferred(
  330. self._auth_handler.delete_access_tokens_for_user(
  331. user_id, device_id=device_id
  332. )
  333. )
  334. yield self.store.delete_e2e_keys_by_device(
  335. user_id=user_id, device_id=device_id
  336. )
  337. yield self.notify_device_update(user_id, device_ids)
  338. @defer.inlineCallbacks
  339. def update_device(self, user_id, device_id, content):
  340. """ Update the given device
  341. Args:
  342. user_id (str):
  343. device_id (str):
  344. content (dict): body of update request
  345. Returns:
  346. defer.Deferred:
  347. """
  348. # Reject a new displayname which is too long.
  349. new_display_name = content.get("display_name")
  350. if new_display_name and len(new_display_name) > MAX_DEVICE_DISPLAY_NAME_LEN:
  351. raise SynapseError(
  352. 400,
  353. "Device display name is too long (max %i)"
  354. % (MAX_DEVICE_DISPLAY_NAME_LEN,),
  355. )
  356. try:
  357. yield self.store.update_device(
  358. user_id, device_id, new_display_name=new_display_name
  359. )
  360. yield self.notify_device_update(user_id, [device_id])
  361. except errors.StoreError as e:
  362. if e.code == 404:
  363. raise errors.NotFoundError()
  364. else:
  365. raise
  366. @trace
  367. @measure_func("notify_device_update")
  368. @defer.inlineCallbacks
  369. def notify_device_update(self, user_id, device_ids):
  370. """Notify that a user's device(s) has changed. Pokes the notifier, and
  371. remote servers if the user is local.
  372. """
  373. users_who_share_room = yield self.store.get_users_who_share_room_with_user(
  374. user_id
  375. )
  376. hosts = set()
  377. if self.hs.is_mine_id(user_id):
  378. hosts.update(get_domain_from_id(u) for u in users_who_share_room)
  379. hosts.discard(self.server_name)
  380. set_tag("target_hosts", hosts)
  381. position = yield self.store.add_device_change_to_streams(
  382. user_id, device_ids, list(hosts)
  383. )
  384. for device_id in device_ids:
  385. logger.debug(
  386. "Notifying about update %r/%r, ID: %r", user_id, device_id, position
  387. )
  388. room_ids = yield self.store.get_rooms_for_user(user_id)
  389. # specify the user ID too since the user should always get their own device list
  390. # updates, even if they aren't in any rooms.
  391. yield self.notifier.on_new_event(
  392. "device_list_key", position, users=[user_id], rooms=room_ids
  393. )
  394. if hosts:
  395. logger.info(
  396. "Sending device list update notif for %r to: %r", user_id, hosts
  397. )
  398. for host in hosts:
  399. self.federation_sender.send_device_messages(host)
  400. log_kv({"message": "sent device update to host", "host": host})
  401. @defer.inlineCallbacks
  402. def notify_user_signature_update(self, from_user_id, user_ids):
  403. """Notify a user that they have made new signatures of other users.
  404. Args:
  405. from_user_id (str): the user who made the signature
  406. user_ids (list[str]): the users IDs that have new signatures
  407. """
  408. position = yield self.store.add_user_signature_change_to_streams(
  409. from_user_id, user_ids
  410. )
  411. self.notifier.on_new_event("device_list_key", position, users=[from_user_id])
  412. @defer.inlineCallbacks
  413. def user_left_room(self, user, room_id):
  414. user_id = user.to_string()
  415. room_ids = yield self.store.get_rooms_for_user(user_id)
  416. if not room_ids:
  417. # We no longer share rooms with this user, so we'll no longer
  418. # receive device updates. Mark this in DB.
  419. yield self.store.mark_remote_user_device_list_as_unsubscribed(user_id)
  420. def _update_device_from_client_ips(device, client_ips):
  421. ip = client_ips.get((device["user_id"], device["device_id"]), {})
  422. device.update({"last_seen_ts": ip.get("last_seen"), "last_seen_ip": ip.get("ip")})
  423. class DeviceListUpdater(object):
  424. "Handles incoming device list updates from federation and updates the DB"
  425. def __init__(self, hs, device_handler):
  426. self.store = hs.get_datastore()
  427. self.federation = hs.get_federation_client()
  428. self.clock = hs.get_clock()
  429. self.device_handler = device_handler
  430. self._remote_edu_linearizer = Linearizer(name="remote_device_list")
  431. # user_id -> list of updates waiting to be handled.
  432. self._pending_updates = {}
  433. # Recently seen stream ids. We don't bother keeping these in the DB,
  434. # but they're useful to have them about to reduce the number of spurious
  435. # resyncs.
  436. self._seen_updates = ExpiringCache(
  437. cache_name="device_update_edu",
  438. clock=self.clock,
  439. max_len=10000,
  440. expiry_ms=30 * 60 * 1000,
  441. iterable=True,
  442. )
  443. # Attempt to resync out of sync device lists every 30s.
  444. self._resync_retry_in_progress = False
  445. self.clock.looping_call(
  446. run_as_background_process,
  447. 30 * 1000,
  448. func=self._maybe_retry_device_resync,
  449. desc="_maybe_retry_device_resync",
  450. )
  451. @trace
  452. @defer.inlineCallbacks
  453. def incoming_device_list_update(self, origin, edu_content):
  454. """Called on incoming device list update from federation. Responsible
  455. for parsing the EDU and adding to pending updates list.
  456. """
  457. set_tag("origin", origin)
  458. set_tag("edu_content", edu_content)
  459. user_id = edu_content.pop("user_id")
  460. device_id = edu_content.pop("device_id")
  461. stream_id = str(edu_content.pop("stream_id")) # They may come as ints
  462. prev_ids = edu_content.pop("prev_id", [])
  463. prev_ids = [str(p) for p in prev_ids] # They may come as ints
  464. if get_domain_from_id(user_id) != origin:
  465. # TODO: Raise?
  466. logger.warning(
  467. "Got device list update edu for %r/%r from %r",
  468. user_id,
  469. device_id,
  470. origin,
  471. )
  472. set_tag("error", True)
  473. log_kv(
  474. {
  475. "message": "Got a device list update edu from a user and "
  476. "device which does not match the origin of the request.",
  477. "user_id": user_id,
  478. "device_id": device_id,
  479. }
  480. )
  481. return
  482. room_ids = yield self.store.get_rooms_for_user(user_id)
  483. if not room_ids:
  484. # We don't share any rooms with this user. Ignore update, as we
  485. # probably won't get any further updates.
  486. set_tag("error", True)
  487. log_kv(
  488. {
  489. "message": "Got an update from a user for which "
  490. "we don't share any rooms",
  491. "other user_id": user_id,
  492. }
  493. )
  494. logger.warning(
  495. "Got device list update edu for %r/%r, but don't share a room",
  496. user_id,
  497. device_id,
  498. )
  499. return
  500. logger.debug("Received device list update for %r/%r", user_id, device_id)
  501. self._pending_updates.setdefault(user_id, []).append(
  502. (device_id, stream_id, prev_ids, edu_content)
  503. )
  504. yield self._handle_device_updates(user_id)
  505. @measure_func("_incoming_device_list_update")
  506. @defer.inlineCallbacks
  507. def _handle_device_updates(self, user_id):
  508. "Actually handle pending updates."
  509. with (yield self._remote_edu_linearizer.queue(user_id)):
  510. pending_updates = self._pending_updates.pop(user_id, [])
  511. if not pending_updates:
  512. # This can happen since we batch updates
  513. return
  514. for device_id, stream_id, prev_ids, content in pending_updates:
  515. logger.debug(
  516. "Handling update %r/%r, ID: %r, prev: %r ",
  517. user_id,
  518. device_id,
  519. stream_id,
  520. prev_ids,
  521. )
  522. # Given a list of updates we check if we need to resync. This
  523. # happens if we've missed updates.
  524. resync = yield self._need_to_do_resync(user_id, pending_updates)
  525. if logger.isEnabledFor(logging.INFO):
  526. logger.info(
  527. "Received device list update for %s, requiring resync: %s. Devices: %s",
  528. user_id,
  529. resync,
  530. ", ".join(u[0] for u in pending_updates),
  531. )
  532. if resync:
  533. yield self.user_device_resync(user_id)
  534. else:
  535. # Simply update the single device, since we know that is the only
  536. # change (because of the single prev_id matching the current cache)
  537. for device_id, stream_id, prev_ids, content in pending_updates:
  538. yield self.store.update_remote_device_list_cache_entry(
  539. user_id, device_id, content, stream_id
  540. )
  541. yield self.device_handler.notify_device_update(
  542. user_id, [device_id for device_id, _, _, _ in pending_updates]
  543. )
  544. self._seen_updates.setdefault(user_id, set()).update(
  545. stream_id for _, stream_id, _, _ in pending_updates
  546. )
  547. @defer.inlineCallbacks
  548. def _need_to_do_resync(self, user_id, updates):
  549. """Given a list of updates for a user figure out if we need to do a full
  550. resync, or whether we have enough data that we can just apply the delta.
  551. """
  552. seen_updates = self._seen_updates.get(user_id, set())
  553. extremity = yield self.store.get_device_list_last_stream_id_for_remote(user_id)
  554. logger.debug("Current extremity for %r: %r", user_id, extremity)
  555. stream_id_in_updates = set() # stream_ids in updates list
  556. for _, stream_id, prev_ids, _ in updates:
  557. if not prev_ids:
  558. # We always do a resync if there are no previous IDs
  559. return True
  560. for prev_id in prev_ids:
  561. if prev_id == extremity:
  562. continue
  563. elif prev_id in seen_updates:
  564. continue
  565. elif prev_id in stream_id_in_updates:
  566. continue
  567. else:
  568. return True
  569. stream_id_in_updates.add(stream_id)
  570. return False
  571. @defer.inlineCallbacks
  572. def _maybe_retry_device_resync(self):
  573. """Retry to resync device lists that are out of sync, except if another retry is
  574. in progress.
  575. """
  576. if self._resync_retry_in_progress:
  577. return
  578. try:
  579. # Prevent another call of this function to retry resyncing device lists so
  580. # we don't send too many requests.
  581. self._resync_retry_in_progress = True
  582. # Get all of the users that need resyncing.
  583. need_resync = yield self.store.get_user_ids_requiring_device_list_resync()
  584. # Iterate over the set of user IDs.
  585. for user_id in need_resync:
  586. try:
  587. # Try to resync the current user's devices list.
  588. result = yield self.user_device_resync(
  589. user_id=user_id, mark_failed_as_stale=False,
  590. )
  591. # user_device_resync only returns a result if it managed to
  592. # successfully resync and update the database. Updating the table
  593. # of users requiring resync isn't necessary here as
  594. # user_device_resync already does it (through
  595. # self.store.update_remote_device_list_cache).
  596. if result:
  597. logger.debug(
  598. "Successfully resynced the device list for %s", user_id,
  599. )
  600. except Exception as e:
  601. # If there was an issue resyncing this user, e.g. if the remote
  602. # server sent a malformed result, just log the error instead of
  603. # aborting all the subsequent resyncs.
  604. logger.debug(
  605. "Could not resync the device list for %s: %s", user_id, e,
  606. )
  607. finally:
  608. # Allow future calls to retry resyncinc out of sync device lists.
  609. self._resync_retry_in_progress = False
  610. @defer.inlineCallbacks
  611. def user_device_resync(self, user_id, mark_failed_as_stale=True):
  612. """Fetches all devices for a user and updates the device cache with them.
  613. Args:
  614. user_id (str): The user's id whose device_list will be updated.
  615. mark_failed_as_stale (bool): Whether to mark the user's device list as stale
  616. if the attempt to resync failed.
  617. Returns:
  618. Deferred[dict]: a dict with device info as under the "devices" in the result of this
  619. request:
  620. https://matrix.org/docs/spec/server_server/r0.1.2#get-matrix-federation-v1-user-devices-userid
  621. """
  622. logger.debug("Attempting to resync the device list for %s", user_id)
  623. log_kv({"message": "Doing resync to update device list."})
  624. # Fetch all devices for the user.
  625. origin = get_domain_from_id(user_id)
  626. try:
  627. result = yield self.federation.query_user_devices(origin, user_id)
  628. except NotRetryingDestination:
  629. if mark_failed_as_stale:
  630. # Mark the remote user's device list as stale so we know we need to retry
  631. # it later.
  632. yield self.store.mark_remote_user_device_cache_as_stale(user_id)
  633. return
  634. except (RequestSendFailed, HttpResponseException) as e:
  635. logger.warning(
  636. "Failed to handle device list update for %s: %s", user_id, e,
  637. )
  638. if mark_failed_as_stale:
  639. # Mark the remote user's device list as stale so we know we need to retry
  640. # it later.
  641. yield self.store.mark_remote_user_device_cache_as_stale(user_id)
  642. # We abort on exceptions rather than accepting the update
  643. # as otherwise synapse will 'forget' that its device list
  644. # is out of date. If we bail then we will retry the resync
  645. # next time we get a device list update for this user_id.
  646. # This makes it more likely that the device lists will
  647. # eventually become consistent.
  648. return
  649. except FederationDeniedError as e:
  650. set_tag("error", True)
  651. log_kv({"reason": "FederationDeniedError"})
  652. logger.info(e)
  653. return
  654. except Exception as e:
  655. set_tag("error", True)
  656. log_kv(
  657. {"message": "Exception raised by federation request", "exception": e}
  658. )
  659. logger.exception("Failed to handle device list update for %s", user_id)
  660. if mark_failed_as_stale:
  661. # Mark the remote user's device list as stale so we know we need to retry
  662. # it later.
  663. yield self.store.mark_remote_user_device_cache_as_stale(user_id)
  664. return
  665. log_kv({"result": result})
  666. stream_id = result["stream_id"]
  667. devices = result["devices"]
  668. # Get the master key and the self-signing key for this user if provided in the
  669. # response (None if not in the response).
  670. # The response will not contain the user signing key, as this key is only used by
  671. # its owner, thus it doesn't make sense to send it over federation.
  672. master_key = result.get("master_key")
  673. self_signing_key = result.get("self_signing_key")
  674. # If the remote server has more than ~1000 devices for this user
  675. # we assume that something is going horribly wrong (e.g. a bot
  676. # that logs in and creates a new device every time it tries to
  677. # send a message). Maintaining lots of devices per user in the
  678. # cache can cause serious performance issues as if this request
  679. # takes more than 60s to complete, internal replication from the
  680. # inbound federation worker to the synapse master may time out
  681. # causing the inbound federation to fail and causing the remote
  682. # server to retry, causing a DoS. So in this scenario we give
  683. # up on storing the total list of devices and only handle the
  684. # delta instead.
  685. if len(devices) > 1000:
  686. logger.warning(
  687. "Ignoring device list snapshot for %s as it has >1K devs (%d)",
  688. user_id,
  689. len(devices),
  690. )
  691. devices = []
  692. for device in devices:
  693. logger.debug(
  694. "Handling resync update %r/%r, ID: %r",
  695. user_id,
  696. device["device_id"],
  697. stream_id,
  698. )
  699. yield self.store.update_remote_device_list_cache(user_id, devices, stream_id)
  700. device_ids = [device["device_id"] for device in devices]
  701. # Handle cross-signing keys.
  702. cross_signing_device_ids = yield self.process_cross_signing_key_update(
  703. user_id, master_key, self_signing_key,
  704. )
  705. device_ids = device_ids + cross_signing_device_ids
  706. yield self.device_handler.notify_device_update(user_id, device_ids)
  707. # We clobber the seen updates since we've re-synced from a given
  708. # point.
  709. self._seen_updates[user_id] = {stream_id}
  710. defer.returnValue(result)
  711. @defer.inlineCallbacks
  712. def process_cross_signing_key_update(
  713. self,
  714. user_id: str,
  715. master_key: Optional[Dict[str, Any]],
  716. self_signing_key: Optional[Dict[str, Any]],
  717. ) -> list:
  718. """Process the given new master and self-signing key for the given remote user.
  719. Args:
  720. user_id: The ID of the user these keys are for.
  721. master_key: The dict of the cross-signing master key as returned by the
  722. remote server.
  723. self_signing_key: The dict of the cross-signing self-signing key as returned
  724. by the remote server.
  725. Return:
  726. The device IDs for the given keys.
  727. """
  728. device_ids = []
  729. if master_key:
  730. yield self.store.set_e2e_cross_signing_key(user_id, "master", master_key)
  731. _, verify_key = get_verify_key_from_cross_signing_key(master_key)
  732. # verify_key is a VerifyKey from signedjson, which uses
  733. # .version to denote the portion of the key ID after the
  734. # algorithm and colon, which is the device ID
  735. device_ids.append(verify_key.version)
  736. if self_signing_key:
  737. yield self.store.set_e2e_cross_signing_key(
  738. user_id, "self_signing", self_signing_key
  739. )
  740. _, verify_key = get_verify_key_from_cross_signing_key(self_signing_key)
  741. device_ids.append(verify_key.version)
  742. return device_ids