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
@@ -5,10 +5,12 @@
5
5
  require 'securerandom'
6
6
  require 'digest'
7
7
  require 'openssl'
8
- require 'ipaddr'
9
8
  require 'rack/request'
9
+ require 'rack/utils'
10
10
  require_relative '../core/freezable'
11
+ require_relative '../core/redacted_inspect'
11
12
  require_relative 'csp/policy'
13
+ require_relative 'trusted_proxy_config'
12
14
 
13
15
  class Otto
14
16
  module Security
@@ -29,15 +31,230 @@ class Otto
29
31
  # config.max_param_depth = 16
30
32
  class Config
31
33
  include Otto::Core::Freezable
34
+ include Otto::Core::RedactedInspect
35
+
36
+ # Otto accepts exactly one W3C Referrer Policy token for its
37
+ # referrer_policy setting. The supported tokens are enumerated below:
38
+ # https://www.w3.org/TR/referrer-policy/#referrer-policy-header-dfn
39
+ REFERRER_POLICIES = %w[
40
+ no-referrer
41
+ no-referrer-when-downgrade
42
+ strict-origin
43
+ strict-origin-when-cross-origin
44
+ same-origin
45
+ origin
46
+ origin-when-cross-origin
47
+ unsafe-url
48
+ ].freeze
49
+ DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'
50
+
51
+ # Thread-safe one-shot flag for a log line that must appear once per
52
+ # config, including after the config is deep-frozen. #deep_freeze! is a
53
+ # no-op, so Otto::Core::Freezable leaves the flag usable when it freezes
54
+ # the config around it. It holds no configuration, only whether the line
55
+ # was logged.
56
+ class OnceFlag
57
+ def initialize
58
+ @mutex = Mutex.new
59
+ @set = false
60
+ end
32
61
 
33
- # Error raised when the two mutually-exclusive trusted-proxy resolution
34
- # modes are configured together: CIDR-walk (enumerated #trusted_proxies)
35
- # and count-based depth (#trusted_proxy_depth >= 1).
36
- PROXY_MODE_CONFLICT_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
37
- Cannot configure both trusted_proxies (CIDR filter mode) and
38
- trusted_proxy_depth >= 1 (count mode). Enumerate proxy CIDRs OR set a
39
- hop count, not both.
40
- MSG
62
+ # Sets the flag.
63
+ #
64
+ # @return [Boolean] true for the first caller only
65
+ def set!
66
+ @mutex.synchronize do
67
+ return false if @set
68
+
69
+ @set = true
70
+ end
71
+ end
72
+
73
+ # @return [self] unfrozen, so #set! keeps working
74
+ def deep_freeze!
75
+ self
76
+ end
77
+ end
78
+
79
+ # Hash-compatible storage that keeps the generic security-header API and
80
+ # the dedicated referrer_policy setting on one validated code path.
81
+ # Existing callers may continue to mutate Config#security_headers like a
82
+ # Hash. Every destructive Hash operation keeps the required
83
+ # Referrer-Policy entry canonical, validates any replacement before
84
+ # committing it, and prevents removal of the dedicated setting.
85
+ class SecurityHeaders < Hash
86
+ REFERRER_POLICY_HEADER = 'referrer-policy'
87
+ REFERRER_POLICY_REMOVAL_MESSAGE =
88
+ 'referrer-policy cannot be removed; assign a valid referrer_policy token instead'
89
+
90
+ def initialize(referrer_policy_validator)
91
+ @referrer_policy_validator = referrer_policy_validator
92
+ super()
93
+ end
94
+
95
+ def []=(header, value)
96
+ if referrer_policy_header?(header)
97
+ validated = @referrer_policy_validator.call(value).dup.freeze
98
+ super(REFERRER_POLICY_HEADER, validated)
99
+ else
100
+ super
101
+ end
102
+ end
103
+ alias store []=
104
+
105
+ def merge!(*other_hashes)
106
+ raise FrozenError, "can't modify frozen #{self.class}" if frozen?
107
+
108
+ replacement = dup
109
+ other_hashes.each do |other_hash|
110
+ converted = Hash.try_convert(other_hash)
111
+ raise TypeError, "no implicit conversion of #{other_hash.class} into Hash" unless converted
112
+
113
+ converted.each_pair do |header, value|
114
+ key = referrer_policy_header?(header) ? REFERRER_POLICY_HEADER : header
115
+ value = yield(key, replacement[key], value) if block_given? && replacement.key?(key)
116
+ replacement[key] = value
117
+ end
118
+ end
119
+
120
+ super(replacement, &nil)
121
+ end
122
+ alias update merge!
123
+
124
+ def replace(other_hash)
125
+ replacement = self.class.new(@referrer_policy_validator)
126
+ replacement.merge!(other_hash)
127
+ replacement[REFERRER_POLICY_HEADER] = self[REFERRER_POLICY_HEADER] unless replacement.key?(
128
+ REFERRER_POLICY_HEADER
129
+ )
130
+ super(replacement)
131
+ end
132
+
133
+ # Clearing custom security headers must not remove Otto's required,
134
+ # dedicated referrer_policy setting.
135
+ def clear
136
+ policy = self[REFERRER_POLICY_HEADER]
137
+ super
138
+ self[REFERRER_POLICY_HEADER] = policy
139
+ self
140
+ end
141
+
142
+ def delete(header, &)
143
+ raise ArgumentError, REFERRER_POLICY_REMOVAL_MESSAGE if referrer_policy_header?(header)
144
+
145
+ super
146
+ end
147
+
148
+ def delete_if(&block)
149
+ return enum_for(__method__) unless block
150
+
151
+ filter_entries!(remove_when: true, return_nil_when_unchanged: false, &block)
152
+ end
153
+
154
+ def reject!(&block)
155
+ return enum_for(__method__) unless block
156
+
157
+ filter_entries!(remove_when: true, return_nil_when_unchanged: true, &block)
158
+ end
159
+
160
+ def keep_if(&block)
161
+ return enum_for(__method__) unless block
162
+
163
+ filter_entries!(remove_when: false, return_nil_when_unchanged: false, &block)
164
+ end
165
+
166
+ def select!(&block)
167
+ return enum_for(__method__) unless block
168
+
169
+ filter_entries!(remove_when: false, return_nil_when_unchanged: true, &block)
170
+ end
171
+ alias filter! select!
172
+
173
+ # Remove the first non-Referrer-Policy entry, keeping the dedicated
174
+ # setting even when it is the only entry left.
175
+ def shift
176
+ raise FrozenError, "can't modify frozen #{self.class}" if frozen?
177
+
178
+ header = each_key.find { |key| !referrer_policy_header?(key) }
179
+ return nil unless header
180
+
181
+ [header, delete(header)]
182
+ end
183
+
184
+ def transform_values!
185
+ return enum_for(__method__) unless block_given?
186
+
187
+ replacement = self.class.new(@referrer_policy_validator)
188
+ each_pair { |header, value| replacement[header] = yield(value) }
189
+ replace(replacement)
190
+ end
191
+
192
+ # Hash#transform_keys! accepts an optional key-mapping Hash, a block,
193
+ # or both (the mapping wins for keys it contains). Referrer-Policy may
194
+ # change case but cannot be renamed to a different field.
195
+ def transform_keys!(*args, &block)
196
+ if args.empty? && !block
197
+ return enum_for(__method__, *args)
198
+ elsif args.length > 1
199
+ raise ArgumentError, "wrong number of arguments (given #{args.length}, expected 0..1)"
200
+ end
201
+
202
+ mapping = args.first
203
+ replacement = self.class.new(@referrer_policy_validator)
204
+ each_pair do |header, value|
205
+ transformed = transformed_header(header, mapping, block)
206
+ raise ArgumentError, REFERRER_POLICY_REMOVAL_MESSAGE if referrer_policy_header?(header) &&
207
+ !referrer_policy_header?(transformed)
208
+
209
+ replacement[transformed] = value
210
+ end
211
+ replace(replacement)
212
+ end
213
+
214
+ # Identity comparison would make normal String lookups miss the
215
+ # canonical Referrer-Policy key and create apparent duplicates.
216
+ def compare_by_identity
217
+ raise ArgumentError, 'security_headers cannot use identity comparison'
218
+ end
219
+
220
+ private
221
+
222
+ def referrer_policy_header?(header)
223
+ header.to_s.casecmp?(REFERRER_POLICY_HEADER)
224
+ end
225
+
226
+ def filter_entries!(remove_when:, return_nil_when_unchanged:)
227
+ replacement = self.class.new(@referrer_policy_validator)
228
+ each_pair do |header, value|
229
+ selected = yield(header, value)
230
+ keep = remove_when ? !selected : selected
231
+ raise ArgumentError, REFERRER_POLICY_REMOVAL_MESSAGE if referrer_policy_header?(header) && !keep
232
+
233
+ replacement[header] = value if keep
234
+ end
235
+
236
+ return nil if return_nil_when_unchanged && replacement == self
237
+
238
+ replace(replacement)
239
+ end
240
+
241
+ def transformed_header(header, mapping, block)
242
+ return mapping[header] if mapping&.key?(header)
243
+ return block.call(header) if block
244
+
245
+ header
246
+ end
247
+ end
248
+
249
+ # Trusted-proxy error messages and values, owned by TrustedProxyConfig
250
+ # and aliased here because callers have always referenced them on Config.
251
+ PROXY_MODE_CONFLICT_MESSAGE = TrustedProxyConfig::PROXY_MODE_CONFLICT_MESSAGE
252
+ TRUST_NO_PROXIES_CONFLICT_MESSAGE = TrustedProxyConfig::TRUST_NO_PROXIES_CONFLICT_MESSAGE
253
+ TRUST_NO_PROXIES_ENTRY_MESSAGE = TrustedProxyConfig::TRUST_NO_PROXIES_ENTRY_MESSAGE
254
+ FORWARDED_HEADER_CIDR_CONFLICT_MESSAGE = TrustedProxyConfig::FORWARDED_HEADER_CIDR_CONFLICT_MESSAGE
255
+ TRUST_NO_PROXIES = TrustedProxyConfig::TRUST_NO_PROXIES
256
+ TRUSTED_PROXY_HEADERS = TrustedProxyConfig::HEADERS
257
+ DEFAULT_TRUSTED_PROXY_HEADER = TrustedProxyConfig::DEFAULT_HEADER
41
258
 
