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.
 
 
 
 
 
 

400 lines
15 KiB

  1. # Copyright 2023 The Matrix.org Foundation.
  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 logging
  15. from typing import TYPE_CHECKING, Optional, Tuple
  16. from netaddr import IPAddress
  17. from twisted.web.server import Request
  18. from synapse import event_auth
  19. from synapse.api.constants import EventTypes, HistoryVisibility, Membership
  20. from synapse.api.errors import (
  21. AuthError,
  22. Codes,
  23. MissingClientTokenError,
  24. UnstableSpecAuthError,
  25. )
  26. from synapse.appservice import ApplicationService
  27. from synapse.http import get_request_user_agent
  28. from synapse.http.site import SynapseRequest
  29. from synapse.logging.opentracing import trace
  30. from synapse.types import Requester, create_requester
  31. from synapse.util.cancellation import cancellable
  32. if TYPE_CHECKING:
  33. from synapse.server import HomeServer
  34. logger = logging.getLogger(__name__)
  35. class BaseAuth:
  36. """Common base class for all auth implementations."""
  37. def __init__(self, hs: "HomeServer"):
  38. self.hs = hs
  39. self.store = hs.get_datastores().main
  40. self._storage_controllers = hs.get_storage_controllers()
  41. self._track_appservice_user_ips = hs.config.appservice.track_appservice_user_ips
  42. self._track_puppeted_user_ips = hs.config.api.track_puppeted_user_ips
  43. async def check_user_in_room(
  44. self,
  45. room_id: str,
  46. requester: Requester,
  47. allow_departed_users: bool = False,
  48. ) -> Tuple[str, Optional[str]]:
  49. """Check if the user is in the room, or was at some point.
  50. Args:
  51. room_id: The room to check.
  52. requester: The user making the request, according to the access token.
  53. current_state: Optional map of the current state of the room.
  54. If provided then that map is used to check whether they are a
  55. member of the room. Otherwise the current membership is
  56. loaded from the database.
  57. allow_departed_users: if True, accept users that were previously
  58. members but have now departed.
  59. Raises:
  60. AuthError if the user is/was not in the room.
  61. Returns:
  62. The current membership of the user in the room and the
  63. membership event ID of the user.
  64. """
  65. user_id = requester.user.to_string()
  66. (
  67. membership,
  68. member_event_id,
  69. ) = await self.store.get_local_current_membership_for_user_in_room(
  70. user_id=user_id,
  71. room_id=room_id,
  72. )
  73. if membership:
  74. if membership == Membership.JOIN:
  75. return membership, member_event_id
  76. # XXX this looks totally bogus. Why do we not allow users who have been banned,
  77. # or those who were members previously and have been re-invited?
  78. if allow_departed_users and membership == Membership.LEAVE:
  79. forgot = await self.store.did_forget(user_id, room_id)
  80. if not forgot:
  81. return membership, member_event_id
  82. raise UnstableSpecAuthError(
  83. 403,
  84. "User %s not in room %s" % (user_id, room_id),
  85. errcode=Codes.NOT_JOINED,
  86. )
  87. @trace
  88. async def check_user_in_room_or_world_readable(
  89. self, room_id: str, requester: Requester, allow_departed_users: bool = False
  90. ) -> Tuple[str, Optional[str]]:
  91. """Checks that the user is or was in the room or the room is world
  92. readable. If it isn't then an exception is raised.
  93. Args:
  94. room_id: room to check
  95. user_id: user to check
  96. allow_departed_users: if True, accept users that were previously
  97. members but have now departed
  98. Returns:
  99. Resolves to the current membership of the user in the room and the
  100. membership event ID of the user. If the user is not in the room and
  101. never has been, then `(Membership.JOIN, None)` is returned.
  102. """
  103. try:
  104. # check_user_in_room will return the most recent membership
  105. # event for the user if:
  106. # * The user is a non-guest user, and was ever in the room
  107. # * The user is a guest user, and has joined the room
  108. # else it will throw.
  109. return await self.check_user_in_room(
  110. room_id, requester, allow_departed_users=allow_departed_users
  111. )
  112. except AuthError:
  113. visibility = await self._storage_controllers.state.get_current_state_event(
  114. room_id, EventTypes.RoomHistoryVisibility, ""
  115. )
  116. if (
  117. visibility
  118. and visibility.content.get("history_visibility")
  119. == HistoryVisibility.WORLD_READABLE
  120. ):
  121. return Membership.JOIN, None
  122. raise AuthError(
  123. 403,
  124. "User %r not in room %s, and room previews are disabled"
  125. % (requester.user, room_id),
  126. )
  127. async def validate_appservice_can_control_user_id(
  128. self, app_service: ApplicationService, user_id: str
  129. ) -> None:
  130. """Validates that the app service is allowed to control
  131. the given user.
  132. Args:
  133. app_service: The app service that controls the user
  134. user_id: The author MXID that the app service is controlling
  135. Raises:
  136. AuthError: If the application service is not allowed to control the user
  137. (user namespace regex does not match, wrong homeserver, etc)
  138. or if the user has not been registered yet.
  139. """
  140. # It's ok if the app service is trying to use the sender from their registration
  141. if app_service.sender == user_id:
  142. pass
  143. # Check to make sure the app service is allowed to control the user
  144. elif not app_service.is_interested_in_user(user_id):
  145. raise AuthError(
  146. 403,
  147. "Application service cannot masquerade as this user (%s)." % user_id,
  148. )
  149. # Check to make sure the user is already registered on the homeserver
  150. elif not (await self.store.get_user_by_id(user_id)):
  151. raise AuthError(
  152. 403, "Application service has not registered this user (%s)" % user_id
  153. )
  154. async def is_server_admin(self, requester: Requester) -> bool:
  155. """Check if the given user is a local server admin.
  156. Args:
  157. requester: user to check
  158. Returns:
  159. True if the user is an admin
  160. """
  161. raise NotImplementedError()
  162. async def check_can_change_room_list(
  163. self, room_id: str, requester: Requester
  164. ) -> bool:
  165. """Determine whether the user is allowed to edit the room's entry in the
  166. published room list.
  167. Args:
  168. room_id
  169. user
  170. """
  171. is_admin = await self.is_server_admin(requester)
  172. if is_admin:
  173. return True
  174. await self.check_user_in_room(room_id, requester)
  175. # We currently require the user is a "moderator" in the room. We do this
  176. # by checking if they would (theoretically) be able to change the
  177. # m.room.canonical_alias events
  178. power_level_event = (
  179. await self._storage_controllers.state.get_current_state_event(
  180. room_id, EventTypes.PowerLevels, ""
  181. )
  182. )
  183. auth_events = {}
  184. if power_level_event:
  185. auth_events[(EventTypes.PowerLevels, "")] = power_level_event
  186. send_level = event_auth.get_send_level(
  187. EventTypes.CanonicalAlias, "", power_level_event
  188. )
  189. user_level = event_auth.get_user_power_level(
  190. requester.user.to_string(), auth_events
  191. )
  192. return user_level >= send_level
  193. @staticmethod
  194. def has_access_token(request: Request) -> bool:
  195. """Checks if the request has an access_token.
  196. Returns:
  197. False if no access_token was given, True otherwise.
  198. """
  199. # This will always be set by the time Twisted calls us.
  200. assert request.args is not None
  201. query_params = request.args.get(b"access_token")
  202. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  203. return bool(query_params) or bool(auth_headers)
  204. @staticmethod
  205. def get_access_token_from_request(request: Request) -> str:
  206. """Extracts the access_token from the request.
  207. Args:
  208. request: The http request.
  209. Returns:
  210. The access_token
  211. Raises:
  212. MissingClientTokenError: If there isn't a single access_token in the
  213. request
  214. """
  215. # This will always be set by the time Twisted calls us.
  216. assert request.args is not None
  217. auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
  218. query_params = request.args.get(b"access_token")
  219. if auth_headers:
  220. # Try the get the access_token from a "Authorization: Bearer"
  221. # header
  222. if query_params is not None:
  223. raise MissingClientTokenError(
  224. "Mixing Authorization headers and access_token query parameters."
  225. )
  226. if len(auth_headers) > 1:
  227. raise MissingClientTokenError("Too many Authorization headers.")
  228. parts = auth_headers[0].split(b" ")
  229. if parts[0] == b"Bearer" and len(parts) == 2:
  230. return parts[1].decode("ascii")
  231. else:
  232. raise MissingClientTokenError("Invalid Authorization header.")
  233. else:
  234. # Try to get the access_token from the query params.
  235. if not query_params:
  236. raise MissingClientTokenError()
  237. return query_params[0].decode("ascii")
  238. @cancellable
  239. async def get_appservice_user(
  240. self, request: Request, access_token: str
  241. ) -> Optional[Requester]:
  242. """
  243. Given a request, reads the request parameters to determine:
  244. - whether it's an application service that's making this request
  245. - what user the application service should be treated as controlling
  246. (the user_id URI parameter allows an application service to masquerade
  247. any applicable user in its namespace)
  248. - what device the application service should be treated as controlling
  249. (the device_id[^1] URI parameter allows an application service to masquerade
  250. as any device that exists for the relevant user)
  251. [^1] Unstable and provided by MSC3202.
  252. Must use `org.matrix.msc3202.device_id` in place of `device_id` for now.
  253. Returns:
  254. the application service `Requester` of that request
  255. Postconditions:
  256. - The `app_service` field in the returned `Requester` is set
  257. - The `user_id` field in the returned `Requester` is either the application
  258. service sender or the controlled user set by the `user_id` URI parameter
  259. - The returned application service is permitted to control the returned user ID.
  260. - The returned device ID, if present, has been checked to be a valid device ID
  261. for the returned user ID.
  262. """
  263. DEVICE_ID_ARG_NAME = b"org.matrix.msc3202.device_id"
  264. app_service = self.store.get_app_service_by_token(access_token)
  265. if app_service is None:
  266. return None
  267. if app_service.ip_range_whitelist:
  268. ip_address = IPAddress(request.getClientAddress().host)
  269. if ip_address not in app_service.ip_range_whitelist:
  270. return None
  271. # This will always be set by the time Twisted calls us.
  272. assert request.args is not None
  273. if b"user_id" in request.args:
  274. effective_user_id = request.args[b"user_id"][0].decode("utf8")
  275. await self.validate_appservice_can_control_user_id(
  276. app_service, effective_user_id
  277. )
  278. else:
  279. effective_user_id = app_service.sender
  280. effective_device_id: Optional[str] = None
  281. if (
  282. self.hs.config.experimental.msc3202_device_masquerading_enabled
  283. and DEVICE_ID_ARG_NAME in request.args
  284. ):
  285. effective_device_id = request.args[DEVICE_ID_ARG_NAME][0].decode("utf8")
  286. # We only just set this so it can't be None!
  287. assert effective_device_id is not None
  288. device_opt = await self.store.get_device(
  289. effective_user_id, effective_device_id
  290. )
  291. if device_opt is None:
  292. # For now, use 400 M_EXCLUSIVE if the device doesn't exist.
  293. # This is an open thread of discussion on MSC3202 as of 2021-12-09.
  294. raise AuthError(
  295. 400,
  296. f"Application service trying to use a device that doesn't exist ('{effective_device_id}' for {effective_user_id})",
  297. Codes.EXCLUSIVE,
  298. )
  299. return create_requester(
  300. effective_user_id, app_service=app_service, device_id=effective_device_id
  301. )
  302. async def _record_request(
  303. self, request: SynapseRequest, requester: Requester
  304. ) -> None:
  305. """Record that this request was made.
  306. This updates the client_ips and monthly_active_user tables.
  307. """
  308. ip_addr = request.get_client_ip_if_available()
  309. if ip_addr and (not requester.app_service or self._track_appservice_user_ips):
  310. user_agent = get_request_user_agent(request)
  311. access_token = self.get_access_token_from_request(request)
  312. # XXX(quenting): I'm 95% confident that we could skip setting the
  313. # device_id to "dummy-device" for appservices, and that the only impact
  314. # would be some rows which whould not deduplicate in the 'user_ips'
  315. # table during the transition
  316. recorded_device_id = (
  317. "dummy-device"
  318. if requester.device_id is None and requester.app_service is not None
  319. else requester.device_id
  320. )
  321. await self.store.insert_client_ip(
  322. user_id=requester.authenticated_entity,
  323. access_token=access_token,
  324. ip=ip_addr,
  325. user_agent=user_agent,
  326. device_id=recorded_device_id,
  327. )
  328. # Track also the puppeted user client IP if enabled and the user is puppeting
  329. if (
  330. requester.user.to_string() != requester.authenticated_entity
  331. and self._track_puppeted_user_ips
  332. ):
  333. await self.store.insert_client_ip(
  334. user_id=requester.user.to_string(),
  335. access_token=access_token,
  336. ip=ip_addr,
  337. user_agent=user_agent,
  338. device_id=requester.device_id,
  339. )