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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 22 additions & 7 deletions Sources/MCP/Base/Authorization/OAuthAuthorizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand All @@ -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
{
Expand All @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion Sources/MCP/Base/Authorization/OAuthClientRegistrar.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ protocol OAuthClientRegistering: Sendable {
func register(
configuration: OAuthConfiguration,
asMetadata: OAuthAuthorizationServerMetadata,
allowingLoopback: Bool,
session: URLSession
) async throws -> (
response: OAuthClientRegistrationResponse,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"
Expand Down
10 changes: 7 additions & 3 deletions Sources/MCP/Base/Authorization/OAuthConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
13 changes: 9 additions & 4 deletions Sources/MCP/Base/Authorization/OAuthDiscoveryClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down Expand Up @@ -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:)``
Expand All @@ -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()
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions Sources/MCP/Base/Authorization/OAuthErrors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
14 changes: 3 additions & 11 deletions Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
27 changes: 21 additions & 6 deletions Sources/MCP/Base/Authorization/OAuthTokenExchange.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -176,31 +178,44 @@ 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:)``
/// when its metadata names another issuer;
/// ``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,
urlValidator: OAuthURLValidator = OAuthURLValidator()
) 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
}
}
Expand Down
Loading
Loading