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
@@ -67,11 +67,17 @@ class Otto
67
67
  # Client-IP resolution is idempotent, but proxy TRUST is not: the
68
68
  # prior pass may have run under a different (or no) configuration,
69
69
  # so this instance still enforces its own trust posture below.
70
- if env.key?('otto.client_ip')
70
+ #
71
+ # otto.ip_match without otto.client_ip also marks a prior pass: the
72
+ # no-resolvable-IP path installs it alone. That path deletes the
73
+ # forwarded address headers, so re-resolving would see only the peer
74
+ # and could turn "client unknown" into "the proxy is the client".
75
+ if env.key?('otto.client_ip') || prior_no_client_ip_pass?(env)
71
76
  ensure_ip_match_present(env)
72
77
  enforce_proxy_trust_after_prior_pass(env)
73
78
  return @app.call(env)
74
79
  end
80
+ discard_out_of_contract_ip_match(env)
75
81
 
76
82
  # Record the connecting peer's trust decision BEFORE any masking, so
77
83
  # secure? can authorize X-Forwarded-Proto canonically even after
@@ -203,16 +209,51 @@ class Otto
203
209
  end
204
210
  end
205
211
 
212
+ # Whether a prior pass of this middleware resolved no client IP.
213
+ #
214
+ # That pass leaves otto.ip_match without otto.client_ip. otto.ip_match
215
+ # alone is not enough to tell: a spec or app may have stubbed it, and
216
+ # taking a stub for a verdict would skip resolution and masking. Every
217
+ # pass writes otto.peer_relayed before resolving, so the pair is the
218
+ # marker.
219
+ #
220
+ # @param env [Hash] Rack environment
221
+ # @return [Boolean]
222
+ def prior_no_client_ip_pass?(env)
223
+ env.key?('otto.ip_match') && env.key?('otto.peer_relayed')
224
+ end
225
+
226
+ # Drop an otto.ip_match this middleware did not install, and say so.
227
+ #
228
+ # Reached only when #call found no prior pass. Resolution below
229
+ # installs the real capability; the warning makes the overwrite
230
+ # diagnosable, as #ensure_ip_match_present does for a hand-set
231
+ # otto.client_ip.
232
+ #
233
+ # @param env [Hash] Rack environment
234
+ def discard_out_of_contract_ip_match(env)
235
+ return unless env.key?('otto.ip_match')
236
+
237
+ Otto.logger.warn(
238
+ '[IPPrivacyMiddleware] otto.ip_match was set outside this ' \
239
+ 'middleware and is being replaced: resolving and masking the ' \
240
+ 'client IP as usual. Test harnesses can build the env with ' \
241
+ 'Otto::Testing.env_for.'
242
+ )
243
+ env.delete('otto.ip_match')
244
+ end
245
+
206
246
  # Guarantee env['otto.ip_match'] exists on the idempotent-return path.
207
247
  #
208
248
  # Every path in this middleware that sets otto.client_ip installs the
209
249
  # capability first, so a second IPPrivacyMiddleware pass that reaches
210
250
  # this guard finds both keys and leaves the precise closure in place.
211
251
  # (The no-resolvable-IP path installs the capability but never sets
212
- # otto.client_ip, so a second pass re-runs apply_privacy and reinstalls
213
- # an equivalent fail-closed closure — idempotent, since there is nothing
214
- # to double-mask.) The gap is out-of-contract writes: otto.client_ip is
215
- # documented as "Set by: IPPrivacyMiddleware" (see Otto::EnvKeys), but
252
+ # otto.client_ip; #call recognises that pass by otto.ip_match plus
253
+ # otto.peer_relayed, so its fail-closed closure is kept too.) The gap
254
+ # is out-of-contract
255
+ # writes: otto.client_ip is documented as "Set by: IPPrivacyMiddleware"
256
+ # (see Otto::EnvKeys), but
216
257
  # an app or test harness that sets it directly trips the idempotency
217
258
  # guard and leaves the advertised capability nil — downstream policy
218
259
  # code then raises NoMethodError on nil.
@@ -232,7 +273,8 @@ class Otto
232
273
  '[IPPrivacyMiddleware] otto.client_ip was set outside this ' \
233
274
  'middleware, so otto.ip_match could not be built from the ' \
234
275
  'unmasked address; installing a fail-closed check (every CIDR ' \
