Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Stop writing access tokens into the rate limit cache

Guido Boykecbc8faee9d68
diff --git a/config/initializers/rack_attack.rb b/config/initializers/rack_attack.rb
index 21ddac3..167e2d1 100644
--- a/config/initializers/rack_attack.rb
+++ b/config/initializers/rack_attack.rb
@@ -228,10 +228,7 @@ class Rack::Attack
### Throttle API v1 per token (60 req/min) ###
# Protects against LLM infinite loops + brute force against leaked tokens.
throttle('api_v1/token', limit: 60, period: 60.seconds) do |req|
- next unless normalized_path(req).start_with?('/api/v1/')
-
- raw = req.env['HTTP_AUTHORIZATION'].to_s.sub(/\ABearer /, '')
- raw.presence
+ token_bucket(req) if normalized_path(req).start_with?('/api/v1/')
end
### Throttle MCP endpoint per token (60 req/min) ###
@@ -239,10 +236,7 @@ class Rack::Attack
# cap — so a per-token throttle bounds runaway agents + leaked-token brute force.
# Per-IP is already covered by the 'api/ip' throttle above (/api/ prefix).
throttle('api_mcp/token', limit: 60, period: 60.seconds) do |req|
- next unless normalized_path(req).match?(MCP_PATH)
-
- raw = req.env['HTTP_AUTHORIZATION'].to_s.sub(/\ABearer /, '')
- raw.presence
+ token_bucket(req) if normalized_path(req).match?(MCP_PATH)
end
### Throttle meetings AI participant detection per user ###
@@ -328,6 +322,14 @@ class Rack::Attack
req.post? && normalized_path(req).match?(pattern)
end
+ # The bucket of a bearer token: its digest, never the token. A discriminator is part
+ # of the cache key, and the file store writes that key into a file name, so the raw
+ # value put the plaintext of every active token into tmp/cache. nil without a token.
+ def self.token_bucket(req)
+ raw = req.env['HTTP_AUTHORIZATION'].to_s.sub(/\ABearer /, '')
+ Digest::SHA256.hexdigest(raw) if raw.present?
+ end
+
# The address a login attempt names, from a form OR a JSON body. req.params
# holds only form and query parameters, so a JSON login (Devise parses it
# later, in the controller) used to reach no per-email bucket at all: a
@@ -441,29 +443,6 @@ class Rack::Attack
end
end
-# ⚠ CLIENT-SPOOFABLE THROTTLE KEY -- needs a server-side fix, NOT a code-only one.
-#
-# Every `req.ip` above is client-controlled as things stand. req.ip (Rack 3)
-# prefers the RFC 7239 Forwarded header; ActionDispatch remote_ip prefers
-# X-Forwarded-For. With `config.action_dispatch.trusted_proxies` unset (it is
-# nil here) BOTH follow the header the client sent -- measured: a forged
-# X-Forwarded-For makes remote_ip return the forged value, so swapping req.ip
-# for remote_ip buys nothing. A client can therefore pick a fresh bucket per
-# request for registrations/ip and registrations/subnet, and can even spend a
-# victim /24's registration budget on purpose. The bot-trap log line has the
-# same weakness.
-#
-# The fix lives at the trust boundary and needs the production topology (Puma
-# behind nginx over a unix socket), which is not in this repo, so it is
-# deliberately NOT guessed here:
-# 1. nginx: set (do not append) X-Forwarded-For to $remote_addr and clear any
-# inbound Forwarded header, so a spoofed value never reaches Rails;
-# 2. Rails: set config.action_dispatch.trusted_proxies to the proxy address so
-# remote_ip stops at the nginx hop and returns the real client.
-# Until both are in place the per-IP and subnet throttles bound accidental
-# floods (a real botnet without header spoofing) but not a deliberate one; the
-# path-normalisation and honeypot defences above do not depend on the client IP.
-
# Every limit above was invisible in the log: a throttled request answers 429
# and disappears, and a track answers nothing at all. Without these two lines a
# wave is only discoverable afterwards, in the database.
diff --git a/spec/requests/auth_throttle_spec.rb b/spec/requests/auth_throttle_spec.rb
index 8cd879d..311893f 100644
--- a/spec/requests/auth_throttle_spec.rb
+++ b/spec/requests/auth_throttle_spec.rb
@@ -297,6 +297,67 @@ RSpec.describe 'Auth endpoint throttling', type: :request do
# The branches of the bucketing function the request specs above never
# reach: IPv6, IPv4-mapped IPv6 and garbage input. Pinned directly.
+ # A throttle discriminator is part of the cache key, and the file store production
+ # runs on writes that key into a file name. The database only ever holds a token's
+ # digest; a raw token as the discriminator put the plaintext of every active token on
+ # disk, in tmp/cache and in whatever backs that up.
+ describe 'token throttles (api_v1/token, api_mcp/token, 60 per minute)' do
+ let(:token) { "#{PersonalAccessToken::TOKEN_PREFIX}#{'x' * PersonalAccessToken::TOKEN_BODY_LENGTH}" }
+ let(:other_token) { "#{PersonalAccessToken::TOKEN_PREFIX}#{'y' * PersonalAccessToken::TOKEN_BODY_LENGTH}" }
+
+ def bearer(raw, ip)
+ { 'Authorization' => "Bearer #{raw}", 'REMOTE_ADDR' => ip }
+ end
+
+ def call_api_v1(raw, ip: '203.0.113.1')
+ get '/api/v1/me', headers: bearer(raw, ip)
+ end
+
+ def call_mcp(raw, ip: '203.0.113.1')
+ post '/api/mcp', headers: bearer(raw, ip)
+ end
+
+ around do |example|
+ Dir.mktmpdir do |dir|
+ @cache_dir = dir
+ Rack::Attack.cache.store = ActiveSupport::Cache::FileStore.new(dir)
+ example.run
+ end
+ end
+
+ before { Prosopite.pause }
+
+ def cache_file_names
+ Dir.glob(File.join(@cache_dir, '**', '*')).select { |path| File.file?(path) }
+ end
+
+ %i[call_api_v1 call_mcp].each do |call|
+ it "keeps the plaintext out of the cache (#{call})" do
+ send(call, token)
+
+ expect(cache_file_names).not_to be_empty
+ expect(cache_file_names.join).not_to include(token)
+ expect(cache_file_names.map { |path| File.binread(path) }.join).not_to include(token)
+ end
+
+ # Each call from its own address, so that only the token bucket can answer 429.
+ it "counts one token across addresses (#{call})" do
+ 60.times { |i| send(call, token, ip: "203.0.113.#{i + 1}") }
+ expect(response).not_to have_http_status(:too_many_requests)
+
+ send(call, token, ip: '198.51.100.1')
+ expect(response).to have_http_status(:too_many_requests)
+ end
+
+ it "gives another token its own bucket (#{call})" do
+ 60.times { |i| send(call, token, ip: "203.0.113.#{i + 1}") }
+
+ send(call, other_token, ip: '198.51.100.1')
+ expect(response).not_to have_http_status(:too_many_requests)
+ end
+ end
+ end
+
describe 'Rack::Attack.subnet_of' do
it 'buckets a /24 together and the neighbouring /24 apart' do
expect(Rack::Attack.subnet_of('203.0.113.7')).to eq(Rack::Attack.subnet_of('203.0.113.200'))