otto 2.11.0 → 2.13.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 +4 -4
- data/.github/workflows/ci.yml +1 -1
- data/.github/workflows/claude-code-review.yml +1 -1
- data/.github/workflows/claude.yml +1 -1
- data/.github/workflows/code-smells.yml +2 -2
- data/.github/workflows/release-gem.yml +1 -1
- data/.github/workflows/ruby-lint.yml +1 -1
- data/.github/workflows/yardoc.yml +1 -1
- data/.rubocop_todo.yml +2 -2
- data/AGENTS.md +4 -2
- data/CHANGELOG.rst +792 -0
- data/Gemfile +3 -2
- data/Gemfile.lock +13 -8
- data/README.md +6 -0
- data/docs/README.md +4 -0
- data/docs/audits/2026-09-28-v2.12.0-code-audit.md +732 -0
- data/docs/audits/README.md +63 -0
- data/docs/guides/authentication.md +329 -0
- data/docs/guides/forwarded-authority.md +85 -5
- data/docs/guides/mcp.md +40 -4
- data/docs/guides/privacy.md +28 -2
- data/docs/guides/routing.md +76 -9
- data/docs/guides/testing-guide.md +146 -5
- data/docs/migrating/v2.3.0.md +13 -7
- data/docs/reference/authentication.md +70 -22
- data/examples/lambda_handlers/README.md +4 -4
- data/examples/lambda_handlers/handlers.rb +4 -5
- data/examples/lambda_handlers/routes +2 -2
- data/examples/mcp_demo/README.md +65 -27
- data/examples/mcp_demo/app.rb +8 -5
- data/examples/mcp_demo/config.ru +50 -3
- data/examples/mcp_demo/routes +10 -6
- data/examples/security_features/README.md +2 -2
- data/lib/otto/caddy_tls/localhost_guard.rb +6 -6
- data/lib/otto/caddy_tls/server.rb +8 -4
- data/lib/otto/core/configuration.rb +5 -3
- data/lib/otto/core/option_hash.rb +124 -0
- data/lib/otto/core/redacted_inspect.rb +149 -0
- data/lib/otto/core/router.rb +57 -34
- data/lib/otto/core.rb +2 -0
- data/lib/otto/env_keys.rb +30 -6
- data/lib/otto/logging_helpers.rb +1 -1
- data/lib/otto/mcp/auth/token.rb +12 -1
- data/lib/otto/mcp/protocol.rb +3 -3
- data/lib/otto/mcp/registry.rb +28 -2
- data/lib/otto/mcp/route_parser.rb +20 -8
- data/lib/otto/mcp/server.rb +17 -9
- data/lib/otto/privacy/config.rb +31 -14
- data/lib/otto/privacy/ip_privacy.rb +109 -3
- data/lib/otto/privacy/redacted_fingerprint.rb +8 -10
- data/lib/otto/request.rb +34 -0
- data/lib/otto/response.rb +5 -2
- data/lib/otto/route.rb +1 -1
- data/lib/otto/route_definition.rb +3 -2
- data/lib/otto/route_handlers/base.rb +1 -1
- data/lib/otto/route_handlers/logic_class.rb +86 -34
- data/lib/otto/security/authentication/route_auth_wrapper.rb +10 -3
- data/lib/otto/security/config.rb +703 -345
- data/lib/otto/security/configurator.rb +82 -45
- data/lib/otto/security/core.rb +4 -2
- data/lib/otto/security/csp/report_middleware.rb +17 -1
- data/lib/otto/security/csrf.rb +17 -2
- data/lib/otto/security/csrf_validation.rb +13 -7
- data/lib/otto/security/middleware/csrf_middleware.rb +203 -37
- data/lib/otto/security/middleware/ip_privacy_middleware.rb +129 -42
- data/lib/otto/security/rate_limiter.rb +8 -5
- data/lib/otto/security/trusted_proxy_config.rb +396 -0
- data/lib/otto/static.rb +70 -6
- data/lib/otto/testing.rb +148 -0
- data/lib/otto/utils.rb +166 -40
- data/lib/otto/version.rb +1 -1
- data/lib/otto.rb +44 -11
- metadata +8 -2
|
@@ -23,34 +23,60 @@ class Otto
|
|
|
23
23
|
@auth_config = auth_config || { auth_strategies: {}, default_auth_strategy: 'noauth' }
|
|
24
24
|
end
|
|
25
25
|
|
|
26
|
+
# Options accepted by #configure, with their defaults. A new security
|
|
27
|
+
# knob is a new entry here, not another keyword parameter.
|
|
28
|
+
CONFIGURE_DEFAULTS = {
|
|
29
|
+
csrf_protection: false,
|
|
30
|
+
request_validation: false,
|
|
31
|
+
rate_limiting: false,
|
|
32
|
+
trusted_proxies: [].freeze,
|
|
33
|
+
trusted_proxy_depth: nil,
|
|
34
|
+
trusted_proxy_header: nil,
|
|
35
|
+
security_headers: {}.freeze,
|
|
36
|
+
hsts: false,
|
|
37
|
+
csp: false,
|
|
38
|
+
frame_protection: false,
|
|
39
|
+
authentication: false,
|
|
40
|
+
}.freeze
|
|
41
|
+
|
|
42
|
+
# The options #configure resolved: CONFIGURE_DEFAULTS overlaid with the
|
|
43
|
+
# caller's, read through accessors so a misspelled read in #configure
|
|
44
|
+
# raises instead of returning nil.
|
|
45
|
+
ConfigureOptions = Data.define(*CONFIGURE_DEFAULTS.keys)
|
|
46
|
+
|
|
26
47
|
# Unified security configuration method with sensible defaults
|
|
27
48
|
#
|
|
28
49
|
# Provides a comprehensive, one-stop configuration method for Otto's security features.
|
|
29
50
|
# This method allows configuring multiple security aspects in a single call, with flexible options.
|
|
51
|
+
# Every option is optional; see CONFIGURE_DEFAULTS.
|
|
30
52
|
#
|
|
31
|
-
# @param
|
|
53
|
+
# @param options [Hash] security options
|
|
54
|
+
# @option options [Boolean, Hash] :csrf_protection Enable CSRF protection
|
|
32
55
|
# - `true`: Enable with default settings
|
|
33
56
|
# - `Hash`: Provide custom CSRF configuration
|
|
34
|
-
# @
|
|
35
|
-
# @
|
|
57
|
+
# @option options [Boolean] :request_validation Enable input validation and sanitization
|
|
58
|
+
# @option options [Boolean, Hash] :rate_limiting Enable rate limiting
|
|
36
59
|
# - `true`: Enable with default settings
|
|
37
60
|
# - `Hash`: Provide custom rate limiting rules
|
|
38
|
-
# @
|
|
39
|
-
# CIDR ranges to trust, or :none to assert that no proxy
|
|
40
|
-
#
|
|
41
|
-
#
|
|
42
|
-
#
|
|
43
|
-
#
|
|
44
|
-
#
|
|
45
|
-
#
|
|
46
|
-
#
|
|
47
|
-
#
|
|
61
|
+
# @option options [String, Array<String>, Symbol] :trusted_proxies IP
|
|
62
|
+
# addresses or CIDR ranges to trust, or :none to assert that no proxy
|
|
63
|
+
# is trusted
|
|
64
|
+
# @option options [Integer, nil] :trusted_proxy_depth Count-based proxy
|
|
65
|
+
# depth ("trust the last N hops") for non-enumerable proxy tiers;
|
|
66
|
+
# mutually exclusive with trusted_proxies
|
|
67
|
+
# @option options [String, nil] :trusted_proxy_header Forwarded header
|
|
68
|
+
# depth mode counts hops from: 'X-Forwarded-For' (default), 'Forwarded'
|
|
69
|
+
# (RFC 7239), or 'Both'. Otto reads it only in depth mode, but setting
|
|
70
|
+
# it always pins Rack::Request.forwarded_priority (process-global) to
|
|
71
|
+
# that family and claims the family for this process; see
|
|
48
72
|
# Otto::Security::Config.apply_rack_forwarding_family!.
|
|
49
|
-
# @
|
|
50
|
-
# @
|
|
51
|
-
# @
|
|
52
|
-
# @
|
|
53
|
-
# @
|
|
73
|
+
# @option options [Hash] :security_headers Custom security headers to merge with defaults
|
|
74
|
+
# @option options [Boolean] :hsts Enable HTTP Strict Transport Security
|
|
75
|
+
# @option options [Boolean, String] :csp Enable Content Security Policy
|
|
76
|
+
# @option options [Boolean, String] :frame_protection Enable frame protection
|
|
77
|
+
# @option options [Boolean] :authentication Accepted for compatibility;
|
|
78
|
+
# authentication is configured through strategies (#add_auth_strategy)
|
|
79
|
+
# @raise [ArgumentError] for an unrecognized option
|
|
54
80
|
#
|
|
55
81
|
# @example Configure multiple security features in one call
|
|
56
82
|
# otto.security.configure(
|
|
@@ -63,41 +89,31 @@ class Otto
|
|
|
63
89
|
# csp: "default-src 'self'",
|
|
64
90
|
# frame_protection: 'SAMEORIGIN'
|
|
65
91
|
# )
|
|
66
|
-
def configure(
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
hsts: false,
|
|
75
|
-
csp: false,
|
|
76
|
-
frame_protection: false,
|
|
77
|
-
authentication: false
|
|
78
|
-
)
|
|
79
|
-
enable_csrf_protection! if csrf_protection
|
|
80
|
-
enable_request_validation! if request_validation
|
|
81
|
-
enable_rate_limiting!(rate_limiting.is_a?(Hash) ? rate_limiting : {}) if rate_limiting
|
|
82
|
-
|
|
83
|
-
if Otto::Security::Config.trust_no_proxies_option?(trusted_proxies)
|
|
92
|
+
def configure(**options)
|
|
93
|
+
opts = resolve_configure_options(options)
|
|
94
|
+
|
|
95
|
+
enable_csrf_protection! if opts.csrf_protection
|
|
96
|
+
enable_request_validation! if opts.request_validation
|
|
97
|
+
enable_rate_limiting!(opts.rate_limiting.is_a?(Hash) ? opts.rate_limiting : {}) if opts.rate_limiting
|
|
98
|
+
|
|
99
|
+
if Otto::Security::Config.trust_no_proxies_option?(opts.trusted_proxies)
|
|
84
100
|
trust_no_proxies!
|
|
85
101
|
else
|
|
86
102
|
# Pass the list whole so add_trusted_proxy validates every entry
|
|
87
103
|
# before registering any; a mixed list like ['10.0.0.0/8', 'none']
|
|
88
104
|
# must not leave the first half installed.
|
|
89
|
-
add_trusted_proxy(Array(trusted_proxies)) unless Array(trusted_proxies).empty?
|
|
105
|
+
add_trusted_proxy(Array(opts.trusted_proxies)) unless Array(opts.trusted_proxies).empty?
|
|
90
106
|
end
|
|
91
|
-
self.trusted_proxy_depth = trusted_proxy_depth unless trusted_proxy_depth.nil?
|
|
92
|
-
self.trusted_proxy_header = trusted_proxy_header unless trusted_proxy_header.nil?
|
|
107
|
+
self.trusted_proxy_depth = opts.trusted_proxy_depth unless opts.trusted_proxy_depth.nil?
|
|
108
|
+
self.trusted_proxy_header = opts.trusted_proxy_header unless opts.trusted_proxy_header.nil?
|
|
93
109
|
# Proxy trust configured here (after Otto.new) commits the app to its
|
|
94
110
|
# forwarding family now rather than at freeze.
|
|
95
111
|
@security_config.commit_rack_forwarding_family!
|
|
96
|
-
self.security_headers = security_headers unless security_headers.empty?
|
|
112
|
+
self.security_headers = opts.security_headers unless opts.security_headers.empty?
|
|
97
113
|
|
|
98
|
-
enable_hsts! if hsts
|
|
99
|
-
enable_csp! if csp
|
|
100
|
-
enable_frame_protection! if frame_protection
|
|
114
|
+
enable_hsts! if opts.hsts
|
|
115
|
+
enable_csp! if opts.csp
|
|
116
|
+
enable_frame_protection! if opts.frame_protection
|
|
101
117
|
end
|
|
102
118
|
|
|
103
119
|
# Enable CSRF protection for POST, PUT, DELETE, and PATCH requests.
|
|
@@ -195,6 +211,13 @@ class Otto
|
|
|
195
211
|
@security_config.security_headers.merge!(headers)
|
|
196
212
|
end
|
|
197
213
|
|
|
214
|
+
# Set the Referrer-Policy value added to Otto responses.
|
|
215
|
+
#
|
|
216
|
+
# @param policy [String] one W3C Referrer Policy HTTP token
|
|
217
|
+
def referrer_policy=(policy)
|
|
218
|
+
@security_config.referrer_policy = policy
|
|
219
|
+
end
|
|
220
|
+
|
|
198
221
|
# Enable HTTP Strict Transport Security (HSTS) header.
|
|
199
222
|
# WARNING: This can make your domain inaccessible if HTTPS is not properly
|
|
200
223
|
# configured. Only enable this when you're certain HTTPS is working correctly.
|
|
@@ -249,7 +272,8 @@ class Otto
|
|
|
249
272
|
# inject {Otto::Security::CSP::ReportMiddleware} pinned OUTERMOST so it
|
|
250
273
|
# intercepts report POSTs ahead of CSRF regardless of enable order.
|
|
251
274
|
#
|
|
252
|
-
# @param report_uri [String] path browsers POST reports to
|
|
275
|
+
# @param report_uri [String] site-absolute path browsers POST reports to,
|
|
276
|
+
# including any mount prefix (see {Otto::Security::Config#csp_report_uri=})
|
|
253
277
|
# @param endpoint_url [String, nil] absolute URL for the modern Reporting
|
|
254
278
|
# API endpoint (emits `report-to` + `Reporting-Endpoints`); nil emits
|
|
255
279
|
# only the legacy `report-uri`
|
|
@@ -267,7 +291,8 @@ class Otto
|
|
|
267
291
|
# Configure the CSP violation report path without injecting middleware.
|
|
268
292
|
# Prefer {#enable_csp_reporting!} for the full turnkey setup.
|
|
269
293
|
#
|
|
270
|
-
# @param uri [String, nil] report path
|
|
294
|
+
# @param uri [String, nil] site-absolute report path, including any mount
|
|
295
|
+
# prefix (see {Otto::Security::Config#csp_report_uri=}), or nil to disable
|
|
271
296
|
def csp_report_uri=(uri)
|
|
272
297
|
@security_config.csp_report_uri = uri
|
|
273
298
|
end
|
|
@@ -327,6 +352,18 @@ class Otto
|
|
|
327
352
|
|
|
328
353
|
private
|
|
329
354
|
|
|
355
|
+
# Overlay the caller's options on CONFIGURE_DEFAULTS. An unrecognized
|
|
356
|
+
# key raises the ArgumentError a keyword parameter list raises, checked
|
|
357
|
+
# here because Data.new would also accept a String spelling of a member.
|
|
358
|
+
def resolve_configure_options(options)
|
|
359
|
+
unknown = options.keys - CONFIGURE_DEFAULTS.keys
|
|
360
|
+
unless unknown.empty?
|
|
361
|
+
raise ArgumentError, "unknown keyword#{'s' if unknown.size > 1}: #{unknown.map(&:inspect).join(', ')}"
|
|
362
|
+
end
|
|
363
|
+
|
|
364
|
+
ConfigureOptions.new(**CONFIGURE_DEFAULTS, **options)
|
|
365
|
+
end
|
|
366
|
+
|
|
330
367
|
def middleware_enabled?(middleware_class)
|
|
331
368
|
@middleware_stack.includes?(middleware_class)
|
|
332
369
|
end
|
data/lib/otto/security/core.rb
CHANGED
|
@@ -221,8 +221,10 @@ class Otto
|
|
|
221
221
|
# emits a `report-to` directive plus a `Reporting-Endpoints` header so those
|
|
222
222
|
# browsers deliver `application/reports+json` to the same receiver.
|
|
223
223
|
#
|
|
224
|
-
# @param report_uri [String] path browsers POST reports to
|
|
225
|
-
#
|
|
224
|
+
# @param report_uri [String] site-absolute path browsers POST reports to,
|
|
225
|
+
# including any mount prefix (e.g. `/_/csp-report`, or
|
|
226
|
+
# `/api/_/csp-report` when mounted at `/api`). See
|
|
227
|
+
# {Otto::Security::Config#csp_report_uri=}.
|
|
226
228
|
# @param endpoint_url [String, nil] absolute URL for the modern Reporting
|
|
227
229
|
# API endpoint (e.g. `https://example.com/_/csp-report`); nil emits only
|
|
228
230
|
# the legacy `report-uri`.
|
|
@@ -22,6 +22,8 @@ class Otto
|
|
|
22
22
|
# not configured the middleware is a transparent pass-through.
|
|
23
23
|
# - Only intercepts a POST whose path matches the configured report URI.
|
|
24
24
|
# Everything else (other paths, other methods) passes through untouched.
|
|
25
|
+
# The match is on the full request path (mount prefix included), since
|
|
26
|
+
# the report URI is the site-absolute path the browser POSTs to.
|
|
25
27
|
# - Short-circuits BEFORE inner middleware, so CSRF, auth, and rate
|
|
26
28
|
# limiting never see the request. This is why browsers can POST reports
|
|
27
29
|
# with no CSRF token: the report never reaches the CSRF middleware.
|
|
@@ -76,6 +78,19 @@ class Otto
|
|
|
76
78
|
# True only when reporting is configured AND this is a POST to the
|
|
77
79
|
# configured report path.
|
|
78
80
|
#
|
|
81
|
+
# The configured path is site-absolute: it is emitted verbatim as the
|
|
82
|
+
# `report-uri` directive, and the browser resolves it against the site
|
|
83
|
+
# root. So it is compared against the request's full path, SCRIPT_NAME
|
|
84
|
+
# plus PATH_INFO, not the mount-relative PATH_INFO the router matches.
|
|
85
|
+
# Under `map '/api' { run otto }` a report to `/api/csp-report` arrives
|
|
86
|
+
# as SCRIPT_NAME=/api, PATH_INFO=/csp-report and still matches a
|
|
87
|
+
# configured `/api/csp-report`. Unmounted, SCRIPT_NAME is empty and the
|
|
88
|
+
# two forms coincide.
|
|
89
|
+
#
|
|
90
|
+
# Both sides go through Otto::Utils.normalize_path, so a trailing slash
|
|
91
|
+
# or percent-encoded spelling of the report path is intercepted the way
|
|
92
|
+
# the router would normalize it.
|
|
93
|
+
#
|
|
79
94
|
# @param env [Hash]
|
|
80
95
|
# @return [Boolean]
|
|
81
96
|
def report_request?(env)
|
|
@@ -83,7 +98,8 @@ class Otto
|
|
|
83
98
|
return false if report_uri.nil? || report_uri.empty?
|
|
84
99
|
return false unless env['REQUEST_METHOD'] == 'POST'
|
|
85
100
|
|
|
86
|
-
env['PATH_INFO']
|
|
101
|
+
request_path = Otto::Utils.normalize_path("#{env['SCRIPT_NAME']}#{env['PATH_INFO']}")
|
|
102
|
+
request_path == Otto::Utils.normalize_path(report_uri)
|
|
87
103
|
end
|
|
88
104
|
|
|
89
105
|
# Read (capped), parse, and dispatch. Never raises; parse/dispatch
|
data/lib/otto/security/csrf.rb
CHANGED
|
@@ -14,14 +14,29 @@ class Otto
|
|
|
14
14
|
|
|
15
15
|
# Helper methods for CSRF token handling in views and controllers
|
|
16
16
|
module CSRFHelpers
|
|
17
|
+
# A CSRF token for the request's binding. On a safe request a binding
|
|
18
|
+
# is minted when there is none. On an unsafe request only an existing
|
|
19
|
+
# binding is used, as CSRFMiddleware does: a binding minted there never
|
|
20
|
+
# reaches the client, because the binding cookie is set only on safe
|
|
21
|
+
# requests.
|
|
22
|
+
#
|
|
23
|
+
# @return [String, nil] the token, or nil when an unsafe request has no
|
|
24
|
+
# binding or the security config is unavailable
|
|
17
25
|
def csrf_token
|
|
18
26
|
if @csrf_token.nil? && otto.respond_to?(:security_config)
|
|
19
|
-
|
|
20
|
-
|
|
27
|
+
config = otto.security_config
|
|
28
|
+
session_id = if CSRFValidation::SAFE_METHODS.include?(req.request_method.to_s.upcase)
|
|
29
|
+
config.get_or_create_session_id(req)
|
|
30
|
+
else
|
|
31
|
+
config.existing_session_id(req)
|
|
32
|
+
end
|
|
33
|
+
@csrf_token = config.generate_csrf_token(session_id) if session_id
|
|
21
34
|
end
|
|
22
35
|
@csrf_token
|
|
23
36
|
end
|
|
24
37
|
|
|
38
|
+
# The tags below render an empty content or value when #csrf_token is
|
|
39
|
+
# nil, and a request that sends that value fails the CSRF check.
|
|
25
40
|
def csrf_meta_tag
|
|
26
41
|
%(<meta name="csrf-token" content="#{csrf_token}">)
|
|
27
42
|
end
|
|
@@ -15,8 +15,8 @@ class Otto
|
|
|
15
15
|
# carried, or how a rejection is shaped. The including object must expose a
|
|
16
16
|
# +@config+ (an +Otto::Security::Config+).
|
|
17
17
|
module CSRFValidation
|
|
18
|
-
#
|
|
19
|
-
#
|
|
18
|
+
# The request methods RFC 9110, section 9.2.1 defines as safe. They are
|
|
19
|
+
# exempt from token validation.
|
|
20
20
|
SAFE_METHODS = %w[GET HEAD OPTIONS TRACE].freeze
|
|
21
21
|
|
|
22
22
|
# Static 403 body. Frozen once so a rejected request does not re-serialize
|
|
@@ -34,10 +34,13 @@ class Otto
|
|
|
34
34
|
|
|
35
35
|
def valid_csrf_token?(request)
|
|
36
36
|
token = extract_csrf_token(request)
|
|
37
|
-
# Reject
|
|
38
|
-
#
|
|
39
|
-
#
|
|
40
|
-
|
|
37
|
+
# Reject a token that cannot be valid before reading the binding or
|
|
38
|
+
# running HMAC verification (#186 review): a missing value, anything
|
|
39
|
+
# that is not an ASCII String (a valid token is hex), and a blank or
|
|
40
|
+
# whitespace-only String. Rack parses _csrf_token[]= into an Array
|
|
41
|
+
# and _csrf_token[k]= into a Hash, and #strip raises on invalid bytes.
|
|
42
|
+
return false unless token.is_a?(String) && token.ascii_only?
|
|
43
|
+
return false if token.strip.empty?
|
|
41
44
|
|
|
42
45
|
session_id = extract_session_id(request)
|
|
43
46
|
@config.verify_csrf_token(token, session_id)
|
|
@@ -56,8 +59,11 @@ class Otto
|
|
|
56
59
|
token
|
|
57
60
|
end
|
|
58
61
|
|
|
62
|
+
# The binding to verify against, or nil. A request that has none
|
|
63
|
+
# cannot pass, so none is created for it: behind a session store that
|
|
64
|
+
# write would commit a new session and set its cookie on the 403.
|
|
59
65
|
def extract_session_id(request)
|
|
60
|
-
@config.
|
|
66
|
+
@config.existing_session_id(request)
|
|
61
67
|
end
|
|
62
68
|
|
|
63
69
|
def csrf_error_response
|
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
# frozen_string_literal: true
|
|
4
4
|
|
|
5
5
|
require_relative '../config'
|
|
6
|
+
require_relative '../csrf_validation'
|
|
6
7
|
|
|
7
8
|
class Otto
|
|
8
9
|
module Security
|
|
9
10
|
module Middleware
|
|
10
|
-
# Global middleware that injects CSRF tokens into HTML responses
|
|
11
|
+
# Global middleware that injects CSRF tokens into HTML responses and
|
|
12
|
+
# sets the CSRF binding cookie on responses to safe requests.
|
|
11
13
|
#
|
|
12
14
|
# Token *enforcement* deliberately does NOT live here. This middleware
|
|
13
15
|
# runs ahead of route matching, so it cannot see per-route options like
|
|
@@ -19,6 +21,8 @@ class Otto
|
|
|
19
21
|
# forms and meta tags can carry it — which is method/content-type based
|
|
20
22
|
# and correctly stays global.
|
|
21
23
|
class CSRFMiddleware
|
|
24
|
+
include Otto::Security::CSRFValidation
|
|
25
|
+
|
|
22
26
|
def initialize(app, config = nil)
|
|
23
27
|
@app = app
|
|
24
28
|
@config = config || Otto::Security::Config.new
|
|
@@ -27,76 +31,238 @@ class Otto
|
|
|
27
31
|
def call(env)
|
|
28
32
|
return @app.call(env) unless @config.csrf_enabled?
|
|
29
33
|
|
|
30
|
-
request
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
+
request = Otto::Request.new(env)
|
|
35
|
+
# Read before @app.call: a session store inside this middleware
|
|
36
|
+
# replaces rack.session there (see #record_store_minted_binding).
|
|
37
|
+
outer_session = env['rack.session']
|
|
38
|
+
response = @app.call(env)
|
|
39
|
+
response = inject_csrf_token(request, with_copied_headers(response), outer_session) if html_response?(response)
|
|
40
|
+
|
|
41
|
+
apply_binding_cookie(request, response)
|
|
34
42
|
end
|
|
35
43
|
|
|
36
44
|
private
|
|
37
45
|
|
|
38
|
-
|
|
39
|
-
|
|
46
|
+
# +response+ with a copy of its headers, so #inject_csrf_token can add
|
|
47
|
+
# Cache-Control and Content-Length without changing the app's
|
|
48
|
+
# headers, which the app may freeze or share between responses.
|
|
49
|
+
def with_copied_headers(response)
|
|
50
|
+
response.dup.tap { |copy| copy[1] = response[1].dup }
|
|
51
|
+
end
|
|
40
52
|
|
|
41
|
-
|
|
42
|
-
|
|
53
|
+
# Sets the binding cookie on any response, HTML or not, to a safe
|
|
54
|
+
# request that resolved a binding the client does not already send:
|
|
55
|
+
# one minted, or read from csrf_session_key, which
|
|
56
|
+
# Otto::Security::Config#get_or_create_session_id records in
|
|
57
|
+
# otto.csrf_binding (as does #record_store_minted_binding for a store
|
|
58
|
+
# that runs inside this middleware). A JSON client that never loads an
|
|
59
|
+
# HTML page needs it too, or it would get a new binding, and a 403, on
|
|
60
|
+
# every request.
|
|
61
|
+
#
|
|
62
|
+
# A session id the request already had and a binding read from a
|
|
63
|
+
# cookie are not recorded, so they are never copied: the client sends
|
|
64
|
+
# them again, and a copy would sit in a second cookie whose lifetime
|
|
65
|
+
# and attributes the application does not configure. A session id
|
|
66
|
+
# read from a cookie someone planted would outlive the session cookie
|
|
67
|
+
# there.
|
|
68
|
+
#
|
|
69
|
+
# An unsafe request does not set it: one that passes the CSRF check
|
|
70
|
+
# already carries its binding, and a cross-site one arrives without
|
|
71
|
+
# the SameSite=Lax cookie, so a binding set on its response would
|
|
72
|
+
# replace the victim's and void their open forms. The app's headers
|
|
73
|
+
# are copied rather than changed, as the app may freeze them or share
|
|
74
|
+
# them between responses.
|
|
75
|
+
def apply_binding_cookie(request, response)
|
|
76
|
+
binding_id = request.env['otto.csrf_binding']
|
|
77
|
+
return response unless binding_id && safe_method?(request.request_method)
|
|
78
|
+
return response unless response.is_a?(Array) && response.length >= 2
|
|
43
79
|
|
|
44
|
-
|
|
80
|
+
new_cookie = binding_cookie(request, binding_id)
|
|
81
|
+
return response unless new_cookie
|
|
45
82
|
|
|
46
|
-
|
|
47
|
-
|
|
83
|
+
headers = response[1].dup
|
|
84
|
+
append_binding_cookie(headers, new_cookie)
|
|
85
|
+
response.dup.tap { |copy| copy[1] = headers }
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def inject_csrf_token(request, response, outer_session)
|
|
89
|
+
return response unless response.is_a?(Array) && response.length >= 3
|
|
48
90
|
|
|
49
|
-
|
|
50
|
-
|
|
91
|
+
status, headers, body = response
|
|
92
|
+
return response unless html_content_type?(headers)
|
|
93
|
+
|
|
94
|
+
session_id = token_binding(request, outer_session)
|
|
95
|
+
return response unless session_id
|
|
51
96
|
|
|
52
97
|
# Generate new CSRF token
|
|
53
98
|
csrf_token = @config.generate_csrf_token(session_id)
|
|
54
99
|
|
|
55
|
-
# Inject meta tag into HTML head
|
|
56
|
-
|
|
100
|
+
# Inject meta tag into HTML head. Rack lets middleware read a body
|
|
101
|
+
# itself only through #to_ary, which also closes it, so the parts
|
|
102
|
+
# it returns replace the body. Any other body, such as a file or a
|
|
103
|
+
# stream, is returned unread.
|
|
104
|
+
return response unless body.respond_to?(:to_ary)
|
|
105
|
+
|
|
106
|
+
# The parts are searched as bytes. The <head> pattern and the meta
|
|
107
|
+
# tag are ASCII, so a part with invalid bytes, or parts in
|
|
108
|
+
# incompatible encodings, can neither raise here nor change. The
|
|
109
|
+
# page then gets the encoding its parts have when joined as text,
|
|
110
|
+
# and stays binary only when they cannot be joined.
|
|
111
|
+
parts = body.to_ary
|
|
112
|
+
strings = parts.map(&:to_s)
|
|
113
|
+
body_content = strings.map(&:b).join
|
|
57
114
|
|
|
58
115
|
head_open_tag = /<head(?:\s[^>]*)?>/i
|
|
59
116
|
if body_content.match?(head_open_tag)
|
|
60
|
-
meta_tag
|
|
61
|
-
body_content
|
|
117
|
+
meta_tag = %(<meta name="csrf-token" content="#{csrf_token}">)
|
|
118
|
+
body_content = body_content.sub(head_open_tag) { |tag| "#{tag}\n#{meta_tag}" }
|
|
119
|
+
text_encoding = begin
|
|
120
|
+
strings.join.encoding
|
|
121
|
+
rescue Encoding::CompatibilityError
|
|
122
|
+
nil
|
|
123
|
+
end
|
|
124
|
+
body_content.force_encoding(text_encoding) if text_encoding
|
|
62
125
|
|
|
63
126
|
# Update content length if present
|
|
64
127
|
content_length_key = headers.keys.find { |k| k.downcase == 'content-length' }
|
|
65
128
|
headers[content_length_key] = body_content.bytesize.to_s if content_length_key
|
|
129
|
+
keep_out_of_shared_caches(headers)
|
|
66
130
|
|
|
67
131
|
[status, headers, [body_content]]
|
|
68
132
|
else
|
|
69
|
-
|
|
133
|
+
[status, headers, parts]
|
|
70
134
|
end
|
|
71
135
|
end
|
|
72
136
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
137
|
+
# The binding the injected token is bound to. A safe request gets one
|
|
138
|
+
# minted when it has none. An unsafe request uses only the binding it
|
|
139
|
+
# already has: a cross-site POST to a csrf=exempt route arrives
|
|
140
|
+
# without the SameSite=Lax binding cookie, and a binding minted for
|
|
141
|
+
# it would replace the victim's (or, behind a session store, commit a
|
|
142
|
+
# new session over theirs). Without a binding the page gets no token.
|
|
143
|
+
def token_binding(request, outer_session)
|
|
144
|
+
return @config.existing_session_id(request) unless safe_method?(request.request_method)
|
|
145
|
+
|
|
146
|
+
existing_id = @config.existing_session_id(request)
|
|
147
|
+
binding_id = @config.get_or_create_session_id(request)
|
|
148
|
+
record_store_minted_binding(request, binding_id, outer_session) unless existing_id
|
|
149
|
+
binding_id
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
# Records a binding minted here in otto.csrf_binding when it is the id
|
|
153
|
+
# a session store created for Otto's write and that store will not
|
|
154
|
+
# send it. get_or_create_session_id does not record a store's id,
|
|
155
|
+
# because the store sends it in its own cookie when it commits. That
|
|
156
|
+
# holds for +outer_session+, set up by a store that wraps this
|
|
157
|
+
# middleware and commits after it returns. A store added inside this
|
|
158
|
+
# middleware (with otto.use before CSRF protection is enabled) has
|
|
159
|
+
# committed before the token is injected, so it never sends the id it
|
|
160
|
+
# creates here, and only the binding cookie can carry it.
|
|
161
|
+
# The id is new, so this copies nothing a client could have planted.
|
|
162
|
+
def record_store_minted_binding(request, binding_id, outer_session)
|
|
163
|
+
return if session_id_of?(outer_session, binding_id)
|
|
164
|
+
|
|
165
|
+
request.env['otto.csrf_binding'] = binding_id
|
|
166
|
+
end
|
|
77
167
|
|
|
78
|
-
|
|
79
|
-
|
|
168
|
+
# Whether +binding_id+ is the id of +session+.
|
|
169
|
+
def session_id_of?(session, binding_id)
|
|
170
|
+
session.respond_to?(:id) && session.id.to_s == binding_id
|
|
171
|
+
rescue StandardError
|
|
172
|
+
false
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# The Set-Cookie value for the binding cookie, or nil when the request
|
|
176
|
+
# already carries +session_id+ in it. On HTTPS the cookie is
|
|
177
|
+
# __Host-otto_session (Secure, Path=/, no Domain); on HTTP it is
|
|
178
|
+
# _otto_session. See Otto::Security::Config#csrf_binding_cookie_name.
|
|
179
|
+
#
|
|
180
|
+
# The value is URL-encoded because Rack URL-decodes cookie values when
|
|
181
|
+
# it parses them (Rack::Utils.parse_cookies_header). A binding that is
|
|
182
|
+
# not a hex token, such as a value an app stored under
|
|
183
|
+
# csrf_session_key, then reads back unchanged instead of being cut at
|
|
184
|
+
# a ';' or decoded a second time.
|
|
185
|
+
def binding_cookie(request, session_id)
|
|
186
|
+
cookie_name = @config.csrf_binding_cookie_name(request)
|
|
187
|
+
return if request.cookies[cookie_name] == session_id
|
|
188
|
+
|
|
189
|
+
cookie_value = "#{Rack::Utils.escape(session_id.to_s)}; Path=/; HttpOnly; SameSite=Lax"
|
|
80
190
|
cookie_value += '; Secure' if request.scheme == 'https'
|
|
191
|
+
"#{cookie_name}=#{cookie_value}"
|
|
192
|
+
end
|
|
81
193
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
194
|
+
# Adds +cookie+ to the Set-Cookie header. An existing value, String or
|
|
195
|
+
# Array, is replaced by a new Array rather than appended to in place,
|
|
196
|
+
# since the app may freeze it or share it between responses. A plain
|
|
197
|
+
# Hash that spells the header Set-Cookie keeps that key.
|
|
198
|
+
def append_set_cookie(headers, cookie)
|
|
199
|
+
key = !headers.key?('set-cookie') && headers.key?('Set-Cookie') ? 'Set-Cookie' : 'set-cookie'
|
|
200
|
+
existing = headers[key]
|
|
201
|
+
headers[key] = existing ? [*existing, cookie] : cookie
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
# Adds the binding cookie to +headers+ and keeps the response out of
|
|
205
|
+
# shared caches (#keep_out_of_shared_caches), unless the response
|
|
206
|
+
# already sets a cookie of that name (#sets_cookie?).
|
|
207
|
+
def append_binding_cookie(headers, cookie)
|
|
208
|
+
return if sets_cookie?(headers, cookie[/\A[^=]+/])
|
|
209
|
+
|
|
210
|
+
append_set_cookie(headers, cookie)
|
|
211
|
+
keep_out_of_shared_caches(headers)
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
# Whether +headers+ already set a cookie named +name+, as they do when
|
|
215
|
+
# this middleware runs more than once for a request: added again by
|
|
216
|
+
# the app, or in nested CSRF-enabled Ottos. RFC 6265, section 4.1.1:
|
|
217
|
+
# "Servers SHOULD NOT include more than one Set-Cookie header field in
|
|
218
|
+
# the same response with the same cookie-name."
|
|
219
|
+
#
|
|
220
|
+
# The first, innermost, middleware's cookie is kept. When the configs
|
|
221
|
+
# differ (csrf_session_key without session middleware), so do the
|
|
222
|
+
# bindings, and a browser keeps the last cookie of a name. Keeping
|
|
223
|
+
# the outer one would make the inner Otto, which checks the requests
|
|
224
|
+
# its routes receive, reject the tokens it issued.
|
|
225
|
+
def sets_cookie?(headers, name)
|
|
226
|
+
pattern = /\A\s*#{Regexp.escape(name)}\s*=/
|
|
227
|
+
headers.any? do |key, value|
|
|
228
|
+
key.casecmp?('set-cookie') && Array(value).any? { |lines| lines.to_s.split("\n").any?(pattern) }
|
|
93
229
|
end
|
|
94
230
|
end
|
|
95
231
|
|
|
232
|
+
# Marks a response that carries the binding cookie or an injected
|
|
233
|
+
# token, both meant for one client, with Cache-Control: private.
|
|
234
|
+
# RFC 9111, section 7.3: "the Set-Cookie response header field
|
|
235
|
+
# [COOKIE] does not inhibit caching". Section 5.2.2.7: "The
|
|
236
|
+
# unqualified private response directive indicates that a shared
|
|
237
|
+
# cache MUST NOT store the response (i.e., the response is intended
|
|
238
|
+
# for a single user)." The browser's own cache may still store it.
|
|
239
|
+
#
|
|
240
|
+
# stale-if-error=0 (RFC 5861) is for a cache that stores the
|
|
241
|
+
# response anyway. CloudFront does when the cache policy's minimum
|
|
242
|
+
# TTL is above 0, and its documentation says: "If the origin is
|
|
243
|
+
# unreachable and the minimum or maximum TTL value is greater than
|
|
244
|
+
# 0, CloudFront will serve the object that it got from the origin
|
|
245
|
+
# previously. To avoid this behavior, include the Cache-Control:
|
|
246
|
+
# stale-if-error=0 directive with the object returned from the
|
|
247
|
+
# origin."
|
|
248
|
+
#
|
|
249
|
+
# A response on which the app set Cache-Control or Expires keeps the
|
|
250
|
+
# app's choice, and gets nothing added.
|
|
251
|
+
def keep_out_of_shared_caches(headers)
|
|
252
|
+
return if headers.each_key.any? { |key| key.casecmp?('cache-control') || key.casecmp?('expires') }
|
|
253
|
+
|
|
254
|
+
headers['cache-control'] = 'private, stale-if-error=0'
|
|
255
|
+
end
|
|
256
|
+
|
|
96
257
|
def html_response?(response)
|
|
97
258
|
return false unless response.is_a?(Array) && response.length >= 2
|
|
98
259
|
|
|
99
|
-
|
|
260
|
+
html_content_type?(response[1])
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
# Whether +headers+ declare a text/html Content-Type, under any case
|
|
264
|
+
# of the key.
|
|
265
|
+
def html_content_type?(headers)
|
|
100
266
|
content_type = headers.find { |k, _v| k.downcase == 'content-type' }&.last
|
|
101
267
|
content_type&.include?('text/html')
|
|
102
268
|
end
|