Skip to content

feat: bind stateful HTTP sessions to the creating principal - #420

Open
EhsanAzish80 wants to merge 5 commits into
modelcontextprotocol:rel/1.0.0from
EhsanAzish80:feat/session-principal-binding
Open

EhsanAzish80 wants to merge 5 commits into
modelcontextprotocol:rel/1.0.0from
EhsanAzish80:feat/session-principal-binding

Conversation

@EhsanAzish80

Copy link
Copy Markdown
Contributor

Depends on #419 (based on 872c930; until #419 merges, its two commits show here too).

Summary

Adds an opt-in sessionPrincipal closure to StatefulHTTPServerTransport that binds a
session to the principal that created it. Today any request that passes the validators and
carries a session ID can use the session; docs/protocol.md asks apps to enforce binding in
their own router. This moves that into the transport, so routers and apps that use the
transport directly get it with one parameter.

StatefulHTTPServerTransport(
    validators: [..., BearerTokenValidator(...), SessionValidator()],
    sessionPrincipal: { request in /* subject of the token the validator verified */ })

Behavior

  • The transport records the principal of the initialize request that creates the session.
  • A later POST, GET (including Last-Event-ID resumption) or DELETE from another principal
    gets the 404 that SessionValidator gives an unknown session (same status, headers and
    JSON body), so the response does not confirm the ID. Principals are compared byte for
    byte, and nil only matches nil.
  • On a bound session, responses to requests not yet checked against the principal
    (validator rejections, 405, a second initialize, stateless-version 400) do not echo the
    session ID.
  • The closure runs only after the validators accept the request, inside the existing
    stateGeneration re-validation loop, so the reentrancy guarantees hold. It is not called
    for rejected requests, unsupported methods, stateless-version requests or a terminated
    session.
  • A refused initialize drops the binding along with the session.
  • Without the closure, behavior is unchanged.

API

  • StatefulHTTPServerTransport.SessionPrincipal
    (@Sendable (HTTPRequest) async -> String?)
  • sessionPrincipal: SessionPrincipal? = nil on the init, before logger:. The two
    tombstone 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

  • A refused principal and an unknown ID can differ in timing, since the closure runs in one
    case and not the other.
  • The closure receives the HTTPRequest, not the verified BearerTokenInfo, so apps
    decode the token again. A subject field on BearerTokenInfo is a possible follow-up.
  • Unguessable event IDs were left out on purpose. About 15 existing tests check the event ID
    format, and binding already makes guessed IDs useless to another principal.

Tests

New SessionPrincipalBindingTests (10): the owner keeps access; another principal gets 404
on 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); nil binding; unbound by default; no
echo before the check; a refused initialize resets the binding; when the closure is
called. No existing tests changed.

  • macOS: swift test (2,170 SDK + 134 snippet tests); focused suites 5 consecutive runs
    green
  • docs, all conformance legs, interop (scripts/ci/run-jobs.sh)
  • Linux (Swift 6.1, RHEL UBI 9): focused HTTP suites, 123 tests
  • swift scripts/weave.swift --check

Docs: protocol (Session hijacking, stateful transport), threat_model.md, CHANGELOG
(Features).

AI disclosure

AI tools helped write this change. I reviewed all of it.

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.
@EhsanAzish80
EhsanAzish80 requested a review from a team as a code owner December 6, 2026 10:40

@varun06 varun06 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 442 to 450
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: terminatedResponse(to:validated:) (lines 558–572) does not account for bound sessions (owner != nil) and bypasses unverifiedEchoedSessionID(for:) / isExactly:

  1. Echoes bound MCP-Session-Id without checking the principal: When terminated is true, validate(..., resolvingPrincipal: false) skips sessionPrincipal. If another principal ("mallory") sends the bound session's Mcp-Session-Id after termination, SessionValidator returns nil, and terminatedResponse sets sessionID: 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).
  2. Confirms the bound session ID via the 404 body: A wrong session ID gets "Not Found: Invalid or expired session ID" from SessionValidator, whereas the real session ID from "mallory" gets "Not Found: Session has been terminated" from terminatedResponse.
  3. Uses == instead of isExactly: 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)
    )
}

Comment on lines +531 to +535
if response == nil, resolvingPrincipal, let sessionPrincipal,
context.isInitializeRequest || owner != nil
{
principal = await sessionPrincipal(request)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
}

Comment on lines +223 to +249
@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()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few additional test cases worth covering in this suite:

  1. Terminated bound session: After DELETE or disconnect(), verify that POST/GET/DELETE with the bound session's Mcp-Session-Id from another principal (or nil) returns 404 with headers[HTTPHeaderName.sessionID] == nil and the same body as an unknown session.
  2. No sessionPrincipal call on re-initialization: Send a second initialize here in resolverCalls and assert calls.count does not increment.
  3. Concurrent state change while sessionPrincipal suspends: Verify that if stateGeneration changes (e.g. a refused initialize drops the session or a concurrent initialize creates it) while sessionPrincipal is suspended, validate re-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.
@EhsanAzish80
EhsanAzish80 force-pushed the feat/session-principal-binding branch from ea69c72 to 9cf132c Compare December 6, 2026 13:43
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.
@EhsanAzish80
EhsanAzish80 force-pushed the feat/session-principal-binding branch from 9cf132c to 95c4c1b Compare December 6, 2026 14:03

@varun06 varun06 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Everything from the previous review looks addressed — leaving one minor doc-comment nit inline.

Comment on lines +1172 to +1180
/// 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() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@EhsanAzish80
EhsanAzish80 force-pushed the feat/session-principal-binding branch from 95c4c1b to 8221ffe Compare December 6, 2026 16:07
@EhsanAzish80

Copy link
Copy Markdown
Contributor Author

Good catch @varun06 , thanks. Moved the terminate() doc comment back above it; dropSessionStreams() keeps its own.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants