-
Notifications
You must be signed in to change notification settings - Fork 55
Add connection rate limiting #1765
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
Draft
baelter
wants to merge
5
commits into
main
Choose a base branch
from
feature/connection-rate-limiting
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b9d451a
Add connection rate limiting to prevent connection churn
baelter d4b0816
Fix global token waste and add per-IP tracking cap
baelter ebe0c61
Address review feedback on connection rate limiter
baelter 759b059
Use single hash with record for per-IP state, O(1) eviction
baelter 6c36179
Make ConnectionRateLimiter thread-safe for multi-threaded Crystal
baelter 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| require "./spec_helper" | ||
|
|
||
| describe LavinMQ::ConnectionRateLimiter do | ||
| describe "global rate limit" do | ||
| it "allows connections when disabled (limit=0)" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit = 0 | ||
| limiter = LavinMQ::ConnectionRateLimiter.new(config) | ||
| 100.times { limiter.allow?("127.0.0.1").should be_true } | ||
| end | ||
|
|
||
| it "allows connections up to the limit" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit = 5 | ||
| limiter = LavinMQ::ConnectionRateLimiter.new(config) | ||
| 5.times { |i| limiter.allow?("127.0.0.1").should(be_true, "failed on attempt #{i}") } | ||
| limiter.allow?("127.0.0.1").should be_false | ||
| end | ||
|
|
||
| it "replenishes tokens over time" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit = 10 | ||
| limiter = LavinMQ::ConnectionRateLimiter.new(config) | ||
| 10.times { limiter.allow?("127.0.0.1") } | ||
| limiter.allow?("127.0.0.1").should be_false | ||
| sleep 0.2.seconds | ||
| limiter.allow?("127.0.0.1").should be_true | ||
| end | ||
| end | ||
|
|
||
| describe "per-IP rate limit" do | ||
| it "allows connections when disabled (limit=0)" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit_per_ip = 0 | ||
| limiter = LavinMQ::ConnectionRateLimiter.new(config) | ||
| 100.times { limiter.allow?("10.0.0.1").should be_true } | ||
| end | ||
|
|
||
| it "limits each IP independently" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit_per_ip = 2 | ||
| limiter = LavinMQ::ConnectionRateLimiter.new(config) | ||
| 2.times { limiter.allow?("10.0.0.1").should be_true } | ||
| limiter.allow?("10.0.0.1").should be_false | ||
| 2.times { limiter.allow?("10.0.0.2").should be_true } | ||
| limiter.allow?("10.0.0.2").should be_false | ||
| end | ||
|
|
||
| it "replenishes per-IP tokens over time" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit_per_ip = 10 | ||
| limiter = LavinMQ::ConnectionRateLimiter.new(config) | ||
| 10.times { limiter.allow?("10.0.0.1") } | ||
| limiter.allow?("10.0.0.1").should be_false | ||
| sleep 0.2.seconds | ||
| limiter.allow?("10.0.0.1").should be_true | ||
| end | ||
| end | ||
|
|
||
| describe "combined global and per-IP limits" do | ||
| it "per-IP limit stops connections before global limit" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit = 10 | ||
| config.connection_rate_limit_per_ip = 2 | ||
| limiter = LavinMQ::ConnectionRateLimiter.new(config) | ||
| 2.times { limiter.allow?("10.0.0.1").should be_true } | ||
| # Per-IP limit reached, even though global has tokens | ||
| limiter.allow?("10.0.0.1").should be_false | ||
| # Different IP still works | ||
| 2.times { limiter.allow?("10.0.0.2").should be_true } | ||
| limiter.allow?("10.0.0.2").should be_false | ||
| end | ||
|
|
||
| it "global limit stops connections even if per-IP has tokens" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit = 3 | ||
| config.connection_rate_limit_per_ip = 5 | ||
| limiter = LavinMQ::ConnectionRateLimiter.new(config) | ||
| 3.times { limiter.allow?("10.0.0.1").should be_true } | ||
| # Global limit reached | ||
| limiter.allow?("10.0.0.1").should be_false | ||
| # Different IP also blocked by global limit | ||
| limiter.allow?("10.0.0.2").should be_false | ||
| end | ||
| end | ||
| end | ||
|
|
||
| describe "Server connection rate limiting" do | ||
| it "rejects connections exceeding the global rate limit" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit = 2 | ||
| with_amqp_server(config: config) do |s| | ||
| conn1 = AMQP::Client.new(port: amqp_port(s)).connect | ||
| conn2 = AMQP::Client.new(port: amqp_port(s)).connect | ||
| # Third connection should fail - server closes socket before handshake | ||
| expect_raises(Exception) do | ||
| AMQP::Client.new(port: amqp_port(s)).connect | ||
| end | ||
| conn1.close | ||
| conn2.close | ||
| end | ||
| end | ||
|
|
||
| it "allows unlimited connections when rate limit is 0" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit = 0 | ||
| with_amqp_server(config: config) do |s| | ||
| conns = Array(AMQP::Client::Connection).new | ||
| 5.times do | ||
| conns << AMQP::Client.new(port: amqp_port(s)).connect | ||
| end | ||
| conns.size.should eq 5 | ||
| conns.each &.close | ||
| end | ||
| end | ||
|
|
||
| it "rejects connections exceeding the per-IP rate limit" do | ||
| config = LavinMQ::Config.new | ||
| config.connection_rate_limit_per_ip = 2 | ||
| with_amqp_server(config: config) do |s| | ||
| conn1 = AMQP::Client.new(port: amqp_port(s)).connect | ||
| conn2 = AMQP::Client.new(port: amqp_port(s)).connect | ||
| expect_raises(Exception) do | ||
| AMQP::Client.new(port: amqp_port(s)).connect | ||
| end | ||
| conn1.close | ||
| conn2.close | ||
| 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| module LavinMQ | ||
| # Token bucket rate limiter for incoming connections. | ||
| # Fiber-safe (single-threaded Crystal runtime). | ||
| class ConnectionRateLimiter | ||
| Log = LavinMQ::Log.for "rate_limiter" | ||
| MAX_TRACKED_IPS = 100_000 | ||
|
|
||
| @global_tokens : Float64 | ||
| @global_last_refill : Time::Instant | ||
| @last_log_time : Time::Instant | ||
|
|
||
| def initialize(@config : Config) | ||
| @global_tokens = @config.connection_rate_limit.to_f | ||
| @global_last_refill = Time.instant | ||
| @per_ip_tokens = Hash(String, Float64).new | ||
| @per_ip_last_refill = Hash(String, Time::Instant).new | ||
| @last_log_time = Time.instant | ||
| @log_suppressed = false | ||
| end | ||
|
|
||
| # Returns true if the connection should be allowed. | ||
| # Per-IP is checked first to avoid consuming a global token | ||
| # when the per-IP limit already rejects the connection. | ||
| def allow?(remote_address : String) : Bool | ||
| return true unless rate_limiting_enabled? | ||
| allow_per_ip?(remote_address) && allow_global? | ||
| end | ||
|
|
||
| private def rate_limiting_enabled? : Bool | ||
| @config.connection_rate_limit > 0 || | ||
| @config.connection_rate_limit_per_ip > 0 | ||
| end | ||
|
|
||
| private def allow_global? : Bool | ||
| limit = @config.connection_rate_limit | ||
| return true if limit <= 0 | ||
| consume_token( | ||
| limit, | ||
| pointerof(@global_tokens), | ||
| pointerof(@global_last_refill) | ||
| ) | ||
| end | ||
|
|
||
| private def allow_per_ip?(ip : String) : Bool | ||
| limit = @config.connection_rate_limit_per_ip | ||
| return true if limit <= 0 | ||
|
|
||
| now = Time.instant | ||
| unless @per_ip_last_refill.has_key?(ip) | ||
| if @per_ip_tokens.size >= MAX_TRACKED_IPS | ||
| Log.warn { "Per-IP tracking limit reached (#{MAX_TRACKED_IPS}), rejecting new IP: #{ip}" } | ||
| return false | ||
| end | ||
| @per_ip_tokens[ip] = limit.to_f | ||
| @per_ip_last_refill[ip] = now | ||
| end | ||
|
|
||
| last_refill = @per_ip_last_refill[ip] | ||
| tokens = @per_ip_tokens[ip] | ||
| elapsed = (now - last_refill).total_seconds | ||
| tokens = Math.min(limit.to_f, tokens + elapsed * limit) | ||
| @per_ip_last_refill[ip] = now | ||
|
|
||
| if tokens >= 1.0 | ||
| @per_ip_tokens[ip] = tokens - 1.0 | ||
| true | ||
| else | ||
| @per_ip_tokens[ip] = tokens | ||
| false | ||
| end | ||
| end | ||
|
|
||
| private def consume_token( | ||
| limit : Int32, | ||
| tokens_ptr : Pointer(Float64), | ||
| last_refill_ptr : Pointer(Time::Instant), | ||
| ) : Bool | ||
| now = Time.instant | ||
| elapsed = (now - last_refill_ptr.value).total_seconds | ||
| tokens = Math.min( | ||
| limit.to_f, | ||
| tokens_ptr.value + elapsed * limit | ||
| ) | ||
| last_refill_ptr.value = now | ||
|
|
||
| if tokens >= 1.0 | ||
| tokens_ptr.value = tokens - 1.0 | ||
| true | ||
| else | ||
| tokens_ptr.value = tokens | ||
| false | ||
| end | ||
| end | ||
|
|
||
| def log_rate_limited(remote_address : String) | ||
| now = Time.instant | ||
| if (now - @last_log_time).total_seconds >= 1.0 | ||
| @last_log_time = now | ||
| Log.warn { "Connection rate limited: #{remote_address}" } | ||
| @log_suppressed = false | ||
| elsif !@log_suppressed | ||
| @log_suppressed = true | ||
| end | ||
| end | ||
|
|
||
| # Remove stale per-IP entries to prevent unbounded growth. | ||
| # Called periodically (e.g. from stats_loop). | ||
| def cleanup_stale_entries | ||
| return if @config.connection_rate_limit_per_ip <= 0 | ||
| now = Time.instant | ||
| @per_ip_last_refill.reject! do |ip, last_refill| | ||
| if (now - last_refill).total_seconds > 60 | ||
| @per_ip_tokens.delete(ip) | ||
| true | ||
| end | ||
| end | ||
| 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.