235
- 'test returns false). Let IPPrivacyMiddleware resolve the client IP.'
276
+ 'test returns false). Let IPPrivacyMiddleware resolve the client IP; ' \
277
+ 'test harnesses can build the env with Otto::Testing.env_for.'
236
278
  )
237
279
  env['otto.ip_match'] = ->(_cidrs) { false }
238
280
  end
@@ -259,8 +301,10 @@ class Otto
259
301
  # its own outcome. To trace resolution here, log a derived value (the
260
302
  # masked IP, the family, the trusted-proxy verdict) — never the address.
261
303
 
262
- # No resolvable client IP (REMOTE_ADDR absent or blank, and no trusted
263
- # forwarded value). There is nothing to mask, and masking would derive
304
+ # No resolvable client IP: REMOTE_ADDR absent or blank with no trusted
305
+ # forwarded value, or a trusted proxy chain whose walk reached an
306
+ # entry that is not an address (Otto::Utils.resolve_client_ip returns
307
+ # nil there). There is nothing to mask, and masking would derive
264
308
  # a nil masked IP (IPPrivacy.mask_ip returns nil for nil/empty input).
265
309
  # Writing that nil back to REMOTE_ADDR / forwarded headers would leave
266
310
  # present-but-nil CGI keys, which violate the Rack SPEC and trip
@@ -278,7 +322,9 @@ class Otto
278
322
  # Likewise, forwarded headers may still carry raw client addresses
279
323
  # (e.g. an X-Forwarded-For / Forwarded value with no usable REMOTE_ADDR
280
324
  # to anchor resolution). There is no masked IP to rewrite them to, so
281
- # DELETE them — leaving them would leak the raw address downstream.
325
+ # the address headers are DELETED and Forwarded loses its for= pairs
326
+ # (its proto=/host=/by= stay) — leaving them would leak the raw
327
+ # address downstream.
282
328
  if client_ip.to_s.empty?
283
329
  Otto.logger.debug '[IPPrivacyMiddleware] No resolvable client IP; skipping IP masking' if Otto.debug
