boto-rb-security 0.7.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1670cd905860a1f6c11cbb6ff2ccb61bf179419e3c8b71c750cbc8a1dee15264
4
+ data.tar.gz: af30368d79ea92b327fd29e9b14c62705207a3af7d0c963d129577f790f25055
5
+ SHA512:
6
+ metadata.gz: 0af28416104d64c6927924eefeea5564faeb6cb9889506731183d04987c824ca728ea485984f8e2ce481ee89bbeee384405317161d599bba80c08846c606dc27
7
+ data.tar.gz: 72ec4584d8f0e083ad7ab62d35a4932b59a0cdd58c8cff4c793560d540bbdfeeb37e2d1690f207f7d9e019421d118bf609fae2da533acc23f2a35d73ff983104
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Evo Tech Builder
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Plugins
5
+ class Auth < Boto::Plugin
6
+ # Checks an API key sent in a request header against a Hash of key_id => key.
7
+ class ApiKey
8
+ attr_reader :challenge, :security_scheme
9
+
10
+ def initialize(keys:, header: "X-API-Key")
11
+ @keys = validate_keys(Boto::Security::Secrets.resolve(keys))
12
+ @rack_key = rack_key_for(header)
13
+ @challenge = %(API-Key header="#{header}").freeze
14
+ @security_scheme = { "type" => "apiKey", "in" => "header", "name" => header }.freeze
15
+ end
16
+
17
+ def authenticate(env)
18
+ given = env[@rack_key]
19
+ return unless given
20
+
21
+ # Compares against every key, so the position of a match does not show up in timing.
22
+ found = @keys.map { |id, key| [id, Boto::Security::Secrets.equal?(given, key)] }.find { |_id, matched| matched }
23
+ { key_id: found.first }.freeze if found
24
+ end
25
+
26
+ private
27
+
28
+ def validate_keys(keys)
29
+ valid = keys.is_a?(Hash) && !keys.empty? && keys.values.all? { |key| key.is_a?(String) && !key.empty? }
30
+ raise ArgumentError, "keys must be a non-empty Hash of key_id => key" unless valid
31
+
32
+ keys.dup.freeze
33
+ end
34
+
35
+ def rack_key_for(header)
36
+ raise ArgumentError, "header must be a non-empty String" unless header.is_a?(String) && !header.empty?
37
+
38
+ "HTTP_#{header.upcase.tr("-", "_")}".freeze
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Plugins
5
+ class Auth < Boto::Plugin
6
+ # Checks HTTP Basic credentials against a Hash of user => password.
7
+ class Basic
8
+ AUTHORIZATION = "HTTP_AUTHORIZATION"
9
+ PREFIX = "Basic "
10
+ # Compared when the user is unknown, so a miss takes about as long as a wrong password.
11
+ DUMMY_PASSWORD = "boto-unknown-user"
12
+ SECURITY_SCHEME = { "type" => "http", "scheme" => "basic" }.freeze
13
+
14
+ attr_reader :challenge, :security_scheme
15
+
16
+ def initialize(credentials:, realm: "Boto")
17
+ @credentials = validate(Boto::Security::Secrets.resolve(credentials))
18
+ @challenge = %(Basic realm="#{realm}").freeze
19
+ @security_scheme = SECURITY_SCHEME
20
+ end
21
+
22
+ def authenticate(env)
23
+ user, password = decode(env[AUTHORIZATION])
24
+ return unless password
25
+
26
+ matched = Boto::Security::Secrets.equal?(password, @credentials.fetch(user, DUMMY_PASSWORD))
27
+ { user: user }.freeze if matched && @credentials.key?(user)
28
+ end
29
+
30
+ private
31
+
32
+ def decode(header)
33
+ return unless header&.start_with?(PREFIX)
34
+
35
+ # split needs binary input: it raises on invalid UTF-8 bytes sent by a client
36
+ header.delete_prefix(PREFIX).unpack1("m").split(":", 2).map { |part| part.force_encoding(Encoding::UTF_8) }
37
+ end
38
+
39
+ def validate(credentials)
40
+ valid = credentials.is_a?(Hash) && !credentials.empty? &&
41
+ credentials.all? { |user, password| user.is_a?(String) && password.is_a?(String) && !password.empty? }
42
+ raise ArgumentError, "credentials must be a non-empty Hash of user => password" unless valid
43
+
44
+ credentials.dup.freeze
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Plugins
5
+ class Auth < Boto::Plugin
6
+ # Checks the HTTP Bearer token against a list of accepted tokens.
7
+ class Bearer
8
+ AUTHORIZATION = "HTTP_AUTHORIZATION"
9
+ PREFIX = "Bearer "
10
+ SECURITY_SCHEME = { "type" => "http", "scheme" => "bearer" }.freeze
11
+
12
+ attr_reader :challenge, :security_scheme
13
+
14
+ def initialize(tokens:, realm: "Boto")
15
+ @tokens = validate(Boto::Security::Secrets.resolve(tokens))
16
+ @challenge = %(Bearer realm="#{realm}").freeze
17
+ @security_scheme = SECURITY_SCHEME
18
+ end
19
+
20
+ def authenticate(env)
21
+ token = bearer_token(env[AUTHORIZATION])
22
+ return unless token
23
+
24
+ index = matching_index(token)
25
+ { token_index: index }.freeze if index
26
+ end
27
+
28
+ private
29
+
30
+ def bearer_token(header)
31
+ header.delete_prefix(PREFIX) if header&.start_with?(PREFIX)
32
+ end
33
+
34
+ # Compares against every token, so the position of a match does not show up in timing.
35
+ def matching_index(token)
36
+ @tokens.map { |expected| Boto::Security::Secrets.equal?(token, expected) }.index(true)
37
+ end
38
+
39
+ def validate(tokens)
40
+ valid = tokens.is_a?(Array) && !tokens.empty? && tokens.all? { |token| token.is_a?(String) && !token.empty? }
41
+ raise ArgumentError, "tokens must be a non-empty Array of Strings" unless valid
42
+
43
+ tokens.dup.freeze
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "jwt"
4
+ require "openssl"
5
+
6
+ module Boto
7
+ module Plugins
8
+ class Auth < Boto::Plugin
9
+ # Bearer JWT strategy: the verified claims become the principal.
10
+ class Jwt
11
+ AUTHORIZATION_KEY = "HTTP_AUTHORIZATION"
12
+ BEARER_PREFIX = "Bearer "
13
+ NONE_ALGORITHM = "none"
14
+ REQUIRED_CLAIMS = ["exp"].freeze
15
+ DEFAULT_REALM = "Boto"
16
+
17
+ def initialize(algorithms:, secret: nil, public_key: nil, issuer: nil, audience: nil, leeway: 0, realm: DEFAULT_REALM)
18
+ @algorithms = validate_algorithms(algorithms)
19
+ @key = load_key(secret, public_key)
20
+ @decode_options = build_decode_options(issuer, audience, validate_leeway(leeway))
21
+ @realm = realm
22
+ end
23
+
24
+ def authenticate(env)
25
+ token = bearer_token(env)
26
+ return unless token
27
+
28
+ payload, _header = JWT.decode(token, @key, true, @decode_options)
29
+ payload.transform_keys(&:to_sym).freeze
30
+ rescue JWT::DecodeError
31
+ nil
32
+ end
33
+
34
+ def challenge
35
+ %(Bearer realm="#{@realm}")
36
+ end
37
+
38
+ def security_scheme
39
+ { "type" => "http", "scheme" => "bearer", "bearerFormat" => "JWT" }
40
+ end
41
+
42
+ private
43
+
44
+ def validate_algorithms(algorithms)
45
+ unless algorithms.is_a?(Array) && !algorithms.empty? && algorithms.all?(String)
46
+ raise ArgumentError, "algorithms deve ser um Array não vazio de Strings"
47
+ end
48
+ raise ArgumentError, "o algoritmo 'none' não é aceito" if algorithms.any? { _1.casecmp?(NONE_ALGORITHM) }
49
+
50
+ algorithms.freeze
51
+ end
52
+
53
+ def load_key(secret, public_key)
54
+ raise ArgumentError, "informe secret ou public_key, exatamente um" if secret.nil? == public_key.nil?
55
+
56
+ secret ? Boto::Security::Secrets.resolve(secret) : parse_public_key(Boto::Security::Secrets.resolve(public_key))
57
+ end
58
+
59
+ def parse_public_key(key)
60
+ key.is_a?(String) ? OpenSSL::PKey.read(key) : key
61
+ end
62
+
63
+ def validate_leeway(leeway)
64
+ raise ArgumentError, "leeway deve ser um Integer >= 0" unless leeway.is_a?(Integer) && leeway >= 0
65
+
66
+ leeway
67
+ end
68
+
69
+ def build_decode_options(issuer, audience, leeway)
70
+ {
71
+ algorithms: @algorithms,
72
+ leeway: leeway,
73
+ iss: issuer,
74
+ verify_iss: !issuer.nil?,
75
+ aud: audience,
76
+ verify_aud: !audience.nil?,
77
+ required_claims: REQUIRED_CLAIMS
78
+ }.freeze
79
+ end
80
+
81
+ def bearer_token(env)
82
+ header = env[AUTHORIZATION_KEY]
83
+ return unless header&.start_with?(BEARER_PREFIX)
84
+
85
+ header.delete_prefix(BEARER_PREFIX)
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module Boto
6
+ module Plugins
7
+ class Auth < Boto::Plugin
8
+ # HMAC webhook strategy: the signature of the raw body (optionally bound to a timestamp) must match.
9
+ class Signature
10
+ ALGORITHMS = %w[sha256 sha512].freeze
11
+ DEFAULT_HEADER = "X-Signature"
12
+ DEFAULT_ALGORITHM = "sha256"
13
+ DEFAULT_TIMESTAMP_HEADER = "X-Timestamp"
14
+ RACK_HTTP_PREFIX = "HTTP_"
15
+ RACK_INPUT = "rack.input"
16
+ TIMESTAMP_FORMAT = /\A\d+\z/
17
+ PRINCIPAL = { signed: true }.freeze
18
+ SIGNED_MESSAGE_SEPARATOR = "."
19
+
20
+ def initialize(secret:, header: DEFAULT_HEADER, algorithm: DEFAULT_ALGORITHM, prefix: nil,
21
+ tolerance: nil, timestamp_header: DEFAULT_TIMESTAMP_HEADER,
22
+ clock: -> { Time.now.to_i })
23
+ @secret = validate_secret(Boto::Security::Secrets.resolve(secret))
24
+ @algorithm = validate_algorithm(algorithm)
25
+ @tolerance = validate_tolerance(tolerance)
26
+ @header = header
27
+ @signature_key = rack_key(header)
28
+ @timestamp_key = rack_key(timestamp_header)
29
+ @prefix = prefix
30
+ @clock = clock
31
+ end
32
+
33
+ def authenticate(env)
34
+ given = signature_from(env)
35
+ return unless given
36
+
37
+ message = signed_message(env, read_body(env))
38
+ return unless message
39
+
40
+ expected = OpenSSL::HMAC.hexdigest(@algorithm, @secret, message)
41
+ Boto::Security::Secrets.equal?(given, expected) ? PRINCIPAL : nil
42
+ end
43
+
44
+ def challenge
45
+ %(Signature header="#{@header}")
46
+ end
47
+
48
+ def security_scheme
49
+ { "type" => "apiKey", "in" => "header", "name" => @header }
50
+ end
51
+
52
+ private
53
+
54
+ def validate_secret(secret)
55
+ raise ArgumentError, "secret deve ser uma String não vazia" unless secret.is_a?(String) && !secret.empty?
56
+
57
+ secret
58
+ end
59
+
60
+ def validate_algorithm(algorithm)
61
+ raise ArgumentError, "algorithm deve ser #{ALGORITHMS.join(" ou ")}" unless ALGORITHMS.include?(algorithm)
62
+
63
+ algorithm
64
+ end
65
+
66
+ def validate_tolerance(tolerance)
67
+ return tolerance if tolerance.nil? || (tolerance.is_a?(Integer) && tolerance.positive?)
68
+
69
+ raise ArgumentError, "tolerance deve ser nil ou um Integer > 0"
70
+ end
71
+
72
+ def rack_key(header)
73
+ "#{RACK_HTTP_PREFIX}#{header.upcase.tr("-", "_")}"
74
+ end
75
+
76
+ def signature_from(env)
77
+ value = env[@signature_key]
78
+ return value unless @prefix && value
79
+
80
+ value.delete_prefix(@prefix) if value.start_with?(@prefix)
81
+ end
82
+
83
+ # Rewinds the input so that the downstream app can still read the body.
84
+ def read_body(env)
85
+ input = env[RACK_INPUT]
86
+ return "" unless input
87
+
88
+ body = input.read.to_s
89
+ input.rewind if input.respond_to?(:rewind)
90
+ body
91
+ end
92
+
93
+ def signed_message(env, body)
94
+ return body unless @tolerance
95
+
96
+ timestamp = timestamp_from(env)
97
+ return unless timestamp && (@clock.call - timestamp).abs <= @tolerance
98
+
99
+ [timestamp, body].join(SIGNED_MESSAGE_SEPARATOR)
100
+ end
101
+
102
+ def timestamp_from(env)
103
+ value = env[@timestamp_key].to_s
104
+ value.to_i if value.match?(TIMESTAMP_FORMAT)
105
+ end
106
+ end
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Plugins
5
+ # Authenticates each request with one strategy (basic, bearer, api_key, ...) and stores the principal in env.
6
+ class Auth < Boto::Plugin
7
+ scope :endpoint
8
+
9
+ STRATEGY_FORMAT = /\A[a-z][a-z0-9_]*\z/
10
+ PRINCIPAL_KEY = "boto.principal"
11
+
12
+ attr_reader :strategy
13
+
14
+ def call(env, app)
15
+ principal = strategy.authenticate(env)
16
+ return Boto::Error::Unauthorized.new(strategy.challenge).to_response unless principal
17
+
18
+ env[PRINCIPAL_KEY] = principal
19
+ app.call(env)
20
+ end
21
+
22
+ private
23
+
24
+ def configure(strategy:, **options)
25
+ @strategy = build_strategy(strategy, options)
26
+ end
27
+
28
+ def build_strategy(name, options)
29
+ strategy_class(name).new(**options)
30
+ end
31
+
32
+ def strategy_class(name)
33
+ const_name = name.to_s.split("_").map(&:capitalize).join
34
+ unless STRATEGY_FORMAT.match?(name.to_s) && self.class.const_defined?(const_name, false)
35
+ raise ArgumentError, "unknown auth strategy #{name.inspect}"
36
+ end
37
+
38
+ self.class.const_get(const_name, false)
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Plugins
5
+ # Answers CORS preflights and adds CORS headers to responses for allowed origins.
6
+ class Cors < Boto::Plugin
7
+ scope :global
8
+
9
+ DEFAULT_METHODS = %w[GET HEAD POST PUT PATCH DELETE QUERY].freeze
10
+ DEFAULT_HEADERS = %w[content-type authorization].freeze
11
+ EMPTY_LIST = [].freeze
12
+ ANY_ORIGIN = "*"
13
+ LIST_SEPARATOR = ", "
14
+ TRUE_VALUE = "true"
15
+
16
+ ORIGIN_ENV = "HTTP_ORIGIN"
17
+ REQUESTED_METHOD_ENV = "HTTP_ACCESS_CONTROL_REQUEST_METHOD"
18
+ REQUEST_METHOD_ENV = "REQUEST_METHOD"
19
+ PREFLIGHT_METHOD = "OPTIONS"
20
+ PREFLIGHT_STATUS = 204
21
+
22
+ ALLOW_ORIGIN = "access-control-allow-origin"
23
+ ALLOW_METHODS = "access-control-allow-methods"
24
+ ALLOW_HEADERS = "access-control-allow-headers"
25
+ ALLOW_CREDENTIALS = "access-control-allow-credentials"
26
+ EXPOSE_HEADERS = "access-control-expose-headers"
27
+ MAX_AGE = "access-control-max-age"
28
+ VARY = "vary"
29
+ VARY_ORIGIN = "Origin"
30
+
31
+ def call(env, app)
32
+ origin = env[ORIGIN_ENV]
33
+ return app.call(env) unless origin
34
+ return preflight(env, origin) if preflight?(env)
35
+ return app.call(env) unless allowed_origin?(origin)
36
+
37
+ status, headers, body = app.call(env)
38
+ [status, with_response_headers(headers, origin), body]
39
+ end
40
+
41
+ private
42
+
43
+ def configure(origins: EMPTY_LIST, methods: DEFAULT_METHODS, headers: DEFAULT_HEADERS,
44
+ expose: EMPTY_LIST, credentials: false, max_age: nil)
45
+ @any_origin = origins == ANY_ORIGIN
46
+ raise ArgumentError, 'cors: origins "*" cannot be used with credentials' if @any_origin && credentials
47
+
48
+ @origins = @any_origin ? EMPTY_LIST : parse_origins(origins)
49
+ validate_max_age!(max_age)
50
+ @credentials = credentials
51
+ @allowed_methods = methods.map { |name| name.upcase.freeze }.freeze
52
+ @preflight_headers = build_preflight_headers(headers, max_age)
53
+ @response_headers = build_response_headers(expose)
54
+ end
55
+
56
+ def parse_origins(origins)
57
+ unless origins.is_a?(Array) && origins.all? { |origin| valid_origin?(origin) }
58
+ raise ArgumentError, 'cors: origins must be an Array of origin Strings or "*"'
59
+ end
60
+
61
+ # Browsers send scheme and host in lowercase, so configured origins are normalized to match.
62
+ origins.map { |origin| -origin.downcase }.freeze
63
+ end
64
+
65
+ def valid_origin?(value)
66
+ value.is_a?(String) && !value.empty? && value != ANY_ORIGIN
67
+ end
68
+
69
+ def validate_max_age!(max_age)
70
+ return if max_age.nil? || (max_age.is_a?(Integer) && max_age >= 0)
71
+
72
+ raise ArgumentError, "cors: max_age must be a non-negative Integer or nil"
73
+ end
74
+
75
+ def build_preflight_headers(headers, max_age)
76
+ {
77
+ ALLOW_METHODS => @allowed_methods.join(LIST_SEPARATOR),
78
+ ALLOW_HEADERS => headers.join(LIST_SEPARATOR),
79
+ MAX_AGE => max_age&.to_s,
80
+ ALLOW_CREDENTIALS => (TRUE_VALUE if @credentials),
81
+ VARY => VARY_ORIGIN
82
+ }.compact.freeze
83
+ end
84
+
85
+ def build_response_headers(expose)
86
+ {
87
+ EXPOSE_HEADERS => (expose.join(LIST_SEPARATOR) unless expose.empty?),
88
+ ALLOW_CREDENTIALS => (TRUE_VALUE if @credentials)
89
+ }.compact.freeze
90
+ end
91
+
92
+ def preflight?(env)
93
+ env[REQUEST_METHOD_ENV] == PREFLIGHT_METHOD && env.key?(REQUESTED_METHOD_ENV)
94
+ end
95
+
96
+ def preflight(env, origin)
97
+ return rejected_preflight unless allowed_origin?(origin) && @allowed_methods.include?(env[REQUESTED_METHOD_ENV])
98
+
99
+ [PREFLIGHT_STATUS, @preflight_headers.merge(ALLOW_ORIGIN => allow_origin(origin)), []]
100
+ end
101
+
102
+ def rejected_preflight
103
+ Boto::Error::Forbidden.new("CORS preflight rejected").to_response
104
+ end
105
+
106
+ def allowed_origin?(origin)
107
+ @any_origin || @origins.include?(origin)
108
+ end
109
+
110
+ def allow_origin(origin)
111
+ @any_origin ? ANY_ORIGIN : origin
112
+ end
113
+
114
+ def with_response_headers(headers, origin)
115
+ result = headers.frozen? ? headers.dup : headers
116
+ result[ALLOW_ORIGIN] = allow_origin(origin)
117
+ result[VARY] = merge_vary(result[VARY])
118
+ @response_headers.each { |name, value| result[name] = value }
119
+ result
120
+ end
121
+
122
+ def merge_vary(existing)
123
+ return VARY_ORIGIN if existing.nil? || existing.empty?
124
+ return existing if existing.split(",").any? { |field| field.strip.casecmp?(VARY_ORIGIN) }
125
+
126
+ "#{existing}#{LIST_SEPARATOR}#{VARY_ORIGIN}"
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Plugins
5
+ # Blocks requests whose Host header is not on the allow list, which stops DNS rebinding.
6
+ class Hosts < Boto::Plugin
7
+ scope :global
8
+
9
+ DEVELOPMENT_HOSTS = %w[localhost 127.0.0.1 ::1].freeze
10
+ SUFFIX_PREFIX = "."
11
+ PORT_SUFFIX = /:\d+\z/
12
+ BRACKETED_IPV6 = /\A\[([^\]]+)\](?::\d+)?\z/
13
+ FORBIDDEN_DETAIL = "host not allowed"
14
+
15
+ def call(env, app)
16
+ return app.call(env) if allowed?(host_from(env))
17
+
18
+ Boto::Error::Forbidden.new(FORBIDDEN_DETAIL).to_response
19
+ end
20
+
21
+ private
22
+
23
+ def configure(allow: [])
24
+ entries = normalize(allow)
25
+ raise ArgumentError, "hosts: allow is required outside development" if entries.empty? && !development?
26
+
27
+ entries += DEVELOPMENT_HOSTS if development?
28
+ @exact_hosts, @suffixes = split(entries)
29
+ end
30
+
31
+ def normalize(allow)
32
+ raise ArgumentError, "hosts: allow must be an Array of Strings" unless allow.is_a?(Array)
33
+
34
+ allow.map do |entry|
35
+ raise ArgumentError, "hosts: allow entries must be Strings" unless entry.is_a?(String)
36
+ # "" or "." would become a suffix that matches every host with a dot.
37
+ raise ArgumentError, "hosts: empty allow entry #{entry.inspect}" if entry.delete_prefix(".").empty?
38
+
39
+ entry.downcase
40
+ end
41
+ end
42
+
43
+ # A suffix such as ".loja.internal" also allows its bare domain "loja.internal".
44
+ def split(entries)
45
+ suffixes, exact = entries.partition { |entry| entry.start_with?(SUFFIX_PREFIX) }
46
+ bare_domains = suffixes.map { |suffix| suffix.delete_prefix(SUFFIX_PREFIX) }
47
+ [Set.new(exact + bare_domains).freeze, suffixes.freeze]
48
+ end
49
+
50
+ def allowed?(host)
51
+ return false if host.nil?
52
+
53
+ @exact_hosts.include?(host) || @suffixes.any? { |suffix| host.end_with?(suffix) }
54
+ end
55
+
56
+ def host_from(env)
57
+ raw = env["HTTP_HOST"]
58
+ return if raw.nil?
59
+
60
+ host = raw.downcase
61
+ bracketed = BRACKETED_IPV6.match(host)
62
+ return bracketed[1] if bracketed
63
+
64
+ host.sub(PORT_SUFFIX, "")
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Plugins
5
+ class RateLimit < Boto::Plugin
6
+ # In-process fixed-window counter. Each store is meant for a single period and keeps counters
7
+ # only for the current window, capped at max_keys keys per window (oldest evicted first).
8
+ # Evicted keys restart at zero, so a client with many IPs can reset an old key's count.
9
+ # Counts are lost on restart and are not shared between processes.
10
+ class MemoryStore
11
+ MIN_RESET_SECONDS = 1
12
+ DEFAULT_MAX_KEYS = 100_000
13
+
14
+ def initialize(clock:, max_keys: DEFAULT_MAX_KEYS)
15
+ @clock = clock
16
+ @max_keys = positive_integer!(max_keys)
17
+ @mutex = Mutex.new
18
+ @windows = {}
19
+ end
20
+
21
+ # Returns [count, reset_in]: the requests counted for key in the current window,
22
+ # and the whole seconds left until that window ends.
23
+ def increment(key, period)
24
+ now = @clock.call
25
+ window = (now / period).floor
26
+ @mutex.synchronize do
27
+ drop_windows_before(window)
28
+ count = count_request((@windows[window] ||= {}), key)
29
+ [count, reset_in(now, window, period)]
30
+ end
31
+ end
32
+
33
+ # Number of live counters (one per key in each stored window). Useful for tests and monitoring.
34
+ def size
35
+ @mutex.synchronize { @windows.sum { |_window, counts| counts.size } }
36
+ end
37
+
38
+ private
39
+
40
+ def positive_integer!(value)
41
+ return value if value.is_a?(Integer) && value.positive?
42
+
43
+ raise ArgumentError, "max_keys must be a positive Integer, got #{value.inspect}"
44
+ end
45
+
46
+ def drop_windows_before(window)
47
+ @windows.delete_if { |stored, _counts| stored < window }
48
+ end
49
+
50
+ # Hash keeps insertion order, so shift removes the oldest key in O(1).
51
+ def count_request(counts, key)
52
+ if counts.key?(key)
53
+ counts[key] += 1
54
+ else
55
+ counts.shift if counts.size >= @max_keys
56
+ counts[key] = 1
57
+ end
58
+ end
59
+
60
+ def reset_in(now, window, period)
61
+ window_end = (window + 1) * period
62
+ [(window_end - now).ceil, MIN_RESET_SECONDS].max
63
+ end
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+
5
+ module Boto
6
+ module Plugins
7
+ # Limits how many requests a client key may make per fixed window. The default key is the
8
+ # client IP, which X-Forwarded-For can only change when the direct peer is a trusted proxy.
9
+ class RateLimit < Boto::Plugin
10
+ scope :endpoint
11
+
12
+ DEFAULT_CLOCK = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }.freeze
13
+ LIMIT_HEADER = "ratelimit-limit"
14
+ REMAINING_HEADER = "ratelimit-remaining"
15
+ RESET_HEADER = "ratelimit-reset"
16
+
17
+ def call(env, app)
18
+ count, reset_in = begin
19
+ @store.increment(client_key(env), @period)
20
+ rescue Boto::Error => error
21
+ return error.to_response
22
+ end
23
+
24
+ status, headers, body = count > @limit ? too_many_requests(reset_in) : app.call(env)
25
+ [status, with_rate_headers(headers, count, reset_in), body]
26
+ end
27
+
28
+ private
29
+
30
+ def configure(limit:, period:, key: nil, trusted_proxies: [], store: nil, clock: nil, max_keys: nil)
31
+ @limit = positive_integer!(limit, :limit)
32
+ @period = positive_integer!(period, :period)
33
+ @key = callable_key!(key)
34
+ @trusted_proxies = parse_proxies(trusted_proxies)
35
+ @store = build_store(store, clock, max_keys)
36
+ end
37
+
38
+ def build_store(store, clock, max_keys)
39
+ return MemoryStore.new(clock: clock || DEFAULT_CLOCK, max_keys: max_keys || MemoryStore::DEFAULT_MAX_KEYS) unless store
40
+
41
+ raise ArgumentError, "max_keys only applies to the default store" unless max_keys.nil?
42
+
43
+ store
44
+ end
45
+
46
+ def positive_integer!(value, name)
47
+ return value if value.is_a?(Integer) && value.positive?
48
+
49
+ raise ArgumentError, "#{name} must be a positive Integer, got #{value.inspect}"
50
+ end
51
+
52
+ def callable_key!(key)
53
+ return key if key.nil? || key.respond_to?(:call)
54
+
55
+ raise ArgumentError, "key must be nil or a callable, got #{key.inspect}"
56
+ end
57
+
58
+ def parse_proxies(entries)
59
+ raise ArgumentError, "trusted_proxies must be an Array" unless entries.is_a?(Array)
60
+
61
+ entries.map { |entry| IPAddr.new(entry) }
62
+ end
63
+
64
+ def too_many_requests(reset_in)
65
+ Boto::Error::TooManyRequests.new(reset_in).to_response
66
+ end
67
+
68
+ def with_rate_headers(headers, count, reset_in)
69
+ headers = headers.dup if headers.frozen?
70
+ headers[LIMIT_HEADER] = @limit.to_s
71
+ headers[REMAINING_HEADER] = [@limit - count, 0].max.to_s
72
+ headers[RESET_HEADER] = reset_in.to_s
73
+ headers
74
+ end
75
+
76
+ def client_key(env)
77
+ @key ? @key.call(env) : client_ip(env)
78
+ end
79
+
80
+ def client_ip(env)
81
+ remote = env["REMOTE_ADDR"]
82
+ forwarded = env["HTTP_X_FORWARDED_FOR"]
83
+ return remote unless forwarded && trusted?(remote)
84
+
85
+ forwarded_client(forwarded.split(",").map(&:strip), remote)
86
+ end
87
+
88
+ # The rightmost hop that is not a trusted proxy is the client; falls back to the leftmost hop.
89
+ def forwarded_client(hops, remote)
90
+ hops.reverse.find { |hop| !trusted?(hop) } || hops.first || remote
91
+ end
92
+
93
+ def trusted?(address)
94
+ ip = parse_ip(address)
95
+ !ip.nil? && @trusted_proxies.any? { |proxy| proxy.include?(ip) }
96
+ end
97
+
98
+ def parse_ip(address)
99
+ IPAddr.new(address.to_s)
100
+ rescue IPAddr::Error
101
+ nil
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "rack/utils"
5
+
6
+ module Boto
7
+ module Security
8
+ # Helpers shared by the security plugins to read secrets and compare them safely.
9
+ module Secrets
10
+ # Secrets may be given as lambdas so they stay out of the code; they are read once, at boot.
11
+ def self.resolve(value)
12
+ value.respond_to?(:call) ? value.call : value
13
+ end
14
+
15
+ # Hashing both sides first gives equal-length inputs, so the comparison leaks neither content nor length.
16
+ def self.equal?(given, expected)
17
+ return false if given.nil? || expected.nil?
18
+
19
+ Rack::Utils.secure_compare(digest(given), digest(expected))
20
+ end
21
+
22
+ def self.digest(value)
23
+ OpenSSL::Digest::SHA256.digest(value.to_s)
24
+ end
25
+ private_class_method :digest
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Security
5
+ VERSION = "0.7.0"
6
+ end
7
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "boto"
4
+ require "zeitwerk"
5
+
6
+ loader = Zeitwerk::Loader.for_gem_extension(Boto)
7
+ loader.setup
8
+
9
+ module Boto
10
+ # Security plugins (hosts, cors, auth, rate_limit) that a project enables with app.use.
11
+ module Security
12
+ end
13
+ end
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: boto-rb-security
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.7.0
5
+ platform: ruby
6
+ authors:
7
+ - Evo Tech Builder
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: boto-rb
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - '='
17
+ - !ruby/object:Gem::Version
18
+ version: 0.7.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - '='
24
+ - !ruby/object:Gem::Version
25
+ version: 0.7.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: jwt
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '3.0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '3.0'
40
+ executables: []
41
+ extensions: []
42
+ extra_rdoc_files: []
43
+ files:
44
+ - LICENSE
45
+ - lib/boto/plugins/auth.rb
46
+ - lib/boto/plugins/auth/api_key.rb
47
+ - lib/boto/plugins/auth/basic.rb
48
+ - lib/boto/plugins/auth/bearer.rb
49
+ - lib/boto/plugins/auth/jwt.rb
50
+ - lib/boto/plugins/auth/signature.rb
51
+ - lib/boto/plugins/cors.rb
52
+ - lib/boto/plugins/hosts.rb
53
+ - lib/boto/plugins/rate_limit.rb
54
+ - lib/boto/plugins/rate_limit/memory_store.rb
55
+ - lib/boto/security.rb
56
+ - lib/boto/security/secrets.rb
57
+ - lib/boto/security/version.rb
58
+ homepage: https://github.com/EvoTechBuilder/boto-rb
59
+ licenses:
60
+ - MIT
61
+ metadata:
62
+ rubygems_mfa_required: 'true'
63
+ source_code_uri: https://github.com/EvoTechBuilder/boto-rb
64
+ changelog_uri: https://github.com/EvoTechBuilder/boto-rb/blob/main/CHANGELOG.md
65
+ rdoc_options: []
66
+ require_paths:
67
+ - lib
68
+ required_ruby_version: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: '3.4'
73
+ required_rubygems_version: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ requirements: []
79
+ rubygems_version: 4.0.20
80
+ specification_version: 4
81
+ summary: 'Security plugins for the Boto framework: auth, CORS, hosts and rate limiting.'
82
+ test_files: []