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
@@ -0,0 +1,124 @@
1
+ # lib/otto/core/option_hash.rb
2
+ #
3
+ # frozen_string_literal: true
4
+
5
+ require_relative 'redacted_inspect'
6
+
7
+ class Otto
8
+ module Core
9
+ # The Hash behind Otto#option. freeze_configuration! deep-freezes it, and
10
+ # Ruby's FrozenError message embeds #inspect of the frozen receiver, so a
11
+ # late write such as otto.option[:x] = 1 would print every option,
12
+ # including the MCP bearer tokens.
13
+ #
14
+ # .build and every Hash method that can store a value under a key (#[]=,
15
+ # #store, #merge!, #update, #replace, #transform_values!,
16
+ # #transform_keys!) store the values of .secret_keys as RedactedInspect
17
+ # secrets (a SecretList or SecretSet of SecretStrings, or a
18
+ # SecretString), so a write to the frozen token collection or to one
19
+ # token cannot print them either. #inspect also redacts those keys
20
+ # whatever their value. It is still a Hash, and the token values are
21
+ # still an Array, a Set or a String.
22
+ class OptionHash < Hash
23
+ # Option keys whose values are MCP bearer tokens, in both spellings a
24
+ # caller may use (see Otto::MCP::Options::OPTION_ALIASES).
25
+ def self.secret_keys
26
+ @secret_keys ||= Otto::MCP::Options::OPTION_ALIASES.fetch(:auth_tokens).flat_map do |key|
27
+ [key, key.to_s]
28
+ end.freeze
29
+ end
30
+
31
+ # @param hash [Hash] assembled options
32
+ # @return [OptionHash] a copy with secret values wrapped
33
+ def self.build(hash)
34
+ hash.each_with_object(new) do |(key, value), options|
35
+ options[key] = value
36
+ end
37
+ end
38
+
39
+ # Stores value, wrapped by RedactedInspect.secret when key is one of
40
+ # .secret_keys, so a token assigned after construction is covered too.
41
+ def []=(key, value)
42
+ super(key, self.class.secret_keys.include?(key) ? RedactedInspect.secret(value) : value)
43
+ end
44
+ alias store []=
45
+
46
+ # The other Hash methods that can put a value under a key are written in
47
+ # C and do not call #[]=, so each wraps the secret keys after it runs.
48
+ # (default= and default_proc= set no entry.)
49
+
50
+ # @return [self]
51
+ def merge!(...)
52
+ super
53
+ wrap_secret_values!
54
+ end
55
+ alias update merge!
56
+
57
+ # @return [self]
58
+ def replace(...)
59
+ super
60
+ wrap_secret_values!
61
+ end
62
+
63
+ # @return [self]
64
+ def transform_values!(...)
65
+ result = super
66
+ wrap_secret_values!
67
+ result
68
+ end
69
+
70
+ # @return [self]
71
+ def transform_keys!(...)
72
+ result = super
73
+ wrap_secret_values!
74
+ result
75
+ end
76
+
77
+ # @return [String] Hash#inspect with each secret key's value redacted
78
+ def inspect
79
+ redacted_view.inspect
80
+ end
81
+ alias to_s inspect
82
+
83
+ # Hash#pretty_print walks the pairs itself instead of calling #inspect.
84
+ #
85
+ # @param printer [PP]
86
+ def pretty_print(printer)
87
+ printer.pp(redacted_view)
88
+ end
89
+
90
+ private
91
+
92
+ # Re-store each secret key's value through #[]=, which wraps it.
93
+ def wrap_secret_values!
94
+ self.class.secret_keys.each do |key|
95
+ self[key] = fetch(key) if key?(key)
96
+ end
97
+ self
98
+ end
99
+
100
+ # A plain Hash copy with each secret key's value replaced.
101
+ def redacted_view
102
+ to_h do |key, value|
103
+ [key, self.class.secret_keys.include?(key) ? Placeholder.new(value) : value]
104
+ end
105
+ end
106
+
107
+ # Prints the redaction placeholder for a secret value from #inspect and
108
+ # from pp.
109
+ Placeholder = Struct.new(:value) do
110
+ def inspect
111
+ return 'nil' if value.nil?
112
+ return "#{RedactedInspect::PLACEHOLDER} (#{value.size})" if value.is_a?(Enumerable) && !value.is_a?(Hash)
113
+
114
+ RedactedInspect::PLACEHOLDER
115
+ end
116
+
117
+ def pretty_print(printer)
118
+ printer.text(inspect)
119
+ end
120
+ end
121
+ private_constant :Placeholder
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,149 @@
1
+ # lib/otto/core/redacted_inspect.rb
2
+ #
3
+ # frozen_string_literal: true
4
+
5
+ class Otto
6
+ module Core
7
+ # An #inspect in the format of Object#inspect that leaves out secret
8
+ # values. Ruby's FrozenError message embeds the receiver's #inspect, so a
9
+ # write to a frozen object that holds a secret would otherwise put the
10
+ # secret in the exception message, and from there in logs.
11
+ #
12
+ # Including classes override #redacted_inspect_value for the instance
13
+ # variables that hold secrets and return the placeholder from
14
+ # #redacted_placeholder instead of the value.
15
+ #
16
+ # @example
17
+ # class Holder
18
+ # include Otto::Core::RedactedInspect
19
+ #
20
+ # private
21
+ #
22
+ # def redacted_inspect_value(ivar, value)
23
+ # ivar == :@secret ? redacted_placeholder(value) : super
24
+ # end
25
+ # end
26
+ module RedactedInspect
27
+ # Stands in for a redacted value in #inspect output.
28
+ PLACEHOLDER = '[REDACTED]'
29
+
30
+ # A String whose #inspect is PLACEHOLDER. Content, #to_s, ==, eql? and
31
+ # hash are String's, so it compares, hashes and interpolates as the
32
+ # secret it holds. A write to a frozen one raises a FrozenError whose
33
+ # message shows the placeholder.
34
+ class SecretString < String
35
+ # @return [String] PLACEHOLDER
36
+ def inspect
37
+ PLACEHOLDER
38
+ end
39
+
40
+ # pp prints a multi-line String line by line, each as a plain String.
41
+ #
42
+ # @param printer [PP]
43
+ def pretty_print(printer)
44
+ printer.text(inspect)
45
+ end
46
+ end
47
+
48
+ # An Array of secrets whose #inspect (and #to_s, which Array aliases to
49
+ # its C inspect) shows PLACEHOLDER and the element count. Element access,
50
+ # ==, include? and iteration are Array's. A write to a frozen one raises
51
+ # a FrozenError whose message shows the placeholder.
52
+ class SecretList < Array
53
+ # @return [String] "[REDACTED] (N)"
54
+ def inspect
55
+ "#{PLACEHOLDER} (#{size})"
56
+ end
57
+ alias to_s inspect
58
+
59
+ # @param printer [PP]
60
+ def pretty_print(printer)
61
+ printer.text(inspect)
62
+ end
63
+ end
64
+
65
+ # A Set of secrets whose #inspect, #to_s and #pretty_print show
66
+ # PLACEHOLDER and the element count. Membership, ==, include? and
67
+ # iteration are Set's. A write to a frozen one raises a FrozenError
68
+ # without the elements: before Ruby 3.5 Set raises it for its internal
69
+ # Hash, whose keys print as SecretString placeholders.
70
+ class SecretSet < Set
71
+ # @return [String] "[REDACTED] (N)"
72
+ def inspect
73
+ "#{PLACEHOLDER} (#{size})"
74
+ end
75
+ alias to_s inspect
76
+
77
+ # @param printer [PP]
78
+ def pretty_print(printer)
79
+ printer.text(inspect)
80
+ end
81
+ end
82
+
83
+ # Wrap a secret so its #inspect is redacted: a String becomes a frozen
84
+ # SecretString copy, an Array a SecretList and a Set a SecretSet of
85
+ # such SecretStrings. Other values (nil, or something validation will
86
+ # reject) are returned as given. The strings are frozen so a write to
87
+ # one raises a FrozenError that shows the placeholder, also inside a
88
+ # Set, which Otto::Core::Freezable freezes without its elements.
89
+ #
90
+ # @param value [Object]
91
+ # @return [Object] a copy for a String, Array or Set, value otherwise
92
+ def self.secret(value)
93
+ case value
94
+ when SecretString then value.frozen? ? value : SecretString.new(value).freeze
95
+ when String then SecretString.new(value).freeze
96
+ when Array then SecretList.new(value.map { |item| secret(item) })
97
+ when Set then SecretSet.new(value.map { |item| secret(item) })
98
+ else value
99
+ end
100
+ end
101
+
102
+ # Per-fiber set of objects whose #inspect is running, so an object that
103
+ # is reachable from its own instance variables prints as "...".
104
+ IN_PROGRESS_KEY = :__otto_redacted_inspect_in_progress__
105
+ private_constant :IN_PROGRESS_KEY
106
+
107
+ # @return [String] "#<Class:0x... @ivar=value, ...>" with secret values
108
+ # replaced
109
+ def inspect
110
+ head = Kernel.instance_method(:to_s).bind_call(self).delete_suffix('>')
111
+ in_progress = (Thread.current[IN_PROGRESS_KEY] ||= {}.compare_by_identity)
112
+ return "#{head} ...>" if in_progress.key?(self)
113
+
114
+ in_progress[self] = true
115
+ begin
116
+ fields = instance_variables.map do |ivar|
117
+ "#{ivar}=#{redacted_inspect_value(ivar, instance_variable_get(ivar))}"
118
+ end
119
+ fields.empty? ? "#{head}>" : "#{head} #{fields.join(', ')}>"
120
+ ensure
121
+ in_progress.delete(self)
122
+ end
123
+ end
124
+
125
+ private
126
+
127
+ # The text shown for one instance variable. Override to redact.
128
+ #
129
+ # @param _ivar [Symbol] instance variable name, e.g. :@secret
130
+ # @param value [Object] its value
131
+ # @return [String]
132
+ def redacted_inspect_value(_ivar, value)
133
+ value.inspect
134
+ end
135
+
136
+ # The placeholder for a secret value: nil stays "nil" so an unset secret
137
+ # is still visible, and a collection shows how many values it holds.
138
+ #
139
+ # @param value [Object] the secret value
140
+ # @return [String]
141
+ def redacted_placeholder(value)
142
+ return 'nil' if value.nil?
143
+ return "#{PLACEHOLDER} (#{value.size})" if value.is_a?(Enumerable) && value.respond_to?(:size)
144
+
145
+ PLACEHOLDER
146
+ end
147
+ end
148
+ end
149
+ end
@@ -8,6 +8,9 @@ class Otto
8
8
  module Core
