ruby-sdk/lib/mcp/server/request_state_security.rb
Koichi ITO e6b5a9b5e3 Add opt-in requestState sealing via RequestStateSecurity
## Motivation and Context

The SEP-2322 `requestState` continuation string leaves the server, sits in the client's hands,
and comes back as client-controlled input. Without protection a client can read the server's continuation state,
tamper with it (for example forging an already-answered elicitation), or replay a state issued for one call against
another tool, other arguments, or another server. The multi-round-trip documentation of the Python SDK is explicit
that the echo must be treated as untrusted input; its high-level server seals the state by default via `RequestStateBoundary`.

New `MCP::Server::RequestStateSecurity` (OpenSSL standard library only) brings that protection to this SDK as an opt-in:

- `seal` encrypts the plaintext state with AES-256-GCM (clients cannot read it, not merely verify it) inside a claims
  envelope binding an expiry window (`ttl:`, default 300 seconds, re-sealed each round), the originating method and target
  (tool/prompt name or resource URI), a digest of the originating arguments (stringified and sorted recursively,
  so symbol/string parses of identical JSON digest identically), and an optional `audience:`. The token format is
  `v1.<base64url(iv || ciphertext || tag)>` with the version prefix bound as GCM associated data,
  following the Python SDK's `AESGCMRequestStateCodec`.
- `unseal` verifies every claim fail-closed and raises `InvalidStateError` on tampering, expiry, or any mismatch.

Passing an instance via `Server.new(request_state_security:)` makes the seal/unseal transparent: issuance seals
the `requestState` of an outgoing `input_required` result, and dispatch unseals the echoed token for `tools/call`,
`prompts/get`, and `resources/read` before any handler runs, so `server_context.request_state` always reads
the plaintext the handler wrote. A tampered, expired, or cross-call echo is rejected as `-32602`
with "Invalid or expired requestState", matching the Python SDK's frozen error.

Without the option the state crosses the wire exactly as the handler wrote it (the Python low-level Server behavior);
the README documents that this is then the handler author's responsibility, and that multi-process deployments
must share the key across workers.

The conformance fixture opts in with a random per-boot key, both to dogfood the feature and because
the tampered-state scenario of the 2026-07-28 conformance requirements retries an MRTR request with
a corrupted `requestState` and requires a JSON-RPC error; without integrity-checked state the fixture
cannot detect the corruption. Every MRTR round trip completes within one server process,
so no key persistence is needed. Sealing is transparent to the fixture tools, whose `requestState` plaintext
round-trips unchanged, and the new `test_input_required_result_tampered_state` tool is therefore
a plain MRTR elicitation flow; the tampered echo is rejected with `-32602` by the server-level unsealing
before dispatch ever reaches it.

Refs #382.

## How Has This Been Tested?

New `test/mcp/server/request_state_security_test.rb` covers constructor validation,
the seal/unseal round trip (opaque `v1.` token, plaintext not visible), expiry via time travel,
fail-closed rejection of method/target/digest/audience mismatches, tampered and malformed tokens,
and tokens sealed under a different key.

New tests in `test/mcp/server_test.rb` drive `Server#handle` with the modern envelope:
transparent sealing on issuance and plaintext restoration on the retry leg, `-32602` for
tampered echoes and for echoes replayed against different arguments, and the pass-through
default when `request_state_security:` is not set.

Against the fixture server at `--spec-version 2026-07-28` (run with `@modelcontextprotocol/conformance@alpha`;
the 2026-07-28 scenarios are not yet in a stable conformance release), `sep-2322-reject-tampered-state` reports SUCCESS,
and the other 13 `input-required-result-*` scenarios stay green with sealing active,
confirming that sealed states round-trip through the suite's retries without false rejections
(the seal binds `method`, target, and an arguments digest, and the suite echoes all three unchanged).
The `--requirements 2025-11-25` server leg still passes.

## Breaking Changes

None. The feature is opt-in via a new keyword argument that defaults to `nil`, in which case behavior is byte-identical to before.
2026-08-08 18:54:14 +09:00

131 lines
5.2 KiB
Ruby

