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.
Files changed (73) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +1 -1
  3. data/.github/workflows/claude-code-review.yml +1 -1
  4. data/.github/workflows/claude.yml +1 -1
  5. data/.github/workflows/code-smells.yml +2 -2
  6. data/.github/workflows/release-gem.yml +1 -1
  7. data/.github/workflows/ruby-lint.yml +1 -1
  8. data/.github/workflows/yardoc.yml +1 -1
  9. data/.rubocop_todo.yml +2 -2
  10. data/AGENTS.md +4 -2
  11. data/CHANGELOG.rst +792 -0
  12. data/Gemfile +3 -2
  13. data/Gemfile.lock +13 -8
  14. data/README.md +6 -0
  15. data/docs/README.md +4 -0
  16. data/docs/audits/2026-09-28-v2.12.0-code-audit.md +732 -0
  17. data/docs/audits/README.md +63 -0
  18. data/docs/guides/authentication.md +329 -0
  19. data/docs/guides/forwarded-authority.md +85 -5
  20. data/docs/guides/mcp.md +40 -4
  21. data/docs/guides/privacy.md +28 -2
  22. data/docs/guides/routing.md +76 -9
  23. data/docs/guides/testing-guide.md +146 -5
  24. data/docs/migrating/v2.3.0.md +13 -7
  25. data/docs/reference/authentication.md +70 -22
  26. data/examples/lambda_handlers/README.md +4 -4
  27. data/examples/lambda_handlers/handlers.rb +4 -5
  28. data/examples/lambda_handlers/routes +2 -2
  29. data/examples/mcp_demo/README.md +65 -27
  30. data/examples/mcp_demo/app.rb +8 -5
  31. data/examples/mcp_demo/config.ru +50 -3
  32. data/examples/mcp_demo/routes +10 -6
  33. data/examples/security_features/README.md +2 -2
  34. data/lib/otto/caddy_tls/localhost_guard.rb +6 -6
  35. data/lib/otto/caddy_tls/server.rb +8 -4
  36. data/lib/otto/core/configuration.rb +5 -3
  37. data/lib/otto/core/option_hash.rb +124 -0
  38. data/lib/otto/core/redacted_inspect.rb +149 -0
  39. data/lib/otto/core/router.rb +57 -34
  40. data/lib/otto/core.rb +2 -0
  41. data/lib/otto/env_keys.rb +30 -6
  42. data/lib/otto/logging_helpers.rb +1 -1
  43. data/lib/otto/mcp/auth/token.rb +12 -1
  44. data/lib/otto/mcp/protocol.rb +3 -3
  45. data/lib/otto/mcp/registry.rb +28 -2
  46. data/lib/otto/mcp/route_parser.rb +20 -8
  47. data/lib/otto/mcp/server.rb +17 -9
  48. data/lib/otto/privacy/config.rb +31 -14
  49. data/lib/otto/privacy/ip_privacy.rb +109 -3
  50. data/lib/otto/privacy/redacted_fingerprint.rb +8 -10
  51. data/lib/otto/request.rb +34 -0
  52. data/lib/otto/response.rb +5 -2
  53. data/lib/otto/route.rb +1 -1
  54. data/lib/otto/route_definition.rb +3 -2
  55. data/lib/otto/route_handlers/base.rb +1 -1
  56. data/lib/otto/route_handlers/logic_class.rb +86 -34
  57. data/lib/otto/security/authentication/route_auth_wrapper.rb +10 -3
  58. data/lib/otto/security/config.rb +703 -345
  59. data/lib/otto/security/configurator.rb +82 -45
  60. data/lib/otto/security/core.rb +4 -2
  61. data/lib/otto/security/csp/report_middleware.rb +17 -1
  62. data/lib/otto/security/csrf.rb +17 -2
  63. data/lib/otto/security/csrf_validation.rb +13 -7
  64. data/lib/otto/security/middleware/csrf_middleware.rb +203 -37
  65. data/lib/otto/security/middleware/ip_privacy_middleware.rb +129 -42
  66. data/lib/otto/security/rate_limiter.rb +8 -5
  67. data/lib/otto/security/trusted_proxy_config.rb +396 -0
  68. data/lib/otto/static.rb +70 -6
  69. data/lib/otto/testing.rb +148 -0
  70. data/lib/otto/utils.rb +166 -40
  71. data/lib/otto/version.rb +1 -1
  72. data/lib/otto.rb +44 -11
  73. 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 csrf_protection [Boolean, Hash] Enable CSRF protection
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
- # @param request_validation [Boolean] Enable input validation and sanitization
35
- # @param rate_limiting [Boolean, Hash] Enable rate limiting
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
- # @param trusted_proxies [String, Array<String>, Symbol] IP addresses or
39
- # CIDR ranges to trust, or :none to assert that no proxy is trusted
40
- # @param trusted_proxy_depth [Integer, nil] Count-based proxy depth ("trust
41
- # the last N hops") for non-enumerable proxy tiers; mutually exclusive
42
- # with trusted_proxies (validated at configuration freeze)
43
- # @param trusted_proxy_header [String, nil] Forwarded header depth mode
44
- # counts hops from: 'X-Forwarded-For' (default), 'Forwarded' (RFC 7239),
45
- # or 'Both'. Otto reads it only in depth mode, but setting it always
46
- # pins Rack::Request.forwarded_priority (process-global) to that family
47
- # and claims the family for this process; see
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
- # @param security_headers [Hash] Custom security headers to merge with defaults
50
- # @param hsts [Boolean] Enable HTTP Strict Transport Security
51
- # @param csp [Boolean, String] Enable Content Security Policy
52
- # @param frame_protection [Boolean, String] Enable frame protection
53
- # @param authentication [Boolean] Enable authentication
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
- csrf_protection: false,
68
- request_validation: false,
69
- rate_limiting: false,
70
- trusted_proxies: [],
71
- trusted_proxy_depth: nil,
72
- trusted_proxy_header: nil,
73
- security_headers: {},
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 (matched against PATH_INFO)
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 (matched against PATH_INFO), or nil to disable
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
@@ -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 (matched against
225
- # `PATH_INFO`, e.g. `/_/csp-report`).
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'] == report_uri
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
@@ -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
- session_id = otto.security_config.get_or_create_session_id(req)
20
- @csrf_token = otto.security_config.generate_csrf_token(session_id)
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
- # HTTP methods that never mutate state and so are exempt from token
19
- # validation (RFC 7231 safe methods plus TRACE).
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 nil / blank / whitespace-only tokens up front, before creating
38
- # a session or running HMAC verification — obviously-malformed input
39
- # should not cause session churn (#186 review).
40
- return false if token.nil? || token.strip.empty?
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.get_or_create_session_id(request)
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 = Otto::Request.new(env)
31
- response = @app.call(env)
32
- response = inject_csrf_token(request, response) if html_response?(response)
33
- response
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
- def inject_csrf_token(request, response)
39
- return response unless response.is_a?(Array) && response.length >= 3
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
- status, headers, body = response
42
- content_type = headers.find { |k, _v| k.downcase == 'content-type' }&.last
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
- return response unless content_type&.include?('text/html')
80
+ new_cookie = binding_cookie(request, binding_id)
81
+ return response unless new_cookie
45
82
 
46
- # Get or create session ID
47
- session_id = @config.get_or_create_session_id(request)
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
- # Ensure session ID is saved to cookie if it was newly created
50
- ensure_session_cookie(request, headers, session_id)
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
- body_content = body.respond_to?(:join) ? body.join : body.to_s
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 = %(<meta name="csrf-token" content="#{csrf_token}">)
61
- body_content = body_content.sub(head_open_tag) { |tag| "#{tag}\n#{meta_tag}" }
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
- response
133
+ [status, headers, parts]
70
134
  end
71
135
  end
72
136
 
73
- def ensure_session_cookie(request, headers, session_id)
74
- # Check if session ID already exists in cookies
75
- existing_cookie = request.cookies['_otto_session']
76
- return if existing_cookie == session_id
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
- # Set the session cookie
79
- cookie_value = "#{session_id}; Path=/; HttpOnly; SameSite=Lax"
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
- # Handle existing Set-Cookie headers
83
- existing_cookies = headers['set-cookie'] || headers['Set-Cookie']
84
- if existing_cookies
85
- # Append to existing cookies (handle both string and array formats)
86
- if existing_cookies.is_a?(Array)
87
- existing_cookies << "_otto_session=#{cookie_value}"
88
- else
89
- headers['set-cookie'] = [existing_cookies, "_otto_session=#{cookie_value}"]
90
- end
91
- else
92
- headers['set-cookie'] = "_otto_session=#{cookie_value}"
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
- headers = response[1]
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