Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

1116 wiersze
42 KiB

  1. # Copyright 2016 OpenMarket Ltd
  2. # Copyright 2019 New Vector Ltd
  3. # Copyright 2019,2020 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 (
  18. TYPE_CHECKING,
  19. Any,
  20. Collection,
  21. Dict,
  22. Iterable,
  23. List,
  24. Mapping,
  25. Optional,
  26. Set,
  27. Tuple,
  28. )
  29. from synapse.api import errors
  30. from synapse.api.constants import EventTypes
  31. from synapse.api.errors import (
  32. Codes,
  33. FederationDeniedError,
  34. HttpResponseException,
  35. RequestSendFailed,
  36. SynapseError,
  37. )
  38. from synapse.logging.opentracing import log_kv, set_tag, trace
  39. from synapse.metrics.background_process_metrics import (
  40. run_as_background_process,
  41. wrap_as_background_process,
  42. )
  43. from synapse.types import (
  44. JsonDict,
  45. StreamToken,
  46. UserID,
  47. get_domain_from_id,
  48. get_verify_key_from_cross_signing_key,
  49. )
  50. from synapse.util import stringutils
  51. from synapse.util.async_helpers import Linearizer
  52. from synapse.util.caches.expiringcache import ExpiringCache
  53. from synapse.util.metrics import measure_func
  54. from synapse.util.retryutils import NotRetryingDestination
  55. if TYPE_CHECKING:
  56. from synapse.server import HomeServer
  57. logger = logging.getLogger(__name__)
  58. MAX_DEVICE_DISPLAY_NAME_LEN = 100
  59. class DeviceWorkerHandler:
  60. def __init__(self, hs: "HomeServer"):
  61. self.clock = hs.get_clock()
  62. self.hs = hs
  63. self.store = hs.get_datastores().main
  64. self.notifier = hs.get_notifier()
  65. self.state = hs.get_state_handler()
  66. self.state_store = hs.get_storage().state
  67. self._auth_handler = hs.get_auth_handler()
  68. self.server_name = hs.hostname
  69. @trace
  70. async def get_devices_by_user(self, user_id: str) -> List[JsonDict]:
  71. """
  72. Retrieve the given user's devices
  73. Args:
  74. user_id: The user ID to query for devices.
  75. Returns:
  76. info on each device
  77. """
  78. set_tag("user_id", user_id)
  79. device_map = await self.store.get_devices_by_user(user_id)
  80. ips = await self.store.get_last_client_ip_by_device(user_id, device_id=None)
  81. devices = list(device_map.values())
  82. for device in devices:
  83. _update_device_from_client_ips(device, ips)
  84. log_kv(device_map)
  85. return devices
  86. @trace
  87. async def get_device(self, user_id: str, device_id: str) -> JsonDict:
  88. """Retrieve the given device
  89. Args:
  90. user_id: The user to get the device from
  91. device_id: The device to fetch.
  92. Returns:
  93. info on the device
  94. Raises:
  95. errors.NotFoundError: if the device was not found
  96. """
  97. device = await self.store.get_device(user_id, device_id)
  98. if device is None:
  99. raise errors.NotFoundError()
  100. ips = await self.store.get_last_client_ip_by_device(user_id, device_id)
  101. _update_device_from_client_ips(device, ips)
  102. set_tag("device", device)
  103. set_tag("ips", ips)
  104. return device
  105. @trace
  106. @measure_func("device.get_user_ids_changed")
  107. async def get_user_ids_changed(
  108. self, user_id: str, from_token: StreamToken
  109. ) -> JsonDict:
  110. """Get list of users that have had the devices updated, or have newly
  111. joined a room, that `user_id` may be interested in.
  112. """
  113. set_tag("user_id", user_id)
  114. set_tag("from_token", from_token)
  115. now_room_key = self.store.get_room_max_token()
  116. room_ids = await self.store.get_rooms_for_user(user_id)
  117. # First we check if any devices have changed for users that we share
  118. # rooms with.
  119. users_who_share_room = await self.store.get_users_who_share_room_with_user(
  120. user_id
  121. )
  122. tracked_users = set(users_who_share_room)
  123. # Always tell the user about their own devices
  124. tracked_users.add(user_id)
  125. changed = await self.store.get_users_whose_devices_changed(
  126. from_token.device_list_key, tracked_users
  127. )
  128. # Then work out if any users have since joined
  129. rooms_changed = self.store.get_rooms_that_changed(room_ids, from_token.room_key)
  130. member_events = await self.store.get_membership_changes_for_user(
  131. user_id, from_token.room_key, now_room_key
  132. )
  133. rooms_changed.update(event.room_id for event in member_events)
  134. stream_ordering = from_token.room_key.stream
  135. possibly_changed = set(changed)
  136. possibly_left = set()
  137. for room_id in rooms_changed:
  138. current_state_ids = await self.store.get_current_state_ids(room_id)
  139. # The user may have left the room
  140. # TODO: Check if they actually did or if we were just invited.
  141. if room_id not in room_ids:
  142. for etype, state_key in current_state_ids.keys():
  143. if etype != EventTypes.Member:
  144. continue
  145. possibly_left.add(state_key)
  146. continue
  147. # Fetch the current state at the time.
  148. try:
  149. event_ids = await self.store.get_forward_extremities_for_room_at_stream_ordering(
  150. room_id, stream_ordering=stream_ordering
  151. )
  152. except errors.StoreError:
  153. # we have purged the stream_ordering index since the stream
  154. # ordering: treat it the same as a new room
  155. event_ids = []
  156. # special-case for an empty prev state: include all members
  157. # in the changed list
  158. if not event_ids:
  159. log_kv(
  160. {"event": "encountered empty previous state", "room_id": room_id}
  161. )
  162. for etype, state_key in current_state_ids.keys():
  163. if etype != EventTypes.Member:
  164. continue
  165. possibly_changed.add(state_key)
  166. continue
  167. current_member_id = current_state_ids.get((EventTypes.Member, user_id))
  168. if not current_member_id:
  169. continue
  170. # mapping from event_id -> state_dict
  171. prev_state_ids = await self.state_store.get_state_ids_for_events(event_ids)
  172. # Check if we've joined the room? If so we just blindly add all the users to
  173. # the "possibly changed" users.
  174. for state_dict in prev_state_ids.values():
  175. member_event = state_dict.get((EventTypes.Member, user_id), None)
  176. if not member_event or member_event != current_member_id:
  177. for etype, state_key in current_state_ids.keys():
  178. if etype != EventTypes.Member:
  179. continue
  180. possibly_changed.add(state_key)
  181. break
  182. # If there has been any change in membership, include them in the
  183. # possibly changed list. We'll check if they are joined below,
  184. # and we're not toooo worried about spuriously adding users.
  185. for key, event_id in current_state_ids.items():
  186. etype, state_key = key
  187. if etype != EventTypes.Member:
  188. continue
  189. # check if this member has changed since any of the extremities
  190. # at the stream_ordering, and add them to the list if so.
  191. for state_dict in prev_state_ids.values():
  192. prev_event_id = state_dict.get(key, None)
  193. if not prev_event_id or prev_event_id != event_id:
  194. if state_key != user_id:
  195. possibly_changed.add(state_key)
  196. break
  197. if possibly_changed or possibly_left:
  198. # Take the intersection of the users whose devices may have changed
  199. # and those that actually still share a room with the user
  200. possibly_joined = possibly_changed & users_who_share_room
  201. possibly_left = (possibly_changed | possibly_left) - users_who_share_room
  202. else:
  203. possibly_joined = set()
  204. possibly_left = set()
  205. result = {"changed": list(possibly_joined), "left": list(possibly_left)}
  206. log_kv(result)
  207. return result
  208. async def on_federation_query_user_devices(self, user_id: str) -> JsonDict:
  209. stream_id, devices = await self.store.get_e2e_device_keys_for_federation_query(
  210. user_id
  211. )
  212. master_key = await self.store.get_e2e_cross_signing_key(user_id, "master")
  213. self_signing_key = await self.store.get_e2e_cross_signing_key(
  214. user_id, "self_signing"
  215. )
  216. return {
  217. "user_id": user_id,
  218. "stream_id": stream_id,
  219. "devices": devices,
  220. "master_key": master_key,
  221. "self_signing_key": self_signing_key,
  222. }
  223. class DeviceHandler(DeviceWorkerHandler):
  224. def __init__(self, hs: "HomeServer"):
  225. super().__init__(hs)
  226. self.federation_sender = hs.get_federation_sender()
  227. self.device_list_updater = DeviceListUpdater(hs, self)
  228. federation_registry = hs.get_federation_registry()
  229. federation_registry.register_edu_handler(
  230. "m.device_list_update", self.device_list_updater.incoming_device_list_update
  231. )
  232. hs.get_distributor().observe("user_left_room", self.user_left_room)
  233. # Whether `_handle_new_device_update_async` is currently processing.
  234. self._handle_new_device_update_is_processing = False
  235. # If a new device update may have happened while the loop was
  236. # processing.
  237. self._handle_new_device_update_new_data = False
  238. # On start up check if there are any updates pending.
  239. hs.get_reactor().callWhenRunning(self._handle_new_device_update_async)
  240. def _check_device_name_length(self, name: Optional[str]) -> None:
  241. """
  242. Checks whether a device name is longer than the maximum allowed length.
  243. Args:
  244. name: The name of the device.
  245. Raises:
  246. SynapseError: if the device name is too long.
  247. """
  248. if name and len(name) > MAX_DEVICE_DISPLAY_NAME_LEN:
  249. raise SynapseError(
  250. 400,
  251. "Device display name is too long (max %i)"
  252. % (MAX_DEVICE_DISPLAY_NAME_LEN,),
  253. errcode=Codes.TOO_LARGE,
  254. )
  255. async def check_device_registered(
  256. self,
  257. user_id: str,
  258. device_id: Optional[str],
  259. initial_device_display_name: Optional[str] = None,
  260. auth_provider_id: Optional[str] = None,
  261. auth_provider_session_id: Optional[str] = None,
  262. ) -> str:
  263. """
  264. If the given device has not been registered, register it with the
  265. supplied display name.
  266. If no device_id is supplied, we make one up.
  267. Args:
  268. user_id: @user:id
  269. device_id: device id supplied by client
  270. initial_device_display_name: device display name from client
  271. auth_provider_id: The SSO IdP the user used, if any.
  272. auth_provider_session_id: The session ID (sid) got from the SSO IdP.
  273. Returns:
  274. device id (generated if none was supplied)
  275. """
  276. self._check_device_name_length(initial_device_display_name)
  277. if device_id is not None:
  278. new_device = await self.store.store_device(
  279. user_id=user_id,
  280. device_id=device_id,
  281. initial_device_display_name=initial_device_display_name,
  282. auth_provider_id=auth_provider_id,
  283. auth_provider_session_id=auth_provider_session_id,
  284. )
  285. if new_device:
  286. await self.notify_device_update(user_id, [device_id])
  287. return device_id
  288. # if the device id is not specified, we'll autogen one, but loop a few
  289. # times in case of a clash.
  290. attempts = 0
  291. while attempts < 5:
  292. new_device_id = stringutils.random_string(10).upper()
  293. new_device = await self.store.store_device(
  294. user_id=user_id,
  295. device_id=new_device_id,
  296. initial_device_display_name=initial_device_display_name,
  297. auth_provider_id=auth_provider_id,
  298. auth_provider_session_id=auth_provider_session_id,
  299. )
  300. if new_device:
  301. await self.notify_device_update(user_id, [new_device_id])
  302. return new_device_id
  303. attempts += 1
  304. raise errors.StoreError(500, "Couldn't generate a device ID.")
  305. @trace
  306. async def delete_device(self, user_id: str, device_id: str) -> None:
  307. """Delete the given device
  308. Args:
  309. user_id: The user to delete the device from.
  310. device_id: The device to delete.
  311. """
  312. try:
  313. await self.store.delete_device(user_id, device_id)
  314. except errors.StoreError as e:
  315. if e.code == 404:
  316. # no match
  317. set_tag("error", True)
  318. log_kv(
  319. {"reason": "User doesn't have device id.", "device_id": device_id}
  320. )
  321. else:
  322. raise
  323. await self._auth_handler.delete_access_tokens_for_user(
  324. user_id, device_id=device_id
  325. )
  326. await self.store.delete_e2e_keys_by_device(user_id=user_id, device_id=device_id)
  327. await self.notify_device_update(user_id, [device_id])
  328. @trace
  329. async def delete_all_devices_for_user(
  330. self, user_id: str, except_device_id: Optional[str] = None
  331. ) -> None:
  332. """Delete all of the user's devices
  333. Args:
  334. user_id: The user to remove all devices from
  335. except_device_id: optional device id which should not be deleted
  336. """
  337. device_map = await self.store.get_devices_by_user(user_id)
  338. device_ids = list(device_map)
  339. if except_device_id is not None:
  340. device_ids = [d for d in device_ids if d != except_device_id]
  341. await self.delete_devices(user_id, device_ids)
  342. async def delete_devices(self, user_id: str, device_ids: List[str]) -> None:
  343. """Delete several devices
  344. Args:
  345. user_id: The user to delete devices from.
  346. device_ids: The list of device IDs to delete
  347. """
  348. try:
  349. await self.store.delete_devices(user_id, device_ids)
  350. except errors.StoreError as e:
  351. if e.code == 404:
  352. # no match
  353. set_tag("error", True)
  354. set_tag("reason", "User doesn't have that device id.")
  355. else:
  356. raise
  357. # Delete access tokens and e2e keys for each device. Not optimised as it is not
  358. # considered as part of a critical path.
  359. for device_id in device_ids:
  360. await self._auth_handler.delete_access_tokens_for_user(
  361. user_id, device_id=device_id
  362. )
  363. await self.store.delete_e2e_keys_by_device(
  364. user_id=user_id, device_id=device_id
  365. )
  366. await self.notify_device_update(user_id, device_ids)
  367. async def update_device(self, user_id: str, device_id: str, content: dict) -> None:
  368. """Update the given device
  369. Args:
  370. user_id: The user to update devices of.
  371. device_id: The device to update.
  372. content: body of update request
  373. """
  374. # Reject a new displayname which is too long.
  375. new_display_name = content.get("display_name")
  376. self._check_device_name_length(new_display_name)
  377. try:
  378. await self.store.update_device(
  379. user_id, device_id, new_display_name=new_display_name
  380. )
  381. await self.notify_device_update(user_id, [device_id])
  382. except errors.StoreError as e:
  383. if e.code == 404:
  384. raise errors.NotFoundError()
  385. else:
  386. raise
  387. @trace
  388. @measure_func("notify_device_update")
  389. async def notify_device_update(
  390. self, user_id: str, device_ids: Collection[str]
  391. ) -> None:
  392. """Notify that a user's device(s) has changed. Pokes the notifier, and
  393. remote servers if the user is local.
  394. Args:
  395. user_id: The Matrix ID of the user who's device list has been updated.
  396. device_ids: The device IDs that have changed.
  397. """
  398. if not device_ids:
  399. # No changes to notify about, so this is a no-op.
  400. return
  401. room_ids = await self.store.get_rooms_for_user(user_id)
  402. position = await self.store.add_device_change_to_streams(
  403. user_id,
  404. device_ids,
  405. room_ids=room_ids,
  406. )
  407. if not position:
  408. # This should only happen if there are no updates, so we bail.
  409. return
  410. for device_id in device_ids:
  411. logger.debug(
  412. "Notifying about update %r/%r, ID: %r", user_id, device_id, position
  413. )
  414. # specify the user ID too since the user should always get their own device list
  415. # updates, even if they aren't in any rooms.
  416. self.notifier.on_new_event(
  417. "device_list_key", position, users={user_id}, rooms=room_ids
  418. )
  419. # We may need to do some processing asynchronously.
  420. self._handle_new_device_update_async()
  421. async def notify_user_signature_update(
  422. self, from_user_id: str, user_ids: List[str]
  423. ) -> None:
  424. """Notify a user that they have made new signatures of other users.
  425. Args:
  426. from_user_id: the user who made the signature
  427. user_ids: the users IDs that have new signatures
  428. """
  429. position = await self.store.add_user_signature_change_to_streams(
  430. from_user_id, user_ids
  431. )
  432. self.notifier.on_new_event("device_list_key", position, users=[from_user_id])
  433. async def user_left_room(self, user: UserID, room_id: str) -> None:
  434. user_id = user.to_string()
  435. room_ids = await self.store.get_rooms_for_user(user_id)
  436. if not room_ids:
  437. # We no longer share rooms with this user, so we'll no longer
  438. # receive device updates. Mark this in DB.
  439. await self.store.mark_remote_user_device_list_as_unsubscribed(user_id)
  440. async def store_dehydrated_device(
  441. self,
  442. user_id: str,
  443. device_data: JsonDict,
  444. initial_device_display_name: Optional[str] = None,
  445. ) -> str:
  446. """Store a dehydrated device for a user. If the user had a previous
  447. dehydrated device, it is removed.
  448. Args:
  449. user_id: the user that we are storing the device for
  450. device_data: the dehydrated device information
  451. initial_device_display_name: The display name to use for the device
  452. Returns:
  453. device id of the dehydrated device
  454. """
  455. device_id = await self.check_device_registered(
  456. user_id,
  457. None,
  458. initial_device_display_name,
  459. )
  460. old_device_id = await self.store.store_dehydrated_device(
  461. user_id, device_id, device_data
  462. )
  463. if old_device_id is not None:
  464. await self.delete_device(user_id, old_device_id)
  465. return device_id
  466. async def get_dehydrated_device(
  467. self, user_id: str
  468. ) -> Optional[Tuple[str, JsonDict]]:
  469. """Retrieve the information for a dehydrated device.
  470. Args:
  471. user_id: the user whose dehydrated device we are looking for
  472. Returns:
  473. a tuple whose first item is the device ID, and the second item is
  474. the dehydrated device information
  475. """
  476. return await self.store.get_dehydrated_device(user_id)
  477. async def rehydrate_device(
  478. self, user_id: str, access_token: str, device_id: str
  479. ) -> dict:
  480. """Process a rehydration request from the user.
  481. Args:
  482. user_id: the user who is rehydrating the device
  483. access_token: the access token used for the request
  484. device_id: the ID of the device that will be rehydrated
  485. Returns:
  486. a dict containing {"success": True}
  487. """
  488. success = await self.store.remove_dehydrated_device(user_id, device_id)
  489. if not success:
  490. raise errors.NotFoundError()
  491. # If the dehydrated device was successfully deleted (the device ID
  492. # matched the stored dehydrated device), then modify the access
  493. # token to use the dehydrated device's ID and copy the old device
  494. # display name to the dehydrated device, and destroy the old device
  495. # ID
  496. old_device_id = await self.store.set_device_for_access_token(
  497. access_token, device_id
  498. )
  499. old_device = await self.store.get_device(user_id, old_device_id)
  500. if old_device is None:
  501. raise errors.NotFoundError()
  502. await self.store.update_device(user_id, device_id, old_device["display_name"])
  503. # can't call self.delete_device because that will clobber the
  504. # access token so call the storage layer directly
  505. await self.store.delete_device(user_id, old_device_id)
  506. await self.store.delete_e2e_keys_by_device(
  507. user_id=user_id, device_id=old_device_id
  508. )
  509. # tell everyone that the old device is gone and that the dehydrated
  510. # device has a new display name
  511. await self.notify_device_update(user_id, [old_device_id, device_id])
  512. return {"success": True}
  513. @wrap_as_background_process("_handle_new_device_update_async")
  514. async def _handle_new_device_update_async(self) -> None:
  515. """Called when we have a new local device list update that we need to
  516. send out over federation.
  517. This happens in the background so as not to block the original request
  518. that generated the device update.
  519. """
  520. if self._handle_new_device_update_is_processing:
  521. self._handle_new_device_update_new_data = True
  522. return
  523. self._handle_new_device_update_is_processing = True
  524. # The stream ID we processed previous iteration (if any), and the set of
  525. # hosts we've already poked about for this update. This is so that we
  526. # don't poke the same remote server about the same update repeatedly.
  527. current_stream_id = None
  528. hosts_already_sent_to: Set[str] = set()
  529. try:
  530. while True:
  531. self._handle_new_device_update_new_data = False
  532. rows = await self.store.get_uncoverted_outbound_room_pokes()
  533. if not rows:
  534. # If the DB returned nothing then there is nothing left to
  535. # do, *unless* a new device list update happened during the
  536. # DB query.
  537. if self._handle_new_device_update_new_data:
  538. continue
  539. else:
  540. return
  541. for user_id, device_id, room_id, stream_id, opentracing_context in rows:
  542. joined_user_ids = await self.store.get_users_in_room(room_id)
  543. hosts = {get_domain_from_id(u) for u in joined_user_ids}
  544. hosts.discard(self.server_name)
  545. # Check if we've already sent this update to some hosts
  546. if current_stream_id == stream_id:
  547. hosts -= hosts_already_sent_to
  548. await self.store.add_device_list_outbound_pokes(
  549. user_id=user_id,
  550. device_id=device_id,
  551. room_id=room_id,
  552. stream_id=stream_id,
  553. hosts=hosts,
  554. context=opentracing_context,
  555. )
  556. # Notify replication that we've updated the device list stream.
  557. self.notifier.notify_replication()
  558. if hosts:
  559. logger.info(
  560. "Sending device list update notif for %r to: %r",
  561. user_id,
  562. hosts,
  563. )
  564. for host in hosts:
  565. self.federation_sender.send_device_messages(
  566. host, immediate=False
  567. )
  568. log_kv(
  569. {"message": "sent device update to host", "host": host}
  570. )
  571. if current_stream_id != stream_id:
  572. # Clear the set of hosts we've already sent to as we're
  573. # processing a new update.
  574. hosts_already_sent_to.clear()
  575. hosts_already_sent_to.update(hosts)
  576. current_stream_id = stream_id
  577. finally:
  578. self._handle_new_device_update_is_processing = False
  579. def _update_device_from_client_ips(
  580. device: JsonDict, client_ips: Mapping[Tuple[str, str], Mapping[str, Any]]
  581. ) -> None:
  582. ip = client_ips.get((device["user_id"], device["device_id"]), {})
  583. device.update({"last_seen_ts": ip.get("last_seen"), "last_seen_ip": ip.get("ip")})
  584. class DeviceListUpdater:
  585. "Handles incoming device list updates from federation and updates the DB"
  586. def __init__(self, hs: "HomeServer", device_handler: DeviceHandler):
  587. self.store = hs.get_datastores().main
  588. self.federation = hs.get_federation_client()
  589. self.clock = hs.get_clock()
  590. self.device_handler = device_handler
  591. self._remote_edu_linearizer = Linearizer(name="remote_device_list")
  592. # user_id -> list of updates waiting to be handled.
  593. self._pending_updates: Dict[
  594. str, List[Tuple[str, str, Iterable[str], JsonDict]]
  595. ] = {}
  596. # Recently seen stream ids. We don't bother keeping these in the DB,
  597. # but they're useful to have them about to reduce the number of spurious
  598. # resyncs.
  599. self._seen_updates: ExpiringCache[str, Set[str]] = ExpiringCache(
  600. cache_name="device_update_edu",
  601. clock=self.clock,
  602. max_len=10000,
  603. expiry_ms=30 * 60 * 1000,
  604. iterable=True,
  605. )
  606. # Attempt to resync out of sync device lists every 30s.
  607. self._resync_retry_in_progress = False
  608. self.clock.looping_call(
  609. run_as_background_process,
  610. 30 * 1000,
  611. func=self._maybe_retry_device_resync,
  612. desc="_maybe_retry_device_resync",
  613. )
  614. @trace
  615. async def incoming_device_list_update(
  616. self, origin: str, edu_content: JsonDict
  617. ) -> None:
  618. """Called on incoming device list update from federation. Responsible
  619. for parsing the EDU and adding to pending updates list.
  620. """
  621. set_tag("origin", origin)
  622. set_tag("edu_content", edu_content)
  623. user_id = edu_content.pop("user_id")
  624. device_id = edu_content.pop("device_id")
  625. stream_id = str(edu_content.pop("stream_id")) # They may come as ints
  626. prev_ids = edu_content.pop("prev_id", [])
  627. prev_ids = [str(p) for p in prev_ids] # They may come as ints
  628. if get_domain_from_id(user_id) != origin:
  629. # TODO: Raise?
  630. logger.warning(
  631. "Got device list update edu for %r/%r from %r",
  632. user_id,
  633. device_id,
  634. origin,
  635. )
  636. set_tag("error", True)
  637. log_kv(
  638. {
  639. "message": "Got a device list update edu from a user and "
  640. "device which does not match the origin of the request.",
  641. "user_id": user_id,
  642. "device_id": device_id,
  643. }
  644. )
  645. return
  646. room_ids = await self.store.get_rooms_for_user(user_id)
  647. if not room_ids:
  648. # We don't share any rooms with this user. Ignore update, as we
  649. # probably won't get any further updates.
  650. set_tag("error", True)
  651. log_kv(
  652. {
  653. "message": "Got an update from a user for which "
  654. "we don't share any rooms",
  655. "other user_id": user_id,
  656. }
  657. )
  658. logger.warning(
  659. "Got device list update edu for %r/%r, but don't share a room",
  660. user_id,
  661. device_id,
  662. )
  663. return
  664. logger.debug("Received device list update for %r/%r", user_id, device_id)
  665. self._pending_updates.setdefault(user_id, []).append(
  666. (device_id, stream_id, prev_ids, edu_content)
  667. )
  668. await self._handle_device_updates(user_id)
  669. @measure_func("_incoming_device_list_update")
  670. async def _handle_device_updates(self, user_id: str) -> None:
  671. "Actually handle pending updates."
  672. async with self._remote_edu_linearizer.queue(user_id):
  673. pending_updates = self._pending_updates.pop(user_id, [])
  674. if not pending_updates:
  675. # This can happen since we batch updates
  676. return
  677. for device_id, stream_id, prev_ids, _ in pending_updates:
  678. logger.debug(
  679. "Handling update %r/%r, ID: %r, prev: %r ",
  680. user_id,
  681. device_id,
  682. stream_id,
  683. prev_ids,
  684. )
  685. # Given a list of updates we check if we need to resync. This
  686. # happens if we've missed updates.
  687. resync = await self._need_to_do_resync(user_id, pending_updates)
  688. if logger.isEnabledFor(logging.INFO):
  689. logger.info(
  690. "Received device list update for %s, requiring resync: %s. Devices: %s",
  691. user_id,
  692. resync,
  693. ", ".join(u[0] for u in pending_updates),
  694. )
  695. if resync:
  696. await self.user_device_resync(user_id)
  697. else:
  698. # Simply update the single device, since we know that is the only
  699. # change (because of the single prev_id matching the current cache)
  700. for device_id, stream_id, _, content in pending_updates:
  701. await self.store.update_remote_device_list_cache_entry(
  702. user_id, device_id, content, stream_id
  703. )
  704. await self.device_handler.notify_device_update(
  705. user_id, [device_id for device_id, _, _, _ in pending_updates]
  706. )
  707. self._seen_updates.setdefault(user_id, set()).update(
  708. stream_id for _, stream_id, _, _ in pending_updates
  709. )
  710. async def _need_to_do_resync(
  711. self, user_id: str, updates: Iterable[Tuple[str, str, Iterable[str], JsonDict]]
  712. ) -> bool:
  713. """Given a list of updates for a user figure out if we need to do a full
  714. resync, or whether we have enough data that we can just apply the delta.
  715. """
  716. seen_updates: Set[str] = self._seen_updates.get(user_id, set())
  717. extremity = await self.store.get_device_list_last_stream_id_for_remote(user_id)
  718. logger.debug("Current extremity for %r: %r", user_id, extremity)
  719. stream_id_in_updates = set() # stream_ids in updates list
  720. for _, stream_id, prev_ids, _ in updates:
  721. if not prev_ids:
  722. # We always do a resync if there are no previous IDs
  723. return True
  724. for prev_id in prev_ids:
  725. if prev_id == extremity:
  726. continue
  727. elif prev_id in seen_updates:
  728. continue
  729. elif prev_id in stream_id_in_updates:
  730. continue
  731. else:
  732. return True
  733. stream_id_in_updates.add(stream_id)
  734. return False
  735. @trace
  736. async def _maybe_retry_device_resync(self) -> None:
  737. """Retry to resync device lists that are out of sync, except if another retry is
  738. in progress.
  739. """
  740. if self._resync_retry_in_progress:
  741. return
  742. try:
  743. # Prevent another call of this function to retry resyncing device lists so
  744. # we don't send too many requests.
  745. self._resync_retry_in_progress = True
  746. # Get all of the users that need resyncing.
  747. need_resync = await self.store.get_user_ids_requiring_device_list_resync()
  748. # Iterate over the set of user IDs.
  749. for user_id in need_resync:
  750. try:
  751. # Try to resync the current user's devices list.
  752. result = await self.user_device_resync(
  753. user_id=user_id,
  754. mark_failed_as_stale=False,
  755. )
  756. # user_device_resync only returns a result if it managed to
  757. # successfully resync and update the database. Updating the table
  758. # of users requiring resync isn't necessary here as
  759. # user_device_resync already does it (through
  760. # self.store.update_remote_device_list_cache).
  761. if result:
  762. logger.debug(
  763. "Successfully resynced the device list for %s",
  764. user_id,
  765. )
  766. except Exception as e:
  767. # If there was an issue resyncing this user, e.g. if the remote
  768. # server sent a malformed result, just log the error instead of
  769. # aborting all the subsequent resyncs.
  770. logger.debug(
  771. "Could not resync the device list for %s: %s",
  772. user_id,
  773. e,
  774. )
  775. finally:
  776. # Allow future calls to retry resyncinc out of sync device lists.
  777. self._resync_retry_in_progress = False
  778. async def user_device_resync(
  779. self, user_id: str, mark_failed_as_stale: bool = True
  780. ) -> Optional[JsonDict]:
  781. """Fetches all devices for a user and updates the device cache with them.
  782. Args:
  783. user_id: The user's id whose device_list will be updated.
  784. mark_failed_as_stale: Whether to mark the user's device list as stale
  785. if the attempt to resync failed.
  786. Returns:
  787. A dict with device info as under the "devices" in the result of this
  788. request:
  789. https://matrix.org/docs/spec/server_server/r0.1.2#get-matrix-federation-v1-user-devices-userid
  790. """
  791. logger.debug("Attempting to resync the device list for %s", user_id)
  792. log_kv({"message": "Doing resync to update device list."})
  793. # Fetch all devices for the user.
  794. origin = get_domain_from_id(user_id)
  795. try:
  796. result = await self.federation.query_user_devices(origin, user_id)
  797. except NotRetryingDestination:
  798. if mark_failed_as_stale:
  799. # Mark the remote user's device list as stale so we know we need to retry
  800. # it later.
  801. await self.store.mark_remote_user_device_cache_as_stale(user_id)
  802. return None
  803. except (RequestSendFailed, HttpResponseException) as e:
  804. logger.warning(
  805. "Failed to handle device list update for %s: %s",
  806. user_id,
  807. e,
  808. )
  809. if mark_failed_as_stale:
  810. # Mark the remote user's device list as stale so we know we need to retry
  811. # it later.
  812. await self.store.mark_remote_user_device_cache_as_stale(user_id)
  813. # We abort on exceptions rather than accepting the update
  814. # as otherwise synapse will 'forget' that its device list
  815. # is out of date. If we bail then we will retry the resync
  816. # next time we get a device list update for this user_id.
  817. # This makes it more likely that the device lists will
  818. # eventually become consistent.
  819. return None
  820. except FederationDeniedError as e:
  821. set_tag("error", True)
  822. log_kv({"reason": "FederationDeniedError"})
  823. logger.info(e)
  824. return None
  825. except Exception as e:
  826. set_tag("error", True)
  827. log_kv(
  828. {"message": "Exception raised by federation request", "exception": e}
  829. )
  830. logger.exception("Failed to handle device list update for %s", user_id)
  831. if mark_failed_as_stale:
  832. # Mark the remote user's device list as stale so we know we need to retry
  833. # it later.
  834. await self.store.mark_remote_user_device_cache_as_stale(user_id)
  835. return None
  836. log_kv({"result": result})
  837. stream_id = result["stream_id"]
  838. devices = result["devices"]
  839. # Get the master key and the self-signing key for this user if provided in the
  840. # response (None if not in the response).
  841. # The response will not contain the user signing key, as this key is only used by
  842. # its owner, thus it doesn't make sense to send it over federation.
  843. master_key = result.get("master_key")
  844. self_signing_key = result.get("self_signing_key")
  845. ignore_devices = False
  846. # If the remote server has more than ~1000 devices for this user
  847. # we assume that something is going horribly wrong (e.g. a bot
  848. # that logs in and creates a new device every time it tries to
  849. # send a message). Maintaining lots of devices per user in the
  850. # cache can cause serious performance issues as if this request
  851. # takes more than 60s to complete, internal replication from the
  852. # inbound federation worker to the synapse master may time out
  853. # causing the inbound federation to fail and causing the remote
  854. # server to retry, causing a DoS. So in this scenario we give
  855. # up on storing the total list of devices and only handle the
  856. # delta instead.
  857. if len(devices) > 1000:
  858. logger.warning(
  859. "Ignoring device list snapshot for %s as it has >1K devs (%d)",
  860. user_id,
  861. len(devices),
  862. )
  863. devices = []
  864. ignore_devices = True
  865. else:
  866. prev_stream_id = await self.store.get_device_list_last_stream_id_for_remote(
  867. user_id
  868. )
  869. cached_devices = await self.store.get_cached_devices_for_user(user_id)
  870. # To ensure that a user with no devices is cached, we skip the resync only
  871. # if we have a stream_id from previously writing a cache entry.
  872. if prev_stream_id is not None and cached_devices == {
  873. d["device_id"]: d for d in devices
  874. }:
  875. logging.info(
  876. "Skipping device list resync for %s, as our cache matches already",
  877. user_id,
  878. )
  879. devices = []
  880. ignore_devices = True
  881. for device in devices:
  882. logger.debug(
  883. "Handling resync update %r/%r, ID: %r",
  884. user_id,
  885. device["device_id"],
  886. stream_id,
  887. )
  888. if not ignore_devices:
  889. await self.store.update_remote_device_list_cache(
  890. user_id, devices, stream_id
  891. )
  892. # mark the cache as valid, whether or not we actually processed any device
  893. # list updates.
  894. await self.store.mark_remote_user_device_cache_as_valid(user_id)
  895. device_ids = [device["device_id"] for device in devices]
  896. # Handle cross-signing keys.
  897. cross_signing_device_ids = await self.process_cross_signing_key_update(
  898. user_id,
  899. master_key,
  900. self_signing_key,
  901. )
  902. device_ids = device_ids + cross_signing_device_ids
  903. if device_ids:
  904. await self.device_handler.notify_device_update(user_id, device_ids)
  905. # We clobber the seen updates since we've re-synced from a given
  906. # point.
  907. self._seen_updates[user_id] = {stream_id}
  908. return result
  909. async def process_cross_signing_key_update(
  910. self,
  911. user_id: str,
  912. master_key: Optional[JsonDict],
  913. self_signing_key: Optional[JsonDict],
  914. ) -> List[str]:
  915. """Process the given new master and self-signing key for the given remote user.
  916. Args:
  917. user_id: The ID of the user these keys are for.
  918. master_key: The dict of the cross-signing master key as returned by the
  919. remote server.
  920. self_signing_key: The dict of the cross-signing self-signing key as returned
  921. by the remote server.
  922. Return:
  923. The device IDs for the given keys.
  924. """
  925. device_ids = []
  926. current_keys_map = await self.store.get_e2e_cross_signing_keys_bulk([user_id])
  927. current_keys = current_keys_map.get(user_id) or {}
  928. if master_key and master_key != current_keys.get("master"):
  929. await self.store.set_e2e_cross_signing_key(user_id, "master", master_key)
  930. _, verify_key = get_verify_key_from_cross_signing_key(master_key)
  931. # verify_key is a VerifyKey from signedjson, which uses
  932. # .version to denote the portion of the key ID after the
  933. # algorithm and colon, which is the device ID
  934. device_ids.append(verify_key.version)
  935. if self_signing_key and self_signing_key != current_keys.get("self_signing"):
  936. await self.store.set_e2e_cross_signing_key(
  937. user_id, "self_signing", self_signing_key
  938. )
  939. _, verify_key = get_verify_key_from_cross_signing_key(self_signing_key)
  940. device_ids.append(verify_key.version)
  941. return device_ids