Skip to content

Commit 2ae883c

Browse files
authored
Merge pull request rails#52825 from fatkodima/include-caching-in-api-controllers
Fix rate limiting for `ActionController::API` controllers
2 parents c7f7b0a + c24450a commit 2ae883c

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

actionpack/lib/action_controller/api.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ def self.without_modules(*modules)
123123
BasicImplicitRender,
124124
StrongParameters,
125125
RateLimiting,
126+
Caching,
126127

127128
DataStreaming,
128129
DefaultHeaders,
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# frozen_string_literal: true
2+
3+
require "abstract_unit"
4+
5+
class ApiRateLimitedController < ActionController::API
6+
self.cache_store = ActiveSupport::Cache::MemoryStore.new
7+
rate_limit to: 2, within: 2.seconds, only: :limited_to_two
8+
9+
def limited_to_two
10+
head :ok
11+
end
12+
end
13+
14+
class ApiRateLimitingTest < ActionController::TestCase
15+
tests ApiRateLimitedController
16+
17+
setup do
18+
ApiRateLimitedController.cache_store.clear
19+
end
20+
21+
test "exceeding basic limit" do
22+
get :limited_to_two
23+
get :limited_to_two
24+
assert_response :ok
25+
26+
get :limited_to_two
27+
assert_response :too_many_requests
28+
end
29+
30+
test "limit resets after time" do
31+
get :limited_to_two
32+
get :limited_to_two
33+
assert_response :ok
34+
35+
travel_to Time.now + 3.seconds do
36+
get :limited_to_two
37+
assert_response :ok
38+
end
39+
end
40+
end

0 commit comments

Comments
 (0)