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.
 
 
 
 
 
 

305 lines
12 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
  16. import pymacaroons
  17. from synapse.api.errors import (
  18. AuthError,
  19. Codes,
  20. InvalidClientTokenError,
  21. MissingClientTokenError,
  22. )
  23. from synapse.http import get_request_user_agent
  24. from synapse.http.site import SynapseRequest
  25. from synapse.logging.opentracing import active_span, force_tracing, start_active_span
  26. from synapse.types import Requester, create_requester
  27. from synapse.util.cancellation import cancellable
  28. from . import GUEST_DEVICE_ID
  29. from .base import BaseAuth
  30. if TYPE_CHECKING:
  31. from synapse.server import HomeServer
  32. logger = logging.getLogger(__name__)
  33. class InternalAuth(BaseAuth):
  34. """
  35. This class contains functions for authenticating users of our client-server API.
  36. """
  37. def __init__(self, hs: "HomeServer"):
  38. super().__init__(hs)
  39. self.clock = hs.get_clock()
  40. self._account_validity_handler = hs.get_account_validity_handler()
  41. self._macaroon_generator = hs.get_macaroon_generator()
  42. self._track_appservice_user_ips = hs.config.appservice.track_appservice_user_ips
  43. self._track_puppeted_user_ips = hs.config.api.track_puppeted_user_ips
  44. self._force_tracing_for_users = hs.config.tracing.force_tracing_for_users
  45. @cancellable
  46. async def get_user_by_req(
  47. self,
  48. request: SynapseRequest,
  49. allow_guest: bool = False,
  50. allow_expired: bool = False,
  51. allow_locked: bool = False,
  52. ) -> Requester:
  53. """Get a registered user's ID.
  54. Args:
  55. request: An HTTP request with an access_token query parameter.
  56. allow_guest: If False, will raise an AuthError if the user making the
  57. request is a guest.
  58. allow_expired: If True, allow the request through even if the account
  59. is expired, or session token lifetime has ended. Note that
  60. /login will deliver access tokens regardless of expiration.
  61. Returns:
  62. Resolves to the requester
  63. Raises:
  64. InvalidClientCredentialsError if no user by that token exists or the token
  65. is invalid.
  66. AuthError if access is denied for the user in the access token
  67. """
  68. parent_span = active_span()
  69. with start_active_span("get_user_by_req"):
  70. requester = await self._wrapped_get_user_by_req(
  71. request, allow_guest, allow_expired, allow_locked
  72. )
  73. if parent_span:
  74. if requester.authenticated_entity in self._force_tracing_for_users:
  75. # request tracing is enabled for this user, so we need to force it
  76. # tracing on for the parent span (which will be the servlet span).
  77. #
  78. # It's too late for the get_user_by_req span to inherit the setting,
  79. # so we also force it on for that.
  80. force_tracing()
  81. force_tracing(parent_span)
  82. parent_span.set_tag(
  83. "authenticated_entity", requester.authenticated_entity
  84. )
  85. parent_span.set_tag("user_id", requester.user.to_string())
  86. if requester.device_id is not None:
  87. parent_span.set_tag("device_id", requester.device_id)
  88. if requester.app_service is not None:
  89. parent_span.set_tag("appservice_id", requester.app_service.id)
  90. return requester
  91. @cancellable
  92. async def _wrapped_get_user_by_req(
  93. self,
  94. request: SynapseRequest,
  95. allow_guest: bool,
  96. allow_expired: bool,
  97. allow_locked: bool,
  98. ) -> Requester:
  99. """Helper for get_user_by_req
  100. Once get_user_by_req has set up the opentracing span, this does the actual work.
  101. """
  102. try:
  103. ip_addr = request.getClientAddress().host
  104. user_agent = get_request_user_agent(request)
  105. access_token = self.get_access_token_from_request(request)
  106. # First check if it could be a request from an appservice
  107. requester = await self.get_appservice_user(request, access_token)
  108. if not requester:
  109. # If not, it should be from a regular user
  110. requester = await self.get_user_by_access_token(
  111. access_token, allow_expired=allow_expired
  112. )
  113. # Deny the request if the user account is locked.
  114. if not allow_locked and await self.store.get_user_locked_status(
  115. requester.user.to_string()
  116. ):
  117. raise AuthError(
  118. 401,
  119. "User account has been locked",
  120. errcode=Codes.USER_LOCKED,
  121. additional_fields={"soft_logout": True},
  122. )
  123. # Deny the request if the user account has expired.
  124. # This check is only done for regular users, not appservice ones.
  125. if not allow_expired:
  126. if await self._account_validity_handler.is_user_expired(
  127. requester.user.to_string()
  128. ):
  129. # Raise the error if either an account validity module has determined
  130. # the account has expired, or the legacy account validity
  131. # implementation is enabled and determined the account has expired
  132. raise AuthError(
  133. 403,
  134. "User account has expired",
  135. errcode=Codes.EXPIRED_ACCOUNT,
  136. )
  137. if ip_addr and (
  138. not requester.app_service or self._track_appservice_user_ips
  139. ):
  140. # XXX(quenting): I'm 95% confident that we could skip setting the
  141. # device_id to "dummy-device" for appservices, and that the only impact
  142. # would be some rows which whould not deduplicate in the 'user_ips'
  143. # table during the transition
  144. recorded_device_id = (
  145. "dummy-device"
  146. if requester.device_id is None and requester.app_service is not None
  147. else requester.device_id
  148. )
  149. await self.store.insert_client_ip(
  150. user_id=requester.authenticated_entity,
  151. access_token=access_token,
  152. ip=ip_addr,
  153. user_agent=user_agent,
  154. device_id=recorded_device_id,
  155. )
  156. # Track also the puppeted user client IP if enabled and the user is puppeting
  157. if (
  158. requester.user.to_string() != requester.authenticated_entity
  159. and self._track_puppeted_user_ips
  160. ):
  161. await self.store.insert_client_ip(
  162. user_id=requester.user.to_string(),
  163. access_token=access_token,
  164. ip=ip_addr,
  165. user_agent=user_agent,
  166. device_id=requester.device_id,
  167. )
  168. if requester.is_guest and not allow_guest:
  169. raise AuthError(
  170. 403,
  171. "Guest access not allowed",
  172. errcode=Codes.GUEST_ACCESS_FORBIDDEN,
  173. )
  174. request.requester = requester
  175. return requester
  176. except KeyError:
  177. raise MissingClientTokenError()
  178. async def get_user_by_access_token(
  179. self,
  180. token: str,
  181. allow_expired: bool = False,
  182. ) -> Requester:
  183. """Validate access token and get user_id from it
  184. Args:
  185. token: The access token to get the user by
  186. allow_expired: If False, raises an InvalidClientTokenError
  187. if the token is expired
  188. Raises:
  189. InvalidClientTokenError if a user by that token exists, but the token is
  190. expired
  191. InvalidClientCredentialsError if no user by that token exists or the token
  192. is invalid
  193. """
  194. # First look in the database to see if the access token is present
  195. # as an opaque token.
  196. user_info = await self.store.get_user_by_access_token(token)
  197. if user_info:
  198. valid_until_ms = user_info.valid_until_ms
  199. if (
  200. not allow_expired
  201. and valid_until_ms is not None
  202. and valid_until_ms < self.clock.time_msec()
  203. ):
  204. # there was a valid access token, but it has expired.
  205. # soft-logout the user.
  206. raise InvalidClientTokenError(
  207. msg="Access token has expired", soft_logout=True
  208. )
  209. # Mark the token as used. This is used to invalidate old refresh
  210. # tokens after some time.
  211. await self.store.mark_access_token_as_used(user_info.token_id)
  212. requester = create_requester(
  213. user_id=user_info.user_id,
  214. access_token_id=user_info.token_id,
  215. is_guest=user_info.is_guest,
  216. shadow_banned=user_info.shadow_banned,
  217. device_id=user_info.device_id,
  218. authenticated_entity=user_info.token_owner,
  219. )
  220. return requester
  221. # If the token isn't found in the database, then it could still be a
  222. # macaroon for a guest, so we check that here.
  223. try:
  224. user_id = self._macaroon_generator.verify_guest_token(token)
  225. # Guest access tokens are not stored in the database (there can
  226. # only be one access token per guest, anyway).
  227. #
  228. # In order to prevent guest access tokens being used as regular
  229. # user access tokens (and hence getting around the invalidation
  230. # process), we look up the user id and check that it is indeed
  231. # a guest user.
  232. #
  233. # It would of course be much easier to store guest access
  234. # tokens in the database as well, but that would break existing
  235. # guest tokens.
  236. stored_user = await self.store.get_user_by_id(user_id)
  237. if not stored_user:
  238. raise InvalidClientTokenError("Unknown user_id %s" % user_id)
  239. if not stored_user.is_guest:
  240. raise InvalidClientTokenError(
  241. "Guest access token used for regular user"
  242. )
  243. return create_requester(
  244. user_id=user_id,
  245. is_guest=True,
  246. # all guests get the same device id
  247. device_id=GUEST_DEVICE_ID,
  248. authenticated_entity=user_id,
  249. )
  250. except (
  251. pymacaroons.exceptions.MacaroonException,
  252. TypeError,
  253. ValueError,
  254. ) as e:
  255. logger.warning(
  256. "Invalid access token in auth: %s %s.",
  257. type(e),
  258. e,
  259. )
  260. raise InvalidClientTokenError("Invalid access token passed.")
  261. async def is_server_admin(self, requester: Requester) -> bool:
  262. """Check if the given user is a local server admin.
  263. Args:
  264. requester: The user making the request, according to the access token.
  265. Returns:
  266. True if the user is an admin
  267. """
  268. return await self.store.is_server_admin(requester.user)