admin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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, Optional, Set
  17. from synapse.api.constants import 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.storage = hs.get_storage()
  28. self.state_store = self.storage.state
  29. async def get_whois(self, user: UserID) -> JsonDict:
  30. connections = []
  31. sessions = await self.store.get_user_ip_and_agents(user)
  32. for session in sessions:
  33. connections.append(
  34. {
  35. "ip": session["ip"],
  36. "last_seen": session["last_seen"],
  37. "user_agent": session["user_agent"],
  38. }
  39. )
  40. ret = {
  41. "user_id": user.to_string(),
  42. "devices": {"": {"sessions": [{"connections": connections}]}},
  43. }
  44. return ret
  45. async def get_user(self, user: UserID) -> Optional[JsonDict]:
  46. """Function to get user details"""
  47. user_info_dict = await self.store.get_user_by_id(user.to_string())
  48. if user_info_dict is None:
  49. return None
  50. # Restrict returned information to a known set of fields. This prevents additional
  51. # fields added to get_user_by_id from modifying Synapse's external API surface.
  52. user_info_to_return = {
  53. "name",
  54. "admin",
  55. "deactivated",
  56. "shadow_banned",
  57. "creation_ts",
  58. "appservice_id",
  59. "consent_server_notice_sent",
  60. "consent_version",
  61. "user_type",
  62. "is_guest",
  63. }
  64. # Restrict returned keys to a known set.
  65. user_info_dict = {
  66. key: value
  67. for key, value in user_info_dict.items()
  68. if key in user_info_to_return
  69. }
  70. # Add additional user metadata
  71. profile = await self.store.get_profileinfo(user.localpart)
  72. threepids = await self.store.user_get_threepids(user.to_string())
  73. external_ids = [
  74. ({"auth_provider": auth_provider, "external_id": external_id})
  75. for auth_provider, external_id in await self.store.get_external_ids_by_user(
  76. user.to_string()
  77. )
  78. ]
  79. user_info_dict["displayname"] = profile.display_name
  80. user_info_dict["avatar_url"] = profile.avatar_url
  81. user_info_dict["threepids"] = threepids
  82. user_info_dict["external_ids"] = external_ids
  83. return user_info_dict
  84. async def export_user_data(self, user_id: str, writer: "ExfiltrationWriter") -> Any:
  85. """Write all data we have on the user to the given writer.
  86. Args:
  87. user_id: The user ID to fetch data of.
  88. writer: The writer to write to.
  89. Returns:
  90. Resolves when all data for a user has been written.
  91. The returned value is that returned by `writer.finished()`.
  92. """
  93. # Get all rooms the user is in or has been in
  94. rooms = await self.store.get_rooms_for_local_user_where_membership_is(
  95. user_id,
  96. membership_list=(
  97. Membership.JOIN,
  98. Membership.LEAVE,
  99. Membership.BAN,
  100. Membership.INVITE,
  101. Membership.KNOCK,
  102. ),
  103. )
  104. # We only try and fetch events for rooms the user has been in. If
  105. # they've been e.g. invited to a room without joining then we handle
  106. # those separately.
  107. rooms_user_has_been_in = await self.store.get_rooms_user_has_been_in(user_id)
  108. for index, room in enumerate(rooms):
  109. room_id = room.room_id
  110. logger.info(
  111. "[%s] Handling room %s, %d/%d", user_id, room_id, index + 1, len(rooms)
  112. )
  113. forgotten = await self.store.did_forget(user_id, room_id)
  114. if forgotten:
  115. logger.info("[%s] User forgot room %d, ignoring", user_id, room_id)
  116. continue
  117. if room_id not in rooms_user_has_been_in:
  118. # If we haven't been in the rooms then the filtering code below
  119. # won't return anything, so we need to handle these cases
  120. # explicitly.
  121. if room.membership == Membership.INVITE:
  122. event_id = room.event_id
  123. invite = await self.store.get_event(event_id, allow_none=True)
  124. if invite:
  125. invited_state = invite.unsigned["invite_room_state"]
  126. writer.write_invite(room_id, invite, invited_state)
  127. if room.membership == Membership.KNOCK:
  128. event_id = room.event_id
  129. knock = await self.store.get_event(event_id, allow_none=True)
  130. if knock:
  131. knock_state = knock.unsigned["knock_room_state"]
  132. writer.write_knock(room_id, knock, knock_state)
  133. continue
  134. # We only want to bother fetching events up to the last time they
  135. # were joined. We estimate that point by looking at the
  136. # stream_ordering of the last membership if it wasn't a join.
  137. if room.membership == Membership.JOIN:
  138. stream_ordering = self.store.get_room_max_stream_ordering()
  139. else:
  140. stream_ordering = room.stream_ordering
  141. from_key = RoomStreamToken(0, 0)
  142. to_key = RoomStreamToken(None, stream_ordering)
  143. # Events that we've processed in this room
  144. written_events: Set[str] = set()
  145. # We need to track gaps in the events stream so that we can then
  146. # write out the state at those events. We do this by keeping track
  147. # of events whose prev events we haven't seen.
  148. # Map from event ID to prev events that haven't been processed,
  149. # dict[str, set[str]].
  150. event_to_unseen_prevs = {}
  151. # The reverse mapping to above, i.e. map from unseen event to events
  152. # that have the unseen event in their prev_events, i.e. the unseen
  153. # events "children".
  154. unseen_to_child_events: Dict[str, Set[str]] = {}
  155. # We fetch events in the room the user could see by fetching *all*
  156. # events that we have and then filtering, this isn't the most
  157. # efficient method perhaps but it does guarantee we get everything.
  158. while True:
  159. events, _ = await self.store.paginate_room_events(
  160. room_id, from_key, to_key, limit=100, direction="f"
  161. )
  162. if not events:
  163. break
  164. from_key = events[-1].internal_metadata.after
  165. events = await filter_events_for_client(self.storage, user_id, events)
  166. writer.write_events(room_id, events)
  167. # Update the extremity tracking dicts
  168. for event in events:
  169. # Check if we have any prev events that haven't been
  170. # processed yet, and add those to the appropriate dicts.
  171. unseen_events = set(event.prev_event_ids()) - written_events
  172. if unseen_events:
  173. event_to_unseen_prevs[event.event_id] = unseen_events
  174. for unseen in unseen_events:
  175. unseen_to_child_events.setdefault(unseen, set()).add(
  176. event.event_id
  177. )
  178. # Now check if this event is an unseen prev event, if so
  179. # then we remove this event from the appropriate dicts.
  180. for child_id in unseen_to_child_events.pop(event.event_id, []):
  181. event_to_unseen_prevs[child_id].discard(event.event_id)
  182. written_events.add(event.event_id)
  183. logger.info(
  184. "Written %d events in room %s", len(written_events), room_id
  185. )
  186. # Extremities are the events who have at least one unseen prev event.
  187. extremities = (
  188. event_id
  189. for event_id, unseen_prevs in event_to_unseen_prevs.items()
  190. if unseen_prevs
  191. )
  192. for event_id in extremities:
  193. if not event_to_unseen_prevs[event_id]:
  194. continue
  195. state = await self.state_store.get_state_for_event(event_id)
  196. writer.write_state(room_id, event_id, state)
  197. return writer.finished()
  198. class ExfiltrationWriter(metaclass=abc.ABCMeta):
  199. """Interface used to specify how to write exported data."""
  200. @abc.abstractmethod
  201. def write_events(self, room_id: str, events: List[EventBase]) -> None:
  202. """Write a batch of events for a room."""
  203. raise NotImplementedError()
  204. @abc.abstractmethod
  205. def write_state(
  206. self, room_id: str, event_id: str, state: StateMap[EventBase]
  207. ) -> None:
  208. """Write the state at the given event in the room.
  209. This only gets called for backward extremities rather than for each
  210. event.
  211. """
  212. raise NotImplementedError()
  213. @abc.abstractmethod
  214. def write_invite(
  215. self, room_id: str, event: EventBase, state: StateMap[EventBase]
  216. ) -> None:
  217. """Write an invite for the room, with associated invite state.
  218. Args:
  219. room_id: The room ID the invite is for.
  220. event: The invite event.
  221. state: A subset of the state at the invite, with a subset of the
  222. event keys (type, state_key content and sender).
  223. """
  224. raise NotImplementedError()
  225. @abc.abstractmethod
  226. def write_knock(
  227. self, room_id: str, event: EventBase, state: StateMap[EventBase]
  228. ) -> None:
  229. """Write a knock for the room, with associated knock state.
  230. Args:
  231. room_id: The room ID the knock is for.
  232. event: The knock event.
  233. state: A subset of the state at the knock, with a subset of the
  234. event keys (type, state_key content and sender).
  235. """
  236. raise NotImplementedError()
  237. @abc.abstractmethod
  238. def finished(self) -> Any:
  239. """Called when all data has successfully been exported and written.
  240. This functions return value is passed to the caller of
  241. `export_user_data`.
  242. """
  243. raise NotImplementedError()