42
259
  # Error raised when an app-configured trusted geo header (ip_privacy
43
260
  # geo_header) is combined with count-based depth mode. Geo headers are
@@ -56,53 +273,16 @@ class Otto
56
273
  (geo_db_path or geo_db_reader).
57
274
  MSG
58
275
 
59
- # Error raised when the explicit "trust no proxy" assertion
60
- # (#trust_no_proxies!, `trusted_proxies: :none`) is combined with an
61
- # actual trust grant (enumerated CIDRs or a depth >= 1). The two say
62
- # opposite things about the same peer, so the combination is refused at
63
- # configuration time rather than silently resolved in one direction.
64
- TRUST_NO_PROXIES_CONFLICT_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
65
- Cannot combine trusted_proxies: :none (trust no proxy) with
66
- trusted_proxies CIDRs or trusted_proxy_depth >= 1. Assert :none OR
67
- grant trust, not both.
68
- MSG
69
-
70
- # Error raised when the trust-nobody sentinel arrives as a proxy ENTRY
71
- # (`trusted_proxies: ['none']`, as a YAML/JSON list naturally yields, or
72
- # `add_trusted_proxy('none')`) instead of as the whole option. Inside a
73
- # list it would otherwise register a legacy string-prefix matcher that
74
- # matches nothing: peers would be untrusted, but trust_no_proxies? would
75
- # stay false and the config would stake a forwarding-family claim, so the
76
- # explicit assertion would be silently replaced by a lookalike.
77
- TRUST_NO_PROXIES_ENTRY_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
78
- trusted_proxies entry :none is the trust-nobody assertion, not a proxy
79
- address. Pass trusted_proxies: :none as the whole option (not inside a
80
- list) or call trust_no_proxies! instead.
81
- MSG
82
-
83
- # Sentinel accepted wherever a trusted_proxies list is accepted, meaning
84
- # "the operator asserts that NO proxy is trusted". See #trust_no_proxies!.
85
- TRUST_NO_PROXIES = :none
86
-
87
- # Whether a trusted_proxies option value is the trust-nobody sentinel.
88
- # Accepts the symbol and the String spelling 'none' (case-insensitive),
89
- # which is what YAML/ENV-driven configuration naturally produces; without
90
- # this, 'none' would fall through to add_trusted_proxy and install a
91
- # legacy string-prefix matcher, silently inverting the assertion.
276
+ # Whether a trusted_proxies option value is the trust-nobody sentinel
277
+ # (:none, or 'none' in any case). See
278
+ # TrustedProxyConfig.trust_no_proxies_option?.
92
279
  #
93
280
  # @param value [Object] raw trusted_proxies option
94
281
  # @return [Boolean]
95
282
  def self.trust_no_proxies_option?(value)
96
- (value.is_a?(Symbol) || value.is_a?(String)) && value.to_s.casecmp?('none')
283
+ TrustedProxyConfig.trust_no_proxies_option?(value)
97
284
  end
98
285
 
99
- # Forwarded-header sources depth mode (#trusted_proxy_depth) can count
100
- # hops from: X-Forwarded-For (default), the RFC 7239 Forwarded header, or
101
- # Both (Forwarded when present, else X-Forwarded-For). Mirrors
102
- # OneTimeSecret's site.network.trusted_proxy.header. Only consulted in
103
- # depth mode; CIDR-walk is unaffected.
104
- TRUSTED_PROXY_HEADERS = %w[X-Forwarded-For Forwarded Both].freeze
105
-
106
286
  # Rack uses one process-global priority for forwarded host, port, scheme,
107
287
  # and IP resolution. Keep it aligned with Otto's configured forwarding
108
288
  # family so the two request views cannot silently disagree.
@@ -113,28 +293,14 @@ class Otto
113
293
  'Forwarded' => [:forwarded].freeze,
114
294
  'Both' => %i[forwarded x_forwarded].freeze,
115
295
  }.freeze
116
- DEFAULT_TRUSTED_PROXY_HEADER = 'X-Forwarded-For'
117
296
  FORWARDING_FAMILY_CONFLICT_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
118
297
  Cannot use forwarding family %s (trusted_proxy_header) because another
119
298
  Otto application in this process already uses %s. Rack's forwarded
120
299
  host, port, scheme, and IP policy is process-global, so every Otto
121
300
  application in one process that resolves proxied requests must use the
122
- same forwarding family.
123
- MSG
124
- # Error raised when a non-default trusted_proxy_header is combined with
125
- # CIDR filter mode. Otto's CIDR-walk resolves the client IP from the
126
- # X-Forwarded-For family only (X-Forwarded-For, then X-Real-IP, then
127
- # X-Client-IP — Otto::Utils::FORWARDED_FOR_HEADERS), never RFC 7239
128
- # Forwarded, while trusted_proxy_header also pins Rack's
129
- # forwarding family; honoring 'Forwarded' or 'Both' there would make Rack
130
- # read a header Otto ignores, recreating the disagreement the pin exists
131
- # to close.
132
- FORWARDED_HEADER_CIDR_CONFLICT_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
133
- Cannot configure trusted_proxy_header 'Forwarded' or 'Both' together
134
- with trusted_proxies (CIDR filter mode): CIDR-walk resolves client IPs
135
- from the X-Forwarded-For family only (X-Forwarded-For, X-Real-IP,
136
- X-Client-IP), never RFC 7239 Forwarded. Use trusted_proxy_depth (count
137
- mode) to read the RFC 7239 Forwarded header.
301
+ same forwarding family. A test suite that builds applications with
302
+ different families must clear this between tests: require
303
+ 'otto/testing' and call Otto::Testing.reset!.
138
304
  MSG
139
305
 
140
306
  # Eager so the first two concurrent Otto.new calls cannot race on
@@ -210,16 +376,16 @@ class Otto
210
376
  attr_reader :rack_forwarding_family
211
377
 
212
378
  # Clear process-global forwarding state between isolated RSpec examples.
379
+ # Otto::Testing.reset! does the same under any test framework.
213
380
  #
214
381
  # @api private
215
382
  def reset_rack_forwarding_family_for_testing!
216
- raise 'reset_rack_forwarding_family_for_testing! is only available in RSpec test environment' unless defined?(RSpec)
217
-
218
- RACK_FORWARDING_MUTEX.synchronize do
219
- @rack_forwarding_owners = nil
220
- @rack_forwarding_family = nil
221
- RACK_REQUEST.forwarded_priority = DEFAULT_RACK_FORWARDED_PRIORITY.dup
383
+ unless defined?(RSpec)
384
+ raise 'reset_rack_forwarding_family_for_testing! is only available in RSpec test environment; ' \
385
+ "outside RSpec, require 'otto/testing' and call Otto::Testing.reset!"
222
386
  end
387
+
388
+ reset_rack_forwarding_family!
223
389
  end
224
390
 
225
391
  private
@@ -228,6 +394,17 @@ class Otto
228
394
  def rack_forwarding_owners
229
395
  @rack_forwarding_owners ||= {}.compare_by_identity
230
396
  end
397
+
398
+ # Drop every commitment and restore Rack's load-time priority. Private
399
+ # because production must never do this: it is what lets two configs
400
+ # with different families coexist. Otto::Testing.reset! reaches it.
401
+ def reset_rack_forwarding_family!
402
+ RACK_FORWARDING_MUTEX.synchronize do
403
+ @rack_forwarding_owners = nil
404
+ @rack_forwarding_family = nil
405
+ RACK_REQUEST.forwarded_priority = DEFAULT_RACK_FORWARDED_PRIORITY.dup
406
+ end
407
+ end
231
408
  end
232
409
 
233
410
  # Endpoint group name shared by the CSP `report-to` directive and the
@@ -238,25 +415,51 @@ class Otto
238
415
  CSP_REPORTING_GROUP = Otto::Security::CSP::Policy::REPORTING_GROUP
239
416
 
240
417
  # Error raised when CSRF protection is enabled in production without an
