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.
 
 
 
 
 
 

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