diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2022-01-20 09:16:11 +0000 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2022-01-20 09:16:11 +0000 |
commit | edaa33dee2ff2f7ea3fac488d41558eb5f86d68c (patch) | |
tree | 11f143effbfeba52329fb7afbd05e6e2a3790241 /spec/support/shared_examples/controllers/rate_limited_endpoint_shared_examples.rb | |
parent | d8a5691316400a0f7ec4f83832698f1988eb27c1 (diff) | |
download | gitlab-ce-76a9e64d004e0c02c35b8165ca38d005afb5e823.tar.gz |
Add latest changes from gitlab-org/gitlab@14-7-stable-eev14.7.0-rc42
Diffstat (limited to 'spec/support/shared_examples/controllers/rate_limited_endpoint_shared_examples.rb')
-rw-r--r-- | spec/support/shared_examples/controllers/rate_limited_endpoint_shared_examples.rb | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/spec/support/shared_examples/controllers/rate_limited_endpoint_shared_examples.rb b/spec/support/shared_examples/controllers/rate_limited_endpoint_shared_examples.rb new file mode 100644 index 00000000000..bb2a4159071 --- /dev/null +++ b/spec/support/shared_examples/controllers/rate_limited_endpoint_shared_examples.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true +# +# Requires a context containing: +# - request (use method definition to avoid memoizing!) +# - current_user +# - error_message # optional + +RSpec.shared_examples 'rate limited endpoint' do |rate_limit_key:| + context 'when rate limiter enabled', :freeze_time, :clean_gitlab_redis_rate_limiting do + let(:expected_logger_attributes) do + { + message: 'Application_Rate_Limiter_Request', + env: :"#{rate_limit_key}_request_limit", + remote_ip: kind_of(String), + request_method: kind_of(String), + path: kind_of(String), + user_id: current_user.id, + username: current_user.username + } + end + + let(:error_message) { _('This endpoint has been requested too many times. Try again later.') } + + before do + allow(Gitlab::ApplicationRateLimiter).to receive(:threshold).with(rate_limit_key).and_return(1) + end + + it 'logs request and declines it when endpoint called more than the threshold' do |example| + expect(Gitlab::AuthLogger).to receive(:error).with(expected_logger_attributes).once + + request + request + + expect(response).to have_gitlab_http_status(:too_many_requests) + + if example.metadata[:type] == :controller + expect(response.body).to eq(error_message) + else # it is API spec + expect(response.body).to eq({ message: { error: error_message } }.to_json) + end + end + end + + context 'when rate limiter is disabled' do + before do + allow(Gitlab::ApplicationRateLimiter).to receive(:threshold).with(rate_limit_key).and_return(0) + end + + it 'does not log request and does not block the request' do + expect(Gitlab::AuthLogger).not_to receive(:error) + + request + + expect(response).not_to have_gitlab_http_status(:too_many_requests) + end + end +end |