241
- # explicitly configured secret. A randomly-generated per-process secret
242
- # silently breaks token verification across workers and restarts, so we
243
- # refuse it in production rather than serve intermittently-failing tokens.
418
+ # explicitly configured secret. A generated secret lives in the memory of
419
+ # the process that built the config and of workers forked from it
420
+ # afterwards. Workers that build their own app (cluster mode without
421
+ # preload), processes started separately, other hosts and restarts each
422
+ # generate a different one and reject each other's tokens. We refuse it
423
+ # in production rather than serve intermittently-failing tokens.
244
424
  CSRF_SECRET_REQUIRED_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
245
425
  CSRF protection is enabled in production without a configured secret.
246
426
  Set OTTO_CSRF_SECRET (or config.csrf_secret=) to a stable random value
247
- (e.g. SecureRandom.hex(32)); a per-process random secret is not valid
248
- across workers or restarts.
427
+ (e.g. SecureRandom.hex(32)); a generated secret is not shared with
428
+ workers that load the app themselves (cluster mode without preload),
429
+ processes started separately, other hosts or a restart.
430
+ MSG
431
+
432
+ # Logged once per config when a generated secret signs CSRF tokens or
433
+ # is frozen into a config with CSRF protection enabled.
434
+ CSRF_GENERATED_SECRET_WARNING = <<~MSG.gsub(/\s+/, ' ').strip.freeze
435
+ [Otto::Security::Config] CSRF tokens are signed with a randomly
436
+ generated secret. Workers forked after the secret was generated (a
437
+ preloaded app) share it, but workers that load the app themselves
438
+ (cluster mode without preload), processes started separately, other
439
+ hosts and restarts each generate their own secret and reject each
440
+ other's tokens. Set OTTO_CSRF_SECRET (or config.csrf_secret=) to a
441
+ stable random value.
249
442
  MSG
250
443
 
444
+ # A CSRF secret made only of these characters is blank: Unicode
445
+ # whitespace ([[:space:]]), the Unicode Default_Ignorable_Code_Point
446
+ # property (characters that render as nothing, such as zero-width
447
+ # spaces and joiners, U+00AD soft hyphen, U+2060 word joiner, U+FEFF,
448
+ # bidirectional marks, variation selectors and Hangul fillers) and NUL.
449
+ BLANK_CSRF_SECRET = /\A[[:space:]\p{Default_Ignorable_Code_Point}\u0000]*\z/
450
+
451
+ # A configured CSRF secret shorter than this many bytes logs a warning.
452
+ CSRF_SECRET_MIN_BYTES = 32
453
+
251
454
  attr_accessor :input_validation, :max_param_depth, :csrf_token_key,
252
455
  :rate_limiting_config, :csrf_session_key, :max_request_size,
253
456
  :max_param_keys
254
457
 
255
458
  attr_reader :csrf_protection, :csrf_header_key,
256
- :trusted_proxies, :require_secure_cookies,
459
+ :require_secure_cookies,
257
460
  :security_headers,
258
461
  :csp_nonce_enabled, :debug_csp, :mcp_auth, :csp_nonce_key,
259
- :ip_privacy_config, :trusted_proxy_depth, :trusted_proxy_header,
462
+ :ip_privacy_config,
260
463
  :csp_report_uri, :csp_report_to_url, :csp_violation_callback,
261
464
  :csp_directive_overrides, :csp_request_extras_enabled
262
465
 
@@ -272,13 +475,10 @@ class Otto
272
475
  @max_request_size = 10 * 1024 * 1024 # 10MB
273
476
  @max_param_depth = 32
274
477
  @max_param_keys = 64
275
- @trusted_proxies = []
276
- @trusted_proxy_matchers = []
277
- @trust_no_proxies = false
278
- @trusted_proxy_depth = nil
279
- @trusted_proxy_header = DEFAULT_TRUSTED_PROXY_HEADER
478
+ @trusted_proxy_config = TrustedProxyConfig.new
280
479
  @require_secure_cookies = false
281
- @security_headers = default_security_headers
480
+ @security_headers = SecurityHeaders.new(method(:validate_referrer_policy!))
481
+ @security_headers.merge!(default_security_headers)
282
482
  @input_validation = true
283
483
  @csp_nonce_enabled = false
284
484
  @debug_csp = false
@@ -290,12 +490,12 @@ class Otto
290
490
  @csp_directive_overrides = {}
291
491
  @csp_request_extras_enabled = false
292
492
  @csp_script_src_override_warned = false
493
+ @csrf_secret_warning = OnceFlag.new
293
494
  @rate_limiting_config = { custom_rules: {} }
294
495
  @ip_privacy_config = Otto::Privacy::Config.new
295
496
 
296
- configured_secret = ENV.fetch('OTTO_CSRF_SECRET', nil)
297
- @csrf_secret_generated = configured_secret.nil? || configured_secret.empty?
298
- @csrf_secret = @csrf_secret_generated ? SecureRandom.hex(32) : configured_secret
497
+ # Unset or blank falls back to a generated secret (see #csrf_secret=).
498
+ self.csrf_secret = ENV.fetch('OTTO_CSRF_SECRET', nil)
299
499
  end
300
500
 
301
501
  # Enable CSRF (Cross-Site Request Forgery) protection
@@ -331,14 +531,52 @@ class Otto
331
531
  @csrf_protection
332
532
  end
333
533
 
534
+ # The active trusted-proxy mode: :filter, :depth, :none, or nil when
535
+ # proxy trust is unconfigured. The TrustedProxyConfig behind it is not
536
+ # exposed, because its setters would skip the Rack forwarding-family pin
537
+ # and the geo_header check this class adds.
538
+ #
539
+ # @return [Symbol, nil]
540
+ def trusted_proxy_mode
541
+ @trusted_proxy_config.mode
542
+ end
543
+
544
+ # Proxy entries registered with #add_trusted_proxy, in order.
545
+ #
546
+ # @return [Array<String, Regexp>]
547
+ def trusted_proxies
548
+ @trusted_proxy_config.proxies
549
+ end
550
+
551
+ # Count-based trusted-proxy depth, or nil. See #trusted_proxy_depth=.
552
+ #
553
+ # @return [Integer, nil]
554
+ def trusted_proxy_depth
555
+ @trusted_proxy_config.depth
556
+ end
557
+
558
+ # Forwarded header family depth mode counts hops from. See
559
+ # #trusted_proxy_header=.
560
+ #
561
+ # @return [String] one of TRUSTED_PROXY_HEADERS
562
+ def trusted_proxy_header
563
+ @trusted_proxy_config.header
564
+ end
565
+
334
566
  # Add a trusted proxy server for accurate client IP detection
335
567
  #
336
568
  # Only requests from trusted proxies will have their X-Forwarded-For
337
569
  # and similar headers honored for IP detection. This prevents IP spoofing
338
570
  # from untrusted sources.
339
571
  #
340
- # @param proxy [String, Array] IP address, CIDR range, or array of addresses
341
- # @raise [ArgumentError] if proxy is not a String or Array
572
+ # Mutually exclusive with count-based depth, with the trust-nobody
573
+ # assertion, and with a trusted_proxy_header other than X-Forwarded-For;
574
+ # each conflict raises here rather than only at freeze (which the test
575
+ # harness skips). A list is validated whole before any entry is
576
+ # registered. See TrustedProxyConfig#add.
577
+ #
578
+ # @param proxy [String, Regexp, Array] IP address, CIDR range, Regexp, or array of these
579
+ # @raise [ArgumentError] if proxy is not a String, Regexp, or Array, or on a conflict
342
580
  # @raise [FrozenError] if configuration is frozen
343
581
  # @return [void]
344
582
  #
@@ -352,67 +590,21 @@ class Otto
352
590
  # config.add_trusted_proxy(['10.0.0.1', '172.16.0.0/12'])
353
591
  def add_trusted_proxy(proxy)
354
592
  ensure_not_frozen!
355
- # CIDR-walk and count-based depth are mutually exclusive. Catch the
356
- # conflict eagerly here (and in #trusted_proxy_depth=) so it surfaces at
357
- # configuration time, not only at freeze (which the test harness skips).
358
- raise ArgumentError, PROXY_MODE_CONFLICT_MESSAGE if trusted_proxy_depth_mode?
359
- raise ArgumentError, TRUST_NO_PROXIES_CONFLICT_MESSAGE if @trust_no_proxies
360
- # Same pattern for header-then-proxies; proxies-then-header is caught
361
- # in #trusted_proxy_header=.
362
- raise ArgumentError, FORWARDED_HEADER_CIDR_CONFLICT_MESSAGE unless default_trusted_proxy_header?
363
-
364
- # The trust-nobody sentinel is an option value, never an entry; validate
365
- # the whole list before registering anything so a bad list leaves the
366
- # config untouched.
367
- Array(proxy).each do |entry|
368
- raise ArgumentError, TRUST_NO_PROXIES_ENTRY_MESSAGE if self.class.trust_no_proxies_option?(entry)
369
- end
370
593
 
371
- case proxy
372
- when String, Regexp
373
- @trusted_proxies << proxy
374
- @trusted_proxy_matchers << register_proxy_matcher(proxy)
375
- when Array
376
- proxy.each { |entry| @trusted_proxy_matchers << register_proxy_matcher(entry) }
377
- @trusted_proxies.concat(proxy)
378
- else
379
- raise ArgumentError, 'Proxy must be a String, Regexp, or Array'
380
- end
594
+ @trusted_proxy_config.add(proxy)
381
595
  end
382
596
 
383
597
  # Check if an IP address is from a trusted proxy
384
598
  #
385
- # String entries that parse as an IP or CIDR range are matched with
386
- # proper IPAddr containment (IPv4 and IPv6). Entries that are not valid
387
- # IPs (e.g. a bare prefix like '172.16.') fall back to the legacy
388
- # exact/prefix string match for backward compatibility. Regexp entries
389
- # are matched against the raw IP string.
390
- #
391
- # Proxy entries are parsed once at registration (see #add_trusted_proxy)
392
- # into @trusted_proxy_matchers, so this never re-parses per request.
599
+ # IP and CIDR entries match by IPAddr containment (IPv4 and IPv6, with
600
+ # IPv4-mapped addresses folded), Regexp entries match the raw string, and
601
+ # non-IP strings fall back to legacy prefix matching. Entries are parsed
602
+ # once at registration. See TrustedProxyConfig#trusted?.
393
603
  #
394
604
  # @param ip [String] IP address to check
395
605
  # @return [Boolean] true if the IP is from a trusted proxy
396
606
  def trusted_proxy?(ip)
397
- return false if @trusted_proxy_matchers.empty? || ip.nil? || ip.empty?
398
-
399
- # Fold IPv4-mapped IPv6 (::ffff:a.b.c.d) to plain IPv4 so a dual-stack
400
- # peer presented in mapped form still matches an IPv4 proxy entry.
401
- client = parse_ipaddr(ip)&.native
402
-
403
- @trusted_proxy_matchers.any? do |entry, range|
404
- if range
405
- # Pre-parsed IP/CIDR entry -> proper containment
406
- client && ip_in_range?(range, client)
407
- elsif entry.is_a?(Regexp)
408
- entry.match?(ip)
409
- elsif entry.is_a?(String)
410
- # Legacy non-IP entry (e.g. '172.16.') -> exact/prefix match
411
- ip == entry || ip.start_with?(entry)
412
- else
413
- false
414
- end
415
- end
607
+ @trusted_proxy_config.trusted?(ip)
416
608
  end
417
609
 
418
610
  # Whether any trusted-proxy IP/CIDR/Regexp matchers are configured.
@@ -425,7 +617,7 @@ class Otto
425
617
  #
426
618
  # @return [Boolean] true when at least one trusted-proxy matcher exists
427
619
  def trusted_proxies_configured?
428
- @trusted_proxy_matchers.any?
620
+ @trusted_proxy_config.filter?
429
621
  end
430
622
 
431
623
  # Whether ANY proxy-trust mode is configured — CIDR matchers (filter
@@ -439,7 +631,7 @@ class Otto
439
631
  # @return [Boolean] true when filter or depth mode is configured, or when
440
632
  # the operator explicitly asserted that no proxy is trusted
441
633
  def proxy_trust_configured?
442
- trusted_proxies_configured? || trusted_proxy_depth_mode? || trust_no_proxies?
634
+ @trusted_proxy_config.configured?
443
635
  end
444
636
 
445
637
  # Assert that NO proxy is trusted for this application.
@@ -467,16 +659,15 @@ class Otto
467
659
  # config.trust_no_proxies!
468
660
  def trust_no_proxies!
469
661
  ensure_not_frozen!
470
- raise ArgumentError, TRUST_NO_PROXIES_CONFLICT_MESSAGE if trusted_proxies_configured? || trusted_proxy_depth_mode?
471
662
 
472
- @trust_no_proxies = true
663
+ @trusted_proxy_config.trust_none!
473
664
  end
474
665
 
475
666
  # Whether the operator explicitly asserted that no proxy is trusted.
476
667
  #
477
668
  # @return [Boolean]
478
669
  def trust_no_proxies?
479
- @trust_no_proxies
670
+ @trusted_proxy_config.trust_none?
480
671
  end
481
672
 
482
673
  # Whether this config's request handling DEPENDS on Rack's process-global
@@ -486,7 +677,7 @@ class Otto
486
677
  #
487
678
  # @return [Boolean]
488
679
  def forwarding_family_dependent?
489
- trusted_proxies_configured? || trusted_proxy_depth_mode?
680
+ @trusted_proxy_config.forwarding_family_dependent?
490
681
  end
491
682
 
492
683
  # Whether count-based ("trust the last N hops") proxy resolution is active.
@@ -499,7 +690,7 @@ class Otto
499
690
  #
500
691
  # @return [Boolean] true when trusted_proxy_depth is an Integer >= 1
501
692
  def trusted_proxy_depth_mode?
502
- @trusted_proxy_depth.is_a?(Integer) && @trusted_proxy_depth >= 1
693
+ @trusted_proxy_config.depth?
503
694
  end
504
695
 
505
696
  # Set the count-based trusted-proxy depth ("trust the last N hops").
@@ -507,7 +698,8 @@ class Otto
507
698
  # Validates eagerly so a misconfiguration fails at assignment rather than
508
699
  # only at freeze (which the test harness skips): the value must be a
509
700
  # non-negative Integer or nil, and the mode is mutually exclusive with
510
- # CIDR-walk (trusted_proxies). nil/0 disable depth mode.
701
+ # CIDR-walk (trusted_proxies), with the trust-nobody assertion, and with
702
+ # a trusted ip_privacy geo_header. nil/0 disable depth mode.
511
703
  #
512
704
  # @param depth [Integer, nil] number of trusted hops (nil/0 disables depth mode)
513
705
  # @raise [FrozenError] if configuration is frozen
@@ -516,14 +708,12 @@ class Otto
516
708
  def trusted_proxy_depth=(depth)
517
709
  ensure_not_frozen!
518
710
 
519
- validate_trusted_proxy_depth!(depth)
520
- raise ArgumentError, PROXY_MODE_CONFLICT_MESSAGE if depth.to_i >= 1 && @trusted_proxies.any?
521
- raise ArgumentError, TRUST_NO_PROXIES_CONFLICT_MESSAGE if depth.to_i >= 1 && @trust_no_proxies
711
+ @trusted_proxy_config.check_depth!(depth)
522
712
  # Depth-then-geo assignment order is caught by configure_ip_privacy;
523
713
  # this catches geo-then-depth so both orders fail eagerly.
524
714
  raise ArgumentError, GEO_HEADER_DEPTH_CONFLICT_MESSAGE if depth.to_i >= 1 && @ip_privacy_config&.geo_header
525
715
 
526
- @trusted_proxy_depth = depth
716
+ @trusted_proxy_config.depth = depth
527
717
  end
528
718
 
529
719
  # Select which forwarded header family Otto and Rack read from:
@@ -556,12 +746,9 @@ class Otto
556
746
  def trusted_proxy_header=(header)
557
747
  ensure_not_frozen!
558
748
 
559
- canonical_header = canonicalize_trusted_proxy_header(header)
560
- cidr_conflict = canonical_header != DEFAULT_TRUSTED_PROXY_HEADER && @trusted_proxies.any?
561
- raise ArgumentError, FORWARDED_HEADER_CIDR_CONFLICT_MESSAGE if cidr_conflict
562
-
749
+ canonical_header = @trusted_proxy_config.check_header!(header)
563
750
  self.class.apply_rack_forwarding_family!(self, canonical_header)
564
- @trusted_proxy_header = canonical_header
751
+ @trusted_proxy_config.header = canonical_header
565
752
  end
566
753
 
567
754
  # Align Rack's forwarding family with this config's current value. Used by
@@ -576,7 +763,7 @@ class Otto
576
763
  def apply_default_rack_forwarding_family!
577
764
  ensure_not_frozen!
578
765
 
579
- self.class.apply_rack_forwarding_family!(self, @trusted_proxy_header, claim: forwarding_family_dependent?)
766
+ self.class.apply_rack_forwarding_family!(self, trusted_proxy_header, claim: forwarding_family_dependent?)
580
767
  end
581
768
 
582
769
  # Commit this config's current family process-wide once it depends on
@@ -593,14 +780,14 @@ class Otto
593
780
  ensure_not_frozen!
594
781
  return unless forwarding_family_dependent?
595
782
 
596
- self.class.apply_rack_forwarding_family!(self, @trusted_proxy_header)
783
+ self.class.apply_rack_forwarding_family!(self, trusted_proxy_header)
597
784
  end
598
785
 
599
786
  # Whether trusted_proxy_header is the X-Forwarded-For default.
600
787
  #
601
788
  # @return [Boolean]
602
789
  def default_trusted_proxy_header?
603
- @trusted_proxy_header == DEFAULT_TRUSTED_PROXY_HEADER
790
+ @trusted_proxy_config.default_header?
604
791
  end
605
792
 
606
793
  # Validate that a request size is within acceptable limits
@@ -647,11 +834,39 @@ class Otto
647
834
  #
648
835
  # Write-only by design: the signing key has no public reader, so it is not
649
836
  # exposed to inspection/logging/serialization via the config object.
