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.
 
 
 
 
 
 

407 lines
17 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from collections import OrderedDict
  16. from typing import Hashable, Optional, Tuple
  17. from synapse.api.errors import LimitExceededError
  18. from synapse.config.ratelimiting import RatelimitSettings
  19. from synapse.storage.databases.main import DataStore
  20. from synapse.types import Requester
  21. from synapse.util import Clock
  22. class Ratelimiter:
  23. """
  24. Ratelimit actions marked by arbitrary keys.
  25. (Note that the source code speaks of "actions" and "burst_count" rather than
  26. "tokens" and a "bucket_size".)
  27. This is a "leaky bucket as a meter". For each key to be tracked there is a bucket
  28. containing some number 0 <= T <= `burst_count` of tokens corresponding to previously
  29. permitted requests for that key. Each bucket starts empty, and gradually leaks
  30. tokens at a rate of `rate_hz`.
  31. Upon an incoming request, we must determine:
  32. - the key that this request falls under (which bucket to inspect), and
  33. - the cost C of this request in tokens.
  34. Then, if there is room in the bucket for C tokens (T + C <= `burst_count`),
  35. the request is permitted and `cost` tokens are added to the bucket.
  36. Otherwise the request is denied, and the bucket continues to hold T tokens.
  37. This means that the limiter enforces an average request frequency of `rate_hz`,
  38. while accumulating a buffer of up to `burst_count` requests which can be consumed
  39. instantaneously.
  40. The tricky bit is the leaking. We do not want to have a periodic process which
  41. leaks every bucket! Instead, we track
  42. - the time point when the bucket was last completely empty, and
  43. - how many tokens have added to the bucket permitted since then.
  44. Then for each incoming request, we can calculate how many tokens have leaked
  45. since this time point, and use that to decide if we should accept or reject the
  46. request.
  47. Args:
  48. clock: A homeserver clock, for retrieving the current time
  49. rate_hz: The long term number of actions that can be performed in a second.
  50. burst_count: How many actions that can be performed before being limited.
  51. """
  52. def __init__(
  53. self,
  54. store: DataStore,
  55. clock: Clock,
  56. cfg: RatelimitSettings,
  57. ):
  58. self.clock = clock
  59. self.rate_hz = cfg.per_second
  60. self.burst_count = cfg.burst_count
  61. self.store = store
  62. self._limiter_name = cfg.key
  63. # An ordered dictionary representing the token buckets tracked by this rate
  64. # limiter. Each entry maps a key of arbitrary type to a tuple representing:
  65. # * The number of tokens currently in the bucket,
  66. # * The time point when the bucket was last completely empty, and
  67. # * The rate_hz (leak rate) of this particular bucket.
  68. self.actions: OrderedDict[Hashable, Tuple[float, float, float]] = OrderedDict()
  69. def _get_key(
  70. self, requester: Optional[Requester], key: Optional[Hashable]
  71. ) -> Hashable:
  72. """Use the requester's MXID as a fallback key if no key is provided."""
  73. if key is None:
  74. if not requester:
  75. raise ValueError("Must supply at least one of `requester` or `key`")
  76. key = requester.user.to_string()
  77. return key
  78. def _get_action_counts(
  79. self, key: Hashable, time_now_s: float
  80. ) -> Tuple[float, float, float]:
  81. """Retrieve the action counts, with a fallback representing an empty bucket."""
  82. return self.actions.get(key, (0.0, time_now_s, 0.0))
  83. async def can_do_action(
  84. self,
  85. requester: Optional[Requester],
  86. key: Optional[Hashable] = None,
  87. rate_hz: Optional[float] = None,
  88. burst_count: Optional[int] = None,
  89. update: bool = True,
  90. n_actions: int = 1,
  91. _time_now_s: Optional[float] = None,
  92. ) -> Tuple[bool, float]:
  93. """Can the entity (e.g. user or IP address) perform the action?
  94. Checks if the user has ratelimiting disabled in the database by looking
  95. for null/zero values in the `ratelimit_override` table. (Non-zero
  96. values aren't honoured, as they're specific to the event sending
  97. ratelimiter, rather than all ratelimiters)
  98. Args:
  99. requester: The requester that is doing the action, if any. Used to check
  100. if the user has ratelimits disabled in the database.
  101. key: An arbitrary key used to classify an action. Defaults to the
  102. requester's user ID.
  103. rate_hz: The long term number of actions that can be performed in a second.
  104. Overrides the value set during instantiation if set.
  105. burst_count: How many actions that can be performed before being limited.
  106. Overrides the value set during instantiation if set.
  107. update: Whether to count this check as performing the action
  108. n_actions: The number of times the user wants to do this action. If the user
  109. cannot do all of the actions, the user's action count is not incremented
  110. at all.
  111. _time_now_s: The current time. Optional, defaults to the current time according
  112. to self.clock. Only used by tests.
  113. Returns:
  114. A tuple containing:
  115. * A bool indicating if they can perform the action now
  116. * The reactor timestamp for when the action can be performed next.
  117. -1 if rate_hz is less than or equal to zero
  118. """
  119. key = self._get_key(requester, key)
  120. if requester:
  121. # Disable rate limiting of users belonging to any AS that is configured
  122. # not to be rate limited in its registration file (rate_limited: true|false).
  123. if requester.app_service and not requester.app_service.is_rate_limited():
  124. return True, -1.0
  125. # Check if ratelimiting has been disabled for the user.
  126. #
  127. # Note that we don't use the returned rate/burst count, as the table
  128. # is specifically for the event sending ratelimiter. Instead, we
  129. # only use it to (somewhat cheekily) infer whether the user should
  130. # be subject to any rate limiting or not.
  131. override = await self.store.get_ratelimit_for_user(
  132. requester.authenticated_entity
  133. )
  134. if override and not override.messages_per_second:
  135. return True, -1.0
  136. # Override default values if set
  137. time_now_s = _time_now_s if _time_now_s is not None else self.clock.time()
  138. rate_hz = rate_hz if rate_hz is not None else self.rate_hz
  139. burst_count = burst_count if burst_count is not None else self.burst_count
  140. # Remove any expired entries
  141. self._prune_message_counts(time_now_s)
  142. # Check if there is an existing count entry for this key
  143. action_count, time_start, _ = self._get_action_counts(key, time_now_s)
  144. # Check whether performing another action is allowed
  145. time_delta = time_now_s - time_start
  146. performed_count = action_count - time_delta * rate_hz
  147. if performed_count < 0:
  148. performed_count = 0
  149. # Reset the start time and forgive all actions
  150. action_count = 0
  151. time_start = time_now_s
  152. # This check would be easier read as performed_count + n_actions > burst_count,
  153. # but performed_count might be a very precise float (with lots of numbers
  154. # following the point) in which case Python might round it up when adding it to
  155. # n_actions. Writing it this way ensures it doesn't happen.
  156. if performed_count > burst_count - n_actions:
  157. # Deny, we have exceeded our burst count
  158. allowed = False
  159. else:
  160. # We haven't reached our limit yet
  161. allowed = True
  162. action_count = action_count + n_actions
  163. if update:
  164. self.actions[key] = (action_count, time_start, rate_hz)
  165. if rate_hz > 0:
  166. # Find out when the count of existing actions expires
  167. time_allowed = time_start + (action_count - burst_count + 1) / rate_hz
  168. # Don't give back a time in the past
  169. if time_allowed < time_now_s:
  170. time_allowed = time_now_s
  171. else:
  172. # XXX: Why is this -1? This seems to only be used in
  173. # self.ratelimit. I guess so that clients get a time in the past and don't
  174. # feel afraid to try again immediately
  175. time_allowed = -1
  176. return allowed, time_allowed
  177. def record_action(
  178. self,
  179. requester: Optional[Requester],
  180. key: Optional[Hashable] = None,
  181. n_actions: int = 1,
  182. _time_now_s: Optional[float] = None,
  183. ) -> None:
  184. """Record that an action(s) took place, even if they violate the rate limit.
  185. This is useful for tracking the frequency of events that happen across
  186. federation which we still want to impose local rate limits on. For instance, if
  187. we are alice.com monitoring a particular room, we cannot prevent bob.com
  188. from joining users to that room. However, we can track the number of recent
  189. joins in the room and refuse to serve new joins ourselves if there have been too
  190. many in the room across both homeservers.
  191. Args:
  192. requester: The requester that is doing the action, if any.
  193. key: An arbitrary key used to classify an action. Defaults to the
  194. requester's user ID.
  195. n_actions: The number of times the user wants to do this action. If the user
  196. cannot do all of the actions, the user's action count is not incremented
  197. at all.
  198. _time_now_s: The current time. Optional, defaults to the current time according
  199. to self.clock. Only used by tests.
  200. """
  201. key = self._get_key(requester, key)
  202. time_now_s = _time_now_s if _time_now_s is not None else self.clock.time()
  203. action_count, time_start, rate_hz = self._get_action_counts(key, time_now_s)
  204. self.actions[key] = (action_count + n_actions, time_start, rate_hz)
  205. def _prune_message_counts(self, time_now_s: float) -> None:
  206. """Remove message count entries that have not exceeded their defined
  207. rate_hz limit
  208. Args:
  209. time_now_s: The current time
  210. """
  211. # We create a copy of the key list here as the dictionary is modified during
  212. # the loop
  213. for key in list(self.actions.keys()):
  214. action_count, time_start, rate_hz = self.actions[key]
  215. # Rate limit = "seconds since we started limiting this action" * rate_hz
  216. # If this limit has not been exceeded, wipe our record of this action
  217. time_delta = time_now_s - time_start
  218. if action_count - time_delta * rate_hz > 0:
  219. continue
  220. else:
  221. del self.actions[key]
  222. async def ratelimit(
  223. self,
  224. requester: Optional[Requester],
  225. key: Optional[Hashable] = None,
  226. rate_hz: Optional[float] = None,
  227. burst_count: Optional[int] = None,
  228. update: bool = True,
  229. n_actions: int = 1,
  230. _time_now_s: Optional[float] = None,
  231. ) -> None:
  232. """Checks if an action can be performed. If not, raises a LimitExceededError
  233. Checks if the user has ratelimiting disabled in the database by looking
  234. for null/zero values in the `ratelimit_override` table. (Non-zero
  235. values aren't honoured, as they're specific to the event sending
  236. ratelimiter, rather than all ratelimiters)
  237. Args:
  238. requester: The requester that is doing the action, if any. Used to check for
  239. if the user has ratelimits disabled.
  240. key: An arbitrary key used to classify an action. Defaults to the
  241. requester's user ID.
  242. rate_hz: The long term number of actions that can be performed in a second.
  243. Overrides the value set during instantiation if set.
  244. burst_count: How many actions that can be performed before being limited.
  245. Overrides the value set during instantiation if set.
  246. update: Whether to count this check as performing the action
  247. n_actions: The number of times the user wants to do this action. If the user
  248. cannot do all of the actions, the user's action count is not incremented
  249. at all.
  250. _time_now_s: The current time. Optional, defaults to the current time according
  251. to self.clock. Only used by tests.
  252. Raises:
  253. LimitExceededError: If an action could not be performed, along with the time in
  254. milliseconds until the action can be performed again
  255. """
  256. time_now_s = _time_now_s if _time_now_s is not None else self.clock.time()
  257. allowed, time_allowed = await self.can_do_action(
  258. requester,
  259. key,
  260. rate_hz=rate_hz,
  261. burst_count=burst_count,
  262. update=update,
  263. n_actions=n_actions,
  264. _time_now_s=time_now_s,
  265. )
  266. if not allowed:
  267. raise LimitExceededError(
  268. limiter_name=self._limiter_name,
  269. retry_after_ms=int(1000 * (time_allowed - time_now_s)),
  270. )
  271. class RequestRatelimiter:
  272. def __init__(
  273. self,
  274. store: DataStore,
  275. clock: Clock,
  276. rc_message: RatelimitSettings,
  277. rc_admin_redaction: Optional[RatelimitSettings],
  278. ):
  279. self.store = store
  280. self.clock = clock
  281. # The rate_hz and burst_count are overridden on a per-user basis
  282. self.request_ratelimiter = Ratelimiter(
  283. store=self.store,
  284. clock=self.clock,
  285. cfg=RatelimitSettings(key=rc_message.key, per_second=0, burst_count=0),
  286. )
  287. self._rc_message = rc_message
  288. # Check whether ratelimiting room admin message redaction is enabled
  289. # by the presence of rate limits in the config
  290. if rc_admin_redaction:
  291. self.admin_redaction_ratelimiter: Optional[Ratelimiter] = Ratelimiter(
  292. store=self.store,
  293. clock=self.clock,
  294. cfg=rc_admin_redaction,
  295. )
  296. else:
  297. self.admin_redaction_ratelimiter = None
  298. async def ratelimit(
  299. self,
  300. requester: Requester,
  301. update: bool = True,
  302. is_admin_redaction: bool = False,
  303. n_actions: int = 1,
  304. ) -> None:
  305. """Ratelimits requests.
  306. Args:
  307. requester
  308. update: Whether to record that a request is being processed.
  309. Set to False when doing multiple checks for one request (e.g.
  310. to check up front if we would reject the request), and set to
  311. True for the last call for a given request.
  312. is_admin_redaction: Whether this is a room admin/moderator
  313. redacting an event. If so then we may apply different
  314. ratelimits depending on config.
  315. n_actions: Multiplier for the number of actions to apply to the
  316. rate limiter at once.
  317. Raises:
  318. LimitExceededError if the request should be ratelimited
  319. """
  320. user_id = requester.user.to_string()
  321. # The AS user itself is never rate limited.
  322. app_service = self.store.get_app_service_by_user_id(user_id)
  323. if app_service is not None:
  324. return # do not ratelimit app service senders
  325. messages_per_second = self._rc_message.per_second
  326. burst_count = self._rc_message.burst_count
  327. # Check if there is a per user override in the DB.
  328. override = await self.store.get_ratelimit_for_user(user_id)
  329. if override:
  330. # If overridden with a null Hz then ratelimiting has been entirely
  331. # disabled for the user
  332. if not override.messages_per_second:
  333. return
  334. messages_per_second = override.messages_per_second
  335. burst_count = override.burst_count
  336. if is_admin_redaction and self.admin_redaction_ratelimiter:
  337. # If we have separate config for admin redactions, use a separate
  338. # ratelimiter as to not have user_ids clash
  339. await self.admin_redaction_ratelimiter.ratelimit(
  340. requester, update=update, n_actions=n_actions
  341. )
  342. else:
  343. # Override rate and burst count per-user
  344. await self.request_ratelimiter.ratelimit(
  345. requester,
  346. rate_hz=messages_per_second,
  347. burst_count=burst_count,
  348. update=update,
  349. n_actions=n_actions,
  350. )