otto 2.12.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 (59) 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/AGENTS.md +4 -2
  10. data/CHANGELOG.rst +692 -0
  11. data/Gemfile +1 -0
  12. data/Gemfile.lock +6 -1
  13. data/docs/README.md +4 -0
  14. data/docs/audits/2026-09-28-v2.12.0-code-audit.md +732 -0
  15. data/docs/audits/README.md +63 -0
  16. data/docs/guides/authentication.md +329 -0
  17. data/docs/guides/forwarded-authority.md +80 -4
  18. data/docs/guides/mcp.md +40 -4
  19. data/docs/guides/privacy.md +23 -2
  20. data/docs/guides/routing.md +8 -4
  21. data/docs/guides/testing-guide.md +31 -3
  22. data/docs/migrating/v2.3.0.md +13 -7
  23. data/docs/reference/authentication.md +70 -22
  24. data/examples/lambda_handlers/README.md +4 -4
  25. data/examples/lambda_handlers/handlers.rb +4 -5
  26. data/examples/lambda_handlers/routes +2 -2
  27. data/examples/mcp_demo/README.md +65 -27
  28. data/examples/mcp_demo/app.rb +8 -5
  29. data/examples/mcp_demo/config.ru +50 -3
  30. data/examples/mcp_demo/routes +10 -6
  31. data/examples/security_features/README.md +2 -2
  32. data/lib/otto/caddy_tls/server.rb +8 -4
  33. data/lib/otto/core/option_hash.rb +124 -0
  34. data/lib/otto/core/redacted_inspect.rb +149 -0
  35. data/lib/otto/core/router.rb +41 -14
  36. data/lib/otto/core.rb +2 -0
  37. data/lib/otto/env_keys.rb +30 -7
  38. data/lib/otto/logging_helpers.rb +1 -1
  39. data/lib/otto/mcp/auth/token.rb +12 -1
  40. data/lib/otto/mcp/protocol.rb +3 -3
  41. data/lib/otto/mcp/registry.rb +28 -2
  42. data/lib/otto/mcp/route_parser.rb +20 -8
  43. data/lib/otto/mcp/server.rb +17 -9
  44. data/lib/otto/privacy/config.rb +12 -1
  45. data/lib/otto/privacy/ip_privacy.rb +109 -3
  46. data/lib/otto/privacy/redacted_fingerprint.rb +8 -10
  47. data/lib/otto/request.rb +34 -0
  48. data/lib/otto/route_definition.rb +3 -2
  49. data/lib/otto/security/authentication/route_auth_wrapper.rb +10 -3
  50. data/lib/otto/security/config.rb +358 -46
  51. data/lib/otto/security/csrf.rb +17 -2
  52. data/lib/otto/security/csrf_validation.rb +13 -7
  53. data/lib/otto/security/middleware/csrf_middleware.rb +203 -37
  54. data/lib/otto/security/middleware/ip_privacy_middleware.rb +127 -38
  55. data/lib/otto/static.rb +63 -0
  56. data/lib/otto/utils.rb +105 -28
  57. data/lib/otto/version.rb +1 -1
  58. data/lib/otto.rb +37 -9
  59. metadata +6 -2
@@ -6,7 +6,9 @@ require 'securerandom'
6
6
  require 'digest'
7
7
  require 'openssl'
8
8
  require 'rack/request'
9
+ require 'rack/utils'
9
10
  require_relative '../core/freezable'
11
+ require_relative '../core/redacted_inspect'
10
12
  require_relative 'csp/policy'
11
13
  require_relative 'trusted_proxy_config'
12
14
 
@@ -29,6 +31,7 @@ class Otto
29
31
  # config.max_param_depth = 16
30
32
  class Config
31
33
  include Otto::Core::Freezable
34
+ include Otto::Core::RedactedInspect
32
35
 
33
36
  # Otto accepts exactly one W3C Referrer Policy token for its
34
37
  # referrer_policy setting. The supported tokens are enumerated below:
@@ -45,6 +48,34 @@ class Otto
45
48
  ].freeze
46
49
  DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'
47
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
61
+
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
+
48
79
  # Hash-compatible storage that keeps the generic security-header API and
49
80
  # the dedicated referrer_policy setting on one validated code path.
50
81
  # Existing callers may continue to mutate Config#security_headers like a
@@ -384,16 +415,42 @@ class Otto
384
415
  CSP_REPORTING_GROUP = Otto::Security::CSP::Policy::REPORTING_GROUP
385
416
 
386
417
  # Error raised when CSRF protection is enabled in production without an
387
- # explicitly configured secret. A randomly-generated per-process secret
388
- # silently breaks token verification across workers and restarts, so we
389
- # 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.
390
424
  CSRF_SECRET_REQUIRED_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
