rate limits: penalize user if they keep making requests while limited.

If the user makes a request while rate limited, penalize them 1 second
for that request, up to a maximum of 30 seconds. This means that if a
user doesn't stop making requests after being rate limited, then they
will stay rate limited forever until they stop.

This is to temp ban bots, especially spam bots, that flood requests
while ignoring HTTP errors or rate limits.

(Note that this is on a per-endpoint basis. Being rate limited on one
endpoint won't penalize you for making calls to other endpoints.)
This commit is contained in:
evazion
2021-03-05 15:53:03 -06:00
parent 413cd34c45
commit 1ee1e807cf
2 changed files with 15 additions and 8 deletions

View File

@@ -26,13 +26,13 @@ class RateLimitTest < ActiveSupport::TestCase
assert_equal(9, limiter.rate_limits.first.points)
end
should "be limited if the point count is negative" do
should "be limited and penalize the caller 1 second if the point count is negative" do
freeze_time
create(:rate_limit, action: "write", key: "users/1", points: -1)
limiter = RateLimiter.new("write", ["users/1"], cost: 1)
assert_equal(true, limiter.limited?)
assert_equal(-1, limiter.rate_limits.first.points)
assert_equal(-2, limiter.rate_limits.first.points)
end
should "not be limited if the point count was positive before the action" do
@@ -50,17 +50,17 @@ class RateLimitTest < ActiveSupport::TestCase
limiter = RateLimiter.new("write", ["users/1"], cost: 1, rate: 1, burst: 10)
assert_equal(true, limiter.limited?)
assert_equal(-2, limiter.rate_limits.first.points)
assert_equal(-3, limiter.rate_limits.first.points)
travel 1.second
limiter = RateLimiter.new("write", ["users/1"], cost: 1, rate: 1, burst: 10)
assert_equal(true, limiter.limited?)
assert_equal(-1, limiter.rate_limits.first.points)
assert_equal(-3, limiter.rate_limits.first.points)
travel 5.second
limiter = RateLimiter.new("write", ["users/1"], cost: 1, rate: 1, burst: 10)
assert_equal(false, limiter.limited?)
assert_equal(3, limiter.rate_limits.first.points)
assert_equal(1, limiter.rate_limits.first.points)
travel 60.second
limiter = RateLimiter.new("write", ["users/1"], cost: 1, rate: 1, burst: 10)