Skip to content

Commit 9c41f58

Browse files
authored
Include controller path into cache keys for rate limiters (rails#52961)
1 parent cde7ffe commit 9c41f58

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

actionpack/lib/action_controller/metal/rate_limiting.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,15 @@ module ClassMethods
5252
# rate_limit to: 3, within: 2.seconds, name: "short-term"
5353
# rate_limit to: 10, within: 5.minutes, name: "long-term"
5454
# end
55-
def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { head :too_many_requests }, store: cache_store, name: controller_path, **options)
55+
def rate_limit(to:, within:, by: -> { request.remote_ip }, with: -> { head :too_many_requests }, store: cache_store, name: nil, **options)
5656
before_action -> { rate_limiting(to: to, within: within, by: by, with: with, store: store, name: name) }, **options
5757
end
5858
end
5959

6060
private
6161
def rate_limiting(to:, within:, by:, with:, store:, name:)
62-
count = store.increment("rate-limit:#{name}:#{instance_exec(&by)}", 1, expires_in: within)
62+
cache_key = ["rate-limit", controller_path, name, instance_exec(&by)].compact.join(":")
63+
count = store.increment(cache_key, 1, expires_in: within)
6364
if count && count > to
6465
ActiveSupport::Notifications.instrument("rate_limit.action_controller", request: request) do
6566
instance_exec(&with)

0 commit comments

Comments
 (0)