rate_guard 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +44 -0
- data/LICENSE +21 -0
- data/README.md +237 -0
- data/lib/rate_guard/admission.rb +13 -0
- data/lib/rate_guard/algorithms/fixed_window_counter.rb +83 -0
- data/lib/rate_guard/algorithms/leaky_bucket_meter.rb +93 -0
- data/lib/rate_guard/algorithms/leaky_bucket_queue.rb +93 -0
- data/lib/rate_guard/algorithms/redis_sliding_window_counter.rb +137 -0
- data/lib/rate_guard/algorithms/sliding_window_counter.lua +60 -0
- data/lib/rate_guard/algorithms/sliding_window_counter.rb +148 -0
- data/lib/rate_guard/algorithms/sliding_window_log.rb +105 -0
- data/lib/rate_guard/algorithms/token_bucket.rb +93 -0
- data/lib/rate_guard/bypass.rb +39 -0
- data/lib/rate_guard/clock.rb +20 -0
- data/lib/rate_guard/configuration.rb +77 -0
- data/lib/rate_guard/errors.rb +9 -0
- data/lib/rate_guard/identifiers/api_key.rb +36 -0
- data/lib/rate_guard/identifiers/first_of.rb +28 -0
- data/lib/rate_guard/identifiers/global.rb +14 -0
- data/lib/rate_guard/identifiers/ip.rb +19 -0
- data/lib/rate_guard/identifiers/user.rb +34 -0
- data/lib/rate_guard/identifiers.rb +17 -0
- data/lib/rate_guard/json_log_formatter.rb +29 -0
- data/lib/rate_guard/metrics.rb +49 -0
- data/lib/rate_guard/middleware/client_ip.rb +40 -0
- data/lib/rate_guard/middleware.rb +147 -0
- data/lib/rate_guard/policy.rb +129 -0
- data/lib/rate_guard/policy_set.rb +59 -0
- data/lib/rate_guard/redis_error_reporter.rb +51 -0
- data/lib/rate_guard/registry.rb +109 -0
- data/lib/rate_guard/request.rb +7 -0
- data/lib/rate_guard/result.rb +17 -0
- data/lib/rate_guard/tiers.rb +25 -0
- data/lib/rate_guard/utils/numeric_utils.rb +22 -0
- data/lib/rate_guard/validators/configuration_validator.rb +28 -0
- data/lib/rate_guard/validators/cost_validator.rb +36 -0
- data/lib/rate_guard/version.rb +5 -0
- data/lib/rate_guard.rb +84 -0
- metadata +105 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'digest'
|
|
4
|
+
|
|
5
|
+
module RateGuard
|
|
6
|
+
module Identifiers
|
|
7
|
+
# Identifies a request by its X-API-Key header: "key:<digest>".
|
|
8
|
+
# Only a short SHA-256 digest is kept, never the key itself.
|
|
9
|
+
#
|
|
10
|
+
# Pass verify: so unknown keys return nil. Otherwise a client could
|
|
11
|
+
# send a new random key each time to get a fresh limit.
|
|
12
|
+
class ApiKey
|
|
13
|
+
DIGEST_LENGTH = 16
|
|
14
|
+
|
|
15
|
+
def initialize(header: 'X-API-Key', verify: nil)
|
|
16
|
+
raise ArgumentError, 'verify must respond to #call' unless verify.nil? || verify.respond_to?(:call)
|
|
17
|
+
|
|
18
|
+
@env_key = "HTTP_#{header.upcase.tr('-', '_')}"
|
|
19
|
+
@verify = verify
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def call(env)
|
|
23
|
+
api_key = env[@env_key].to_s.strip
|
|
24
|
+
return if api_key.empty?
|
|
25
|
+
return if @verify && !@verify.call(api_key)
|
|
26
|
+
|
|
27
|
+
key_for(api_key)
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# The key an API key is counted under, e.g. to map keys to plans.
|
|
31
|
+
def key_for(api_key)
|
|
32
|
+
"key:#{Digest::SHA256.hexdigest(api_key)[0, DIGEST_LENGTH]}"
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RateGuard
|
|
4
|
+
module Identifiers
|
|
5
|
+
# Returns the first key found, e.g. user, then API key, then IP:
|
|
6
|
+
#
|
|
7
|
+
# FirstOf.new(User.new, ApiKey.new(verify: ...), Ip.new)
|
|
8
|
+
class FirstOf
|
|
9
|
+
def initialize(*identifiers)
|
|
10
|
+
raise ArgumentError, 'FirstOf needs at least one identifier' if identifiers.empty?
|
|
11
|
+
|
|
12
|
+
identifiers.each do |identifier|
|
|
13
|
+
raise ArgumentError, "#{identifier.inspect} does not respond to #call" unless identifier.respond_to?(:call)
|
|
14
|
+
end
|
|
15
|
+
@identifiers = identifiers.freeze
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def call(env)
|
|
19
|
+
@identifiers.each do |identifier|
|
|
20
|
+
key = identifier.call(env)
|
|
21
|
+
return key unless key.nil? || key.empty?
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
nil
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative '../middleware/client_ip'
|
|
4
|
+
|
|
5
|
+
module RateGuard
|
|
6
|
+
module Identifiers
|
|
7
|
+
# Identifies a request by client IP: "ip:<address>" (see ClientIp).
|
|
8
|
+
class Ip
|
|
9
|
+
def initialize(client_ip: Middleware::ClientIp.new)
|
|
10
|
+
@client_ip = client_ip
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def call(env)
|
|
14
|
+
address = @client_ip.call(env).to_s
|
|
15
|
+
address.empty? ? nil : "ip:#{address}"
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
end
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RateGuard
|
|
4
|
+
module Identifiers
|
|
5
|
+
# Identifies a request by the logged-in user: "user:<id>".
|
|
6
|
+
# `from:` is an env key set by your auth middleware, or a callable(env).
|
|
7
|
+
# HTTP_* keys are refused: they are headers, which clients can fake.
|
|
8
|
+
class User
|
|
9
|
+
DEFAULT_ENV_KEY = 'rate_guard.user_id'
|
|
10
|
+
|
|
11
|
+
def initialize(from: DEFAULT_ENV_KEY)
|
|
12
|
+
@resolver = resolver_for(from)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def call(env)
|
|
16
|
+
id = @resolver.call(env)
|
|
17
|
+
id.nil? || id.to_s.empty? ? nil : "user:#{id}"
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
private
|
|
21
|
+
|
|
22
|
+
def resolver_for(from)
|
|
23
|
+
return from if from.respond_to?(:call)
|
|
24
|
+
raise ArgumentError, 'from must be an env key (String) or respond to #call' unless from.is_a?(String)
|
|
25
|
+
if from.upcase.start_with?('HTTP_')
|
|
26
|
+
raise ArgumentError, "#{from} is a request header that any client can forge; " \
|
|
27
|
+
'use a key set by your authentication'
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
->(env) { env[from] }
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RateGuard
|
|
4
|
+
# Identifiers decide who a request counts against.
|
|
5
|
+
#
|
|
6
|
+
# Any object with #call(env) returning a prefixed key
|
|
7
|
+
# ("ip:203.0.113.7", "user:42") or nil. The prefix keeps kinds apart.
|
|
8
|
+
# Keys are stored and logged, so they must never contain secrets.
|
|
9
|
+
module Identifiers
|
|
10
|
+
end
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
require_relative 'identifiers/ip'
|
|
14
|
+
require_relative 'identifiers/api_key'
|
|
15
|
+
require_relative 'identifiers/user'
|
|
16
|
+
require_relative 'identifiers/first_of'
|
|
17
|
+
require_relative 'identifiers/global'
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
require 'time'
|
|
5
|
+
|
|
6
|
+
module RateGuard
|
|
7
|
+
# Logger formatter that writes one JSON object per line:
|
|
8
|
+
#
|
|
9
|
+
# logger.warn(event: 'rate_limited', policy: 'login')
|
|
10
|
+
# # => {"time":"...","level":"warn","event":"rate_limited","policy":"login"}
|
|
11
|
+
#
|
|
12
|
+
# Non-Hash messages go under "message".
|
|
13
|
+
class JsonLogFormatter
|
|
14
|
+
# A Logger writing JSON lines to `io`. Requires the logger gem.
|
|
15
|
+
# Turns off buffering so lines show up at once in Docker.
|
|
16
|
+
def self.logger(io = $stdout, level: :info)
|
|
17
|
+
require 'logger'
|
|
18
|
+
io.sync = true if io.respond_to?(:sync=)
|
|
19
|
+
Logger.new(io, level:, formatter: new)
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def call(severity, time, progname, message)
|
|
23
|
+
fields = message.is_a?(Hash) ? message : { message: message.to_s }
|
|
24
|
+
head = { time: time.utc.iso8601(3), level: severity.downcase, progname: progname }.compact
|
|
25
|
+
|
|
26
|
+
"#{JSON.generate(head.merge(fields))}\n"
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RateGuard
|
|
4
|
+
# Metrics interface. Any object with these two methods works:
|
|
5
|
+
#
|
|
6
|
+
# increment(name, tags = {})
|
|
7
|
+
# timing(name, seconds, tags = {})
|
|
8
|
+
#
|
|
9
|
+
# Names: rate_guard.allowed, .rejected, .bypassed, .redis_errors, .decision
|
|
10
|
+
module Metrics
|
|
11
|
+
# Default: records nothing.
|
|
12
|
+
class Null
|
|
13
|
+
def increment(_name, _tags = {}) = nil
|
|
14
|
+
def timing(_name, _seconds, _tags = {}) = nil
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# Keeps metrics in memory. For tests. Thread-safe.
|
|
18
|
+
class InMemory
|
|
19
|
+
def initialize
|
|
20
|
+
@counters = Hash.new(0)
|
|
21
|
+
@timings = Hash.new { |hash, key| hash[key] = [] }
|
|
22
|
+
@mutex = Mutex.new
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def increment(name, tags = {})
|
|
26
|
+
@mutex.synchronize { @counters[[name, tags.freeze]] += 1 }
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def timing(name, seconds, tags = {})
|
|
30
|
+
@mutex.synchronize { @timings[[name, tags.freeze]] << seconds }
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Total for `name` across entries matching `tags`.
|
|
34
|
+
def count(name, **tags)
|
|
35
|
+
@mutex.synchronize { matching(@counters, name, tags).sum { |_key, value| value } }
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def timings(name, **tags)
|
|
39
|
+
@mutex.synchronize { matching(@timings, name, tags).flat_map { |_key, values| values } }
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
def matching(store, name, tags)
|
|
45
|
+
store.select { |(entry_name, entry_tags), _| entry_name == name && tags <= entry_tags }
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'ipaddr'
|
|
4
|
+
|
|
5
|
+
module RateGuard
|
|
6
|
+
class Middleware
|
|
7
|
+
# Finds the real client IP.
|
|
8
|
+
# Uses REMOTE_ADDR unless the request came from a trusted proxy;
|
|
9
|
+
# then reads X-Forwarded-For right to left and takes the first
|
|
10
|
+
# untrusted address. Clients can't fake it.
|
|
11
|
+
class ClientIp
|
|
12
|
+
def initialize(trusted_proxies: [])
|
|
13
|
+
# Bad proxy addresses raise here, at boot.
|
|
14
|
+
@trusted_proxies = trusted_proxies.map { |proxy| IPAddr.new(proxy) }.freeze
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def call(env)
|
|
18
|
+
remote_addr = env['REMOTE_ADDR'].to_s
|
|
19
|
+
return remote_addr unless trusted?(remote_addr)
|
|
20
|
+
|
|
21
|
+
chain = env['HTTP_X_FORWARDED_FOR'].to_s.split(',').map(&:strip).reject(&:empty?)
|
|
22
|
+
return remote_addr if chain.empty?
|
|
23
|
+
|
|
24
|
+
chain.reverse_each { |addr| return addr unless trusted?(addr) }
|
|
25
|
+
|
|
26
|
+
# All hops were trusted proxies: use the furthest one.
|
|
27
|
+
chain.first
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
private
|
|
31
|
+
|
|
32
|
+
def trusted?(addr)
|
|
33
|
+
ip = IPAddr.new(addr)
|
|
34
|
+
@trusted_proxies.any? { |range| range.family == ip.family && range.include?(ip) }
|
|
35
|
+
rescue IPAddr::Error
|
|
36
|
+
false
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'rack'
|
|
4
|
+
require_relative 'clock'
|
|
5
|
+
require_relative 'metrics'
|
|
6
|
+
require_relative 'middleware/client_ip'
|
|
7
|
+
require_relative 'identifiers'
|
|
8
|
+
require_relative 'request'
|
|
9
|
+
require_relative 'policy_set'
|
|
10
|
+
|
|
11
|
+
module RateGuard
|
|
12
|
+
# Rack middleware. Asks the policies about each request, then adds
|
|
13
|
+
# RateLimit-* headers, rejects with 429, logs and records metrics.
|
|
14
|
+
class Middleware
|
|
15
|
+
CLIENT_KEY = 'rate_guard.client_key'
|
|
16
|
+
RESULT_KEY = 'rate_guard.result'
|
|
17
|
+
POLICY_KEY = 'rate_guard.policy'
|
|
18
|
+
DECISION_KEY = 'rate_guard.decision'
|
|
19
|
+
BYPASSED_KEY = 'rate_guard.bypassed'
|
|
20
|
+
|
|
21
|
+
UNIDENTIFIED_KEY = Policy::UNIDENTIFIED_KEY
|
|
22
|
+
|
|
23
|
+
# Float math can give 10.000000000000002; don't round that up to 11.
|
|
24
|
+
ROUNDING_TOLERANCE = 1e-9
|
|
25
|
+
|
|
26
|
+
# Default 429 response. Headers are added to any responder's response.
|
|
27
|
+
DEFAULT_RESPONDER = lambda do |_env, _result, _policy|
|
|
28
|
+
[429, { 'content-type' => 'text/plain' }, ["Too Many Requests\n"]]
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# policies - a PolicySet, or use limiter + paths for a single rule
|
|
32
|
+
# limiter - an immediate limiter
|
|
33
|
+
# paths - paths it applies to
|
|
34
|
+
# identifier - who a request counts against (default: client IP)
|
|
35
|
+
# client_ip - old option; prefer identifier: Identifiers::Ip.new(client_ip:)
|
|
36
|
+
# responder - callable(env, result, policy) returning the 429 response
|
|
37
|
+
# logger - a Logger, or nil for no logs
|
|
38
|
+
# metrics - see RateGuard::Metrics
|
|
39
|
+
# clock - times each decision
|
|
40
|
+
def initialize(app, policies: nil, limiter: nil, paths: nil, identifier: nil, client_ip: nil,
|
|
41
|
+
responder: DEFAULT_RESPONDER, logger: nil, metrics: Metrics::Null.new, clock: Clock::Monotonic)
|
|
42
|
+
@app = app
|
|
43
|
+
@policies = policies || single_policy(limiter, paths, identifier, client_ip)
|
|
44
|
+
raise ArgumentError, 'pass policies: or limiter:/paths:, not both' if policies && (limiter || paths)
|
|
45
|
+
raise ArgumentError, 'policies must be a RateGuard::PolicySet' unless @policies.is_a?(PolicySet)
|
|
46
|
+
raise ArgumentError, 'responder must respond to #call' unless responder.respond_to?(:call)
|
|
47
|
+
|
|
48
|
+
@responder = responder
|
|
49
|
+
@logger = logger
|
|
50
|
+
@metrics = metrics
|
|
51
|
+
@clock = clock
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def call(env)
|
|
55
|
+
request = Request.new(http_method: env['REQUEST_METHOD'].to_s.upcase,
|
|
56
|
+
path: normalize(env['PATH_INFO'].to_s), env: env)
|
|
57
|
+
started = @clock.now
|
|
58
|
+
decision = @policies.decide(request)
|
|
59
|
+
return @app.call(env) unless decision.matched?
|
|
60
|
+
return bypass(env) if decision.bypassed?
|
|
61
|
+
|
|
62
|
+
reported = record(env, decision)
|
|
63
|
+
report(request, decision, reported, @clock.now - started)
|
|
64
|
+
return reject(env, reported) unless decision.allowed?
|
|
65
|
+
|
|
66
|
+
status, headers, body = @app.call(env)
|
|
67
|
+
[status, headers.merge(rate_limit_headers(reported)), body]
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
private
|
|
71
|
+
|
|
72
|
+
def single_policy(limiter, paths, identifier, client_ip)
|
|
73
|
+
raise ArgumentError, 'pass policies:, or limiter: and paths:' if limiter.nil? || paths.nil?
|
|
74
|
+
raise ArgumentError, 'pass identifier: or client_ip:, not both' if identifier && client_ip
|
|
75
|
+
|
|
76
|
+
identifier ||= Identifiers::Ip.new(client_ip: client_ip || ClientIp.new)
|
|
77
|
+
raise ArgumentError, "identifier must respond to #call (got #{identifier.class})" unless
|
|
78
|
+
identifier.respond_to?(:call)
|
|
79
|
+
|
|
80
|
+
PolicySet.new(Policy.new(name: 'default', limiter:, identifier:, paths: paths.map { |path| normalize(path) }))
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Trusted clients: not limited, so no RateLimit-* headers.
|
|
84
|
+
def bypass(env)
|
|
85
|
+
env[BYPASSED_KEY] = true
|
|
86
|
+
@metrics.increment('rate_guard.bypassed')
|
|
87
|
+
@app.call(env)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def record(env, decision)
|
|
91
|
+
reported = decision.reported
|
|
92
|
+
env[DECISION_KEY] = decision
|
|
93
|
+
env[POLICY_KEY] = reported.policy.name
|
|
94
|
+
env[CLIENT_KEY] = reported.key
|
|
95
|
+
env[RESULT_KEY] = reported.result
|
|
96
|
+
reported
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# Metrics for every request; a log line only for rejections.
|
|
100
|
+
# Keys are digests for API keys, so no secret is logged.
|
|
101
|
+
def report(request, decision, outcome, elapsed)
|
|
102
|
+
tags = { policy: outcome.policy.name, algorithm: outcome.algorithm }
|
|
103
|
+
@metrics.timing('rate_guard.decision', elapsed, tags)
|
|
104
|
+
@metrics.increment(decision.allowed? ? 'rate_guard.allowed' : 'rate_guard.rejected', tags)
|
|
105
|
+
return if decision.allowed? || @logger.nil?
|
|
106
|
+
|
|
107
|
+
@logger.warn(event: 'rate_limited', policy: outcome.policy.name, key: outcome.key, path: request.path,
|
|
108
|
+
method: request.http_method, limit: outcome.limit, remaining: outcome.result.remaining,
|
|
109
|
+
retry_after: outcome.result.retry_after.round(3), algorithm: outcome.algorithm)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def reject(env, outcome)
|
|
113
|
+
status, headers, body = @responder.call(env, outcome.result, outcome.policy)
|
|
114
|
+
retry_after = { 'retry-after' => whole_seconds(outcome.result.retry_after) }
|
|
115
|
+
|
|
116
|
+
[status, headers.merge(retry_after, rate_limit_headers(outcome)), body]
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# New Hash per response. ratelimit-reset only if the limiter reports it.
|
|
120
|
+
def rate_limit_headers(outcome)
|
|
121
|
+
result = outcome.result
|
|
122
|
+
headers = {
|
|
123
|
+
'ratelimit-limit' => outcome.limit.to_s,
|
|
124
|
+
'ratelimit-remaining' => result.remaining.to_s
|
|
125
|
+
}
|
|
126
|
+
headers['ratelimit-reset'] = whole_seconds(result.reset_after) unless result.reset_after.nil?
|
|
127
|
+
headers
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# Whole seconds, rounded up, ignoring float noise.
|
|
131
|
+
def whole_seconds(seconds)
|
|
132
|
+
(seconds - ROUNDING_TOLERANCE).ceil.to_s
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def normalize(path)
|
|
136
|
+
decoded = Rack::Utils.unescape_path(path.b).tr('\\', '/')
|
|
137
|
+
|
|
138
|
+
segments = decoded.split('/').each_with_object([]) do |segment, kept|
|
|
139
|
+
next if segment.empty? || segment == '.'
|
|
140
|
+
|
|
141
|
+
segment == '..' ? kept.pop : kept << segment
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
"/#{segments.join('/')}"
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
end
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative 'identifiers'
|
|
4
|
+
require_relative 'tiers'
|
|
5
|
+
|
|
6
|
+
module RateGuard
|
|
7
|
+
# One rule: which requests, who they count against, their cost,
|
|
8
|
+
# and the limiter that decides.
|
|
9
|
+
class Policy
|
|
10
|
+
# Key for requests no identifier recognizes, so they are still limited.
|
|
11
|
+
UNIDENTIFIED_KEY = 'anonymous'
|
|
12
|
+
|
|
13
|
+
PRIORITIES = %i[high low].freeze
|
|
14
|
+
|
|
15
|
+
# Result of one policy for one request.
|
|
16
|
+
Outcome = Data.define(:policy, :key, :limit, :cost, :algorithm, :result) do
|
|
17
|
+
def allowed? = result.allowed?
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Algorithms::TokenBucket -> "token_bucket"; anonymous class -> "custom".
|
|
21
|
+
def self.algorithm_name(limiter)
|
|
22
|
+
name = limiter.class.name.to_s.split('::').last.to_s
|
|
23
|
+
name.empty? ? 'custom' : name.gsub(/([a-z\d])([A-Z])/, '\\1_\\2').downcase
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
attr_reader :name
|
|
27
|
+
|
|
28
|
+
# name - unique name, used in logs and metrics
|
|
29
|
+
# limiter - an immediate limiter, or a Tiers
|
|
30
|
+
# methods - e.g. %w[GET]; nil means all
|
|
31
|
+
# paths - e.g. %w[/login]; nil means all
|
|
32
|
+
# match - callable(request) -> true/false, instead of methods/paths
|
|
33
|
+
# identifier - callable(env) -> key or nil (default: client IP)
|
|
34
|
+
# cost - Integer or callable(env); never more than the limit
|
|
35
|
+
# priority - callable(env) -> :high or :low (default: all :high)
|
|
36
|
+
# reserve - units :low requests can't use
|
|
37
|
+
def initialize(name:, limiter:, methods: nil, paths: nil, match: nil, identifier: Identifiers::Ip.new,
|
|
38
|
+
cost: 1, priority: nil, reserve: 0)
|
|
39
|
+
@name = name.to_s
|
|
40
|
+
@selector = limiter.is_a?(Tiers) ? limiter : Tiers.new(name => limiter) { name }
|
|
41
|
+
@matcher = build_matcher(methods, paths, match)
|
|
42
|
+
@identifier = callable!(identifier, 'identifier')
|
|
43
|
+
@cost = cost.respond_to?(:call) ? cost : fixed_cost!(cost)
|
|
44
|
+
@priority = priority.nil? ? nil : callable!(priority, 'priority')
|
|
45
|
+
@reserve = reserve
|
|
46
|
+
validate_limiters!
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def matches?(request) = @matcher.call(request)
|
|
50
|
+
|
|
51
|
+
def apply(request)
|
|
52
|
+
env = request.env
|
|
53
|
+
key = identify(env)
|
|
54
|
+
limiter = @selector.select(key, env)
|
|
55
|
+
cost = [@cost.respond_to?(:call) ? @cost.call(env) : @cost, limiter.limit].min
|
|
56
|
+
reserve = low_priority?(env) ? [@reserve, limiter.limit - cost].min : 0
|
|
57
|
+
result = reserve.zero? ? limiter.acquire(key, cost:) : limiter.acquire(key, cost:, reserve:)
|
|
58
|
+
|
|
59
|
+
Outcome.new(policy: self, key:, limit: limiter.limit, cost:, algorithm: Policy.algorithm_name(limiter), result:)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
private
|
|
63
|
+
|
|
64
|
+
def identify(env)
|
|
65
|
+
key = @identifier.call(env)
|
|
66
|
+
key.nil? || key.empty? ? UNIDENTIFIED_KEY : key
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def low_priority?(env)
|
|
70
|
+
return false if @priority.nil? || @reserve.zero?
|
|
71
|
+
|
|
72
|
+
priority = @priority.call(env)
|
|
73
|
+
raise ArgumentError, "priority must return one of #{PRIORITIES.inspect} (got #{priority.inspect})" unless
|
|
74
|
+
PRIORITIES.include?(priority)
|
|
75
|
+
|
|
76
|
+
priority == :low
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def build_matcher(methods, paths, match)
|
|
80
|
+
if match
|
|
81
|
+
raise ArgumentError, 'pass match: or methods:/paths:, not both' if methods || paths
|
|
82
|
+
|
|
83
|
+
return callable!(match, 'match')
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
verbs = methods&.map { |verb| verb.to_s.upcase }&.freeze
|
|
87
|
+
routes = paths&.map { |path| canonical_path!(path) }&.freeze
|
|
88
|
+
|
|
89
|
+
lambda do |request|
|
|
90
|
+
(verbs.nil? || verbs.include?(request.http_method)) && (routes.nil? || routes.include?(request.path))
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# Paths must be written in normalized form, or they would never match.
|
|
95
|
+
def canonical_path!(path)
|
|
96
|
+
path = path.to_s
|
|
97
|
+
segments = path.split('/').drop(1)
|
|
98
|
+
return path if path == '/' || (path.match?(%r{\A(/[^/%\\]+)+\z}) && (segments & %w[. ..]).empty?)
|
|
99
|
+
|
|
100
|
+
raise ArgumentError, "policy #{@name}: write the path #{path.inspect} normalized, like \"/login\""
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def fixed_cost!(cost)
|
|
104
|
+
return cost if cost.is_a?(Integer) && cost.positive?
|
|
105
|
+
|
|
106
|
+
raise ArgumentError, "policy #{@name}: cost must be a positive Integer or respond to #call"
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def validate_limiters!
|
|
110
|
+
raise ArgumentError, 'reserve must be a non-negative Integer' unless @reserve.is_a?(Integer) && @reserve >= 0
|
|
111
|
+
|
|
112
|
+
@selector.limiters.each do |limiter|
|
|
113
|
+
unless limiter.respond_to?(:acquire) && limiter.respond_to?(:limit)
|
|
114
|
+
raise ArgumentError,
|
|
115
|
+
"limiter must respond to #acquire and #limit (got #{limiter.class}): " \
|
|
116
|
+
'queue algorithms delay work instead of answering allow-or-reject immediately, ' \
|
|
117
|
+
'so build the limiter with RateGuard.limiter'
|
|
118
|
+
end
|
|
119
|
+
raise ArgumentError, "policy #{@name}: reserve must be below the limit" if @reserve >= limiter.limit
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def callable!(object, what)
|
|
124
|
+
return object if object.respond_to?(:call)
|
|
125
|
+
|
|
126
|
+
raise ArgumentError, "#{what} must respond to #call (got #{object.class})"
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative 'policy'
|
|
4
|
+
|
|
5
|
+
module RateGuard
|
|
6
|
+
# Checks a request against every matching policy, in order.
|
|
7
|
+
# - All must allow it. The first rejection stops the rest.
|
|
8
|
+
# - Policies already checked stay charged, so put strict ones first.
|
|
9
|
+
# - The client sees one policy: the one that rejected, or the one
|
|
10
|
+
# with the fewest requests left.
|
|
11
|
+
# - A bypassed client skips every policy.
|
|
12
|
+
class PolicySet
|
|
13
|
+
# The result of checking one request.
|
|
14
|
+
Decision = Data.define(:outcomes, :bypassed) do
|
|
15
|
+
def matched? = bypassed || !outcomes.empty?
|
|
16
|
+
def bypassed? = bypassed
|
|
17
|
+
def allowed? = outcomes.all?(&:allowed?)
|
|
18
|
+
|
|
19
|
+
# The outcome shown to the client.
|
|
20
|
+
def reported
|
|
21
|
+
outcomes.find { |outcome| !outcome.allowed? } ||
|
|
22
|
+
outcomes.min_by { |outcome| [outcome.result.remaining, -(outcome.result.reset_after || 0.0)] }
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
UNMATCHED = Decision.new(outcomes: [].freeze, bypassed: false)
|
|
27
|
+
BYPASSED = Decision.new(outcomes: [].freeze, bypassed: true)
|
|
28
|
+
|
|
29
|
+
attr_reader :policies
|
|
30
|
+
|
|
31
|
+
# bypass - optional callable(env) -> true to skip limiting (see Bypass)
|
|
32
|
+
def initialize(policies, bypass: nil)
|
|
33
|
+
policies = Array(policies)
|
|
34
|
+
raise ArgumentError, 'a PolicySet needs at least one policy' if policies.empty?
|
|
35
|
+
raise ArgumentError, 'policies must be RateGuard::Policy objects' unless policies.all?(Policy)
|
|
36
|
+
|
|
37
|
+
duplicates = policies.map(&:name).tally.select { |_name, count| count > 1 }.keys
|
|
38
|
+
raise ArgumentError, "policy names must be unique (repeated: #{duplicates.join(', ')})" if duplicates.any?
|
|
39
|
+
raise ArgumentError, 'bypass must respond to #call' unless bypass.nil? || bypass.respond_to?(:call)
|
|
40
|
+
|
|
41
|
+
@policies = policies.freeze
|
|
42
|
+
@bypass = bypass
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def decide(request)
|
|
46
|
+
matching = @policies.select { |policy| policy.matches?(request) }
|
|
47
|
+
return UNMATCHED if matching.empty?
|
|
48
|
+
return BYPASSED if @bypass&.call(request.env)
|
|
49
|
+
|
|
50
|
+
outcomes = []
|
|
51
|
+
matching.each do |policy|
|
|
52
|
+
outcomes << policy.apply(request)
|
|
53
|
+
break unless outcomes.last.allowed?
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
Decision.new(outcomes: outcomes.freeze, bypassed: false)
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative 'clock'
|
|
4
|
+
require_relative 'metrics'
|
|
5
|
+
|
|
6
|
+
module RateGuard
|
|
7
|
+
# Logs Redis failures without flooding the log:
|
|
8
|
+
#
|
|
9
|
+
# config.on_redis_error = RedisErrorReporter.new(logger:, metrics:, failure_policy: :allow)
|
|
10
|
+
#
|
|
11
|
+
# Counts every failure, logs the first at once, then one line per
|
|
12
|
+
# `interval` with how many were skipped.
|
|
13
|
+
class RedisErrorReporter
|
|
14
|
+
def initialize(logger: nil, metrics: Metrics::Null.new, failure_policy: :allow, interval: 60,
|
|
15
|
+
clock: Clock::Monotonic)
|
|
16
|
+
@logger = logger
|
|
17
|
+
@metrics = metrics
|
|
18
|
+
@action = failure_policy.to_sym == :reject ? 'rejecting' : 'allowing'
|
|
19
|
+
@interval = interval
|
|
20
|
+
@clock = clock
|
|
21
|
+
@last_logged_at = nil
|
|
22
|
+
@suppressed = 0
|
|
23
|
+
@mutex = Mutex.new
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def call(error)
|
|
27
|
+
@metrics.increment('rate_guard.redis_errors', error: error.class.name)
|
|
28
|
+
suppressed = due_for_a_log_line
|
|
29
|
+
return if suppressed.nil? || @logger.nil?
|
|
30
|
+
|
|
31
|
+
@logger.error(event: 'redis_unavailable', action: @action, error: error.class.name,
|
|
32
|
+
message: error.message, suppressed: suppressed)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
private
|
|
36
|
+
|
|
37
|
+
# nil inside the interval; otherwise how many were skipped.
|
|
38
|
+
def due_for_a_log_line
|
|
39
|
+
@mutex.synchronize do
|
|
40
|
+
now = @clock.now
|
|
41
|
+
if @last_logged_at && now - @last_logged_at < @interval
|
|
42
|
+
@suppressed += 1
|
|
43
|
+
next nil
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
@last_logged_at = now
|
|
47
|
+
@suppressed.tap { @suppressed = 0 }
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|