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.
 
 
 
 
 
 

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