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.
 
 
 
 
 
 

133 lines
5.6 KiB

  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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 Optional
  16. from synapse.api.constants import LimitBlockingTypes, UserTypes
  17. from synapse.api.errors import Codes, ResourceLimitError
  18. from synapse.config.server import is_threepid_reserved
  19. from synapse.types import Requester
  20. logger = logging.getLogger(__name__)
  21. class AuthBlocking:
  22. def __init__(self, hs):
  23. self.store = hs.get_datastore()
  24. self._server_notices_mxid = hs.config.server_notices_mxid
  25. self._hs_disabled = hs.config.hs_disabled
  26. self._hs_disabled_message = hs.config.hs_disabled_message
  27. self._admin_contact = hs.config.admin_contact
  28. self._max_mau_value = hs.config.max_mau_value
  29. self._limit_usage_by_mau = hs.config.limit_usage_by_mau
  30. self._mau_limits_reserved_threepids = hs.config.mau_limits_reserved_threepids
  31. self._server_name = hs.hostname
  32. self._track_appservice_user_ips = hs.config.appservice.track_appservice_user_ips
  33. async def check_auth_blocking(
  34. self,
  35. user_id: Optional[str] = None,
  36. threepid: Optional[dict] = None,
  37. user_type: Optional[str] = None,
  38. requester: Optional[Requester] = None,
  39. ):
  40. """Checks if the user should be rejected for some external reason,
  41. such as monthly active user limiting or global disable flag
  42. Args:
  43. user_id: If present, checks for presence against existing
  44. MAU cohort
  45. threepid: If present, checks for presence against configured
  46. reserved threepid. Used in cases where the user is trying register
  47. with a MAU blocked server, normally they would be rejected but their
  48. threepid is on the reserved list. user_id and
  49. threepid should never be set at the same time.
  50. user_type: If present, is used to decide whether to check against
  51. certain blocking reasons like MAU.
  52. requester: If present, and the authenticated entity is a user, checks for
  53. presence against existing MAU cohort. Passing in both a `user_id` and
  54. `requester` is an error.
  55. """
  56. if requester and user_id:
  57. raise Exception(
  58. "Passed in both 'user_id' and 'requester' to 'check_auth_blocking'"
  59. )
  60. if requester:
  61. if requester.authenticated_entity.startswith("@"):
  62. user_id = requester.authenticated_entity
  63. elif requester.authenticated_entity == self._server_name:
  64. # We never block the server from doing actions on behalf of
  65. # users.
  66. return
  67. elif requester.app_service and not self._track_appservice_user_ips:
  68. # If we're authenticated as an appservice then we only block
  69. # auth if `track_appservice_user_ips` is set, as that option
  70. # implicitly means that application services are part of MAU
  71. # limits.
  72. return
  73. # Never fail an auth check for the server notices users or support user
  74. # This can be a problem where event creation is prohibited due to blocking
  75. if user_id is not None:
  76. if user_id == self._server_notices_mxid:
  77. return
  78. if await self.store.is_support_user(user_id):
  79. return
  80. if self._hs_disabled:
  81. raise ResourceLimitError(
  82. 403,
  83. self._hs_disabled_message,
  84. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  85. admin_contact=self._admin_contact,
  86. limit_type=LimitBlockingTypes.HS_DISABLED,
  87. )
  88. if self._limit_usage_by_mau is True:
  89. assert not (user_id and threepid)
  90. # If the user is already part of the MAU cohort or a trial user
  91. if user_id:
  92. timestamp = await self.store.user_last_seen_monthly_active(user_id)
  93. if timestamp:
  94. return
  95. is_trial = await self.store.is_trial_user(user_id)
  96. if is_trial:
  97. return
  98. elif threepid:
  99. # If the user does not exist yet, but is signing up with a
  100. # reserved threepid then pass auth check
  101. if is_threepid_reserved(self._mau_limits_reserved_threepids, threepid):
  102. return
  103. elif user_type == UserTypes.SUPPORT:
  104. # If the user does not exist yet and is of type "support",
  105. # allow registration. Support users are excluded from MAU checks.
  106. return
  107. # Else if there is no room in the MAU bucket, bail
  108. current_mau = await self.store.get_monthly_active_count()
  109. if current_mau >= self._max_mau_value:
  110. raise ResourceLimitError(
  111. 403,
  112. "Monthly Active User Limit Exceeded",
  113. admin_contact=self._admin_contact,
  114. errcode=Codes.RESOURCE_LIMIT_EXCEEDED,
  115. limit_type=LimitBlockingTypes.MONTHLY_ACTIVE_USER,
  116. )