Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions lib/mcp/server/request_state_security.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ 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"
unless ttl.is_a?(Numeric) && ttl.finite? && ttl.positive?
raise ArgumentError, "ttl must be a positive, finite number of seconds"
end

@key = key.dup.force_encoding(Encoding::BINARY).freeze
Expand All @@ -51,7 +51,8 @@ def initialize(key:, ttl: DEFAULT_TTL, audience: nil)
def seal(state, method:, target:, arguments_digest:)
claims = {
v: 1,
exp: Time.now.to_i + @ttl,
# Whole seconds, as `verify!` requires: an `Integer` TTL keeps its exact value, a fractional one ends within the second it falls in.
exp: (Time.now + @ttl).to_i,
m: method,
t: target,
a: arguments_digest,
Expand Down
20 changes: 20 additions & 0 deletions test/mcp/server/request_state_security_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,26 @@ class RequestStateSecurityTest < ActiveSupport::TestCase
assert_raises(ArgumentError) { RequestStateSecurity.new(key: KEY, ttl: 0) }
end

test "rejects a ttl that is not finite" do
assert_raises(ArgumentError) { RequestStateSecurity.new(key: KEY, ttl: Float::INFINITY) }
assert_raises(ArgumentError) { RequestStateSecurity.new(key: KEY, ttl: Float::NAN) }
end

test "unseals a token sealed with a fractional ttl until it expires" do
[30.5, 60.0, Rational(5, 2)].each do |ttl|
security = RequestStateSecurity.new(key: KEY, ttl: ttl)
sealed = security.seal("state", method: "tools/call", target: "t", arguments_digest: "d")

assert_equal "state", security.unseal(sealed, method: "tools/call", target: "t", arguments_digest: "d")

travel ttl + 2 do
assert_raises(RequestStateSecurity::InvalidStateError) do
security.unseal(sealed, method: "tools/call", target: "t", arguments_digest: "d")
end
end
end
end

test "seals and unseals a state bound to the originating request" do
security = RequestStateSecurity.new(key: KEY, audience: "my_server")
sealed = security.seal("plain-state", method: "tools/call", target: "my_tool", arguments_digest: "digest")
Expand Down