284
330
  scrub_sensitive_headers(
@@ -298,7 +344,14 @@ class Otto
298
344
  env['otto.original_ip'] = client_ip
299
345
  # Canonical client IP downstream reads (exempt: not masked)
300
346
  env['otto.client_ip'] = client_ip
301
- # Don't mask forwarded headers for private IPs
347
+ # Rewrite the forwarded address headers to the exempt client IP
348
+ # rather than leaving them as received. They can carry public
349
+ # addresses: entries left of client_ip in the chain (an unlisted
350
+ # private hop appended after the real client), or a header an
351
+ # untrusted private peer sent. Rack::Request#ip trusts private
352
+ # and loopback peers by default and would read those raw values;
353
+ # rewritten, it returns client_ip.
354
+ rewrite_forwarded_addresses(env, client_ip)
302
355
  #
303
356
  # This early return also means NONE of the privacy fingerprint
304
357
  # values are produced for exempt IPs — no otto.privacy.fingerprint,
@@ -363,7 +416,7 @@ class Otto
363
416
 
364
417
  # Mask X-Forwarded-For headers to prevent leakage
365
418
  # Replace with masked IP so proxy resolution logic finds the masked IP
366
- mask_forwarded_headers(env, fingerprint.masked_ip)
419
+ rewrite_forwarded_addresses(env, fingerprint.masked_ip)
367
420
 
368
421
  Otto.logger.debug "[IPPrivacyMiddleware] Masked IP: #{fingerprint.masked_ip}" if Otto.debug
369
422
 
@@ -490,53 +543,87 @@ class Otto
490
543
  UNTRUSTED_FORWARDING_METADATA_HEADERS.each { |key| env.delete(key) }
491
544
  end
492
545
 
493
- # Delete forwarded IP headers outright.
546
+ # Remove the client addresses from the forwarded headers.
494
547
  #
495
548
  # Used on the no-resolvable-client-IP path, where there is no masked IP
496
- # to rewrite these to. Leaving them would leak a raw client address (in
497
- # X-Forwarded-For / X-Real-IP / X-Client-IP / RFC 7239 Forwarded)
498
- # downstream. Deleting is Rack-SPEC-safe: an absent CGI key is valid.
549
+ # to rewrite these to. Leaving them would leak a raw client address
550
+ # downstream. X-Forwarded-For, X-Real-IP, X-Client-IP and the vendor
551
+ # client-address headers carry nothing but addresses, so they are
552
+ # deleted (an absent CGI key is Rack-SPEC-safe). RFC 7239 Forwarded
553
+ # also carries the scheme (proto=)
554
+ # and host (host=) a trusted proxy asserts, which Rack reads for
555
+ # #scheme, #ssl? and #host; deleting it would turn an https request
556
+ # into http and hand the host to the proxy. Its for= pairs are removed
557
+ # instead (see IPPrivacy.strip_forwarded_for for why not `unknown`),
558
+ # and the header is deleted only if nothing else remains.
499
559
  #
500
560
  # @param env [Hash] Rack environment
501
561
  def scrub_forwarded_headers(env)
502
- env.delete('HTTP_X_FORWARDED_FOR')
503
- env.delete('HTTP_X_REAL_IP')
504
- env.delete('HTTP_X_CLIENT_IP')
505
- env.delete('HTTP_FORWARDED')
562
+ Otto::Utils::ADDRESS_ONLY_HEADERS.each { |key| env.delete(key) }
563
+ rewrite_forwarded_for(env, nil)
506
564
  end
507
565
 
508
- # Mask X-Forwarded-For and related proxy headers
566
+ # Rewrite X-Forwarded-For and related proxy headers to one address
509
567
  #
510
- # Replaces forwarded IP headers with the masked IP to prevent leakage
511
- # when downstream code (including Rack's request.ip) parses these headers.
568
+ # Replaces every present forwarded IP header with +address+ so
569
+ # downstream code (including Rack's request.ip) that parses these
570
+ # headers finds only that address. The masking path passes the masked
571
+ # IP; the private/localhost exemption passes the resolved client IP.
572
+ # Absent headers stay absent.
512
573
  #
513
574
  # @param env [Hash] Rack environment
514
- # @param masked_ip [String] The masked IP to use as replacement
515
- def mask_forwarded_headers(env, masked_ip)
575
+ # @param address [String] The address to use as replacement
576
+ def rewrite_forwarded_addresses(env, address)
516
577
  # Defensive: never write a nil replacement into these CGI-style headers
517
578
  # (the Rack SPEC requires String values; a nil trips Rack::Lint — see
518
579
  # issue #167). apply_privacy's early "no client IP" guard already
519
- # guarantees a non-nil masked_ip here, but keep this method
580
+ # guarantees a non-nil address here, but keep this method
520
581
  # self-contained so a future caller change can't reintroduce a
521
582
  # present-but-nil HTTP_X_FORWARDED_FOR.
522
- return if masked_ip.nil?
523
-
524
- # Replace X-Forwarded-For with masked IP
525
- # This prevents Rack::Request#ip from finding the real IP
526
- env['HTTP_X_FORWARDED_FOR'] = masked_ip if env['HTTP_X_FORWARDED_FOR']
527
- env['HTTP_X_REAL_IP'] = masked_ip if env['HTTP_X_REAL_IP']
528
- env['HTTP_X_CLIENT_IP'] = masked_ip if env['HTTP_X_CLIENT_IP']
529
-
530
- # RFC 7239 Forwarded carries the client IP in a structured `for=`
531
- # token, and Otto reads it as an authoritative client-IP source in
532
- # count-based depth mode (trusted_proxy_header 'Forwarded'/'Both').
533
- # Left as-is it would leak the real IP to downstream code. Redact only
534
- # the `for=` value(s) so proto=/host=/by= metadata survives.
535
- if env['HTTP_FORWARDED']
536
- env['HTTP_FORWARDED'] = Otto::Privacy::IPPrivacy.mask_forwarded_for(env['HTTP_FORWARDED'], masked_ip)
537
- end
583
+ return if address.nil?
584
+
585
+ # Replace X-Forwarded-For, X-Real-IP, X-Client-IP and the vendor
586
+ # client-address headers (CF-Connecting-IP, True-Client-IP, ...)
587
+ # with the address. This prevents Rack::Request#ip, or code reading
588
+ # a vendor header, from finding any other address.
589
+ Otto::Utils::ADDRESS_ONLY_HEADERS.each { |key| env[key] = address if env[key] }
590
+
591
+ rewrite_forwarded_for(env, address)
592
+
593
+ Otto.logger.debug "[IPPrivacyMiddleware] Rewrote forwarded headers" if Otto.debug
594
+ end
538
595
 
539
- Otto.logger.debug "[IPPrivacyMiddleware] Masked forwarded headers" if Otto.debug
596
+ # Replace every `for=` value in RFC 7239 Forwarded with +replacement+,
597
+ # or remove the `for=` pairs when +replacement+ is nil.
598
+ #
599
+ # Forwarded carries the client IP in a structured `for=` token, and Otto
600
+ # reads it as an authoritative client-IP source in count-based depth
601
+ # mode (trusted_proxy_header 'Forwarded'/'Both'). Left as-is it would
602
+ # leak the real IP to downstream code. Only the `for=` value(s) are
603
+ # redacted, so proto=/host=/by= metadata survives. A header left with
604
+ # nothing but separators is deleted.
605
+ #
606
+ # The rewrite is a pattern match, so the result is re-read with Rack's
607
+ # parser (and Otto's). If any `for=` other than +replacement+ survives,
608
+ # or Rack cannot parse the result, the header is deleted and the
609
+ # deletion logged: losing proto=/host= is recoverable, a client-chosen
610
+ # address reaching Rack::Request#ip is not.
611
+ #
612
+ # @param env [Hash] Rack environment
613
+ # @param replacement [String, nil] an address, or nil to remove `for=`
614
+ def rewrite_forwarded_for(env, replacement)
615
+ value = env['HTTP_FORWARDED']
616
+ return unless value
617
+
618
+ rewritten = Otto::Privacy::IPPrivacy.redact_forwarded_for(value, replacement)
619
+ if rewritten.empty?
620
+ env.delete('HTTP_FORWARDED')
621
+ elsif Otto::Privacy::IPPrivacy.forwarded_for_only?(rewritten, replacement)
622
+ env['HTTP_FORWARDED'] = rewritten
623
+ else
624
+ env.delete('HTTP_FORWARDED')
625
+ Otto::Privacy::IPPrivacy.log_forwarded_deletion
626
+ end
540
627
  end
541
628
 
542
629
  # Check if the connecting peer counts as a trusted proxy
@@ -5,6 +5,7 @@
5
5
  require 'json'
6
6
 
7
7
  require_relative '../optional_dependency'
8
+ require_relative '../utils'
8
9
 
9
10
  class Otto
10
11
  module Security
@@ -31,12 +32,14 @@ class Otto
31
32
  default_requests_per_minute = config.fetch(:requests_per_minute, 100)
32
33
 
33
34
  # General request throttling. Internal paths (/_mcp, /_status, ...)
34
- # are skipped by default. PATH_INFO, not Rack::Request#path: #path
35
- # prepends SCRIPT_NAME, so with Otto mounted under `map '/api'` the
36
- # internal /_mcp request read as /api/_mcp and was counted here while
37
- # the MCP throttle, comparing the same way, never saw it at all.
35
+ # are skipped by default. The mount-relative routing path, not
36
+ # Rack::Request#path: #path prepends SCRIPT_NAME, so with Otto mounted
37
+ # under `map '/api'` the internal /_mcp request read as /api/_mcp and
38
+ # was counted here while the MCP throttle never saw it at all. And the
39
+ # routing path, not raw PATH_INFO, which counted /%5Fmcp while the
40
+ # router dispatched it as /_mcp.
38
41
  Rack::Attack.throttle('requests', limit: default_requests_per_minute, period: 60) do |request|
39
- request.ip unless request.path_info.start_with?('/_')
42
+ request.ip unless Otto::Utils.routing_path(request.env).start_with?('/_')
40
43
  end
41
44
 
42
45
  # Apply custom rules if provided
@@ -0,0 +1,396 @@
1
+ # lib/otto/security/trusted_proxy_config.rb
2
+ #
3
+ # frozen_string_literal: true
4
+
5
+ require 'ipaddr'
6
+ require_relative '../core/freezable'
7
+
8
+ class Otto
9
+ module Security
10
+ # Trusted-proxy resolution settings for one Otto application.
11
+ #
12
+ # An application answers "which peer may speak for the client?" in at most
13
+ # one of three ways (#mode):
14
+ #
15
+ # - :filter — enumerated proxy entries (IP, CIDR, Regexp, or a legacy
16
+ # string prefix); the client IP is found by walking the forwarded chain
17
+ # past trusted hops.
18
+ # - :depth — trust the last N hops, for proxy tiers whose addresses cannot
19
+ # be enumerated (Fly, cloud load balancers, dynamic reverse proxies).
20
+ # - :none — the explicit operator assertion that no proxy is trusted.
21
+ #
22
+ # #header picks the forwarded header depth mode counts hops from.
23
+ #
24
+ # This object owns the rules that keep those settings coherent. #mode is
25
+ # derived from the stored settings rather than stored beside them, and
26
+ # every mutator checks the state it would produce with #ensure_compatible!,
27
+ # the same check #validate! runs at freeze, so each rule is written once.
28
+ #
29
+ # Rules that involve other objects stay with Otto::Security::Config: the
30
+ # ip_privacy geo_header vs depth conflict, and pinning Rack's
31
+ # process-global forwarding family. Config keeps this object private and
32
+ # routes every change through its own setters (add_trusted_proxy,
33
+ # trusted_proxy_depth=, trusted_proxy_header=, trust_no_proxies!), which
34
+ # add those checks; #check_depth! and #check_header! let Config run them
35
+ # before anything is stored.
36
+ class TrustedProxyConfig
37
+ include Otto::Core::Freezable
38
+
39
+ # Error raised when the two mutually-exclusive trusted-proxy resolution
40
+ # modes are configured together: CIDR-walk (enumerated trusted_proxies)
41
+ # and count-based depth (trusted_proxy_depth >= 1).
42
+ PROXY_MODE_CONFLICT_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
43
+ Cannot configure both trusted_proxies (CIDR filter mode) and
44
+ trusted_proxy_depth >= 1 (count mode). Enumerate proxy CIDRs OR set a
45
+ hop count, not both.
46
+ MSG
47
+
48
+ # Error raised when the explicit "trust no proxy" assertion
49
+ # (trust_no_proxies!, `trusted_proxies: :none`) is combined with an
50
+ # actual trust grant (enumerated CIDRs or a depth >= 1). The two say
51
+ # opposite things about the same peer, so the combination is refused at
52
+ # configuration time rather than silently resolved in one direction.
53
+ TRUST_NO_PROXIES_CONFLICT_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
54
+ Cannot combine trusted_proxies: :none (trust no proxy) with
55
+ trusted_proxies CIDRs or trusted_proxy_depth >= 1. Assert :none OR
56
+ grant trust, not both.
57
+ MSG
58
+
59
+ # Error raised when the trust-nobody sentinel arrives as a proxy ENTRY
60
+ # (`trusted_proxies: ['none']`, as a YAML/JSON list naturally yields, or
61
+ # `add_trusted_proxy('none')`) instead of as the whole option. Inside a
62
+ # list it would otherwise register a legacy string-prefix matcher that
63
+ # matches nothing: peers would be untrusted, but trust_no_proxies? would
64
+ # stay false and the config would stake a forwarding-family claim, so the
65
+ # explicit assertion would be silently replaced by a lookalike.
66
+ TRUST_NO_PROXIES_ENTRY_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
67
+ trusted_proxies entry :none is the trust-nobody assertion, not a proxy
68
+ address. Pass trusted_proxies: :none as the whole option (not inside a
69
+ list) or call trust_no_proxies! instead.
70
+ MSG
71
+
72
+ # Error raised when a non-default header is combined with CIDR filter
73
+ # mode. Otto's CIDR-walk resolves the client IP from the X-Forwarded-For
74
+ # family only (X-Forwarded-For, then X-Real-IP, then X-Client-IP —
75
+ # Otto::Utils::FORWARDED_FOR_HEADERS), never RFC 7239 Forwarded, while
76
+ # trusted_proxy_header also pins Rack's forwarding family; honoring
77
+ # 'Forwarded' or 'Both' there would make Rack read a header Otto ignores,
78
+ # recreating the disagreement the pin exists to close.
79
+ FORWARDED_HEADER_CIDR_CONFLICT_MESSAGE = <<~MSG.gsub(/\s+/, ' ').strip.freeze
80
+ Cannot configure trusted_proxy_header 'Forwarded' or 'Both' together
81
+ with trusted_proxies (CIDR filter mode): CIDR-walk resolves client IPs
82
+ from the X-Forwarded-For family only (X-Forwarded-For, X-Real-IP,
83
+ X-Client-IP), never RFC 7239 Forwarded. Use trusted_proxy_depth (count
84
+ mode) to read the RFC 7239 Forwarded header.
85
+ MSG
86
+
87
+ # Sentinel accepted wherever a trusted_proxies list is accepted, meaning
88
+ # "the operator asserts that NO proxy is trusted". See #trust_none!.
89
+ TRUST_NO_PROXIES = :none
90
+
91
+ # Forwarded-header sources depth mode can count hops from:
92
+ # X-Forwarded-For (default), the RFC 7239 Forwarded header, or Both
93
+ # (Forwarded when present, else X-Forwarded-For). Mirrors OneTimeSecret's
94
+ # site.network.trusted_proxy.header. Only consulted in depth mode;
95
+ # CIDR-walk is unaffected.
96
+ HEADERS = %w[X-Forwarded-For Forwarded Both].freeze
97
+ DEFAULT_HEADER = 'X-Forwarded-For'
98
+
99
+ # Whether a trusted_proxies option value is the trust-nobody sentinel.
100
+ # Accepts the symbol and the String spelling 'none' (case-insensitive),
101
+ # which is what YAML/ENV-driven configuration naturally produces; without
102
+ # this, 'none' would fall through to #add and install a legacy
103
+ # string-prefix matcher, silently inverting the assertion.
104
+ #
105
+ # @param value [Object] raw trusted_proxies option
106
+ # @return [Boolean]
107
+ def self.trust_no_proxies_option?(value)
108
+ (value.is_a?(Symbol) || value.is_a?(String)) && value.to_s.casecmp?('none')
109
+ end
110
+
111
+ # Proxy entries in registration order (filter mode).
112
+ # @return [Array<String, Regexp>]
113
+ attr_reader :proxies
114
+
115
+ # Count-based depth; nil or 0 disables depth mode.
116
+ # @return [Integer, nil]
117
+ attr_reader :depth
118
+
119
+ # Canonical forwarded header depth mode counts hops from.
120
+ # @return [String] one of HEADERS
121
+ attr_reader :header
122
+
123
+ def initialize
124
+ @proxies = []
125
+ @matchers = []
126
+ @trust_none = false
127
+ @depth = nil
128
+ @header = DEFAULT_HEADER
129
+ end
130
+
131
+ # The active resolution mode, or nil when proxy trust is unconfigured.
132
+ #
133
+ # @return [Symbol, nil] :filter, :depth, :none, or nil
134
+ def mode
135
+ return :filter if filter?
136
+ return :depth if depth?
137
+
138
+ :none if trust_none?
139
+ end
140
+
141
+ # Whether any mode is configured. When false, Otto leaves
142
+ # env['otto.via_trusted_proxy'] absent (the tri-state contract).
143
+ #
144
+ # @return [Boolean]
145
+ def configured?
146
+ !mode.nil?
147
+ end
148
+
149
+ # Whether proxy entries are registered (CIDR filter mode).
150
+ #
151
+ # @return [Boolean]
152
+ def filter?
153
+ @matchers.any?
154
+ end
155
+
156
+ # Whether count-based depth mode is active. Integer-strict, so a value
157
+ # that never passed #depth= cannot enable it.
158
+ #
159
+ # @return [Boolean] true when depth is an Integer >= 1
160
+ def depth?
161
+ @depth.is_a?(Integer) && @depth >= 1
162
+ end
163
+
164
+ # Whether the operator asserted that no proxy is trusted.
165
+ #
166
+ # @return [Boolean]
167
+ def trust_none?
168
+ @trust_none
169
+ end
170
+
171
+ # Whether request handling reads a forwarded chain, and so depends on
172
+ # Rack's process-global forwarding family. True in filter and depth mode;
173
+ # false under trust-nobody (reads nothing) and when unconfigured.
174
+ #
175
+ # @return [Boolean]
176
+ def forwarding_family_dependent?
177
+ filter? || depth?
178
+ end
179
+
180
+ # Whether #header is the X-Forwarded-For default.
181
+ #
182
+ # @return [Boolean]
183
+ def default_header?
184
+ @header == DEFAULT_HEADER
185
+ end
186
+
187
+ # Register one entry or a list of entries (filter mode). The whole list
188
+ # is validated before anything is registered, so a rejected list leaves
189
+ # this object untouched.
190
+ #
191
+ # @param proxy [String, Regexp, Array<String, Regexp>] entry or entries
192
+ # @raise [ArgumentError] on a mode conflict, a trust-nobody sentinel
193
+ # inside the list, or an unsupported type
194
+ # @raise [FrozenError] if frozen
195
+ # @return [void]
196
+ def add(proxy)
197
+ ensure_not_frozen!
198
+ # Adding claims filter mode even when the list is empty, so the
199
+ # conflict surfaces at the call that introduced it.
200
+ ensure_compatible!(filter: true)
201
+ Array(proxy).each do |entry|
202
+ raise ArgumentError, TRUST_NO_PROXIES_ENTRY_MESSAGE if self.class.trust_no_proxies_option?(entry)
203
+ end
204
+
205
+ case proxy
206
+ when String, Regexp
207
+ @proxies << proxy
208
+ @matchers << build_matcher(proxy)
209
+ when Array
210
+ # Build every matcher before touching state, so a failure partway
211
+ # through cannot leave entries and matchers out of step.
212
+ matchers = proxy.map { |entry| build_matcher(entry) }
213
+ @proxies.concat(proxy)
214
+ @matchers.concat(matchers)
215
+ else
216
+ raise ArgumentError, 'Proxy must be a String, Regexp, or Array'
217
+ end
218
+ end
219
+
220
+ # Assert that no proxy is trusted.
221
+ #
222
+ # @raise [ArgumentError] if entries or a depth >= 1 are configured
223
+ # @raise [FrozenError] if frozen
224
+ # @return [void]
225
+ def trust_none!
226
+ ensure_not_frozen!
227
+ ensure_compatible!(trust_none: true)
228
+ @trust_none = true
229
+ end
230
+
231
+ # Raise unless depth could be assigned: a non-negative Integer or nil,
232
+ # compatible with the current mode. Stores nothing.
233
+ #
234
+ # @param depth [Object] candidate value
235
+ # @raise [ArgumentError] if invalid or conflicting
236
+ # @return [Integer, nil] depth
237
+ def check_depth!(depth)
238
+ validate_depth_value!(depth)
239
+ ensure_compatible!(depth: depth.to_i >= 1)
240
+ depth
241
+ end
242
+
243
+ # @param depth [Integer, nil] number of trusted hops (nil/0 disables depth mode)
244
+ # @raise [ArgumentError] if invalid or conflicting (see #check_depth!)
245
+ # @raise [FrozenError] if frozen
246
+ def depth=(depth)
247
+ ensure_not_frozen!
248
+ @depth = check_depth!(depth)
249
+ end
250
+
251
+ # Raise unless header could be assigned, and return its canonical
252
+ # spelling. Matching is case-insensitive and ignores surrounding
253
+ # whitespace; an unrecognized value fails loud instead of silently
254
+ # resolving from the wrong header. Stores nothing.
255
+ #
256
+ # @param header [Object] candidate value
257
+ # @raise [ArgumentError] if unrecognized or conflicting with filter mode
258
+ # @return [String] canonical header (one of HEADERS)
259
+ def check_header!(header)
260
+ candidate = header.to_s.strip
261
+ canonical = HEADERS.find { |allowed| allowed.casecmp?(candidate) }
262
+ raise ArgumentError, invalid_header_message(header) unless canonical
263
+
264
+ ensure_compatible!(header: canonical)
265
+ canonical
266
+ end
267
+
268
+ # @param header [String] one of HEADERS (case-insensitive)
269
+ # @raise [ArgumentError] if invalid or conflicting (see #check_header!)
270
+ # @raise [FrozenError] if frozen
271
+ def header=(header)
272
+ ensure_not_frozen!
273
+ @header = check_header!(header)
274
+ end
275
+
276
+ # Whether ip matches a registered entry.
277
+ #
278
+ # String entries that parse as an IP or CIDR range are matched with
279
+ # proper IPAddr containment (IPv4 and IPv6). Entries that are not valid
280
+ # IPs (e.g. a bare prefix like '172.16.') fall back to the legacy
281
+ # exact/prefix string match for backward compatibility. Regexp entries
282
+ # are matched against the raw IP string. Entries are parsed once at
283
+ # registration, never per request.
284
+ #
285
+ # @param ip [String] IP address to check
286
+ # @return [Boolean]
287
+ def trusted?(ip)
288
+ return false if @matchers.empty? || ip.nil? || ip.empty?
289
+
290
+ # Fold IPv4-mapped IPv6 (::ffff:a.b.c.d) to plain IPv4 so a dual-stack
291
+ # peer presented in mapped form still matches an IPv4 proxy entry.
292
+ client = parse_ipaddr(ip)&.native
293
+
294
+ @matchers.any? do |entry, range|
295
+ if range
296
+ # Pre-parsed IP/CIDR entry -> proper containment
297
+ client && ip_in_range?(range, client)
298
+ elsif entry.is_a?(Regexp)
299
+ entry.match?(ip)
300
+ elsif entry.is_a?(String)
301
+ # Legacy non-IP entry (e.g. '172.16.') -> exact/prefix match
302
+ ip == entry || ip.start_with?(entry)
303
+ else
304
+ false
305
+ end
306
+ end
307
+ end
308
+
309
+ # Re-check every rule against the stored state. The mutators already
310
+ # enforce them; this is the freeze-time backstop for state that bypassed
311
+ # them (a direct instance-variable write).
312
+ #
313
+ # @raise [ArgumentError] if any rule is violated
314
+ # @return [void]
315
+ def validate!
316
+ raise ArgumentError, invalid_header_message(@header) unless HEADERS.include?(@header)
317
+
318
+ validate_depth_value!(@depth)
319
+ ensure_compatible!
320
+ end
321
+
322
+ private
323
+
324
+ def ensure_not_frozen!
325
+ raise FrozenError, 'Cannot modify frozen configuration' if frozen?
326
+ end
327
+
328
+ # The mutual-exclusion rules, in one place. Each flag says whether that
329
+ # mode would be active; a mutator overrides the one it is about to
330
+ # change and the rest default to the stored state.
331
+ def ensure_compatible!(filter: filter?, depth: depth?, trust_none: trust_none?, header: @header)
332
+ raise ArgumentError, PROXY_MODE_CONFLICT_MESSAGE if filter && depth
333
+ raise ArgumentError, TRUST_NO_PROXIES_CONFLICT_MESSAGE if trust_none && (filter || depth)
334
+ raise ArgumentError, FORWARDED_HEADER_CIDR_CONFLICT_MESSAGE if filter && header != DEFAULT_HEADER
335
+ end
336
+
337
+ # Type and range only, so an invalid value raises a clear ArgumentError
338
+ # instead of a downstream NoMethodError from #to_i coercion.
339
+ def validate_depth_value!(depth)
340
+ return if depth.nil?
341
+
342
+ unless depth.is_a?(Integer)
343
+ raise ArgumentError,
344
+ "trusted_proxy_depth must be an Integer or nil, got #{depth.class}"
345
+ end
346
+
347
+ raise ArgumentError, "trusted_proxy_depth must be >= 0, got #{depth}" if depth.negative?
348
+ end
349
+
350
+ def invalid_header_message(header)
351
+ "trusted_proxy_header must be one of #{HEADERS.join(', ')}, got #{header.inspect}"
352
+ end
353
+
354
+ # Parse a value into an IPAddr, returning nil for invalid / non-IP input.
355
+ def parse_ipaddr(value)
356
+ IPAddr.new(value)
357
+ rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError
358
+ nil
359
+ end
360
+
361
+ # Build a cached [raw_entry, parsed_range_or_nil] tuple at registration.
362
+ #
363
+ # The parsed range is folded through IPAddr#native, to match the fold
364
+ # #trusted? applies to the client address. Without it a mapped-IPv6
365
+ # proxy entry (::ffff:10.0.0.0/104) could never match, because
366
+ # #ip_in_range?'s family check would reject the folded IPv4 client — a
367
+ # proxy silently untrusted, which is what gates otto.via_trusted_proxy,
368
+ # secure?, and geo-header trust. #native returns self for entries that
369
+ # are not IPv4-mapped/compatible.
370
+ def build_matcher(entry)
371
+ return [entry, nil] unless entry.is_a?(String)
372
+
373
+ range = parse_ipaddr(entry)&.native
374
+ warn_legacy_proxy_entry(entry) unless range
375
+ [entry, range]
376
+ end
377
+
378
+ def warn_legacy_proxy_entry(entry)
379
+ Otto.logger.warn(
380
+ "[Otto::Security::Config] trusted proxy #{entry.inspect} is not a " \
381
+ 'valid IP or CIDR; using legacy string-prefix matching. Prefer a ' \
382
+ "CIDR range (e.g. '172.16.0.0/12')."
383
+ )
384
+ end
385
+
386
+ # CIDR/host containment that is safe across address families.
387
+ def ip_in_range?(range, client)
388
+ return false unless range.family == client.family
389
+
390
+ range.include?(client)
391
+ rescue IPAddr::InvalidAddressError
392
+ false
393
+ end
394
+ end
395
+ end
396
+ end