2019-12-05 16:07:40 -05:00
# frozen_string_literal: true
module Gitlab
2022-01-21 10:13:54 -05:00
# This module implements a simple rate limiter that can be used to throttle
2019-12-05 16:07:40 -05:00
# certain actions. Unlike Rack Attack and Rack::Throttle, which operate at
# the middleware level, this can be used at the controller or API level.
2021-12-10 10:10:24 -05:00
# See CheckRateLimit concern for usage.
2022-01-21 10:13:54 -05:00
module ApplicationRateLimiter
2021-11-02 11:12:22 -04:00
InvalidKeyError = Class . new ( StandardError )
2019-12-05 16:07:40 -05:00
class << self
# Application rate limits
#
# Threshold value can be either an Integer or a Proc
# in order to not evaluate it's value every time this method is called
# and only do that when it's needed.
2022-02-08 13:16:03 -05:00
def rate_limits # rubocop:disable Metrics/AbcSize
2019-12-05 16:07:40 -05:00
{
2020-07-07 11:08:49 -04:00
issues_create : { threshold : - > { application_settings . issues_create_limit } , interval : 1 . minute } ,
2021-02-09 16:09:19 -05:00
notes_create : { threshold : - > { application_settings . notes_create_limit } , interval : 1 . minute } ,
2020-07-07 11:08:49 -04:00
project_export : { threshold : - > { application_settings . project_export_limit } , interval : 1 . minute } ,
project_download_export : { threshold : - > { application_settings . project_download_export_limit } , interval : 1 . minute } ,
2020-02-22 07:08:58 -05:00
project_repositories_archive : { threshold : 5 , interval : 1 . minute } ,
2020-07-07 11:08:49 -04:00
project_generate_new_export : { threshold : - > { application_settings . project_export_limit } , interval : 1 . minute } ,
project_import : { threshold : - > { application_settings . project_import_limit } , interval : 1 . minute } ,
2020-08-28 11:10:21 -04:00
project_testing_hook : { threshold : 5 , interval : 1 . minute } ,
2020-07-07 11:08:49 -04:00
play_pipeline_schedule : { threshold : 1 , interval : 1 . minute } ,
2021-12-10 10:10:24 -05:00
raw_blob : { threshold : - > { application_settings . raw_blob_request_limit } , interval : 1 . minute } ,
2020-07-07 11:08:49 -04:00
group_export : { threshold : - > { application_settings . group_export_limit } , interval : 1 . minute } ,
group_download_export : { threshold : - > { application_settings . group_download_export_limit } , interval : 1 . minute } ,
2020-08-28 11:10:21 -04:00
group_import : { threshold : - > { application_settings . group_import_limit } , interval : 1 . minute } ,
2020-10-01 14:10:20 -04:00
group_testing_hook : { threshold : 5 , interval : 1 . minute } ,
profile_add_new_email : { threshold : 5 , interval : 1 . minute } ,
2021-05-14 05:10:24 -04:00
web_hook_calls : { interval : 1 . minute } ,
2022-02-08 13:16:03 -05:00
users_get_by_id : { threshold : - > { application_settings . users_get_by_id_limit } , interval : 10 . minutes } ,
2022-01-06 07:14:04 -05:00
username_exists : { threshold : 20 , interval : 1 . minute } ,
2022-01-12 07:14:10 -05:00
user_sign_up : { threshold : 20 , interval : 1 . minute } ,
2020-11-08 22:09:03 -05:00
profile_resend_email_confirmation : { threshold : 5 , interval : 1 . minute } ,
2022-01-05 19:15:57 -05:00
profile_update_username : { threshold : 10 , interval : 1 . minute } ,
2020-11-20 01:09:10 -05:00
update_environment_canary_ingress : { threshold : 1 , interval : 1 . minute } ,
2021-12-20 13:13:27 -05:00
auto_rollback_deployment : { threshold : 1 , interval : 3 . minutes } ,
2022-03-14 02:07:47 -04:00
search_rate_limit : { threshold : - > { application_settings . search_rate_limit } , interval : 1 . minute } ,
search_rate_limit_unauthenticated : { threshold : - > { application_settings . search_rate_limit_unauthenticated } , interval : 1 . minute } ,
2022-01-18 13:11:20 -05:00
gitlab_shell_operation : { threshold : 600 , interval : 1 . minute }
2019-12-05 16:07:40 -05:00
} . freeze
end
# Increments the given key and returns true if the action should
# be throttled.
#
# @param key [Symbol] Key attribute registered in `.rate_limits`
2022-01-18 13:11:20 -05:00
# @param scope [Array<ActiveRecord>] Array of ActiveRecord models, Strings or Symbols to scope throttling to a specific request (e.g. per user per project)
2021-12-06 16:10:14 -05:00
# @param threshold [Integer] Optional threshold value to override default one registered in `.rate_limits`
# @param users_allowlist [Array<String>] Optional list of usernames to exclude from the limit. This param will only be functional if Scope includes a current user.
# @param peek [Boolean] Optional. When true the key will not be incremented but the current throttled state will be returned.
2019-12-05 16:07:40 -05:00
#
# @return [Boolean] Whether or not a request should be throttled
2021-12-06 16:10:14 -05:00
def throttled? ( key , scope : , threshold : nil , users_allowlist : nil , peek : false )
2021-11-02 11:12:22 -04:00
raise InvalidKeyError unless rate_limits [ key ]
2019-12-05 16:07:40 -05:00
2021-12-06 16:10:14 -05:00
return false if scoped_user_in_allowlist? ( scope , users_allowlist )
2019-12-05 16:07:40 -05:00
2021-12-06 16:10:14 -05:00
threshold_value = threshold || threshold ( key )
2019-12-05 16:07:40 -05:00
2021-12-06 16:10:14 -05:00
return false if threshold_value == 0
2021-11-03 14:13:40 -04:00
2021-12-06 16:10:14 -05:00
interval_value = interval ( key )
# `period_key` is based on the current time and interval so when time passes to the next interval
# the key changes and the rate limit count starts again from 0.
# Based on https://github.com/rack/rack-attack/blob/886ba3a18d13c6484cd511a4dc9b76c0d14e5e96/lib/rack/attack/cache.rb#L63-L68
2021-11-03 14:13:40 -04:00
period_key , time_elapsed_in_period = Time . now . to_i . divmod ( interval_value )
2021-12-06 16:10:14 -05:00
cache_key = cache_key ( key , scope , period_key )
2021-11-03 14:13:40 -04:00
2021-12-06 16:10:14 -05:00
value = if peek
read ( cache_key )
else
increment ( cache_key , interval_value , time_elapsed_in_period )
end
2021-11-03 14:13:40 -04:00
2021-12-06 16:10:14 -05:00
value > threshold_value
end
# Returns the current rate limited state without incrementing the count.
#
# @param key [Symbol] Key attribute registered in `.rate_limits`
# @param scope [Array<ActiveRecord>] Array of ActiveRecord models to scope throttling to a specific request (e.g. per user per project)
# @param threshold [Integer] Optional threshold value to override default one registered in `.rate_limits`
# @param users_allowlist [Array<String>] Optional list of usernames to exclude from the limit. This param will only be functional if Scope includes a current user.
#
# @return [Boolean] Whether or not a request is currently throttled
def peek ( key , scope : , threshold : nil , users_allowlist : nil )
throttled? ( key , peek : true , scope : scope , threshold : threshold , users_allowlist : users_allowlist )
2021-11-03 14:13:40 -04:00
end
2019-12-05 16:07:40 -05:00
# Logs request using provided logger
#
# @param request [Http::Request] - Web request to be logged
# @param type [Symbol] A symbol key that represents the request
# @param current_user [User] Current user of the request, it can be nil
# @param logger [Logger] Logger to log request to a specific log file. Defaults to Gitlab::AuthLogger
def log_request ( request , type , current_user , logger = Gitlab :: AuthLogger )
request_information = {
message : 'Application_Rate_Limiter_Request' ,
env : type ,
remote_ip : request . ip ,
request_method : request . request_method ,
path : request . fullpath
}
if current_user
request_information . merge! ( {
user_id : current_user . id ,
username : current_user . username
} )
end
logger . error ( request_information )
end
private
def threshold ( key )
value = rate_limit_value_by_key ( key , :threshold )
return value . call if value . is_a? ( Proc )
value . to_i
end
def interval ( key )
rate_limit_value_by_key ( key , :interval ) . to_i
end
def rate_limit_value_by_key ( key , setting )
action = rate_limits [ key ]
action [ setting ] if action
end
2021-12-06 16:10:14 -05:00
# Increments the rate limit count and returns the new count value.
def increment ( cache_key , interval_value , time_elapsed_in_period )
# We add a 1 second buffer to avoid timing issues when we're at the end of a period
expiry = interval_value - time_elapsed_in_period + 1
:: Gitlab :: Redis :: RateLimiting . with do | redis |
redis . pipelined do
redis . incr ( cache_key )
redis . expire ( cache_key , expiry )
end . first
end
end
# Returns the rate limit count.
# Will be 0 if there is no data in the cache.
def read ( cache_key )
:: Gitlab :: Redis :: RateLimiting . with do | redis |
redis . get ( cache_key ) . to_i
end
end
def cache_key ( key , scope , period_key )
2019-12-05 16:07:40 -05:00
composed_key = [ key , scope ] . flatten . compact
serialized = composed_key . map do | obj |
if obj . is_a? ( String ) || obj . is_a? ( Symbol )
" #{ obj } "
else
" #{ obj . class . model_name . to_s . underscore } : #{ obj . id } "
end
end . join ( " : " )
2021-12-06 16:10:14 -05:00
" application_rate_limiter: #{ serialized } : #{ period_key } "
2019-12-05 16:07:40 -05:00
end
2020-07-07 11:08:49 -04:00
def application_settings
Gitlab :: CurrentSettings . current_application_settings
end
2021-02-11 07:08:52 -05:00
2021-12-06 16:10:14 -05:00
def scoped_user_in_allowlist? ( scope , users_allowlist )
return unless users_allowlist . present?
2021-02-11 07:08:52 -05:00
2021-12-06 16:10:14 -05:00
scoped_user = [ scope ] . flatten . find { | s | s . is_a? ( User ) }
2021-02-11 07:08:52 -05:00
return unless scoped_user
2021-12-06 16:10:14 -05:00
scoped_user . username . downcase . in? ( users_allowlist )
2021-02-11 07:08:52 -05:00
end
2019-12-05 16:07:40 -05:00
end
end
end