837
+ #
838
+ # nil or a blank String (see BLANK_CSRF_SECRET) is not used as the key.
839
+ # A non-blank OTTO_CSRF_SECRET is used instead, read when the setter
840
+ # runs. If that is unset or blank too, a fresh random per-process secret
841
+ # is generated and marked as generated, so the production guard
842
+ # (CSRF_SECRET_REQUIRED_MESSAGE) still applies. The constructor assigns
843
+ # OTTO_CSRF_SECRET through this setter.
844
+ #
845
+ # A configured secret shorter than CSRF_SECRET_MIN_BYTES bytes is used
846
+ # as given and logs a warning, without raising.
847
+ #
848
+ # Each generated secret gets a fresh once-only flag, so the
849
+ # generated-secret warning is logged for it even if it was already
850
+ # logged for an earlier one (generate_csrf_token on an unfrozen config
851
+ # logs it before this setter can run again).
852
+ #
853
+ # @param secret [String, nil] stable signing secret, or nil/blank for
854
+ # OTTO_CSRF_SECRET or a generated per-process secret
855
+ # @raise [FrozenError] if configuration is frozen
856
+ # @raise [ArgumentError] if secret is neither a String nor nil
650
857
  def csrf_secret=(secret)
651
858
  ensure_not_frozen!
652
859
 
653
- @csrf_secret = secret
654
- @csrf_secret_generated = false
860
+ unless secret.nil? || secret.is_a?(String)
861
+ raise ArgumentError,
862
+ "CSRF secret must be a String or nil, got: #{secret.class}"
863
+ end
864
+
865
+ secret = ENV.fetch('OTTO_CSRF_SECRET', nil) if blank_csrf_secret?(secret)
866
+ @csrf_secret_generated = blank_csrf_secret?(secret)
867
+ @csrf_secret = @csrf_secret_generated ? SecureRandom.hex(32) : secret
868
+ @csrf_secret_warning = OnceFlag.new if @csrf_secret_generated
869
+ warn_short_csrf_secret unless @csrf_secret_generated
655
870
  end
656
871
 
657
872
  # Generate a CSRF token bound to the given session id and signed (HMAC-SHA256)
@@ -670,7 +885,13 @@ class Otto
670
885
  # Verify a CSRF token against its session binding using a constant-time
671
886
  # comparison. Returns false (never raises) for blank/malformed input.
672
887
  def verify_csrf_token(token, session_id = nil)
673
- return false if token.nil? || token.empty?
888
+ # A token is two hex strings joined by ':', so a value that is not an
889
+ # ASCII String cannot match. Rejecting it here also keeps it from
890
+ # #split and the HMAC input below, which raise for the Array or Hash
891
+ # Rack parses from _csrf_token[]= or _csrf_token[k]=, for invalid
892
+ # bytes, and for an ASCII-8BIT token with non-ASCII bytes next to a
893
+ # non-ASCII binding.
894
+ return false unless token.is_a?(String) && token.ascii_only?
674
895
 
675
896
  binding_id = session_id.to_s
676
897
  return false if binding_id.empty?
@@ -682,6 +903,43 @@ class Otto
682
903
  secure_compare(signature, expected_signature)
683
904
  end
684
905
 
906
+ # Cookie that carries the CSRF binding on plain HTTP requests.
907
+ CSRF_BINDING_COOKIE = '_otto_session'
908
+
909
+ # Cookie that carries the CSRF binding on HTTPS requests. Browsers that
910
+ # enforce cookie name prefixes accept a __Host- cookie only when it is
911
+ # set with Secure and Path=/, without a Domain, from a secure origin, so
912
+ # in those browsers a sibling subdomain or a network attacker cannot
913
+ # plant one.
914
+ CSRF_HOST_BINDING_COOKIE = '__Host-otto_session'
915
+
916
+ # Name of the cookie that carries the CSRF binding for +request+:
917
+ # CSRF_HOST_BINDING_COOKIE when Rack reports the request as HTTPS,
918
+ # CSRF_BINDING_COOKIE otherwise. CSRFMiddleware sets the cookie under
919
+ # this name.
920
+ #
921
+ # @param request [Rack::Request]
922
+ # @return [String]
923
+ def csrf_binding_cookie_name(request)
924
+ request.scheme == 'https' ? CSRF_HOST_BINDING_COOKIE : CSRF_BINDING_COOKIE
925
+ end
926
+
927
+ # The cookie value used as the CSRF binding when the session provides
928
+ # none. On HTTPS only CSRF_HOST_BINDING_COOKIE is read: the plantable
929
+ # _otto_session, session_id and _session_id cookies are ignored there.
930
+ # On HTTP, where a __Host- cookie cannot be set, the legacy names are
931
+ # read in their old order.
932
+ #
933
+ # @param request [Rack::Request]
934
+ # @return [String, nil]
935
+ def csrf_binding_cookie(request)
936
+ cookies = request.cookies
937
+ return cookies[CSRF_HOST_BINDING_COOKIE] if request.scheme == 'https'
938
+
939
+ cookies[CSRF_BINDING_COOKIE] || cookies['session_id'] || cookies['_session_id']
940
+ end
941
+ private :csrf_binding_cookie
942
+
685
943
  # Enable HTTP Strict Transport Security (HSTS) header
686
944
  #
687
945
  # HSTS forces browsers to use HTTPS for all future requests to this domain.
@@ -892,10 +1150,24 @@ class Otto
892
1150
  # For the turnkey setup that also injects the receiving middleware, prefer
893
1151
  # {Otto::Security::Core#enable_csp_reporting!} on the Otto instance.
894
1152
  #
895
- # @param uri [String, nil] path browsers POST reports to (matched against
896
- # `PATH_INFO`, e.g. `/_/csp-report`), or nil to disable reporting. A
897
- # value without a leading slash is coerced to an absolute path so it
898
- # matches the slash-prefixed `PATH_INFO` the middleware compares against.
1153
+ # The value is a site-absolute path: the path from the site root that the
1154
+ # browser POSTs to, including any prefix the app is mounted under. It is
1155
+ # emitted verbatim in the `report-uri` directive, which browsers resolve
1156
+ # against the site root, and the middleware compares it against the
1157
+ # request's full path (`SCRIPT_NAME` + `PATH_INFO`), so one value is right
1158
+ # for both. With Otto mounted by `map '/api' { run otto }`, configure
1159
+ # `/api/csp-report`, not `/csp-report`. Unmounted, `SCRIPT_NAME` is empty
1160
+ # and the full path is `PATH_INFO`.
1161
+ #
1162
+ # The comparison normalizes both sides with {Otto::Utils.normalize_path}
1163
+ # (percent-decoding, one trailing slash stripped), so `/_/csp-report/`
1164
+ # and a percent-encoded spelling of the path are also intercepted.
1165
+ #
1166
+ # @param uri [String, nil] site-absolute path browsers POST reports to
1167
+ # (e.g. `/_/csp-report`, or `/api/csp-report` when mounted at `/api`),
1168
+ # or nil to disable reporting. A value without a leading slash is
1169
+ # coerced to an absolute path, since browsers would otherwise resolve
1170
+ # it relative to the document URL.
899
1171
  # @return [void]
900
1172
  # @raise [FrozenError] if configuration is frozen
901
1173
  def csp_report_uri=(uri)
@@ -920,7 +1192,8 @@ class Otto
920
1192
  # The value MUST be an ABSOLUTE URL (Reporting-Endpoints does not accept a
921
1193
  # bare path). Point it at the same receiver as {#csp_report_uri=}: its path
922
1194
  # component should equal the report URI so {Otto::Security::CSP::ReportMiddleware}
923
- # (which matches on PATH_INFO) intercepts modern reports too.
1195
+ # (which matches the full request path, mount prefix included) intercepts
1196
+ # modern reports too.
924
1197
  #
925
1198
  # When nil/empty (the default), NO `report-to` directive or
926
1199
  # `Reporting-Endpoints` header is emitted and policy output is
@@ -1023,6 +1296,24 @@ class Otto
1023
1296
  @security_headers['x-frame-options'] = option
1024
1297
  end
1025
1298
 
1299
+ # The Referrer-Policy value applied to Otto-generated responses.
1300
+ #
1301
+ # @return [String] one of {REFERRER_POLICIES}
1302
+ def referrer_policy
1303
+ @security_headers['referrer-policy']
1304
+ end
1305
+
1306
+ # Configure the Referrer-Policy value applied to Otto responses.
1307
+ #
1308
+ # @param policy [String] one W3C Referrer Policy HTTP policy token
1309
+ # @return [String] the configured policy
1310
+ # @raise [ArgumentError] when +policy+ is not a recognized token
1311
+ # @raise [FrozenError] if configuration is frozen
1312
+ def referrer_policy=(policy)
1313
+ ensure_not_frozen!
1314
+ @security_headers['referrer-policy'] = policy
1315
+ end
1316
+
1026
1317
  # Set custom security headers
1027
1318
  #
1028
1319
  # @param headers [Hash] Hash of header name => value pairs
@@ -1040,20 +1331,68 @@ class Otto
1040
1331
  @security_headers.merge!(headers)
1041
1332
  end
1042
1333
 