391
425
  CSRF protection is enabled in production without a configured secret.
392
426
  Set OTTO_CSRF_SECRET (or config.csrf_secret=) to a stable random value
393
- (e.g. SecureRandom.hex(32)); a per-process random secret is not valid
394
- 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.
395
430
  MSG
396
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.
442
+ MSG
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
+
397
454
  attr_accessor :input_validation, :max_param_depth, :csrf_token_key,
398
455
  :rate_limiting_config, :csrf_session_key, :max_request_size,
399
456
  :max_param_keys
@@ -433,12 +490,12 @@ class Otto
433
490
  @csp_directive_overrides = {}
434
491
  @csp_request_extras_enabled = false
435
492
  @csp_script_src_override_warned = false
493
+ @csrf_secret_warning = OnceFlag.new
436
494
  @rate_limiting_config = { custom_rules: {} }
437
495
  @ip_privacy_config = Otto::Privacy::Config.new
438
496
 
439
- configured_secret = ENV.fetch('OTTO_CSRF_SECRET', nil)
440
- @csrf_secret_generated = configured_secret.nil? || configured_secret.empty?
441
- @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)
442
499
  end
443
500
 
444
501
  # Enable CSRF (Cross-Site Request Forgery) protection
@@ -777,11 +834,39 @@ class Otto
777
834
  #
778
835
  # Write-only by design: the signing key has no public reader, so it is not
779
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
780
857
  def csrf_secret=(secret)
781
858
  ensure_not_frozen!
782
859
 
783
- @csrf_secret = secret
784
- @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
785
870
  end
786
871
 
787
872
  # Generate a CSRF token bound to the given session id and signed (HMAC-SHA256)
@@ -800,7 +885,13 @@ class Otto
800
885
  # Verify a CSRF token against its session binding using a constant-time
801
886
  # comparison. Returns false (never raises) for blank/malformed input.
802
887
  def verify_csrf_token(token, session_id = nil)
803
- 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?
804
895
 
805
896
  binding_id = session_id.to_s
806
897
  return false if binding_id.empty?
@@ -812,6 +903,43 @@ class Otto
812
903
  secure_compare(signature, expected_signature)
813
904
  end
814
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
+
815
943
  # Enable HTTP Strict Transport Security (HSTS) header
816
944
  #
817
945
  # HSTS forces browsers to use HTTPS for all future requests to this domain.
@@ -1203,13 +1331,52 @@ class Otto
1203
1331
  @security_headers.merge!(headers)
1204
1332
  end
1205
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
+
1206
1350
  # Override deep_freeze! to ensure rate_limiting_config has custom_rules initialized
1207
1351
  #
1208
1352
  # This pre-initializes any lazy values before freezing to prevent FrozenError
1209
1353
  # when accessing configuration after it's frozen.
1210
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
+ #
1211
1371
  # @return [self] The frozen configuration
1372
+ # @raise [FrozenError] if the config was frozen with Object#freeze
1212
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
+
1213
1380
  # Ensure custom_rules is initialized (should already be done in constructor)
1214
1381
  @rate_limiting_config[:custom_rules] ||= {}
1215
1382
  validate_referrer_policy!(@security_headers['referrer-policy'])
@@ -1218,6 +1385,14 @@ class Otto
1218
1385
  super
1219
1386
  end
1220
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.
1221
1396
  def get_or_create_session_id(request)
1222
1397
  # Try existing sources first
1223
1398
  session_id = extract_existing_session_id(request)
@@ -1226,13 +1401,52 @@ class Otto
1226
1401
  if session_id.nil? || session_id.empty?
1227
1402
  session_id = SecureRandom.hex(16)
1228
1403
  store_session_id(request, session_id)
1404
+ minted_id = minted_session_id(request)
1405
+ session_id = minted_id if minted_id
1229
1406
  end
1230
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)
1231
1411
  session_id
1232
1412
  end
1233
1413
 
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.
1418
+ #
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.
1423
+ #
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
1429
+ end
1430
+
1234
1431
  private
1235
1432
 
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
1437
+ end
1438
+
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
1449
+
1236
1450
  # Guard for mutators: refuse changes once the configuration is frozen.
1237
1451
  # Centralizes the repeated frozen-check so every setter shares one message.
1238
1452
  def ensure_not_frozen!
@@ -1261,23 +1475,71 @@ class Otto
1261
1475
  commit_rack_forwarding_family!
1262
1476
  end
1263
1477
 
