From e4f7f84f2e6de6fcf2166c23708b778e5283d240 Mon Sep 17 00:00:00 2001 From: canarik Date: Mon, 30 Nov 2026 23:07:24 +0300 Subject: [PATCH 1/2] fix: apply the redirect loopback rule to OAuth URLs that servers name `OAuthRedirectGuard` follows a discovery redirect to a loopback host only from a loopback host. The URLs a server names directly were checked for private IP literals only: the `resource_metadata` URL of a `WWW-Authenticate` challenge, the `authorization_servers` of the protected resource metadata, the authorization, token and registration endpoints of the authorization server metadata, and the token endpoint in an identity provider's metadata. `isPrivateIPHost` leaves loopback out because the MCP endpoint itself may be on loopback, so these URLs could name a loopback host whatever the server that named them. Fix: `rejectPrivateIP` and `validateAuthorizationServerAndHost` take an `allowingLoopback` flag, and a URL a server names may be on a loopback host only when that server is (RFC 9728 section 7.7). The challenge URL and the listed authorization servers follow the MCP endpoint; the endpoints in authorization server or identity provider metadata follow that server. URLs in `endpointOverrides` and the URLs an application passes to `OAuthTokenExchange` are not affected. The loopback check of `OAuthRedirectGuard` moves to `OAuthURLValidator.isLoopbackHost`, so both use the same definition. Adds tests to `OAuthAuthorizerTests`, `OAuthDiscoveryClientTests`, `OAuthClientRegistrarTests`, `OAuthURLValidatorTests` and `OAuthJWTBearerTests`, and updates the protocol guide, `design/auth.md` and `design/threat_model.md`. --- .../Base/Authorization/OAuthAuthorizer.swift | 29 ++- .../Authorization/OAuthClientRegistrar.swift | 7 +- .../Authorization/OAuthConfiguration.swift | 10 +- .../Authorization/OAuthDiscoveryClient.swift | 13 +- .../MCP/Base/Authorization/OAuthErrors.swift | 5 +- .../Authorization/OAuthRedirectGuard.swift | 14 +- .../Authorization/OAuthTokenExchange.swift | 27 ++- .../Authorization/OAuthURLValidator.swift | 39 +++- .../MCPTests/OAuthAuthorizerStateTests.swift | 3 +- Tests/MCPTests/OAuthAuthorizerTests.swift | 154 +++++++++++++- .../MCPTests/OAuthClientRegistrarTests.swift | 54 +++++ .../MCPTests/OAuthDiscoveryClientTests.swift | 88 ++++++++ Tests/MCPTests/OAuthJWTBearerTests.swift | 200 ++++++++++++++++++ Tests/MCPTests/OAuthURLValidatorTests.swift | 50 +++++ design/auth.md | 27 ++- design/threat_model.md | 4 +- docs/protocol.md | 5 +- docs/src/protocol.src.md | 5 +- 18 files changed, 678 insertions(+), 56 deletions(-) diff --git a/Sources/MCP/Base/Authorization/OAuthAuthorizer.swift b/Sources/MCP/Base/Authorization/OAuthAuthorizer.swift index 6ae8520f..1ba46f66 100644 --- a/Sources/MCP/Base/Authorization/OAuthAuthorizer.swift +++ b/Sources/MCP/Base/Authorization/OAuthAuthorizer.swift @@ -625,7 +625,8 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { if !triedRefresh, let rejected, let refreshToken = rejected.refreshToken { let asMetadata: OAuthAuthorizationServerMetadata? do { - asMetadata = try await resolveAuthorizationServerMetadata(metadata: current, session: session) + asMetadata = try await resolveAuthorizationServerMetadata( + metadata: current, endpoint: endpoint, session: session) } catch let error where error is OAuthMetadataUnavailable || error is CancellationError { // Says nothing about the server: keep the token. throw error @@ -843,7 +844,8 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { try urlValidator.validateHTTPSOrLoopback( challengeURL, context: "Protected resource metadata URL") try urlValidator.rejectPrivateIP( - challengeURL, context: "Protected resource metadata URL") + challengeURL, context: "Protected resource metadata URL", + allowingLoopback: OAuthURLValidator.isLoopback(endpoint)) candidates.append(challengeURL) } if let configuredURL = configuration.endpointOverrides.protectedResourceMetadataURL, @@ -922,6 +924,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { private func resolveAuthorizationServerMetadata( metadata: OAuthProtectedResourceMetadata, + endpoint: URL, session: URLSession ) async throws -> OAuthAuthorizationServerMetadata { if let cached = authorizationServerMetadata { @@ -948,6 +951,10 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { } candidates = metadata.authorizationServers } + // A server the resource names is on loopback only when the resource + // is; one the application configures may be. + let allowsLoopback = + configuration.endpointOverrides.authorizationServerURL != nil || OAuthURLValidator.isLoopback(endpoint) // The issuer of a jwt-bearer server is checked even when configured: // it is the audience of the assertion (RFC 7523 §3), and the ID-JAG @@ -963,7 +970,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { do { (server, asMetadata) = try await discoveryClient.fetchAuthorizationServerMetadata( candidates: candidates, trustedIssuer: trustedIssuer, - reportRefused: !usesDefaultEndpointsFallback, session: session) + reportRefused: !usesDefaultEndpointsFallback, allowingLoopback: allowsLoopback, session: session) } catch OAuthAuthorizationError.authorizationServerMetadataDiscoveryFailed where usesDefaultEndpointsFallback { @@ -979,6 +986,12 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { return asMetadata } + /// Whether the selected authorization server is on a loopback host: only + /// then may the endpoints its metadata names be on one. + private var authorizationServerIsLoopback: Bool { + OAuthURLValidator.isLoopback(selectedAuthorizationServer) + } + // MARK: - Token Acquisition private func acquireToken( @@ -988,7 +1001,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { session: URLSession ) async throws { let asMetadata = try await resolveAuthorizationServerMetadata( - metadata: metadata, session: session) + metadata: metadata, endpoint: endpoint, session: session) try checkDPoPSupport(metadata: metadata, asMetadata: asMetadata) try await maybeRegisterClient(asMetadata: asMetadata, session: session) let resource = try canonicalResource(for: endpoint) @@ -1121,7 +1134,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { throw OAuthAuthorizationError.tokenEndpointMissing } try urlValidator.validateAuthorizationServerAndHost( - authorizationEndpoint, context: "Authorization endpoint") + authorizationEndpoint, context: "Authorization endpoint", allowingLoopback: authorizationServerIsLoopback) try urlValidator.validateRedirectURI(configuration.authorizationRedirectURI) try PKCE.checkSupport(in: asMetadata) @@ -1302,6 +1315,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { result = try await clientRegistrar.register( configuration: configuration, asMetadata: asMetadata, + allowingLoopback: authorizationServerIsLoopback, session: session ) } catch { @@ -1386,7 +1400,8 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { guard let tokenEndpoint = asMetadata.tokenEndpoint else { throw OAuthAuthorizationError.tokenEndpointMissing } - try urlValidator.validateAuthorizationServerAndHost(tokenEndpoint, context: "Token endpoint") + try urlValidator.validateAuthorizationServerAndHost( + tokenEndpoint, context: "Token endpoint", allowingLoopback: authorizationServerIsLoopback) return tokenEndpoint } @@ -1490,7 +1505,7 @@ public final class OAuthAuthorizer: HTTPClientAuthorizer, @unchecked Sendable { throw OAuthAuthorizationError.assertionProviderMissing } let asMetadata = try await resolveAuthorizationServerMetadata( - metadata: metadata, session: session) + metadata: metadata, endpoint: endpoint, session: session) let resource = try canonicalResource(for: endpoint) let authorizationServer = configuration.endpointOverrides.authorizationServerURL ?? selectedAuthorizationServer diff --git a/Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift b/Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift index ba2d1420..83f799fd 100644 --- a/Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift +++ b/Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift @@ -9,6 +9,7 @@ protocol OAuthClientRegistering: Sendable { func register( configuration: OAuthConfiguration, asMetadata: OAuthAuthorizationServerMetadata, + allowingLoopback: Bool, session: URLSession ) async throws -> ( response: OAuthClientRegistrationResponse, @@ -37,10 +38,14 @@ struct OAuthClientRegistrar: Sendable { /// /// Throws ``OAuthAuthorizationError/registrationInformationRequired`` when /// the client ID is empty and the server has no registration endpoint. + /// Throws ``OAuthAuthorizationError/privateIPAddressBlocked(context:url:)`` + /// before a request when the registration endpoint is on a private + /// address, or on a loopback host unless `allowingLoopback`. /// Throws if registration was attempted but failed (4xx, 5xx, or unexpected response). func register( configuration: OAuthConfiguration, asMetadata: OAuthAuthorizationServerMetadata, + allowingLoopback: Bool, session: URLSession ) async throws -> ( response: OAuthClientRegistrationResponse, @@ -81,7 +86,7 @@ struct OAuthClientRegistrar: Sendable { return nil } try urlValidator.validateAuthorizationServerAndHost( - registrationEndpoint, context: "Client registration endpoint") + registrationEndpoint, context: "Client registration endpoint", allowingLoopback: allowingLoopback) var request = URLRequest(url: registrationEndpoint) request.httpMethod = "POST" diff --git a/Sources/MCP/Base/Authorization/OAuthConfiguration.swift b/Sources/MCP/Base/Authorization/OAuthConfiguration.swift index d8df4d67..73a734b5 100644 --- a/Sources/MCP/Base/Authorization/OAuthConfiguration.swift +++ b/Sources/MCP/Base/Authorization/OAuthConfiguration.swift @@ -367,11 +367,15 @@ public struct OAuthConfiguration: Sendable { public let resource: URL /// Selected authorization server issuer URL, if discovered. public let authorizationServer: URL? - /// Authorization endpoint from AS metadata, if available. + /// Authorization endpoint from AS metadata, if available. The SDK has + /// not checked it: it may be on a loopback or private host. public let authorizationEndpoint: URL? - /// Token endpoint from AS metadata (or configuration override), if available. + /// Token endpoint from AS metadata (or configuration override), if + /// available. One from AS metadata has not been checked: it may be on + /// a loopback or private host. public let tokenEndpoint: URL? - /// Dynamic registration endpoint from AS metadata, if available. + /// Dynamic registration endpoint from AS metadata, if available. The + /// SDK has not checked it: it may be on a loopback or private host. public let registrationEndpoint: URL? /// `scope` value from the latest challenge header, when present. public let challengedScope: String? diff --git a/Sources/MCP/Base/Authorization/OAuthDiscoveryClient.swift b/Sources/MCP/Base/Authorization/OAuthDiscoveryClient.swift index fae55b2d..82c188f0 100644 --- a/Sources/MCP/Base/Authorization/OAuthDiscoveryClient.swift +++ b/Sources/MCP/Base/Authorization/OAuthDiscoveryClient.swift @@ -8,21 +8,24 @@ import Foundation protocol OAuthDiscoveryFetching: Sendable { var metadataDiscovery: any OAuthMetadataDiscovering { get } func fetchProtectedResourceMetadata(candidates: [URL], fallbackIssuer: URL?, session: URLSession) async throws -> OAuthProtectedResourceMetadata - func fetchAuthorizationServerMetadata(candidates: [URL], trustedIssuer: URL?, reportRefused: Bool, session: URLSession) async throws -> (server: URL, metadata: OAuthAuthorizationServerMetadata) + func fetchAuthorizationServerMetadata(candidates: [URL], trustedIssuer: URL?, reportRefused: Bool, allowingLoopback: Bool, session: URLSession) async throws -> (server: URL, metadata: OAuthAuthorizationServerMetadata) } extension OAuthDiscoveryFetching { + /// A candidate on a loopback host is refused. func fetchAuthorizationServerMetadata( candidates: [URL], session: URLSession ) async throws -> (server: URL, metadata: OAuthAuthorizationServerMetadata) { try await fetchAuthorizationServerMetadata(candidates: candidates, trustedIssuer: nil, session: session) } + /// A candidate on a loopback host is refused. func fetchAuthorizationServerMetadata( candidates: [URL], trustedIssuer: URL?, session: URLSession ) async throws -> (server: URL, metadata: OAuthAuthorizationServerMetadata) { try await fetchAuthorizationServerMetadata( - candidates: candidates, trustedIssuer: trustedIssuer, reportRefused: true, session: session) + candidates: candidates, trustedIssuer: trustedIssuer, reportRefused: true, allowingLoopback: false, + session: session) } } @@ -147,7 +150,8 @@ struct OAuthDiscoveryClient: Sendable { /// The metadata `issuer` must match the issuer the well-known URL was /// built from (RFC 8414 §3.3, SEP-2468); metadata that names another /// issuer, or none, is not used. For `trustedIssuer`, an issuer the - /// application configured, metadata is accepted with any `issuer`. + /// application configured, metadata is accepted with any `issuer`. A + /// candidate on a loopback host is refused unless `allowingLoopback`. /// /// - Throws: `CancellationError` when cancelled; /// ``OAuthAuthorizationError/authorizationServerIssuerMismatch(expected:actual:)`` @@ -167,6 +171,7 @@ struct OAuthDiscoveryClient: Sendable { candidates: [URL], trustedIssuer: URL?, reportRefused: Bool, + allowingLoopback: Bool, session: URLSession ) async throws -> (server: URL, metadata: OAuthAuthorizationServerMetadata) { let decoder = JSONDecoder() @@ -178,7 +183,7 @@ struct OAuthDiscoveryClient: Sendable { for candidateServer in candidates { do { try urlValidator.validateAuthorizationServerAndHost( - candidateServer, context: "Authorization server issuer") + candidateServer, context: "Authorization server issuer", allowingLoopback: allowingLoopback) } catch { refused = refused ?? error continue diff --git a/Sources/MCP/Base/Authorization/OAuthErrors.swift b/Sources/MCP/Base/Authorization/OAuthErrors.swift index e854e0d7..fabbb88a 100644 --- a/Sources/MCP/Base/Authorization/OAuthErrors.swift +++ b/Sources/MCP/Base/Authorization/OAuthErrors.swift @@ -62,8 +62,9 @@ public struct OAuthAuthorizationError: LocalizedError, Hashable, Sendable { /// The authorization server supports neither Client ID Metadata Documents nor dynamic /// registration: ``clientID``. public static let cimdNotSupported = Code(rawValue: "cimdNotSupported") - /// A URL resolves to a private or reserved IP address, blocked against SSRF: - /// ``context``, ``url``. + /// A URL resolves to a private or reserved IP address, or names a + /// loopback host while the server that named it is not on one, + /// blocked against SSRF: ``context``, ``url``. public static let privateIPAddressBlocked = Code(rawValue: "privateIPAddressBlocked") /// An endpoint is neither HTTPS nor loopback HTTP: ``context``, ``url``. public static let insecureOAuthEndpoint = Code(rawValue: "insecureOAuthEndpoint") diff --git a/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift b/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift index e33ac6fc..5f14e919 100644 --- a/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift +++ b/Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift @@ -48,23 +48,15 @@ final class OAuthRedirectGuard: NSObject, URLSessionTaskDelegate, @unchecked Sen if validator.isPrivateIPHost(host) { return false } let sourceComponents = source.flatMap { URLComponents(url: $0, resolvingAgainstBaseURL: false) } // A remote server must not send the client to services on this machine. - if isLoopback(host), !(sourceComponents?.host.map { isLoopback($0.lowercased()) } ?? false) { + if OAuthURLValidator.isLoopbackHost(host), + !(sourceComponents?.host.map { OAuthURLValidator.isLoopbackHost($0) } ?? false) + { return false } if scheme == OAuthURLScheme.https { return true } return scheme == OAuthURLScheme.http && sourceComponents?.scheme?.lowercased() == OAuthURLScheme.http && OAuthLoopbackHost.isLoopback(host) } - - /// Whether `host` names this machine: `localhost`, a name under - /// `.localhost` (RFC 6761 §6.3), `127.0.0.0/8` or `::1`. - private func isLoopback(_ host: String) -> Bool { - let name = host.hasSuffix(".") ? String(host.dropLast()) : host - if name == OAuthLoopbackHost.localhost || name.hasSuffix(".\(OAuthLoopbackHost.localhost)") { - return true - } - return validator.isPrivateIPHost(host, includingLoopback: true) && !validator.isPrivateIPHost(host) - } } extension URLSession { diff --git a/Sources/MCP/Base/Authorization/OAuthTokenExchange.swift b/Sources/MCP/Base/Authorization/OAuthTokenExchange.swift index 2fd39567..40f31a5d 100644 --- a/Sources/MCP/Base/Authorization/OAuthTokenExchange.swift +++ b/Sources/MCP/Base/Authorization/OAuthTokenExchange.swift @@ -125,7 +125,9 @@ public enum OAuthTokenExchange { session: URLSession = .shared, urlValidator: OAuthURLValidator = OAuthURLValidator() ) async throws -> Response { - try urlValidator.validateAuthorizationServerAndHost(tokenEndpoint, context: "Token exchange endpoint") + // The application names this endpoint, so it may be on loopback. + try urlValidator.validateAuthorizationServerAndHost( + tokenEndpoint, context: "Token exchange endpoint", allowingLoopback: true) var parameters: [String: String] = [ OAuthParameterName.grantType: OAuthGrantTypeValue.tokenExchange, @@ -176,9 +178,14 @@ public enum OAuthTokenExchange { /// Discovers the token endpoint of `issuer` from its authorization server /// metadata (RFC 8414) or OpenID configuration. The metadata's `issuer` - /// must match. + /// must match. The endpoint it names must be `https` (or loopback `http` + /// when `urlValidator` allows it), may be on a loopback host only when + /// `issuer` is, and never on a private IP literal (host names are not + /// resolved). /// - /// - Throws: ``OAuthAuthorizationError/insecureAuthorizationServerEndpoint(context:url:)`` + /// - Throws: ``OAuthAuthorizationError/invalidResourceURI(_:)`` when `issuer` is not an + /// absolute URL with a host, or has a fragment, and + /// ``OAuthAuthorizationError/insecureAuthorizationServerEndpoint(context:url:)`` /// or ``OAuthAuthorizationError/privateIPAddressBlocked(context:url:)`` when `issuer` is /// refused, before any request; /// ``OAuthAuthorizationError/authorizationServerIssuerMismatch(expected:actual:)`` @@ -186,9 +193,11 @@ public enum OAuthTokenExchange { /// ``OAuthAuthorizationError/authorizationServerMetadataDiscoveryFailed`` when every /// metadata URL answers 404 or 410; an error naming the URL and the reason when a /// metadata request fails otherwise (a network error, another status, or a body that is - /// not metadata); `CancellationError` when cancelled; and + /// not metadata); `CancellationError` when cancelled; /// ``OAuthAuthorizationError/tokenEndpointMissing`` when the metadata has no token - /// endpoint. + /// endpoint; and, for the token endpoint, the errors `issuer` is refused with, or + /// ``OAuthAuthorizationError/privateIPAddressBlocked(context:url:)`` when its host is a + /// loopback host while `issuer` is not. public static func tokenEndpoint( issuer: URL, session: URLSession = .shared, @@ -196,11 +205,17 @@ public enum OAuthTokenExchange { ) async throws -> URL { let discovery = OAuthDiscoveryClient( metadataDiscovery: DefaultOAuthMetadataDiscovery(), urlValidator: urlValidator) + // The application names the issuer, so it may be on loopback. let (_, metadata) = try await discovery.fetchAuthorizationServerMetadata( - candidates: [issuer], session: session) + candidates: [issuer], trustedIssuer: nil, reportRefused: true, allowingLoopback: true, session: session) guard let tokenEndpoint = metadata.tokenEndpoint else { throw OAuthAuthorizationError.tokenEndpointMissing } + // The provider's metadata names this endpoint: it gets the checks + // `exchange` applies, and is on loopback only when the provider is. + try urlValidator.validateAuthorizationServerAndHost( + tokenEndpoint, context: "Token exchange endpoint", + allowingLoopback: OAuthURLValidator.isLoopback(issuer)) return tokenEndpoint } } diff --git a/Sources/MCP/Base/Authorization/OAuthURLValidator.swift b/Sources/MCP/Base/Authorization/OAuthURLValidator.swift index b944a7a4..5694f074 100644 --- a/Sources/MCP/Base/Authorization/OAuthURLValidator.swift +++ b/Sources/MCP/Base/Authorization/OAuthURLValidator.swift @@ -21,20 +21,26 @@ protocol OAuthURLValidating: Sendable { extension OAuthURLValidating { /// Throws ``OAuthAuthorizationError/privateIPAddressBlocked(context:url:)`` - /// when `url` has a private or reserved IP literal host. - func rejectPrivateIP(_ url: URL, context: String) throws { + /// when `url` has a private or reserved IP literal host, or a loopback + /// host (``OAuthURLValidator/isLoopbackHost(_:)``) unless `allowingLoopback`. + /// + /// A server may send the client to this machine only from this machine + /// (RFC 9728 §7.7): set `allowingLoopback` when the party that named + /// `url` is on a loopback host, as ``OAuthRedirectGuard`` does for redirects. + func rejectPrivateIP(_ url: URL, context: String, allowingLoopback: Bool) throws { if let host = URLComponents(url: url, resolvingAgainstBaseURL: false)?.host?.lowercased(), - isPrivateIPHost(host) + isPrivateIPHost(host) || (!allowingLoopback && OAuthURLValidator.isLoopbackHost(host)) { throw OAuthAuthorizationError.privateIPAddressBlocked( context: context, url: url.absoluteString) } } - /// Validates an authorization server URL and rejects private IP literal hosts. - func validateAuthorizationServerAndHost(_ url: URL, context: String) throws { + /// Validates an authorization server URL and rejects private IP literal + /// hosts, and loopback hosts unless `allowingLoopback`. + func validateAuthorizationServerAndHost(_ url: URL, context: String, allowingLoopback: Bool) throws { try validateAuthorizationServer(url, context: context) - try rejectPrivateIP(url, context: context) + try rejectPrivateIP(url, context: context, allowingLoopback: allowingLoopback) } } @@ -192,6 +198,27 @@ public struct OAuthURLValidator: Sendable { return Self.isNumericIPv4(literal) } + /// Whether `host` names this machine: `localhost`, a name under + /// `.localhost` (RFC 6761 §6.3), `127.0.0.0/8` or `::1`, also embedded + /// in IPv6 as for ``isPrivateIPHost(_:)``. + static func isLoopbackHost(_ host: String) -> Bool { + let host = host.lowercased() + let name = host.hasSuffix(".") ? String(host.dropLast()) : host + if name == OAuthLoopbackHost.localhost || name.hasSuffix(".\(OAuthLoopbackHost.localhost)") { + return true + } + let validator = OAuthURLValidator() + return validator.isPrivateIPHost(host, includingLoopback: true) && !validator.isPrivateIPHost(host) + } + + /// Whether the host of `url` names this machine (``isLoopbackHost(_:)``). + static func isLoopback(_ url: URL?) -> Bool { + guard let url, let host = URLComponents(url: url, resolvingAgainstBaseURL: false)?.host else { + return false + } + return isLoopbackHost(host) + } + /// The bytes of `text` as an address of `family`, or `nil`. private static func parse(_ text: String, family: Int32, size: Int) -> [UInt8]? { var buffer = [UInt8](repeating: 0, count: 16) diff --git a/Tests/MCPTests/OAuthAuthorizerStateTests.swift b/Tests/MCPTests/OAuthAuthorizerStateTests.swift index 03d21cbb..2b7dc779 100644 --- a/Tests/MCPTests/OAuthAuthorizerStateTests.swift +++ b/Tests/MCPTests/OAuthAuthorizerStateTests.swift @@ -121,7 +121,8 @@ final class FlakyClientRegistrar: OAuthClientRegistering, @unchecked Sendable { var registerCallCount: Int { lock.withLock { calls } } func register( - configuration: OAuthConfiguration, asMetadata: OAuthAuthorizationServerMetadata, session: URLSession + configuration: OAuthConfiguration, asMetadata: OAuthAuthorizationServerMetadata, allowingLoopback: Bool, + session: URLSession ) async throws -> ( response: OAuthClientRegistrationResponse, updatedAuthentication: OAuthConfiguration.TokenEndpointAuthentication diff --git a/Tests/MCPTests/OAuthAuthorizerTests.swift b/Tests/MCPTests/OAuthAuthorizerTests.swift index af8a38ae..f03557a9 100644 --- a/Tests/MCPTests/OAuthAuthorizerTests.swift +++ b/Tests/MCPTests/OAuthAuthorizerTests.swift @@ -79,6 +79,8 @@ final class MockDiscoveryClient: OAuthDiscoveryFetching, @unchecked Sendable { var authorizationServerMetadataError: Error? /// The `candidates` of the last protected resource metadata fetch. var lastProtectedResourceMetadataCandidates: [URL] = [] + /// The `allowingLoopback` of the last authorization server metadata fetch. + var lastAllowingLoopback: Bool? func fetchProtectedResourceMetadata(candidates: [URL], fallbackIssuer: URL?, session: URLSession) async throws -> OAuthProtectedResourceMetadata { fetchProtectedResourceMetadataCallCount += 1 @@ -91,11 +93,12 @@ final class MockDiscoveryClient: OAuthDiscoveryFetching, @unchecked Sendable { } func fetchAuthorizationServerMetadata( - candidates: [URL], trustedIssuer: URL?, reportRefused: Bool, session: URLSession + candidates: [URL], trustedIssuer: URL?, reportRefused: Bool, allowingLoopback: Bool, session: URLSession ) async throws -> (server: URL, metadata: OAuthAuthorizationServerMetadata) { fetchAuthorizationServerMetadataCallCount += 1 lastTrustedIssuer = trustedIssuer lastReportRefused = reportRefused + lastAllowingLoopback = allowingLoopback if let error = authorizationServerMetadataError { throw error } if let refusal = candidateRefusal { throw reportRefused ? refusal : OAuthAuthorizationError.authorizationServerMetadataDiscoveryFailed @@ -136,6 +139,8 @@ final class MockClientRegistrar: OAuthClientRegistering, @unchecked Sendable { var registerCallCount = 0 /// The authentication each registration started from. var registeredFrom: [OAuthConfiguration.TokenEndpointAuthentication] = [] + /// The `allowingLoopback` of the last registration. + var lastAllowingLoopback: Bool? var registrationResult: ( response: OAuthClientRegistrationResponse, updatedAuthentication: OAuthConfiguration.TokenEndpointAuthentication @@ -144,6 +149,7 @@ final class MockClientRegistrar: OAuthClientRegistering, @unchecked Sendable { func register( configuration: OAuthConfiguration, asMetadata: OAuthAuthorizationServerMetadata, + allowingLoopback: Bool, session: URLSession ) async throws -> ( response: OAuthClientRegistrationResponse, @@ -151,6 +157,7 @@ final class MockClientRegistrar: OAuthClientRegistering, @unchecked Sendable { )? { registerCallCount += 1 registeredFrom.append(configuration.authentication) + lastAllowingLoopback = allowingLoopback return registrationResult } } @@ -511,20 +518,25 @@ struct OAuthAuthorizerTests { /// An authorizer with the SDK's URL validator. func makeValidatingAuthorizer( grantType: OAuthConfiguration.GrantType = .clientCredentials, + authentication: OAuthConfiguration.TokenEndpointAuthentication = .clientSecretBasic( + clientID: "client", clientSecret: "secret"), + endpointOverrides: OAuthConfiguration.EndpointOverrides = .none, discoveryClient: MockDiscoveryClient, tokenClient: MockTokenClient = MockTokenClient(), + registrar: MockClientRegistrar = MockClientRegistrar(), authCodeFlow: MockAuthCodeFlow = MockAuthCodeFlow() ) -> OAuthAuthorizer { OAuthAuthorizer( configuration: OAuthConfiguration( grantType: grantType, - authentication: .clientSecretBasic(clientID: "client", clientSecret: "secret"), + authentication: authentication, + endpointOverrides: endpointOverrides, authorizationRedirectURI: URL(string: "https://app.example.com/callback")! ), urlValidator: OAuthURLValidator(), discoveryClient: discoveryClient, tokenEndpointClient: tokenClient, - clientRegistrar: MockClientRegistrar(), + clientRegistrar: registrar, authCodeFlow: authCodeFlow ) } @@ -590,4 +602,140 @@ struct OAuthAuthorizerTests { #expect(authCodeFlow.buildURLCallCount == 0) #expect(authCodeFlow.performCallCount == 0) } + + // MARK: - Loopback hosts + + /// URLs on this machine, written in the ways a server can name them. + static let loopbackURLs = [ + "http://127.0.0.1:8080/x", "https://127.0.0.2/x", "https://localhost/x", "https://localhost./x", + "https://app.localhost/x", "https://[::1]/x", "https://[::ffff:127.0.0.1]/x", + ] + + @Test( + "A loopback resource_metadata URL from an endpoint that is not on loopback is refused before discovery", + arguments: loopbackURLs) + func testLoopbackResourceMetadataURLIsRefused(metadataURL: String) async throws { + let discovery = MockDiscoveryClient() + let authorizer = makeValidatingAuthorizer(discoveryClient: discovery) + + await #expect { + try await authorizer.handleChallenge( + statusCode: 401, headers: ["WWW-Authenticate": "Bearer resource_metadata=\"\(metadataURL)\""], + endpoint: endpoint, operationKey: nil, session: .shared) + } throws: { isPrivateIPBlocked($0, "Protected resource metadata URL", metadataURL) } + #expect(discovery.fetchProtectedResourceMetadataCallCount == 0) + } + + @Test("A loopback resource_metadata URL is fetched when the endpoint is on loopback too") + func testLoopbackResourceMetadataURLFromLoopbackEndpoint() async throws { + let discovery = MockDiscoveryClient() + let tokenClient = MockTokenClient() + let authorizer = makeValidatingAuthorizer(discoveryClient: discovery, tokenClient: tokenClient) + let localEndpoint = URL(string: "http://localhost:8080/mcp")! + let metadataURL = URL(string: "http://localhost:8080/.well-known/oauth-protected-resource/mcp")! + + let handled = try await authorizer.handleChallenge( + statusCode: 401, + headers: ["WWW-Authenticate": "Bearer resource_metadata=\"\(metadataURL.absoluteString)\""], + endpoint: localEndpoint, operationKey: nil, session: .shared) + + #expect(handled) + #expect(discovery.lastProtectedResourceMetadataCandidates.first == metadataURL) + #expect(tokenClient.requestCallCount == 1) + } + + @Test( + "Authorization servers the resource names may be on loopback only when the endpoint is", + arguments: zip(["https://mcp.example.com/mcp", "http://127.0.0.1:8080/mcp"], [false, true])) + func testListedAuthorizationServersFollowTheEndpoint(endpoint: String, allowsLoopback: Bool) async throws { + let discovery = MockDiscoveryClient() + let authorizer = makeValidatingAuthorizer(discoveryClient: discovery) + + _ = try await authorizer.handleChallenge( + statusCode: 401, headers: ["WWW-Authenticate": "Bearer"], endpoint: URL(string: endpoint)!, + operationKey: nil, session: .shared) + + #expect(discovery.lastAllowingLoopback == allowsLoopback) + } + + @Test("A configured authorization server on loopback is used with its loopback token endpoint") + func testConfiguredLoopbackAuthorizationServer() async throws { + let server = URL(string: "https://localhost:8443")! + let tokenEndpoint = URL(string: "https://localhost:8443/token")! + let discovery = MockDiscoveryClient(authorizationServer: server, tokenEndpoint: tokenEndpoint) + let tokenClient = MockTokenClient() + let authorizer = makeValidatingAuthorizer( + endpointOverrides: .init(authorizationServerURL: server), discoveryClient: discovery, + tokenClient: tokenClient) + + let handled = try await authorizer.handleChallenge( + statusCode: 401, headers: headers401, endpoint: endpoint, operationKey: nil, session: .shared) + + #expect(handled) + #expect(discovery.lastAllowingLoopback == true) + #expect(tokenClient.capturedEndpoint == tokenEndpoint) + } + + @Test("A loopback token endpoint of an authorization server that is not on loopback is refused") + func testLoopbackTokenEndpointIsRefused() async throws { + let tokenEndpoint = "https://127.0.0.1:9443/token" + let discovery = MockDiscoveryClient(tokenEndpoint: URL(string: tokenEndpoint)!) + let tokenClient = MockTokenClient() + let authorizer = makeValidatingAuthorizer(discoveryClient: discovery, tokenClient: tokenClient) + + await #expect { + try await authorizer.handleChallenge( + statusCode: 401, headers: headers401, endpoint: endpoint, operationKey: nil, session: .shared) + } throws: { isPrivateIPBlocked($0, "Token endpoint", tokenEndpoint) } + #expect(tokenClient.requestCallCount == 0) + } + + @Test("A loopback authorization endpoint of an authorization server that is not on loopback is refused") + func testLoopbackAuthorizationEndpointIsRefused() async throws { + let authorizationEndpoint = "https://localhost/authorize" + let discovery = MockDiscoveryClient() + let server = discovery.authorizationServerMetadataResult + discovery.authorizationServerMetadataResult = ( + server: server.server, + metadata: OAuthAuthorizationServerMetadata( + issuer: server.server, + authorizationEndpoint: URL(string: authorizationEndpoint)!, + tokenEndpoint: server.metadata.tokenEndpoint, + registrationEndpoint: nil, + codeChallengeMethodsSupported: ["S256"], + tokenEndpointAuthMethodsSupported: nil, + clientIDMetadataDocumentSupported: nil + ) + ) + let authCodeFlow = MockAuthCodeFlow() + let authorizer = makeValidatingAuthorizer( + grantType: .authorizationCode, discoveryClient: discovery, authCodeFlow: authCodeFlow) + + await #expect { + try await authorizer.handleChallenge( + statusCode: 401, headers: headers401, endpoint: endpoint, operationKey: nil, session: .shared) + } throws: { isPrivateIPBlocked($0, "Authorization endpoint", authorizationEndpoint) } + #expect(authCodeFlow.buildURLCallCount == 0) + #expect(authCodeFlow.performCallCount == 0) + } + + @Test( + "The registration endpoint may be on loopback only when the authorization server is", + arguments: zip(["https://auth.example.com", "https://localhost:8443"], [false, true])) + func testRegistrationFollowsTheAuthorizationServer(server: String, allowsLoopback: Bool) async throws { + let serverURL = URL(string: server)! + let registrar = MockClientRegistrar() + let authorizer = makeValidatingAuthorizer( + authentication: .none(clientID: "plain-client"), + endpointOverrides: .init(authorizationServerURL: serverURL), + discoveryClient: MockDiscoveryClient( + authorizationServer: serverURL, tokenEndpoint: serverURL.appendingPathComponent("token")), + registrar: registrar) + + _ = try await authorizer.handleChallenge( + statusCode: 401, headers: headers401, endpoint: endpoint, operationKey: nil, session: .shared) + + #expect(registrar.registerCallCount == 1) + #expect(registrar.lastAllowingLoopback == allowsLoopback) + } } diff --git a/Tests/MCPTests/OAuthClientRegistrarTests.swift b/Tests/MCPTests/OAuthClientRegistrarTests.swift index b885b0ee..4b7dc2a0 100644 --- a/Tests/MCPTests/OAuthClientRegistrarTests.swift +++ b/Tests/MCPTests/OAuthClientRegistrarTests.swift @@ -48,6 +48,7 @@ import Testing let result = try await registrar.register( configuration: config, asMetadata: makeASMetadata(), + allowingLoopback: false, session: session ) #expect(result == nil) @@ -60,6 +61,7 @@ import Testing let result = try await registrar.register( configuration: config, asMetadata: makeASMetadata(registrationEndpoint: nil), + allowingLoopback: false, session: session ) #expect(result == nil) @@ -77,6 +79,7 @@ import Testing try await registrar.register( configuration: config, asMetadata: makeASMetadata(registrationEndpoint: nil), + allowingLoopback: false, session: session ) } @@ -95,6 +98,7 @@ import Testing let result = try await registrar.register( configuration: makeConfig(authentication: .none(clientID: "plain-client-id")), asMetadata: makeASMetadata(registrationEndpoint: registrationEndpoint), + allowingLoopback: false, session: session ) #expect(result == nil) @@ -117,6 +121,7 @@ import Testing try await registrar.register( configuration: config, asMetadata: asMetadata, + allowingLoopback: false, session: session ) } @@ -139,6 +144,7 @@ import Testing let result = try await registrar.register( configuration: config, asMetadata: makeASMetadata(registrationEndpoint: registrationEndpoint), + allowingLoopback: false, session: session ) @@ -164,6 +170,7 @@ import Testing try await registrar.register( configuration: config, asMetadata: makeASMetadata(registrationEndpoint: registrationEndpoint), + allowingLoopback: false, session: session ) } @@ -184,12 +191,59 @@ import Testing try await registrar.register( configuration: config, asMetadata: makeASMetadata(registrationEndpoint: registrationEndpoint), + allowingLoopback: false, session: session ) } #expect(error == .tokenRequestFailed(statusCode: 503, oauthError: nil)) } + // MARK: - Loopback registration endpoints + + @Test("A loopback registration endpoint is refused before a request unless loopback is allowed") + func testRegisterRefusesLoopbackEndpoint() async throws { + let loopbackEndpoint = URL(string: "https://127.0.0.1:9443/register")! + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + Issue.record("no request may be sent to a refused registration endpoint: \(request.url!)") + let response = HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)! + return (response, try self.successRegistrationBody()) + } + + let error = await #expect(throws: OAuthAuthorizationError.self) { + try await registrar.register( + configuration: makeConfig(authentication: .none(clientID: "")), + asMetadata: makeASMetadata(registrationEndpoint: loopbackEndpoint), + allowingLoopback: false, + session: session + ) + } + #expect( + error + == .privateIPAddressBlocked( + context: "Client registration endpoint", url: loopbackEndpoint.absoluteString)) + } + + @Test("A loopback registration endpoint is used when loopback is allowed") + func testRegisterAllowsLoopbackEndpoint() async throws { + let loopbackEndpoint = URL(string: "https://localhost:9443/register")! + let body = try successRegistrationBody(clientID: "local-client") + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + let response = HTTPURLResponse(url: request.url!, statusCode: 201, httpVersion: nil, headerFields: nil)! + return (response, body) + } + + let result = try await registrar.register( + configuration: makeConfig(authentication: .none(clientID: "")), + asMetadata: makeASMetadata(registrationEndpoint: loopbackEndpoint), + allowingLoopback: true, + session: session + ) + + #expect(try #require(result).updatedAuthentication == .none(clientID: "local-client")) + } + // MARK: - updatedAuthentication helper @Test("updatedAuthentication updates client ID and secret for basic auth") diff --git a/Tests/MCPTests/OAuthDiscoveryClientTests.swift b/Tests/MCPTests/OAuthDiscoveryClientTests.swift index 28bf7d4a..a5ef79e7 100644 --- a/Tests/MCPTests/OAuthDiscoveryClientTests.swift +++ b/Tests/MCPTests/OAuthDiscoveryClientTests.swift @@ -334,6 +334,87 @@ import Testing #expect(storage.load()?.value == "override-token") } + @Test("A loopback candidate is refused without a request unless loopback is allowed") + func testFetchAuthorizationServerMetadataRefusesLoopback() async throws { + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + Issue.record("no request may be sent to a refused issuer: \(request.url!)") + return (HTTPURLResponse(url: request.url!, statusCode: 404, httpVersion: nil, headerFields: nil)!, Data()) + } + let loopback = URL(string: "https://localhost:9443")! + await #expect { + try await makeClient().fetchAuthorizationServerMetadata( + candidates: [loopback], trustedIssuer: nil, reportRefused: true, allowingLoopback: false, + session: session) + } throws: { error in + (error as? OAuthAuthorizationError)?.errorDescription + == OAuthAuthorizationError.privateIPAddressBlocked( + context: "Authorization server issuer", url: loopback.absoluteString + ).errorDescription + } + } + + @Test("A loopback candidate is fetched when loopback is allowed") + func testFetchAuthorizationServerMetadataAllowsLoopback() async throws { + let loopback = URL(string: "https://localhost:9443")! + let body = try makeASMetadataBody(issuer: loopback.absoluteString) + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + (HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!, body) + } + let (server, _) = try await makeClient().fetchAuthorizationServerMetadata( + candidates: [loopback], trustedIssuer: nil, reportRefused: true, allowingLoopback: true, + session: session) + #expect(server == loopback) + } + + @Test("A resource that is not on loopback cannot send discovery or token requests to loopback hosts") + func testRemoteResourceCannotReachLoopbackHosts() async throws { + let resourceMetadataURL = URL(string: "https://mcp.example.com/.well-known/oauth-protected-resource/mcp")! + let asMetadataURL = URL(string: "https://auth.example.com/.well-known/oauth-authorization-server")! + let requested = RequestedURLs() + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + let url = request.url! + await requested.append(url) + let body: [String: Any] + switch url { + case resourceMetadataURL: + body = [ + "resource": "https://mcp.example.com/mcp", + "authorization_servers": ["https://127.0.0.1:9443", "https://auth.example.com"], + ] + case asMetadataURL: + body = ["issuer": "https://auth.example.com", "token_endpoint": "https://localhost:9443/token"] + default: + return (HTTPURLResponse(url: url, statusCode: 404, httpVersion: nil, headerFields: nil)!, Data()) + } + return ( + HTTPURLResponse( + url: url, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "application/json"])!, + try JSONSerialization.data(withJSONObject: body) + ) + } + let authorizer = OAuthAuthorizer( + configuration: OAuthConfiguration( + grantType: .clientCredentials, authentication: .clientSecretPost(clientID: "c", clientSecret: "s"))) + + await #expect { + try await authorizer.handleChallenge( + statusCode: 401, + headers: ["WWW-Authenticate": "Bearer resource_metadata=\"\(resourceMetadataURL.absoluteString)\""], + endpoint: URL(string: "https://mcp.example.com/mcp")!, session: session) + } throws: { error in + (error as? OAuthAuthorizationError)?.errorDescription + == OAuthAuthorizationError.privateIPAddressBlocked( + context: "Token endpoint", url: "https://localhost:9443/token" + ).errorDescription + } + let urls = await requested.urls + #expect(urls.contains(asMetadataURL)) + #expect(!urls.contains { OAuthURLValidator.isLoopback($0) }) + } + @Test("Throws discovery failed when every candidate answers 404") func testFetchAuthorizationServerMetadataThrowsWhenAllAbsent() async throws { let (session, key) = makeIsolatedSession() @@ -418,4 +499,11 @@ import Testing } } + /// The URLs a mock session was asked for. + actor RequestedURLs { + private(set) var urls: [URL] = [] + + func append(_ url: URL) { urls.append(url) } + } + #endif diff --git a/Tests/MCPTests/OAuthJWTBearerTests.swift b/Tests/MCPTests/OAuthJWTBearerTests.swift index 88d036b4..f535876a 100644 --- a/Tests/MCPTests/OAuthJWTBearerTests.swift +++ b/Tests/MCPTests/OAuthJWTBearerTests.swift @@ -362,6 +362,161 @@ struct OAuthJWTBearerGrantTests { issuer: URL(string: "https://idp.example.com")!, session: session) #expect(tokenEndpoint == URL(string: "https://idp.example.com/oauth/token")!) } + + @Test("An endpoint the application passes may be on loopback") + func loopbackEndpoint() async throws { + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + try json(request.url!, 200, [ + "access_token": "id-jag", + "issued_token_type": "urn:ietf:params:oauth:token-type:id-jag", + "token_type": "N_A", + ]) + } + let response = try await OAuthTokenExchange.exchange( + request, tokenEndpoint: URL(string: "https://localhost:9443/token")!, + authentication: .none(clientID: "c"), session: session) + #expect(response.accessToken == "id-jag") + } + + @Test("An issuer the application passes may be on loopback") + func loopbackIssuer() async throws { + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + let url = request.url! + guard url.path.hasPrefix("/.well-known/") else { return try json(url, 404, [:]) } + return try json(url, 200, [ + "issuer": "https://localhost:8443", "token_endpoint": "https://localhost:8443/token", + ]) + } + let tokenEndpoint = try await OAuthTokenExchange.tokenEndpoint( + issuer: URL(string: "https://localhost:8443")!, session: session) + #expect(tokenEndpoint == URL(string: "https://localhost:8443/token")!) + } + + @Test( + "The token endpoint an issuer names is on loopback only when the issuer is, and never on a private IP literal", + arguments: [ + ("https://idp.example.com", "https://localhost:8443/token", false), + ("https://idp.example.com", "https://127.0.0.2/token", false), + ("https://idp.example.com", "https://[::1]/token", false), + ("https://idp.example.com", "https://[::ffff:127.0.0.1]/token", false), + ("https://idp.example.com", "https://10.0.0.1/token", false), + ("https://localhost:8443", "https://10.0.0.1/token", false), + ("https://localhost:8443", "https://[fd00::1]/token", false), + ("https://localhost:8443", "https://169.254.169.254/token", false), + ("https://idp.example.com", "https://tokens.example.net/token", true), + ("https://127.0.0.1:8443", "https://localhost:8443/token", true), + ]) + func tokenEndpointFollowsTheIssuer(issuer: String, endpoint: String, allowed: Bool) async throws { + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + let url = request.url! + guard url.path.hasPrefix("/.well-known/") else { return try json(url, 404, [:]) } + return try json(url, 200, ["issuer": issuer, "token_endpoint": endpoint]) + } + let discover = { + try await OAuthTokenExchange.tokenEndpoint(issuer: URL(string: issuer)!, session: session) + } + if allowed { + #expect(try await discover() == URL(string: endpoint)!) + } else { + await #expect { + _ = try await discover() + } throws: { error in + (error as? OAuthAuthorizationError)?.errorDescription + == OAuthAuthorizationError.privateIPAddressBlocked( + context: "Token exchange endpoint", url: endpoint + ).errorDescription + } + } + } + + @Test( + "The token endpoint an issuer names must be https, or loopback http when allowed, without a fragment", + arguments: [ + ( + "https://idp.example.com", "http://tokens.example.net/token", false, + OAuthAuthorizationError.insecureAuthorizationServerEndpoint( + context: "Token exchange endpoint", url: "http://tokens.example.net/token") + ), + ( + "https://localhost:8443", "http://localhost:8443/token", false, + .insecureAuthorizationServerEndpoint( + context: "Token exchange endpoint", url: "http://localhost:8443/token") + ), + ( + "https://idp.example.com", "https://idp.example.com/token#top", false, + .invalidResourceURI("Invalid Token exchange endpoint: https://idp.example.com/token#top") + ), + ( + "https://idp.example.com", "http://10.0.0.1/token", false, + .insecureAuthorizationServerEndpoint( + context: "Token exchange endpoint", url: "http://10.0.0.1/token") + ), + ( + "https://idp.example.com", "http://localhost:8080/token", true, + .privateIPAddressBlocked(context: "Token exchange endpoint", url: "http://localhost:8080/token") + ), + ("http://localhost:8080", "http://localhost:8080/token", true, nil), + ] as [(String, String, Bool, OAuthAuthorizationError?)]) + func tokenEndpointIsValidated( + issuer: String, endpoint: String, allowsLoopbackHTTP: Bool, refusal: OAuthAuthorizationError? + ) async throws { + let (session, key) = makeIsolatedSession() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + let url = request.url! + guard url.path.hasPrefix("/.well-known/") else { return try json(url, 404, [:]) } + return try json(url, 200, ["issuer": issuer, "token_endpoint": endpoint]) + } + let validator = OAuthURLValidator(allowLoopbackHTTPForAuthorizationServer: allowsLoopbackHTTP) + let discover = { + try await OAuthTokenExchange.tokenEndpoint( + issuer: URL(string: issuer)!, session: session, urlValidator: validator) + } + if let refusal { + await #expect { + _ = try await discover() + } throws: { error in + (error as? OAuthAuthorizationError)?.errorDescription == refusal.errorDescription + } + } else { + #expect(try await discover() == URL(string: endpoint)!) + } + } + + @Test( + "A refused issuer fails before any request", + arguments: [ + ( + "https://idp.example.com/#top", + OAuthAuthorizationError.invalidResourceURI( + "Invalid Authorization server issuer: https://idp.example.com/#top") + ), + ( + "http://idp.example.com", + .insecureAuthorizationServerEndpoint( + context: "Authorization server issuer", url: "http://idp.example.com") + ), + ( + "https://10.0.0.1", + .privateIPAddressBlocked(context: "Authorization server issuer", url: "https://10.0.0.1") + ), + ]) + func refusedIssuer(issuer: String, refusal: OAuthAuthorizationError) async throws { + let (session, key) = makeIsolatedSession() + let calls = Recorder() + await IsolatedMockURLProtocol.setHandler(key: key) { request in + await calls.append(1) + return try json(request.url!, 404, [:]) + } + await #expect { + _ = try await OAuthTokenExchange.tokenEndpoint(issuer: URL(string: issuer)!, session: session) + } throws: { error in + (error as? OAuthAuthorizationError)?.errorDescription == refusal.errorDescription + } + #expect(await calls.values.isEmpty) + } } @Suite("Enterprise-managed authorization (SEP-990)", .serialized) @@ -852,5 +1007,50 @@ struct OAuthJWTBearerDestinationTests { #expect(try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: session)) #expect(await discoveries.values.count == 1) } + + @Test( + "The token endpoint an identity provider names is on loopback only when the provider is", + arguments: zip(["https://login.example.com", "https://localhost:8443"], [false, true])) + func idpTokenEndpointFollowsTheProvider(issuer: String, allowed: Bool) async throws { + let (session, key) = makeIsolatedSession() + let requested = Recorder() + let loopbackTokenEndpoint = URL(string: "https://localhost:8443/token")! + await IsolatedMockURLProtocol.setHandler(key: key) { request in + let url = request.url! + await requested.append(url) + switch (url.host!, url.path) { + case ("mcp.example.com", _): + return try json(url, 200, ["authorization_servers": ["https://auth.example.com"]]) + case ("auth.example.com", "/.well-known/oauth-authorization-server"): + return try json(url, 200, ["issuer": "https://auth.example.com", "token_endpoint": "https://auth.example.com/token"]) + case (_, "/.well-known/oauth-authorization-server") where url.absoluteString.hasPrefix(issuer): + return try json(url, 200, ["issuer": issuer, "token_endpoint": loopbackTokenEndpoint.absoluteString]) + case ("localhost", "/token"): + return try json(url, 200, [ + "access_token": "id-jag", "issued_token_type": "urn:ietf:params:oauth:token-type:id-jag", + "token_type": "N_A", + ]) + case ("auth.example.com", "/token"): + return try json(url, 200, ["access_token": "mcp-token", "token_type": "Bearer", "expires_in": 3600]) + default: + return try json(url, 404, [:]) + } + } + let authorizer = OAuthAuthorizer( + configuration: .enterpriseManaged( + authentication: .clientSecretBasic(clientID: "c", clientSecret: "s"), + authorizationServer: URL(string: "https://auth.example.com")!, + identityProvider: .init(endpoint: .issuer(URL(string: issuer)!), authentication: .none(clientID: "i")), + idToken: { _ in "id-token" })) + + if allowed { + #expect(try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: session)) + } else { + await #expect { + _ = try await authorizer.handleChallenge(statusCode: 401, headers: headers401, endpoint: endpoint, session: session) + } throws: { ($0 as? OAuthAuthorizationError)?.code == .privateIPAddressBlocked } + } + #expect(await requested.values.contains(loopbackTokenEndpoint) == allowed) + } } diff --git a/Tests/MCPTests/OAuthURLValidatorTests.swift b/Tests/MCPTests/OAuthURLValidatorTests.swift index 8044ae9f..63189f5d 100644 --- a/Tests/MCPTests/OAuthURLValidatorTests.swift +++ b/Tests/MCPTests/OAuthURLValidatorTests.swift @@ -332,6 +332,56 @@ struct OAuthURLValidatorTests { #expect(!OAuthLoopbackHost.isLoopback("[::2]")) } + // MARK: - Loopback hosts a server names + + @Test( + "Every spelling of this machine is a loopback host", + arguments: [ + "localhost", "LOCALHOST", "localhost.", "a.b.localhost", "127.0.0.1", "127.255.255.254", "::1", + "[::1]", "[::ffff:127.0.0.1]", "[::127.0.0.1]", "[64:ff9b::7f00:1]", + ]) + func testIsLoopbackHost(host: String) { + #expect(OAuthURLValidator.isLoopbackHost(host)) + } + + @Test( + "Hosts that only look like this machine are not loopback hosts", + arguments: [ + "localhost.example.com", "notlocalhost", "evil-localhost", "localhostx", "example.com", "[::2]", + "128.0.0.1", "10.0.0.1", "[::ffff:10.0.0.1]", "[localhost]", "", + ]) + func testIsNotLoopbackHost(host: String) { + #expect(!OAuthURLValidator.isLoopbackHost(host)) + } + + @Test("A URL is on loopback only when its host is") + func testIsLoopbackURL() { + #expect(OAuthURLValidator.isLoopback(URL(string: "https://localhost:8443/token"))) + #expect(OAuthURLValidator.isLoopback(URL(string: "http://[::1]:8080/mcp"))) + #expect(!OAuthURLValidator.isLoopback(URL(string: "https://mcp.example.com/mcp"))) + #expect(!OAuthURLValidator.isLoopback(URL(string: "file:///tmp/x"))) + #expect(!OAuthURLValidator.isLoopback(nil)) + } + + @Test("A loopback URL is refused unless loopback is allowed; a private one always is") + func testRejectPrivateIPAllowingLoopback() throws { + let v = OAuthURLValidator() + let isBlocked: (any Error) -> Bool = { ($0 as? OAuthAuthorizationError)?.code == .privateIPAddressBlocked } + let loopback = URL(string: "https://127.0.0.1:9443/token")! + #expect { try v.rejectPrivateIP(loopback, context: "Token endpoint", allowingLoopback: false) } throws: { + isBlocked($0) + } + try v.rejectPrivateIP(loopback, context: "Token endpoint", allowingLoopback: true) + for allowingLoopback in [false, true] { + #expect { + try v.rejectPrivateIP( + URL(string: "https://10.0.0.1/token")!, context: "Token endpoint", allowingLoopback: allowingLoopback) + } throws: { isBlocked($0) } + } + try v.rejectPrivateIP( + URL(string: "https://auth.example.com/token")!, context: "Token endpoint", allowingLoopback: false) + } + // MARK: - Redirects @Test("Discovery redirects must stay https and public") diff --git a/design/auth.md b/design/auth.md index 281c20c6..fd7e8d59 100644 --- a/design/auth.md +++ b/design/auth.md @@ -142,7 +142,7 @@ gate, so concurrent requests refresh once. PRM candidates, first 2xx response with non-empty `authorization_servers` wins: 1. `resource_metadata` from the `WWW-Authenticate` challenge (must be HTTPS or loopback, not a - private IP); + private IP, and on a loopback host only when the endpoint is); 2. `endpointOverrides.protectedResourceMetadataURL`; 3. `/.well-known/oauth-protected-resource`; 4. `/.well-known/oauth-protected-resource`. @@ -157,7 +157,8 @@ AS metadata. AS candidates: `endpointOverrides.authorizationServerURL`, else the selected AS, else the PRM's `authorization_servers` in order. Candidates that fail validation or are private IPs are skipped -without a request. When every candidate is skipped, discovery throws the first refusal +without a request, and so are loopback candidates unless the endpoint is on loopback or the +candidate is the override. When every candidate is skipped, discovery throws the first refusal (`insecureAuthorizationServerEndpoint` or `privateIPAddressBlocked`), not `authorizationServerMetadataDiscoveryFailed`, except for the origin of the [2025-03-26 fallback](#2025-03-26-fallback). @@ -248,7 +249,8 @@ only there. `https` (or allowed loopback) and no private IP literal; no redirects. The response must carry `issued_token_type` equal to the requested type (`issuedTokenTypeMismatch`); `token_type` is not checked (`N_A` for an ID-JAG). `OAuthTokenExchange.tokenEndpoint(issuer:)` reads the token -endpoint from the issuer's metadata, with the same issuer check as AS discovery. +endpoint from the issuer's metadata, with the same issuer check as AS discovery, and checks it as +`exchange` does; it also refuses a loopback host while the issuer is not on loopback. Comparison: the Python SDK implements leg 2 (`IdentityAssertionOAuthProvider`, configured issuer, no PRM) and leaves leg 1 to the application; the Go SDK has both legs (`EnterpriseHandler`, @@ -327,10 +329,21 @@ validated when it is used, so a refused origin still works with a `tokenEndpoint ### URL safety -The MCP endpoint, discovery URLs and AS endpoints must be HTTPS or loopback HTTP. A challenge's -PRM URL, AS candidates, the authorization endpoint and the token endpoint are rejected when the -host is a private or link-local IP literal (`isPrivateIPHost`). Host names are not resolved, so -DNS rebinding is not covered. The redirect URI is validated before the flow starts. +The MCP endpoint, discovery URLs, AS endpoints and an identity provider's token endpoint must be +HTTPS or loopback HTTP. A challenge's PRM URL, AS candidates, the authorization, token and +registration endpoints, and the token endpoint an identity provider's metadata names are rejected +when the host is a private or link-local IP literal (`isPrivateIPHost`). A URL a server names is +also rejected when its host is loopback (`localhost`, a name under `.localhost`, `127.0.0.0/8`, +`::1`, `OAuthURLValidator.isLoopbackHost`) and the server that named it is not: the challenge's +PRM URL and the PRM's `authorization_servers` follow the MCP endpoint, and the authorization, +token and registration endpoints follow the selected AS. This is the rule `OAuthRedirectGuard` +applies to redirect hops (RFC 9728 §7.7). URLs in `endpointOverrides` are not checked for +loopback, but the servers a configured `protectedResourceMetadataURL` lists still follow the MCP +endpoint. The token endpoint an identity provider's metadata names +(`OAuthTokenExchange.tokenEndpoint(issuer:)`, used by `enterpriseManaged` with `.issuer`) follows +the provider's issuer. `AccessTokenProviderContext` passes the AS-named endpoints to the +application unchecked. Host names are not resolved, so DNS rebinding is not covered. The redirect +URI is validated before the flow starts. ## Alternatives considered diff --git a/design/threat_model.md b/design/threat_model.md index 982e72d2..8de7834e 100644 --- a/design/threat_model.md +++ b/design/threat_model.md @@ -100,7 +100,9 @@ See [auth.md](auth.md). In short: - The MCP endpoint, discovery URLs and authorization server endpoints must be HTTPS or loopback HTTP. URLs a server names are refused when their host is a private, link-local or reserved IP - literal, in any spelling (`isPrivateIPHost` parses with `inet_pton`). + literal, in any spelling (`isPrivateIPHost` parses with `inet_pton`), and when their host is + loopback (`OAuthURLValidator.isLoopbackHost`) unless the server that named them is on loopback + too. URLs set in `endpointOverrides` may be on loopback. - Discovery follows redirects only to URLs that pass the same checks; token, registration and exchange requests follow none (`OAuthRedirectGuard`, on every platform). - Authorization server metadata whose `issuer` differs from the candidate is refused. A refresh diff --git a/docs/protocol.md b/docs/protocol.md index 52baef5e..270ae2cc 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -802,7 +802,7 @@ let configuration = OAuthConfiguration.enterpriseManaged( - Every 401 runs both steps again, unless the authorization server issued a refresh token. Without a refresh token, the authorizer also runs them before the token expires (`proactiveRefreshWindowSeconds`). ID-JAGs are not cached. Concurrent 401s run them once. - The exchange requires `issued_token_type` to be the ID-JAG type (`issuedTokenTypeMismatch` otherwise) and accepts the `token_type` `N_A`. Exchange and grant requests follow no redirects. -`OAuthTokenExchange.exchange(_:tokenEndpoint:authentication:session:urlValidator:)` performs one RFC 8693 exchange for other uses, and `OAuthTokenExchange.tokenEndpoint(issuer:session:urlValidator:)` discovers a token endpoint. `OAuthTokenExchange.TokenType` has the token type URIs. +`OAuthTokenExchange.exchange(_:tokenEndpoint:authentication:session:urlValidator:)` performs one RFC 8693 exchange for other uses, and `OAuthTokenExchange.tokenEndpoint(issuer:session:urlValidator:)` discovers a token endpoint and checks it as `exchange` does: it refuses one that is not `https` (`insecureAuthorizationServerEndpoint`), has a fragment or no host (`invalidResourceURI`), or whose host is a private IP literal, or a loopback host while the issuer is not (`privateIPAddressBlocked`). `OAuthTokenExchange.TokenType` has the token type URIs. #### Workload identity @@ -946,7 +946,8 @@ await server.withMethodHandler(CallTool.self) { params in A malicious server can point OAuth discovery at internal addresses. `OAuthAuthorizer` applies these rules: - **HTTPS.** The MCP endpoint, resource metadata URLs and authorization server endpoints must be `https`; `http` is accepted only for loopback hosts (`localhost`, `127.0.0.1`, `::1`), and for authorization server endpoints not at all by default. URLs with fragments are rejected. -- **Private addresses.** `OAuthURLValidator.isPrivateIPHost` parses literal IP hosts with `inet_pton` and rejects `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `169.254.0.0/16` (cloud metadata), `172.16.0.0/12`, `192.0.0.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `224.0.0.0/4`, `240.0.0.0/4`, `::`, `fc00::/7`, `fe80::/10`, `fec0::/10` and `ff00::/8`, in any spelling: bracketed, zoned (`%en0`), and IPv4 addresses embedded as IPv4-mapped, IPv4-compatible or NAT64 IPv6. Numeric hosts that are not a canonical dotted quad (`167772161`, `10.1`, `0x0a.0.0.1`, `012.0.0.1`) are rejected too. Host names and loopback addresses are never rejected. It is applied to the challenge's `resource_metadata` URL, authorization server candidates (skipped; when every candidate is refused, discovery throws the first refusal, `privateIPAddressBlocked` or `insecureAuthorizationServerEndpoint`), and the authorization, token and registration endpoints (`privateIPAddressBlocked`). +- **Private addresses.** `OAuthURLValidator.isPrivateIPHost` parses literal IP hosts with `inet_pton` and rejects `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `169.254.0.0/16` (cloud metadata), `172.16.0.0/12`, `192.0.0.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `224.0.0.0/4`, `240.0.0.0/4`, `::`, `fc00::/7`, `fe80::/10`, `fec0::/10` and `ff00::/8`, in any spelling: bracketed, zoned (`%en0`), and IPv4 addresses embedded as IPv4-mapped, IPv4-compatible or NAT64 IPv6. Numeric hosts that are not a canonical dotted quad (`167772161`, `10.1`, `0x0a.0.0.1`, `012.0.0.1`) are rejected too. It never rejects host names or loopback addresses. It is applied to the challenge's `resource_metadata` URL, authorization server candidates (skipped; when every candidate is refused, discovery throws the first refusal, `privateIPAddressBlocked` or `insecureAuthorizationServerEndpoint`), the authorization, token and registration endpoints, and the token endpoint an identity provider's metadata names (`privateIPAddressBlocked`). +- **Loopback hosts.** A URL a server names may be on a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only when that server is on one too: the challenge's `resource_metadata` URL and the resource's authorization servers when the MCP endpoint is, and the authorization, token and registration endpoints when the selected authorization server is. Otherwise they are refused like private addresses, before any request. URLs set in `endpointOverrides` may be on loopback; the servers a configured `protectedResourceMetadataURL` lists still follow the MCP endpoint, so set `authorizationServerURL` for a local authorization server. The token endpoint that an identity provider's metadata names (`OAuthTokenExchange.tokenEndpoint(issuer:)`, which `enterpriseManaged` uses with `.issuer`) follows that provider's issuer. Redirects follow the same rule. - **Redirects.** Metadata discovery follows a redirect only to an `https` URL, or from loopback `http` to loopback `http`, whose host is not a private address, and to a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only from a loopback host. Each hop is checked against the one before it. Token and registration requests, which carry credentials, follow no redirects. What the SDK does not do: it checks literal IP addresses only, so a host name that resolves to a private address passes, and DNS rebinding is not prevented. On Linux (swift-corelibs-foundation), which has no per-task delegates, each OAuth request runs in a session with the caller session's configuration and the redirect check as its delegate. Run clients that connect to untrusted servers behind an egress proxy or firewall that blocks internal ranges. diff --git a/docs/src/protocol.src.md b/docs/src/protocol.src.md index 1626dc4c..529a90af 100644 --- a/docs/src/protocol.src.md +++ b/docs/src/protocol.src.md @@ -494,7 +494,7 @@ In an enterprise that manages access to MCP servers (SEP-990), the user signs in - Every 401 runs both steps again, unless the authorization server issued a refresh token. Without a refresh token, the authorizer also runs them before the token expires (`proactiveRefreshWindowSeconds`). ID-JAGs are not cached. Concurrent 401s run them once. - The exchange requires `issued_token_type` to be the ID-JAG type (`issuedTokenTypeMismatch` otherwise) and accepts the `token_type` `N_A`. Exchange and grant requests follow no redirects. -`OAuthTokenExchange.exchange(_:tokenEndpoint:authentication:session:urlValidator:)` performs one RFC 8693 exchange for other uses, and `OAuthTokenExchange.tokenEndpoint(issuer:session:urlValidator:)` discovers a token endpoint. `OAuthTokenExchange.TokenType` has the token type URIs. +`OAuthTokenExchange.exchange(_:tokenEndpoint:authentication:session:urlValidator:)` performs one RFC 8693 exchange for other uses, and `OAuthTokenExchange.tokenEndpoint(issuer:session:urlValidator:)` discovers a token endpoint and checks it as `exchange` does: it refuses one that is not `https` (`insecureAuthorizationServerEndpoint`), has a fragment or no host (`invalidResourceURI`), or whose host is a private IP literal, or a loopback host while the issuer is not (`privateIPAddressBlocked`). `OAuthTokenExchange.TokenType` has the token type URIs. #### Workload identity @@ -570,7 +570,8 @@ A server must accept only tokens issued for itself and must not forward client t A malicious server can point OAuth discovery at internal addresses. `OAuthAuthorizer` applies these rules: - **HTTPS.** The MCP endpoint, resource metadata URLs and authorization server endpoints must be `https`; `http` is accepted only for loopback hosts (`localhost`, `127.0.0.1`, `::1`), and for authorization server endpoints not at all by default. URLs with fragments are rejected. -- **Private addresses.** `OAuthURLValidator.isPrivateIPHost` parses literal IP hosts with `inet_pton` and rejects `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `169.254.0.0/16` (cloud metadata), `172.16.0.0/12`, `192.0.0.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `224.0.0.0/4`, `240.0.0.0/4`, `::`, `fc00::/7`, `fe80::/10`, `fec0::/10` and `ff00::/8`, in any spelling: bracketed, zoned (`%en0`), and IPv4 addresses embedded as IPv4-mapped, IPv4-compatible or NAT64 IPv6. Numeric hosts that are not a canonical dotted quad (`167772161`, `10.1`, `0x0a.0.0.1`, `012.0.0.1`) are rejected too. Host names and loopback addresses are never rejected. It is applied to the challenge's `resource_metadata` URL, authorization server candidates (skipped; when every candidate is refused, discovery throws the first refusal, `privateIPAddressBlocked` or `insecureAuthorizationServerEndpoint`), and the authorization, token and registration endpoints (`privateIPAddressBlocked`). +- **Private addresses.** `OAuthURLValidator.isPrivateIPHost` parses literal IP hosts with `inet_pton` and rejects `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `169.254.0.0/16` (cloud metadata), `172.16.0.0/12`, `192.0.0.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `224.0.0.0/4`, `240.0.0.0/4`, `::`, `fc00::/7`, `fe80::/10`, `fec0::/10` and `ff00::/8`, in any spelling: bracketed, zoned (`%en0`), and IPv4 addresses embedded as IPv4-mapped, IPv4-compatible or NAT64 IPv6. Numeric hosts that are not a canonical dotted quad (`167772161`, `10.1`, `0x0a.0.0.1`, `012.0.0.1`) are rejected too. It never rejects host names or loopback addresses. It is applied to the challenge's `resource_metadata` URL, authorization server candidates (skipped; when every candidate is refused, discovery throws the first refusal, `privateIPAddressBlocked` or `insecureAuthorizationServerEndpoint`), the authorization, token and registration endpoints, and the token endpoint an identity provider's metadata names (`privateIPAddressBlocked`). +- **Loopback hosts.** A URL a server names may be on a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only when that server is on one too: the challenge's `resource_metadata` URL and the resource's authorization servers when the MCP endpoint is, and the authorization, token and registration endpoints when the selected authorization server is. Otherwise they are refused like private addresses, before any request. URLs set in `endpointOverrides` may be on loopback; the servers a configured `protectedResourceMetadataURL` lists still follow the MCP endpoint, so set `authorizationServerURL` for a local authorization server. The token endpoint that an identity provider's metadata names (`OAuthTokenExchange.tokenEndpoint(issuer:)`, which `enterpriseManaged` uses with `.issuer`) follows that provider's issuer. Redirects follow the same rule. - **Redirects.** Metadata discovery follows a redirect only to an `https` URL, or from loopback `http` to loopback `http`, whose host is not a private address, and to a loopback host (`localhost`, a name under `.localhost`, `127.0.0.0/8`, `::1`) only from a loopback host. Each hop is checked against the one before it. Token and registration requests, which carry credentials, follow no redirects. What the SDK does not do: it checks literal IP addresses only, so a host name that resolves to a private address passes, and DNS rebinding is not prevented. On Linux (swift-corelibs-foundation), which has no per-task delegates, each OAuth request runs in a session with the caller session's configuration and the redirect check as its delegate. Run clients that connect to untrusted servers behind an egress proxy or firewall that blocks internal ranges. From ebe8447b8e260423540103d1796d036f5ccb0466 Mon Sep 17 00:00:00 2001 From: Jean-Matthieu Schaffhauser Date: Tue, 1 Dec 2026 08:19:29 +0000 Subject: [PATCH 2/2] docs: record the OAuth loopback refusal in CHANGELOG and migration guide The previous commit refuses a loopback URL that a remote server names (resource_metadata, authorization servers, and the endpoints in authorization server or identity provider metadata), and OAuthTokenExchange.tokenEndpoint(issuer:) now checks the endpoint it returns. Releases up to 0.12.x accepted these setups, so upgraders can hit privateIPAddressBlocked where they did not before. Add a bullet to the behavior changes of 1.0.0 in CHANGELOG.md, and a summary row and two Authorization bullets to the migration guide that point at endpointOverrides. docs/migration.md is regenerated with scripts/weave.swift. Assisted-by: Claude --- CHANGELOG.md | 6 ++++++ docs/migration.md | 18 ++++++++++++++++++ docs/src/migration.src.md | 18 ++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d968fcc9..7f2af9c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,12 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha dynamic client registration. Pass `""` to register. - Authorization server metadata whose `issuer` does not match fails discovery (`authorizationServerIssuerMismatch`) instead of being used. +- An OAuth URL a server names (a challenge's `resource_metadata`, the listed authorization + servers, and the endpoints in authorization server or identity provider metadata, including the + one `OAuthTokenExchange.tokenEndpoint(issuer:)` returns) may be on a loopback host only when + that server is, and fails with `privateIPAddressBlocked` otherwise. Set `endpointOverrides` for + a local authorization server used with a remote MCP endpoint + ([details](docs/migration.md#authorization)). - `HTTPClientTransport.connect()` after `disconnect()` throws `internalError`: create a new transport to reconnect. - `Client.connect(transport:)` disconnects and throws `internalError` when the server answers diff --git a/docs/migration.md b/docs/migration.md index c99d6ae0..17f8844e 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -48,6 +48,7 @@ each change that breaks source code. | `.stateless(version)` | No retry with another version | Use `.automatic` for negotiation | | Sampling with tools | The client refuses tools without `sampling.tools`, and tool messages that break the rules, with -32602; `requestSampling` refuses them before it sends | Declare `sampling.tools` when the sampling handler takes tools | | `.none(clientID:)` | A plain client ID is pre-registered: no dynamic registration | Pass `""` to register | +| OAuth loopback URLs | A URL a server names may be on a loopback host only when that server is; otherwise `privateIPAddressBlocked`, also from `OAuthTokenExchange.tokenEndpoint(issuer:)` | Set `endpointOverrides` for a local authorization server used with a remote MCP endpoint | | `StatelessHTTPServerTransport` with an `initializeHook` | Handshake requests other than `initialize` are refused with -32600 unless a `statelessRequestHook` is set | Set a `statelessRequestHook` | | Terminated stateful HTTP session | After a session ends and validation passes, requests without a session ID receive 400 instead of 404; requests with any session ID receive 404 | Route a new sessionless `initialize` to a new transport and `Server` | | `data:` URL strings | Arrive as sent instead of rewritten as base64 `data:` URLs; prose such as `data: 3 rows, 2 columns` is no longer a `data:` URL | Nothing | @@ -857,6 +858,23 @@ session ended. redirects only to `https` hosts that are not private addresses, and to a loopback host only from a loopback host, and follow no redirect for token and registration requests; +- accept a loopback host (`localhost`, a name under `.localhost`, + `127.0.0.0/8`, `::1`) in a URL a server names only when that server is on + one: the challenge's `resource_metadata` URL and the listed authorization + servers follow the MCP endpoint, and the authorization, token and + registration endpoints follow the selected authorization server. The + previous release accepted them from any server; now they fail with + `privateIPAddressBlocked` before any request. To use a local authorization + server with a remote MCP endpoint, set + `endpointOverrides.authorizationServerURL` (and `tokenEndpoint` if + needed), which may be on loopback; +- check the token endpoint that + `OAuthTokenExchange.tokenEndpoint(issuer:)` returns as `exchange` does. It + throws `insecureAuthorizationServerEndpoint` when the endpoint is not + `https`, `invalidResourceURI` when it has a fragment or no host, and + `privateIPAddressBlocked` when its host is a private IP literal, or a + loopback host while the issuer is not. The previous release returned it + unchecked; - count as private the IPv6 addresses that embed a private IPv4 address as IPv4-translated (`::ffff:0:0:0/96`) or 6to4 (`2002::/16`), and the local-use NAT64 prefix `64:ff9b:1::/48`. A host with `:` that is not an diff --git a/docs/src/migration.src.md b/docs/src/migration.src.md index 31041194..be6a4d2f 100644 --- a/docs/src/migration.src.md +++ b/docs/src/migration.src.md @@ -46,6 +46,7 @@ each change that breaks source code. | `.stateless(version)` | No retry with another version | Use `.automatic` for negotiation | | Sampling with tools | The client refuses tools without `sampling.tools`, and tool messages that break the rules, with -32602; `requestSampling` refuses them before it sends | Declare `sampling.tools` when the sampling handler takes tools | | `.none(clientID:)` | A plain client ID is pre-registered: no dynamic registration | Pass `""` to register | +| OAuth loopback URLs | A URL a server names may be on a loopback host only when that server is; otherwise `privateIPAddressBlocked`, also from `OAuthTokenExchange.tokenEndpoint(issuer:)` | Set `endpointOverrides` for a local authorization server used with a remote MCP endpoint | | `StatelessHTTPServerTransport` with an `initializeHook` | Handshake requests other than `initialize` are refused with -32600 unless a `statelessRequestHook` is set | Set a `statelessRequestHook` | | Terminated stateful HTTP session | After a session ends and validation passes, requests without a session ID receive 400 instead of 404; requests with any session ID receive 404 | Route a new sessionless `initialize` to a new transport and `Server` | | `data:` URL strings | Arrive as sent instead of rewritten as base64 `data:` URLs; prose such as `data: 3 rows, 2 columns` is no longer a `data:` URL | Nothing | @@ -743,6 +744,23 @@ session ended. redirects only to `https` hosts that are not private addresses, and to a loopback host only from a loopback host, and follow no redirect for token and registration requests; +- accept a loopback host (`localhost`, a name under `.localhost`, + `127.0.0.0/8`, `::1`) in a URL a server names only when that server is on + one: the challenge's `resource_metadata` URL and the listed authorization + servers follow the MCP endpoint, and the authorization, token and + registration endpoints follow the selected authorization server. The + previous release accepted them from any server; now they fail with + `privateIPAddressBlocked` before any request. To use a local authorization + server with a remote MCP endpoint, set + `endpointOverrides.authorizationServerURL` (and `tokenEndpoint` if + needed), which may be on loopback; +- check the token endpoint that + `OAuthTokenExchange.tokenEndpoint(issuer:)` returns as `exchange` does. It + throws `insecureAuthorizationServerEndpoint` when the endpoint is not + `https`, `invalidResourceURI` when it has a fragment or no host, and + `privateIPAddressBlocked` when its host is a private IP literal, or a + loopback host while the issuer is not. The previous release returned it + unchecked; - count as private the IPv6 addresses that embed a private IPv4 address as IPv4-translated (`::ffff:0:0:0/96`) or 6to4 (`2002::/16`), and the local-use NAT64 prefix `64:ff9b:1::/48`. A host with `:` that is not an