Add user api key client rate limit settings (#30402)

This commit is contained in:
Angus McLeod 2024-12-30 17:10:48 +01:00 committed by GitHub
parent 9a22e8d2f1
commit ce7a14104b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 62 additions and 2 deletions

View File

@ -12,7 +12,7 @@ class UserApiKeyClientsController < ApplicationController
end
def create
rate_limit
rate_limit unless skip_rate_limit?
require_params
validate_params
ensure_new_client
@ -34,8 +34,20 @@ class UserApiKeyClientsController < ApplicationController
end
end
def skip_rate_limit?
SiteSetting
.create_user_api_key_client_ip_rate_limit_override_ips
.split("|")
.include?(request.remote_ip)
end
def rate_limit
RateLimiter.new(nil, "user-api-key-clients-#{request.remote_ip}", 1, 24.hours).performed!
RateLimiter.new(
nil,
"user-api-key-clients-#{request.remote_ip}",
SiteSetting.user_api_key_clients_create_per_day,
24.hours,
).performed!
end
def require_params

View File

@ -2381,6 +2381,11 @@ rate_limits:
max_uploads_per_minute:
default: 10
hidden: true
user_api_key_clients_create_per_day:
default: 3
min: 1
max: 10
hidden: true
developer:
force_hostname:
@ -3168,6 +3173,10 @@ user_api:
default: 30
max: 36500
hidden: true
create_user_api_key_client_ip_rate_limit_override_ips:
default: ""
type: list
hidden: true
tags:
tagging_enabled:

View File

@ -84,6 +84,45 @@ RSpec.describe UserApiKeyClientsController do
expect(response.status).to eq(403)
end
end
context "with rate limiting" do
before { RateLimiter.enable }
it "works" do
SiteSetting.user_api_key_clients_create_per_day = 1
post "/user-api-key-client.json", params: args_with_scopes
expect(response.status).to eq(200)
post "/user-api-key-client.json",
params: args_with_scopes.merge(client_id: "another_client1")
expect(response.status).to eq(429)
end
it "can be changed via site setting" do
SiteSetting.user_api_key_clients_create_per_day = 2
post "/user-api-key-client.json", params: args_with_scopes
expect(response.status).to eq(200)
post "/user-api-key-client.json",
params: args_with_scopes.merge(client_id: "another_client1")
expect(response.status).to eq(200)
post "/user-api-key-client.json",
params: args_with_scopes.merge(client_id: "another_client2")
expect(response.status).to eq(429)
end
it "can be overriden by ip address set in a site setting" do
SiteSetting.user_api_key_clients_create_per_day = 1
SiteSetting.create_user_api_key_client_ip_rate_limit_override_ips = "1.2.3.4"
post "/user-api-key-client.json", params: args_with_scopes
expect(response.status).to eq(200)
post "/user-api-key-client.json",
params: args_with_scopes.merge(client_id: "another_client1"),
env: {
REMOTE_ADDR: "1.2.3.4",
}
expect(response.status).to eq(200)
end
end
end
end
end