1478
+ # Returns the existing CSRF binding as a String, or nil.
1479
+ #
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.
1483
+ #
1484
+ # Values are coerced with to_s because session ids may be objects
1485
+ # (rack-session returns a Rack::Session::SessionId).
1264
1486
  def extract_existing_session_id(request)
1265
1487
  # Try session first
1266
1488
  begin
1267
1489
  session = request.session
1268
1490
  if session
1269
- return session.id if session.respond_to?(:id) && session.id
1270
- return session[csrf_session_key] if session[csrf_session_key]
1271
- 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']
1272
1494
  end
1273
1495
  rescue StandardError
1274
1496
  # Fall through to cookies
1275
1497
  end
1276
1498
 
1277
- # Try cookies
1278
- request.cookies['_otto_session'] ||
1279
- request.cookies['session_id'] ||
1280
- 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
+ )
1281
1543
  end
1282
1544
 
1283
1545
  def store_session_id(request, session_id)
@@ -1287,6 +1549,49 @@ class Otto
1287
1549
  # Cookie fallback handled in inject_csrf_token
1288
1550
  end
1289
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
+
1290
1595
  # Default security headers applied to all responses
1291
1596
  #
1292
1597
  # These headers provide basic defense against common web vulnerabilities:
@@ -1314,21 +1619,24 @@ class Otto
1314
1619
  "Invalid referrer_policy #{policy.inspect}; expected one of: #{REFERRER_POLICIES.join(', ')}"
1315
1620
  end
1316
1621
 
1317
- # Perform constant-time string comparison to prevent timing attacks
1318
- #
1319
- # This method compares two strings in constant time regardless of where
1320
- # they differ, preventing attackers from using timing differences to
1321
- # deduce information about secret values.
1322
- #
1323
- # @param a [String, nil] First string to compare
1324
- # @param b [String, nil] Second string to compare
1325
- # @return [Boolean] true if strings are equal
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
1326
1636
  def secure_compare(a, b)
1327
- return false if a.nil? || b.nil? || a.length != b.length
1637
+ return false unless a.is_a?(String) && b.is_a?(String)
1328
1638
 
1329
- result = 0
1330
- a.bytes.zip(b.bytes) { |x, y| result |= x ^ y }
1331
- result == 0
1639
+ Rack::Utils.secure_compare(a, b)
1332
1640
  end
1333
1641
 
1334
1642
  # HMAC-SHA256 signature binding a token's random component to a session id
@@ -1338,21 +1646,18 @@ class Otto
1338
1646
  OpenSSL::HMAC.hexdigest('SHA256', @csrf_secret, "#{session_id}:#{token}")
1339
1647
  end
1340
1648
 
1341
- # Warn once per config instance when CSRF tokens are being signed with a
1342
- # randomly-generated per-process secret. Such tokens do not survive process
1343
- # restarts and are not shared across workers; set OTTO_CSRF_SECRET (or
1344
- # 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.
1345
1656
  def warn_generated_csrf_secret
1346
1657
  return unless @csrf_secret_generated
1347
- return if @csrf_secret_warning_emitted
1348
-
1349
- @csrf_secret_warning_emitted = true
1350
- Otto.logger.warn(<<~MSG.gsub(/\s+/, ' ').strip)
1351
- [Otto::Security::Config] CSRF tokens are signed with a randomly
1352
- generated per-process secret; they will not survive restarts or be
1353
- valid across workers. Set OTTO_CSRF_SECRET (or config.csrf_secret=)
1354
- for stable CSRF tokens in multi-process deployments.
1355
- MSG
1658
+ return unless @csrf_secret_warning.set!
1659
+
1660
+ Otto.logger.warn(CSRF_GENERATED_SECRET_WARNING)
1356
1661
  end
1357
1662
 
1358
1663
  # Warn once per config instance when a `script-src` override is stored for
@@ -1382,13 +1687,20 @@ class Otto
1382
1687
  # enables CSRF with a generated (non-configured) secret. Mirrors
1383
1688
  # #validate_trusted_proxy_config! so the failure surfaces at boot, before
1384
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.
1385
1693
  def validate_csrf_secret_config!
1386
1694
  raise ArgumentError, CSRF_SECRET_REQUIRED_MESSAGE if csrf_secret_unsafe_for_production?
1695
+
1696
+ warn_generated_csrf_secret if @csrf_protection
1387
1697
  end
1388
1698
 
1389
1699
  # Generation-time guard for apps that never freeze their config: never
1390
- # mint a CSRF token signed with a generated per-process secret in
1391
- # 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).
1392
1704
  def reject_generated_secret_in_production!
1393
1705
  raise ArgumentError, CSRF_SECRET_REQUIRED_MESSAGE if csrf_secret_unsafe_for_production?
1394
1706
  end
@@ -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