# frozen_string_literal: true
require "json"
require "openssl"
module MCP
class Server
# Opt-in protection for the SEP-2322 `requestState` echo. The opaque continuation string leaves the server,
# sits in the client's hands, and comes back as client-controlled input, so it must be treated like
# any other untrusted data. Sealing encrypts the state with AES-256-GCM (clients cannot read it) and binds
# a claims envelope that unsealing verifies fail-closed:
#
# - `exp`: a TTL window (re-sealed each round)
# - `m` / `t`: the originating method and target (tool/prompt name or resource URI)
# - `a`: a digest of the originating arguments, so the state only resumes the same call with the same inputs
# - `aud`: an optional audience, so tokens cannot cross servers sharing a key
#
# Pass an instance via `Server.new(request_state_security:)` and the seal/unseal happens transparently;
# handlers keep reading plaintext through `server_context.request_state`. Without it, the state crosses
# the wire exactly as the handler wrote it (the author's responsibility, matching the Python SDK's low-level Server).
# The key must be shared across workers in multi-process
#
# deployments; a per-process random key makes retries that land on another worker fail with an invalid-state error,
# forcing clients to restart the flow.
#
# The token format is `v1.<base64url(iv || ciphertext || tag)>`, with the version prefix bound as GCM associated data,
# following the Python SDK's `AESGCMRequestStateCodec`.
class RequestStateSecurity
class InvalidStateError < StandardError; end
VERSION_PREFIX = "v1."
KEY_BYTES = 32
IV_BYTES = 12
TAG_BYTES = 16
DEFAULT_TTL = 300
def initialize(key:, ttl: DEFAULT_TTL, audience: nil)
unless key.is_a?(String) && key.bytesize == KEY_BYTES
raise ArgumentError, "key must be a #{KEY_BYTES}-byte String"
end
unless ttl.is_a?(Numeric) && ttl.positive?
raise ArgumentError, "ttl must be a positive number of seconds"
end
@key = key.dup.force_encoding(Encoding::BINARY).freeze
@ttl = ttl
@audience = audience
end
# Seals a plaintext state into an opaque token bound to the originating request.
def seal(state, method:, target:, arguments_digest:)
claims = {
v: 1,
exp: Time.now.to_i + @ttl,
m: method,
t: target,
a: arguments_digest,
aud: @audience,
s: state,
}.compact
cipher = OpenSSL::Cipher.new("aes-256-gcm").encrypt
cipher.key = @key
iv = cipher.random_iv
cipher.auth_data = VERSION_PREFIX
ciphertext = cipher.update(JSON.generate(claims)) + cipher.final
VERSION_PREFIX + base64url_encode(iv + ciphertext + cipher.auth_tag)
end
# Unseals a client-echoed token and verifies every claim, failing closed with
# `InvalidStateError` on tampering, expiry, or a claims mismatch.
def unseal(sealed, method:, target:, arguments_digest:)
unless sealed.is_a?(String) && sealed.start_with?(VERSION_PREFIX)
raise InvalidStateError, "malformed token"
end
blob = base64url_decode(sealed.delete_prefix(VERSION_PREFIX))
raise InvalidStateError, "malformed token" if blob.bytesize < IV_BYTES + TAG_BYTES
iv = blob.byteslice(0, IV_BYTES)
tag = blob.byteslice(-TAG_BYTES, TAG_BYTES)
ciphertext = blob.byteslice(IV_BYTES, blob.bytesize - IV_BYTES - TAG_BYTES)
cipher = OpenSSL::Cipher.new("aes-256-gcm").decrypt
cipher.key = @key
cipher.iv = iv
cipher.auth_tag = tag
cipher.auth_data = VERSION_PREFIX
plaintext = begin
cipher.update(ciphertext) + cipher.final
rescue OpenSSL::Cipher::CipherError
raise InvalidStateError, "authentication failed"
end
claims = begin
JSON.parse(plaintext, symbolize_names: true)
rescue JSON::ParserError
raise InvalidStateError, "malformed claims"
end
verify!(claims, method: method, target: target, arguments_digest: arguments_digest)
claims[:s]
end
private
def verify!(claims, method:, target:, arguments_digest:)
raise InvalidStateError, "unsupported version" unless claims[:v] == 1
raise InvalidStateError, "expired" unless claims[:exp].is_a?(Integer) && Time.now.to_i <= claims[:exp]
raise InvalidStateError, "method mismatch" unless claims[:m] == method
raise InvalidStateError, "target mismatch" unless claims[:t] == target
raise InvalidStateError, "arguments mismatch" unless claims[:a] == arguments_digest
raise InvalidStateError, "audience mismatch" unless claims[:aud] == @audience
raise InvalidStateError, "missing state" unless claims[:s].is_a?(String)
end
def base64url_encode(data)
[data].pack("m0").tr("+/", "-_").delete("=")
end
def base64url_decode(encoded)
padded = encoded.tr("-_", "+/")
padded += "=" * ((4 - padded.length % 4) % 4)
padded.unpack1("m0")
rescue ArgumentError
raise InvalidStateError, "malformed token"
end
end
end
end