From bbaae47359db1dc1b3dac90d8fd897dcd2aed889 Mon Sep 17 00:00:00 2001 From: EhsanAzish80 Date: Sun, 6 Dec 2026 12:14:38 +0300 Subject: [PATCH 1/5] fix: stop disclosing session IDs and validate headers before parsing 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. --- CHANGELOG.md | 5 + .../HTTPServer/HTTPRequestValidation.swift | 53 ++-- .../HTTPServer/HTTPServerTypes.swift | 3 +- .../StatefulHTTPServerTransport.swift | 85 +++--- .../StatelessHTTPServerTransport.swift | 47 ++-- Tests/MCPTests/SessionIDDisclosureTests.swift | 255 ++++++++++++++++++ design/design.md | 2 +- design/threat_model.md | 6 +- docs/protocol.md | 4 +- docs/src/protocol.src.md | 4 +- docs/src/troubleshooting.src.md | 6 +- docs/troubleshooting.md | 6 +- 12 files changed, 380 insertions(+), 96 deletions(-) create mode 100644 Tests/MCPTests/SessionIDDisclosureTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 98178e31..cdf0f941 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -400,6 +400,11 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha ### Fixes +- HTTP server transports now return header validation errors before malformed-body errors. + On unsupported methods, validator responses with status 401, 403 or 421 take precedence over 405. + The stateful transport no longer echoes a session ID to callers that did not provide it in + validator, parse, method, re-initialization, stream-conflict or invalid event-ID errors, + and no longer logs raw session IDs. - Prompt message content blocks keep `annotations` and `meta`, and `resourceLink` blocks keep `size`, `icons`, and `meta`. - `Response.id` (`ID?`) represents JSON `null` distinctly from `""`, and rejects a `null` ID on a diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift index 4cdb9a4b..25178b77 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPRequestValidation.swift @@ -174,7 +174,7 @@ public struct AcceptHeaderValidator: HTTPRequestValidator { .invalidRequest( "Not Acceptable: Client must accept both application/json and text/event-stream" ), - sessionID: context.sessionID + sessionID: nil ) } case .requiresJSON: @@ -184,7 +184,7 @@ public struct AcceptHeaderValidator: HTTPRequestValidator { .invalidRequest( "Not Acceptable: Client must accept application/json" ), - sessionID: context.sessionID + sessionID: nil ) } } @@ -195,7 +195,7 @@ public struct AcceptHeaderValidator: HTTPRequestValidator { .invalidRequest( "Not Acceptable: Client must accept text/event-stream" ), - sessionID: context.sessionID + sessionID: nil ) } default: @@ -233,7 +233,7 @@ public struct ContentTypeValidator: HTTPRequestValidator { .invalidRequest( "Unsupported Media Type: Content-Type must be application/json" ), - sessionID: context.sessionID + sessionID: nil ) } @@ -287,7 +287,7 @@ public struct ProtocolVersionValidator: HTTPRequestValidator { return .error( statusCode: 400, .headerMismatch("\(HTTPHeaderName.protocolVersion) appears more than once"), - sessionID: context.sessionID + sessionID: nil ) } } @@ -298,7 +298,7 @@ public struct ProtocolVersionValidator: HTTPRequestValidator { .unsupportedProtocolVersion( supported: context.supportedProtocolVersions.sorted(by: >), requested: version), - sessionID: context.sessionID + sessionID: nil ) } @@ -344,15 +344,15 @@ public struct SessionValidator: HTTPRequestValidator { return .error( statusCode: 400, .invalidRequest("Bad Request: Missing \(HTTPHeaderName.sessionID) header"), - sessionID: expectedSessionID + sessionID: nil ) } - guard requestSessionID == expectedSessionID else { + guard requestSessionID.isExactly(expectedSessionID) else { return .error( statusCode: 404, .invalidRequest("Not Found: Invalid or expired session ID"), - sessionID: expectedSessionID + sessionID: nil ) } @@ -447,7 +447,7 @@ public struct OriginValidator: HTTPRequestValidator { return .error( statusCode: 421, .invalidRequest("Misdirected Request: Host header not allowed"), - sessionID: context.sessionID + sessionID: nil ) } } @@ -461,7 +461,7 @@ public struct OriginValidator: HTTPRequestValidator { return .error( statusCode: 403, .invalidRequest("Forbidden: Origin not allowed"), - sessionID: context.sessionID + sessionID: nil ) } } @@ -762,13 +762,11 @@ public struct BearerTokenValidator: HTTPRequestValidator { return unauthorizedResponse( challengeScope: challengeScopeProvider?(request, context), error: nil, - errorDescription: nil, - sessionID: context.sessionID + errorDescription: nil ) case .malformed(let message): return invalidRequestResponse( - message: message, challengeScope: challengeScopeProvider?(request, context), - sessionID: context.sessionID) + message: message, challengeScope: challengeScopeProvider?(request, context)) } switch await tokenVerifier(parsedToken, request, context).outcome { @@ -778,8 +776,7 @@ public struct BearerTokenValidator: HTTPRequestValidator { return unauthorizedResponse( challengeScope: challengeScopeProvider?(request, context), error: "invalid_token", - errorDescription: "Token has expired", - sessionID: context.sessionID + errorDescription: "Token has expired" ) } // Audience check — skipped for opaque tokens (audience == nil) @@ -793,8 +790,7 @@ public struct BearerTokenValidator: HTTPRequestValidator { return unauthorizedResponse( challengeScope: challengeScopeProvider?(request, context), error: "invalid_token", - errorDescription: "Token audience mismatch", - sessionID: context.sessionID + errorDescription: "Token audience mismatch" ) } } @@ -804,28 +800,26 @@ public struct BearerTokenValidator: HTTPRequestValidator { return unauthorizedResponse( challengeScope: challengeScopeProvider?(request, context), error: "invalid_token", - errorDescription: errorDescription, - sessionID: context.sessionID + errorDescription: errorDescription ) case .insufficientScope(let requiredScopes, let errorDescription): return forbiddenInsufficientScopeResponse( requiredScopes: requiredScopes, - errorDescription: errorDescription, - sessionID: context.sessionID + errorDescription: errorDescription ) case .malformedRequest(let errorDescription): return invalidRequestResponse( message: errorDescription ?? "Malformed authorization request", - challengeScope: challengeScopeProvider?(request, context), sessionID: context.sessionID) + challengeScope: challengeScopeProvider?(request, context)) } } /// 400 with a Bearer challenge carrying `error="invalid_request"` /// (RFC 6750 §3.1), so the client still learns `resource_metadata`. private func invalidRequestResponse( - message: String, challengeScope: Set?, sessionID: String? + message: String, challengeScope: Set? ) -> HTTPResponse { let challenge = makeBearerChallenge( resourceMetadataURL: resourceMetadataURL, @@ -836,7 +830,6 @@ public struct BearerTokenValidator: HTTPRequestValidator { return .error( statusCode: 400, .invalidRequest("Bad Request: \(message)"), - sessionID: sessionID, extraHeaders: [HTTPHeaderName.wwwAuthenticate: challenge] ) } @@ -844,8 +837,7 @@ public struct BearerTokenValidator: HTTPRequestValidator { private func unauthorizedResponse( challengeScope: Set?, error: String?, - errorDescription: String?, - sessionID: String? + errorDescription: String? ) -> HTTPResponse { let challenge = makeBearerChallenge( resourceMetadataURL: resourceMetadataURL, @@ -856,15 +848,13 @@ public struct BearerTokenValidator: HTTPRequestValidator { return .error( statusCode: 401, .invalidRequest("Unauthorized"), - sessionID: sessionID, extraHeaders: [HTTPHeaderName.wwwAuthenticate: challenge] ) } private func forbiddenInsufficientScopeResponse( requiredScopes: Set, - errorDescription: String?, - sessionID: String? + errorDescription: String? ) -> HTTPResponse { let challenge = makeBearerChallenge( resourceMetadataURL: resourceMetadataURL, @@ -875,7 +865,6 @@ public struct BearerTokenValidator: HTTPRequestValidator { return .error( statusCode: 403, .invalidRequest("Forbidden: Insufficient scope"), - sessionID: sessionID, extraHeaders: [HTTPHeaderName.wwwAuthenticate: challenge] ) } diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift index 2c3cb628..3c683f8a 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift @@ -320,7 +320,8 @@ public struct HTTPResponse: Sendable { /// - statusCode: The HTTP status code of the response. /// - error: The JSON-RPC error to encode in the response body. /// - id: The JSON-RPC request ID, or `nil` when absent or unknown. - /// - sessionID: The active session ID to send in `MCP-Session-Id`, if any. + /// - sessionID: The session ID to echo only when the request carried that same ID, + /// or to send on a successful initialization response. /// - extraHeaders: Additional response headers merged into the response. /// - Returns: An HTTP response carrying the encoded JSON-RPC error body. public static func error( diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift index ca0f068d..8be410aa 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift @@ -347,7 +347,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // A refused `initialize` (for example by the server's // initialize hook) leaves no session behind. if JSONRPCMessageFields.errorCode(in: data) != nil { - logger.info("Initialization failed; session dropped", metadata: ["sessionID": "\(sessionID ?? "none")"]) + logger.info("Initialization failed; session dropped") sessionID = nil stateGeneration += 1 } @@ -383,7 +383,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { /// - **POST**: JSON-RPC messages (requests, notifications) /// - **GET**: Establish standalone SSE stream for server-initiated messages /// - **DELETE**: Terminate the session - /// - Others: 405 Method Not Allowed + /// - Others: a successful validator response, 401, 403 or 421; otherwise 405 /// /// The transport handles other requests while this one's validators /// suspend. A request whose session ends while its validators run gets @@ -418,13 +418,16 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { supportedProtocolVersions: Set(Version.handshake)) } guard !terminated else { return terminatedResponse(to: request, validated: response) } - if let response, (200..<300).contains(response.statusCode) || response.statusCode == 304 { + if let response, + (200..<300).contains(response.statusCode) || response.statusCode == 304 + || response.statusCode == 401 || response.statusCode == 403 || response.statusCode == 421 + { return response } return .error( statusCode: 405, .invalidRequest("Method Not Allowed"), - sessionID: sessionID, + sessionID: echoedSessionID(for: request), extraHeaders: [HTTPHeaderName.allow: "GET, POST, DELETE"] ) } @@ -452,7 +455,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { for _ in 0.. HTTPResponse { - // Parse body first so we can determine if it's an initialization request - guard let body = request.body, !body.isEmpty else { - return .error( - statusCode: 400, - .parseError("Empty request body"), - sessionID: sessionID - ) - } - - guard let messageKind = JSONRPCMessageKind(data: body) else { - return .error( - statusCode: 400, - JSONRPCMessageKind.classificationError(for: body), - sessionID: sessionID - ) - } + // Classify the body to tell validators whether this is initialize, + // but let them reject the headers before returning a parse error. + let body = request.body + let messageKind = body.flatMap(JSONRPCMessageKind.init(data:)) // Requests at 2026-07-28 and later carry no session; this transport // serves handshake revisions only, whether the stateless version is @@ -506,7 +497,8 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // get -32022, whose data lets the client fall back to `initialize`. // Validators see the handshake revisions, the ones this transport // serves, so the context does not change with `Version.supported`. - if case .request(let id, _) = messageKind, !messageKind.isInitializeRequest, + if let body, let messageKind, case .request(let id, _) = messageKind, + !messageKind.isInitializeRequest, let version = request.statelessProtocolVersion ?? JSONRPCMessageFields.metaProtocolVersion(in: body).flatMap({ Version.handshake.contains($0) ? nil : $0 @@ -522,12 +514,11 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { return errorResponse } // Echo the session ID only to a client that already holds it. - let knownSession = request.value(forHeader: HTTPHeaderName.sessionID) == sessionID ? sessionID : nil return .error( statusCode: 400, .unsupportedProtocolVersion(supported: Version.handshake, requested: version), id: id, - sessionID: knownSession + sessionID: echoedSessionID(for: request) ) } @@ -535,7 +526,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { HTTPValidationContext( method: "POST", sessionID: sessionID, - isInitializeRequest: messageKind.isInitializeRequest, + isInitializeRequest: messageKind?.isInitializeRequest ?? false, supportedProtocolVersions: Set(Version.handshake) ) } @@ -546,6 +537,17 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { return errorResponse } + guard let body, !body.isEmpty else { + return .error( + statusCode: 400, .parseError("Empty request body"), + sessionID: echoedSessionID(for: request)) + } + guard let messageKind else { + return .error( + statusCode: 400, JSONRPCMessageKind.classificationError(for: body), + sessionID: echoedSessionID(for: request)) + } + // Handle initialization request specially. A second `initialize` // validated while the first created the session gets 400 here. if messageKind.isInitializeRequest { @@ -573,7 +575,8 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // request it names fails instead of waiting. incomingContinuation.yield(body) return .error( - statusCode: 400, .invalidRequest(InvalidRequestReason.jsonrpc), sessionID: sessionID) + statusCode: 400, .invalidRequest(InvalidRequestReason.jsonrpc), + sessionID: echoedSessionID(for: request)) case .request(let id, _): return handleJSONRPCRequest(body, requestID: id, request: request) @@ -587,7 +590,8 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // read as a response gets -32600 with its `id`, and no stream is // opened for it. One that reads as a response is a `.response`. return .error( - statusCode: 400, .invalidRequest(reason), id: id, sessionID: sessionID) + statusCode: 400, .invalidRequest(reason), id: id, + sessionID: echoedSessionID(for: request)) } } @@ -597,7 +601,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { return .error( statusCode: 400, .invalidRequest("Bad Request: Session already initialized"), - sessionID: sessionID + sessionID: echoedSessionID(for: request) ) } @@ -615,14 +619,14 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { self.sessionID = newSessionID stateGeneration += 1 - logger.info("Session initialized", metadata: ["sessionID": "\(newSessionID)"]) + logger.info("Session initialized") // Extract request ID for routing the response guard case .request(let requestID, _) = JSONRPCMessageKind(data: body) else { return .error( statusCode: 400, .parseError("Invalid initialize request"), - sessionID: newSessionID + sessionID: echoedSessionID(for: request) ) } @@ -688,7 +692,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { return .error( statusCode: 409, .invalidRequest("Conflict: Only one SSE stream is allowed per session"), - sessionID: sessionID + sessionID: echoedSessionID(for: request) ) } @@ -843,7 +847,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { return .error( statusCode: 400, .invalidRequest("Invalid Last-Event-ID"), - sessionID: sessionID + sessionID: echoedSessionID(for: request) ) } @@ -988,6 +992,21 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // MARK: - Session Helpers + private func echoedSessionID(for request: HTTPRequest) -> String? { + guard let sessionID, + request.value(forHeader: HTTPHeaderName.sessionID)?.isExactly(sessionID) == true + else { return nil } + return sessionID + } + + private func validatedResponse(_ response: HTTPResponse, for request: HTTPRequest) -> HTTPResponse { + var response = withoutSessionHeader(response) + if let sessionID = echoedSessionID(for: request) { + response.headers[HTTPHeaderName.sessionID] = sessionID + } + return response + } + private func sessionHeaders() -> [String: String] { var headers: [String: String] = [:] if let sessionID { @@ -1051,7 +1070,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { guard !terminated else { return } terminated = true - logger.info("Terminating session", metadata: ["sessionID": "\(sessionID ?? "none")"]) + logger.info("Terminating session") // Close all request SSE streams for (_, continuation) in requestSSEContinuations { diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift index 5c4eacac..5146be38 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift @@ -9,7 +9,8 @@ import Logging /// - Earlier revisions used without session management. /// /// Behavior: -/// - POST only; GET and DELETE return 405 Method Not Allowed. +/// - POST only; other methods get 405 unless a validator answers with 2xx, +/// 304, 401, 403 or 421. /// - No `Mcp-Session-Id` header is read or set. /// - The response is a single JSON body. When the handler sends notifications /// for the request (progress, logging) and the client accepts @@ -306,9 +307,7 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { /// /// Only POST is supported: /// - **POST**: JSON-RPC messages (requests, notifications) - /// - **GET**: 405 Method Not Allowed - /// - **DELETE**: 405 Method Not Allowed - /// - Others: 405 Method Not Allowed + /// - Other methods: a successful validator response, 401, 403 or 421; otherwise 405 /// /// The transport handles other requests while this one's validators /// suspend. A request whose validators finish after ``disconnect()`` gets @@ -334,7 +333,10 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { supportedProtocolVersions: Set(servedVersions)) let response = await validation.validateInline(request, context: context) guard !terminated else { return Self.terminatedResponse } - if let response, (200..<300).contains(response.statusCode) || response.statusCode == 304 { + if let response, + (200..<300).contains(response.statusCode) || response.statusCode == 304 + || response.statusCode == 401 || response.statusCode == 403 || response.statusCode == 421 + { return response } return .error( @@ -353,28 +355,25 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { // MARK: - POST Handler private func handlePost(_ request: HTTPRequest) async -> HTTPResponse { - guard let body = request.body, !body.isEmpty else { - return .error(statusCode: 400, .parseError("Empty request body")) - } - // Parsers resolve duplicate member names differently (JSONSerialization // on Linux keeps the last, JSONDecoder the first). Check and dispatch // one re-serialized form, which has none, so the headers are checked // against the values the server reads. - guard let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any], - let normalized = try? JSONSerialization.data(withJSONObject: json, options: [.withoutEscapingSlashes]), - let messageKind = JSONRPCMessageKind(data: normalized) - else { - return .error(statusCode: 400, JSONRPCMessageKind.classificationError(for: body)) + let body = request.body + var normalized: Data? + if let body, let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any] { + normalized = try? JSONSerialization.data(withJSONObject: json, options: [.withoutEscapingSlashes]) } + let messageKind = normalized.flatMap(JSONRPCMessageKind.init(data:)) // One probe for the id and the `_meta` version. - let fields = JSONRPCMessageFields.requestFields(in: normalized) var requestID: ID? - switch messageKind { - case .request: requestID = fields.id - case .invalid(_, let id, _): requestID = id - case .notification, .response, .invalidResponse: break + if let messageKind, let normalized { + switch messageKind { + case .request: requestID = JSONRPCMessageFields.requestFields(in: normalized).id + case .invalid(_, let id, _): requestID = id + case .notification, .response, .invalidResponse: break + } } // Validators see the versions the server serves, so a version it @@ -382,7 +381,7 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { let context = HTTPValidationContext( method: "POST", sessionID: nil, - isInitializeRequest: messageKind.isInitializeRequest, + isInitializeRequest: messageKind?.isInitializeRequest ?? false, supportedProtocolVersions: Set(servedVersions) ) @@ -394,6 +393,14 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { return errorResponse.withRequestID(requestID) } + guard let body, !body.isEmpty else { + return .error(statusCode: 400, .parseError("Empty request body")) + } + guard let normalized, let messageKind else { + return .error(statusCode: 400, JSONRPCMessageKind.classificationError(for: body)) + } + let fields = JSONRPCMessageFields.requestFields(in: normalized) + switch messageKind { case .invalid(_, _, let reason): // JSON-RPC 2.0 §5: a request whose `id` or `jsonrpc` is invalid is diff --git a/Tests/MCPTests/SessionIDDisclosureTests.swift b/Tests/MCPTests/SessionIDDisclosureTests.swift new file mode 100644 index 00000000..80da1585 --- /dev/null +++ b/Tests/MCPTests/SessionIDDisclosureTests.swift @@ -0,0 +1,255 @@ +import Foundation +import Testing + +@testable import MCP + +private struct DisclosureSessionIDGenerator: SessionIDGenerator { + func makeSessionID() -> String { "test-session-secret" } +} + +private struct LegacySessionHeaderValidator: HTTPRequestValidator { + func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + guard request.method == "GET" else { return nil } + return .error(statusCode: 401, .invalidRequest("Unauthorized"), sessionID: context.sessionID) + } +} + +@Suite("HTTP session response headers") +struct SessionIDDisclosureTests { + private let sessionID = "test-session-secret" + + @Test("SessionValidator does not disclose the expected ID") + func sessionValidator() throws { + let validator = SessionValidator() + let context = HTTPValidationContext(method: "POST", sessionID: sessionID) + let missing = try #require(validator.validate(HTTPRequest(method: "POST"), context: context)) + #expect(missing.statusCode == 400) + #expect(missing.headers[HTTPHeaderName.sessionID] == nil) + + let wrong = try #require(validator.validate(HTTPRequest( + method: "POST", headers: [HTTPHeaderName.sessionID: "wrong"]), context: context)) + #expect(wrong.statusCode == 404) + #expect(wrong.headers[HTTPHeaderName.sessionID] == nil) + + let byteDifferent = try #require(SessionValidator().validate(HTTPRequest( + method: "POST", headers: [HTTPHeaderName.sessionID: "test-session-secre\u{212A}"]), + context: HTTPValidationContext(method: "POST", sessionID: "test-session-secreK"))) + #expect(byteDifferent.statusCode == 404) + #expect(byteDifferent.headers[HTTPHeaderName.sessionID] == nil) + } + + private var headers: [String: String] { + [ + HTTPHeaderName.host: "localhost:3001", + HTTPHeaderName.accept: "application/json, text/event-stream", + HTTPHeaderName.contentType: "application/json", + ] + } + + private func startSession( + validators: [any HTTPRequestValidator] = StatefulHTTPServerTransport.defaultValidators, + authorization: String? = nil + ) async throws -> StatefulHTTPServerTransport { + let transport = StatefulHTTPServerTransport( + sessionIDGenerator: DisclosureSessionIDGenerator(), validators: validators) + try await transport.connect() + let body = Data(#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"#.utf8) + var initializationHeaders = headers + initializationHeaders[HTTPHeaderName.authorization] = authorization + let response = await transport.handleRequest( + HTTPRequest(method: "POST", headers: initializationHeaders, body: body)) + #expect(response.statusCode == 200) + #expect(response.headers[HTTPHeaderName.sessionID] == sessionID) + return transport + } + + @Test("Unknown callers never receive the live session ID") + func unknownCaller() async throws { + let transport = try await startSession() + let ping = Data(#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#.utf8) + let initialize = Data(#"{"jsonrpc":"2.0","id":3,"method":"initialize"}"#.utf8) + var wrong = headers + wrong[HTTPHeaderName.sessionID] = "wrong" + var badOrigin = headers + badOrigin[HTTPHeaderName.origin] = "https://other.example" + var badHost = headers + badHost[HTTPHeaderName.host] = "other.example" + var badAccept = headers + badAccept[HTTPHeaderName.accept] = "application/json" + var badType = headers + badType[HTTPHeaderName.contentType] = "text/plain" + var badVersion = headers + badVersion[HTTPHeaderName.protocolVersion] = "unsupported" + let requests: [(HTTPRequest, Int)] = [ + (.init(method: "POST", headers: headers, body: ping), 400), + (.init(method: "POST", headers: wrong, body: ping), 404), + (.init(method: "POST", headers: headers, body: nil), 400), + (.init(method: "POST", headers: headers, body: Data("{not json".utf8)), 400), + (.init(method: "POST", headers: badOrigin, body: ping), 403), + (.init(method: "POST", headers: badHost, body: ping), 421), + (.init(method: "POST", headers: badAccept, body: ping), 406), + (.init(method: "POST", headers: badType, body: ping), 415), + (.init(method: "POST", headers: badVersion, body: ping), 400), + (.init(method: "POST", headers: headers, body: initialize), 400), + (.init(method: "PUT", headers: headers), 405), + (.init(method: "OPTIONS", headers: headers), 405), + ] + for (request, status) in requests { + let response = await transport.handleRequest(request) + #expect(response.statusCode == status) + #expect(response.headers[HTTPHeaderName.sessionID] == nil, "\(request.method) \(response.statusCode)") + } + await transport.disconnect() + } + + @Test("A matching session ID is still echoed on accepted requests") + func knownCaller() async throws { + let transport = try await startSession() + var known = headers + known[HTTPHeaderName.sessionID] = sessionID + let notification = Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8) + let response = await transport.handleRequest(HTTPRequest(method: "POST", headers: known, body: notification)) + #expect(response.statusCode == 202) + #expect(response.headers[HTTPHeaderName.sessionID] == sessionID) + let stream = await transport.handleRequest(HTTPRequest(method: "GET", headers: known)) + #expect(stream.statusCode == 200) + #expect(stream.headers[HTTPHeaderName.sessionID] == sessionID) + let malformed = await transport.handleRequest( + HTTPRequest(method: "POST", headers: known, body: Data("{not json".utf8))) + #expect(malformed.statusCode == 400) + #expect(malformed.headers[HTTPHeaderName.sessionID] == sessionID) + let method = await transport.handleRequest(HTTPRequest(method: "PUT", headers: known)) + #expect(method.statusCode == 405) + #expect(method.headers[HTTPHeaderName.sessionID] == sessionID) + await transport.disconnect() + } + + @Test("A known caller keeps its session ID on transport errors") + func knownCallerErrors() async throws { + let transport = try await startSession() + var known = headers + known[HTTPHeaderName.sessionID] = sessionID + + let stream = await transport.handleRequest(HTTPRequest(method: "GET", headers: known)) + #expect(stream.statusCode == 200) + let secondStream = await transport.handleRequest(HTTPRequest(method: "GET", headers: known)) + #expect(secondStream.statusCode == 409) + #expect(secondStream.headers[HTTPHeaderName.sessionID] == sessionID) + + var badEventID = known + badEventID[HTTPHeaderName.lastEventID] = "bogus" + let invalidResume = await transport.handleRequest(HTTPRequest(method: "GET", headers: badEventID)) + #expect(invalidResume.statusCode == 400) + #expect(invalidResume.headers[HTTPHeaderName.sessionID] == sessionID) + + let invalidMessage = Data(#"{"jsonrpc":"2.0","id":5}"#.utf8) + let invalidPost = await transport.handleRequest( + HTTPRequest(method: "POST", headers: known, body: invalidMessage)) + #expect(invalidPost.statusCode == 400) + #expect(invalidPost.headers[HTTPHeaderName.sessionID] == sessionID) + await transport.disconnect() + } + + @Test("An unauthenticated request cannot learn the session ID") + func bearerRejection() async throws { + let bearer = BearerTokenValidator( + resourceMetadataURL: URL(string: "https://example.com/.well-known/oauth-protected-resource/mcp")!, + resourceIdentifier: URL(string: "https://example.com/mcp")!, + tokenVerifier: { _, _, _ in .valid(BearerTokenInfo()) }) + let transport = try await startSession(validators: [ + OriginValidator.localhost(), + bearer, + SessionValidator(), + ], authorization: "Bearer valid") + let ping = Data(#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#.utf8) + for method in ["POST", "PUT"] { + let response = await transport.handleRequest( + HTTPRequest(method: method, headers: headers, body: ping)) + #expect(response.statusCode == 401) + #expect(response.headers[HTTPHeaderName.sessionID] == nil) + } + await transport.disconnect() + } + + @Test("Custom validator responses cannot disclose a session ID") + func customValidator() async throws { + let transport = try await startSession(validators: [LegacySessionHeaderValidator()]) + let unknown = await transport.handleRequest(HTTPRequest(method: "GET")) + #expect(unknown.statusCode == 401) + #expect(unknown.headers[HTTPHeaderName.sessionID] == nil) + var known = headers + known[HTTPHeaderName.sessionID] = sessionID + let matching = await transport.handleRequest(HTTPRequest(method: "GET", headers: known)) + #expect(matching.statusCode == 401) + #expect(matching.headers[HTTPHeaderName.sessionID] == sessionID) + await transport.disconnect() + } + + @Test("Rejected Origin wins over a malformed body in both transports") + func originBeforeParsing() async throws { + var rejected = headers + rejected[HTTPHeaderName.origin] = "https://other.example" + let stateful = StatefulHTTPServerTransport() + let stateless = StatelessHTTPServerTransport() + try await stateful.connect() + try await stateless.connect() + for body in [Data(), Data("{not json".utf8)] { + let request = HTTPRequest(method: "POST", headers: rejected, body: body) + #expect(await stateful.handleRequest(request).statusCode == 403) + #expect(await stateless.handleRequest(request).statusCode == 403) + } + await stateful.disconnect() + await stateless.disconnect() + } + + @Test("Authentication wins over malformed JSON in both transports") + func bearerBeforeParsing() async throws { + let bearer = BearerTokenValidator( + resourceMetadataURL: URL(string: "https://example.com/.well-known/oauth-protected-resource/mcp")!, + resourceIdentifier: URL(string: "https://example.com/mcp")!, + tokenVerifier: { _, _, _ in .valid(BearerTokenInfo()) }) + let stateful = StatefulHTTPServerTransport(validators: [bearer]) + let stateless = StatelessHTTPServerTransport(validators: [bearer]) + try await stateful.connect() + try await stateless.connect() + let request = HTTPRequest(method: "POST", headers: headers, body: Data("{not json".utf8)) + #expect(await stateful.handleRequest(request).statusCode == 401) + #expect(await stateless.handleRequest(request).statusCode == 401) + await stateful.disconnect() + await stateless.disconnect() + } + + @Test("Validator rejection wins over 405") + func validatorBeforeMethod() async throws { + let transport = try await startSession() + var rejected = headers + rejected[HTTPHeaderName.origin] = "https://other.example" + let response = await transport.handleRequest(HTTPRequest(method: "PUT", headers: rejected)) + #expect(response.statusCode == 403) + #expect(response.headers[HTTPHeaderName.sessionID] == nil) + await transport.disconnect() + } + + @Test("Stateless unsupported methods keep security rejections and otherwise return 405") + func statelessMethodPrecedence() async throws { + let transport = StatelessHTTPServerTransport() + try await transport.connect() + var badOrigin = headers + badOrigin[HTTPHeaderName.origin] = "https://other.example" + var badHost = headers + badHost[HTTPHeaderName.host] = "other.example" + #expect(await transport.handleRequest(HTTPRequest(method: "PUT", headers: badOrigin)).statusCode == 403) + #expect(await transport.handleRequest(HTTPRequest(method: "PUT", headers: badHost)).statusCode == 421) + #expect(await transport.handleRequest(HTTPRequest(method: "GET")).statusCode == 405) + await transport.disconnect() + + let bearer = BearerTokenValidator( + resourceMetadataURL: URL(string: "https://example.com/.well-known/oauth-protected-resource/mcp")!, + resourceIdentifier: URL(string: "https://example.com/mcp")!, + tokenVerifier: { _, _, _ in .valid(BearerTokenInfo()) }) + let authenticated = StatelessHTTPServerTransport(validators: [bearer]) + try await authenticated.connect() + #expect(await authenticated.handleRequest(HTTPRequest(method: "PUT")).statusCode == 401) + await authenticated.disconnect() + } +} diff --git a/design/design.md b/design/design.md index 50d885e1..873023f8 100644 --- a/design/design.md +++ b/design/design.md @@ -244,7 +244,7 @@ headers and authentication data there. The stateless transport also implements | | `StatefulHTTPServerTransport` | `StatelessHTTPServerTransport` | |---|---|---| | Revisions | handshake (2025-11-25 and earlier) | 2026-07-28; also handshake requests without a session | -| HTTP methods | POST, GET (standalone SSE stream), DELETE (end session) | POST only; others 405 | +| HTTP methods | POST, GET (standalone SSE stream), DELETE (end session) | POST only; others 405 after the Host, Origin and authentication checks | | Session | `Mcp-Session-Id`, one transport and one `Server` per session | none; one shared `Server` | | Response | SSE stream per POST; priming event; replay with `Last-Event-ID` | one JSON body, or SSE when notifications precede the response and the client accepts `text/event-stream` | | Request ids | client ids | rewritten to `mcp-http-` per exchange, restored on the way out | diff --git a/design/threat_model.md b/design/threat_model.md index d0f224ce..8a3ae9a6 100644 --- a/design/threat_model.md +++ b/design/threat_model.md @@ -35,7 +35,11 @@ and side channels other than the `requestState` principal tag (compared in const ## Server side -**Request validation.** The transport's validators run on every HTTP request before decoding. +**Request validation.** For POST, the transports classify the body to identify `initialize` +before running validators; the stateless transport also extracts the request ID for errors. +Validator rejections take precedence over parse errors. For unsupported HTTP methods, validator +responses with status 2xx, 304, 401, 403 or 421 take precedence over 405. +Error responses carry `Mcp-Session-Id` only when the request carried the same ID. A request whose session is created, or dropped by a refused `initialize`, while its validators suspend is validated again, and none reaches a terminated session. `OriginValidator.localhost()`, the default, refuses a `Host` that is not a loopback host (421) and an diff --git a/docs/protocol.md b/docs/protocol.md index 80c7df6b..5265c1ec 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -327,6 +327,8 @@ Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -3202 The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. +Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 401, 403 or 421 take precedence over 405. Error responses include `Mcp-Session-Id` only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. + Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: ```swift @@ -388,7 +390,7 @@ Validation errors: `StatelessHTTPServerTransport` answers each POST with one exchange and keeps no session. One transport and one `Server` serve every client. -- POST only; other methods get 405 with `Allow: POST`. +- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 401, 403 or 421. - `Mcp-Session-Id` is neither read nor set. - The reply is a single JSON body. When the handler sends notifications for the request (progress, logs, listen events) and the client accepts `text/event-stream`, the reply becomes an SSE stream that carries them and ends with the response. Without SSE in `Accept`, those notifications are dropped, and `subscriptions/listen` is refused with 406. - Each request gets an internal JSON-RPC id (`mcp-http-`) while in flight, so clients may reuse ids. The response carries the client's id again. diff --git a/docs/src/protocol.src.md b/docs/src/protocol.src.md index 9641cdb2..95ad6fa3 100644 --- a/docs/src/protocol.src.md +++ b/docs/src/protocol.src.md @@ -234,6 +234,8 @@ Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -3202 The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. +Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 401, 403 or 421 take precedence over 405. Error responses include `Mcp-Session-Id` only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. + Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: %include Examples/Snippets/Protocol/Transports.swift transport-stateful-sessions @@ -255,7 +257,7 @@ Validation errors: `StatelessHTTPServerTransport` answers each POST with one exchange and keeps no session. One transport and one `Server` serve every client. -- POST only; other methods get 405 with `Allow: POST`. +- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 401, 403 or 421. - `Mcp-Session-Id` is neither read nor set. - The reply is a single JSON body. When the handler sends notifications for the request (progress, logs, listen events) and the client accepts `text/event-stream`, the reply becomes an SSE stream that carries them and ends with the response. Without SSE in `Accept`, those notifications are dropped, and `subscriptions/listen` is refused with 406. - Each request gets an internal JSON-RPC id (`mcp-http-`) while in flight, so clients may reuse ids. The response carries the client's id again. diff --git a/docs/src/troubleshooting.src.md b/docs/src/troubleshooting.src.md index c1bb13b4..dc42a254 100644 --- a/docs/src/troubleshooting.src.md +++ b/docs/src/troubleshooting.src.md @@ -191,14 +191,14 @@ Server transports: | Status | Transport | Cause | |---|---|---| -| 400 | both | Empty body or invalid JSON-RPC; an unsupported `MCP-Protocol-Version` header (-32022). | +| 400 | both | Empty body or invalid JSON-RPC after header and session checks; an unsupported `MCP-Protocol-Version` header (-32022). | | 400 | stateless | At 2026-07-28, JSON-RPC errors -32600, -32602, -32020, -32021 and -32022. | | 400 | stateful | No session yet (`Session not initialized`), a missing `Mcp-Session-Id` (also after the session ended), a second `initialize` on the session, an unknown `Last-Event-ID`, a stateless request (-32022). | | 403 | both | An `Origin` header that the `OriginValidator` does not allow. | | 404 | stateless | At 2026-07-28, -32601; any request after the transport stopped. | | 404 | stateful | An unknown or expired `Mcp-Session-Id`, including any ID sent after the session ended. | -| 405 | stateless | Any method other than POST. The `Allow` header is `POST`. | -| 405 | stateful | Any method other than GET, POST and DELETE. | +| 405 | stateless | Any method other than POST once the Host, Origin and authentication checks pass. The `Allow` header is `POST`. | +| 405 | stateful | Any method other than GET, POST and DELETE once the Host, Origin and authentication checks pass. | | 406 | both | An `Accept` header without `application/json` (stateless), or without both `application/json` and `text/event-stream` (stateful POST). | | 409 | stateful | A second GET stream for the session. | | 415 | both | A POST whose `Content-Type` is not `application/json`. | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index a3f76f8d..7145c9be 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -271,14 +271,14 @@ Server transports: | Status | Transport | Cause | |---|---|---| -| 400 | both | Empty body or invalid JSON-RPC; an unsupported `MCP-Protocol-Version` header (-32022). | +| 400 | both | Empty body or invalid JSON-RPC after header and session checks; an unsupported `MCP-Protocol-Version` header (-32022). | | 400 | stateless | At 2026-07-28, JSON-RPC errors -32600, -32602, -32020, -32021 and -32022. | | 400 | stateful | No session yet (`Session not initialized`), a missing `Mcp-Session-Id` (also after the session ended), a second `initialize` on the session, an unknown `Last-Event-ID`, a stateless request (-32022). | | 403 | both | An `Origin` header that the `OriginValidator` does not allow. | | 404 | stateless | At 2026-07-28, -32601; any request after the transport stopped. | | 404 | stateful | An unknown or expired `Mcp-Session-Id`, including any ID sent after the session ended. | -| 405 | stateless | Any method other than POST. The `Allow` header is `POST`. | -| 405 | stateful | Any method other than GET, POST and DELETE. | +| 405 | stateless | Any method other than POST once the Host, Origin and authentication checks pass. The `Allow` header is `POST`. | +| 405 | stateful | Any method other than GET, POST and DELETE once the Host, Origin and authentication checks pass. | | 406 | both | An `Accept` header without `application/json` (stateless), or without both `application/json` and `text/event-stream` (stateful POST). | | 409 | stateful | A second GET stream for the session. | | 415 | both | A POST whose `Content-Type` is not `application/json`. | From 872c930af88b5e8b3d428020293f517789dba11f Mon Sep 17 00:00:00 2001 From: EhsanAzish80 Date: Sun, 6 Dec 2026 13:03:09 +0300 Subject: [PATCH 2/5] refactor: address review nits in session ID fix --- .../HTTPServer/HTTPServerTypes.swift | 11 ++++++++-- .../StatefulHTTPServerTransport.swift | 5 +---- .../StatelessHTTPServerTransport.swift | 13 +++++------ Tests/MCPTests/SessionIDDisclosureTests.swift | 22 +++++++++---------- 4 files changed, 25 insertions(+), 26 deletions(-) diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift index 3c683f8a..2ceb1137 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift @@ -320,8 +320,8 @@ public struct HTTPResponse: Sendable { /// - statusCode: The HTTP status code of the response. /// - error: The JSON-RPC error to encode in the response body. /// - id: The JSON-RPC request ID, or `nil` when absent or unknown. - /// - sessionID: The session ID to echo only when the request carried that same ID, - /// or to send on a successful initialization response. + /// - sessionID: The session ID to send in `MCP-Session-Id`. Pass it only when + /// the request carried the same ID. /// - extraHeaders: Additional response headers merged into the response. /// - Returns: An HTTP response carrying the encoded JSON-RPC error body. public static func error( @@ -373,6 +373,13 @@ public struct HTTPResponse: Sendable { } } +extension HTTPResponse { + var answersUnsupportedMethod: Bool { + (200..<300).contains(statusCode) || statusCode == 304 + || statusCode == 401 || statusCode == 403 || statusCode == 421 + } +} + // MARK: - HTTP Header Names /// Standard header names used by the MCP Streamable HTTP transport. diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift index 8be410aa..eefe53ba 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift @@ -418,10 +418,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { supportedProtocolVersions: Set(Version.handshake)) } guard !terminated else { return terminatedResponse(to: request, validated: response) } - if let response, - (200..<300).contains(response.statusCode) || response.statusCode == 304 - || response.statusCode == 401 || response.statusCode == 403 || response.statusCode == 421 - { + if let response, response.answersUnsupportedMethod { return response } return .error( diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift index 5146be38..902fd4ce 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift @@ -333,10 +333,7 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { supportedProtocolVersions: Set(servedVersions)) let response = await validation.validateInline(request, context: context) guard !terminated else { return Self.terminatedResponse } - if let response, - (200..<300).contains(response.statusCode) || response.statusCode == 304 - || response.statusCode == 401 || response.statusCode == 403 || response.statusCode == 421 - { + if let response, response.answersUnsupportedMethod { return response } return .error( @@ -367,10 +364,11 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { let messageKind = normalized.flatMap(JSONRPCMessageKind.init(data:)) // One probe for the id and the `_meta` version. + let fields = normalized.map(JSONRPCMessageFields.requestFields(in:)) var requestID: ID? - if let messageKind, let normalized { + if let messageKind { switch messageKind { - case .request: requestID = JSONRPCMessageFields.requestFields(in: normalized).id + case .request: requestID = fields?.id case .invalid(_, let id, _): requestID = id case .notification, .response, .invalidResponse: break } @@ -396,10 +394,9 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { guard let body, !body.isEmpty else { return .error(statusCode: 400, .parseError("Empty request body")) } - guard let normalized, let messageKind else { + guard let normalized, let messageKind, let fields else { return .error(statusCode: 400, JSONRPCMessageKind.classificationError(for: body)) } - let fields = JSONRPCMessageFields.requestFields(in: normalized) switch messageKind { case .invalid(_, _, let reason): diff --git a/Tests/MCPTests/SessionIDDisclosureTests.swift b/Tests/MCPTests/SessionIDDisclosureTests.swift index 80da1585..97f4e467 100644 --- a/Tests/MCPTests/SessionIDDisclosureTests.swift +++ b/Tests/MCPTests/SessionIDDisclosureTests.swift @@ -18,6 +18,13 @@ private struct LegacySessionHeaderValidator: HTTPRequestValidator { struct SessionIDDisclosureTests { private let sessionID = "test-session-secret" + private func makeBearerValidator() -> BearerTokenValidator { + BearerTokenValidator( + resourceMetadataURL: URL(string: "https://example.com/.well-known/oauth-protected-resource/mcp")!, + resourceIdentifier: URL(string: "https://example.com/mcp")!, + tokenVerifier: { _, _, _ in .valid(BearerTokenInfo()) }) + } + @Test("SessionValidator does not disclose the expected ID") func sessionValidator() throws { let validator = SessionValidator() @@ -152,10 +159,7 @@ struct SessionIDDisclosureTests { @Test("An unauthenticated request cannot learn the session ID") func bearerRejection() async throws { - let bearer = BearerTokenValidator( - resourceMetadataURL: URL(string: "https://example.com/.well-known/oauth-protected-resource/mcp")!, - resourceIdentifier: URL(string: "https://example.com/mcp")!, - tokenVerifier: { _, _, _ in .valid(BearerTokenInfo()) }) + let bearer = makeBearerValidator() let transport = try await startSession(validators: [ OriginValidator.localhost(), bearer, @@ -204,10 +208,7 @@ struct SessionIDDisclosureTests { @Test("Authentication wins over malformed JSON in both transports") func bearerBeforeParsing() async throws { - let bearer = BearerTokenValidator( - resourceMetadataURL: URL(string: "https://example.com/.well-known/oauth-protected-resource/mcp")!, - resourceIdentifier: URL(string: "https://example.com/mcp")!, - tokenVerifier: { _, _, _ in .valid(BearerTokenInfo()) }) + let bearer = makeBearerValidator() let stateful = StatefulHTTPServerTransport(validators: [bearer]) let stateless = StatelessHTTPServerTransport(validators: [bearer]) try await stateful.connect() @@ -243,10 +244,7 @@ struct SessionIDDisclosureTests { #expect(await transport.handleRequest(HTTPRequest(method: "GET")).statusCode == 405) await transport.disconnect() - let bearer = BearerTokenValidator( - resourceMetadataURL: URL(string: "https://example.com/.well-known/oauth-protected-resource/mcp")!, - resourceIdentifier: URL(string: "https://example.com/mcp")!, - tokenVerifier: { _, _, _ in .valid(BearerTokenInfo()) }) + let bearer = makeBearerValidator() let authenticated = StatelessHTTPServerTransport(validators: [bearer]) try await authenticated.connect() #expect(await authenticated.handleRequest(HTTPRequest(method: "PUT")).statusCode == 401) From 2a3858b7b51daee76d3cd22719096ab46bd75748 Mon Sep 17 00:00:00 2001 From: EhsanAzish80 Date: Sun, 6 Dec 2026 16:29:05 +0300 Subject: [PATCH 3/5] fix: keep session IDs off responder answers and honor Bearer 400 challenges MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review on #420 for the #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. --- CHANGELOG.md | 3 +- .../HTTPServer/HTTPServerTypes.swift | 7 ++ .../StatefulHTTPServerTransport.swift | 9 +- .../StatelessHTTPServerTransport.swift | 5 +- Tests/MCPTests/SessionIDDisclosureTests.swift | 100 ++++++++++++++++++ design/threat_model.md | 2 +- docs/protocol.md | 4 +- docs/src/protocol.src.md | 4 +- 8 files changed, 124 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cdf0f941..6f88a317 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -401,7 +401,8 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha ### Fixes - HTTP server transports now return header validation errors before malformed-body errors. - On unsupported methods, validator responses with status 401, 403 or 421 take precedence over 405. + On unsupported methods, validator responses with status 401, 403 or 421, and a 400 Bearer + challenge, take precedence over 405. The stateful transport no longer echoes a session ID to callers that did not provide it in validator, parse, method, re-initialization, stream-conflict or invalid event-ID errors, and no longer logs raw session IDs. diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift index 2ceb1137..2090b2af 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift @@ -374,9 +374,16 @@ public struct HTTPResponse: Sendable { } extension HTTPResponse { + /// Whether a validator's response answers a request whose method the + /// transport does not serve, instead of 405: a responder's answer (2xx or + /// 304), or a Host, Origin or authentication rejection (401, 403, 421, + /// or a 400 with a `WWW-Authenticate` challenge, RFC 6750 §3.1). var answersUnsupportedMethod: Bool { (200..<300).contains(statusCode) || statusCode == 304 || statusCode == 401 || statusCode == 403 || statusCode == 421 + || (statusCode == 400 && headers.keys.contains { + $0.lowercased() == HTTPHeaderName.wwwAuthenticate.lowercased() + }) } } diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift index eefe53ba..01581d98 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift @@ -383,7 +383,8 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { /// - **POST**: JSON-RPC messages (requests, notifications) /// - **GET**: Establish standalone SSE stream for server-initiated messages /// - **DELETE**: Terminate the session - /// - Others: a successful validator response, 401, 403 or 421; otherwise 405 + /// - Others: a successful validator response, 401, 403, 421 or a 400 + /// Bearer challenge; otherwise 405 /// /// The transport handles other requests while this one's validators /// suspend. A request whose session ends while its validators run gets @@ -996,9 +997,13 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { return sessionID } + /// A validator's response with the session header set by the transport: + /// echoed on an error to a request that carried the same ID, and never on + /// a 2xx or 3xx answer, such as a ``ServerCardResponder`` reply that + /// shared caches may store. private func validatedResponse(_ response: HTTPResponse, for request: HTTPRequest) -> HTTPResponse { var response = withoutSessionHeader(response) - if let sessionID = echoedSessionID(for: request) { + if response.statusCode >= 400, let sessionID = echoedSessionID(for: request) { response.headers[HTTPHeaderName.sessionID] = sessionID } return response diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift index 902fd4ce..436c6bb5 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift @@ -10,7 +10,7 @@ import Logging /// /// Behavior: /// - POST only; other methods get 405 unless a validator answers with 2xx, -/// 304, 401, 403 or 421. +/// 304, 401, 403 or 421, or a 400 Bearer challenge. /// - No `Mcp-Session-Id` header is read or set. /// - The response is a single JSON body. When the handler sends notifications /// for the request (progress, logging) and the client accepts @@ -307,7 +307,8 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { /// /// Only POST is supported: /// - **POST**: JSON-RPC messages (requests, notifications) - /// - Other methods: a successful validator response, 401, 403 or 421; otherwise 405 + /// - Other methods: a successful validator response, 401, 403, 421 or a + /// 400 Bearer challenge; otherwise 405 /// /// The transport handles other requests while this one's validators /// suspend. A request whose validators finish after ``disconnect()`` gets diff --git a/Tests/MCPTests/SessionIDDisclosureTests.swift b/Tests/MCPTests/SessionIDDisclosureTests.swift index 97f4e467..765ad6f1 100644 --- a/Tests/MCPTests/SessionIDDisclosureTests.swift +++ b/Tests/MCPTests/SessionIDDisclosureTests.swift @@ -250,4 +250,104 @@ struct SessionIDDisclosureTests { #expect(await authenticated.handleRequest(HTTPRequest(method: "PUT")).statusCode == 401) await authenticated.disconnect() } + + @Test("Responder answers never carry the session ID") + func responderAnswers() async throws { + let card = ServerCard( + name: "com.example/weather", version: "1.2.0", description: "Current weather for a city.", + title: "Weather", + remotes: [.init(type: .streamableHTTP, url: "https://example.com/mcp", supportedProtocolVersions: ["2025-11-25"])]) + let responder = try ServerCardResponder(card: card, endpointPath: "/mcp/") + let transport = try await startSession(validators: [responder, SessionValidator()]) + var known = headers + known[HTTPHeaderName.sessionID] = sessionID + for method in ["GET", "HEAD", "OPTIONS"] { + let response = await transport.handleRequest( + HTTPRequest(method: method, headers: known, body: nil, path: "/mcp/server-card")) + #expect(response.statusCode < 300, "\(method)") + #expect(response.headers[HTTPHeaderName.sessionID] == nil, "\(method)") + } + await transport.disconnect() + } + + @Test("A malformed Bearer header gets its 400 challenge, not 405, in both transports") + func malformedBearerOnUnsupportedMethod() async throws { + let stateful = StatefulHTTPServerTransport(validators: [makeBearerValidator()]) + let stateless = StatelessHTTPServerTransport(validators: [makeBearerValidator()]) + try await stateful.connect() + try await stateless.connect() + let request = HTTPRequest(method: "PUT", headers: [HTTPHeaderName.authorization: "Bearer a b"]) + for response in [await stateful.handleRequest(request), await stateless.handleRequest(request)] { + #expect(response.statusCode == 400) + #expect(response.headers[HTTPHeaderName.wwwAuthenticate] != nil) + } + await stateful.disconnect() + await stateless.disconnect() + } + + @Test("ProtocolVersionValidator rejections do not carry the session ID") + func protocolVersionValidator() throws { + let validator = ProtocolVersionValidator() + let context = HTTPValidationContext( + method: "POST", sessionID: sessionID, supportedProtocolVersions: Set(Version.handshake)) + let unsupported = try #require(validator.validate( + HTTPRequest(method: "POST", headers: [ + HTTPHeaderName.protocolVersion: "1999-01-01", HTTPHeaderName.sessionID: sessionID, + ]), + context: context)) + #expect(unsupported.statusCode == 400) + #expect(unsupported.headers[HTTPHeaderName.sessionID] == nil) + + let repeated = try #require(validator.validate( + HTTPRequest(method: "POST", headerFields: [ + (name: HTTPHeaderName.protocolVersion, value: "2026-07-28"), + (name: HTTPHeaderName.protocolVersion, value: "2026-07-28"), + (name: HTTPHeaderName.sessionID, value: sessionID), + ]), + context: context)) + #expect(repeated.statusCode == 400) + #expect(repeated.headers[HTTPHeaderName.sessionID] == nil) + } + + @Test("A parse error without SessionValidator does not carry the session ID") + func parseErrorWithoutSessionValidator() async throws { + let transport = try await startSession(validators: []) + for body in [Data(), Data("{not json".utf8)] { + let response = await transport.handleRequest(HTTPRequest(method: "POST", headers: headers, body: body)) + #expect(response.statusCode == 400) + #expect(response.headers[HTTPHeaderName.sessionID] == nil) + } + await transport.disconnect() + } + + @Test("Stateless header rejections win over a malformed body") + func statelessHeaderRejectionsBeforeParsing() async throws { + let transport = StatelessHTTPServerTransport() + try await transport.connect() + let malformed = Data("{not json".utf8) + var badAccept = headers + badAccept[HTTPHeaderName.accept] = "text/plain" + var badType = headers + badType[HTTPHeaderName.contentType] = "text/plain" + var badHost = headers + badHost[HTTPHeaderName.host] = "other.example" + var badVersion = headers + badVersion[HTTPHeaderName.protocolVersion] = "1999-01-01" + for (requestHeaders, status) in [(badAccept, 406), (badType, 415), (badHost, 421), (badVersion, 400)] { + let response = await transport.handleRequest( + HTTPRequest(method: "POST", headers: requestHeaders, body: malformed)) + #expect(response.statusCode == status) + } + let unsupported = await transport.handleRequest( + HTTPRequest(method: "POST", headers: badVersion, body: malformed)) + guard case .data(let body) = unsupported.body, + case .object(let object) = try JSONDecoder().decode(Value.self, from: body), + case .object(let error)? = object["error"] + else { + Issue.record("Expected a JSON-RPC error body") + return + } + #expect(error["code"] == .int(-32022)) + await transport.disconnect() + } } diff --git a/design/threat_model.md b/design/threat_model.md index 8a3ae9a6..769c4fa5 100644 --- a/design/threat_model.md +++ b/design/threat_model.md @@ -38,7 +38,7 @@ and side channels other than the `requestState` principal tag (compared in const **Request validation.** For POST, the transports classify the body to identify `initialize` before running validators; the stateless transport also extracts the request ID for errors. Validator rejections take precedence over parse errors. For unsupported HTTP methods, validator -responses with status 2xx, 304, 401, 403 or 421 take precedence over 405. +responses with status 2xx, 304, 401, 403 or 421, and a 400 Bearer challenge, take precedence over 405. Error responses carry `Mcp-Session-Id` only when the request carried the same ID. A request whose session is created, or dropped by a refused `initialize`, while its validators suspend is validated again, and none reaches a terminated session. diff --git a/docs/protocol.md b/docs/protocol.md index 5265c1ec..7c97cd64 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -327,7 +327,7 @@ Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -3202 The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. -Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 401, 403 or 421 take precedence over 405. Error responses include `Mcp-Session-Id` only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. +Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 401, 403 or 421, and a 400 with a Bearer challenge, take precedence over 405. Error responses include `Mcp-Session-Id` only if the request already carried the matching ID; 2xx and 304 answers from validators such as `ServerCardResponder` never do. A successful `initialize` still returns the newly assigned ID. Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: @@ -390,7 +390,7 @@ Validation errors: `StatelessHTTPServerTransport` answers each POST with one exchange and keeps no session. One transport and one `Server` serve every client. -- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 401, 403 or 421. +- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 401, 403, 421 or a 400 Bearer challenge. - `Mcp-Session-Id` is neither read nor set. - The reply is a single JSON body. When the handler sends notifications for the request (progress, logs, listen events) and the client accepts `text/event-stream`, the reply becomes an SSE stream that carries them and ends with the response. Without SSE in `Accept`, those notifications are dropped, and `subscriptions/listen` is refused with 406. - Each request gets an internal JSON-RPC id (`mcp-http-`) while in flight, so clients may reuse ids. The response carries the client's id again. diff --git a/docs/src/protocol.src.md b/docs/src/protocol.src.md index 95ad6fa3..554b16b9 100644 --- a/docs/src/protocol.src.md +++ b/docs/src/protocol.src.md @@ -234,7 +234,7 @@ Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -3202 The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. -Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 401, 403 or 421 take precedence over 405. Error responses include `Mcp-Session-Id` only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. +Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 401, 403 or 421, and a 400 with a Bearer challenge, take precedence over 405. Error responses include `Mcp-Session-Id` only if the request already carried the matching ID; 2xx and 304 answers from validators such as `ServerCardResponder` never do. A successful `initialize` still returns the newly assigned ID. Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: @@ -257,7 +257,7 @@ Validation errors: `StatelessHTTPServerTransport` answers each POST with one exchange and keeps no session. One transport and one `Server` serve every client. -- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 401, 403 or 421. +- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 401, 403, 421 or a 400 Bearer challenge. - `Mcp-Session-Id` is neither read nor set. - The reply is a single JSON body. When the handler sends notifications for the request (progress, logs, listen events) and the client accepts `text/event-stream`, the reply becomes an SSE stream that carries them and ends with the response. Without SSE in `Accept`, those notifications are dropped, and `subscriptions/listen` is refused with 406. - Each request gets an internal JSON-RPC id (`mcp-http-`) while in flight, so clients may reuse ids. The response carries the client's id again. From 87ce344228e7397cf0562eb05be6ba57645ef5f1 Mon Sep 17 00:00:00 2001 From: EhsanAzish80 Date: Sun, 6 Dec 2026 16:46:53 +0300 Subject: [PATCH 4/5] fix: preserve HTTP validator response boundaries 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. --- CHANGELOG.md | 9 +- .../HTTPServer/HTTPServerTypes.swift | 11 +- .../StatefulHTTPServerTransport.swift | 21 +-- .../StatelessHTTPServerTransport.swift | 14 +- Tests/MCPTests/SessionIDDisclosureTests.swift | 163 +++++++++++++++++- design/threat_model.md | 5 +- docs/migration.md | 7 +- docs/protocol.md | 4 +- docs/src/migration.src.md | 7 +- docs/src/protocol.src.md | 4 +- docs/src/troubleshooting.src.md | 4 +- docs/troubleshooting.md | 4 +- 12 files changed, 205 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f88a317..7182edef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -401,11 +401,10 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha ### Fixes - HTTP server transports now return header validation errors before malformed-body errors. - On unsupported methods, validator responses with status 401, 403 or 421, and a 400 Bearer - challenge, take precedence over 405. - The stateful transport no longer echoes a session ID to callers that did not provide it in - validator, parse, method, re-initialization, stream-conflict or invalid event-ID errors, - and no longer logs raw session IDs. + On unsupported methods, validator responses with status 2xx, 304, Bearer challenge 400, + 401, 403, 405, 421 or 503 take precedence over the transport's 405. + The stateful transport omits the session ID from validator responses, echoes it in + transport-owned errors only when the request carried the exact ID, and no longer logs raw IDs. - Prompt message content blocks keep `annotations` and `meta`, and `resourceLink` blocks keep `size`, `icons`, and `meta`. - `Response.id` (`ID?`) represents JSON `null` distinctly from `""`, and rejects a `null` ID on a diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift index 2090b2af..d6ea46c4 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift @@ -374,15 +374,14 @@ public struct HTTPResponse: Sendable { } extension HTTPResponse { - /// Whether a validator's response answers a request whose method the - /// transport does not serve, instead of 405: a responder's answer (2xx or - /// 304), or a Host, Origin or authentication rejection (401, 403, 421, - /// or a 400 with a `WWW-Authenticate` challenge, RFC 6750 §3.1). + /// Whether a validator's response answers a method the transport does not + /// serve, including responder replies and authentication challenges. var answersUnsupportedMethod: Bool { (200..<300).contains(statusCode) || statusCode == 304 - || statusCode == 401 || statusCode == 403 || statusCode == 421 + || statusCode == 401 || statusCode == 403 || statusCode == 405 + || statusCode == 421 || statusCode == 503 || (statusCode == 400 && headers.keys.contains { - $0.lowercased() == HTTPHeaderName.wwwAuthenticate.lowercased() + $0.caseInsensitiveCompare(HTTPHeaderName.wwwAuthenticate) == .orderedSame }) } } diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift index 01581d98..7f9dedcb 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift @@ -383,8 +383,8 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { /// - **POST**: JSON-RPC messages (requests, notifications) /// - **GET**: Establish standalone SSE stream for server-initiated messages /// - **DELETE**: Terminate the session - /// - Others: a successful validator response, 401, 403, 421 or a 400 - /// Bearer challenge; otherwise 405 + /// - Others: a successful validator response, 304, 400 with an authentication + /// challenge, 401, 403, 405, 421 or 503; otherwise 405 /// /// The transport handles other requests while this one's validators /// suspend. A request whose session ends while its validators run gets @@ -453,7 +453,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { for _ in 0.. HTTPResponse { - var response = withoutSessionHeader(response) - if response.statusCode >= 400, let sessionID = echoedSessionID(for: request) { - response.headers[HTTPHeaderName.sessionID] = sessionID - } - return response - } - private func sessionHeaders() -> [String: String] { var headers: [String: String] = [:] if let sessionID { diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift index 436c6bb5..4e1eb0be 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift @@ -10,7 +10,7 @@ import Logging /// /// Behavior: /// - POST only; other methods get 405 unless a validator answers with 2xx, -/// 304, 401, 403 or 421, or a 400 Bearer challenge. +/// 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503. /// - No `Mcp-Session-Id` header is read or set. /// - The response is a single JSON body. When the handler sends notifications /// for the request (progress, logging) and the client accepts @@ -307,8 +307,8 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { /// /// Only POST is supported: /// - **POST**: JSON-RPC messages (requests, notifications) - /// - Other methods: a successful validator response, 401, 403, 421 or a - /// 400 Bearer challenge; otherwise 405 + /// - Other methods: a successful validator response, 304, 400 with an authentication + /// challenge, 401, 403, 405, 421 or 503; otherwise 405 /// /// The transport handles other requests while this one's validators /// suspend. A request whose validators finish after ``disconnect()`` gets @@ -364,12 +364,10 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { } let messageKind = normalized.flatMap(JSONRPCMessageKind.init(data:)) - // One probe for the id and the `_meta` version. - let fields = normalized.map(JSONRPCMessageFields.requestFields(in:)) var requestID: ID? if let messageKind { switch messageKind { - case .request: requestID = fields?.id + case .request(let id, _): requestID = id case .invalid(_, let id, _): requestID = id case .notification, .response, .invalidResponse: break } @@ -395,9 +393,11 @@ public actor StatelessHTTPServerTransport: HTTPServerTransport { guard let body, !body.isEmpty else { return .error(statusCode: 400, .parseError("Empty request body")) } - guard let normalized, let messageKind, let fields else { + guard let normalized, let messageKind else { return .error(statusCode: 400, JSONRPCMessageKind.classificationError(for: body)) } + // Decode the request headers only after validators accept the request. + let fields = JSONRPCMessageFields.requestFields(in: normalized) switch messageKind { case .invalid(_, _, let reason): diff --git a/Tests/MCPTests/SessionIDDisclosureTests.swift b/Tests/MCPTests/SessionIDDisclosureTests.swift index 765ad6f1..2ca92987 100644 --- a/Tests/MCPTests/SessionIDDisclosureTests.swift +++ b/Tests/MCPTests/SessionIDDisclosureTests.swift @@ -1,4 +1,5 @@ import Foundation +import Logging import Testing @testable import MCP @@ -7,6 +8,16 @@ private struct DisclosureSessionIDGenerator: SessionIDGenerator { func makeSessionID() -> String { "test-session-secret" } } +private struct UnicodeDisclosureSessionIDGenerator: SessionIDGenerator { + func makeSessionID() -> String { "test-session-secreK" } +} + +private struct ServiceUnavailableValidator: HTTPRequestValidator { + func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { + .error(statusCode: 503, .internalError("Service Unavailable")) + } +} + private struct LegacySessionHeaderValidator: HTTPRequestValidator { func validate(_ request: HTTPRequest, context: HTTPValidationContext) -> HTTPResponse? { guard request.method == "GET" else { return nil } @@ -45,6 +56,29 @@ struct SessionIDDisclosureTests { #expect(byteDifferent.headers[HTTPHeaderName.sessionID] == nil) } + @Test("Built-in validator rejections do not disclose the context session ID") + func builtInValidators() async throws { + let context = HTTPValidationContext( + method: "POST", sessionID: sessionID, + supportedProtocolVersions: Set(Version.handshake)) + let origin = try #require(OriginValidator.localhost().validate( + HTTPRequest(method: "POST", headers: [HTTPHeaderName.origin: "https://other.example"]), + context: context)) + let accept = try #require(AcceptHeaderValidator(mode: .requiresEventStream).validate( + HTTPRequest(method: "POST", headers: [HTTPHeaderName.accept: "application/json"]), + context: context)) + let contentType = try #require(ContentTypeValidator().validate( + HTTPRequest(method: "POST", headers: [HTTPHeaderName.contentType: "text/plain"]), + context: context)) + let version = try #require(ProtocolVersionValidator().validate( + HTTPRequest(method: "POST", headers: [HTTPHeaderName.protocolVersion: "unsupported"]), + context: context)) + let bearer = try #require(await makeBearerValidator().validate(HTTPRequest(method: "POST"), context: context)) + for response in [origin, accept, contentType, version, bearer] { + #expect(response.headers[HTTPHeaderName.sessionID] == nil) + } + } + private var headers: [String: String] { [ HTTPHeaderName.host: "localhost:3001", @@ -106,6 +140,11 @@ struct SessionIDDisclosureTests { #expect(response.statusCode == status) #expect(response.headers[HTTPHeaderName.sessionID] == nil, "\(request.method) \(response.statusCode)") } + for body in [Data(), Data("{not json".utf8)] { + let response = await transport.handleRequest(HTTPRequest(method: "POST", headers: headers, body: body)) + let json = try JSONDecoder().decode(Value.self, from: try #require(response.bodyData)) + #expect(json.objectValue?["error"]?.objectValue?["code"] == .int(-32600)) + } await transport.disconnect() } @@ -185,10 +224,132 @@ struct SessionIDDisclosureTests { known[HTTPHeaderName.sessionID] = sessionID let matching = await transport.handleRequest(HTTPRequest(method: "GET", headers: known)) #expect(matching.statusCode == 401) - #expect(matching.headers[HTTPHeaderName.sessionID] == sessionID) + #expect(matching.headers[HTTPHeaderName.sessionID] == nil) + await transport.disconnect() + } + + @Test("A public card response never carries the active session ID") + func publicCardDoesNotEchoSession() async throws { + let card = ServerCard( + name: "com.example/test", version: "1.0.0", description: "Test server.", + remotes: [.init(type: .streamableHTTP, url: "https://example.com/mcp")]) + let responder = try ServerCardResponder(card: card) + let metadata = ProtectedResourceMetadataResponder(metadata: OAuthProtectedResourceMetadata( + resource: "https://example.com/mcp", authorizationServers: ["https://example.com/auth"])) + let transport = try await startSession(validators: [responder, metadata, SessionValidator()]) + var known = headers + known[HTTPHeaderName.sessionID] = sessionID + let response = await transport.handleRequest( + HTTPRequest(method: "GET", headers: known, path: "/mcp/server-card")) + #expect(response.statusCode == 200) + #expect(response.headers[HTTPHeaderName.cacheControl] == "public, max-age=3600") + #expect(response.headers[HTTPHeaderName.sessionID] == nil) + let preflight = await transport.handleRequest( + HTTPRequest(method: "OPTIONS", headers: known, path: "/mcp/server-card")) + #expect(preflight.statusCode == 204) + #expect(preflight.headers[HTTPHeaderName.sessionID] == nil) + var revalidation = known + revalidation[HTTPHeaderName.ifNoneMatch] = response.headers[HTTPHeaderName.etag] + let cached = await transport.handleRequest( + HTTPRequest(method: "GET", headers: revalidation, path: "/mcp/server-card")) + #expect(cached.statusCode == 304) + #expect(cached.headers[HTTPHeaderName.sessionID] == nil) + let discovery = await transport.handleRequest(HTTPRequest( + method: "GET", headers: known, path: "/.well-known/oauth-protected-resource/mcp")) + #expect(discovery.statusCode == 200) + #expect(discovery.headers[HTTPHeaderName.sessionID] == nil) + await transport.disconnect() + } + + @Test("Authentication rejection does not echo a supplied session ID") + func rejectedBearerDoesNotEchoSession() async throws { + let transport = try await startSession( + validators: [OriginValidator.localhost(), makeBearerValidator(), SessionValidator()], + authorization: "Bearer valid") + var known = headers + known[HTTPHeaderName.sessionID] = sessionID + let response = await transport.handleRequest(HTTPRequest(method: "GET", headers: known)) + #expect(response.statusCode == 401) + #expect(response.headers[HTTPHeaderName.sessionID] == nil) + var badOrigin = known + badOrigin[HTTPHeaderName.origin] = "https://other.example" + let origin = await transport.handleRequest(HTTPRequest(method: "GET", headers: badOrigin)) + #expect(origin.statusCode == 403) + #expect(origin.headers[HTTPHeaderName.sessionID] == nil) + var badHost = known + badHost[HTTPHeaderName.host] = "other.example" + let host = await transport.handleRequest(HTTPRequest(method: "GET", headers: badHost)) + #expect(host.statusCode == 421) + #expect(host.headers[HTTPHeaderName.sessionID] == nil) await transport.disconnect() } + @Test("A terminated session compares IDs byte for byte without validators") + func terminatedSessionIDIsByteExact() async throws { + let transport = StatefulHTTPServerTransport( + sessionIDGenerator: UnicodeDisclosureSessionIDGenerator(), validators: []) + try await transport.connect() + let body = Data(#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"#.utf8) + let initialized = await transport.handleRequest(HTTPRequest(method: "POST", headers: headers, body: body)) + #expect(initialized.statusCode == 200) + await transport.disconnect() + let different = await transport.handleRequest(HTTPRequest( + method: "GET", headers: [HTTPHeaderName.sessionID: "test-session-secre\u{212A}"])) + #expect(different.statusCode == 404) + #expect(different.headers[HTTPHeaderName.sessionID] == nil) + let exact = await transport.handleRequest(HTTPRequest( + method: "GET", headers: [HTTPHeaderName.sessionID: "test-session-secreK"])) + #expect(exact.statusCode == 404) + #expect(exact.headers[HTTPHeaderName.sessionID] == "test-session-secreK") + } + + @Test("Session lifecycle logs omit the raw ID") + func sessionLogs() async throws { + let captured = CapturingLogHandler(minimumLevel: .info) + let logger = Logger(label: "mcp.test.session-disclosure") { _ in captured } + let transport = StatefulHTTPServerTransport( + sessionIDGenerator: DisclosureSessionIDGenerator(), validators: [], logger: logger) + try await transport.connect() + let body = Data(#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"#.utf8) + _ = await transport.handleRequest(HTTPRequest(method: "POST", headers: headers, body: body)) + await transport.disconnect() + #expect(captured.messages.contains { $0.contains("Session initialized") }) + #expect(captured.messages.contains { $0.contains("Terminating session") }) + #expect(!captured.messages.contains { $0.contains(sessionID) }) + } + + @Test("Unsupported methods keep Bearer challenges and responder status") + func unsupportedMethodResponses() async throws { + let bearer = makeBearerValidator() + let stateful = StatefulHTTPServerTransport(validators: [bearer]) + let stateless = StatelessHTTPServerTransport(validators: [bearer]) + let malformedHeaders = [HTTPHeaderName.authorization: "Bearer"] + for response in [ + await stateful.handleRequest(HTTPRequest(method: "PUT", headers: malformedHeaders)), + await stateful.handleRequest(HTTPRequest(method: "OPTIONS", headers: malformedHeaders)), + await stateless.handleRequest(HTTPRequest(method: "PUT", headers: malformedHeaders)), + await stateless.handleRequest(HTTPRequest(method: "GET", headers: malformedHeaders)), + ] { + #expect(response.statusCode == 400) + #expect(response.headers[HTTPHeaderName.wwwAuthenticate]?.contains("invalid_request") == true) + } + + let card = ServerCard( + name: "com.example/test", version: "1.0.0", description: "Test server.", + remotes: [.init(type: .streamableHTTP, url: "https://example.com/mcp")]) + let responder = try ServerCardResponder(card: card) + let withCard = StatefulHTTPServerTransport(validators: [responder]) + let statelessWithCard = StatelessHTTPServerTransport(validators: [responder]) + let cardRequest = HTTPRequest(method: "PUT", path: "/mcp/server-card") + for response in [await withCard.handleRequest(cardRequest), await statelessWithCard.handleRequest(cardRequest)] { + #expect(response.statusCode == 405) + #expect(response.headers[HTTPHeaderName.allow] == "GET, HEAD, OPTIONS") + } + + let unavailable = StatefulHTTPServerTransport(validators: [ServiceUnavailableValidator()]) + #expect(await unavailable.handleRequest(HTTPRequest(method: "PUT")).statusCode == 503) + } + @Test("Rejected Origin wins over a malformed body in both transports") func originBeforeParsing() async throws { var rejected = headers diff --git a/design/threat_model.md b/design/threat_model.md index 769c4fa5..8c316f4d 100644 --- a/design/threat_model.md +++ b/design/threat_model.md @@ -38,8 +38,9 @@ and side channels other than the `requestState` principal tag (compared in const **Request validation.** For POST, the transports classify the body to identify `initialize` before running validators; the stateless transport also extracts the request ID for errors. Validator rejections take precedence over parse errors. For unsupported HTTP methods, validator -responses with status 2xx, 304, 401, 403 or 421, and a 400 Bearer challenge, take precedence over 405. -Error responses carry `Mcp-Session-Id` only when the request carried the same ID. +responses with status 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or +503 take precedence over a transport-generated 405. Validator responses never carry +`Mcp-Session-Id`; transport-owned errors echo it only when the request carried the same ID. A request whose session is created, or dropped by a refused `initialize`, while its validators suspend is validated again, and none reaches a terminated session. `OriginValidator.localhost()`, the default, refuses a `Host` that is not a loopback host (421) and an diff --git a/docs/migration.md b/docs/migration.md index 556ebe12..47718309 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -68,7 +68,7 @@ each change that breaks source code. | Sampling with tools | `Client.Configuration.maximumContextInclusion` defaults to `.none`; tool-use/result rules and `sampling.tools` checked with -32602 / -32601 | Declare `sampling.tools`; raise `maximumContextInclusion` only if needed | | OAuth & HTTP redirects | Loopback URLs restricted to loopback peers; canonical RFC 3986 §6 resource URIs; same-origin credentials and redirect security; step-up key includes tool name for `tools/call` | Set `endpointOverrides` for local AS with remote MCP endpoint | | HTTP & stream transports | Terminated stateful session returns 400/404; 16 MiB message limit on stdio/network/HTTP; single-use transports (`connect()` after `disconnect()` throws `connectionClosed`); `HTTPClientTransport` connection limit 64 and SSE on Linux | Create a new transport to reconnect; raise `maximumMessageLength` on `NetworkTransport` if needed | -| Exact code-point matching | `ID`, `ProgressToken`, task IDs/owners, method names, SEP-2243 headers/keys, subscription URIs and `RequestState` audiences compare by exact Unicode scalars | Send matching Unicode scalar spellings | +| Exact code-point matching | `ID`, `ProgressToken`, task IDs/owners, `Mcp-Session-Id`, method names, SEP-2243 headers/keys, subscription URIs and `RequestState` audiences compare by exact Unicode scalars | Send matching Unicode scalar spellings | | Package & platforms | Swift 6.1 tools; adds swift-crypto and Yams, drops eventsource; minimums raised to macOS 15, iOS/iPadOS/Mac Catalyst/tvOS 18, watchOS 11, visionOS 2 | Use Xcode 16.3+, resolve packages, raise deployment targets (or stay on 0.12) | ## Breaking changes @@ -1821,6 +1821,11 @@ The specification's rules for sampling with tools (SEP-1577) are checked: ### HTTP server transports +Both server transports return header validation errors before malformed-body errors. On an +unsupported method, responder replies and authentication challenges take precedence over the +transport's 405. The stateful transport does not add `Mcp-Session-Id` to validator responses; +transport-owned errors echo it only when the request carried the same ID byte for byte. + `StatefulHTTPServerTransport`: - An unsupported `MCP-Protocol-Version` header is answered with HTTP 400 and diff --git a/docs/protocol.md b/docs/protocol.md index 7c97cd64..fcb5ae83 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -327,7 +327,7 @@ Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -3202 The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. -Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 401, 403 or 421, and a 400 with a Bearer challenge, take precedence over 405. Error responses include `Mcp-Session-Id` only if the request already carried the matching ID; 2xx and 304 answers from validators such as `ServerCardResponder` never do. A successful `initialize` still returns the newly assigned ID. +Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503 take precedence over a transport-generated 405. Validator responses do not include `Mcp-Session-Id`; transport-owned errors include it only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: @@ -390,7 +390,7 @@ Validation errors: `StatelessHTTPServerTransport` answers each POST with one exchange and keeps no session. One transport and one `Server` serve every client. -- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 401, 403, 421 or a 400 Bearer challenge. +- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503. A responder's 405 keeps its own `Allow` header. - `Mcp-Session-Id` is neither read nor set. - The reply is a single JSON body. When the handler sends notifications for the request (progress, logs, listen events) and the client accepts `text/event-stream`, the reply becomes an SSE stream that carries them and ends with the response. Without SSE in `Accept`, those notifications are dropped, and `subscriptions/listen` is refused with 406. - Each request gets an internal JSON-RPC id (`mcp-http-`) while in flight, so clients may reuse ids. The response carries the client's id again. diff --git a/docs/src/migration.src.md b/docs/src/migration.src.md index da7a3365..583fd6ca 100644 --- a/docs/src/migration.src.md +++ b/docs/src/migration.src.md @@ -66,7 +66,7 @@ each change that breaks source code. | Sampling with tools | `Client.Configuration.maximumContextInclusion` defaults to `.none`; tool-use/result rules and `sampling.tools` checked with -32602 / -32601 | Declare `sampling.tools`; raise `maximumContextInclusion` only if needed | | OAuth & HTTP redirects | Loopback URLs restricted to loopback peers; canonical RFC 3986 §6 resource URIs; same-origin credentials and redirect security; step-up key includes tool name for `tools/call` | Set `endpointOverrides` for local AS with remote MCP endpoint | | HTTP & stream transports | Terminated stateful session returns 400/404; 16 MiB message limit on stdio/network/HTTP; single-use transports (`connect()` after `disconnect()` throws `connectionClosed`); `HTTPClientTransport` connection limit 64 and SSE on Linux | Create a new transport to reconnect; raise `maximumMessageLength` on `NetworkTransport` if needed | -| Exact code-point matching | `ID`, `ProgressToken`, task IDs/owners, method names, SEP-2243 headers/keys, subscription URIs and `RequestState` audiences compare by exact Unicode scalars | Send matching Unicode scalar spellings | +| Exact code-point matching | `ID`, `ProgressToken`, task IDs/owners, `Mcp-Session-Id`, method names, SEP-2243 headers/keys, subscription URIs and `RequestState` audiences compare by exact Unicode scalars | Send matching Unicode scalar spellings | | Package & platforms | Swift 6.1 tools; adds swift-crypto and Yams, drops eventsource; minimums raised to macOS 15, iOS/iPadOS/Mac Catalyst/tvOS 18, watchOS 11, visionOS 2 | Use Xcode 16.3+, resolve packages, raise deployment targets (or stay on 0.12) | ## Breaking changes @@ -1530,6 +1530,11 @@ The specification's rules for sampling with tools (SEP-1577) are checked: ### HTTP server transports +Both server transports return header validation errors before malformed-body errors. On an +unsupported method, responder replies and authentication challenges take precedence over the +transport's 405. The stateful transport does not add `Mcp-Session-Id` to validator responses; +transport-owned errors echo it only when the request carried the same ID byte for byte. + `StatefulHTTPServerTransport`: - An unsupported `MCP-Protocol-Version` header is answered with HTTP 400 and diff --git a/docs/src/protocol.src.md b/docs/src/protocol.src.md index 554b16b9..8d581245 100644 --- a/docs/src/protocol.src.md +++ b/docs/src/protocol.src.md @@ -234,7 +234,7 @@ Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -3202 The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. -Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 401, 403 or 421, and a 400 with a Bearer challenge, take precedence over 405. Error responses include `Mcp-Session-Id` only if the request already carried the matching ID; 2xx and 304 answers from validators such as `ServerCardResponder` never do. A successful `initialize` still returns the newly assigned ID. +Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503 take precedence over a transport-generated 405. Validator responses do not include `Mcp-Session-Id`; transport-owned errors include it only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: @@ -257,7 +257,7 @@ Validation errors: `StatelessHTTPServerTransport` answers each POST with one exchange and keeps no session. One transport and one `Server` serve every client. -- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 401, 403, 421 or a 400 Bearer challenge. +- POST only; other methods get 405 with `Allow: POST` unless a validator answers with 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503. A responder's 405 keeps its own `Allow` header. - `Mcp-Session-Id` is neither read nor set. - The reply is a single JSON body. When the handler sends notifications for the request (progress, logs, listen events) and the client accepts `text/event-stream`, the reply becomes an SSE stream that carries them and ends with the response. Without SSE in `Accept`, those notifications are dropped, and `subscriptions/listen` is refused with 406. - Each request gets an internal JSON-RPC id (`mcp-http-`) while in flight, so clients may reuse ids. The response carries the client's id again. diff --git a/docs/src/troubleshooting.src.md b/docs/src/troubleshooting.src.md index dc42a254..a33d49c4 100644 --- a/docs/src/troubleshooting.src.md +++ b/docs/src/troubleshooting.src.md @@ -197,8 +197,8 @@ Server transports: | 403 | both | An `Origin` header that the `OriginValidator` does not allow. | | 404 | stateless | At 2026-07-28, -32601; any request after the transport stopped. | | 404 | stateful | An unknown or expired `Mcp-Session-Id`, including any ID sent after the session ended. | -| 405 | stateless | Any method other than POST once the Host, Origin and authentication checks pass. The `Allow` header is `POST`. | -| 405 | stateful | Any method other than GET, POST and DELETE once the Host, Origin and authentication checks pass. | +| 405 | stateless | An unsupported method after validation. The transport sets `Allow: POST`; a responder's 405 keeps its own `Allow` header. Validator 2xx, 304, Bearer challenge 400, 401, 403, 421 and 503 responses take precedence. | +| 405 | stateful | An unsupported method after validation. The transport sets `Allow: GET, POST, DELETE`; a responder's 405 keeps its own `Allow` header. Validator 2xx, 304, Bearer challenge 400, 401, 403, 421 and 503 responses take precedence. | | 406 | both | An `Accept` header without `application/json` (stateless), or without both `application/json` and `text/event-stream` (stateful POST). | | 409 | stateful | A second GET stream for the session. | | 415 | both | A POST whose `Content-Type` is not `application/json`. | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 7145c9be..6ee2cda6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -277,8 +277,8 @@ Server transports: | 403 | both | An `Origin` header that the `OriginValidator` does not allow. | | 404 | stateless | At 2026-07-28, -32601; any request after the transport stopped. | | 404 | stateful | An unknown or expired `Mcp-Session-Id`, including any ID sent after the session ended. | -| 405 | stateless | Any method other than POST once the Host, Origin and authentication checks pass. The `Allow` header is `POST`. | -| 405 | stateful | Any method other than GET, POST and DELETE once the Host, Origin and authentication checks pass. | +| 405 | stateless | An unsupported method after validation. The transport sets `Allow: POST`; a responder's 405 keeps its own `Allow` header. Validator 2xx, 304, Bearer challenge 400, 401, 403, 421 and 503 responses take precedence. | +| 405 | stateful | An unsupported method after validation. The transport sets `Allow: GET, POST, DELETE`; a responder's 405 keeps its own `Allow` header. Validator 2xx, 304, Bearer challenge 400, 401, 403, 421 and 503 responses take precedence. | | 406 | both | An `Accept` header without `application/json` (stateless), or without both `application/json` and `text/event-stream` (stateful POST). | | 409 | stateful | A second GET stream for the session. | | 415 | both | A POST whose `Content-Type` is not `application/json`. | From 8221ffe5460e41db2c5dede64a9c908e3e7c439d Mon Sep 17 00:00:00 2001 From: EhsanAzish80 Date: Sun, 6 Dec 2026 16:54:38 +0300 Subject: [PATCH 5/5] feat: bind stateful HTTP sessions to the creating principal 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. --- CHANGELOG.md | 5 + .../StatefulHTTPServerTransport.swift | 201 ++++++-- .../SessionPrincipalBindingTests.swift | 439 ++++++++++++++++++ design/threat_model.md | 5 + docs/protocol.md | 8 +- docs/src/protocol.src.md | 8 +- docs/src/troubleshooting.src.md | 2 +- docs/troubleshooting.md | 2 +- 8 files changed, 629 insertions(+), 41 deletions(-) create mode 100644 Tests/MCPTests/SessionPrincipalBindingTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 7182edef..ae19c7fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -390,6 +390,9 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha `UnsubscribeFromResource.Parameters.init(uri:meta:)` are public, and `Client.subscribedResourceURIs` lists active handshake subscriptions in addition to 2026-07-28 listen streams. +- `StatefulHTTPServerTransport(sessionPrincipal:)` binds a session to the principal of the + `initialize` request that created it; requests from another principal get the 404 of an unknown + session. - `DataURL`: explicit RFC 2397 `data:` URL value type (`Codable`, `Hashable`, `Sendable`) with strict RFC 2045 token header validation and MIME type normalization. - From `main` after 0.12.1: `Implementation` carries `description`, `websiteURL` and `icons`, sent @@ -405,6 +408,8 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha 401, 403, 405, 421 or 503 take precedence over the transport's 405. The stateful transport omits the session ID from validator responses, echoes it in transport-owned errors only when the request carried the exact ID, and no longer logs raw IDs. +- A refused `initialize` on the stateful transport closes the dropped session's streams and + forgets its stored events, so a session created next on the transport receives none of them. - Prompt message content blocks keep `annotations` and `meta`, and `resourceLink` blocks keep `size`, `icons`, and `meta`. - `Response.id` (`ID?`) represents JSON `null` distinctly from `""`, and rejects a `null` ID on a diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift index 7f9dedcb..0a9f8e68 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift @@ -37,6 +37,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { private let sessionIDGenerator: any SessionIDGenerator private let validation: StandardValidationPipeline private let retryInterval: Duration? + private let sessionPrincipal: SessionPrincipal? // MARK: - State @@ -53,6 +54,26 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { /// checks `terminated` after its validators ran instead, and running /// them again would repeat their work, such as a token introspection. private var stateGeneration = 0 + /// The principal that created the session, when `sessionPrincipal` binds + /// sessions; `nil` while there is no bound session. Set and cleared with + /// `sessionID`, so it changes only with `stateGeneration`. + private var owner: SessionOwner? + + /// The caller that created a bound session. + private struct SessionOwner { + /// What `sessionPrincipal` returned for the `initialize` request. + let principal: String? + + /// Whether a request whose `sessionPrincipal` is `principal` may use + /// the session: the same principal byte for byte, or `nil` for both. + func admits(_ principal: String?) -> Bool { + switch (self.principal, principal) { + case (nil, nil): true + case (let owner?, let caller?): owner.isExactly(caller) + default: false + } + } + } // MARK: - Incoming message stream (client → server) @@ -182,6 +203,13 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // MARK: - Init + /// Returns who sent a request, such as the subject of the token a + /// validator verified, or `nil` for a request without a principal. + /// + /// See the `sessionPrincipal` parameter of + /// ``init(sessionIDGenerator:validators:retryInterval:eventStoreCapacity:eventStoreByteCapacity:sessionPrincipal:logger:)``. + public typealias SessionPrincipal = @Sendable (_ request: HTTPRequest) async -> String? + /// The validators the transport runs when `init` is called without /// `validators:`, in order: `OriginValidator.localhost()`, /// `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, @@ -229,6 +257,24 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { /// - eventStoreByteCapacity: The most bytes of messages kept for /// replay in this session. Defaults to 16 MiB. The newest event is /// always kept. + /// - sessionPrincipal: Binds the session to the caller that creates it. + /// Return who sent a request, such as the subject of its verified + /// token, or `nil` for a request without one. Derive it only from + /// credentials a validator in `validators` verified, such as the token + /// that ``BearerTokenValidator`` accepted: a header the client sets + /// freely would let any caller claim the session. The transport calls it + /// once the validators accept an `initialize`, or a POST, GET or + /// DELETE on the session. It records the answer for the `initialize` + /// that creates the session and refuses every later request whose + /// answer differs, byte for byte, with the 404 of an unknown session, + /// including a stream resumption with `Last-Event-ID`. A second + /// `initialize` on the session gets that 404 without a call, and once + /// the session has ended, every caller gets it. A session + /// created with `nil` admits only requests whose answer is `nil` too. + /// A response to a request not yet checked this way, such as a + /// validator's rejection, does not carry the bound session's ID. The + /// closure may suspend, as a validator may. Without it (the default), + /// any request that passes the validators may use the session. /// - logger: Optional logger. If `nil`, a no-op logger is used. public init( sessionIDGenerator: any SessionIDGenerator = UUIDSessionIDGenerator(), @@ -236,6 +282,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { retryInterval: Duration? = nil, eventStoreCapacity: Int = 1000, eventStoreByteCapacity: Int = 16 << 20, + sessionPrincipal: SessionPrincipal? = nil, logger: Logger? = nil ) { self.eventStoreCapacity = max(1, eventStoreCapacity) @@ -243,6 +290,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { self.sessionIDGenerator = sessionIDGenerator self.validation = StandardValidationPipeline(validators: validators) self.retryInterval = retryInterval + self.sessionPrincipal = sessionPrincipal self.logger = logger ?? Logger( label: "mcp.transport.http.server.stateful", factory: { _ in SwiftLogNoOpLogHandler() } @@ -253,7 +301,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { self.incomingContinuation = continuation } - /// Replaced by ``init(sessionIDGenerator:validators:retryInterval:eventStoreCapacity:eventStoreByteCapacity:logger:)``. + /// Replaced by ``init(sessionIDGenerator:validators:retryInterval:eventStoreCapacity:eventStoreByteCapacity:sessionPrincipal:logger:)``. @available(*, unavailable, message: "Pass retryInterval as a Duration, for example .milliseconds(3000)") public init( sessionIDGenerator: any SessionIDGenerator = UUIDSessionIDGenerator(), @@ -266,7 +314,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { fatalError() } - /// Replaced by ``init(sessionIDGenerator:validators:retryInterval:eventStoreCapacity:eventStoreByteCapacity:logger:)``. + /// Replaced by ``init(sessionIDGenerator:validators:retryInterval:eventStoreCapacity:eventStoreByteCapacity:sessionPrincipal:logger:)``. @available( *, unavailable, message: "Use init(sessionIDGenerator:validators:retryInterval:logger:); pass validators directly or omit validators: for defaults; retryInterval is a Duration" @@ -349,6 +397,8 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { if JSONRPCMessageFields.errorCode(in: data) != nil { logger.info("Initialization failed; session dropped") sessionID = nil + owner = nil + dropSessionStreams() stateGeneration += 1 } } @@ -394,12 +444,13 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { /// - Returns: The HTTP response to write back to the client. public func handleRequest(_ request: HTTPRequest) async -> HTTPResponse { 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) } switch request.method.uppercased() { @@ -413,11 +464,12 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // Validators that answer a request themselves, such as // ServerCardResponder for a CORS preflight or a HEAD (200 or // 304), run for every method. - let response = await validate(request) { + // These methods do not use the session: its principal is not checked. + let response = await validate(request, resolvingPrincipal: false) { HTTPValidationContext( method: request.method.uppercased(), sessionID: sessionID, supportedProtocolVersions: Set(Version.handshake)) - } + }.response guard !terminated else { return terminatedResponse(to: request, validated: response) } if let response, response.answersUnsupportedMethod { return response @@ -425,7 +477,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { return .error( statusCode: 405, .invalidRequest("Method Not Allowed"), - sessionID: echoedSessionID(for: request), + sessionID: unverifiedEchoedSessionID(for: request), extraHeaders: [HTTPHeaderName.allow: "GET, POST, DELETE"] ) } @@ -437,39 +489,92 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { /// changes each time they run. private static let maxValidationRuns = 3 + /// What ``validate(_:resolvingPrincipal:makeContext:)`` decided for a request. + private struct Validation { + /// The validators' response, the 404 of a session the request's + /// principal did not create, or `nil` to let the request through. + var response: HTTPResponse? + /// What `sessionPrincipal` returned for the request; `nil` when it + /// returned `nil` or was not called. + var principal: String? + } + + /// The answer to a request on a session its principal did not create: + /// the 404 that ``SessionValidator`` gives an unknown session (same + /// status, headers and JSON body), so it does not confirm the ID. A test + /// keeps the two equal. + private static var unknownSessionResponse: HTTPResponse { + .error(statusCode: 404, .invalidRequest("Not Found: Invalid or expired session ID")) + } + /// Runs the validators against the current session state. Synchronous /// validators run on the actor without suspending; only the others are - /// awaited. When the session state changes while they run, runs them - /// again against the new state, up to `maxValidationRuns` times; the - /// caller re-checks `terminated` before it acts on the request. + /// awaited. When the validators let the request through and + /// `sessionPrincipal` binds sessions, resolves the request's principal for + /// an `initialize` or for a request on a bound session, and refuses a + /// request on a session that another principal created. When the session + /// state changes while they run, runs them again against the new state, + /// up to `maxValidationRuns` times; the caller re-checks `terminated` + /// before it acts on the request. /// - /// - Returns: The validators' response, `nil` to let the request through, - /// or 503 when the state changed during every run: a response from a - /// state that is no longer current could let a request into a session - /// it was not validated against. + /// - Parameter resolvingPrincipal: `false` for a request the transport + /// answers without using the session. + /// - Returns: The validators' response, the 404 of a session another + /// principal created, `nil` to let the request through, or 503 when the + /// state changed during every run: a response from a state that is no + /// longer current could let a request into a session it was not + /// validated against. private func validate( - _ request: HTTPRequest, makeContext: () -> HTTPValidationContext - ) async -> HTTPResponse? { + _ request: HTTPRequest, resolvingPrincipal: Bool = true, makeContext: () -> HTTPValidationContext + ) async -> Validation { for _ in 0.. HTTPResponse { if let response { return withoutSessionHeader(response) } let requestedSessionID = request.value(forHeader: HTTPHeaderName.sessionID) let hasEndedSession = sessionID != nil && requestedSessionID != nil + if owner != nil, hasEndedSession { + return Self.unknownSessionResponse + } return .error( statusCode: hasEndedSession ? 404 : 400, .invalidRequest(hasEndedSession @@ -501,11 +606,11 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { Version.handshake.contains($0) ? nil : $0 }) { - let errorResponse = await validate(request) { + let errorResponse = await validate(request, resolvingPrincipal: false) { HTTPValidationContext( method: "POST", sessionID: nil, isInitializeRequest: true, supportedProtocolVersions: Set(Version.handshake)) - } + }.response guard !terminated else { return terminatedResponse(to: request, validated: errorResponse) } if let errorResponse { return errorResponse @@ -515,11 +620,11 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { statusCode: 400, .unsupportedProtocolVersion(supported: Version.handshake, requested: version), id: id, - sessionID: echoedSessionID(for: request) + sessionID: unverifiedEchoedSessionID(for: request) ) } - let errorResponse = await validate(request) { + let validated = await validate(request) { HTTPValidationContext( method: "POST", sessionID: sessionID, @@ -527,6 +632,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { supportedProtocolVersions: Set(Version.handshake) ) } + let errorResponse = validated.response // The session may have ended while the validators ran; nothing below // may open a stream or reach the server then. guard !terminated else { return terminatedResponse(to: request, validated: errorResponse) } @@ -548,7 +654,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // Handle initialization request specially. A second `initialize` // validated while the first created the session gets 400 here. if messageKind.isInitializeRequest { - return handleInitializationRequest(body, request: request) + return handleInitializationRequest(body, request: request, principal: validated.principal) } // Handle by message type @@ -592,13 +698,15 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { } } - private func handleInitializationRequest(_ body: Data, request: HTTPRequest) -> HTTPResponse { + private func handleInitializationRequest( + _ body: Data, request: HTTPRequest, principal: String? + ) -> HTTPResponse { // Reject re-initialization at the transport level if sessionID != nil { return .error( statusCode: 400, .invalidRequest("Bad Request: Session already initialized"), - sessionID: echoedSessionID(for: request) + sessionID: unverifiedEchoedSessionID(for: request) ) } @@ -615,6 +723,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { } self.sessionID = newSessionID + owner = sessionPrincipal == nil ? nil : SessionOwner(principal: principal) stateGeneration += 1 logger.info("Session initialized") @@ -672,7 +781,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { isInitializeRequest: false, supportedProtocolVersions: Set(Version.handshake) ) - } + }.response // A stream registered on a terminated session would never finish. guard !terminated else { return terminatedResponse(to: request, validated: errorResponse) } if let errorResponse { @@ -726,7 +835,7 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { isInitializeRequest: false, supportedProtocolVersions: Set(Version.handshake) ) - } + }.response // A DELETE validated while another one ended the session gets 404. guard !terminated else { return terminatedResponse(to: request, validated: errorResponse) } if let errorResponse { @@ -996,6 +1105,14 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { return sessionID } + /// The session ID for a response to a request that has not been checked + /// against the session's principal: as ``echoedSessionID(for:)`` while + /// the session is not bound, and `nil` for a bound one, so a caller that + /// learned the ID cannot confirm it. + private func unverifiedEchoedSessionID(for request: HTTPRequest) -> String? { + owner == nil ? echoedSessionID(for: request) : nil + } + private func sessionHeaders() -> [String: String] { var headers: [String: String] = [:] if let sessionID { @@ -1052,6 +1169,28 @@ public actor StatefulHTTPServerTransport: HTTPServerTransport { // MARK: - Termination + /// 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() { + for (_, continuation) in requestSSEContinuations { + continuation.finish() + } + requestSSEContinuations.removeAll() + httpRequestContexts.removeAll() + openRequestIDs.removeAll() + streamGenerations.removeAll() + standaloneSSEContinuation?.finish() + standaloneSSEContinuation = nil + storedEvents.removeAll() + storedEventsHead = 0 + storedBytes = 0 + storedEventCounts.removeAll() + evictedThrough.removeAll() + } + /// 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. diff --git a/Tests/MCPTests/SessionPrincipalBindingTests.swift b/Tests/MCPTests/SessionPrincipalBindingTests.swift new file mode 100644 index 00000000..f946b6b6 --- /dev/null +++ b/Tests/MCPTests/SessionPrincipalBindingTests.swift @@ -0,0 +1,439 @@ +import Foundation +import Testing + +@testable import MCP + +/// Counts the calls of a `sessionPrincipal` closure. +private actor PrincipalCalls { + private(set) var count = 0 + func record() { count += 1 } +} + +/// Counts the validator runs for requests of one principal. +private actor ValidatorRuns { + private(set) var count = 0 + func record() { count += 1 } +} + +private struct CountingValidator: HTTPRequestValidator { + let runs: ValidatorRuns + let principal: String + + func validate(_ request: HTTPRequest, context: HTTPValidationContext) async -> HTTPResponse? { + if request.value(forHeader: "X-Test-Principal") == principal { await runs.record() } + return nil + } +} + +@Suite("Stateful HTTP session principal binding") +struct SessionPrincipalBindingTests { + private static let principalHeader = "X-Test-Principal" + + private static let initializeBody = Data( + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"# + .utf8) + private static let notificationBody = Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8) + + /// The principal is the value of `X-Test-Principal`, or `nil` without one. + private static let principalFromHeader: StatefulHTTPServerTransport.SessionPrincipal = { request in + request.value(forHeader: SessionPrincipalBindingTests.principalHeader) + } + + private func headers(sessionID: String? = nil, principal: String? = nil) -> [String: String] { + var headers = [ + HTTPHeaderName.accept: "application/json, text/event-stream", + HTTPHeaderName.contentType: "application/json", + ] + headers[HTTPHeaderName.sessionID] = sessionID + headers[Self.principalHeader] = principal + return headers + } + + private func makeTransport( + validators: [any HTTPRequestValidator] = [SessionValidator()], + sessionPrincipal: StatefulHTTPServerTransport.SessionPrincipal? = SessionPrincipalBindingTests.principalFromHeader + ) async throws -> StatefulHTTPServerTransport { + let transport = StatefulHTTPServerTransport(validators: validators, sessionPrincipal: sessionPrincipal) + try await transport.connect() + return transport + } + + /// Sends `initialize` as `principal` and returns the new session ID. + private func initialize(_ transport: StatefulHTTPServerTransport, as principal: String?) async throws -> String { + let response = await transport.handleRequest( + HTTPRequest(method: "POST", headers: headers(principal: principal), body: Self.initializeBody)) + #expect(response.statusCode == 200) + return try #require(response.headers[HTTPHeaderName.sessionID]) + } + + private func notify( + _ transport: StatefulHTTPServerTransport, sessionID: String, as principal: String? + ) async -> HTTPResponse { + await transport.handleRequest( + HTTPRequest( + method: "POST", headers: headers(sessionID: sessionID, principal: principal), + body: Self.notificationBody)) + } + + private func expectUnknownSession(_ response: HTTPResponse, sourceLocation: SourceLocation = #_sourceLocation) { + #expect(response.statusCode == 404, sourceLocation: sourceLocation) + #expect(response.headers[HTTPHeaderName.sessionID] == nil, sourceLocation: sourceLocation) + } + + @Test("The creating principal keeps using the session") + func ownerIsAdmitted() async throws { + let transport = try await makeTransport() + let sessionID = try await initialize(transport, as: "alice") + + let posted = await notify(transport, sessionID: sessionID, as: "alice") + #expect(posted.statusCode == 202) + #expect(posted.headers[HTTPHeaderName.sessionID] == sessionID) + + let stream = await transport.handleRequest( + HTTPRequest(method: "GET", headers: headers(sessionID: sessionID, principal: "alice"))) + #expect(stream.statusCode == 200) + #expect(stream.headers[HTTPHeaderName.sessionID] == sessionID) + await transport.disconnect() + } + + @Test("Another principal gets the 404 of an unknown session for POST, GET and DELETE") + func otherPrincipalIsRefused() async throws { + let transport = try await makeTransport() + let sessionID = try await initialize(transport, as: "alice") + + expectUnknownSession(await notify(transport, sessionID: sessionID, as: "mallory")) + expectUnknownSession( + await transport.handleRequest( + HTTPRequest(method: "GET", headers: headers(sessionID: sessionID, principal: "mallory")))) + expectUnknownSession( + await transport.handleRequest( + HTTPRequest(method: "DELETE", headers: headers(sessionID: sessionID, principal: "mallory")))) + // A caller without a principal is another principal too. + expectUnknownSession(await notify(transport, sessionID: sessionID, as: nil)) + + // The refused DELETE did not end the session. + #expect(await notify(transport, sessionID: sessionID, as: "alice").statusCode == 202) + await transport.disconnect() + } + + @Test("Another principal cannot resume or replace the owner's streams") + func otherPrincipalCannotResume() async throws { + let transport = try await makeTransport() + let sessionID = try await initialize(transport, as: "alice") + let owned = await transport.handleRequest( + HTTPRequest(method: "GET", headers: headers(sessionID: sessionID, principal: "alice"))) + #expect(owned.statusCode == 200) + try await transport.send(Data(#"{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}"#.utf8)) + let eventID = try #require(await transport.storedEventIDs.last) + + var resume = headers(sessionID: sessionID, principal: "mallory") + resume[HTTPHeaderName.lastEventID] = eventID + expectUnknownSession(await transport.handleRequest(HTTPRequest(method: "GET", headers: resume))) + + // The owner's stream is still the session's stream: a second GET conflicts. + let second = await transport.handleRequest( + HTTPRequest(method: "GET", headers: headers(sessionID: sessionID, principal: "alice"))) + #expect(second.statusCode == 409) + await transport.disconnect() + } + + @Test("The refusal is the 404 SessionValidator gives an unknown session") + func refusalMatchesUnknownSession() async throws { + let transport = try await makeTransport() + let sessionID = try await initialize(transport, as: "alice") + let refused = await notify(transport, sessionID: sessionID, as: "mallory") + let unknown = await notify(transport, sessionID: "not-a-session", as: "alice") + #expect(refused.statusCode == unknown.statusCode) + #expect(refused.headers == unknown.headers) + guard case .data(let refusedBody) = refused.body, case .data(let unknownBody) = unknown.body else { + Issue.record("Expected data bodies") + return + } + // HTTPResponse.error does not sort JSON keys: compare the documents. + let decoder = JSONDecoder() + #expect(try decoder.decode(Value.self, from: refusedBody) == decoder.decode(Value.self, from: unknownBody)) + await transport.disconnect() + } + + @Test("Principals are compared byte for byte") + func byteExactComparison() async throws { + let transport = try await makeTransport() + let sessionID = try await initialize(transport, as: "user-K") + // U+212A KELVIN SIGN is canonically equivalent to "K" but another principal. + expectUnknownSession(await notify(transport, sessionID: sessionID, as: "user-\u{212A}")) + #expect(await notify(transport, sessionID: sessionID, as: "user-K").statusCode == 202) + await transport.disconnect() + } + + @Test("A session created without a principal admits only callers without one") + func nilPrincipalSession() async throws { + let transport = try await makeTransport() + let sessionID = try await initialize(transport, as: nil) + #expect(await notify(transport, sessionID: sessionID, as: nil).statusCode == 202) + expectUnknownSession(await notify(transport, sessionID: sessionID, as: "alice")) + await transport.disconnect() + } + + @Test("Without sessionPrincipal any caller that passes the validators uses the session") + func unboundByDefault() async throws { + let transport = try await makeTransport(sessionPrincipal: nil) + let sessionID = try await initialize(transport, as: "alice") + #expect(await notify(transport, sessionID: sessionID, as: "mallory").statusCode == 202) + await transport.disconnect() + } + + @Test("A bound session's ID is not confirmed to callers that were not checked against it") + func noEchoBeforeTheCheck() async throws { + let transport = try await makeTransport(validators: [ + AcceptHeaderValidator(mode: .requiresEventStream), SessionValidator(), + ]) + let sessionID = try await initialize(transport, as: "alice") + + // A validator rejection: the principal is not checked, so no echo. + var badAccept = headers(sessionID: sessionID, principal: "alice") + badAccept[HTTPHeaderName.accept] = "application/json" + let rejected = await transport.handleRequest( + HTTPRequest(method: "POST", headers: badAccept, body: Self.notificationBody)) + #expect(rejected.statusCode == 406) + #expect(rejected.headers[HTTPHeaderName.sessionID] == nil) + + // An unsupported method does not use the session: 405 without echo. + let method = await transport.handleRequest( + HTTPRequest(method: "PUT", headers: headers(sessionID: sessionID, principal: "mallory"))) + #expect(method.statusCode == 405) + #expect(method.headers[HTTPHeaderName.sessionID] == nil) + + // A second initialize gets the 404 of an unknown session, from any principal. + for principal in ["mallory", "alice"] { + expectUnknownSession( + await transport.handleRequest( + HTTPRequest( + method: "POST", headers: headers(sessionID: sessionID, principal: principal), + body: Self.initializeBody))) + } + + // Once admitted, errors still carry the ID. + let malformed = await transport.handleRequest( + HTTPRequest( + method: "POST", headers: headers(sessionID: sessionID, principal: "alice"), + body: Data("{not json".utf8))) + #expect(malformed.statusCode == 400) + #expect(malformed.headers[HTTPHeaderName.sessionID] == sessionID) + await transport.disconnect() + } + + @Test("A refused initialize drops the binding with the session") + func refusedInitializeDropsBinding() async throws { + let transport = try await makeTransport() + let first = try await initialize(transport, as: "alice") + // The server refuses the initialize (for example its initialize hook threw). + try await transport.send( + Data(#"{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"refused"}}"#.utf8)) + + let second = try await initialize(transport, as: "bob") + #expect(second != first) + #expect(await notify(transport, sessionID: second, as: "bob").statusCode == 202) + expectUnknownSession(await notify(transport, sessionID: second, as: "alice")) + await transport.disconnect() + } + + @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() + } + + // MARK: - Owner operations + + @Test("The owner can send requests, resume its stream and end the session") + func ownerOperations() async throws { + let transport = try await makeTransport() + let sessionID = try await initialize(transport, as: "alice") + let ping = Data(#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#.utf8) + + expectUnknownSession( + await transport.handleRequest( + HTTPRequest(method: "POST", headers: headers(sessionID: sessionID, principal: "mallory"), body: ping))) + let request = await transport.handleRequest( + HTTPRequest(method: "POST", headers: headers(sessionID: sessionID, principal: "alice"), body: ping)) + #expect(request.statusCode == 200) + + let stream = await transport.handleRequest( + HTTPRequest(method: "GET", headers: headers(sessionID: sessionID, principal: "alice"))) + #expect(stream.statusCode == 200) + try await transport.send(Data(#"{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}"#.utf8)) + let eventID = try #require(await transport.storedEventIDs.last) + var resume = headers(sessionID: sessionID, principal: "alice") + resume[HTTPHeaderName.lastEventID] = eventID + #expect(await transport.handleRequest(HTTPRequest(method: "GET", headers: resume)).statusCode == 200) + + let deleted = await transport.handleRequest( + HTTPRequest(method: "DELETE", headers: headers(sessionID: sessionID, principal: "alice"))) + #expect(deleted.statusCode == 200) + await transport.disconnect() + } + + @Test("A second initialize on a bound session is refused without calling sessionPrincipal") + func secondInitializeSkipsResolver() async throws { + let calls = PrincipalCalls() + let transport = try await makeTransport(sessionPrincipal: { request in + await calls.record() + return request.value(forHeader: SessionPrincipalBindingTests.principalHeader) + }) + let sessionID = try await initialize(transport, as: "alice") + #expect(await calls.count == 1) + for sessionHeader in [sessionID, nil] { + expectUnknownSession( + await transport.handleRequest( + HTTPRequest( + method: "POST", headers: headers(sessionID: sessionHeader, principal: "alice"), + body: Self.initializeBody))) + } + #expect(await calls.count == 1) + await transport.disconnect() + } + + @Test("Without sessionPrincipal a second initialize still gets 400") + func secondInitializeUnbound() async throws { + let transport = try await makeTransport(sessionPrincipal: nil) + let sessionID = try await initialize(transport, as: "alice") + let second = await transport.handleRequest( + HTTPRequest( + method: "POST", headers: headers(sessionID: sessionID, principal: "alice"), + body: Self.initializeBody)) + #expect(second.statusCode == 400) + await transport.disconnect() + } + + // MARK: - Terminated and dropped sessions + + @Test("A terminated bound session answers every caller as an unknown session") + func terminatedBoundSession() async throws { + let calls = PrincipalCalls() + let transport = try await makeTransport(sessionPrincipal: { request in + await calls.record() + return request.value(forHeader: SessionPrincipalBindingTests.principalHeader) + }) + let sessionID = try await initialize(transport, as: "alice") + let deleted = await transport.handleRequest( + HTTPRequest(method: "DELETE", headers: headers(sessionID: sessionID, principal: "alice"))) + #expect(deleted.statusCode == 200) + let callsBefore = await calls.count + + let unknown = await notify(transport, sessionID: "not-a-session", as: "mallory") + for principal in ["mallory", "alice"] { + let response = await notify(transport, sessionID: sessionID, as: principal) + expectUnknownSession(response) + guard case .data(let body) = response.body, case .data(let unknownBody) = unknown.body else { + Issue.record("Expected data bodies") + continue + } + let decoder = JSONDecoder() + #expect(try decoder.decode(Value.self, from: body) == decoder.decode(Value.self, from: unknownBody)) + } + // A terminated session's requests do not call sessionPrincipal. + #expect(await calls.count == callsBefore) + await transport.disconnect() + } + + @Test("A refused initialize closes the dropped session's streams and forgets its events") + func refusedInitializeClosesStreams() async throws { + let transport = try await makeTransport() + let first = try await initialize(transport, as: "alice") + let stream = await transport.handleRequest( + HTTPRequest(method: "GET", headers: headers(sessionID: first, principal: "alice"))) + #expect(stream.statusCode == 200) + try await transport.send(Data(#"{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}"#.utf8)) + #expect(await transport.storedEventIDs.isEmpty == false) + + try await transport.send( + Data(#"{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"refused"}}"#.utf8)) + #expect(await transport.storedEventIDs.isEmpty) + + // The next session opens its own GET stream: the dropped one is gone. + let second = try await initialize(transport, as: "bob") + let bobStream = await transport.handleRequest( + HTTPRequest(method: "GET", headers: headers(sessionID: second, principal: "bob"))) + #expect(bobStream.statusCode == 200) + await transport.disconnect() + } + + // MARK: - A sessionPrincipal that suspends + + @Test("A request whose session ends while sessionPrincipal suspends gets the unknown-session 404", + .timeLimit(.minutes(1))) + func terminationWhilePrincipalSuspends() async throws { + let gate = ValidationGate() + let transport = try await makeTransport(sessionPrincipal: { request in + if request.value(forHeader: "X-Slow") != nil { await gate.wait() } + return request.value(forHeader: SessionPrincipalBindingTests.principalHeader) + }) + let sessionID = try await initialize(transport, as: "alice") + + var slow = headers(sessionID: sessionID, principal: "alice") + slow["X-Slow"] = "1" + let post = Task { + await transport.handleRequest(HTTPRequest(method: "POST", headers: slow, body: Self.notificationBody)) + } + #expect(await eventually { await gate.arrivals == 1 }) + let deleted = await transport.handleRequest( + HTTPRequest(method: "DELETE", headers: headers(sessionID: sessionID, principal: "alice"))) + #expect(deleted.statusCode == 200) + + await gate.open() + expectUnknownSession(await post.value) + await transport.disconnect() + } + + @Test("Two principals initializing while sessionPrincipal suspends create one session, bound to the first", + .timeLimit(.minutes(1))) + func concurrentInitialize() async throws { + let gate = ValidationGate() + let runs = ValidatorRuns() + let transport = try await makeTransport( + validators: [CountingValidator(runs: runs, principal: "mallory"), SessionValidator()], + sessionPrincipal: { request in + let principal = request.value(forHeader: SessionPrincipalBindingTests.principalHeader) + if principal == "mallory" { await gate.wait() } + return principal + }) + + let mallory = Task { + await transport.handleRequest( + HTTPRequest(method: "POST", headers: headers(principal: "mallory"), body: Self.initializeBody)) + } + #expect(await eventually { await gate.arrivals == 1 }) + let sessionID = try await initialize(transport, as: "alice") + + await gate.open() + // The session changed while mallory's lookup was suspended: its + // validators ran again against alice's session, which refused it. + expectUnknownSession(await mallory.value) + #expect(await runs.count == 2) + #expect(await gate.arrivals == 1) + #expect(await notify(transport, sessionID: sessionID, as: "alice").statusCode == 202) + await transport.disconnect() + } +} diff --git a/design/threat_model.md b/design/threat_model.md index 8c316f4d..489179c6 100644 --- a/design/threat_model.md +++ b/design/threat_model.md @@ -60,6 +60,11 @@ per-connection state ([stateless.md](stateless.md)). `mcp-http-` and restores it on the way out, so a client cannot address another's response, cancellation or listen stream. `setSubscriptionAuthorizer` narrows or refuses a listen filter, and `notify(_:where:)` targets callers ([subscriptions.md](subscriptions.md)). +`StatefulHTTPServerTransport(sessionPrincipal:)` binds a session to the principal of its +`initialize`. A request from another principal, including a stream resumption with +`Last-Event-ID`, and any second `initialize` on a bound session get the 404 of an unknown session. +A bound session's ID is echoed only to a request that passed that check, also once the session has +ended. A refused `initialize` closes the dropped session's streams and forgets its stored events. Without it, a session ID is a bearer credential. **`requestState`.** Sealed with AES-GCM under a random nonce; the key id and version prefix are authenticated. It is bound to the method, the name or URI, a hash of the arguments, the audience diff --git a/docs/protocol.md b/docs/protocol.md index fcb5ae83..4417d988 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -325,9 +325,9 @@ To add headers to every request (an API key, a user agent), pass `requestModifie Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -32022 and `data.supported` set to the handshake revisions, so a client in `.automatic` mode falls back to `initialize`. -The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. +The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. `sessionPrincipal:` binds the session to the principal of its `initialize` request ([Session hijacking](#session-hijacking)). -Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503 take precedence over a transport-generated 405. Validator responses do not include `Mcp-Session-Id`; transport-owned errors include it only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. +Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503 take precedence over a transport-generated 405. Validator responses do not include `Mcp-Session-Id`; transport-owned errors include it only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. On a session bound with `sessionPrincipal:`, the ID is echoed only once the request's principal has been checked. Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: @@ -380,7 +380,7 @@ Validation errors: | Status | Cause | |---|---| | 400 | Empty or invalid JSON-RPC body; missing `Mcp-Session-Id`, including after termination; request before `initialize`; second `initialize`; unsupported `MCP-Protocol-Version` (-32022); a stateless request (-32022). | -| 404 | Unknown or expired session ID, including any ID sent after the session ended, and a request whose session ended while its validators ran. A transport stopped before a session existed answers 400, as before `initialize`. | +| 404 | Unknown or expired session ID, including any ID sent after the session ended, and a request whose session ended while its validators ran. With `sessionPrincipal:`, also a request whose principal did not create the session, and any second `initialize` on the session. A transport stopped before a session existed answers 400, as before `initialize`. | | 403, 421 | `Origin` or `Host` not allowed by `OriginValidator`. | | 406 | POST `Accept` lacks `application/json` or `text/event-stream`; GET `Accept` lacks `text/event-stream`. | | 415 | `Content-Type` is not `application/json`. | @@ -1020,7 +1020,7 @@ On the server side, `OriginValidator` protects local servers against DNS rebindi An attacker who learns a session ID could send requests in another user's session. - `StatefulHTTPServerTransport` generates session IDs with `UUID()` (`UUIDSessionIDGenerator`) and rejects IDs outside visible ASCII. A custom `SessionIDGenerator` must produce unguessable IDs. -- The SDK does not bind a session to a user. Put `BearerTokenValidator` in every session's validators so each request is authenticated, and in your session router record the token subject when the session is created and reject later requests whose subject differs. +- Authenticate every request: put `BearerTokenValidator` in every session's validators. Then bind each session to its user with `sessionPrincipal:` on `StatefulHTTPServerTransport`: return the request's principal, such as the subject of the token your `tokenVerifier` verified; never a value the client sets freely. The transport records it for the `initialize` that creates the session and answers a later request from another principal with the 404 of an unknown session, so a leaked session ID is of no use to another user. Without it, any request that passes the validators may use the session. - At 2026-07-28 there are no sessions: every request is authenticated on its own. ### Issuer mix-up diff --git a/docs/src/protocol.src.md b/docs/src/protocol.src.md index 8d581245..fb93d30c 100644 --- a/docs/src/protocol.src.md +++ b/docs/src/protocol.src.md @@ -232,9 +232,9 @@ To add headers to every request (an API key, a user agent), pass `requestModifie Requests whose `MCP-Protocol-Version` is a stateless revision get 400 with -32022 and `data.supported` set to the handshake revisions, so a client in `.automatic` mode falls back to `initialize`. -The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. +The default validators, `StatefulHTTPServerTransport.defaultValidators`, are `OriginValidator.localhost()`, `AcceptHeaderValidator(mode: .requiresEventStream)`, `ContentTypeValidator()`, `ProtocolVersionValidator()`, `SessionValidator()`. Pass `validators:` to replace them, for example to add authentication or allow other hosts. The transport runs them in order, and the first that returns a response ends the request. A validator may suspend (`validate` is `async`), but the built-in ones other than `BearerTokenValidator` run without suspending, so with them each request is handled without other requests in between. While a validator suspends, the transport handles other requests: it validates a request again when its session is created, or dropped by a refused `initialize`, meanwhile, and answers a request whose session ended meanwhile as one on a terminated session. A `notifications/cancelled` whose validators finish before those of the request it cancels is ignored. `sessionIDGenerator:` replaces the UUID generator; IDs must be visible ASCII (0x21-0x7E) or the transport answers 500. `retryInterval:` sets the SSE `retry:` field of the priming event; priming events are sent at 2025-03-26 through 2025-11-25. `sessionPrincipal:` binds the session to the principal of its `initialize` request ([Session hijacking](#session-hijacking)). -Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503 take precedence over a transport-generated 405. Validator responses do not include `Mcp-Session-Id`; transport-owned errors include it only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. +Header validation errors take precedence over malformed POST bodies. On unsupported HTTP methods, validator responses with status 2xx, 304, 400 with an authentication challenge, 401, 403, 405, 421 or 503 take precedence over a transport-generated 405. Validator responses do not include `Mcp-Session-Id`; transport-owned errors include it only if the request already carried the matching ID. A successful `initialize` still returns the newly assigned ID. On a session bound with `sessionPrincipal:`, the ID is echoed only once the request's principal has been checked. Your HTTP layer keeps one transport and one `Server` per session and routes by `Mcp-Session-Id`. The snippet leaves out what a deployed router needs: create a session only for a POST `initialize`, cap the number of sessions, and close idle ones, as [`Examples/http-server/main.swift`](../Examples/http-server/main.swift) does: @@ -247,7 +247,7 @@ Validation errors: | Status | Cause | |---|---| | 400 | Empty or invalid JSON-RPC body; missing `Mcp-Session-Id`, including after termination; request before `initialize`; second `initialize`; unsupported `MCP-Protocol-Version` (-32022); a stateless request (-32022). | -| 404 | Unknown or expired session ID, including any ID sent after the session ended, and a request whose session ended while its validators ran. A transport stopped before a session existed answers 400, as before `initialize`. | +| 404 | Unknown or expired session ID, including any ID sent after the session ended, and a request whose session ended while its validators ran. With `sessionPrincipal:`, also a request whose principal did not create the session, and any second `initialize` on the session. A transport stopped before a session existed answers 400, as before `initialize`. | | 403, 421 | `Origin` or `Host` not allowed by `OriginValidator`. | | 406 | POST `Accept` lacks `application/json` or `text/event-stream`; GET `Accept` lacks `text/event-stream`. | | 415 | `Content-Type` is not `application/json`. | @@ -613,7 +613,7 @@ On the server side, `OriginValidator` protects local servers against DNS rebindi An attacker who learns a session ID could send requests in another user's session. - `StatefulHTTPServerTransport` generates session IDs with `UUID()` (`UUIDSessionIDGenerator`) and rejects IDs outside visible ASCII. A custom `SessionIDGenerator` must produce unguessable IDs. -- The SDK does not bind a session to a user. Put `BearerTokenValidator` in every session's validators so each request is authenticated, and in your session router record the token subject when the session is created and reject later requests whose subject differs. +- Authenticate every request: put `BearerTokenValidator` in every session's validators. Then bind each session to its user with `sessionPrincipal:` on `StatefulHTTPServerTransport`: return the request's principal, such as the subject of the token your `tokenVerifier` verified; never a value the client sets freely. The transport records it for the `initialize` that creates the session and answers a later request from another principal with the 404 of an unknown session, so a leaked session ID is of no use to another user. Without it, any request that passes the validators may use the session. - At 2026-07-28 there are no sessions: every request is authenticated on its own. ### Issuer mix-up diff --git a/docs/src/troubleshooting.src.md b/docs/src/troubleshooting.src.md index a33d49c4..6a9e1487 100644 --- a/docs/src/troubleshooting.src.md +++ b/docs/src/troubleshooting.src.md @@ -196,7 +196,7 @@ Server transports: | 400 | stateful | No session yet (`Session not initialized`), a missing `Mcp-Session-Id` (also after the session ended), a second `initialize` on the session, an unknown `Last-Event-ID`, a stateless request (-32022). | | 403 | both | An `Origin` header that the `OriginValidator` does not allow. | | 404 | stateless | At 2026-07-28, -32601; any request after the transport stopped. | -| 404 | stateful | An unknown or expired `Mcp-Session-Id`, including any ID sent after the session ended. | +| 404 | stateful | An unknown or expired `Mcp-Session-Id`, including any ID sent after the session ended; with `sessionPrincipal:`, a request whose principal did not create the session (after token rotation, or a principal lookup that returned `nil`). | | 405 | stateless | An unsupported method after validation. The transport sets `Allow: POST`; a responder's 405 keeps its own `Allow` header. Validator 2xx, 304, Bearer challenge 400, 401, 403, 421 and 503 responses take precedence. | | 405 | stateful | An unsupported method after validation. The transport sets `Allow: GET, POST, DELETE`; a responder's 405 keeps its own `Allow` header. Validator 2xx, 304, Bearer challenge 400, 401, 403, 421 and 503 responses take precedence. | | 406 | both | An `Accept` header without `application/json` (stateless), or without both `application/json` and `text/event-stream` (stateful POST). | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6ee2cda6..67ed2cf1 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -276,7 +276,7 @@ Server transports: | 400 | stateful | No session yet (`Session not initialized`), a missing `Mcp-Session-Id` (also after the session ended), a second `initialize` on the session, an unknown `Last-Event-ID`, a stateless request (-32022). | | 403 | both | An `Origin` header that the `OriginValidator` does not allow. | | 404 | stateless | At 2026-07-28, -32601; any request after the transport stopped. | -| 404 | stateful | An unknown or expired `Mcp-Session-Id`, including any ID sent after the session ended. | +| 404 | stateful | An unknown or expired `Mcp-Session-Id`, including any ID sent after the session ended; with `sessionPrincipal:`, a request whose principal did not create the session (after token rotation, or a principal lookup that returned `nil`). | | 405 | stateless | An unsupported method after validation. The transport sets `Allow: POST`; a responder's 405 keeps its own `Allow` header. Validator 2xx, 304, Bearer challenge 400, 401, 403, 421 and 503 responses take precedence. | | 405 | stateful | An unsupported method after validation. The transport sets `Allow: GET, POST, DELETE`; a responder's 405 keeps its own `Allow` header. Validator 2xx, 304, Bearer challenge 400, 401, 403, 421 and 503 responses take precedence. | | 406 | both | An `Accept` header without `application/json` (stateless), or without both `application/json` and `text/event-stream` (stateful POST). |