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
@@ -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)
@@ -105,26 +108,18 @@ class Otto
105
108
  # symlink-free root (issue #257). A missing root leaves @static_route
106
109
  # nil and the request falls through to normal routing (404), rather
107
110
  # than raising at construction.
108
- @static_route ||= build_static_route
109
- path_info = Rack::Utils.unescape(env['PATH_INFO'])
110
- path_info = '/' if path_info.to_s.empty?
111
-
112
- begin
113
- # Shared with Otto::CaddyTLS::LocalhostGuard so the guard and the
114
- # router cannot normalize a path differently (which would be a guard
115
- # bypass). See Otto::Utils.normalize_path.
116
- path_info_clean = Otto::Utils.normalize_path(env['PATH_INFO'])
117
- rescue ArgumentError => e
118
- # Log the error but don't expose details
119
- Otto.logger.error '[Otto.handle_request] Path encoding error'
120
- Otto.logger.debug "[Otto.handle_request] Error details: #{e.message}" if Otto.debug
121
- # Set a default value or use the original path_info
122
- path_info_clean = path_info
123
- end
111
+ @static_route ||= build_static_route
124
112
 
125
- http_verb = env['REQUEST_METHOD'].upcase.to_sym
126
- literal_routes = routes_literal[http_verb] || {}
127
- literal_routes.merge! routes_literal[:GET] if http_verb == :HEAD
113
+ # The one path every dispatch stage matches. It comes from the public
114
+ # Otto::Utils.routing_path so that guards running before the router
115
+ # (Otto::CaddyTLS::LocalhostGuard, an application's own middleware)
116
+ # judge exactly this value rather than re-deriving it; a guard that
117
+ # normalized differently would be a bypass. It never raises: a
118
+ # malformed escape (%zz) is kept as written and routed like any other
119
+ # path.
120
+ path_info_clean = Otto::Utils.routing_path(env)
121
+
122
+ http_verb = env['REQUEST_METHOD'].upcase.to_sym
128
123
 
129
124
  # Dynamic-route and static-file dispatch match against the SAME
130
125
  # normalized path the literal table and the LocalhostGuard use, so all
@@ -140,7 +135,10 @@ class Otto
140
135
  # for them. Literal lookup keeps '' — it already keys root that way.
141
136
  dispatch_path = path_info_clean.empty? ? '/' : path_info_clean
142
137
 
143
- 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
144
142
 
145
143
  # Dispatch precedence is fixed: literal routes, then explicit static
146
144
  # mounts (longest prefix first), then the implicit public directory,
@@ -148,8 +146,7 @@ class Otto
148
146
  # containment validation before it is served (issues #257, #260 and
149
147
  # #267). A mount or the public directory claims files, not paths: when
150
148
  # the file is absent the request falls through to the next stage.
