Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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