-
Notifications
You must be signed in to change notification settings - Fork 0
multi: add Rack::Attack rate limiting throttling and GET /v1/sismos/stats endpoint #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| module Rack | ||
| class Attack | ||
| # Cache store for rate limit counters. | ||
| # Uses RedisCacheStore if RACK_ATTACK_REDIS_URL or REDIS_URL is present. | ||
| # Falls back gracefully to MemoryStore if Redis is not configured yet. | ||
| redis_url = ENV['RACK_ATTACK_REDIS_URL'].presence || ENV['REDIS_URL'].presence | ||
|
|
||
| Rack::Attack.cache.store = if redis_url | ||
| ActiveSupport::Cache::RedisCacheStore.new( | ||
| url: redis_url, | ||
| namespace: 'rack_attack' | ||
| ) | ||
| elsif Rails.env.production? | ||
| raise 'RACK_ATTACK_REDIS_URL or REDIS_URL is required in production' | ||
| else | ||
| ActiveSupport::Cache::MemoryStore.new | ||
|
Euler-B marked this conversation as resolved.
|
||
| end | ||
|
|
||
| # 1. Throttle all requests by IP (60 req/min) | ||
| throttle('req/ip', limit: 60, period: 1.minute) do |req| | ||
| req.ip unless req.path.start_with?('/assets') | ||
| end | ||
|
|
||
| # 2. Throttle POST reports endpoint by IP (5 req/min) to prevent spam | ||
| throttle('reports/ip', limit: 5, period: 1.minute) do |req| | ||
| req.ip if req.path_info.match?(%r{\A/v1/sismos/\d+/reports(?:\.[^/]+)?\z}) && req.post? | ||
| end | ||
|
|
||
| # 3. Custom Response for Throttled Requests (HTTP 429) | ||
| self.throttled_responder = lambda do |request| | ||
| match_data = request.env['rack.attack.match_data'] || {} | ||
| now = match_data[:epoch_time] || Time.now.to_i | ||
| period = match_data[:period] || 60 | ||
| retry_after = period - (now % period) | ||
|
|
||
| headers = { | ||
| 'Content-Type' => 'application/json; charset=utf-8', | ||
| 'Retry-After' => retry_after.to_s | ||
| } | ||
|
|
||
| body = { | ||
| error: "Rate limit exceeded. Try again in #{retry_after} seconds." | ||
| }.to_json | ||
|
|
||
| [429, headers, [body]] | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| require 'test_helper' | ||
|
|
||
| class RateLimitingTest < ActionDispatch::IntegrationTest | ||
| setup do | ||
| Rack::Attack.cache.store.clear | ||
| end | ||
|
|
||
| test 'allows requests under the rate limit' do | ||
| get sismos_url | ||
| assert_response :success | ||
| end | ||
|
|
||
| test 'returns 429 too many requests when general rate limit is exceeded' do | ||
| travel_to Time.utc(2026, 8, 4, 12, 0, 0) do | ||
| 60.times do | ||
| get sismos_url | ||
| assert_response :success | ||
| end | ||
|
|
||
| get sismos_url | ||
| assert_response :too_many_requests | ||
|
|
||
| json = JSON.parse(response.body) | ||
| assert json.key?('error') | ||
| assert_includes json['error'], 'Rate limit exceeded' | ||
| assert response.headers.key?('Retry-After') | ||
| end | ||
| end | ||
|
|
||
| test 'returns 429 when POST report rate limit is exceeded' do | ||
| sismo = sismos(:one) | ||
|
|
||
| travel_to Time.utc(2026, 8, 4, 12, 0, 0) do | ||
| 5.times do | ||
| post sismo_reports_url(sismo), params: { felt: true, intensity: 'moderate' }, as: :json | ||
| assert_response :created | ||
| end | ||
|
|
||
| post sismo_reports_url(sismo), params: { felt: true, intensity: 'moderate' }, as: :json | ||
| assert_response :too_many_requests | ||
|
|
||
| json = JSON.parse(response.body) | ||
| assert json.key?('error') | ||
| assert_includes json['error'], 'Rate limit exceeded' | ||
| end | ||
| end | ||
|
|
||
| test 'returns 429 when POST report rate limit is exceeded on format-suffixed path' do | ||
| sismo = sismos(:one) | ||
|
|
||
| travel_to Time.utc(2026, 8, 4, 12, 0, 0) do | ||
| 5.times do | ||
| post "#{sismo_reports_path(sismo)}.json", params: { felt: true, intensity: 'moderate' }, as: :json | ||
| assert_response :created | ||
| end | ||
|
|
||
| post "#{sismo_reports_path(sismo)}.json", params: { felt: true, intensity: 'moderate' }, as: :json | ||
| assert_response :too_many_requests | ||
|
|
||
| json = JSON.parse(response.body) | ||
| assert json.key?('error') | ||
| assert_includes json['error'], 'Rate limit exceeded' | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.