151
- if literal_routes.has_key?(path_info_clean)
152
- route = literal_routes[path_info_clean]
149
+ if (route = find_literal_route(http_verb, path_info_clean))
153
150
  Otto.structured_log(:debug, 'Route matched',
154
151
  Otto::LoggingHelpers.request_context(env).merge(
155
152
  type: 'literal',
@@ -161,7 +158,7 @@ class Otto
161
158
  @route_matched_callbacks.each { |cb| cb.call(env, route.route_definition) }
162
159
  end
163
160
  route.call(env)
164
- elsif http_verb == :GET && (mounted = resolve_mounted_file(dispatch_path))
161
+ elsif static_verb && (mounted = resolve_mounted_file(dispatch_path))
165
162
  mount, static_file = mounted
166
163
  Otto.structured_log(:debug, 'Route matched',
167
164
  Otto::LoggingHelpers.request_context(env).merge(
@@ -173,7 +170,7 @@ class Otto
173
170
  Otto::LoggingHelpers.request_context(env).merge(type: 'static'))
174
171
  serve_static_file(env, static_file)
175
172
  else
176
- match_dynamic_route(env, dispatch_path, http_verb, literal_routes)
173
+ match_dynamic_route(env, dispatch_path, http_verb)
177
174
  end
178
175
  end
179
176
 
@@ -220,7 +217,9 @@ class Otto
220
217
  # Rack::Files unescapes PATH_INFO, so escape the canonical path to
221
218
  # survive the round trip (escape_path preserves '/').
222
219
  static_env['PATH_INFO'] = "/#{Rack::Utils.escape_path(static_file.relative)}"
223
- files.call(static_env)
220
+ status, headers, body = files.call(static_env)
221
+ headers['referrer-policy'] ||= @security_config.referrer_policy
222
+ [status, headers, body]
224
223
  end
225
224
 
226
225
  # Rack::Files rooted at the root +static_file+ was validated against.
@@ -248,15 +247,33 @@ class Otto
248
247
  root && Rack::Files.new(root)
249
248
  end
250
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
+
251
263
  # +dispatch_path+ is the normalized path from #handle_request (see the
252
- # +dispatch_path+ comment there): +Otto::Utils.normalize_path+ output with
264
+ # +dispatch_path+ comment there): +Otto::Utils.routing_path+ output with
253
265
  # root's empty string mapped back to '/' so the anchored route regexes can
254
- # match. It is deliberately NOT the raw +normalize_path+ value.
255
- def match_dynamic_route(env, dispatch_path, http_verb, literal_routes)
266
+ # match. It is deliberately NOT the raw +routing_path+ value.
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)
256
273
  extra_params = {}
257
274
  found_route = nil
258
275
  valid_routes = routes[http_verb] || []
259
- valid_routes.push(*routes[:GET]) if http_verb == :HEAD
276
+ valid_routes = valid_routes.chain(routes[:GET] || []) if http_verb == :HEAD
260
277
 
261
278
  valid_routes.each do |route|
262
279
  next unless (match = route.pattern.match(dispatch_path))
@@ -280,10 +297,11 @@ class Otto
280
297
  break
281
298
  end
282
299
 
283
- found_route ||= literal_routes['/404']
300
+ not_found_route = find_literal_route(http_verb, '/404')
301
+ found_route ||= not_found_route
284
302
  if found_route
285
303
  # Log 404 route usage if we fell back to it
286
- if found_route == literal_routes['/404']
304
+ if found_route == not_found_route
287
305
  Otto.structured_log(:info, 'Route not found',
288
306
  Otto::LoggingHelpers.request_context(env).merge(
289
307
  fallback_to: '404_route'
@@ -319,7 +337,7 @@ class Otto
319
337
  # @return [Array] a fresh Rack triple
320
338
  def not_found_response(env)
321
339
  fallback = @not_found
322
- return Otto::Static.not_found if fallback.nil?
340
+ return Otto::Static.not_found(@security_config) if fallback.nil?
323
341
 
324
342
  resolve_fallback_response(:not_found, fallback, env)
325
343
  end
@@ -347,8 +365,13 @@ class Otto
347
365
  @mcp_server.register_mcp_route(route_info)
348
366
  Otto.logger.debug "[MCP] Registered resource route: #{definition}" if Otto.debug
349
367
  rescue Otto::RouteDefinitionError
350
- # Same fail-fast contract as the normal route loader: a malformed
351
- # 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.
352
375
  raise
353
376
  rescue StandardError => e
354
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,7 +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.
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').
221
245
  IP_MATCH = 'otto.ip_match'
222
246
 
223
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 })
@@ -10,11 +10,14 @@ require_relative 'schema_validation'
10
10
  require_relative 'rate_limiting'
11
11
  require_relative 'options'
12
12
  require_relative '../security/constant_resolver'
13
+ require_relative '../core/redacted_inspect'
13
14
 
14
15
  class Otto
15
16
  module MCP
16
17
  # MCP server implementation providing Model Context Protocol endpoints
17
18
  class Server
19
+ include Otto::Core::RedactedInspect
20
+
18
21
  attr_reader :protocol, :otto_instance
19
22
 
20
23
  # Normalize raw options into the canonical MCP option hash.
@@ -72,7 +75,7 @@ class Otto
72
75
 
73
76
  @enabled = true
74
77
  @http_endpoint = options[:http_endpoint]
75
- @auth_tokens = options[:auth_tokens]
78
+ @auth_tokens = Otto::Core::RedactedInspect.secret(options[:auth_tokens])
76
79
  @enable_validation = options[:enable_validation]
77
80
  @enable_rate_limiting = options[:enable_rate_limiting]
78
81
  @allow_unauthenticated = options[:allow_unauthenticated]
@@ -105,6 +108,11 @@ class Otto
105
108
 
106
109
  private
107
110
 
111
+ # #inspect shows the bearer tokens as [REDACTED] with their count.
112
+ def redacted_inspect_value(ivar, value)
113
+ ivar == :@auth_tokens ? redacted_placeholder(value) : super
114
+ end
115
+
108
116
  # Publish the per-minute limits under the keys RateLimitMiddleware /
109
117
  # RateLimiter.configure_rack_attack! already read, via Otto's sanctioned
110
118
  # rate-limiting configuration entry point. Before this, the values passed
@@ -222,15 +230,15 @@ class Otto
222
230
  klass_name = klass_method[0..-2].join('::')
223
231
  method_name = klass_method.last
224
232
 
225
- # Create resource handler
226
- handler = lambda do
233
+ # Create resource handler. It receives the Rack env of the MCP request
234
+ # from Registry#read_resource and passes it on when the class method
235
+ # takes one argument, so a resource can check permissions per request.
236
+ handler = lambda do |env|
227
237
  klass = Otto::Security::ConstantResolver.safe_const_get(klass_name)
228
- method = klass.method(method_name)
229
- if method.arity != 0
230
- raise ArgumentError, "Handler #{klass_name}.#{method_name} must be a zero-arity method for resource #{uri}"
231
- end
232
-
233
- klass.public_send(method_name)
238
+ args = Otto::MCP::Registry.resource_handler_args(
239
+ klass.method(method_name), env, "Handler #{klass_name}.#{method_name} for resource #{uri}"
240
+ )
241
+ klass.public_send(method_name, *args)
234
242
  rescue StandardError => e
235
243
  Otto.logger.error "[MCP] Resource handler error for #{uri}: #{e.message}"
236
244
  raise
@@ -9,6 +9,7 @@ require 'digest'
9
9
  require 'concurrent'
10
10
 
11
11
  require_relative '../core/freezable'
12
+ require_relative '../core/redacted_inspect'
12
13
  require_relative '../optional_dependency'
13
14
 
14
15
  class Otto
@@ -31,6 +32,7 @@ class Otto
31
32
  # modules would hide the symmetry that makes them reviewable.
32
33
  class Config
33
34
  include Otto::Core::Freezable
35
+ include Otto::Core::RedactedInspect
34
36
 
35
37
  MAXMIND_DB_REQUIREMENT = '~> 1.2'
36
38
 
@@ -50,10 +52,17 @@ class Otto
50
52
  # Note the axis this controls: what PERSISTS observably (env keys, logs,
51
53
  # fingerprints). Precise ephemeral matching against the unmasked IP does
52
54
  # not require :audit — see EnvKeys::IP_MATCH, available in every profile.
55
+ #
56
+ # This table is the only list of knobs a profile governs: #profile=
57
+ # assigns whatever keys a preset carries, through each knob's writer so
58
+ # any check or normalization the writer does still runs. Every profile
59
+ # names the same keys, so applying one yields the same state whatever
60
+ # preceded it, and each key names a Config attribute with a writer and
61
+ # a public reader.
53
62
  PROFILES = {
54
63
  anonymous: { disabled: false, mask_private_ips: true }.freeze,
55
64
  masked: { disabled: false, mask_private_ips: false }.freeze,
56
- audit: { disabled: true }.freeze,
65
+ audit: { disabled: true, mask_private_ips: false }.freeze,
57
66
  }.freeze
58
67
 
59
68
  attr_accessor :octet_precision, :hash_rotation_period, :geo_enabled, :mask_private_ips,
@@ -181,7 +190,10 @@ class Otto
181
190
  raise ArgumentError, "correlation_secret must be a String or nil, got: #{value.class}"
182
191
  end
183
192
 
184
- @correlation_secret = value
193
+ # A frozen SecretString copy: the reader cannot hand out a String
194
+ # whose FrozenError would print the secret, and the caller's String is
195
+ # not frozen by deep_freeze!.
196
+ @correlation_secret = Otto::Core::RedactedInspect.secret(value)
185
197
  end
186
198
 
187
199
  # Set the trusted, app-configured geo header.
@@ -396,23 +408,18 @@ class Otto
396
408
 
397
409
  # Apply a named privacy profile's presets to this config.
398
410
  #
399
- # Sets only the knobs the profile names (see {PROFILES}); other settings
411
+ # Assigns every knob the preset names (see {PROFILES}), so the result
412
+ # never depends on the profile applied before it: :anonymous -> :audit
413
+ # -> enable! lands on :masked, exactly as
414
+ # Config.new(profile: :audit).enable! does. Other settings
400
415
  # (octet_precision, geo, correlation_secret, ...) are untouched.
401
416
  #
402
- # Presets are applied, not reset: a knob a profile does not name keeps its
403
- # previous value. Switching :anonymous -> :audit therefore leaves
404
- # mask_private_ips true, because :audit names only `disabled`. That is
405
- # inert rather than wrong — `disabled` short-circuits privacy_enabled?
406
- # before mask_private_ips is ever read, and #profile below tests @disabled
407
- # first, so the derived label stays accurate. Switching on to :masked
408
- # re-sets both knobs explicitly. Only surprising if you read the raw ivars.
409
- #
410
417
  # @param profile [Symbol, String] :anonymous, :masked, or :audit
411
418
  # @raise [ArgumentError] for an unknown profile name
412
419
  def profile=(profile)
413
- presets = self.class.profile_presets(profile)
414
- @disabled = presets[:disabled] if presets.key?(:disabled)
415
- @mask_private_ips = presets[:mask_private_ips] if presets.key?(:mask_private_ips)
420
+ self.class.profile_presets(profile).each do |knob, value|
421
+ send(:"#{knob}=", value)
422
+ end
416
423
  end
417
424
 
418
425
  # The profile the current knob state corresponds to.
@@ -517,6 +524,16 @@ class Otto
517
524
 
518
525
  private
519
526
 
527
+ # #inspect (and so a native FrozenError message) shows the correlation
528
+ # secret as [REDACTED]. See Otto::Core::RedactedInspect.
529
+ def redacted_inspect_value(ivar, value)
530
+ ivar == :@correlation_secret ? redacted_placeholder(value) : super
531
+ end
532
+
533
+ # Profile-governed, so #profile= can assign it through a writer like the
534
+ # other knobs. Public callers use #disable! and #enable!.
535
+ attr_writer :disabled
536
+
520
537
  # Normalize a database-path option to a non-empty String or nil. Shared by
521
538
  # the geo, ASN and anonymizer paths — the rule is identical for all three.
522
539
  #