device.py 43 KB

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