9
9
  # Router module providing route loading and request dispatching functionality
10
10
  module Router
11
+ # Request methods the static-mount and public-directory stages answer.
12
+ STATIC_VERBS = %i[GET HEAD].freeze
13
+
11
14
  def load(path)
12
15
  path = File.expand_path(path)
13
16
  raise ArgumentError, "Bad path: #{path}" unless File.exist?(path)
@@ -116,9 +119,7 @@ class Otto
116
119
  # path.
117
120
  path_info_clean = Otto::Utils.routing_path(env)
118
121
 
119
- http_verb = env['REQUEST_METHOD'].upcase.to_sym
120
- literal_routes = routes_literal[http_verb] || {}
121
- literal_routes.merge! routes_literal[:GET] if http_verb == :HEAD
122
+ http_verb = env['REQUEST_METHOD'].upcase.to_sym
122
123
 
123
124
  # Dynamic-route and static-file dispatch match against the SAME
124
125
  # normalized path the literal table and the LocalhostGuard use, so all
@@ -134,7 +135,10 @@ class Otto
134
135
  # for them. Literal lookup keeps '' — it already keys root that way.
135
136
  dispatch_path = path_info_clean.empty? ? '/' : path_info_clean
136
137
 
137
- static_candidate = !static_route.nil? && http_verb == :GET
138
+ # The static stages answer GET and HEAD. Rack::Files returns the GET
139
+ # headers with an empty body for HEAD.
140
+ static_verb = STATIC_VERBS.include?(http_verb)
141
+ static_candidate = !static_route.nil? && static_verb
138
142
 
