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,732 @@
1
+ # Otto audit report
2
+
3
+ **Stamp:** 2026-09-28 @ 359a25f (main, v2.12.0) · **Repository:** `delano/otto`
4
+
5
+ **Headline:** The audit found 33 verified findings covering 27 distinct issues. The most serious: client IP resolution trusts the leftmost, spoofable X-Forwarded-For entry, and five separate bugs cause 500s or rejected requests once the app runs outside the test suite.
6
+
7
+ ## Status on main
8
+
9
+ Rechecked on 2026-10-06 at `4e2758c`. The rest of this report describes
10
+ `359a25f` and has not been edited, so its line numbers refer to that commit.
11
+
12
+ **Fixed.** The critical finding and all nine high findings are fixed on main:
13
+ S1 and C1 by [#292](https://github.com/delano/otto/pull/292),
14
+ S2 by [#293](https://github.com/delano/otto/pull/293),
15
+ C2 by [#294](https://github.com/delano/otto/pull/294),
16
+ C5 by [#295](https://github.com/delano/otto/pull/295),
17
+ D1 by [#296](https://github.com/delano/otto/pull/296),
18
+ C3 by [#297](https://github.com/delano/otto/pull/297),
19
+ C4 by [#298](https://github.com/delano/otto/pull/298),
20
+ and C6 and T1 by [#299](https://github.com/delano/otto/pull/299).
21
+ The regression specs those pull requests added pass at `4e2758c`, where the
22
+ full suite reports 3367 examples and 0 failures.
23
+
24
+ **Still open.** All 23 medium and low findings. At `4e2758c` the line each one
25
+ cites still reads as quoted, and the spec gaps that T2 to T6 describe are still
26
+ there. C7, C8, C9, C10, S3 (with C11), T4, D5 and D6 were reproduced again
27
+ outside RSpec, where `Otto#call` freezes the configuration. The others were
28
+ checked by reading the code.
29
+
30
+ | Finding | Severity | Location at `4e2758c` |
31
+ | --- | --- | --- |
32
+ | S3, C11 | Low | `lib/otto/security/csrf_validation.rb:40` |
33
+ | S4 | Low | `lib/otto/mcp/auth/token.rb:45` (was 34) |
34
+ | C7, T5 | Medium, Low | `lib/otto/utils.rb:170` (was 133) |
35
+ | C8 | Medium | `lib/otto/security/middleware/csrf_middleware.rb:67` |
36
+ | C9, T2 | Medium | `lib/otto/mcp/protocol.rb:70` and `lib/otto/mcp/schema_validation.rb:101` |
37
+ | C10, T3 | Medium | `lib/otto/route_handlers/logic_class.rb:128` |
38
+ | T4 | Medium | `lib/otto/security/middleware/validation_middleware.rb:45` |
39
+ | T6 | Low | `lib/otto/security/authentication/route_auth_wrapper/role_authorization.rb:94` |
40
+ | D2 | Medium | `lib/otto/security/middleware/validation_middleware.rb:100` |
41
+ | D3 | Medium | `lib/otto/core/configuration.rb:274` |
42
+ | D4 | Medium | `lib/otto/route.rb:168` |
43
+ | D5 | Low | `lib/otto.rb:467` (was 439) |
44
+ | D6 | Low | `lib/otto/security/config.rb:458` (was 402) |
45
+ | D7 | Low | `lib/otto/route_handlers/base.rb:163` |
46
+ | D8 | Low | `lib/otto/security/csrf_validation.rb:54` |
47
+ | D9 | Low | `lib/otto/mcp/schema_validation.rb:45` |
48
+ | D10 | Low | `lib/otto/helpers/validation.rb:80` |
49
+ | D11 | Low | `lib/otto/helpers/base.rb:7` |
50
+ | P1 | Low | `.github/workflows/release-gem.yml:125` |
51
+
52
+ **C9 has a second raise site.** MCP schema validation is on by default
53
+ (`enable_validation: true` in `lib/otto/mcp/options.rb:73`). On that path,
54
+ `SchemaValidationMiddleware#call` runs before `Protocol#handle_request`. It
55
+ answers `null` and non-object `params` with -32600 and HTTP 400, but the bodies
56
+ `[]`, `123` and `true` still return 500, because its `ValidationError` rescue
57
+ calls `data&.dig('id')` (`lib/otto/mcp/schema_validation.rb:101`), which raises
58
+ for an Array, an Integer or `true`. With `enable_validation: false`, every C9
59
+ input returns 500 from `Protocol#handle_request`, as the finding describes.
60
+ `schema_validation.rb` has not changed since `359a25f`, so this was already
61
+ true when the report was written. A fix for C9 needs both sites.
62
+
63
+ ## Severity summary
64
+
65
+ | Dimension | Critical | High | Medium | Low | Total |
66
+ |-----------------|:--------:|:----:|:------:|:---:|:-----:|
67
+ | Security | 0 | 2 | 0 | 2 | 4 |
68
+ | Correctness | 1 | 5 | 4 | 1 | 11 |
69
+ | Test coverage | 0 | 1 | 3 | 2 | 6 |
70
+ | Dead code | 0 | 1 | 3 | 7 | 11 |
71
+ | Dependency risk | 0 | 0 | 0 | 1 | 1 |
72
+ | **Total** | **1** | **9** | **10** | **13** | **33** |
73
+
74
+ Verifier consensus was 3/3 on 30 findings and 2/3 on three: S4, T1 and T6.
75
+
76
+ ### Issues reported under two dimensions
77
+
78
+ Six issues were filed independently by two auditors. The full write-up appears at the first ID listed. The second entry adds only what is new.
79
+
80
+ | Issue | IDs | Severities |
81
+ |---|---|---|
82
+ | Leftmost X-Forwarded-For entry resolved as client IP | S1, C1 | High / **Critical** |
83
+ | Non-String `_csrf_token` param causes a 500 | S3, C11 | Low / Low |
84
+ | `csrf_secret=` accepts `''` and `nil` | C6, T1 | High / High |
85
+ | Non-object JSON-RPC payloads crash the MCP protocol handler | C9, T2 | Medium / Medium |
86
+ | Logic-class JSON parsing uses non-SPEC `size` / `rewind` | C10, T3 | Medium / Medium |
87
+ | `normalize_path` decodes `+` as a space | C7, T5 | Medium / Low |
88
+
89
+ The two auditors rated the X-Forwarded-For issue differently. Read it as **critical**, because it defeats the IP-based access check that the privacy guide recommends (see S1).
90
+
91
+ ### Failures that only appear outside the test suite
92
+
93
+ `Otto#call` skips the lazy configuration freeze when RSpec is defined. Three high-severity bugs therefore pass CI and fail on the first real request:
94
+
95
+ - S2 (MCP bearer tokens)
96
+ - C2 (HEAD routes)
97
+ - C3 (generated CSRF secret)
98
+
99
+ Each one needs a regression spec that freezes the configuration explicitly.
100
+
101
+ ---
102
+
103
+ ## Security
104
+
105
+ ### S1 · High · CIDR filter mode takes the leftmost X-Forwarded-For entry as the client IP
106
+
107
+ `lib/otto/utils.rb:253` · ip-spoofing / broken-trust-boundary · **Consensus 3/3** · also C1
108
+
109
+ **Why it matters.**
110
+
111
+ *The mechanism.*
112
+ - `Otto::Utils.resolve_client_ip` is the single resolver behind `IPPrivacyMiddleware` and `Otto::Request#client_ipaddress`.
113
+ - In filter mode it concatenates `HTTP_X_FORWARDED_FOR`, `HTTP_X_REAL_IP` and `HTTP_X_CLIENT_IP`, then returns the first entry that is not a trusted proxy (lines 249-259).
114
+ - Common reverse proxies append the observed peer to the inbound header instead of replacing it. This includes nginx `$proxy_add_x_forwarded_for`, ALB, Cloudflare and Caddy. So the leftmost entry is whatever the client sent.
115
+ - Depth mode in the same file already handles this; the comment at line 273 reads "a forged leftmost entry is never reached". `Rack::Request#ip` also takes the last untrusted entry. Filter mode does the opposite.
116
+
117
+ *Reproduced through the full stack.*
118
+ - Setup: `trusted_proxies: ['10.0.0.0/8']`, `REMOTE_ADDR=10.0.0.5`, `X-Forwarded-For: 1.2.3.4, 203.0.113.9`.
119
+ - Result: `env['otto.client_ip']` is `1.2.3.0`.
120
+ - `env['otto.ip_match'].call(['1.2.3.0/24'])` returns `true`, but the real peer's range `203.0.113.0/24` returns `false`.
121
+ - The same happens when nginx sets `X-Real-IP` correctly but passes the client's `X-Forwarded-For` through, because XFF is read first.
122
+
123
+ *Impact.*
124
+ - `docs/guides/privacy.md:147-148` points to `env['otto.ip_match']` "For precise access control without exposing the address to application code". That check can be bypassed.
125
+ - The following all key on an address the attacker chooses:
126
+ - `req.ip` and `otto.client_ip`, which feed rate-limit keys when Rack::Attack runs inside Otto, audit logs, and RouteAuthWrapper metadata
127
+ - `correlation_hash` and `hashed_ip`
128
+ - the geo lookup
129
+ - `Request#local?`
130
+ - The spec at `spec/otto/utils_spec.rb:454`, titled "walks the forwarded chain and returns the first non-proxy address", pins the current behavior.
131
+
132
+ **Suggested fix.**
133
+ 1. Walk the chain from the right:
134
+ - Build it per header instead of concatenating three headers, and reverse it.
135
+ - Skip entries where `security_config.trusted_proxy?` is true, and return the first untrusted one. This matches `resolve_client_ip_by_depth` and `Rack::Request#ip`.
136
+ - Fall back to `REMOTE_ADDR` when every entry is trusted.
137
+ 2. Read the single-valued `X-Real-IP` / `X-Client-IP` only when `X-Forwarded-For` is absent, or prefer them when the proxy sets them. Never treat them as extra chain positions.
138
+ 3. Update the spec at `utils_spec.rb:454` to assert the rightmost untrusted entry.
139
+ 4. Add a padding test that mirrors the depth-mode one: `9.9.9.9, 203.0.113.50` must resolve to `203.0.113.50`.
140
+ 5. State in `docs/guides/forwarded-authority.md` that proxies must append to the header, not pass it through.
141
+
142
+ ### S2 · High · `Config#deep_freeze!` is not idempotent, so MCP auth tokens make every request fail after the first
143
+
144
+ `lib/otto/security/config.rb:1216` · denial-of-service / security-feature regression · **Consensus 3/3**
145
+
146
+ **Why it matters.**
147
+
148
+ *The mechanism.*
149
+ - `Otto::Core::Freezable#deep_freeze!` returns early when the object is already frozen.
150
+ - `Otto::Security::Config#deep_freeze!` overrides it. It runs three validators before calling `super` (lines 1215-1218): `validate_referrer_policy!`, `validate_trusted_proxy_config!` and `validate_csrf_secret_config!`.
151
+ - `validate_trusted_proxy_config!` ends in `commit_rack_forwarding_family!`, whose first statement is `ensure_not_frozen!` (line 722).
152
+ - `Otto#freeze_configuration!` freezes `@security_config` first and then deep-freezes the middleware stack, which walks each entry's args.
153
+ - `Otto::MCP::Server` passes the security config as a middleware argument in two places:
154
+ - `TokenMiddleware` (`lib/otto/mcp/server.rb:169`)
155
+ - `RateLimitMiddleware` (`:176`, on by default)
156
+ - So the already-frozen Config is visited a second time, and it raises `FrozenError` ("Cannot modify frozen configuration").
157
+ - The raise happens in `Otto#call` outside the rescue that feeds `handle_error`. `@configuration_frozen` is never set, so every later request retries the freeze and fails the same way.
158
+
159
+ *Reproduced outside RSpec.*
160
+ - This call raises: `Otto.new(routes, mcp_enabled: true, mcp_http: true, mcp_auth_tokens: ['tok'], mcp_rate_limiting: false, mcp_validation: false).call(env)`.
161
+ - The same app with `mcp_allow_unauthenticated: true` returns 200.
162
+ - The rate-limiting path was confirmed by reading only, because rack-attack is not installed here.
163
+
164
+ *Why tests miss it.* `Otto#call` skips the lazy freeze under RSpec, and the MCP specs use `Otto.unfreeze_for_testing`.
165
+
166
+ *Impact.* The token setup shown in `docs/guides/mcp.md:52` (`mcp_auth_tokens: [ENV.fetch('MCP_TOKEN')]`) takes down the whole application in production. That pushes operators toward `allow_unauthenticated: true`.
167
+
168
+ **Suggested fix.**
169
+ 1. Add `return self if frozen?` as the first line of `Config#deep_freeze!`, matching `Freezable`.
170
+ 2. Make `commit_rack_forwarding_family!` tolerate re-entry: return early when this config already committed the family, instead of calling `ensure_not_frozen!` unconditionally.
171
+ 3. Preferably, stop passing the Config as a middleware argument. Add `TokenMiddleware` and the MCP `RateLimitMiddleware` to `MiddlewareStack#middleware_needs_config?` so `#wrap` injects the config.
172
+ 4. Add a regression spec: build an Otto with `mcp_auth_tokens`, call `freeze_configuration!` explicitly, then serve a request through `#call`.
173
+
174
+ ### S3 · Low · A non-String `_csrf_token` parameter turns a CSRF rejection into a 500
175
+
176
+ `lib/otto/security/csrf_validation.rb:40` · input-validation / error-handling · **Consensus 3/3** · also C11
177
+
178
+ **Why it matters.**
179
+ - `valid_csrf_token?` reads the token from `request.params` and calls `token.strip`.
180
+ - Rack parses `_csrf_token[]=abc` into an Array and `_csrf_token[a]=b` into a Hash, so `.strip` raises `NoMethodError`. The error reaches `handle_error` as unhandled.
181
+ - Reproduced: `POST /form?_csrf_token[]=abc` with CSRF enabled returns 500 and logs "Unhandled error in request" with a backtrace. A String token gets the intended 403.
182
+ - `Config#verify_csrf_token` makes the same assumption (`.split`).
183
+ - There is no bypass. But any client can produce ERROR-level logs with backtraces that count as server faults against error budgets and alerting.
184
+
185
+ **Suggested fix.**
186
+ - In `valid_csrf_token?`: `return false unless token.is_a?(String) && !token.strip.empty?`
187
+ - At the top of `Config#verify_csrf_token`: `return false unless token.is_a?(String)`
188
+ - Add specs for Array and Hash token params that expect 403.
189
+
190
+ ### S4 · Low · MCP bearer-token comparison leaks configured token lengths through timing
191
+
192
+ `lib/otto/mcp/auth/token.rb:34` · timing-side-channel · **Consensus 2/3**
193
+
194
+ **Why it matters.**
195
+ - `TokenAuth#valid_token?` compares the raw candidate against each configured token with `Rack::Utils.secure_compare`. That function returns immediately when the byte sizes differ.
196
+ - Response timing therefore shows whether the presented token's length matches a configured token, which narrows a brute-force search.
197
+ - The sibling `APIKeyStrategy` (`lib/otto/security/authentication/strategies/api_key_strategy.rb:192-198`) reduces both sides to SHA-256 digests to avoid exactly this. The two authenticators are inconsistent.
198
+
199
+ **Suggested fix.**
200
+ - Precompute `Digest::SHA256.hexdigest` for each configured token at construction.
201
+ - Compare with `Rack::Utils.secure_compare(token_digest, Digest::SHA256.hexdigest(candidate))`.
202
+ - Reject non-String configured tokens at construction, so a YAML integer cannot raise `NoMethodError` at request time.
203
+
204
+ ---
205
+
206
+ ## Correctness
207
+
208
+ ### C1 · Critical · Client-IP resolution returns the leftmost, client-controlled X-Forwarded-For entry
209
+
210
+ `lib/otto/utils.rb:253` · ip-spoofing · **Consensus 3/3** · same issue as S1; the mechanism and fix are there
211
+
212
+ **What this finding adds.**
213
+ - A second reproduction: `REMOTE_ADDR=10.0.0.1` (with `10.0.0.0/8` trusted) and `X-Forwarded-For: 203.0.113.99, 198.51.100.7`.
214
+ - Otto resolves `203.0.113.99`. `Rack::Request#ip` with the same trust settings resolves `198.51.100.7`, because Rack walks the list with `reverse_each`.
215
+ - `env['otto.ip_match'].call(['203.0.113.99/32'])` returns `true`. An attacker passes an IP allowlist by naming an allowlisted address in XFF.
216
+ - `X-Real-IP` and `X-Client-IP` are appended to the chain. When XFF is absent and the proxy does not overwrite those headers, a client-supplied `X-Real-IP` wins.
217
+ - The existing spec at `spec/otto/utils_spec.rb:454` only uses a chain whose other entries are all trusted, so it cannot tell the two directions apart.
218
+
219
+ **Suggested fix.**
220
+ - Use `forwarded_ips.reverse_each { |c| ip = normalize_ip(c.strip); next unless ip; return ip unless security_config.trusted_proxy?(ip) }`, then fall back to `remote_addr`.
221
+ - Consult `X-Real-IP` / `X-Client-IP` only when XFF is absent.
222
+ - Add a spec with two untrusted entries (`spoofed, real`) that asserts the rightmost one wins. Mirror the depth-mode forged-leftmost test for filter mode.
223
+
224
+ ### C2 · High · HEAD dispatch mutates the shared route tables
225
+
226
+ `lib/otto/core/router.rb:121` · correctness · **Consensus 3/3**
227
+
228
+ **Why it matters.**
229
+
230
+ *The mechanism.*
231
+ - Two lines mutate the registered tables whenever a HEAD route exists:
232
+ - `literal_routes.merge! routes_literal[:GET] if http_verb == :HEAD` (line 121) changes `routes_literal[:HEAD]`.
233
+ - `valid_routes.push(*routes[:GET]) if http_verb == :HEAD` (line 255) changes `routes[:HEAD]`.
234
+ - The `|| {}` / `|| []` fallback allocates a fresh container only when no HEAD routes exist.
235
+
236
+ *When the configuration is frozen* (the first request outside RSpec; `configuration.rb:309-310`):
237
+ - Every HEAD request raises `FrozenError` and returns 500.
238
+ - Reproduced with a routes file containing `HEAD /health`: after the first request, HEAD requests to `/health`, `/show/1` and `/other` all return 500.
239
+
240
+ *When it is not frozen* (under RSpec):
241
+ - `merge!` lets the GET entry win, so `HEAD /health` runs the GET handler instead of the declared HEAD handler.
242
+ - `@routes[:HEAD]` grew from 2 to 8 entries after three HEAD requests. That is unbounded growth of shared state, written from request threads without synchronization.
243
+
244
+ **Suggested fix.**
245
+ - Never mutate the registered tables at dispatch time. Build per-request views where the verb-specific entry wins:
246
+ - `literal_routes = http_verb == :HEAD ? (routes_literal[:GET] || {}).merge(routes_literal[:HEAD] || {}) : (routes_literal[http_verb] || {})`
247
+ - `valid_routes = http_verb == :HEAD ? (routes[:HEAD] || []) + (routes[:GET] || []) : (routes[http_verb] || [])`
248
+ - Better: compute the merged HEAD tables once, at load or freeze time.
249
+ - Add a spec that freezes the configuration, defines a HEAD route and issues HEAD requests.
250
+
251
+ ### C3 · High · `warn_generated_csrf_secret` writes to the frozen config, so every HTML response returns 500
252
+
253
+ `lib/otto/security/config.rb:1349` · correctness · **Consensus 3/3**
254
+
255
+ **Why it matters.**
256
+ - `Config#deep_freeze!` freezes the instance on the first request outside RSpec.
257
+ - `generate_csrf_token` (line 795) then calls `warn_generated_csrf_secret`, which sets `@csrf_secret_warning_emitted = true` on the frozen object and raises `FrozenError`.
258
+ - Reproduced with `Otto.new` + `enable_csrf_protection!` and no `OTTO_CSRF_SECRET` or `csrf_secret=`, with `RACK_ENV` unset, `development` or `staging`:
259
+ - Every GET of an HTML page returns 500, starting with the first request.
260
+ - The failure path is `CSRFMiddleware#inject_csrf_token` → `generate_csrf_token` → `FrozenError`.
261
+ - The `production_environment?` guard does not help, because the failure is in the non-production branch.
262
+ - The similar `@csp_script_src_override_warned = true` is safe only because its callers are setters guarded by `ensure_not_frozen!`.
263
+
264
+ **Suggested fix.** Keep the once-only flag off the frozen instance. Any of these works:
265
+ - Emit the warning once at enable or freeze time, for example in `validate_csrf_secret_config!` or `enable_csrf_protection!`.
266
+ - Store the flag in a class-level `Concurrent::Map` keyed by `object_id`. `Otto::Privacy::Config` uses this pattern for rotation keys.
267
+ - Use a `Concurrent::AtomicBoolean` created in `initialize`.
268
+
269
+ Add a spec that calls `deep_freeze!` and then `generate_csrf_token` with a generated secret.
270
+
271
+ ### C4 · High · `handle_auth_success` replaces the real Rack session with `{}` on noauth and role/permission routes
272
+
273
+ `lib/otto/security/authentication/route_auth_wrapper.rb:214` · correctness · **Consensus 3/3**
274
+
275
+ **Why it matters.**
276
+ - Line 214 is `env['rack.session'] = result.session if result.is_a?(StrategyResult) && result.session`. It treats any truthy session as authoritative.
277
+ - Two constructors default to `session: {}`, which is truthy:
278
+ - `StrategyResult.anonymous` (`strategy_result.rb:115`)
279
+ - `AuthStrategy#success` (`auth_strategy.rb:30`)
280
+ - Three strategies never pass the real session:
281
+ - `NoAuthStrategy`
282
+ - `RoleStrategy` (`role_strategy.rb:33`, `:41`)
283
+ - `PermissionStrategy` (`permission_strategy.rb:33`)
284
+ - So on these routes the handler gets a bare Hash instead of the session middleware's `SessionHash`:
285
+ - `auth=noauth`
286
+ - an `auth=session,noauth` fall-through
287
+ - role and permission routes
288
+ - Reproduced with rack-session 2.1.2 (`Rack::Session::Pool`):
289
+ - `/plain` works.
290
+ - `/noauth` and `/either` raise `NoMethodError: undefined method 'options' for an instance of Hash` from rack-session's `commit_session`.
291
+ - That error happens above Otto, so `handle_error` never sees it, and every session write the handler made is lost.
292
+
293
+ **Suggested fix.**
294
+ - Sync the session only when the strategy actually produced one, for example `env['rack.session'] = session if session && !session.empty? && !env.key?('rack.session')`.
295
+ - Cleaner: never overwrite an existing `env['rack.session']`, and have `StrategyResult.anonymous` / `AuthStrategy#success` default `session:` to `env['rack.session']`.
296
+ - Add an integration spec with rack-session that covers `auth=noauth` and role-strategy routes.
297
+
298
+ ### C5 · High · CSRF session binding changes between GET and POST, so a new visitor's first form POST gets 403
299
+
300
+ `lib/otto/security/config.rb:1269` · correctness · **Consensus 3/3**
301
+
302
+ **Why it matters.**
303
+
304
+ *The mechanism.* `extract_existing_session_id` returns `session.id` first (line 1269) and checks `session[csrf_session_key]` only after that.
305
+
306
+ *The failing sequence for a new visitor.*
307
+ 1. On the GET, rack-session's `SessionHash#id` is nil because the session has not loaded yet.
308
+ 2. Otto generates a random hex id and stores it in `session['_csrf_session_id']`.
309
+ 3. That write loads the session and makes rack-session mint a real SID.
310
+ 4. The token is bound to the hex id.
311
+ 5. On the following POST the session cookie exists, so `session.id` returns the rack-session SID.
312
+ 6. The token is checked against a different binding and fails.
313
+
314
+ *Reproduced* with rack-session 2.1.2 for both `Rack::Session::Pool` and `Rack::Session::Cookie`:
315
+ - `GET /form` returns 200 and issues the token and the `_otto_session` cookie.
316
+ - `POST /submit` with that token and those cookies returns 403.
317
+
318
+ *Why it hides.* If the GET handler writes to the session first, the flow succeeds. Apps whose pages already touch the session never see the bug. It breaks the common login form that leaves the session untouched.
319
+
320
+ **Suggested fix.**
321
+ - Read `session[csrf_session_key]` before `session.id`. This also forces rack-session to load and assign its id.
322
+ - Always coerce `session.id.to_s`. rack-session returns a `SessionId` object. That is also why `ensure_session_cookie`'s `existing_cookie == session_id` never matches, so the cookie is set again on every response.
323
+ - Add an integration spec with rack-session: GET an HTML page without touching the session, then POST with the issued token.
324
+
325
+ ### C6 · High · `csrf_secret=` accepts `''` and `nil`, defeating the production guard; empty-key tokens are forgeable
326
+
327
+ `lib/otto/security/config.rb:780` · security · **Consensus 3/3** · also T1
328
+
329
+ **Why it matters.**
330
+ - The initializer treats a blank `OTTO_CSRF_SECRET` as generated: `@csrf_secret_generated = configured_secret.nil? || configured_secret.empty?` (line 439).
331
+ - The setter (lines 780-785) stores any value and sets `@csrf_secret_generated = false` without checking it.
332
+ - Common idioms pass `''`: `config.csrf_secret = ENV.fetch('OTTO_CSRF_SECRET', '')` or `ENV['OTTO_CSRF_SECRET'].to_s`.
333
+ - Reproduced with `RACK_ENV=production` and `csrf_secret = ''`:
334
+ - `generate_csrf_token` does not raise.
335
+ - A token forged as `"deadbeef:#{OpenSSL::HMAC.hexdigest('SHA256', '', 'sess1:deadbeef')}"` verifies as valid. Anyone can mint CSRF tokens.
336
+ - With `nil`, the failure is loud but in the wrong place: `sign_csrf_token` raises `TypeError` on every HTML response (500) instead of a configuration error at boot.
337
+
338
+ **Suggested fix.**
339
+ - In the setter, raise `ArgumentError` unless `secret.is_a?(String) && !secret.strip.empty?`. Alternatively, treat a blank value as generated, exactly as the initializer does.
340
+ - Consider a minimum length.
341
+ - Add specs for `csrf_secret = ''` and `csrf_secret = nil`.
342
+
343
+ ### C7 · Medium · `normalize_path` uses form decoding, so `+` becomes a space in every dispatch stage
344
+
345
+ `lib/otto/utils.rb:133` · correctness · **Consensus 3/3** · also T5
346
+
347
+ **Why it matters.**
348
+ - In Rack 3.2, `Rack::Utils.unescape` is `URI.decode_www_form_component`, which is the query and form decoder. The path decoder is `Rack::Utils.unescape_path`.
349
+ - Every dispatch stage sees `+` as a space: the literal table, the dynamic matcher, static mounts, the public dir, LocalhostGuard, the MCP endpoint and the CSP report path.
350
+ - Reproduced:
351
+ - `normalize_path('/a+b')` returns `"/a b"`.
352
+ - A literal route `GET /a+b` returns 404, while `/a%2Bb` matches. The literal table key at `router.rb:43` is the raw route path.
353
+ - The public file `c++.txt` returns 404 at `/c++.txt` but is served at `/c%2B%2B.txt`.
354
+ - A request for the non-existent `/a+b.txt` serves a different file, `a b.txt`.
355
+ - Browsers send `+` literally in paths, so every route or asset with a plus sign is affected.
356
+
357
+ **Suggested fix.**
358
+ - Use `Rack::Utils.unescape_path(raw)`. It raises the same ArgumentError family on malformed escapes, so the existing rescue stays valid.
359
+ - Normalize the literal-table keys with the same function at load time. `router.rb:43` currently only strips a trailing slash.
360
+ - Add specs for `+` in routes and in static file names.
361
+
362
+ ### C8 · Medium · CSRF token injection replaces the response body without closing the original
363
+
364
+ `lib/otto/security/middleware/csrf_middleware.rb:67` · resource-leak · **Consensus 3/3**
365
+
366
+ **Why it matters.**
367
+ - `inject_csrf_token` reads the downstream body with `body.join` (line 56) and returns `[status, headers, [body_content]]` (line 67). The original body object is dropped.
368
+ - Rack requires the server to call `close` on the body it receives. The server now sees only the new Array.
369
+ - So a downstream `Rack::BodyProxy` never runs its close block. Affected users include Rack::Lock, Rack::ETag, rack-timeout, ActiveRecord/Sequel connection release, and wrapped file bodies.
370
+ - Reproduced: an app returning `Rack::BodyProxy.new(['<html><head></head></html>']) { closed = true }` still has `closed == false` after the returned body is fully consumed and closed.
371
+ - Under Rack::Lock this leaves the mutex held.
372
+
373
+ **Suggested fix.**
374
+ - Close the original body before returning the new triple: `body.close if body.respond_to?(:close)`. Alternatively, return `Rack::BodyProxy.new([body_content]) { body.close if body.respond_to?(:close) }`.
375
+ - Iterate with `each` instead of relying on `join`, so non-Array bodies are handled the same way.
376
+
377
+ ### C9 · Medium · Non-object JSON-RPC payloads and params raise instead of returning -32600 / -32602
378
+
379
+ `lib/otto/mcp/protocol.rb:70` · error-handling · **Consensus 3/3** · also T2
380
+
381
+ **Why it matters.**
382
+ - `valid_jsonrpc_request?` correctly returns false for a non-Hash payload. But the failure branch at line 70 immediately evaluates `data['id']`:
383
+ - Array and Integer payloads raise `TypeError`.
384
+ - `nil` and `true` raise `NoMethodError`.
385
+ - `params` has the same problem at line 124 (`params['uri']`) and line 151 (`params['name']`) when it is an Array or Integer.
386
+ - These inputs all raise out of `Protocol#handle_request`:
387
+ - bodies `[]`, `null`, `123` and `true`
388
+ - a `resources/read` request with `"params":[1]` or `"params":5`
389
+ - Each becomes Otto's generic 500 with "Unhandled error in request" and a backtrace in the log. The class comment's error table (`protocol.rb:14-23`) maps -32600 and -32602 to HTTP 400.
390
+ - When no auth tokens are configured, an unauthenticated client can generate this log noise at will.
391
+
392
+ **Suggested fix.**
393
+ - Compute the id safely before the validity check: `id = data.is_a?(Hash) ? data['id'] : nil`.
394
+ - In `handle_resources_read` and `handle_tools_call`, check that `params` is a Hash or nil, and return -32602 "Invalid params" otherwise.
395
+ - Add specs for array and scalar top-level bodies and params.
396
+
397
+ ### C10 · Medium · Logic-class JSON parsing calls `rack.input#size` and `#rewind`, so JSON POSTs fail under Rack::Lint
398
+
399
+ `lib/otto/route_handlers/logic_class.rb:128` · compatibility · **Consensus 3/3** · also T3
400
+
401
+ **Why it matters.**
402
+ - `json_body?` calls `req.body&.size&.positive?` (line 128), and `parse_json_body` calls `req.body.rewind` (line 137).
403
+ - Rack 3 dropped the rewind requirement for `rack.input` and never required `#size`. Rack::Lint's `InputWrapper` exposes only `gets`, `read`, `each` and `close`.
404
+ - Reproduced: `POST /echo` with `{"name":"zed"}` to a `response=json` Logic route:
405
+ - returns 200 when calling Otto directly
406
+ - returns 500 under `Rack::Lint.new(otto)`, with `NoMethodError: undefined method 'size' for an instance of Rack::Lint::Wrapper::InputWrapper`
407
+ - Any SPEC-conformant server with a streaming, non-rewindable input hits the same path.
408
+
409
+ **Suggested fix.**
410
+ - Decide whether there is a body from the request, not the IO: `req.content_length.to_i > 0 || env['HTTP_TRANSFER_ENCODING']`.
411
+ - Read once with `req.body.read`, and call `rewind` only if `req.body.respond_to?(:rewind)`.
412
+ - Cache the parsed JSON in `env` so later readers do not need the stream.
413
+ - Add a spec that runs the handler under Rack::Lint.
414
+
415
+ ### C11 · Low · A CSRF token sent as an array or hash param returns 500 instead of 403
416
+
417
+ `lib/otto/security/csrf_validation.rb:40` · error-handling · **Consensus 3/3** · same issue as S3; the fix is there
418
+
419
+ **What this finding adds.**
420
+ - It confirms both nested forms, `?_csrf_token[]=abc` and `?_csrf_token[a]=b`, reach the generic 500.
421
+ - `extract_csrf_token` returns `request.params[@config.csrf_token_key]` unchanged, so the non-String value reaches both `valid_csrf_token?` and `Config#verify_csrf_token`.
422
+
423
+ ---
424
+
425
+ ## Test coverage
426
+
427
+ ### T1 · High · No spec covers `csrf_secret = ''` or `nil`
428
+
429
+ `lib/otto/security/config.rb:780` · security-untested · **Consensus 2/3** · same issue as C6; the full write-up is there
430
+
431
+ **What this finding adds.**
432
+ - After `csrf_secret = ''`, the production guard `csrf_secret_unsafe_for_production?` (line 1399) stops firing, because the flag says the secret was configured.
433
+ - With `nil`, `sign_csrf_token` (line 1337) calls `OpenSSL::HMAC.hexdigest('SHA256', nil, ...)` and raises `TypeError` on every HTML response.
434
+ - `spec/security_config_spec.rb` only sets 64-character secrets (lines 143-155, 183).
435
+ - Two failure modes pass the suite undetected for `config.csrf_secret = ENV['OTTO_CSRF_SECRET']`:
436
+ - If the variable is empty, the app ships with a zero-entropy signing key.
437
+ - If the variable is unset, every HTML response returns 500.
438
+
439
+ **Suggested fix.**
440
+ - Make the setter reject `nil` and blank values, or regenerate a secret and set `@csrf_secret_generated = true`, matching the constructor.
441
+ - Add specs:
442
+ - `''` and `nil` are rejected, or restore the generated state.
443
+ - Under `RACK_ENV=production`, `generate_csrf_token` still raises `CSRF_SECRET_REQUIRED_MESSAGE` after `csrf_secret = ''`.
444
+
445
+ ### T2 · Medium · No spec sends a well-formed JSON-RPC body that is not an object
446
+
447
+ `lib/otto/mcp/protocol.rb:70` · error-branch-untested · **Consensus 3/3** · same issue as C9; the full write-up is there
448
+
449
+ **What this finding adds.**
450
+ - The exception propagates out of `InternalHandler.handle_request` (`server.rb:310`) into `handle_error`.
451
+ - The "envelope validation" block in `spec/otto/mcp/protocol_spec.rb` (lines 61-73) only sends Hash payloads with missing fields.
452
+
453
+ **Suggested fix.** Add table-driven specs for the bodies `[]`, `null`, `42`, `true` and `"str"`. Each should assert HTTP 400, code -32600 and `id: nil`.
454
+
455
+ ### T3 · Medium · No spec posts JSON to a Logic route with a SPEC-minimal `rack.input`
456
+
457
+ `lib/otto/route_handlers/logic_class.rb:128` · compatibility-untested · **Consensus 3/3** · same issue as C10; the full write-up is there
458
+
459
+ **What this finding adds.**
460
+ - An input object that implements only `gets`, `read`, `each` and `close` also returns 500. The same request with a `StringIO` input returns 200.
461
+ - Every JSON-body test in `spec/otto/route_handlers_spec.rb` (lines 236-405) uses `StringIO`.
462
+ - The existing Rack::Lint tests (`spec/otto/ip_privacy_spec.rb:1082-1104`) never post JSON to a Logic route.
463
+
464
+ **Suggested fix.**
465
+ - Detect a body by reading it, treat an empty string as no JSON, and drop the `size` call. Guard `rewind` with `respond_to?`.
466
+ - Add two specs, both asserting 200 and the parsed params:
467
+ - one that posts JSON through `Rack::Lint.new(otto)`
468
+ - one that uses a minimal input object
469
+
470
+ ### T4 · Medium · Malformed form bodies raise Rack parser errors that surface as untested 500s
471
+
472
+ `lib/otto/security/middleware/validation_middleware.rb:45` · error-branch-untested · **Consensus 3/3**
473
+
474
+ **Why it matters.**
475
+ - `CSRFValidation#extract_csrf_token` (`csrf_validation.rb:48`) calls `request.params` on every unsafe request to a CSRF-protected route.
476
+ - Rack's query parser raises two errors that nothing catches:
477
+ - `ParameterTypeError` for conflicting shapes (`a[]=1&a[b]=2`)
478
+ - `InvalidParameterError` for bad escapes (`a=%ZZ`)
479
+ - Neither is a `QueryLimitError`, so the rescue at line 45 misses them.
480
+ - Probes with `csrf_protection: true`, with and without `enable_request_validation!`: both bodies return 500 with a logged backtrace instead of 400.
481
+ - The same `request.params` call appears in two more places:
482
+ - `api_key_strategy.rb:116`, when `param_name:` is set
483
+ - `logic_class.rb:112`
484
+ - No spec under `spec/` references these exception classes or sends a malformed body. Input that should be a cheap 400 is an untested 500 on every route that accepts forms.
485
+
486
+ **Suggested fix.**
487
+ - Broaden the rescue to `Rack::QueryParser::ParamsTooDeepError, Rack::QueryParser::ParameterTypeError, Rack::QueryParser::InvalidParameterError`, and raise `Otto::Security::ValidationError` (400).
488
+ - Register those Rack classes with `register_error_handler(..., status: 400, log_level: :info)` in `register_framework_errors`, so routes without ValidationMiddleware get the same answer.
489
+ - Add specs that post `a[]=1&a[b]=2` and `a=%ZZ` to a CSRF-protected route and to a Logic route. They should assert 400 and no backtrace log.
490
+
491
+ ### T5 · Low · The `+`-in-path behavior of `normalize_path` is not pinned by any spec
492
+
493
+ `lib/otto/utils.rb:133` · correctness-untested · **Consensus 3/3** · same issue as C7; the full write-up is there
494
+
495
+ **What this finding adds.**
496
+ - `Rack::Files`, the static server at `router.rb:216`, keeps `+` literal, as RFC 3986 path semantics do. So the router and the static server disagree.
497
+ - The only spec that touches this input (`spec/otto/utils_spec.rb:188`) asserts `routing_path(env) == normalize_path(raw)` for `"/a+b"` but never checks the value.
498
+ - The guard and the router share this function by design. Any fix must be pinned by a test, or the guard and router will drift apart again.
499
+
500
+ **Suggested fix.**
501
+ - Add `utils_spec` cases asserting `normalize_path('/a+b') == '/a+b'` and `normalize_path('/a%2Bb') == '/a+b'`.
502
+ - Add an end-to-end static-file test for a filename containing `+`.
503
+ - If form decoding is intended, document it and assert `'/a b'` explicitly.
504
+
505
+ ### T6 · Low · Hash-backed users with Symbol roles are always denied
506
+
507
+ `lib/otto/security/authentication/route_auth_wrapper/role_authorization.rb:94` · edge-case-untested · **Consensus 2/3**
508
+
509
+ **Why it matters.**
510
+ - Lines 94-95 return `Array(user[:roles] || user['roles'])` without converting the values. Line 38 then intersects them with the route's String requirements.
511
+ - On a `role=admin` route:
512
+ - `{ roles: [:admin] }` is denied.
513
+ - `{ roles: ['admin'] }` is allowed.
514
+ - The object-backed branch (line 100) applies `.to_s`, and `StrategyResult#roles` (`strategy_result.rb:263`) normalizes too. So the same user data is allowed or denied depending only on the container type.
515
+ - The Hash-user specs (`role_authorization_spec.rb:154-166`) use String roles only.
516
+ - The failure is closed (403), but it is a silent inconsistency on the route-level authorization boundary.
517
+
518
+ **Suggested fix.**
519
+ - Normalize the Hash branch with `Array(roles).map(&:to_s)`, or reuse StrategyResult's `normalize_list`.
520
+ - Add specs for `{ roles: [:admin] }` and `{ 'roles' => [:admin] }` on a `role=admin` route.
521
+ - Add a metadata case with `user_roles: [:admin]` (line 110).
522
+
523
+ ---
524
+
525
+ ## Dead code
526
+
527
+ ### D1 · High · `auth=` and `role=` on MCP and TOOL routes are parsed but never enforced
528
+
529
+ `lib/otto/mcp/route_parser.rb:53` · dead-value / stale security option · **Consensus 3/3**
530
+
531
+ **Why it matters.** This finding is filed under dead code, but in practice it is an authorization gap.
532
+
533
+ *The options are parsed.*
534
+ - `parse_mcp_route` (line 30) and `parse_tool_route` (line 53) store `options: extract_options_from_handler(...)`.
535
+ - The comment at lines 68-72 says malformed auth/role/csrf tokens fail fast "instead of silently registering the route without its intended protection". That reads as though the protection is then applied. This is an interpretation of the comment, not a documented guarantee.
536
+
537
+ *They are never applied.*
538
+ - `Otto::MCP::Server#register_resource` and `#register_tool` (`server.rb:216-265`) read only `:resource_uri`, `:tool_name` and `:handler`. They also discard the options via `handler_def.split(/\s+/).first`.
539
+ - `Registry#call_tool` and `Protocol#handle_tools_call` never consult a RouteDefinition or a strategy.
540
+ - `route_parser_spec.rb:31` and `:58` check parsing, not enforcement.
541
+
542
+ *Confirmed at runtime.* A routes file containing `POST /_x TOOL delete_all App.delete_all auth=role:admin`, run with `mcp_allow_unauthenticated: true`, returned 200 and the tool output to an anonymous `tools/call` from 203.0.113.5.
543
+
544
+ **Suggested fix.** Choose one:
545
+ - **Enforce:** keep `route_info[:options]`, and run `auth`/`role` through RouteAuthWrapper (or an equivalent check against `otto.auth_config`) before `Registry#call_tool` / `#read_resource`.
546
+ - **Reject:** raise `Otto::RouteDefinitionError` at load time when an MCP/TOOL route carries `auth`, `role` or `csrf`, and fix the comment.
547
+
548
+ Either way, add a spec showing that a tool with `auth=` cannot be called anonymously.
549
+
550
+ ### D2 · Medium · `sanitize_params` writes its results to a throwaway Hash
551
+
552
+ `lib/otto/security/middleware/validation_middleware.rb:100` · dead-store · **Consensus 3/3**
553
+
554
+ **Why it matters.**
555
+ - In Rack 3, `Rack::Request#params` returns a new `GET.merge(POST)` Hash on every call.
556
+ - `validate_parameters` passes that temporary Hash to `sanitize_params`, which assigns `params[key] = sanitize_value(value)` and then drops it. It also visits only top-level values.
557
+ - Only the raises inside `sanitize_value` have any effect: value too long, NUL byte, script-injection pattern.
558
+ - The Loofah and control-character cleanup (lines 176-179) runs a Loofah parse per string on every request, and the result is discarded.
559
+ - Runtime check on Rack 3.2.7: `/x?name=<b>bold</b>%01&nested[a]=<i>x</i>` returned 200, and the app received the original, unsanitized values.
560
+ - The specs (`spec/security_validation_spec.rb:369-395`) call `sanitize_value` directly via `send`, which hides this.
561
+ - Two places describe sanitization that never reaches the app:
562
+ - the comment at line 42 ("Validate and sanitize parameters")
563
+ - `README.md:99` (`request_validation: true, # Input sanitization and limits`)
564
+
565
+ **Suggested fix.** Decide whether this middleware rejects or rewrites.
566
+ - **Reject only:** make `sanitize_value` a pure check (keep the raises, drop the Loofah/gsub output), and correct the comment and README.
567
+ - **Rewrite:** write the sanitized values back to `env['rack.request.query_hash']` / `env['rack.request.form_hash']`, recursing into nested values. Add an end-to-end spec showing that the downstream app receives the sanitized value.
568
+
569
+ ### D3 · Medium · `default_auth_strategy` is set by three public APIs but never read
570
+
571
+ `lib/otto/core/configuration.rb:274` · stale-config-flag · **Consensus 3/3**
572
+
573
+ **Why it matters.**
574
+ - Three public APIs set it:
575
+ - `Otto.new(default_auth_strategy:)` (`configuration.rb:100`)
576
+ - `Otto#configure_auth_strategies(default_strategy:)` (`configuration.rb:270-275`)
577
+ - `Configurator#configure_auth_strategies` (`configurator.rb:337-341`)
578
+ - It is seeded to `'noauth'` at `otto.rb:249`, `configurator.rb:23` and `security/core.rb:273`.
579
+ - The `@param` docs at `configuration.rb:262` and `configurator.rb:336` read "Default strategy to use when none specified".
580
+ - Nothing in `lib` reads `auth_config[:default_auth_strategy]`. RouteAuthWrapper uses only `route_definition.auth_requirements`, and a route without `auth=` always gets an anonymous StrategyResult.
581
+ - An operator who sets `default_strategy: 'session'`, expecting unannotated routes to require a session, gets anonymous access and no warning.
582
+ - The specs (`auth_config_sharing_spec`, `configuration_methods_spec`) only check that the value is stored.
583
+
584
+ **Suggested fix.** Choose one:
585
+ - **Implement it:** in `RouteAuthWrapper#call`, use `[auth_config[:default_auth_strategy]]` when `auth_requirements` is empty and the default is not `'noauth'`.
586
+ - **Deprecate it:** warn when a non-`'noauth'` value is passed, remove the misleading docs, and stop seeding the key.
587
+
588
+ ### D4 · Medium · The legacy fallback in `Route#call` cannot run in production and would bypass auth and CSRF if it did
589
+
590
+ `lib/otto/route.rb:168` · unreachable-branch · **Consensus 3/3**
591
+
592
+ **Why it matters.**
593
+
594
+ *The branch is unreachable.*
595
+ - Lines 168-231 run only when `otto&.route_handler_factory` is falsy.
596
+ - `Otto#initialize_options` always sets `@route_handler_factory = opts[:route_handler_factory] || Otto::RouteHandlers::HandlerFactory`, so any Route attached to an Otto has a factory.
597
+ - With `otto` nil, the fallback crashes immediately on `otto.request_class`.
598
+
599
+ *It is still maintained.* The only way in is `spec/otto/route_single_setup_spec.rb:80`, which forces it with `instance_variable_set(:@route_handler_factory, nil)`, under a `legacy fallback ordering (review follow-up)` block at line 75.
600
+
601
+ *It would be unsafe if reached.*
602
+ - It skips RouteAuthWrapper and CSRFEnforcementWrapper, so `auth=`, `role=` and CSRF enforcement would be bypassed.
603
+ - It also cannot dispatch the `:logic` or `:lambda` kinds.
604
+
605
+ *It duplicates live code.*
606
+ - `Otto::ResponseHandlers::HandlerFactory` is called only from `route.rb:228`.
607
+ - The live path, `BaseHandler#handle_response`, keeps its own copy of the response-type mapping, and the two already differ: the factory lowercases the type, the live `case` does not.
608
+
609
+ **Suggested fix.**
610
+ - Delete the branch, and have `Route#call` always delegate to `otto.route_handler_factory`. Raise a clear error when `otto` is nil.
611
+ - Delete the spec that forces the branch.
612
+ - Delete `ResponseHandlers::HandlerFactory`, or make `BaseHandler#handle_response` use `HANDLER_MAP`, so there is one mapping.
613
+
614
+ ### D5 · Low · `Otto.path` always raises `NoMethodError`
615
+
616
+ `lib/otto.rb:439` · stale-delegator · **Consensus 3/3**
617
+
618
+ **Why it matters.**
619
+ - `Otto::ClassMethods#path` delegates to `default.path`, but Otto has no instance method `path`. The reverse-routing method is `Otto#uri` (`core/uri_generator.rb:16`).
620
+ - Verified: `Otto.new.respond_to?(:path)` is false, and `Otto.path('X.y')` raises.
621
+ - The doc comment at `uri_generator.rb:14` still shows `Otto.default.path 'YourClass.somemethod'`.
622
+ - Nothing in lib, spec, examples or docs calls `Otto.path`.
623
+
624
+ **Suggested fix.** Either delegate to `default.uri` and fix the `uri_generator.rb` example, or remove `Otto.path` and note the removal in the changelog.
625
+
626
+ ### D6 · Low · `require_secure_cookies` is fixed at false, has no writer, and is never read; the shipped example calls the missing setter
627
+
628
+ `lib/otto/security/config.rb:402` · stale-config-flag · **Consensus 3/3**
629
+
630
+ **Why it matters.**
631
+ - `attr_reader :require_secure_cookies` (line 402) and `@require_secure_cookies = false` (line 422) are its only appearances in `lib`.
632
+ - No cookie code reads it: not the CSRF `_otto_session` cookie, not `send_secure_cookie`.
633
+ - The only spec is a default-value assertion (`security_config_spec.rb:31`).
634
+ - `examples/security_features/config.ru:60` calls `app.security_config.require_secure_cookies = true` when `RACK_ENV=production`. That raises `NoMethodError` because there is no writer, so the example crashes in exactly the mode it is meant to demonstrate.
635
+
636
+ **Suggested fix.** Either remove the attribute, its ivar and line 60 of the example, or add a setter and actually use it, for example to force `; Secure` on the CSRF session cookie in `CSRFMiddleware#ensure_session_cookie`.
637
+
638
+ ### D7 · Low · Every CSRF-enabled response is extended with `CSRFHelpers`, whose methods can only raise on `Otto::Response`
639
+
640
+ `lib/otto/route_handlers/base.rb:163` · dead-integration · **Consensus 3/3**
641
+
642
+ **Why it matters.**
643
+ - `CSRFHelpers#csrf_token` (`security/csrf.rb:17-23`) calls `otto` and `req`. `Otto::Response` defines neither; it has `request`.
644
+ - Verified: `Otto::Response.new.extend(Otto::Security::CSRFHelpers).csrf_form_tag` raises a NameError for `otto`.
645
+ - So the per-request `res.extend Otto::Security::CSRFHelpers` adds nothing usable, but still costs a singleton class on each response. It appears at `base.rb:163`, and at `route.rb:202` in the unreachable D4 path.
646
+ - The helpers work only when a controller includes the module and defines `otto`/`req` itself, as `examples/security_features/app.rb:8-19` and `spec/security_csrf_spec.rb:244-247` do.
647
+
648
+ **Suggested fix.**
649
+ - Remove the `res.extend` lines.
650
+ - If response-level helpers are wanted, make `CSRFHelpers` use `request` and `request.env['otto.security_config']`, or register the module once through `register_response_helpers`.
651
+
652
+ ### D8 · Low · The XHR fallback in `extract_csrf_token` rereads the same env key
653
+
654
+ `lib/otto/security/csrf_validation.rb:54` · unreachable-branch · **Consensus 3/3**
655
+
656
+ **Why it matters.**
657
+ - Line 51 reads `request.env[@config.csrf_header_key]`. `csrf_header_key` has only a reader and is fixed to `'HTTP_X_CSRF_TOKEN'` in `Config#initialize` (`config.rb:416`).
658
+ - Line 54 reads `request.env['HTTP_X_CSRF_TOKEN']` under an XHR condition. If line 51 returned nil, line 54 does too.
659
+ - The branch adds a condition to review on the CSRF path and does nothing.
660
+
661
+ **Suggested fix.** Delete line 54 and its comment. If a second header spelling was intended, name that key explicitly.
662
+
663
+ ### D9 · Low · `Validator#validate_tool_arguments` is never called
664
+
665
+ `lib/otto/mcp/schema_validation.rb:45` · unused-method · **Consensus 3/3**
666
+
667
+ **Why it matters.**
668
+ - No code in lib or spec calls `validate_tool_arguments`.
669
+ - The SchemaValidationMiddleware comment (line 77) reads "Validates JSON-RPC 2.0 structure and tool argument schemas", but the middleware only calls `validate_request`.
670
+ - Every registered tool gets a hard-coded empty `input_schema` (`server.rb:261-265`), so there is no schema to validate against anyway.
671
+ - The comment overstates what the validation layer checks.
672
+
673
+ **Suggested fix.** Delete the method and change the comment to describe JSON-RPC 2.0 request-structure validation only. Alternatively, call it from `Protocol#handle_tools_call` once tools carry real input schemas.
674
+
675
+ ### D10 · Low · The private helper `contains_html_like_content?` has no callers
676
+
677
+ `lib/otto/helpers/validation.rb:80` · unused-method · **Consensus 3/3**
678
+
679
+ **Why it matters.** It is defined in the private section of `Otto::Security::ValidationHelpers` and is not referenced anywhere in lib, spec or examples. `validate_input` and ValidationMiddleware use only `looks_like_script_injection?`.
680
+
681
+ **Suggested fix.** Delete the method.
682
+
683
+ ### D11 · Low · `lib/otto/helpers/base.rb` is an orphaned file
684
+
685
+ `lib/otto/helpers/base.rb:7` · orphaned-file · **Consensus 3/3**
686
+
687
+ **Why it matters.**
688
+ - No `require` or `require_relative` in lib, spec, examples or bin resolves to this file.
689
+ - `Otto::BaseHelpers` has no references, and its body is only a comment. The file still ships in the gem.
690
+ - By contrast, `lib/otto/helpers.rb` is also comment-only but is still required by `lib/otto.rb` for compatibility.
691
+
692
+ **Suggested fix.** Delete `lib/otto/helpers/base.rb`.
693
+
694
+ ---
695
+
696
+ ## Dependency risk
697
+
698
+ ### P1 · Low · The gem-publishing job installs 75 dev and optional gems while holding `id-token: write`
699
+
700
+ `.github/workflows/release-gem.yml:125` · supply-chain · **Consensus 3/3**
701
+
702
+ **Why it matters.**
703
+
704
+ *What gets installed.*
705
+ - `BUNDLE_WITH: development` (line 125) turns on the optional `:development` group and the `:development, :test, optional: true` group (`Gemfile:19-42`).
706
+ - setup-ruby with `bundler-cache: true` (line 144) then installs 75 gems, including rubocop\*, ruby-lsp/rbs/prism, debug, stackprof, syntax_tree, reek/dry-\*, tryouts, yard, kramdown, rack-attack, json_schemer and maxmind-db.
707
+ - Several of these build native extensions, and their install code runs inside the job.
708
+
709
+ *What the job can do.* It holds `id-token: write` (line 133, the RubyGems Trusted Publishing credential) and `contents: write` (line 132).
710
+
711
+ *What it actually needs.*
712
+ - `rake release` needs only rake plus Otto's runtime dependencies, about 8 gems.
713
+ - The workflow comment (lines 117-123) says the group is enabled so that rake is installed.
714
+
715
+ *The exposure.*
716
+ - Dependabot regularly bumps these dev gems. A compromised dev-tool release merged that way would get OIDC publish rights on the next release.
717
+ - The CI jobs hold no secrets; the release job is the exposure.
718
+ - `Gemfile.lock` has no `CHECKSUMS` section, so installs are not checked against recorded hashes.
719
+
720
+ **Suggested fix.**
721
+ 1. Move rake out of the optional development group. Either declare it at top level or in a non-optional `:release` group (`gem 'rake', '~> 13.4', require: false`), or point the release job at a minimal gemfile via `BUNDLE_GEMFILE`.
722
+ 2. Remove `BUNDLE_WITH: development` from the release job.
723
+ 3. Run `bundle lock --add-checksums`.
724
+
725
+ ---
726
+
727
+ ## Evidence notes
728
+
729
+ - **Source of findings.** The findings come from auditor and verifier agents. AGENTS.md treats agent output as leads, not evidence.
730
+ - **What was rechecked for this report.** At 359a25f, each cited primary line anchor and every quoted source string was checked against the tree, and all matched. The `route_parser.rb` comment quoted in D1 spans lines 68-72. Reproduction results were not re-run for this report and are reported as the verifiers observed them.
731
+ - **Docs and comments are not guarantees.** Quotations from `docs/guides/*.md`, `README.md` and code comments show what those texts say. None is identified as an authoritative source under AGENTS.md, so this report does not treat them as project guarantees. Statements about intended behavior (for example, in D1 and D3) are interpretations.
732
+ - **Severity is the auditors' judgment.** Ratings are the auditors' assessments, not project-defined classifications.