You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1463 lines
55 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 http import HTTPStatus
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Collection,
  22. Dict,
  23. Iterable,
  24. List,
  25. Mapping,
  26. Optional,
  27. Set,
  28. Tuple,
  29. )
  30. from synapse.api import errors
  31. from synapse.api.constants import EduTypes, EventTypes
  32. from synapse.api.errors import (
  33. Codes,
  34. FederationDeniedError,
  35. HttpResponseException,
  36. InvalidAPICallError,
  37. RequestSendFailed,
  38. SynapseError,
  39. )
  40. from synapse.logging.opentracing import log_kv, set_tag, trace
  41. from synapse.metrics.background_process_metrics import (
  42. run_as_background_process,
  43. wrap_as_background_process,
  44. )
  45. from synapse.types import (
  46. JsonDict,
  47. StreamKeyType,
  48. StreamToken,
  49. UserID,
  50. get_domain_from_id,
  51. get_verify_key_from_cross_signing_key,
  52. )
  53. from synapse.util import stringutils
  54. from synapse.util.async_helpers import Linearizer
  55. from synapse.util.caches.expiringcache import ExpiringCache
  56. from synapse.util.cancellation import cancellable
  57. from synapse.util.metrics import measure_func
  58. from synapse.util.retryutils import NotRetryingDestination
  59. if TYPE_CHECKING:
  60. from synapse.server import HomeServer
  61. logger = logging.getLogger(__name__)
  62. MAX_DEVICE_DISPLAY_NAME_LEN = 100
  63. DELETE_STALE_DEVICES_INTERVAL_MS = 24 * 60 * 60 * 1000
  64. class DeviceWorkerHandler:
  65. device_list_updater: "DeviceListWorkerUpdater"
  66. def __init__(self, hs: "HomeServer"):
  67. self.clock = hs.get_clock()
  68. self.hs = hs
  69. self.store = hs.get_datastores().main
  70. self.notifier = hs.get_notifier()
  71. self.state = hs.get_state_handler()
  72. self._state_storage = hs.get_storage_controllers().state
  73. self._auth_handler = hs.get_auth_handler()
  74. self.server_name = hs.hostname
  75. self._msc3852_enabled = hs.config.experimental.msc3852_enabled
  76. self.device_list_updater = DeviceListWorkerUpdater(hs)
  77. @trace
  78. async def get_devices_by_user(self, user_id: str) -> List[JsonDict]:
  79. """
  80. Retrieve the given user's devices
  81. Args:
  82. user_id: The user ID to query for devices.
  83. Returns:
  84. info on each device
  85. """
  86. set_tag("user_id", user_id)
  87. device_map = await self.store.get_devices_by_user(user_id)
  88. ips = await self.store.get_last_client_ip_by_device(user_id, device_id=None)
  89. devices = list(device_map.values())
  90. for device in devices:
  91. _update_device_from_client_ips(device, ips)
  92. log_kv(device_map)
  93. return devices
  94. async def get_dehydrated_device(
  95. self, user_id: str
  96. ) -> Optional[Tuple[str, JsonDict]]:
  97. """Retrieve the information for a dehydrated device.
  98. Args:
  99. user_id: the user whose dehydrated device we are looking for
  100. Returns:
  101. a tuple whose first item is the device ID, and the second item is
  102. the dehydrated device information
  103. """
  104. return await self.store.get_dehydrated_device(user_id)
  105. @trace
  106. async def get_device(self, user_id: str, device_id: str) -> JsonDict:
  107. """Retrieve the given device
  108. Args:
  109. user_id: The user to get the device from
  110. device_id: The device to fetch.
  111. Returns:
  112. info on the device
  113. Raises:
  114. errors.NotFoundError: if the device was not found
  115. """
  116. device = await self.store.get_device(user_id, device_id)
  117. if device is None:
  118. raise errors.NotFoundError()
  119. ips = await self.store.get_last_client_ip_by_device(user_id, device_id)
  120. _update_device_from_client_ips(device, ips)
  121. set_tag("device", str(device))
  122. set_tag("ips", str(ips))
  123. return device
  124. @cancellable
  125. async def get_device_changes_in_shared_rooms(
  126. self, user_id: str, room_ids: Collection[str], from_token: StreamToken
  127. ) -> Set[str]:
  128. """Get the set of users whose devices have changed who share a room with
  129. the given user.
  130. """
  131. changed_users = await self.store.get_device_list_changes_in_rooms(
  132. room_ids, from_token.device_list_key
  133. )
  134. if changed_users is not None:
  135. # We also check if the given user has changed their device. If
  136. # they're in no rooms then the above query won't include them.
  137. changed = await self.store.get_users_whose_devices_changed(
  138. from_token.device_list_key, [user_id]
  139. )
  140. changed_users.update(changed)
  141. return changed_users
  142. # If the DB returned None then the `from_token` is too old, so we fall
  143. # back on looking for device updates for all users.
  144. users_who_share_room = await self.store.get_users_who_share_room_with_user(
  145. user_id
  146. )
  147. tracked_users = set(users_who_share_room)
  148. # Always tell the user about their own devices
  149. tracked_users.add(user_id)
  150. changed = await self.store.get_users_whose_devices_changed(
  151. from_token.device_list_key, tracked_users
  152. )
  153. return changed
  154. @trace
  155. @measure_func("device.get_user_ids_changed")
  156. @cancellable
  157. async def get_user_ids_changed(
  158. self, user_id: str, from_token: StreamToken
  159. ) -> JsonDict:
  160. """Get list of users that have had the devices updated, or have newly
  161. joined a room, that `user_id` may be interested in.
  162. """
  163. set_tag("user_id", user_id)
  164. set_tag("from_token", str(from_token))
  165. now_room_key = self.store.get_room_max_token()
  166. room_ids = await self.store.get_rooms_for_user(user_id)
  167. changed = await self.get_device_changes_in_shared_rooms(
  168. user_id, room_ids, from_token
  169. )
  170. # Then work out if any users have since joined
  171. rooms_changed = self.store.get_rooms_that_changed(room_ids, from_token.room_key)
  172. member_events = await self.store.get_membership_changes_for_user(
  173. user_id, from_token.room_key, now_room_key
  174. )
  175. rooms_changed.update(event.room_id for event in member_events)
  176. stream_ordering = from_token.room_key.stream
  177. possibly_changed = set(changed)
  178. possibly_left = set()
  179. for room_id in rooms_changed:
  180. current_state_ids = await self._state_storage.get_current_state_ids(
  181. room_id, await_full_state=False
  182. )
  183. # The user may have left the room
  184. # TODO: Check if they actually did or if we were just invited.
  185. if room_id not in room_ids:
  186. for etype, state_key in current_state_ids.keys():
  187. if etype != EventTypes.Member:
  188. continue
  189. possibly_left.add(state_key)
  190. continue
  191. # Fetch the current state at the time.
  192. try:
  193. event_ids = await self.store.get_forward_extremities_for_room_at_stream_ordering(
  194. room_id, stream_ordering=stream_ordering
  195. )
  196. except errors.StoreError:
  197. # we have purged the stream_ordering index since the stream
  198. # ordering: treat it the same as a new room
  199. event_ids = []
  200. # special-case for an empty prev state: include all members
  201. # in the changed list
  202. if not event_ids:
  203. log_kv(
  204. {"event": "encountered empty previous state", "room_id": room_id}
  205. )
  206. for etype, state_key in current_state_ids.keys():
  207. if etype != EventTypes.Member:
  208. continue
  209. possibly_changed.add(state_key)
  210. continue
  211. current_member_id = current_state_ids.get((EventTypes.Member, user_id))
  212. if not current_member_id:
  213. continue
  214. # mapping from event_id -> state_dict
  215. prev_state_ids = await self._state_storage.get_state_ids_for_events(
  216. event_ids,
  217. await_full_state=False,
  218. )
  219. # Check if we've joined the room? If so we just blindly add all the users to
  220. # the "possibly changed" users.
  221. for state_dict in prev_state_ids.values():
  222. member_event = state_dict.get((EventTypes.Member, user_id), None)
  223. if not member_event or member_event != current_member_id:
  224. for etype, state_key in current_state_ids.keys():
  225. if etype != EventTypes.Member:
  226. continue
  227. possibly_changed.add(state_key)
  228. break
  229. # If there has been any change in membership, include them in the
  230. # possibly changed list. We'll check if they are joined below,
  231. # and we're not toooo worried about spuriously adding users.
  232. for key, event_id in current_state_ids.items():
  233. etype, state_key = key
  234. if etype != EventTypes.Member:
  235. continue
  236. # check if this member has changed since any of the extremities
  237. # at the stream_ordering, and add them to the list if so.
  238. for state_dict in prev_state_ids.values():
  239. prev_event_id = state_dict.get(key, None)
  240. if not prev_event_id or prev_event_id != event_id:
  241. if state_key != user_id:
  242. possibly_changed.add(state_key)
  243. break
  244. if possibly_changed or possibly_left:
  245. possibly_joined = possibly_changed
  246. possibly_left = possibly_changed | possibly_left
  247. # Double check if we still share rooms with the given user.
  248. users_rooms = await self.store.get_rooms_for_users(possibly_left)
  249. for changed_user_id, entries in users_rooms.items():
  250. if any(rid in room_ids for rid in entries):
  251. possibly_left.discard(changed_user_id)
  252. else:
  253. possibly_joined.discard(changed_user_id)
  254. else:
  255. possibly_joined = set()
  256. possibly_left = set()
  257. result = {"changed": list(possibly_joined), "left": list(possibly_left)}
  258. log_kv(result)
  259. return result
  260. async def on_federation_query_user_devices(self, user_id: str) -> JsonDict:
  261. stream_id, devices = await self.store.get_e2e_device_keys_for_federation_query(
  262. user_id
  263. )
  264. master_key = await self.store.get_e2e_cross_signing_key(user_id, "master")
  265. self_signing_key = await self.store.get_e2e_cross_signing_key(
  266. user_id, "self_signing"
  267. )
  268. return {
  269. "user_id": user_id,
  270. "stream_id": stream_id,
  271. "devices": devices,
  272. "master_key": master_key,
  273. "self_signing_key": self_signing_key,
  274. }
  275. async def handle_room_un_partial_stated(self, room_id: str) -> None:
  276. """Handles sending appropriate device list updates in a room that has
  277. gone from partial to full state.
  278. """
  279. # TODO(faster_joins): worker mode support
  280. # https://github.com/matrix-org/synapse/issues/12994
  281. logger.error(
  282. "Trying handling device list state for partial join: not supported on workers."
  283. )
  284. class DeviceHandler(DeviceWorkerHandler):
  285. device_list_updater: "DeviceListUpdater"
  286. def __init__(self, hs: "HomeServer"):
  287. super().__init__(hs)
  288. self.federation_sender = hs.get_federation_sender()
  289. self._account_data_handler = hs.get_account_data_handler()
  290. self._storage_controllers = hs.get_storage_controllers()
  291. self.device_list_updater = DeviceListUpdater(hs, self)
  292. federation_registry = hs.get_federation_registry()
  293. federation_registry.register_edu_handler(
  294. EduTypes.DEVICE_LIST_UPDATE,
  295. self.device_list_updater.incoming_device_list_update,
  296. )
  297. # Whether `_handle_new_device_update_async` is currently processing.
  298. self._handle_new_device_update_is_processing = False
  299. # If a new device update may have happened while the loop was
  300. # processing.
  301. self._handle_new_device_update_new_data = False
  302. # On start up check if there are any updates pending.
  303. hs.get_reactor().callWhenRunning(self._handle_new_device_update_async)
  304. self._delete_stale_devices_after = hs.config.server.delete_stale_devices_after
  305. # Ideally we would run this on a worker and condition this on the
  306. # "run_background_tasks_on" setting, but this would mean making the notification
  307. # of device list changes over federation work on workers, which is nontrivial.
  308. if self._delete_stale_devices_after is not None:
  309. self.clock.looping_call(
  310. run_as_background_process,
  311. DELETE_STALE_DEVICES_INTERVAL_MS,
  312. "delete_stale_devices",
  313. self._delete_stale_devices,
  314. )
  315. def _check_device_name_length(self, name: Optional[str]) -> None:
  316. """
  317. Checks whether a device name is longer than the maximum allowed length.
  318. Args:
  319. name: The name of the device.
  320. Raises:
  321. SynapseError: if the device name is too long.
  322. """
  323. if name and len(name) > MAX_DEVICE_DISPLAY_NAME_LEN:
  324. raise SynapseError(
  325. 400,
  326. "Device display name is too long (max %i)"
  327. % (MAX_DEVICE_DISPLAY_NAME_LEN,),
  328. errcode=Codes.TOO_LARGE,
  329. )
  330. async def check_device_registered(
  331. self,
  332. user_id: str,
  333. device_id: Optional[str],
  334. initial_device_display_name: Optional[str] = None,
  335. auth_provider_id: Optional[str] = None,
  336. auth_provider_session_id: Optional[str] = None,
  337. ) -> str:
  338. """
  339. If the given device has not been registered, register it with the
  340. supplied display name.
  341. If no device_id is supplied, we make one up.
  342. Args:
  343. user_id: @user:id
  344. device_id: device id supplied by client
  345. initial_device_display_name: device display name from client
  346. auth_provider_id: The SSO IdP the user used, if any.
  347. auth_provider_session_id: The session ID (sid) got from the SSO IdP.
  348. Returns:
  349. device id (generated if none was supplied)
  350. """
  351. self._check_device_name_length(initial_device_display_name)
  352. if device_id is not None:
  353. new_device = await self.store.store_device(
  354. user_id=user_id,
  355. device_id=device_id,
  356. initial_device_display_name=initial_device_display_name,
  357. auth_provider_id=auth_provider_id,
  358. auth_provider_session_id=auth_provider_session_id,
  359. )
  360. if new_device:
  361. await self.notify_device_update(user_id, [device_id])
  362. return device_id
  363. # if the device id is not specified, we'll autogen one, but loop a few
  364. # times in case of a clash.
  365. attempts = 0
  366. while attempts < 5:
  367. new_device_id = stringutils.random_string(10).upper()
  368. new_device = await self.store.store_device(
  369. user_id=user_id,
  370. device_id=new_device_id,
  371. initial_device_display_name=initial_device_display_name,
  372. auth_provider_id=auth_provider_id,
  373. auth_provider_session_id=auth_provider_session_id,
  374. )
  375. if new_device:
  376. await self.notify_device_update(user_id, [new_device_id])
  377. return new_device_id
  378. attempts += 1
  379. raise errors.StoreError(500, "Couldn't generate a device ID.")
  380. async def _delete_stale_devices(self) -> None:
  381. """Background task that deletes devices which haven't been accessed for more than
  382. a configured time period.
  383. """
  384. # We should only be running this job if the config option is defined.
  385. assert self._delete_stale_devices_after is not None
  386. now_ms = self.clock.time_msec()
  387. since_ms = now_ms - self._delete_stale_devices_after
  388. devices = await self.store.get_local_devices_not_accessed_since(since_ms)
  389. for user_id, user_devices in devices.items():
  390. await self.delete_devices(user_id, user_devices)
  391. @trace
  392. async def delete_all_devices_for_user(
  393. self, user_id: str, except_device_id: Optional[str] = None
  394. ) -> None:
  395. """Delete all of the user's devices
  396. Args:
  397. user_id: The user to remove all devices from
  398. except_device_id: optional device id which should not be deleted
  399. """
  400. device_map = await self.store.get_devices_by_user(user_id)
  401. device_ids = list(device_map)
  402. if except_device_id is not None:
  403. device_ids = [d for d in device_ids if d != except_device_id]
  404. await self.delete_devices(user_id, device_ids)
  405. async def delete_devices(self, user_id: str, device_ids: List[str]) -> None:
  406. """Delete several devices
  407. Args:
  408. user_id: The user to delete devices from.
  409. device_ids: The list of device IDs to delete
  410. """
  411. try:
  412. await self.store.delete_devices(user_id, device_ids)
  413. except errors.StoreError as e:
  414. if e.code == 404:
  415. # no match
  416. set_tag("error", True)
  417. set_tag("reason", "User doesn't have that device id.")
  418. else:
  419. raise
  420. # Delete data specific to each device. Not optimised as it is not
  421. # considered as part of a critical path.
  422. for device_id in device_ids:
  423. await self._auth_handler.delete_access_tokens_for_user(
  424. user_id, device_id=device_id
  425. )
  426. await self.store.delete_e2e_keys_by_device(
  427. user_id=user_id, device_id=device_id
  428. )
  429. if self.hs.config.experimental.msc3890_enabled:
  430. # Remove any local notification settings for this device in accordance
  431. # with MSC3890.
  432. await self._account_data_handler.remove_account_data_for_user(
  433. user_id,
  434. f"org.matrix.msc3890.local_notification_settings.{device_id}",
  435. )
  436. await self.notify_device_update(user_id, device_ids)
  437. async def update_device(self, user_id: str, device_id: str, content: dict) -> None:
  438. """Update the given device
  439. Args:
  440. user_id: The user to update devices of.
  441. device_id: The device to update.
  442. content: body of update request
  443. """
  444. # Reject a new displayname which is too long.
  445. new_display_name = content.get("display_name")
  446. self._check_device_name_length(new_display_name)
  447. try:
  448. await self.store.update_device(
  449. user_id, device_id, new_display_name=new_display_name
  450. )
  451. await self.notify_device_update(user_id, [device_id])
  452. except errors.StoreError as e:
  453. if e.code == 404:
  454. raise errors.NotFoundError()
  455. else:
  456. raise
  457. @trace
  458. @measure_func("notify_device_update")
  459. async def notify_device_update(
  460. self, user_id: str, device_ids: Collection[str]
  461. ) -> None:
  462. """Notify that a user's device(s) has changed. Pokes the notifier, and
  463. remote servers if the user is local.
  464. Args:
  465. user_id: The Matrix ID of the user who's device list has been updated.
  466. device_ids: The device IDs that have changed.
  467. """
  468. if not device_ids:
  469. # No changes to notify about, so this is a no-op.
  470. return
  471. room_ids = await self.store.get_rooms_for_user(user_id)
  472. position = await self.store.add_device_change_to_streams(
  473. user_id,
  474. device_ids,
  475. room_ids=room_ids,
  476. )
  477. if not position:
  478. # This should only happen if there are no updates, so we bail.
  479. return
  480. for device_id in device_ids:
  481. logger.debug(
  482. "Notifying about update %r/%r, ID: %r", user_id, device_id, position
  483. )
  484. # specify the user ID too since the user should always get their own device list
  485. # updates, even if they aren't in any rooms.
  486. self.notifier.on_new_event(
  487. StreamKeyType.DEVICE_LIST, position, users={user_id}, rooms=room_ids
  488. )
  489. # We may need to do some processing asynchronously for local user IDs.
  490. if self.hs.is_mine_id(user_id):
  491. self._handle_new_device_update_async()
  492. async def notify_user_signature_update(
  493. self, from_user_id: str, user_ids: List[str]
  494. ) -> None:
  495. """Notify a user that they have made new signatures of other users.
  496. Args:
  497. from_user_id: the user who made the signature
  498. user_ids: the users IDs that have new signatures
  499. """
  500. position = await self.store.add_user_signature_change_to_streams(
  501. from_user_id, user_ids
  502. )
  503. self.notifier.on_new_event(
  504. StreamKeyType.DEVICE_LIST, position, users=[from_user_id]
  505. )
  506. async def store_dehydrated_device(
  507. self,
  508. user_id: str,
  509. device_data: JsonDict,
  510. initial_device_display_name: Optional[str] = None,
  511. ) -> str:
  512. """Store a dehydrated device for a user. If the user had a previous
  513. dehydrated device, it is removed.
  514. Args:
  515. user_id: the user that we are storing the device for
  516. device_data: the dehydrated device information
  517. initial_device_display_name: The display name to use for the device
  518. Returns:
  519. device id of the dehydrated device
  520. """
  521. device_id = await self.check_device_registered(
  522. user_id,
  523. None,
  524. initial_device_display_name,
  525. )
  526. old_device_id = await self.store.store_dehydrated_device(
  527. user_id, device_id, device_data
  528. )
  529. if old_device_id is not None:
  530. await self.delete_devices(user_id, [old_device_id])
  531. return device_id
  532. async def rehydrate_device(
  533. self, user_id: str, access_token: str, device_id: str
  534. ) -> dict:
  535. """Process a rehydration request from the user.
  536. Args:
  537. user_id: the user who is rehydrating the device
  538. access_token: the access token used for the request
  539. device_id: the ID of the device that will be rehydrated
  540. Returns:
  541. a dict containing {"success": True}
  542. """
  543. success = await self.store.remove_dehydrated_device(user_id, device_id)
  544. if not success:
  545. raise errors.NotFoundError()
  546. # If the dehydrated device was successfully deleted (the device ID
  547. # matched the stored dehydrated device), then modify the access
  548. # token to use the dehydrated device's ID and copy the old device
  549. # display name to the dehydrated device, and destroy the old device
  550. # ID
  551. old_device_id = await self.store.set_device_for_access_token(
  552. access_token, device_id
  553. )
  554. old_device = await self.store.get_device(user_id, old_device_id)
  555. if old_device is None:
  556. raise errors.NotFoundError()
  557. await self.store.update_device(user_id, device_id, old_device["display_name"])
  558. # can't call self.delete_device because that will clobber the
  559. # access token so call the storage layer directly
  560. await self.store.delete_devices(user_id, [old_device_id])
  561. await self.store.delete_e2e_keys_by_device(
  562. user_id=user_id, device_id=old_device_id
  563. )
  564. # tell everyone that the old device is gone and that the dehydrated
  565. # device has a new display name
  566. await self.notify_device_update(user_id, [old_device_id, device_id])
  567. return {"success": True}
  568. @wrap_as_background_process("_handle_new_device_update_async")
  569. async def _handle_new_device_update_async(self) -> None:
  570. """Called when we have a new local device list update that we need to
  571. send out over federation.
  572. This happens in the background so as not to block the original request
  573. that generated the device update.
  574. """
  575. if self._handle_new_device_update_is_processing:
  576. self._handle_new_device_update_new_data = True
  577. return
  578. self._handle_new_device_update_is_processing = True
  579. # The stream ID we processed previous iteration (if any), and the set of
  580. # hosts we've already poked about for this update. This is so that we
  581. # don't poke the same remote server about the same update repeatedly.
  582. current_stream_id = None
  583. hosts_already_sent_to: Set[str] = set()
  584. try:
  585. stream_id, room_id = await self.store.get_device_change_last_converted_pos()
  586. while True:
  587. self._handle_new_device_update_new_data = False
  588. max_stream_id = self.store.get_device_stream_token()
  589. rows = await self.store.get_uncoverted_outbound_room_pokes(
  590. stream_id, room_id
  591. )
  592. if not rows:
  593. # If the DB returned nothing then there is nothing left to
  594. # do, *unless* a new device list update happened during the
  595. # DB query.
  596. # Advance `(stream_id, room_id)`.
  597. # `max_stream_id` comes from *before* the query for unconverted
  598. # rows, which means that any unconverted rows must have a larger
  599. # stream ID.
  600. if max_stream_id > stream_id:
  601. stream_id, room_id = max_stream_id, ""
  602. await self.store.set_device_change_last_converted_pos(
  603. stream_id, room_id
  604. )
  605. else:
  606. assert max_stream_id == stream_id
  607. # Avoid moving `room_id` backwards.
  608. pass
  609. if self._handle_new_device_update_new_data:
  610. continue
  611. else:
  612. return
  613. for user_id, device_id, room_id, stream_id, opentracing_context in rows:
  614. hosts = set()
  615. # Ignore any users that aren't ours
  616. if self.hs.is_mine_id(user_id):
  617. hosts = set(
  618. await self._storage_controllers.state.get_current_hosts_in_room_or_partial_state_approximation(
  619. room_id
  620. )
  621. )
  622. hosts.discard(self.server_name)
  623. # For rooms with partial state, `hosts` is merely an
  624. # approximation. When we transition to a full state room, we
  625. # will have to send out device list updates to any servers we
  626. # missed.
  627. # Check if we've already sent this update to some hosts
  628. if current_stream_id == stream_id:
  629. hosts -= hosts_already_sent_to
  630. await self.store.add_device_list_outbound_pokes(
  631. user_id=user_id,
  632. device_id=device_id,
  633. room_id=room_id,
  634. hosts=hosts,
  635. context=opentracing_context,
  636. )
  637. # Notify replication that we've updated the device list stream.
  638. self.notifier.notify_replication()
  639. if hosts:
  640. logger.info(
  641. "Sending device list update notif for %r to: %r",
  642. user_id,
  643. hosts,
  644. )
  645. for host in hosts:
  646. self.federation_sender.send_device_messages(
  647. host, immediate=False
  648. )
  649. # TODO: when called, this isn't in a logging context.
  650. # This leads to log spam, sentry event spam, and massive
  651. # memory usage.
  652. # See https://github.com/matrix-org/synapse/issues/12552.
  653. # log_kv(
  654. # {"message": "sent device update to host", "host": host}
  655. # )
  656. if current_stream_id != stream_id:
  657. # Clear the set of hosts we've already sent to as we're
  658. # processing a new update.
  659. hosts_already_sent_to.clear()
  660. hosts_already_sent_to.update(hosts)
  661. current_stream_id = stream_id
  662. # Advance `(stream_id, room_id)`.
  663. _, _, room_id, stream_id, _ = rows[-1]
  664. await self.store.set_device_change_last_converted_pos(
  665. stream_id, room_id
  666. )
  667. finally:
  668. self._handle_new_device_update_is_processing = False
  669. async def handle_room_un_partial_stated(self, room_id: str) -> None:
  670. """Handles sending appropriate device list updates in a room that has
  671. gone from partial to full state.
  672. """
  673. # We defer to the device list updater to handle pending remote device
  674. # list updates.
  675. await self.device_list_updater.handle_room_un_partial_stated(room_id)
  676. # Replay local updates.
  677. (
  678. join_event_id,
  679. device_lists_stream_id,
  680. ) = await self.store.get_join_event_id_and_device_lists_stream_id_for_partial_state(
  681. room_id
  682. )
  683. # Get the local device list changes that have happened in the room since
  684. # we started joining. If there are no updates there's nothing left to do.
  685. changes = await self.store.get_device_list_changes_in_room(
  686. room_id, device_lists_stream_id
  687. )
  688. local_changes = {(u, d) for u, d in changes if self.hs.is_mine_id(u)}
  689. if not local_changes:
  690. return
  691. # Note: We have persisted the full state at this point, we just haven't
  692. # cleared the `partial_room` flag.
  693. join_state_ids = await self._state_storage.get_state_ids_for_event(
  694. join_event_id, await_full_state=False
  695. )
  696. current_state_ids = await self.store.get_partial_current_state_ids(room_id)
  697. # Now we need to work out all servers that might have been in the room
  698. # at any point during our join.
  699. # First we look for any membership states that have changed between the
  700. # initial join and now...
  701. all_keys = set(join_state_ids)
  702. all_keys.update(current_state_ids)
  703. potentially_changed_hosts = set()
  704. for etype, state_key in all_keys:
  705. if etype != EventTypes.Member:
  706. continue
  707. prev = join_state_ids.get((etype, state_key))
  708. current = current_state_ids.get((etype, state_key))
  709. if prev != current:
  710. potentially_changed_hosts.add(get_domain_from_id(state_key))
  711. # ... then we add all the hosts that are currently joined to the room...
  712. current_hosts_in_room = await self.store.get_current_hosts_in_room(room_id)
  713. potentially_changed_hosts.update(current_hosts_in_room)
  714. # ... and finally we remove any hosts that we were told about, as we
  715. # will have sent device list updates to those hosts when they happened.
  716. known_hosts_at_join = await self.store.get_partial_state_servers_at_join(
  717. room_id
  718. )
  719. potentially_changed_hosts.difference_update(known_hosts_at_join)
  720. potentially_changed_hosts.discard(self.server_name)
  721. if not potentially_changed_hosts:
  722. # Nothing to do.
  723. return
  724. logger.info(
  725. "Found %d changed hosts to send device list updates to",
  726. len(potentially_changed_hosts),
  727. )
  728. for user_id, device_id in local_changes:
  729. await self.store.add_device_list_outbound_pokes(
  730. user_id=user_id,
  731. device_id=device_id,
  732. room_id=room_id,
  733. hosts=potentially_changed_hosts,
  734. context=None,
  735. )
  736. # Notify things that device lists need to be sent out.
  737. self.notifier.notify_replication()
  738. for host in potentially_changed_hosts:
  739. self.federation_sender.send_device_messages(host, immediate=False)
  740. def _update_device_from_client_ips(
  741. device: JsonDict, client_ips: Mapping[Tuple[str, str], Mapping[str, Any]]
  742. ) -> None:
  743. ip = client_ips.get((device["user_id"], device["device_id"]), {})
  744. device.update(
  745. {
  746. "last_seen_user_agent": ip.get("user_agent"),
  747. "last_seen_ts": ip.get("last_seen"),
  748. "last_seen_ip": ip.get("ip"),
  749. }
  750. )
  751. class DeviceListWorkerUpdater:
  752. "Handles incoming device list updates from federation and contacts the main process over replication"
  753. def __init__(self, hs: "HomeServer"):
  754. from synapse.replication.http.devices import (
  755. ReplicationMultiUserDevicesResyncRestServlet,
  756. ReplicationUserDevicesResyncRestServlet,
  757. )
  758. self._user_device_resync_client = (
  759. ReplicationUserDevicesResyncRestServlet.make_client(hs)
  760. )
  761. self._multi_user_device_resync_client = (
  762. ReplicationMultiUserDevicesResyncRestServlet.make_client(hs)
  763. )
  764. async def multi_user_device_resync(
  765. self, user_ids: List[str], mark_failed_as_stale: bool = True
  766. ) -> Dict[str, Optional[JsonDict]]:
  767. """
  768. Like `user_device_resync` but operates on multiple users **from the same origin**
  769. at once.
  770. Returns:
  771. Dict from User ID to the same Dict as `user_device_resync`.
  772. """
  773. # mark_failed_as_stale is not sent. Ensure this doesn't break expectations.
  774. assert mark_failed_as_stale
  775. if not user_ids:
  776. # Shortcut empty requests
  777. return {}
  778. try:
  779. return await self._multi_user_device_resync_client(user_ids=user_ids)
  780. except SynapseError as err:
  781. if not (
  782. err.code == HTTPStatus.NOT_FOUND and err.errcode == Codes.UNRECOGNIZED
  783. ):
  784. raise
  785. # Fall back to single requests
  786. result: Dict[str, Optional[JsonDict]] = {}
  787. for user_id in user_ids:
  788. result[user_id] = await self._user_device_resync_client(user_id=user_id)
  789. return result
  790. async def user_device_resync(
  791. self, user_id: str, mark_failed_as_stale: bool = True
  792. ) -> Optional[JsonDict]:
  793. """Fetches all devices for a user and updates the device cache with them.
  794. Args:
  795. user_id: The user's id whose device_list will be updated.
  796. mark_failed_as_stale: Whether to mark the user's device list as stale
  797. if the attempt to resync failed.
  798. Returns:
  799. A dict with device info as under the "devices" in the result of this
  800. request:
  801. https://matrix.org/docs/spec/server_server/r0.1.2#get-matrix-federation-v1-user-devices-userid
  802. None when we weren't able to fetch the device info for some reason,
  803. e.g. due to a connection problem.
  804. """
  805. return (await self.multi_user_device_resync([user_id]))[user_id]
  806. class DeviceListUpdater(DeviceListWorkerUpdater):
  807. "Handles incoming device list updates from federation and updates the DB"
  808. def __init__(self, hs: "HomeServer", device_handler: DeviceHandler):
  809. self.store = hs.get_datastores().main
  810. self.federation = hs.get_federation_client()
  811. self.clock = hs.get_clock()
  812. self.device_handler = device_handler
  813. self._notifier = hs.get_notifier()
  814. self._remote_edu_linearizer = Linearizer(name="remote_device_list")
  815. # user_id -> list of updates waiting to be handled.
  816. self._pending_updates: Dict[
  817. str, List[Tuple[str, str, Iterable[str], JsonDict]]
  818. ] = {}
  819. # Recently seen stream ids. We don't bother keeping these in the DB,
  820. # but they're useful to have them about to reduce the number of spurious
  821. # resyncs.
  822. self._seen_updates: ExpiringCache[str, Set[str]] = ExpiringCache(
  823. cache_name="device_update_edu",
  824. clock=self.clock,
  825. max_len=10000,
  826. expiry_ms=30 * 60 * 1000,
  827. iterable=True,
  828. )
  829. # Attempt to resync out of sync device lists every 30s.
  830. self._resync_retry_in_progress = False
  831. self.clock.looping_call(
  832. run_as_background_process,
  833. 30 * 1000,
  834. func=self._maybe_retry_device_resync,
  835. desc="_maybe_retry_device_resync",
  836. )
  837. @trace
  838. async def incoming_device_list_update(
  839. self, origin: str, edu_content: JsonDict
  840. ) -> None:
  841. """Called on incoming device list update from federation. Responsible
  842. for parsing the EDU and adding to pending updates list.
  843. """
  844. set_tag("origin", origin)
  845. set_tag("edu_content", str(edu_content))
  846. user_id = edu_content.pop("user_id")
  847. device_id = edu_content.pop("device_id")
  848. stream_id = str(edu_content.pop("stream_id")) # They may come as ints
  849. prev_ids = edu_content.pop("prev_id", [])
  850. if not isinstance(prev_ids, list):
  851. raise SynapseError(
  852. 400, "Device list update had an invalid 'prev_ids' field"
  853. )
  854. prev_ids = [str(p) for p in prev_ids] # They may come as ints
  855. if get_domain_from_id(user_id) != origin:
  856. # TODO: Raise?
  857. logger.warning(
  858. "Got device list update edu for %r/%r from %r",
  859. user_id,
  860. device_id,
  861. origin,
  862. )
  863. set_tag("error", True)
  864. log_kv(
  865. {
  866. "message": "Got a device list update edu from a user and "
  867. "device which does not match the origin of the request.",
  868. "user_id": user_id,
  869. "device_id": device_id,
  870. }
  871. )
  872. return
  873. # Check if we are partially joining any rooms. If so we need to store
  874. # all device list updates so that we can handle them correctly once we
  875. # know who is in the room.
  876. # TODO(faster_joins): this fetches and processes a bunch of data that we don't
  877. # use. Could be replaced by a tighter query e.g.
  878. # SELECT EXISTS(SELECT 1 FROM partial_state_rooms)
  879. partial_rooms = await self.store.get_partial_state_room_resync_info()
  880. if partial_rooms:
  881. await self.store.add_remote_device_list_to_pending(
  882. user_id,
  883. device_id,
  884. )
  885. self._notifier.notify_replication()
  886. room_ids = await self.store.get_rooms_for_user(user_id)
  887. if not room_ids:
  888. # We don't share any rooms with this user. Ignore update, as we
  889. # probably won't get any further updates.
  890. set_tag("error", True)
  891. log_kv(
  892. {
  893. "message": "Got an update from a user for which "
  894. "we don't share any rooms",
  895. "other user_id": user_id,
  896. }
  897. )
  898. logger.warning(
  899. "Got device list update edu for %r/%r, but don't share a room",
  900. user_id,
  901. device_id,
  902. )
  903. return
  904. logger.debug("Received device list update for %r/%r", user_id, device_id)
  905. self._pending_updates.setdefault(user_id, []).append(
  906. (device_id, stream_id, prev_ids, edu_content)
  907. )
  908. await self._handle_device_updates(user_id)
  909. @measure_func("_incoming_device_list_update")
  910. async def _handle_device_updates(self, user_id: str) -> None:
  911. "Actually handle pending updates."
  912. async with self._remote_edu_linearizer.queue(user_id):
  913. pending_updates = self._pending_updates.pop(user_id, [])
  914. if not pending_updates:
  915. # This can happen since we batch updates
  916. return
  917. for device_id, stream_id, prev_ids, _ in pending_updates:
  918. logger.debug(
  919. "Handling update %r/%r, ID: %r, prev: %r ",
  920. user_id,
  921. device_id,
  922. stream_id,
  923. prev_ids,
  924. )
  925. # Given a list of updates we check if we need to resync. This
  926. # happens if we've missed updates.
  927. resync = await self._need_to_do_resync(user_id, pending_updates)
  928. if logger.isEnabledFor(logging.INFO):
  929. logger.info(
  930. "Received device list update for %s, requiring resync: %s. Devices: %s",
  931. user_id,
  932. resync,
  933. ", ".join(u[0] for u in pending_updates),
  934. )
  935. if resync:
  936. await self.user_device_resync(user_id)
  937. else:
  938. # Simply update the single device, since we know that is the only
  939. # change (because of the single prev_id matching the current cache)
  940. for device_id, stream_id, _, content in pending_updates:
  941. await self.store.update_remote_device_list_cache_entry(
  942. user_id, device_id, content, stream_id
  943. )
  944. await self.device_handler.notify_device_update(
  945. user_id, [device_id for device_id, _, _, _ in pending_updates]
  946. )
  947. self._seen_updates.setdefault(user_id, set()).update(
  948. stream_id for _, stream_id, _, _ in pending_updates
  949. )
  950. async def _need_to_do_resync(
  951. self, user_id: str, updates: Iterable[Tuple[str, str, Iterable[str], JsonDict]]
  952. ) -> bool:
  953. """Given a list of updates for a user figure out if we need to do a full
  954. resync, or whether we have enough data that we can just apply the delta.
  955. """
  956. seen_updates: Set[str] = self._seen_updates.get(user_id, set())
  957. extremity = await self.store.get_device_list_last_stream_id_for_remote(user_id)
  958. logger.debug("Current extremity for %r: %r", user_id, extremity)
  959. stream_id_in_updates = set() # stream_ids in updates list
  960. for _, stream_id, prev_ids, _ in updates:
  961. if not prev_ids:
  962. # We always do a resync if there are no previous IDs
  963. return True
  964. for prev_id in prev_ids:
  965. if prev_id == extremity:
  966. continue
  967. elif prev_id in seen_updates:
  968. continue
  969. elif prev_id in stream_id_in_updates:
  970. continue
  971. else:
  972. return True
  973. stream_id_in_updates.add(stream_id)
  974. return False
  975. @trace
  976. async def _maybe_retry_device_resync(self) -> None:
  977. """Retry to resync device lists that are out of sync, except if another retry is
  978. in progress.
  979. """
  980. if self._resync_retry_in_progress:
  981. return
  982. try:
  983. # Prevent another call of this function to retry resyncing device lists so
  984. # we don't send too many requests.
  985. self._resync_retry_in_progress = True
  986. # Get all of the users that need resyncing.
  987. need_resync = await self.store.get_user_ids_requiring_device_list_resync()
  988. # Iterate over the set of user IDs.
  989. for user_id in need_resync:
  990. try:
  991. # Try to resync the current user's devices list.
  992. result = await self.user_device_resync(
  993. user_id=user_id,
  994. mark_failed_as_stale=False,
  995. )
  996. # user_device_resync only returns a result if it managed to
  997. # successfully resync and update the database. Updating the table
  998. # of users requiring resync isn't necessary here as
  999. # user_device_resync already does it (through
  1000. # self.store.update_remote_device_list_cache).
  1001. if result:
  1002. logger.debug(
  1003. "Successfully resynced the device list for %s",
  1004. user_id,
  1005. )
  1006. except Exception as e:
  1007. # If there was an issue resyncing this user, e.g. if the remote
  1008. # server sent a malformed result, just log the error instead of
  1009. # aborting all the subsequent resyncs.
  1010. logger.debug(
  1011. "Could not resync the device list for %s: %s",
  1012. user_id,
  1013. e,
  1014. )
  1015. finally:
  1016. # Allow future calls to retry resyncinc out of sync device lists.
  1017. self._resync_retry_in_progress = False
  1018. async def multi_user_device_resync(
  1019. self, user_ids: List[str], mark_failed_as_stale: bool = True
  1020. ) -> Dict[str, Optional[JsonDict]]:
  1021. """
  1022. Like `user_device_resync` but operates on multiple users **from the same origin**
  1023. at once.
  1024. Returns:
  1025. Dict from User ID to the same Dict as `user_device_resync`.
  1026. """
  1027. if not user_ids:
  1028. return {}
  1029. origins = {UserID.from_string(user_id).domain for user_id in user_ids}
  1030. if len(origins) != 1:
  1031. raise InvalidAPICallError(f"Only one origin permitted, got {origins!r}")
  1032. result = {}
  1033. failed = set()
  1034. # TODO(Perf): Actually batch these up
  1035. for user_id in user_ids:
  1036. user_result, user_failed = await self._user_device_resync_returning_failed(
  1037. user_id
  1038. )
  1039. result[user_id] = user_result
  1040. if user_failed:
  1041. failed.add(user_id)
  1042. if mark_failed_as_stale:
  1043. await self.store.mark_remote_users_device_caches_as_stale(failed)
  1044. return result
  1045. async def user_device_resync(
  1046. self, user_id: str, mark_failed_as_stale: bool = True
  1047. ) -> Optional[JsonDict]:
  1048. result, failed = await self._user_device_resync_returning_failed(user_id)
  1049. if failed and mark_failed_as_stale:
  1050. # Mark the remote user's device list as stale so we know we need to retry
  1051. # it later.
  1052. await self.store.mark_remote_users_device_caches_as_stale((user_id,))
  1053. return result
  1054. async def _user_device_resync_returning_failed(
  1055. self, user_id: str
  1056. ) -> Tuple[Optional[JsonDict], bool]:
  1057. """Fetches all devices for a user and updates the device cache with them.
  1058. Args:
  1059. user_id: The user's id whose device_list will be updated.
  1060. Returns:
  1061. - A dict with device info as under the "devices" in the result of this
  1062. request:
  1063. https://matrix.org/docs/spec/server_server/r0.1.2#get-matrix-federation-v1-user-devices-userid
  1064. None when we weren't able to fetch the device info for some reason,
  1065. e.g. due to a connection problem.
  1066. - True iff the resync failed and the device list should be marked as stale.
  1067. """
  1068. logger.debug("Attempting to resync the device list for %s", user_id)
  1069. log_kv({"message": "Doing resync to update device list."})
  1070. # Fetch all devices for the user.
  1071. origin = get_domain_from_id(user_id)
  1072. try:
  1073. result = await self.federation.query_user_devices(origin, user_id)
  1074. except NotRetryingDestination:
  1075. return None, True
  1076. except (RequestSendFailed, HttpResponseException) as e:
  1077. logger.warning(
  1078. "Failed to handle device list update for %s: %s",
  1079. user_id,
  1080. e,
  1081. )
  1082. # We abort on exceptions rather than accepting the update
  1083. # as otherwise synapse will 'forget' that its device list
  1084. # is out of date. If we bail then we will retry the resync
  1085. # next time we get a device list update for this user_id.
  1086. # This makes it more likely that the device lists will
  1087. # eventually become consistent.
  1088. return None, True
  1089. except FederationDeniedError as e:
  1090. set_tag("error", True)
  1091. log_kv({"reason": "FederationDeniedError"})
  1092. logger.info(e)
  1093. return None, False
  1094. except Exception as e:
  1095. set_tag("error", True)
  1096. log_kv(
  1097. {"message": "Exception raised by federation request", "exception": e}
  1098. )
  1099. logger.exception("Failed to handle device list update for %s", user_id)
  1100. return None, True
  1101. log_kv({"result": result})
  1102. stream_id = result["stream_id"]
  1103. devices = result["devices"]
  1104. # Get the master key and the self-signing key for this user if provided in the
  1105. # response (None if not in the response).
  1106. # The response will not contain the user signing key, as this key is only used by
  1107. # its owner, thus it doesn't make sense to send it over federation.
  1108. master_key = result.get("master_key")
  1109. self_signing_key = result.get("self_signing_key")
  1110. ignore_devices = False
  1111. # If the remote server has more than ~1000 devices for this user
  1112. # we assume that something is going horribly wrong (e.g. a bot
  1113. # that logs in and creates a new device every time it tries to
  1114. # send a message). Maintaining lots of devices per user in the
  1115. # cache can cause serious performance issues as if this request
  1116. # takes more than 60s to complete, internal replication from the
  1117. # inbound federation worker to the synapse master may time out
  1118. # causing the inbound federation to fail and causing the remote
  1119. # server to retry, causing a DoS. So in this scenario we give
  1120. # up on storing the total list of devices and only handle the
  1121. # delta instead.
  1122. if len(devices) > 1000:
  1123. logger.warning(
  1124. "Ignoring device list snapshot for %s as it has >1K devs (%d)",
  1125. user_id,
  1126. len(devices),
  1127. )
  1128. devices = []
  1129. ignore_devices = True
  1130. else:
  1131. prev_stream_id = await self.store.get_device_list_last_stream_id_for_remote(
  1132. user_id
  1133. )
  1134. cached_devices = await self.store.get_cached_devices_for_user(user_id)
  1135. # To ensure that a user with no devices is cached, we skip the resync only
  1136. # if we have a stream_id from previously writing a cache entry.
  1137. if prev_stream_id is not None and cached_devices == {
  1138. d["device_id"]: d for d in devices
  1139. }:
  1140. logging.info(
  1141. "Skipping device list resync for %s, as our cache matches already",
  1142. user_id,
  1143. )
  1144. devices = []
  1145. ignore_devices = True
  1146. for device in devices:
  1147. logger.debug(
  1148. "Handling resync update %r/%r, ID: %r",
  1149. user_id,
  1150. device["device_id"],
  1151. stream_id,
  1152. )
  1153. if not ignore_devices:
  1154. await self.store.update_remote_device_list_cache(
  1155. user_id, devices, stream_id
  1156. )
  1157. # mark the cache as valid, whether or not we actually processed any device
  1158. # list updates.
  1159. await self.store.mark_remote_user_device_cache_as_valid(user_id)
  1160. device_ids = [device["device_id"] for device in devices]
  1161. # Handle cross-signing keys.
  1162. cross_signing_device_ids = await self.process_cross_signing_key_update(
  1163. user_id,
  1164. master_key,
  1165. self_signing_key,
  1166. )
  1167. device_ids = device_ids + cross_signing_device_ids
  1168. if device_ids:
  1169. await self.device_handler.notify_device_update(user_id, device_ids)
  1170. # We clobber the seen updates since we've re-synced from a given
  1171. # point.
  1172. self._seen_updates[user_id] = {stream_id}
  1173. return result, False
  1174. async def process_cross_signing_key_update(
  1175. self,
  1176. user_id: str,
  1177. master_key: Optional[JsonDict],
  1178. self_signing_key: Optional[JsonDict],
  1179. ) -> List[str]:
  1180. """Process the given new master and self-signing key for the given remote user.
  1181. Args:
  1182. user_id: The ID of the user these keys are for.
  1183. master_key: The dict of the cross-signing master key as returned by the
  1184. remote server.
  1185. self_signing_key: The dict of the cross-signing self-signing key as returned
  1186. by the remote server.
  1187. Return:
  1188. The device IDs for the given keys.
  1189. """
  1190. device_ids = []
  1191. current_keys_map = await self.store.get_e2e_cross_signing_keys_bulk([user_id])
  1192. current_keys = current_keys_map.get(user_id) or {}
  1193. if master_key and master_key != current_keys.get("master"):
  1194. await self.store.set_e2e_cross_signing_key(user_id, "master", master_key)
  1195. _, verify_key = get_verify_key_from_cross_signing_key(master_key)
  1196. # verify_key is a VerifyKey from signedjson, which uses
  1197. # .version to denote the portion of the key ID after the
  1198. # algorithm and colon, which is the device ID
  1199. device_ids.append(verify_key.version)
  1200. if self_signing_key and self_signing_key != current_keys.get("self_signing"):
  1201. await self.store.set_e2e_cross_signing_key(
  1202. user_id, "self_signing", self_signing_key
  1203. )
  1204. _, verify_key = get_verify_key_from_cross_signing_key(self_signing_key)
  1205. device_ids.append(verify_key.version)
  1206. return device_ids
  1207. async def handle_room_un_partial_stated(self, room_id: str) -> None:
  1208. """Handles sending appropriate device list updates in a room that has
  1209. gone from partial to full state.
  1210. """
  1211. pending_updates = (
  1212. await self.store.get_pending_remote_device_list_updates_for_room(room_id)
  1213. )
  1214. for user_id, device_id in pending_updates:
  1215. logger.info(
  1216. "Got pending device list update in room %s: %s / %s",
  1217. room_id,
  1218. user_id,
  1219. device_id,
  1220. )
  1221. position = await self.store.add_device_change_to_streams(
  1222. user_id,
  1223. [device_id],
  1224. room_ids=[room_id],
  1225. )
  1226. if not position:
  1227. # This should only happen if there are no updates, which
  1228. # shouldn't happen when we've passed in a non-empty set of
  1229. # device IDs.
  1230. continue
  1231. self.device_handler.notifier.on_new_event(
  1232. StreamKeyType.DEVICE_LIST, position, rooms=[room_id]
  1233. )