139
143
  # Dispatch precedence is fixed: literal routes, then explicit static
140
144
  # mounts (longest prefix first), then the implicit public directory,
@@ -142,8 +146,7 @@ class Otto
142
146
  # containment validation before it is served (issues #257, #260 and
143
147
  # #267). A mount or the public directory claims files, not paths: when
144
148
  # the file is absent the request falls through to the next stage.
145
- if literal_routes.has_key?(path_info_clean)
146
- route = literal_routes[path_info_clean]
149
+ if (route = find_literal_route(http_verb, path_info_clean))
147
150
  Otto.structured_log(:debug, 'Route matched',
148
151
  Otto::LoggingHelpers.request_context(env).merge(
149
152
  type: 'literal',
@@ -155,7 +158,7 @@ class Otto
155
158
  @route_matched_callbacks.each { |cb| cb.call(env, route.route_definition) }
156
159
  end
157
160
  route.call(env)
158
- elsif http_verb == :GET && (mounted = resolve_mounted_file(dispatch_path))
161
+ elsif static_verb && (mounted = resolve_mounted_file(dispatch_path))
159
162
  mount, static_file = mounted
160
163
  Otto.structured_log(:debug, 'Route matched',
161
164
  Otto::LoggingHelpers.request_context(env).merge(
@@ -167,7 +170,7 @@ class Otto
167
170
  Otto::LoggingHelpers.request_context(env).merge(type: 'static'))
168
171
  serve_static_file(env, static_file)
169
172
  else
170
- match_dynamic_route(env, dispatch_path, http_verb, literal_routes)
173
+ match_dynamic_route(env, dispatch_path, http_verb)
171
174
  end
172
175
  end
173
176
 
@@ -244,15 +247,33 @@ class Otto
244
247
  root && Rack::Files.new(root)
245
248
  end
246
249
 
250
+ # Look up a literal route for +http_verb+ without building or mutating a
251
+ # table. A HEAD request uses the declared HEAD route when there is one
252
+ # and falls back to the GET route for the same path.
253
+ #
254
+ # @param http_verb [Symbol] request method, e.g. +:GET+ or +:HEAD+
255
+ # @param path [String] normalized routing path
256
+ # @return [Otto::Route, nil]
257
+ def find_literal_route(http_verb, path)
258
+ route = routes_literal[http_verb]&.[](path)
259
+ route ||= routes_literal[:GET]&.[](path) if http_verb == :HEAD
260
+ route
261
+ end
262
+
247
263
  # +dispatch_path+ is the normalized path from #handle_request (see the
248
264
  # +dispatch_path+ comment there): +Otto::Utils.routing_path+ output with
249
265
  # root's empty string mapped back to '/' so the anchored route regexes can
250
266
  # match. It is deliberately NOT the raw +routing_path+ value.
251
- def match_dynamic_route(env, dispatch_path, http_verb, literal_routes)
267
+ #
268
+ # HEAD tries the declared HEAD routes first, then the GET routes. The two
269
+ # tables are chained rather than merged, so no request copies or mutates
270
+ # the registered tables (the configuration freeze makes them read-only
271
+ # after the first request).
272
+ def match_dynamic_route(env, dispatch_path, http_verb)
252
273
  extra_params = {}
253
274
  found_route = nil
254
275
  valid_routes = routes[http_verb] || []
255
- valid_routes.push(*routes[:GET]) if http_verb == :HEAD
276
+ valid_routes = valid_routes.chain(routes[:GET] || []) if http_verb == :HEAD
256
277
 
257
278
  valid_routes.each do |route|
258
279
  next unless (match = route.pattern.match(dispatch_path))
@@ -276,10 +297,11 @@ class Otto
276
297
  break
277
298
  end
278
299
 
279
- found_route ||= literal_routes['/404']
300
+ not_found_route = find_literal_route(http_verb, '/404')
301
+ found_route ||= not_found_route
280
302
  if found_route
281
303
  # Log 404 route usage if we fell back to it
282
- if found_route == literal_routes['/404']
304
+ if found_route == not_found_route
283
305
  Otto.structured_log(:info, 'Route not found',
284
306
  Otto::LoggingHelpers.request_context(env).merge(
285
307
  fallback_to: '404_route'
@@ -343,8 +365,13 @@ class Otto
343
365
  @mcp_server.register_mcp_route(route_info)
344
366
  Otto.logger.debug "[MCP] Registered resource route: #{definition}" if Otto.debug
345
367
  rescue Otto::RouteDefinitionError
346
- # Same fail-fast contract as the normal route loader: a malformed
347
- # security-gating option must abort boot, not just log-and-drop.
368
+ # Must abort boot, not log-and-drop. RouteParser raises this for any
369
+ # auth, role or csrf token on an MCP or TOOL line, well formed or not,
370
+ # because the MCP server never enforces them: registering the route
371
+ # would make it look protected while any caller of the endpoint can
372
+ # reach it. handle_tool_route re-raises for the same reason. The
373
+ # "not enabled" RuntimeError above is still logged and dropped, so a
374
+ # file loaded before enable_mcp! skips these lines unchecked.
348
375
  raise
349
376
  rescue StandardError => e
350
377
  Otto.logger.error "[MCP] Failed to parse MCP route: #{definition} - #{e.message}"
data/lib/otto/core.rb CHANGED
@@ -2,6 +2,8 @@
2
2
  #
3
3
  # frozen_string_literal: true
4
4
 
5
+ require_relative 'core/redacted_inspect'
6
+ require_relative 'core/option_hash'
5
7
  require_relative 'core/router'
6
8
  require_relative 'core/file_safety'
7
9
  require_relative 'core/static_mounts'
data/lib/otto/env_keys.rb CHANGED
@@ -64,6 +64,20 @@ class Otto
64
64
  # Used by: All security middleware (CSRF, Headers, Validation)
65
65
  SECURITY_CONFIG = 'otto.security_config'
66
66
 
67
+ # The CSRF binding resolved for this request, as a String, when the client
68
+ # does not already send it: a binding minted by, or read from
69
+ # csrf_session_key in, Otto::Security::Config#get_or_create_session_id.
70
+ # The session store's own id and a binding read from a cookie are not
71
+ # written, except the id a store that runs inside CSRFMiddleware creates
72
+ # when CSRFMiddleware mints a binding: that store has already committed
73
+ # and does not send it. A later call that records a binding replaces an
74
+ # earlier one; a call that records none leaves it.
75
+ # Type: String
76
+ # Set by: Otto::Security::Config#get_or_create_session_id, CSRFMiddleware
77
+ # Used by: CSRFMiddleware (sets the binding cookie from it on responses,
78
+ # HTML or not, to safe requests; it is the only source of that cookie)
79
+ CSRF_BINDING = 'otto.csrf_binding'
80
+
67
81
  # Per-request CSP nonce, minted lazily on first access and memoized here.
68
82
  # Type: String (base64)
69
83
  # Set by: Otto::Security::CSP.nonce / Otto::Request#csp_nonce (first touch)
@@ -192,18 +206,23 @@ class Otto
192
206
  # Canonical client IP, resolved once early by IPPrivacyMiddleware
193
207
  # ("resolve once, read everywhere"). Downstream code (client_ipaddress,
194
208
  # Request#ip) reads this instead of re-deriving from REMOTE_ADDR / XFF.
195
- # Type: String
196
- # Set by: IPPrivacyMiddleware (every request, all modes)
209
+ # Type: String, or nil when no client IP resolves
210
+ # Set by: IPPrivacyMiddleware (every request that resolves a client IP;
211
+ # with privacy disabled it is also written, as nil, when none
212
+ # resolves)
197
213
  # Value: masked IP when privacy enabled; resolved real IP when privacy
198
214
  # disabled or the address is exempt (private/localhost)
199
- # Note: presence also acts as the idempotency guard for the middleware
215
+ # Note: presence acts as the idempotency guard for the middleware. A pass
216
+ # that resolved no client IP under privacy masking leaves this key
217
+ # absent; the guard recognises that pass by IP_MATCH together with
218
+ # otto.peer_relayed, which every pass writes before resolving.
200
219
  CLIENT_IP = 'otto.client_ip'
201
220
 
202
221
  # Verdict-only CIDR membership check over the resolved, UNMASKED client IP
203
222
  # Type: Proc — call with an Enumerable of CIDR strings or IPAddr objects,
204
223
  # returns true/false
205
- # Set by: IPPrivacyMiddleware (every path that resolves an IP, all
206
- # privacy profiles)
224
+ # Set by: IPPrivacyMiddleware (every request it processes, all privacy
225
+ # profiles, including a request with no resolvable client IP)
207
226
  # Used by: Downstream IP policy code (allowlists, denylists, network
208
227
  # zones) that needs full /32-/128 precision without changing the
209
228
  # observability posture — CLIENT_IP is masked under the default
@@ -217,8 +236,12 @@ class Otto
217
236
  # Note: setting CLIENT_IP yourself is out of contract — it trips the
218
237
  # middleware's idempotency guard, so the unmasked address is never
219
238
  # captured and this capability degrades to a logged fail-closed
220
- # check that denies every range. Test harnesses build both keys
221
- # with Otto::Testing.env_for (require 'otto/testing').
239
+ # check that denies every range. Setting IP_MATCH yourself is out of
240
+ # contract too, but does not trip the guard: without
241
+ # otto.peer_relayed it is not taken for a prior pass, so the
242
+ # middleware logs a warning, replaces it, and resolves and masks as
243
+ # usual. Test harnesses build both keys with Otto::Testing.env_for
244
+ # (require 'otto/testing').
222
245
  IP_MATCH = 'otto.ip_match'
223
246
 
224
247
  # Privacy-safe masked IP address
@@ -40,7 +40,7 @@ class Otto
40
40
  #
41
41
  # custom_base = Otto::LoggingHelpers.request_context(env).merge(
42
42
  # transaction_id: Thread.current[:transaction_id],
43
- # user_id: env['otto.user']&.id,
43
+ # user_id: env['otto.strategy_result']&.user_id,
44
44
  # tenant_id: env['tenant_id']
45
45
  # )
46
46
  #
@@ -6,14 +6,20 @@ require 'json'
6
6
  require 'rack/utils'
7
7
 
8
8
  require_relative '../endpoint'
9
+ require_relative '../../core/redacted_inspect'
9
10
 
10
11
  class Otto
11
12
  module MCP
12
13
  module Auth
13
14
  # Token-based authentication for MCP protocol endpoints
14
15
  class TokenAuth
16
+ include Otto::Core::RedactedInspect
17
+
15
18
  def initialize(tokens)
16
- @tokens = Array(tokens).to_set
19
+ # A frozen SecretSet of frozen SecretStrings. Otto::Core::Freezable
20
+ # only shallow-freezes a TokenAuth, and nothing here mutates the
21
+ # tokens after construction, so they are frozen now.
22
+ @tokens = Otto::Core::RedactedInspect.secret(Array(tokens).to_set).freeze
17
23
  end
18
24
 
19
25
  def authenticate(env)
@@ -25,6 +31,11 @@ class Otto
25
31
 
26
32
  private
27
33
 
34
+ # #inspect shows the tokens as [REDACTED] with their count.
35
+ def redacted_inspect_value(ivar, value)
36
+ ivar == :@tokens ? redacted_placeholder(value) : super
37
+ end
38
+
28
39
  def valid_token?(candidate)
29
40
  # Constant-time membership: compare against every configured token without
30
41
  # short-circuiting on the first match, so neither match position nor
@@ -76,7 +76,7 @@ class Otto
76
76
  when 'resources/list'
77
77
  handle_resources_list(data)
78
78
  when 'resources/read'
79
- handle_resources_read(data)
79
+ handle_resources_read(data, env)
80
80
  when 'tools/list'
81
81
  handle_tools_list(data)
82
82
  when 'tools/call'
@@ -119,14 +119,14 @@ class Otto
119
119
  success_response(data['id'], { resources: resources })
120
120
  end
121
121
 
122
- def handle_resources_read(data)
122
+ def handle_resources_read(data, env)
123
123
  params = data['params'] || {}
124
124
  uri = params['uri']
125
125
 
126
126
  return error_response(data['id'], -32_602, 'Invalid params', 'Missing uri parameter') unless uri
127
127
 
128
128
  begin
129
- resource = @registry.read_resource(uri)
129
+ resource = @registry.read_resource(uri, env)
130
130
  rescue StandardError => e
131
131
  # Detail stays in the log: handler exceptions (Errno::*, constant
132
132
  # resolution) can carry absolute paths and internals.
@@ -9,6 +9,28 @@ class Otto
9
9
  module MCP
10
10
  # Registry for managing MCP resources and tools
11
11
  class Registry
12
+ POSITIONAL_PARAMETER_TYPES = %i[req opt rest].freeze
13
+
14
+ # Arguments to call a resource handler with: the Rack env of the MCP
15
+ # request when the handler takes a positional argument, nothing when it
16
+ # takes none, so zero-argument handlers keep working. Reflects on
17
+ # #parameters rather than #arity: +->(env = nil) {}+ has arity -1.
18
+ #
19
+ # @param callable [Proc, Method, #call] the handler, or the Method it calls
20
+ # @param env [Hash, nil] Rack env of the MCP request
21
+ # @param label [String] names the handler in the error message
22
+ # @return [Array] +[]+ or +[env]+
23
+ # @raise [ArgumentError] if the handler requires more than one positional
24
+ # argument or any keyword argument
25
+ def self.resource_handler_args(callable, env, label)
26
+ callable = callable.method(:call) unless callable.is_a?(Proc) || callable.is_a?(Method)
27
+ params = callable.parameters
28
+ unusable = params.count { |(type, _)| type == :req } > 1 || params.any? { |(type, _)| type == :keyreq }
29
+ raise ArgumentError, "#{label} must take no arguments or one (the Rack env)" if unusable
30
+
31
+ params.any? { |(type, _)| POSITIONAL_PARAMETER_TYPES.include?(type) } ? [env] : []
32
+ end
33
+
12
34
  def initialize
13
35
  @resources = {}
14
36
  @tools = {}
@@ -54,7 +76,10 @@ class Otto
54
76
  end
55
77
  end
56
78
 
57
- def read_resource(uri)
79
+ # @param uri [String] resource URI
80
+ # @param env [Hash, nil] Rack env of the MCP request, passed to a handler
81
+ # that takes one argument (see .resource_handler_args)
82
+ def read_resource(uri, env = nil)
58
83
  resource = @resources[uri]
59
84
  return nil unless resource
60
85
 
@@ -62,7 +87,8 @@ class Otto
62
87
  # (-32603/500), not a missing resource (-32001/404). Returning nil
63
88
  # here previously made the two indistinguishable to the protocol,
64
89
  # which owns the logging (Protocol#handle_resources_read).
65
- content = resource[:handler].call
90
+ handler = resource[:handler]
91
+ content = handler.call(*self.class.resource_handler_args(handler, env, "Resource handler for #{uri}"))
66
92
  {
67
93
  contents: [{
68
94
  uri: uri,
@@ -27,7 +27,7 @@ class Otto
27
27
  type: :mcp_resource,
28
28
  resource_uri: resource_uri,
29
29
  handler: handler_definition,
30
- options: extract_options_from_handler(handler_definition),
30
+ options: extract_options_from_handler(handler_definition, "MCP route #{resource_uri.inspect}"),
31
31
  }
32
32
  end
33
33
 
@@ -50,7 +50,7 @@ class Otto
50
50
  type: :mcp_tool,
51
51
  tool_name: tool_name,
52
52
  handler: handler_definition,
53
- options: extract_options_from_handler(handler_definition),
53
+ options: extract_options_from_handler(handler_definition, "TOOL route #{tool_name.inspect}"),
54
54
  }
55
55
  end
56
56
 
@@ -62,19 +62,31 @@ class Otto
62
62
  definition.start_with?('TOOL ')
63
63
  end
64
64
 
65
- def self.extract_options_from_handler(handler_definition)
65
+ def self.extract_options_from_handler(handler_definition, route_label = "handler #{handler_definition.inspect}")
66
66
  parts = handler_definition.split(/\s+/)
67
67
  options = {}
68
68
 
69
- # First part is the handler class.method. Delegate token parsing to
70
- # Otto::RouteDefinition so a bare/empty auth|role|csrf token here
71
- # fails fast exactly like it does for normal routes (issue #191
72
- # MCP/TOOL follow-up), instead of silently registering the route
73
- # without its intended protection.
69
+ # First part is the handler class.method. The MCP server registers
70
+ # resources and tools without running the auth, role or CSRF checks
71
+ # that normal routes get, so an auth|role|csrf token here (in any
72
+ # form or case) fails the load instead of registering the route as
73
+ # if it were protected. Other tokens are parsed by
74
+ # Otto::RouteDefinition exactly as for normal routes and returned in
75
+ # :options, but Otto::MCP::Server reads only the resource URI or tool
76
+ # name and the handler, so each one is logged as not applied.
74
77
  parts[1..]&.each do |part|
78
+ if Otto::RouteDefinition::SECURITY_GATING_OPTIONS.include?(part.split('=', 2).first.to_s.downcase)
79
+ raise Otto::RouteDefinitionError,
80
+ "#{route_label} sets #{part.inspect}, but auth, role and csrf options are not " \
81
+ 'enforced on MCP or TOOL routes. Remove the option and use mcp_auth_tokens ' \
82
+ 'to require a token for the MCP endpoint.'
83
+ end
84
+
75
85
  pair = Otto::RouteDefinition.parse_option_token(part, "handler #{handler_definition.inspect}")
76
86
  if pair
77
87
  options[pair[0]] = pair[1]
88
+ Otto.structured_log(:warn, 'MCP/tool route option not applied',
89
+ { option: part, route: route_label })
78
90
  else
79
91
  Otto.structured_log(:warn, 'Malformed MCP/tool route option ignored',
80
92
  { option: part, handler: handler_definition })