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.
 
 
 
 
 
 

408 lines
15 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import abc
  15. import logging
  16. from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Set
  17. from synapse.api.constants import Direction, Membership
  18. from synapse.events import EventBase
  19. from synapse.types import JsonDict, RoomStreamToken, StateMap, UserID
  20. from synapse.visibility import filter_events_for_client
  21. if TYPE_CHECKING:
  22. from synapse.server import HomeServer
  23. logger = logging.getLogger(__name__)
  24. class AdminHandler:
  25. def __init__(self, hs: "HomeServer"):
  26. self._store = hs.get_datastores().main
  27. self._device_handler = hs.get_device_handler()
  28. self._storage_controllers = hs.get_storage_controllers()
  29. self._state_storage_controller = self._storage_controllers.state
  30. self._msc3866_enabled = hs.config.experimental.msc3866.enabled
  31. async def get_whois(self, user: UserID) -> JsonDict:
  32. connections = []
  33. sessions = await self._store.get_user_ip_and_agents(user)
  34. for session in sessions:
  35. connections.append(
  36. {
  37. "ip": session["ip"],
  38. "last_seen": session["last_seen"],
  39. "user_agent": session["user_agent"],
  40. }
  41. )
  42. ret = {
  43. "user_id": user.to_string(),
  44. "devices": {"": {"sessions": [{"connections": connections}]}},
  45. }
  46. return ret
  47. async def get_user(self, user: UserID) -> Optional[JsonDict]:
  48. """Function to get user details"""
  49. user_info_dict = await self._store.get_user_by_id(user.to_string())
  50. if user_info_dict is None:
  51. return None
  52. # Restrict returned information to a known set of fields. This prevents additional
  53. # fields added to get_user_by_id from modifying Synapse's external API surface.
  54. user_info_to_return = {
  55. "name",
  56. "admin",
  57. "deactivated",
  58. "shadow_banned",
  59. "creation_ts",
  60. "appservice_id",
  61. "consent_server_notice_sent",
  62. "consent_version",
  63. "consent_ts",
  64. "user_type",
  65. "is_guest",
  66. }
  67. if self._msc3866_enabled:
  68. # Only include the approved flag if support for MSC3866 is enabled.
  69. user_info_to_return.add("approved")
  70. # Restrict returned keys to a known set.
  71. user_info_dict = {
  72. key: value
  73. for key, value in user_info_dict.items()
  74. if key in user_info_to_return
  75. }
  76. # Add additional user metadata
  77. profile = await self._store.get_profileinfo(user)
  78. threepids = await self._store.user_get_threepids(user.to_string())
  79. external_ids = [
  80. ({"auth_provider": auth_provider, "external_id": external_id})
  81. for auth_provider, external_id in await self._store.get_external_ids_by_user(
  82. user.to_string()
  83. )
  84. ]
  85. user_info_dict["displayname"] = profile.display_name
  86. user_info_dict["avatar_url"] = profile.avatar_url
  87. user_info_dict["threepids"] = threepids
  88. user_info_dict["external_ids"] = external_ids
  89. user_info_dict["erased"] = await self._store.is_user_erased(user.to_string())
  90. return user_info_dict
  91. async def export_user_data(self, user_id: str, writer: "ExfiltrationWriter") -> Any:
  92. """Write all data we have on the user to the given writer.
  93. Args:
  94. user_id: The user ID to fetch data of.
  95. writer: The writer to write to.
  96. Returns:
  97. Resolves when all data for a user has been written.
  98. The returned value is that returned by `writer.finished()`.
  99. """
  100. # Get all rooms the user is in or has been in
  101. rooms = await self._store.get_rooms_for_local_user_where_membership_is(
  102. user_id,
  103. membership_list=(
  104. Membership.JOIN,
  105. Membership.LEAVE,
  106. Membership.BAN,
  107. Membership.INVITE,
  108. Membership.KNOCK,
  109. ),
  110. )
  111. # We only try and fetch events for rooms the user has been in. If
  112. # they've been e.g. invited to a room without joining then we handle
  113. # those separately.
  114. rooms_user_has_been_in = await self._store.get_rooms_user_has_been_in(user_id)
  115. for index, room in enumerate(rooms):
  116. room_id = room.room_id
  117. logger.info(
  118. "[%s] Handling room %s, %d/%d", user_id, room_id, index + 1, len(rooms)
  119. )
  120. forgotten = await self._store.did_forget(user_id, room_id)
  121. if forgotten:
  122. logger.info("[%s] User forgot room %d, ignoring", user_id, room_id)
  123. continue
  124. if room_id not in rooms_user_has_been_in:
  125. # If we haven't been in the rooms then the filtering code below
  126. # won't return anything, so we need to handle these cases
  127. # explicitly.
  128. if room.membership == Membership.INVITE:
  129. event_id = room.event_id
  130. invite = await self._store.get_event(event_id, allow_none=True)
  131. if invite:
  132. invited_state = invite.unsigned["invite_room_state"]
  133. writer.write_invite(room_id, invite, invited_state)
  134. if room.membership == Membership.KNOCK:
  135. event_id = room.event_id
  136. knock = await self._store.get_event(event_id, allow_none=True)
  137. if knock:
  138. knock_state = knock.unsigned["knock_room_state"]
  139. writer.write_knock(room_id, knock, knock_state)
  140. continue
  141. # We only want to bother fetching events up to the last time they
  142. # were joined. We estimate that point by looking at the
  143. # stream_ordering of the last membership if it wasn't a join.
  144. if room.membership == Membership.JOIN:
  145. stream_ordering = self._store.get_room_max_stream_ordering()
  146. else:
  147. stream_ordering = room.stream_ordering
  148. from_key = RoomStreamToken(0, 0)
  149. to_key = RoomStreamToken(None, stream_ordering)
  150. # Events that we've processed in this room
  151. written_events: Set[str] = set()
  152. # We need to track gaps in the events stream so that we can then
  153. # write out the state at those events. We do this by keeping track
  154. # of events whose prev events we haven't seen.
  155. # Map from event ID to prev events that haven't been processed,
  156. # dict[str, set[str]].
  157. event_to_unseen_prevs = {}
  158. # The reverse mapping to above, i.e. map from unseen event to events
  159. # that have the unseen event in their prev_events, i.e. the unseen
  160. # events "children".
  161. unseen_to_child_events: Dict[str, Set[str]] = {}
  162. # We fetch events in the room the user could see by fetching *all*
  163. # events that we have and then filtering, this isn't the most
  164. # efficient method perhaps but it does guarantee we get everything.
  165. while True:
  166. events, _ = await self._store.paginate_room_events(
  167. room_id, from_key, to_key, limit=100, direction=Direction.FORWARDS
  168. )
  169. if not events:
  170. break
  171. from_key = events[-1].internal_metadata.after
  172. events = await filter_events_for_client(
  173. self._storage_controllers, user_id, events
  174. )
  175. writer.write_events(room_id, events)
  176. # Update the extremity tracking dicts
  177. for event in events:
  178. # Check if we have any prev events that haven't been
  179. # processed yet, and add those to the appropriate dicts.
  180. unseen_events = set(event.prev_event_ids()) - written_events
  181. if unseen_events:
  182. event_to_unseen_prevs[event.event_id] = unseen_events
  183. for unseen in unseen_events:
  184. unseen_to_child_events.setdefault(unseen, set()).add(
  185. event.event_id
  186. )
  187. # Now check if this event is an unseen prev event, if so
  188. # then we remove this event from the appropriate dicts.
  189. for child_id in unseen_to_child_events.pop(event.event_id, []):
  190. event_to_unseen_prevs[child_id].discard(event.event_id)
  191. written_events.add(event.event_id)
  192. logger.info(
  193. "Written %d events in room %s", len(written_events), room_id
  194. )
  195. # Extremities are the events who have at least one unseen prev event.
  196. extremities = (
  197. event_id
  198. for event_id, unseen_prevs in event_to_unseen_prevs.items()
  199. if unseen_prevs
  200. )
  201. for event_id in extremities:
  202. if not event_to_unseen_prevs[event_id]:
  203. continue
  204. state = await self._state_storage_controller.get_state_for_event(
  205. event_id
  206. )
  207. writer.write_state(room_id, event_id, state)
  208. # Get the user profile
  209. profile = await self.get_user(UserID.from_string(user_id))
  210. if profile is not None:
  211. writer.write_profile(profile)
  212. logger.info("[%s] Written profile", user_id)
  213. # Get all devices the user has
  214. devices = await self._device_handler.get_devices_by_user(user_id)
  215. writer.write_devices(devices)
  216. logger.info("[%s] Written %s devices", user_id, len(devices))
  217. # Get all connections the user has
  218. connections = await self.get_whois(UserID.from_string(user_id))
  219. writer.write_connections(
  220. connections["devices"][""]["sessions"][0]["connections"]
  221. )
  222. logger.info("[%s] Written %s connections", user_id, len(connections))
  223. # Get all account data the user has global and in rooms
  224. global_data = await self._store.get_global_account_data_for_user(user_id)
  225. by_room_data = await self._store.get_room_account_data_for_user(user_id)
  226. writer.write_account_data("global", global_data)
  227. for room_id in by_room_data:
  228. writer.write_account_data(room_id, by_room_data[room_id])
  229. logger.info(
  230. "[%s] Written account data for %s rooms", user_id, len(by_room_data)
  231. )
  232. # Get all media ids the user has
  233. limit = 100
  234. start = 0
  235. while True:
  236. media_ids, total = await self._store.get_local_media_by_user_paginate(
  237. start, limit, user_id
  238. )
  239. for media in media_ids:
  240. writer.write_media_id(media["media_id"], media)
  241. logger.info(
  242. "[%s] Written %d media_ids of %s",
  243. user_id,
  244. (start + len(media_ids)),
  245. total,
  246. )
  247. if (start + limit) >= total:
  248. break
  249. start += limit
  250. return writer.finished()
  251. class ExfiltrationWriter(metaclass=abc.ABCMeta):
  252. """Interface used to specify how to write exported data."""
  253. @abc.abstractmethod
  254. def write_events(self, room_id: str, events: List[EventBase]) -> None:
  255. """Write a batch of events for a room."""
  256. raise NotImplementedError()
  257. @abc.abstractmethod
  258. def write_state(
  259. self, room_id: str, event_id: str, state: StateMap[EventBase]
  260. ) -> None:
  261. """Write the state at the given event in the room.
  262. This only gets called for backward extremities rather than for each
  263. event.
  264. """
  265. raise NotImplementedError()
  266. @abc.abstractmethod
  267. def write_invite(
  268. self, room_id: str, event: EventBase, state: StateMap[EventBase]
  269. ) -> None:
  270. """Write an invite for the room, with associated invite state.
  271. Args:
  272. room_id: The room ID the invite is for.
  273. event: The invite event.
  274. state: A subset of the state at the invite, with a subset of the
  275. event keys (type, state_key content and sender).
  276. """
  277. raise NotImplementedError()
  278. @abc.abstractmethod
  279. def write_knock(
  280. self, room_id: str, event: EventBase, state: StateMap[EventBase]
  281. ) -> None:
  282. """Write a knock for the room, with associated knock state.
  283. Args:
  284. room_id: The room ID the knock is for.
  285. event: The knock event.
  286. state: A subset of the state at the knock, with a subset of the
  287. event keys (type, state_key content and sender).
  288. """
  289. raise NotImplementedError()
  290. @abc.abstractmethod
  291. def write_profile(self, profile: JsonDict) -> None:
  292. """Write the profile of a user.
  293. Args:
  294. profile: The user profile.
  295. """
  296. raise NotImplementedError()
  297. @abc.abstractmethod
  298. def write_devices(self, devices: List[JsonDict]) -> None:
  299. """Write the devices of a user.
  300. Args:
  301. devices: The list of devices.
  302. """
  303. raise NotImplementedError()
  304. @abc.abstractmethod
  305. def write_connections(self, connections: List[JsonDict]) -> None:
  306. """Write the connections of a user.
  307. Args:
  308. connections: The list of connections / sessions.
  309. """
  310. raise NotImplementedError()
  311. @abc.abstractmethod
  312. def write_account_data(
  313. self, file_name: str, account_data: Mapping[str, JsonDict]
  314. ) -> None:
  315. """Write the account data of a user.
  316. Args:
  317. file_name: file name to write data
  318. account_data: mapping of global or room account_data
  319. """
  320. raise NotImplementedError()
  321. @abc.abstractmethod
  322. def write_media_id(self, media_id: str, media_metadata: JsonDict) -> None:
  323. """Write the media's metadata of a user.
  324. Exports only the metadata, as this can be fetched from the database via
  325. read only. In order to access the files, a connection to the correct
  326. media repository would be required.
  327. Args:
  328. media_id: ID of the media.
  329. media_metadata: Metadata of one media file.
  330. """
  331. @abc.abstractmethod
  332. def finished(self) -> Any:
  333. """Called when all data has successfully been exported and written.
  334. This functions return value is passed to the caller of
  335. `export_user_data`.
  336. """
  337. raise NotImplementedError()