Repository navigation
feat: bind stateful HTTP sessions to the creating principal - #420
EhsanAzish80 wants to merge 5 commits into
Conversation
Keep session response headers tied to the ID supplied by the request and let header validation run before malformed-body errors. Preserve supported-method precedence, add transport regression tests, and update the documentation.
varun06
left a comment
There was a problem hiding this comment.
Thanks for adding session principal binding — the opt-in API, byte-exact SessionOwner.admits(_:), identical 404 response matching SessionValidator, and clearing owner when initialize fails are all clean.
The shared validation/session-header items from the base branch are covered in the review on #419. Focusing on the session-principal binding changes (ea69c72), there is one blocking issue on terminated bound sessions and one should-fix on re-initialization requests — see inline comments below.
| if terminated { | ||
| let response = await validate(request) { | ||
| // A terminated session serves no request: its principal is not checked. | ||
| let validated = await validate(request, resolvingPrincipal: false) { | ||
| HTTPValidationContext( | ||
| method: request.method.uppercased(), sessionID: sessionID, | ||
| supportedProtocolVersions: Set(Version.handshake)) | ||
| } | ||
| return terminatedResponse(to: request, validated: response) | ||
| return terminatedResponse(to: request, validated: validated.response) | ||
| } |
There was a problem hiding this comment.
Blocking: terminatedResponse(to:validated:) (lines 558–572) does not account for bound sessions (owner != nil) and bypasses unverifiedEchoedSessionID(for:) / isExactly:
- Echoes bound
MCP-Session-Idwithout checking the principal: Whenterminatedistrue,validate(..., resolvingPrincipal: false)skipssessionPrincipal. If another principal ("mallory") sends the bound session'sMcp-Session-Idafter termination,SessionValidatorreturnsnil, andterminatedResponsesetssessionID: isTerminatedSession ? sessionID : nil— echoing the bound session ID to an unverified caller, contradicting the documented invariant (lines 272–274, 1095–1101,design/threat_model.md:64). - Confirms the bound session ID via the 404 body: A wrong session ID gets
"Not Found: Invalid or expired session ID"fromSessionValidator, whereas the real session ID from"mallory"gets"Not Found: Session has been terminated"fromterminatedResponse. - Uses
==instead ofisExactly: Line 563 (requestedSessionID == sessionID) uses canonical equivalence rather than exact bytes (also noted on fix: stop disclosing session IDs and validate headers before parsing #419).
Suggested fix in terminatedResponse(to:validated:):
private func terminatedResponse(to request: HTTPRequest, validated response: HTTPResponse?) -> HTTPResponse {
if let response {
return withoutSessionHeader(response)
}
let hasEndedSession = sessionID != nil && request.value(forHeader: HTTPHeaderName.sessionID) != nil
if owner != nil, hasEndedSession {
return Self.unknownSessionResponse
}
return .error(
statusCode: hasEndedSession ? 404 : 400,
.invalidRequest(hasEndedSession
? "Not Found: Session has been terminated"
: "Bad Request: No active session"),
sessionID: unverifiedEchoedSessionID(for: request)
)
}| if response == nil, resolvingPrincipal, let sessionPrincipal, | ||
| context.isInitializeRequest || owner != nil | ||
| { | ||
| principal = await sessionPrincipal(request) | ||
| } |
There was a problem hiding this comment.
Should-fix: When a session is already established (context.sessionID != nil) and a second initialize request arrives, SessionValidator skips it (response == nil) and context.isInitializeRequest || owner != nil is true, so validate still calls await sessionPrincipal(request).
Immediately afterward, line 540 skips owner.admits(principal) because !context.isInitializeRequest is false, and handleInitializationRequest (lines 692–698) unconditionally rejects the request with 400 and discards validated.principal. That triggers an unnecessary async call (and actor suspension) for a rejected request that never uses the session.
Restricting initialize principal resolution to when no session exists yet avoids this (and if a session is dropped/created concurrently, the stateGeneration check on line 536 re-runs the loop):
if response == nil, resolvingPrincipal, let sessionPrincipal,
context.isInitializeRequest ? context.sessionID == nil : owner != nil
{
principal = await sessionPrincipal(request)
}| @Test("sessionPrincipal runs only for requests the validators accept and that use a bound session") | ||
| func resolverCalls() async throws { | ||
| let calls = PrincipalCalls() | ||
| let transport = try await makeTransport( | ||
| validators: [OriginValidator.localhost(), SessionValidator()], | ||
| sessionPrincipal: { request in | ||
| await calls.record() | ||
| return request.value(forHeader: Self.principalHeader) | ||
| }) | ||
| let sessionID = try await initialize(transport, as: "alice") | ||
| #expect(await calls.count == 1) | ||
|
|
||
| var badOrigin = headers(sessionID: sessionID, principal: "alice") | ||
| badOrigin[HTTPHeaderName.origin] = "https://attacker.example" | ||
| let rejected = await transport.handleRequest( | ||
| HTTPRequest(method: "POST", headers: badOrigin, body: Self.notificationBody)) | ||
| #expect(rejected.statusCode == 403) | ||
| #expect(await calls.count == 1) | ||
|
|
||
| _ = await transport.handleRequest( | ||
| HTTPRequest(method: "PUT", headers: headers(sessionID: sessionID, principal: "alice"))) | ||
| #expect(await calls.count == 1) | ||
|
|
||
| #expect(await notify(transport, sessionID: sessionID, as: "alice").statusCode == 202) | ||
| #expect(await calls.count == 2) | ||
| await transport.disconnect() | ||
| } |
There was a problem hiding this comment.
A few additional test cases worth covering in this suite:
- Terminated bound session: After
DELETEordisconnect(), verify thatPOST/GET/DELETEwith the bound session'sMcp-Session-Idfrom another principal (ornil) returns404withheaders[HTTPHeaderName.sessionID] == niland the same body as an unknown session. - No
sessionPrincipalcall on re-initialization: Send a secondinitializehere inresolverCallsand assertcalls.countdoes not increment. - Concurrent state change while
sessionPrincipalsuspends: Verify that ifstateGenerationchanges (e.g. a refusedinitializedrops the session or a concurrentinitializecreates it) whilesessionPrincipalis suspended,validatere-runs against the updated state.
…lenges Address review on modelcontextprotocol#420 for the modelcontextprotocol#419 code: the stateful transport echoes the session ID on validator responses only for errors, so ServerCardResponder and other 2xx/304 answers that shared caches may store never carry it; a Bearer 400 challenge (RFC 6750 §3.1) on an unsupported method is returned instead of 405. Add tests for ProtocolVersionValidator, parse errors without SessionValidator, and stateless header rejections before parsing.
ea69c72 to
9cf132c
Compare
Keep responder statuses and headers intact on unsupported methods. Align session header handling and documentation with the validator lifecycle, with regression coverage for both HTTP transports.
9cf132c to
95c4c1b
Compare
varun06
left a comment
There was a problem hiding this comment.
Everything from the previous review looks addressed — leaving one minor doc-comment nit inline.
| /// Terminates the session, closing all active streams. | ||
| /// After validation, requests without a session ID get 400; if a session | ||
| /// existed, requests with any session ID get 404. | ||
| /// Closes the streams of a session a refused `initialize` dropped and | ||
| /// forgets its stored events, so a session created next on this transport, | ||
| /// possibly by another principal, gets none of them. `eventCounter` and | ||
| /// `streamGenerationCounter` keep counting, so a stale stream's | ||
| /// termination cannot touch the next session's streams. | ||
| private func dropSessionStreams() { |
There was a problem hiding this comment.
Nit: Lines 1172–1174 (/// Terminates the session...) belong to terminate() below (line 1197) — moving those three lines back above private func terminate() keeps both doc comments attached to the right method.
Add an opt-in sessionPrincipal closure to StatefulHTTPServerTransport. The transport records the principal of the initialize request that creates the session and answers later POST, GET (including Last-Event-ID resumption) and DELETE requests from another principal with the 404 of an unknown session. On a bound session, responses to requests not yet checked against the principal do not carry the session ID. Without the closure, behavior is unchanged.
95c4c1b to
8221ffe
Compare
|
Good catch @varun06 , thanks. Moved the terminate() doc comment back above it; dropSessionStreams() keeps its own. |
Depends on #419 (based on 872c930; until #419 merges, its two commits show here too).
Summary
Adds an opt-in
sessionPrincipalclosure toStatefulHTTPServerTransportthat binds asession to the principal that created it. Today any request that passes the validators and
carries a session ID can use the session;
docs/protocol.mdasks apps to enforce binding intheir own router. This moves that into the transport, so routers and apps that use the
transport directly get it with one parameter.
Behavior
initializerequest that creates the session.Last-Event-IDresumption) or DELETE from another principalgets the 404 that
SessionValidatorgives an unknown session (same status, headers andJSON body), so the response does not confirm the ID. Principals are compared byte for
byte, and
nilonly matchesnil.(validator rejections, 405, a second
initialize, stateless-version 400) do not echo thesession ID.
stateGenerationre-validation loop, so the reentrancy guarantees hold. It is not calledfor rejected requests, unsupported methods, stateless-version requests or a terminated
session.
initializedrops the binding along with the session.API
StatefulHTTPServerTransport.SessionPrincipal(
@Sendable (HTTPRequest) async -> String?)sessionPrincipal: SessionPrincipal? = nilon the init, beforelogger:. The twotombstone doc links are updated. Additive and source compatible.
The docs say to derive the principal only from credentials a validator verified. A header
the client sets freely would let any caller claim the session.
Known trade-offs
case and not the other.
HTTPRequest, not the verifiedBearerTokenInfo, so appsdecode the token again. A
subjectfield onBearerTokenInfois a possible follow-up.format, and binding already makes guessed IDs useless to another principal.
Tests
New
SessionPrincipalBindingTests(10): the owner keeps access; another principal gets 404on POST, GET and DELETE, and a refused DELETE leaves the session alive; a resume from
another principal is refused and the owner keeps its stream; the refusal matches an unknown
session's 404; byte-exact comparison (Kelvin sign);
nilbinding; unbound by default; noecho before the check; a refused
initializeresets the binding; when the closure iscalled. No existing tests changed.
swift test(2,170 SDK + 134 snippet tests); focused suites 5 consecutive runsgreen
docs, all conformance legs,interop(scripts/ci/run-jobs.sh)swift scripts/weave.swift --checkDocs:
protocol(Session hijacking, stateful transport),threat_model.md, CHANGELOG(Features).
AI disclosure
AI tools helped write this change. I reviewed all of it.