1334
+ # Nested settings #deep_freeze! always freezes. A frozen config with any
1335
+ # of these unfrozen was frozen with Object#freeze.
1336
+ DEEP_FREEZE_MARKERS = %i[
1337
+ @security_headers @rate_limiting_config @csp_directive_overrides
1338
+ @trusted_proxy_config @ip_privacy_config
1339
+ ].freeze
1340
+ private_constant :DEEP_FREEZE_MARKERS
1341
+
1342
+ # Raised by #deep_freeze! on a config frozen with Object#freeze.
1343
+ SHALLOW_FREEZE_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
1344
+ Otto::Security::Config was frozen with Object#freeze, not deep_freeze!,
1345
+ so its nested settings are still mutable and it cannot be deep-frozen
1346
+ now. Call deep_freeze! (or Otto#freeze_configuration!) instead of
1347
+ freeze.
1348
+ MSG
1349
+
1043
1350
  # Override deep_freeze! to ensure rate_limiting_config has custom_rules initialized
1044
1351
  #
1045
1352
  # This pre-initializes any lazy values before freezing to prevent FrozenError
1046
1353
  # when accessing configuration after it's frozen.
1047
1354
  #
1355
+ # Idempotent, like Otto::Core::Freezable#deep_freeze!: a config that
1356
+ # deep_freeze! already froze returns self without rerunning the
1357
+ # freeze-time validators. Middleware that takes this config as an
1358
+ # argument (the MCP token and rate limit middleware) leads
1359
+ # Otto#freeze_configuration! to reach it a second time while freezing
1360
+ # the middleware stack.
1361
+ #
1362
+ # A config frozen with Object#freeze is frozen while its nested settings
1363
+ # (security headers, rate limiting config, ...) are not. It cannot be
1364
+ # finished either, since its instance variables can no longer be
1365
+ # replaced, so that case raises instead of passing as deep-frozen.
1366
+ # deep_freeze! freezes every instance variable before the config itself,
1367
+ # so a frozen config counts as deep-frozen only when all of
1368
+ # DEEP_FREEZE_MARKERS are frozen too; one Hash the application froze by
1369
+ # hand is not enough.
1370
+ #
1048
1371
  # @return [self] The frozen configuration
1372
+ # @raise [FrozenError] if the config was frozen with Object#freeze
1049
1373
  def deep_freeze!
1374
+ if frozen?
1375
+ return self if DEEP_FREEZE_MARKERS.all? { |ivar| instance_variable_get(ivar).frozen? }
1376
+
1377
+ raise FrozenError, SHALLOW_FREEZE_MESSAGE
1378
+ end
1379
+
1050
1380
  # Ensure custom_rules is initialized (should already be done in constructor)
1051
1381
  @rate_limiting_config[:custom_rules] ||= {}
1382
+ validate_referrer_policy!(@security_headers['referrer-policy'])
1052
1383
  validate_trusted_proxy_config!
1053
1384
  validate_csrf_secret_config!
1054
1385
  super
1055
1386
  end
1056
1387
 
1388
+ # Returns the value CSRF tokens are bound to, always as a String.
1389
+ #
1390
+ # When no binding exists yet, a random value is stored under
1391
+ # csrf_session_key. A lazy session store (rack-session) mints its session
1392
+ # id on that first write, so the id is read back and used as the binding
1393
+ # when there is one. The next request then finds the same value through
1394
+ # session.id, and a store that renews the id (for example at login)
1395
+ # retires every token bound to the old one.
1057
1396
  def get_or_create_session_id(request)
1058
1397
  # Try existing sources first
1059
1398
  session_id = extract_existing_session_id(request)
@@ -1062,99 +1401,73 @@ class Otto
1062
1401
  if session_id.nil? || session_id.empty?
1063
1402
  session_id = SecureRandom.hex(16)
1064
1403
  store_session_id(request, session_id)
1404
+ minted_id = minted_session_id(request)
1405
+ session_id = minted_id if minted_id
1065
1406
  end
1066
1407
 
1408
+ # CSRFMiddleware sets the binding cookie from this on responses to
1409
+ # safe requests (see EnvKeys::CSRF_BINDING).
1410
+ request.env['otto.csrf_binding'] = session_id.to_s if record_binding?(request, session_id)
1067
1411
  session_id
1068
1412
  end
1069
1413
 
1070
- private
1071
-
1072
- # Guard for mutators: refuse changes once the configuration is frozen.
1073
- # Centralizes the repeated frozen-check so every setter shares one message.
1074
- def ensure_not_frozen!
1075
- raise FrozenError, 'Cannot modify frozen configuration' if frozen?
1076
- end
1077
-
1078
- # Validate a candidate trusted_proxy_depth value (type and range).
1414
+ # Returns the CSRF binding the request already has, from the same
1415
+ # sources and in the same order as #get_or_create_session_id, or nil.
1416
+ # Unlike #get_or_create_session_id it never mints a binding, writes to
1417
+ # the session or sets otto.csrf_binding.
1079
1418
  #
1080
- # Shared by the eager #trusted_proxy_depth= setter and the freeze-time
1081
- # backstop so an invalid value raises a clear ArgumentError instead of a
1082
- # downstream NoMethodError from #to_i coercion. nil disables depth mode.
1419
+ # Use it where a new binding could not reach the client: a token can
1420
+ # verify only against a binding that exists, and CSRFMiddleware sets the
1421
+ # binding cookie only on safe requests. CSRF validation and token
1422
+ # injection on unsafe requests read the binding this way.
1083
1423
  #
1084
- # @param depth [Object] candidate value
1085
- # @raise [ArgumentError] if depth is non-nil and not a non-negative Integer
1086
- # @return [void]
1087
- def validate_trusted_proxy_depth!(depth)
1088
- return if depth.nil?
1089
-
1090
- unless depth.is_a?(Integer)
1091
- raise ArgumentError,
1092
- "trusted_proxy_depth must be an Integer or nil, got #{depth.class}"
1093
- end
1094
-
1095
- raise ArgumentError, "trusted_proxy_depth must be >= 0, got #{depth}" if depth.negative?
1424
+ # @param request [Rack::Request]
1425
+ # @return [String, nil] the binding, or nil when there is none
1426
+ def existing_session_id(request)
1427
+ session_id = extract_existing_session_id(request)
1428
+ session_id.nil? || session_id.empty? ? nil : session_id
1096
1429
  end
1097
1430
 
1098
- # Canonicalize a candidate trusted_proxy_header value: match it
1099
- # case-insensitively (ignoring surrounding whitespace) against the
1100
- # recognized set and return the canonical spelling. Liberal in the spelling
1101
- # it accepts (e.g. 'forwarded' => 'Forwarded') but fail-loud on a genuinely
1102
- # unrecognized value, so a typo is caught at config time rather than
1103
- # silently resolving the client IP from the wrong header.
1104
- #
1105
- # @param header [Object] candidate value
1106
- # @raise [ArgumentError] if header is not one of TRUSTED_PROXY_HEADERS
1107
- # @return [String] the canonical header value
1108
- def canonicalize_trusted_proxy_header(header)
1109
- candidate = header.to_s.strip
1110
- canonical = TRUSTED_PROXY_HEADERS.find { |allowed| allowed.casecmp?(candidate) }
1111
- return canonical if canonical
1431
+ private
1112
1432
 
1113
- raise ArgumentError,
1114
- "trusted_proxy_header must be one of #{TRUSTED_PROXY_HEADERS.join(', ')}, got #{header.inspect}"
1433
+ # #inspect (and so a native FrozenError message) shows the CSRF signing
1434
+ # key as [REDACTED]. See Otto::Core::RedactedInspect.
1435
+ def redacted_inspect_value(ivar, value)
1436
+ ivar == :@csrf_secret ? redacted_placeholder(value) : super
1115
1437
  end
1116
1438
 
1117
- # Strictly validate a stored trusted_proxy_header value against the allowed
1118
- # set. The eager #trusted_proxy_header= setter already canonicalizes, so by
1119
- # freeze time the value is canonical; this freeze-time backstop catches a
1120
- # value smuggled in through a direct-ivar path that bypassed the setter,
1121
- # failing loud rather than silently mis-resolving the client IP at request
1122
- # time.
1123
- #
1124
- # @param header [Object] candidate value
1125
- # @raise [ArgumentError] if header is not one of TRUSTED_PROXY_HEADERS
1126
- # @return [void]
1127
- def validate_trusted_proxy_header!(header)
1128
- return if TRUSTED_PROXY_HEADERS.include?(header)
1439
+ # Freezable#deep_freeze! calls this before freezing the config. The
1440
+ # signing key is replaced with a frozen SecretString copy first, so the
1441
+ # caller's String is not frozen by the config (a later write to it would
1442
+ # raise a FrozenError that prints it) and the config keeps signing with
1443
+ # the value it had. Done here rather than in csrf_secret= so it covers
1444
+ # every way the key is set.
1445
+ def freeze_instance_variables!
1446
+ @csrf_secret = Otto::Core::RedactedInspect.secret(@csrf_secret)
1447
+ super
1448
+ end
1129
1449
 
1130
- raise ArgumentError,
1131
- "trusted_proxy_header must be one of #{TRUSTED_PROXY_HEADERS.join(', ')}, got #{header.inspect}"
1450
+ # Guard for mutators: refuse changes once the configuration is frozen.
1451
+ # Centralizes the repeated frozen-check so every setter shares one message.
1452
+ def ensure_not_frozen!
1453
+ raise FrozenError, 'Cannot modify frozen configuration' if frozen?
1132
1454
  end
1133
1455
 
1134
1456
  # Validate trusted-proxy configuration coherence at freeze time.
1135
1457
  #
1136
- # The eager setters (#trusted_proxy_depth=, #add_trusted_proxy) already
1137
- # reject invalid types and the mutually-exclusive CIDR-walk vs depth
1138
- # combination at assignment. This re-checks at finalization as a backstop
1139
- # for a direct/ivar configuration path that bypassed the setters.
1458
+ # TrustedProxyConfig#validate! re-checks its own rules (header value,
1459
+ # depth type, mode exclusivity) as a backstop for state that bypassed the
1460
+ # eager setters; the geo_header rule spans two sub-configs, so it is
1461
+ # checked here.
1140
1462
  #
1141
- # @raise [ArgumentError] if depth is non-integer/negative, or if both
1142
- # trusted_proxies and a depth >= 1 are configured
1463
+ # @raise [ArgumentError] if any trusted-proxy rule is violated
1143
1464
  # @return [void]
1144
1465
  def validate_trusted_proxy_config!
1145
- validate_trusted_proxy_header!(@trusted_proxy_header)
1146
- validate_trusted_proxy_depth!(@trusted_proxy_depth)
1147
- raise ArgumentError, FORWARDED_HEADER_CIDR_CONFLICT_MESSAGE if !default_trusted_proxy_header? && @trusted_proxies.any?
1148
-
1149
- raise ArgumentError, TRUST_NO_PROXIES_CONFLICT_MESSAGE if @trust_no_proxies && (@trusted_proxies.any? || @trusted_proxy_depth.to_i >= 1)
1466
+ @trusted_proxy_config.validate!
1150
1467
 
1151
- if @trusted_proxy_depth
1152
- raise ArgumentError, PROXY_MODE_CONFLICT_MESSAGE if @trusted_proxy_depth >= 1 && @trusted_proxies.any?
1153
-
1154
- # Backstop for the direct path (ip_privacy_config.geo_header=) that
1155
- # bypasses both eager checks; the setters cover the common orders.
1156
- raise ArgumentError, GEO_HEADER_DEPTH_CONFLICT_MESSAGE if @trusted_proxy_depth >= 1 && @ip_privacy_config&.geo_header
1157
- end
1468
+ # Backstop for the direct path (ip_privacy_config.geo_header=) that
1469
+ # bypasses both eager checks; the setters cover the common orders.
1470
+ raise ArgumentError, GEO_HEADER_DEPTH_CONFLICT_MESSAGE if trusted_proxy_depth_mode? && @ip_privacy_config&.geo_header
1158
1471
 
1159
1472
  # Last, so a config that fails the checks above never registers as an
1160
1473
  # owner: late-configured proxy trust (after Otto.new) commits here at
@@ -1162,84 +1475,71 @@ class Otto
1162
1475
  commit_rack_forwarding_family!
1163
1476
  end
1164
1477
 
1165
- # Parse a value into an IPAddr, returning nil for invalid / non-IP input.
1166
- #
1167
- # @param value [String] candidate IP or CIDR string
1168
- # @return [IPAddr, nil]
1169
- def parse_ipaddr(value)
1170
- IPAddr.new(value)
1171
- rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError
1172
- nil
1173
- end
1174
-
1175
- # Build a cached matcher tuple for a proxy entry at registration time.
1478
+ # Returns the existing CSRF binding as a String, or nil.
1176
1479
  #
1177
- # String entries are parsed to an IPAddr exactly once here; the result is
1178
- # reused for both the legacy-entry warning and per-request matching, so
1179
- # trusted_proxy? never re-parses. Non-IP strings and Regexp/other entries
1180
- # store a nil range and fall back to prefix/regexp matching.
1480
+ # session.id is read first, so the binding follows the store's session
1481
+ # id and changes when the store renews it. The value stored under
1482
+ # csrf_session_key is used only by sessions without an id.
1181
1483
  #
1182
- # The parsed range is folded through IPAddr#native at registration, to
1183
- # match the fold trusted_proxy? applies to the client address. Without
1184
- # it a mapped-IPv6 proxy entry (::ffff:10.0.0.0/104) could never match,
1185
- # because ip_in_range?'s family check would reject the folded IPv4
1186
- # client — a proxy silently untrusted, which is what gates
1187
- # otto.via_trusted_proxy, secure?, and geo-header trust. #native returns
1188
- # self for entries that are not IPv4-mapped/compatible.
1189
- #
1190
- # @param entry [String, Regexp, Object] trusted proxy entry being added
1191
- # @return [Array(Object, IPAddr)] [raw_entry, parsed_range_or_nil]
1192
- def register_proxy_matcher(entry)
1193
- return [entry, nil] unless entry.is_a?(String)
1194
-
1195
- range = parse_ipaddr(entry)&.native
1196
- warn_legacy_proxy_entry(entry) unless range
1197
- [entry, range]
1198
- end
1199
-
1200
- # Warn that a string proxy entry is not a valid IP/CIDR and will use
1201
- # legacy string-prefix matching.
1202
- #
1203
- # @param entry [String] trusted proxy entry
1204
- # @return [void]
1205
- def warn_legacy_proxy_entry(entry)
1206
- Otto.logger.warn(
1207
- "[Otto::Security::Config] trusted proxy #{entry.inspect} is not a " \
1208
- 'valid IP or CIDR; using legacy string-prefix matching. Prefer a ' \
1209
- "CIDR range (e.g. '172.16.0.0/12')."
1210
- )
1211
- end
1212
-
1213
- # CIDR/host containment that is safe across address families.
1214
- #
1215
- # @param range [IPAddr] trusted proxy range or host
1216
- # @param client [IPAddr] client address
1217
- # @return [Boolean]
1218
- def ip_in_range?(range, client)
1219
- return false unless range.family == client.family
1220
-
1221
- range.include?(client)
1222
- rescue IPAddr::InvalidAddressError
1223
- false
1224
- end
1225
-
1484
+ # Values are coerced with to_s because session ids may be objects
1485
+ # (rack-session returns a Rack::Session::SessionId).
1226
1486
  def extract_existing_session_id(request)
1227
1487
  # Try session first
1228
1488
  begin
1229
1489
  session = request.session
1230
1490
  if session
1231
- return session.id if session.respond_to?(:id) && session.id
1232
- return session[csrf_session_key] if session[csrf_session_key]
1233
- return session['session_id'] if session['session_id']
1491
+ return session.id.to_s if session.respond_to?(:id) && session.id
1492
+ return session[csrf_session_key].to_s if session[csrf_session_key]
1493
+ return session['session_id'].to_s if session['session_id']
1234
1494
  end
1235
1495
  rescue StandardError
1236
1496
  # Fall through to cookies
1237
1497
  end
1238
1498
 
1239
- # Try cookies
1240
- request.cookies['_otto_session'] ||
1241
- request.cookies['session_id'] ||
1242
- request.cookies['_session_id']
1499
+ # Then the binding cookie (see #csrf_binding_cookie)
1500
+ csrf_binding_cookie(request)
1501
+ end
1502
+
1503
+ # Whether secret is nil or blank per BLANK_CSRF_SECRET. The string is
1504
+ # checked in UTF-8: converted from its own encoding, or else its bytes
1505
+ # read as UTF-8, which is how a non-ASCII OTTO_CSRF_SECRET arrives under
1506
+ # LANG=C (tagged ASCII-8BIT). A string that fits neither is blank only
1507
+ # if it holds nothing but ASCII whitespace and NUL, the characters
1508
+ # String#strip removes; such bytes still work as an HMAC key.
1509
+ def blank_csrf_secret?(secret)
1510
+ return true if secret.nil?
1511
+
1512
+ utf8 = transcoded_utf8(secret) || relabelled_utf8(secret)
1513
+ utf8 ? BLANK_CSRF_SECRET.match?(utf8) : secret.b.strip.empty?
1514
+ end
1515
+
1516
+ # secret converted to valid UTF-8 from its own encoding, or nil.
1517
+ def transcoded_utf8(secret)
1518
+ utf8 = secret.encode(Encoding::UTF_8)
1519
+ utf8 if utf8.valid_encoding?
1520
+ rescue EncodingError
1521
+ nil
1522
+ end
1523
+
1524
+ # secret's bytes read as UTF-8 if they are valid UTF-8, or nil.
1525
+ def relabelled_utf8(secret)
1526
+ utf8 = secret.dup.force_encoding(Encoding::UTF_8)
1527
+ utf8 if utf8.valid_encoding?
1528
+ end
1529
+
1530
+ # Warn, without raising, when the configured secret is shorter than
1531
+ # CSRF_SECRET_MIN_BYTES. Logs the length, never the secret. Raising
1532
+ # would stop deploys that already run with a short secret from booting.
1533
+ def warn_short_csrf_secret
1534
+ bytes = @csrf_secret.bytesize
1535
+ return if bytes >= CSRF_SECRET_MIN_BYTES
1536
+
1537
+ Otto.logger.warn(
1538
+ '[Otto::Security::Config] The configured CSRF secret is shorter than ' \
1539
+ "#{CSRF_SECRET_MIN_BYTES} bytes (#{bytes} bytes). A short secret is " \
1540
+ 'easier to guess from a token the app issued. Set a stable random value ' \
1541
+ "of at least #{CSRF_SECRET_MIN_BYTES} bytes, e.g. SecureRandom.hex(32)."
1542
+ )
1243
1543
  end
1244
1544
 
1245
1545
  def store_session_id(request, session_id)
@@ -1249,6 +1549,49 @@ class Otto
1249
1549
  # Cookie fallback handled in inject_csrf_token
1250
1550
  end
1251
1551
 
1552
+ # Whether #get_or_create_session_id records +binding+ in
1553
+ # otto.csrf_binding: only when the client does not already send it, that
1554
+ # is when it was minted here or read from csrf_session_key. The session
1555
+ # store's own id travels in the store's cookie when the store sets one,
1556
+ # and a binding read from a cookie comes back with the next request; a
1557
+ # copy of either would sit in a second cookie whose lifetime and
1558
+ # attributes the application does not configure.
1559
+ def record_binding?(request, binding)
1560
+ return false unless request.respond_to?(:env)
1561
+ return false if binding.to_s == csrf_binding_cookie(request).to_s
1562
+
1563
+ !session_store_id?(request, binding)
1564
+ end
1565
+
1566
+ # Whether +binding+ is the session store's own id: session.id, or
1567
+ # session['session_id'], for which rack-session's Pool and Cookie
1568
+ # stores return the session's public id.
1569
+ def session_store_id?(request, binding)
1570
+ session = request.session
1571
+ return false unless session
1572
+
1573
+ binding = binding.to_s
1574
+ store_id = session.id if session.respond_to?(:id)
1575
+ return true if store_id && store_id.to_s == binding
1576
+
1577
+ legacy_id = session['session_id']
1578
+ !legacy_id.nil? && legacy_id.to_s == binding
1579
+ rescue StandardError
1580
+ false
1581
+ end
1582
+
1583
+ # The session id a lazy store minted while #store_session_id wrote to the
1584
+ # session, as a String, or nil when the session has no id.
1585
+ def minted_session_id(request)
1586
+ session = request.session
1587
+ return nil unless session.respond_to?(:id)
1588
+
1589
+ minted_id = session.id.to_s
1590
+ minted_id.empty? ? nil : minted_id
1591
+ rescue StandardError
1592
+ nil
1593
+ end
1594
+
1252
1595
  # Default security headers applied to all responses
1253
1596
  #
1254
1597
  # These headers provide basic defense against common web vulnerabilities:
@@ -1265,25 +1608,35 @@ class Otto
1265
1608
  {
1266
1609
  'x-content-type-options' => 'nosniff',
1267
1610
  'x-xss-protection' => '1; mode=block',
1268
- 'referrer-policy' => 'strict-origin-when-cross-origin',
1611
+ 'referrer-policy' => DEFAULT_REFERRER_POLICY,
1269
1612
  }
1270
1613
  end
1271
1614
 
1272
- # Perform constant-time string comparison to prevent timing attacks
1273
- #
1274
- # This method compares two strings in constant time regardless of where
1275
- # they differ, preventing attackers from using timing differences to
1276
- # deduce information about secret values.
1277
- #
1278
- # @param a [String, nil] First string to compare
1279
- # @param b [String, nil] Second string to compare
1280
- # @return [Boolean] true if strings are equal
1615
+ def validate_referrer_policy!(policy)
1616
+ return policy if policy.is_a?(String) && REFERRER_POLICIES.include?(policy)
1617
+
1618
+ raise ArgumentError,
1619
+ "Invalid referrer_policy #{policy.inspect}; expected one of: #{REFERRER_POLICIES.join(', ')}"
1620
+ end
1621
+
1622
+ # Compare two Strings by their bytes with Rack::Utils.secure_compare.
1623
+ # It returns false when the byte sizes differ. Otherwise it calls
1624
+ # OpenSSL.fixed_length_secure_compare if OpenSSL was loaded before
1625
+ # rack/utils, or runs a Ruby loop that XORs every byte if not. Rack's
1626
+ # comment on the OpenSSL version, in lib/rack/utils.rb, reads "Constant
1627
+ # time string comparison." and "the values compared should be of fixed
1628
+ # length, such as strings that have already been processed by HMAC."
1629
+ # The expected value here is a hex HMAC-SHA256. A presented value with
1630
+ # multibyte characters is unequal rather than an error, as sizes are
1631
+ # counted in bytes.
1632
+ #
1633
+ # @param a [Object] presented value; false unless it is a String
1634
+ # @param b [Object] expected value; false unless it is a String
1635
+ # @return [Boolean] true only when both are Strings with the same bytes
1281
1636
  def secure_compare(a, b)
1282
- return false if a.nil? || b.nil? || a.length != b.length
1637
+ return false unless a.is_a?(String) && b.is_a?(String)
1283
1638
 
1284
- result = 0
1285
- a.bytes.zip(b.bytes) { |x, y| result |= x ^ y }
1286
- result == 0
1639
+ Rack::Utils.secure_compare(a, b)
1287
1640
  end
1288
1641
 
1289
1642
  # HMAC-SHA256 signature binding a token's random component to a session id
@@ -1293,21 +1646,18 @@ class Otto
1293
1646
  OpenSSL::HMAC.hexdigest('SHA256', @csrf_secret, "#{session_id}:#{token}")
1294
1647
  end
1295
1648
 
1296
- # Warn once per config instance when CSRF tokens are being signed with a
1297
- # randomly-generated per-process secret. Such tokens do not survive process
1298
- # restarts and are not shared across workers; set OTTO_CSRF_SECRET (or
1299
- # config.csrf_secret=) for stable multi-process behavior.
1649
+ # Log CSRF_GENERATED_SECRET_WARNING once per config instance when the
1650
+ # secret was generated rather than configured.
1651
+ #
1652
+ # Called from #validate_csrf_secret_config! while #deep_freeze! runs with
1653
+ # CSRF enabled, and from #generate_csrf_token, frozen or not. The
1654
+ # once-only state is a OnceFlag, which stays writable after the freeze
1655
+ # and lets one thread log when several generate the first tokens at once.
1300
1656
  def warn_generated_csrf_secret
1301
1657
  return unless @csrf_secret_generated
1302
- return if @csrf_secret_warning_emitted
1303
-
1304
- @csrf_secret_warning_emitted = true
1305
- Otto.logger.warn(<<~MSG.gsub(/\s+/, ' ').strip)
1306
- [Otto::Security::Config] CSRF tokens are signed with a randomly
1307
- generated per-process secret; they will not survive restarts or be
1308
- valid across workers. Set OTTO_CSRF_SECRET (or config.csrf_secret=)
1309
- for stable CSRF tokens in multi-process deployments.
1310
- MSG
1658
+ return unless @csrf_secret_warning.set!
1659
+
1660
+ Otto.logger.warn(CSRF_GENERATED_SECRET_WARNING)
1311
1661
  end
1312
1662
 
1313
1663
  # Warn once per config instance when a `script-src` override is stored for
@@ -1337,13 +1687,20 @@ class Otto
1337
1687
  # enables CSRF with a generated (non-configured) secret. Mirrors
1338
1688
  # #validate_trusted_proxy_config! so the failure surfaces at boot, before
1339
1689
  # serving traffic, for apps that deep-freeze their config.
1690
+ #
1691
+ # Outside production, a generated secret is allowed, so the generated-secret
1692
+ # warning is logged here, at boot for an app that freezes its config then.
1340
1693
  def validate_csrf_secret_config!
1341
1694
  raise ArgumentError, CSRF_SECRET_REQUIRED_MESSAGE if csrf_secret_unsafe_for_production?
1695
+
1696
+ warn_generated_csrf_secret if @csrf_protection
1342
1697
  end
1343
1698
 
1344
1699
  # Generation-time guard for apps that never freeze their config: never
1345
- # mint a CSRF token signed with a generated per-process secret in
1346
- # production (fail loud instead of serving tokens that won't verify).
1700
+ # mint a CSRF token signed with a generated secret in production, where
1701
+ # workers that load the app themselves, separately started processes,
1702
+ # other hosts and restarts would reject each other's tokens (fail loud
1703
+ # instead of serving tokens that won't verify).
1347
1704
  def reject_generated_secret_in_production!
1348
1705
  raise ArgumentError, CSRF_SECRET_REQUIRED_MESSAGE if csrf_secret_unsafe_for_production?
1349
1706
  end
@@ -1374,13 +1731,14 @@ class Otto
1374
1731
  stripped.empty? ? nil : stripped
1375
1732
  end
1376
1733
 
1377
- # Normalize a configured report PATH: the local endpoint the receiver
1378
- # matches on `PATH_INFO`. Same strip/blank-to-nil handling as
1379
- # {#normalize_report_uri}, but a bare relative value is coerced to an
1380
- # absolute path — a value like `"csp-report"` would otherwise (a) never
1381
- # equal the slash-prefixed `PATH_INFO` the middleware compares against, and
1382
- # (b) be resolved by browsers relative to the document URL. An absolute URL
1383
- # (contains a scheme) is left untouched.
1734
+ # Normalize a configured report PATH: the site-absolute endpoint the
1735
+ # receiver matches against `SCRIPT_NAME` + `PATH_INFO`. Same
1736
+ # strip/blank-to-nil handling as {#normalize_report_uri}, but a bare
1737
+ # relative value is coerced to an absolute path — a value like
1738
+ # `"csp-report"` would otherwise (a) never equal the slash-prefixed request
1739
+ # path the middleware compares against, and (b) be resolved by browsers
1740
+ # relative to the document URL. An absolute URL (contains a scheme) is left
1741
+ # untouched.
1384
1742
  #
1385
1743
  # @param uri [String, nil]
1386
1744
  # @return [String, nil]