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.
- checksums.yaml +4 -4
- data/.github/workflows/ci.yml +1 -1
- data/.github/workflows/claude-code-review.yml +1 -1
- data/.github/workflows/claude.yml +1 -1
- data/.github/workflows/code-smells.yml +2 -2
- data/.github/workflows/release-gem.yml +1 -1
- data/.github/workflows/ruby-lint.yml +1 -1
- data/.github/workflows/yardoc.yml +1 -1
- data/AGENTS.md +4 -2
- data/CHANGELOG.rst +692 -0
- data/Gemfile +1 -0
- data/Gemfile.lock +6 -1
- data/docs/README.md +4 -0
- data/docs/audits/2026-09-28-v2.12.0-code-audit.md +732 -0
- data/docs/audits/README.md +63 -0
- data/docs/guides/authentication.md +329 -0
- data/docs/guides/forwarded-authority.md +80 -4
- data/docs/guides/mcp.md +40 -4
- data/docs/guides/privacy.md +23 -2
- data/docs/guides/routing.md +8 -4
- data/docs/guides/testing-guide.md +31 -3
- data/docs/migrating/v2.3.0.md +13 -7
- data/docs/reference/authentication.md +70 -22
- data/examples/lambda_handlers/README.md +4 -4
- data/examples/lambda_handlers/handlers.rb +4 -5
- data/examples/lambda_handlers/routes +2 -2
- data/examples/mcp_demo/README.md +65 -27
- data/examples/mcp_demo/app.rb +8 -5
- data/examples/mcp_demo/config.ru +50 -3
- data/examples/mcp_demo/routes +10 -6
- data/examples/security_features/README.md +2 -2
- data/lib/otto/caddy_tls/server.rb +8 -4
- data/lib/otto/core/option_hash.rb +124 -0
- data/lib/otto/core/redacted_inspect.rb +149 -0
- data/lib/otto/core/router.rb +41 -14
- data/lib/otto/core.rb +2 -0
- data/lib/otto/env_keys.rb +30 -7
- data/lib/otto/logging_helpers.rb +1 -1
- data/lib/otto/mcp/auth/token.rb +12 -1
- data/lib/otto/mcp/protocol.rb +3 -3
- data/lib/otto/mcp/registry.rb +28 -2
- data/lib/otto/mcp/route_parser.rb +20 -8
- data/lib/otto/mcp/server.rb +17 -9
- data/lib/otto/privacy/config.rb +12 -1
- data/lib/otto/privacy/ip_privacy.rb +109 -3
- data/lib/otto/privacy/redacted_fingerprint.rb +8 -10
- data/lib/otto/request.rb +34 -0
- data/lib/otto/route_definition.rb +3 -2
- data/lib/otto/security/authentication/route_auth_wrapper.rb +10 -3
- data/lib/otto/security/config.rb +358 -46
- data/lib/otto/security/csrf.rb +17 -2
- data/lib/otto/security/csrf_validation.rb +13 -7
- data/lib/otto/security/middleware/csrf_middleware.rb +203 -37
- data/lib/otto/security/middleware/ip_privacy_middleware.rb +127 -38
- data/lib/otto/static.rb +63 -0
- data/lib/otto/utils.rb +105 -28
- data/lib/otto/version.rb +1 -1
- data/lib/otto.rb +37 -9
- metadata +6 -2
data/docs/guides/routing.md
CHANGED
|
@@ -192,6 +192,10 @@ the result is still inside that root and is a regular, readable file owned by
|
|
|
192
192
|
the process user or group. Anything else, including a symlink that points
|
|
193
193
|
outside the root, is treated as not found.
|
|
194
194
|
|
|
195
|
+
Both answer `GET` and `HEAD` requests. A `HEAD` response carries the headers a
|
|
196
|
+
`GET` would get, including `content-length`, and an empty body. Requests with
|
|
197
|
+
any other method skip the static stages.
|
|
198
|
+
|
|
195
199
|
### Implicit public directory
|
|
196
200
|
|
|
197
201
|
Passing `public:` serves every file under that directory at its relative path.
|
|
@@ -232,10 +236,10 @@ otto.mount_static('/', root: 'public/root-files') # favicon.ico, robots.txt
|
|
|
232
236
|
directory. Registering the same prefix twice on one instance raises
|
|
233
237
|
`ArgumentError`; different Otto instances are fully independent.
|
|
234
238
|
- Requests are matched on the decoded, trailing-slash-stripped path, the same
|
|
235
|
-
normalization every other dispatch stage uses. Only `GET`
|
|
236
|
-
prefix itself is not (mounts serve files, not directory
|
|
237
|
-
request for a file the root does not contain falls through
|
|
238
|
-
dispatch stage.
|
|
239
|
+
normalization every other dispatch stage uses. Only `GET` and `HEAD` are
|
|
240
|
+
served, the prefix itself is not (mounts serve files, not directory
|
|
241
|
+
listings), and a request for a file the root does not contain falls through
|
|
242
|
+
to the next dispatch stage.
|
|
239
243
|
- `mount_static` must be called before the first request. After configuration
|
|
240
244
|
freezing it raises `FrozenError`, and `otto.static_mounts` is a frozen,
|
|
241
245
|
read-only table.
|
|
@@ -357,11 +357,39 @@ Valid request tokens must come from `config.generate_csrf_token(session_id)` and
|
|
|
357
357
|
must use the matching session ID; an arbitrary value copied into the session and
|
|
358
358
|
header is not a valid token.
|
|
359
359
|
|
|
360
|
+
When the session provides no binding (no session middleware, or a session with
|
|
361
|
+
no id and no stored binding), the binding lives in a cookie that
|
|
362
|
+
`CSRFMiddleware` sets only on responses to safe requests, HTML or not, whose
|
|
363
|
+
binding the client does not already send: one Otto minted, or one stored under
|
|
364
|
+
`csrf_session_key`. A session id the request already had, or a binding read
|
|
365
|
+
from a cookie, is never copied into it, so a test behind a session middleware
|
|
366
|
+
that wraps `CSRFMiddleware` carries the store's cookie, not `_otto_session`. A
|
|
367
|
+
store added with `otto.use` before CSRF protection is enabled runs inside
|
|
368
|
+
`CSRFMiddleware`; there the binding cookie carries the id the store creates
|
|
369
|
+
when the middleware mints a binding. An unsafe request never creates a
|
|
370
|
+
binding, so a test that posts without one gets `403` and no cookie, and an
|
|
371
|
+
HTML response to it carries no token.
|
|
372
|
+
`spec/otto/security/csrf_rack_session_spec.rb` runs these flows behind
|
|
373
|
+
rack-session's `Pool` and `Cookie` stores.
|
|
374
|
+
`Otto::Security::Config#csrf_binding_cookie_name`
|
|
375
|
+
returns its name: `__Host-otto_session` when Rack reports the request as HTTPS
|
|
376
|
+
(`request.scheme == 'https'`), set with `Secure`, `Path=/` and no `Domain`, and
|
|
377
|
+
`_otto_session` otherwise. On HTTPS requests Otto reads only the `__Host-`
|
|
378
|
+
cookie; `_otto_session`, `session_id` and `_session_id` cookies are ignored
|
|
379
|
+
there, because a sibling subdomain or a network attacker could plant them and
|
|
380
|
+
choose the binding. A test that drives a form over HTTPS must carry
|
|
381
|
+
`__Host-otto_session` from the response to the next request.
|
|
382
|
+
|
|
360
383
|
Use these maintained specs as executable examples:
|
|
361
384
|
|
|
362
|
-
- [`spec/security_csrf_spec.rb`](../../spec/security_csrf_spec.rb)
|
|
363
|
-
- [`spec/otto/security/csrf_enforcement_wrapper_spec.rb`](../../spec/otto/security/csrf_enforcement_wrapper_spec.rb)
|
|
364
|
-
- [`spec/otto/security/csrf_validation_spec.rb`](../../spec/otto/security/csrf_validation_spec.rb)
|
|
385
|
+
- [`spec/security_csrf_spec.rb`](../../spec/security_csrf_spec.rb): response injection.
|
|
386
|
+
- [`spec/otto/security/csrf_enforcement_wrapper_spec.rb`](../../spec/otto/security/csrf_enforcement_wrapper_spec.rb): safe methods, unsafe methods, valid tokens, and `csrf=exempt`.
|
|
387
|
+
- [`spec/otto/security/csrf_validation_spec.rb`](../../spec/otto/security/csrf_validation_spec.rb): token and session extraction.
|
|
388
|
+
- [`spec/otto/security/csrf_binding_cookie_spec.rb`](../../spec/otto/security/csrf_binding_cookie_spec.rb): the binding cookie on HTTP and HTTPS.
|
|
389
|
+
- [`spec/otto/security/csrf_rack_session_spec.rb`](../../spec/otto/security/csrf_rack_session_spec.rb): the binding behind rack-session's `Pool` and `Cookie` stores.
|
|
390
|
+
- [`spec/otto/security/csrf_cache_control_spec.rb`](../../spec/otto/security/csrf_cache_control_spec.rb): `Cache-Control: private, stale-if-error=0` on responses that carry the binding cookie or an injected token.
|
|
391
|
+
- [`spec/otto/security/csrf_nested_middleware_spec.rb`](../../spec/otto/security/csrf_nested_middleware_spec.rb): one binding cookie when `CSRFMiddleware` runs more than once, including nested Ottos.
|
|
392
|
+
- [`spec/otto/security/csrf_middleware_rack_spec.rb`](../../spec/otto/security/csrf_middleware_rack_spec.rb): `CSRFMiddleware` under `Rack::Lint`, including bodies it may not read (files from `public:` and streams), 204, 304 and HEAD responses, and a binding that is not a hex token.
|
|
365
393
|
|
|
366
394
|
## Test IP privacy with the application configuration
|
|
367
395
|
|
data/docs/migrating/v2.3.0.md
CHANGED
|
@@ -128,7 +128,7 @@ and the `ConfigureTrustedProxy` monkeypatch
|
|
|
128
128
|
|
|
129
129
|
| Use… | When… |
|
|
130
130
|
|------|-------|
|
|
131
|
-
| **CIDR-walk** (`add_trusted_proxy`, the default) | Your proxy IPs are **enumerable** — a fixed set of load balancers / reverse proxies you can list as IPs or CIDR ranges.
|
|
131
|
+
| **CIDR-walk** (`add_trusted_proxy`, the default) | Your proxy IPs are **enumerable** — a fixed set of load balancers / reverse proxies you can list as IPs or CIDR ranges. Which forwarded entry becomes the client changed in the first release after 2.12.0; see [How enumerated proxy trust resolves the client IP](../guides/forwarded-authority.md#how-enumerated-proxy-trust-resolves-the-client-ip). |
|
|
132
132
|
| **Depth** (`trusted_proxy_depth = N`) | Your proxy tier is **non-enumerable** — Fly, cloud load balancers, dynamic/autoscaling reverse proxies whose addresses you cannot pin down. You instead know the **fixed number of hops** between the client and your app. |
|
|
133
133
|
|
|
134
134
|
The two modes are **mutually exclusive**. Configuring both `trusted_proxies` and
|
|
@@ -184,10 +184,15 @@ counting, so an attacker cannot pad the header with junk/invalid entries to shif
|
|
|
184
184
|
the index. Only the single selected entry is validated.
|
|
185
185
|
|
|
186
186
|
**Short-chain and invalid-target fallback.** If the chain is shorter than
|
|
187
|
-
`N + 1` (a request that may have **bypassed** the proxy tier),
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
187
|
+
`N + 1` (a request that may have **bypassed** the proxy tier), the resolver
|
|
188
|
+
returns `REMOTE_ADDR` rather than a spoofable forwarded value. This is
|
|
189
|
+
intentionally **stricter than Express**, which returns the leftmost (most
|
|
190
|
+
spoofable) forwarded entry in that case. If the selected entry is not a valid
|
|
191
|
+
IP, releases through 2.12.0 also returned `REMOTE_ADDR`; starting with the first
|
|
192
|
+
release after 2.12.0 the request has no client IP instead (`otto.ip_match`
|
|
193
|
+
denies every range; see
|
|
194
|
+
[How enumerated proxy trust resolves the client IP](../guides/forwarded-authority.md#how-enumerated-proxy-trust-resolves-the-client-ip)
|
|
195
|
+
for the rest of that state).
|
|
191
196
|
|
|
192
197
|
**Single-value headers are never consulted.** `X-Real-IP` and `X-Client-IP`
|
|
193
198
|
cannot express a hop chain, so depth mode ignores them (CIDR-walk still consults
|
|
@@ -246,8 +251,9 @@ Otto.new(routes, trusted_proxy_depth: 1, trusted_proxy_header: 'Forwarded')
|
|
|
246
251
|
`for=` parameter is read case-insensitively and unquoted. Quoted IPv6 with a
|
|
247
252
|
port (`for="[2001:db8::1]:443"`) resolves to `2001:db8::1`. Obfuscated
|
|
248
253
|
(`for=_hidden`) and `for=unknown` identifiers still occupy a hop position but
|
|
249
|
-
are not valid IPs, so if one is the selected hop the
|
|
250
|
-
|
|
254
|
+
are not valid IPs, so if one is the selected hop the request has no client
|
|
255
|
+
IP (first release after 2.12.0; 2.12.0 and earlier fell back to
|
|
256
|
+
`REMOTE_ADDR`). Multiple `Forwarded` headers (joined by Rack into one
|
|
251
257
|
comma-separated value) are handled.
|
|
252
258
|
- **Raw position counting is preserved** in all three modes: elements are never
|
|
253
259
|
dropped before counting (an element without a `for=` still counts as a hop),
|
|
@@ -28,10 +28,24 @@ GET /api/data DataLogic#show auth=session,apikey,oauth
|
|
|
28
28
|
```
|
|
29
29
|
|
|
30
30
|
**Execution Flow:**
|
|
31
|
-
1.
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
31
|
+
1. Unknown strategy names fail the request with 401 before any strategy runs
|
|
32
|
+
(strict mode)
|
|
33
|
+
2. Strategies execute left-to-right in order
|
|
34
|
+
3. The first **authenticated** success (a result with a user) wins; the
|
|
35
|
+
remaining strategies are not executed
|
|
36
|
+
4. An **anonymous** success (a result without a user, e.g. from `noauth`)
|
|
37
|
+
does not win yet. It is held as a fallback and the chain continues; only
|
|
38
|
+
the first anonymous success is held
|
|
39
|
+
5. A plain failure is recorded and the next strategy runs
|
|
40
|
+
6. A terminal failure (`AuthFailure` with `terminal: true`, e.g. an API key
|
|
41
|
+
that was presented and rejected) halts the chain, and a held anonymous
|
|
42
|
+
fallback does not rescue the request
|
|
43
|
+
7. If the chain completes without an authenticated success or a terminal
|
|
44
|
+
failure, the held anonymous fallback wins
|
|
45
|
+
8. Otherwise the request fails: 403 if any strategy returned an
|
|
46
|
+
`AuthorizationFailure`, else 401 when the route is `response=json` or the
|
|
47
|
+
request accepts `application/json`, and a 302 redirect to the login path
|
|
48
|
+
for other requests
|
|
35
49
|
|
|
36
50
|
**Performance Tip:** Put fastest/most-common strategies first (e.g., `auth=session,apikey`)
|
|
37
51
|
|
|
@@ -39,14 +53,22 @@ GET /api/data DataLogic#show auth=session,apikey,oauth
|
|
|
39
53
|
```ruby
|
|
40
54
|
# Route: auth=session,apikey,oauth
|
|
41
55
|
# 1. Tries 'session' strategy
|
|
42
|
-
# 2. If session
|
|
56
|
+
# 2. If session authenticates → call handler (apikey/oauth not executed)
|
|
43
57
|
# 3. If session fails → try 'apikey' strategy
|
|
44
|
-
# 4. If apikey
|
|
58
|
+
# 4. If apikey authenticates → call handler (oauth not executed)
|
|
45
59
|
# 5. If apikey fails → try 'oauth' strategy
|
|
46
|
-
# 6. If oauth
|
|
47
|
-
# 7. If all fail →
|
|
60
|
+
# 6. If oauth authenticates → call handler
|
|
61
|
+
# 7. If all fail → 401, 403 or 302 (Execution Flow, step 8)
|
|
48
62
|
```
|
|
49
63
|
|
|
64
|
+
Declaration order does not let an anonymous strategy win early. On
|
|
65
|
+
`auth=noauth,session`, a request whose session holds a user is
|
|
66
|
+
authenticated by `session`, and `noauth` wins only when `session` fails. On
|
|
67
|
+
`auth=noauth,apikey`, a request that presents an invalid API key is refused:
|
|
68
|
+
the key's terminal failure halts the chain, and the response follows step 8
|
|
69
|
+
(401 when the route is `response=json` or the request accepts
|
|
70
|
+
`application/json`, otherwise a 302 redirect to the login path).
|
|
71
|
+
|
|
50
72
|
## Strategy Pattern Matching
|
|
51
73
|
|
|
52
74
|
- **Exact match**: `'authenticated'` → looks up `auth_config[:auth_strategies]['authenticated']`
|
|
@@ -72,14 +94,25 @@ GET /profile ProfileLogic auth=session
|
|
|
72
94
|
- Use `auth=` for authentication strategies
|
|
73
95
|
- Use `role=` for role-based route access (OR logic for multiple roles)
|
|
74
96
|
- Fast execution (no database queries)
|
|
75
|
-
- Returns 401 (Unauthorized) for authentication failures
|
|
97
|
+
- Returns 401 (Unauthorized) for authentication failures, or a 302 redirect to
|
|
98
|
+
the login path for requests that do not want JSON
|
|
76
99
|
- Returns 403 (Forbidden) for authorization failures
|
|
77
100
|
|
|
78
|
-
**Role Extraction Order
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
101
|
+
**Role Extraction Order** (checked in order; the first source that is set is
|
|
102
|
+
used):
|
|
103
|
+
1. `result.user_roles`, if the result responds to it (`StrategyResult` does
|
|
104
|
+
not define it)
|
|
105
|
+
2. For a Hash user: `result.user[:roles]`, then `result.user['roles']`. A set
|
|
106
|
+
value is used even when it is empty
|
|
107
|
+
3. For any other user object (ORM model, PORO, `Data`/`Struct`):
|
|
108
|
+
`result.user.roles`, stringified; if the user does not respond to `#roles`
|
|
109
|
+
or it yields no roles, `result.user.role`
|
|
110
|
+
4. `result.metadata[:user_roles]` (metadata; `RoleStrategy` puts the session's
|
|
111
|
+
roles here)
|
|
112
|
+
|
|
113
|
+
A user object that is not a Hash and responds to neither `#roles` nor `#role`
|
|
114
|
+
contributes no roles instead of raising `NoMethodError`; the metadata source
|
|
115
|
+
is still checked.
|
|
83
116
|
|
|
84
117
|
### Layer 2: Resource-Level Authorization
|
|
85
118
|
|
|
@@ -264,21 +297,36 @@ end
|
|
|
264
297
|
When a route has authentication requirements:
|
|
265
298
|
|
|
266
299
|
1. Looks up strategies from `auth_config[:auth_strategies]`
|
|
267
|
-
2. Executes `strategy.authenticate(env, requirement)` for each strategy
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
- Sets `env['
|
|
300
|
+
2. Executes `strategy.authenticate(env, requirement)` for each strategy in
|
|
301
|
+
order, until one authenticates or a terminal failure halts the chain
|
|
302
|
+
3. On the winning success (the first authenticated success, or the held
|
|
303
|
+
anonymous fallback once the chain completes; see Execution Flow above):
|
|
304
|
+
- Sets `env['rack.session']` to `result.session` (unless that is `nil` or
|
|
305
|
+
`false`) when env holds no session a middleware installed: the key is
|
|
306
|
+
absent, or it holds the `Otto::Request::DefaultSession` that
|
|
307
|
+
`Otto::Request#session` installs when no session middleware ran. A
|
|
308
|
+
session a middleware installed is never replaced
|
|
309
|
+
- Sets `env['otto.strategy_result']`; the user is
|
|
310
|
+
`env['otto.strategy_result'].user`
|
|
272
311
|
- Checks role requirements (if `role=` specified)
|
|
273
312
|
- Calls wrapped handler
|
|
274
|
-
4. If
|
|
313
|
+
4. If the chain fails (every strategy failed, or a terminal failure halted
|
|
314
|
+
it): Returns 403, 401 or 302, as in Execution Flow step 8
|
|
275
315
|
5. If role check fails: Returns 403
|
|
276
316
|
|
|
277
317
|
## Compatibility Notes
|
|
278
318
|
|
|
279
|
-
- `enable_authentication!`
|
|
319
|
+
- `enable_authentication!` was removed; calling it raises `NoMethodError`.
|
|
320
|
+
`RouteAuthWrapper` wraps every route handler without it
|
|
280
321
|
- AuthenticationMiddleware was removed (architecturally broken - ran before routing)
|
|
281
|
-
- `
|
|
322
|
+
- `env['otto.user']` is not set; read the user from
|
|
323
|
+
`env['otto.strategy_result'].user`
|
|
324
|
+
- `auth=role:admin` is a strategy requirement, not the route-level role check.
|
|
325
|
+
It resolves to a strategy registered under the exact name `role:admin`, or
|
|
326
|
+
else to the one registered as `role` (prefix match). A `RoleStrategy`
|
|
327
|
+
checks `admin` against the session's roles (`user_roles` by default).
|
|
328
|
+
`role=admin` is the separate route-level check (Layer 1) against the
|
|
329
|
+
successful strategy result
|
|
282
330
|
|
|
283
331
|
## Best Practices
|
|
284
332
|
|
|
@@ -73,10 +73,10 @@ class/instance/logic handler does:
|
|
|
73
73
|
Route options apply to lambdas just like any other handler:
|
|
74
74
|
|
|
75
75
|
- `response=json` — serialize the returned Hash as JSON.
|
|
76
|
-
- `csrf=exempt` —
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
76
|
+
- `csrf=exempt` — skip CSRF token validation for the route (the webhook,
|
|
77
|
+
which external callers reach without a browser token). Otto enforces it at
|
|
78
|
+
the handler layer (issue #186), so exempt only routes that are authenticated
|
|
79
|
+
another way.
|
|
80
80
|
- `auth=` / `role=` — authentication and authorization (when `auth_config`
|
|
81
81
|
is configured on the Otto instance).
|
|
82
82
|
|
|
@@ -48,11 +48,10 @@ module LambdaHandlers
|
|
|
48
48
|
{ greeting: "Hello, #{name}!" }
|
|
49
49
|
end
|
|
50
50
|
|
|
51
|
-
# A webhook-style POST handler. The matching route declares `csrf=exempt
|
|
52
|
-
#
|
|
53
|
-
#
|
|
54
|
-
#
|
|
55
|
-
# CSRF only for endpoints authenticated another way (signature header, shared
|
|
51
|
+
# A webhook-style POST handler. The matching route declares `csrf=exempt`
|
|
52
|
+
# so external callers, which cannot present a CSRF token, can reach it.
|
|
53
|
+
# Otto enforces the option at the handler layer (issue #186), so exempt CSRF
|
|
54
|
+
# only for endpoints authenticated another way (signature header, shared
|
|
56
55
|
# secret, etc.).
|
|
57
56
|
WEBHOOK = lambda do |req, _res, _extra|
|
|
58
57
|
# Rewind first: upstream middleware may already have read the input stream.
|
|
@@ -23,6 +23,6 @@ GET /status &status response=json
|
|
|
23
23
|
# Reads a path param, returned as JSON.
|
|
24
24
|
GET /greet/:name &greet response=json
|
|
25
25
|
|
|
26
|
-
# Webhook receiver:
|
|
27
|
-
#
|
|
26
|
+
# Webhook receiver: csrf=exempt skips the CSRF check for this route (enforced
|
|
27
|
+
# since 2.6.0, #186), so authenticate it another way, such as a signature header.
|
|
28
28
|
POST /webhook &webhook csrf=exempt response=json
|
data/examples/mcp_demo/README.md
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
# Otto MCP Demo
|
|
2
2
|
|
|
3
3
|
This example boots Otto's Model Context Protocol (MCP) JSON-RPC 2.0 endpoint at
|
|
4
|
-
`/_mcp
|
|
5
|
-
routes.
|
|
4
|
+
`/_mcp`, with one resource and one tool declared in the routes file, alongside
|
|
5
|
+
ordinary Otto web routes.
|
|
6
6
|
|
|
7
7
|
## What You'll Learn
|
|
8
8
|
|
|
9
9
|
- How to enable an MCP HTTP endpoint
|
|
10
|
+
- How to declare an MCP resource and tool in the routes file
|
|
10
11
|
- How the endpoint coexists with ordinary Otto web routes
|
|
11
|
-
- How to send
|
|
12
|
+
- How to send JSON-RPC 2.0 requests to list, read, and call them
|
|
12
13
|
- How bearer-token authentication protects the endpoint
|
|
13
|
-
- The current resource and tool limitations described below
|
|
14
14
|
|
|
15
15
|
## Features Demonstrated
|
|
16
16
|
|
|
17
17
|
- **MCP endpoint**: A single `POST /_mcp` endpoint
|
|
18
|
+
- **Resource and tool**: The `users` resource and the `create_user` tool
|
|
18
19
|
- **Web interface**: Separate web routes coexist with the MCP endpoint
|
|
19
|
-
- **JSON-RPC 2.0**: `initialize`, `resources/list`,
|
|
20
|
+
- **JSON-RPC 2.0**: `initialize`, `resources/list`, `resources/read`,
|
|
21
|
+
`tools/list`, and `tools/call` requests
|
|
20
22
|
|
|
21
23
|
## How to Run
|
|
22
24
|
|
|
@@ -38,7 +40,10 @@ If either enabled feature's gem is missing or incompatible, MCP setup raises
|
|
|
38
40
|
`enable_validation: false` or `enable_rate_limiting: false` to `enable_mcp!`, or
|
|
39
41
|
alongside `mcp_enabled: true` in the `Otto.new` options, only when that protection
|
|
40
42
|
is intentionally disabled. To enforce the configured limits, mount
|
|
41
|
-
`Rack::Attack` before Otto in `config.ru`, as this example does.
|
|
43
|
+
`Rack::Attack` before Otto in `config.ru`, as this example does. `Rack::Attack`
|
|
44
|
+
counts requests in a cache store and has no default store outside Rails, so
|
|
45
|
+
`config.ru` sets a small in-process store (`DemoRateLimitStore`). Use a shared
|
|
46
|
+
store, such as Redis, when the app runs in more than one process.
|
|
42
47
|
|
|
43
48
|
```sh
|
|
44
49
|
cd /path/to/otto
|
|
@@ -64,14 +69,27 @@ and a JSON-RPC `Unauthorized` error. The `requests_per_minute` and
|
|
|
64
69
|
`tools_per_minute` values in `config.ru` are applied as configured. See the
|
|
65
70
|
[MCP guide](../../docs/guides/mcp.md) for the full option list.
|
|
66
71
|
|
|
67
|
-
##
|
|
72
|
+
## Resources and Tools
|
|
68
73
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
74
|
+
`routes` declares one resource and one tool:
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
GET /mcp/users MCP users UserAPI.mcp_list_users
|
|
78
|
+
POST /mcp/create_user TOOL create_user UserAPI.mcp_create_user
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The verb and path are required by the route-file grammar but create no HTTP
|
|
82
|
+
route: the resource and the tool are served only through `POST /_mcp`. The word
|
|
83
|
+
after `MCP` is the resource URI (`users`), and the word after `TOOL` is the tool
|
|
84
|
+
name (`create_user`). MCP must be enabled when the routes file loads, as
|
|
85
|
+
`Otto.new('routes', mcp_enabled: true, ...)` in `config.ru` does. If the file
|
|
86
|
+
loads before MCP is enabled, Otto skips its `MCP` and `TOOL` lines.
|
|
87
|
+
|
|
88
|
+
`UserAPI.mcp_list_users` takes no arguments. A resource handler may instead
|
|
89
|
+
take one argument, the Rack env of the MCP request. `UserAPI.mcp_create_user`
|
|
90
|
+
receives the tool `arguments` and the Rack env. `MCP` and `TOOL` lines cannot
|
|
91
|
+
use `auth=`, `role=`, or `csrf=`; see the
|
|
92
|
+
[MCP guide](../../docs/guides/mcp.md#register-resources-and-tools).
|
|
75
93
|
|
|
76
94
|
## Interacting with the MCP Endpoint
|
|
77
95
|
|
|
@@ -101,7 +119,8 @@ curl -X POST http://localhost:9292/_mcp \
|
|
|
101
119
|
|
|
102
120
|
### MCP: Initialize
|
|
103
121
|
|
|
104
|
-
The `initialize` method is a built-in MCP method that returns
|
|
122
|
+
The `initialize` method is a built-in MCP method that returns the protocol
|
|
123
|
+
version, the server capabilities, and the server name and version.
|
|
105
124
|
|
|
106
125
|
```sh
|
|
107
126
|
curl -X POST http://localhost:9292/_mcp \
|
|
@@ -114,7 +133,7 @@ curl -X POST http://localhost:9292/_mcp \
|
|
|
114
133
|
|
|
115
134
|
A successful `initialize` request returns `result.protocolVersion`,
|
|
116
135
|
`result.capabilities`, and `result.serverInfo` with the same request ID. To
|
|
117
|
-
|
|
136
|
+
list the registered resource and tool, run:
|
|
118
137
|
|
|
119
138
|
```sh
|
|
120
139
|
curl -X POST http://localhost:9292/_mcp \
|
|
@@ -128,34 +147,53 @@ curl -X POST http://localhost:9292/_mcp \
|
|
|
128
147
|
-d '{"jsonrpc":"2.0","method":"tools/list","id":3}'
|
|
129
148
|
```
|
|
130
149
|
|
|
131
|
-
|
|
132
|
-
|
|
150
|
+
`resources/list` returns one entry with `"uri":"users"`, and `tools/list`
|
|
151
|
+
returns one entry with `"name":"create_user"`. Read the resource and call the
|
|
152
|
+
tool:
|
|
153
|
+
|
|
154
|
+
```sh
|
|
155
|
+
curl -X POST http://localhost:9292/_mcp \
|
|
156
|
+
-H 'Content-Type: application/json' \
|
|
157
|
+
-H 'Authorization: Bearer demo-token-123' \
|
|
158
|
+
-d '{"jsonrpc":"2.0","method":"resources/read","id":4,"params":{"uri":"users"}}'
|
|
159
|
+
|
|
160
|
+
curl -X POST http://localhost:9292/_mcp \
|
|
161
|
+
-H 'Content-Type: application/json' \
|
|
162
|
+
-H 'Authorization: Bearer demo-token-123' \
|
|
163
|
+
-d '{"jsonrpc":"2.0","method":"tools/call","id":5,"params":{"name":"create_user","arguments":{"name":"Carol"}}}'
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`resources/read` returns `result.contents[0].text`, the JSON list of users
|
|
167
|
+
from `UserAPI.mcp_list_users`. `tools/call` returns `result.content[0].text`,
|
|
168
|
+
starting with `Created user:`. `tools_per_minute: 20` limits each client IP:
|
|
169
|
+
the 21st `tools/call` in the same 60-second window gets HTTP `429`.
|
|
133
170
|
|
|
134
171
|
## File Structure
|
|
135
172
|
|
|
136
173
|
- `README.md`: This file
|
|
137
174
|
- `app.rb`: Application logic
|
|
138
175
|
- `DemoApp`: Web interface and health check
|
|
139
|
-
- `UserAPI`:
|
|
140
|
-
- `config.ru`: Rack configuration (loads Otto, enables MCP
|
|
176
|
+
- `UserAPI`: MCP resource and tool handlers
|
|
177
|
+
- `config.ru`: Rack configuration (loads Otto, enables MCP, sets the
|
|
178
|
+
`Rack::Attack` store)
|
|
141
179
|
- `routes`: Route definitions for web and MCP routes
|
|
142
180
|
|
|
143
181
|
## Routes
|
|
144
182
|
|
|
145
|
-
The ordinary web routes in `routes` are active:
|
|
146
|
-
|
|
147
183
|
```
|
|
148
|
-
GET
|
|
149
|
-
GET
|
|
184
|
+
GET / DemoApp.index
|
|
185
|
+
GET /health DemoApp.health
|
|
186
|
+
GET /mcp/users MCP users UserAPI.mcp_list_users
|
|
187
|
+
POST /mcp/create_user TOOL create_user UserAPI.mcp_create_user
|
|
150
188
|
```
|
|
151
189
|
|
|
152
|
-
The
|
|
153
|
-
|
|
154
|
-
they are not registered by this checkout's route-loading path.
|
|
190
|
+
The first two are ordinary web routes. The last two register the MCP resource
|
|
191
|
+
and tool described in [Resources and Tools](#resources-and-tools).
|
|
155
192
|
|
|
156
193
|
## Next Steps
|
|
157
194
|
|
|
158
195
|
- Build a CLI that communicates with the MCP endpoint
|
|
159
196
|
- Integrate with AI systems that support MCP
|
|
160
|
-
-
|
|
197
|
+
- Protect the endpoint with `mcp_auth_tokens`. `MCP` and `TOOL` routes cannot use
|
|
198
|
+
`auth=`, `role=`, or `csrf=`; see the [MCP guide](../../docs/guides/mcp.md#register-resources-and-tools)
|
|
161
199
|
- Explore [Advanced Routes](../advanced_routes/) for more routing patterns
|
data/examples/mcp_demo/app.rb
CHANGED
|
@@ -8,7 +8,7 @@ class DemoApp
|
|
|
8
8
|
res.headers['content-type'] = 'text/html; charset=utf-8'
|
|
9
9
|
res.body = <<~HTML
|
|
10
10
|
<h1>Otto MCP Demo</h1>
|
|
11
|
-
<p>This example demonstrates Otto's Model
|
|
11
|
+
<p>This example demonstrates Otto's Model Context Protocol (MCP) feature, which provides a JSON-RPC 2.0 endpoint for interacting with your application.</p>
|
|
12
12
|
<p>The MCP endpoint is available at: <code>POST /_mcp</code></p>
|
|
13
13
|
<p>See the <code>README.md</code> file for detailed `curl` commands to test the API.</p>
|
|
14
14
|
HTML
|
|
@@ -22,8 +22,10 @@ end
|
|
|
22
22
|
|
|
23
23
|
# UserAPI provides handlers for the MCP tool and resource routes.
|
|
24
24
|
class UserAPI
|
|
25
|
-
# MCP
|
|
26
|
-
#
|
|
25
|
+
# MCP resource "users" (routes: MCP users UserAPI.mcp_list_users).
|
|
26
|
+
# Read it with the JSON-RPC method resources/read and params {"uri": "users"}.
|
|
27
|
+
# A resource handler may instead take one argument, the Rack env of the MCP
|
|
28
|
+
# request, to check permissions per request.
|
|
27
29
|
def self.mcp_list_users
|
|
28
30
|
{
|
|
29
31
|
users: [
|
|
@@ -33,8 +35,9 @@ class UserAPI
|
|
|
33
35
|
}.to_json
|
|
34
36
|
end
|
|
35
37
|
|
|
36
|
-
# MCP
|
|
37
|
-
#
|
|
38
|
+
# MCP tool "create_user" (routes: TOOL create_user UserAPI.mcp_create_user).
|
|
39
|
+
# Call it with the JSON-RPC method tools/call and params
|
|
40
|
+
# {"name": "create_user", "arguments": {...}}.
|
|
38
41
|
def self.mcp_create_user(arguments, _env)
|
|
39
42
|
name = arguments['name'] || 'Anonymous'
|
|
40
43
|
email = arguments['email'] || "#{name.downcase}@example.com"
|
data/examples/mcp_demo/config.ru
CHANGED
|
@@ -3,7 +3,53 @@
|
|
|
3
3
|
require_relative '../../lib/otto'
|
|
4
4
|
require_relative 'app'
|
|
5
5
|
|
|
6
|
-
#
|
|
6
|
+
# Rack::Attack counts requests in a cache store and raises
|
|
7
|
+
# Rack::Attack::MissingStoreError without one. Outside Rails there is no
|
|
8
|
+
# default store, so this demo keeps the counts in process memory. Use a shared
|
|
9
|
+
# store (for example Redis) when the app runs in more than one process.
|
|
10
|
+
class DemoRateLimitStore
|
|
11
|
+
def initialize
|
|
12
|
+
@entries = {}
|
|
13
|
+
@mutex = Mutex.new
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def read(key)
|
|
17
|
+
@mutex.synchronize { live_value(key) }
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def write(key, value, expires_in: nil)
|
|
21
|
+
@mutex.synchronize { @entries[key] = [value, expires_in && (now + expires_in)] }
|
|
22
|
+
value
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Returns nil for a missing or expired key. Rack::Attack::Cache#do_count
|
|
26
|
+
# accepts nil from a store and writes the first count itself.
|
|
27
|
+
def increment(key, amount = 1, **)
|
|
28
|
+
@mutex.synchronize do
|
|
29
|
+
value = live_value(key)
|
|
30
|
+
value && (@entries[key][0] = value + amount)
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def delete(key)
|
|
35
|
+
@mutex.synchronize { @entries.delete(key) }
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
private
|
|
39
|
+
|
|
40
|
+
def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
41
|
+
|
|
42
|
+
def live_value(key)
|
|
43
|
+
value, expires_at = @entries[key]
|
|
44
|
+
return value unless expires_at && expires_at <= now
|
|
45
|
+
|
|
46
|
+
@entries.delete(key)
|
|
47
|
+
nil
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Initialize Otto with MCP support. MCP must be enabled when the routes file
|
|
52
|
+
# loads, or Otto skips its MCP and TOOL lines.
|
|
7
53
|
app = Otto.new('routes', {
|
|
8
54
|
mcp_enabled: true,
|
|
9
55
|
auth_tokens: ['demo-token-123', 'another-token-456'],
|
|
@@ -11,8 +57,9 @@ app = Otto.new('routes', {
|
|
|
11
57
|
tools_per_minute: 20,
|
|
12
58
|
})
|
|
13
59
|
|
|
14
|
-
# The `mcp_enabled: true` flag
|
|
15
|
-
#
|
|
60
|
+
# The `mcp_enabled: true` flag sets up the /_mcp endpoint. The routes file
|
|
61
|
+
# declares one MCP resource and one tool for it to serve.
|
|
16
62
|
|
|
63
|
+
Rack::Attack.cache.store = DemoRateLimitStore.new
|
|
17
64
|
use Rack::Attack
|
|
18
65
|
run app
|
data/examples/mcp_demo/routes
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
# Basic HTTP routes
|
|
2
|
-
GET /
|
|
3
|
-
GET /health
|
|
2
|
+
GET / DemoApp.index
|
|
3
|
+
GET /health DemoApp.health
|
|
4
4
|
|
|
5
|
-
# MCP
|
|
6
|
-
MCP
|
|
5
|
+
# MCP and TOOL declarations need a verb and a path to satisfy the route-file
|
|
6
|
+
# grammar, but they create no HTTP route. The single MCP endpoint (POST /_mcp)
|
|
7
|
+
# serves them.
|
|
7
8
|
|
|
8
|
-
# MCP
|
|
9
|
-
|
|
9
|
+
# MCP resource: read-only data, read with resources/read (uri "users")
|
|
10
|
+
GET /mcp/users MCP users UserAPI.mcp_list_users
|
|
11
|
+
|
|
12
|
+
# MCP tool: an action, called with tools/call (name "create_user")
|
|
13
|
+
POST /mcp/create_user TOOL create_user UserAPI.mcp_create_user
|
|
@@ -51,9 +51,9 @@ curl -i -X POST http://127.0.0.1:10770/feedback -d 'message=test'
|
|
|
51
51
|
|
|
52
52
|
The feedback handler rejects script-like input and limits messages to 1,000 characters; profile fields have their own limits and the email field must match the example's basic format check. The upload form demonstrates filename sanitization and request handling. It displays metadata and does **not** permanently store uploaded files; it does not implement a file-type allowlist.
|
|
53
53
|
|
|
54
|
-
###
|
|
54
|
+
### CSRF secret
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
`config.ru` does not set a CSRF secret. Without `OTTO_CSRF_SECRET`, Otto signs tokens with a secret generated for the process and logs a warning about it once, when it freezes the configuration on the first request. The forms on the home page include a token, so submitting the feedback form exercises the valid-token path.
|
|
57
57
|
|
|
58
58
|
## Files to inspect
|
|
59
59
|
|
|
@@ -132,16 +132,20 @@ class Otto
|
|
|
132
132
|
respond(req, res, allowed ? 200 : 403, allowed ? 'OK' : 'Forbidden')
|
|
133
133
|
end
|
|
134
134
|
|
|
135
|
-
#
|
|
135
|
+
# The body is set for HEAD too. Otto#call empties it for HEAD
|
|
136
|
+
# (Otto::Static.head_response) and sets content-length from this Array,
|
|
137
|
+
# so a HEAD response advertises the length a GET would send. An empty
|
|
138
|
+
# Array here would make that content-length 0.
|
|
139
|
+
#
|
|
140
|
+
# @param _req [Otto::Request] unused; kept for the existing signature
|
|
136
141
|
# @param res [Otto::Response]
|
|
137
142
|
# @param status [Integer]
|
|
138
143
|
# @param body [String]
|
|
139
144
|
# @return [Otto::Response]
|
|
140
|
-
def self.respond(
|
|
145
|
+
def self.respond(_req, res, status, body)
|
|
141
146
|
res.status = status
|
|
142
147
|
res['content-type'] = 'text/plain'
|
|
143
|
-
|
|
144
|
-
res.body = req.head? ? [] : [body]
|
|
148
|
+
res.body = [body]
|
|
145
149
|
res
|
|
146
150
|
end
|
|
147
151
|
end
|