go-sdk/oauthex/resource_meta.go
Maciej Kisiel c9317fb5b7
all: client side OAuth support (#785)
This PR introduces client-side OAuth support.

# Overall design philosophy

The main new interface introduced to support client-side OAuth is the
`OAuthHandler`. Contrary to its counter-parts in some other SDKs, it is
intentionally small and generic so that it can support most of the OAuth
authorization flow variants. The main `mcp` package purposefully
delegates almost all auth handling to `OAuthHandler` implementations.
This way, the `mcp` package continues to be largely OAuth agnostic.

The `auth` package comes with a default `OAuthHandler` implementation –
`AuthorizationCodeHandler`, which implements the authorization flow
for the `authorization_code` grant type, as defined in the [MCP
specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).
It is expected that the `OAuthHandler` implementation granularity will
be roughly per grant type, as this parameter influences the
authorization flow the most.

# Detailed design

## `OAuthHandler` (auth/client.go)

The main interface for the integration consists of two methods:

```go
type OAuthHandler interface {
	// TokenSource returns a token source to be used for outgoing requests.
	// Returned token source might be nil. In that case, the transport will not
	// add any authorization headers to the request.
	TokenSource(context.Context) (oauth2.TokenSource, error)

	// Authorize is called when an HTTP request results in an error that may
	// be addressed by the authorization flow (currently 401 Unauthorized and 403 Forbidden).
	// It is responsible for performing the OAuth flow to obtain an access token.
	// The arguments are the request that failed and the response that was received for it.
	// The headers of the request are available, but the body will have already been consumed
	// when Authorize is called.
	// If the returned error is nil, TokenSource is expected to return a non-nil token source.
	// After a successful call to Authorize, the HTTP request will be retried by the transport.
	// The function is responsible for closing the response body.
	Authorize(context.Context, *http.Request, *http.Response) error
}
```

`StreamableClientTransport` accepts this interface as a field and uses
the `TokenSource` method to add an `Authorization: Bearer` header to
outgoing requests to the MCP server. If the request fails with `401:
Unauthorized` or `403: Forbidden`, the transport calls `Authorize` to
perform the authorization flow. If `Authorize` returns a non-nil error,
the request is retried once. `Authorize` errors do not result in
termination of the client session (unless they happen during
connection initialization), as some OAuth flows are multi-legged and it should be
acceptable to retry for example when the authorization grant was
received.

*Note:* There was already an `OAuthHandler` type defined as part of a
previous iteration of OAuth support. It was renamed to
`OAuthHandlerLegacy`. This is the only backwards incompatible API change
in the experimental client `auth` part (protected by the
`mcp_go_client_oauth` Go build tag). The cost of replacing previous
usages is deemed worthwhile to maintain clear naming, under the
assumption that the experimental client `auth` part was not widely used.

## `AuthorizationCodeHandler` (auth/authorization_code.go)

This is the `OAuthHandler` implementation that fulfills the [MCP
specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).
In particular, in supports:

- Protected Resource Metadata discovery and fetching
- Authorization Server Metadata discovery and fetching
- Client registration
  - OpenID Connect metadata document
  - Pre-registration
  - Dynamic Client Registration
- PKCE
- `client_secret_post`, `client_secret_basic` token endpoint
auth methods
- Automatic refresh of tokens

### Authorization Server redirect

As part of the flow for the `authorization_code` grant type, the client
needs to point the user to the authorization URL, so that they confirm
the access request. This design proposes that it will be supported via a
pluggable dependency that will initiate this process in an
application-specific way:

```go
type AuthorizationCodeHandler struct {
	...

	// AuthorizationCodeFetcher is a required function called to initiate the authorization flow.
	// It is responsible for opening the URL in a browser for the user to start the authorization process.
	// It should return the authorization code and state once the Authorization Server
	// redirects back to the RedirectURL.
	AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error)

	...
}
```

The function is supposed perform any application specific logic to handle the redirect
from the Authorization Server and return the resulting code and state.

## `oauthex` changes

Some additional/adjusted building blocks that may be useful when
creating `OAuthHandler` implementations are present in the `oauthex`
package:

- `auth_meta.go`: Authorization Server Metadata utilities:
  - `GetAuthServerMeta`: get Authorization Server Metadata from a URL
- `dcr.go`: Dynamic Client Registration utilities (unchanged)
- `resource_meta.go`: Protected Resource Metadata utilities:
- `GetProtectedResourceMetadata`: get Protected Resource Metadata from a
URL
  - `ParseWWWAuthenticate` – as per name (unchanged)
- [deprecated] `GetProtectedResourceMetadataFromID` and
`GetProtectedResourceMetadataFromHeader` in favor of more generic
`GetProtectedResourceMetadata`. They will be kept under the Go build tag
and removed one version of the SDK in the future.
2026-02-27 15:30:13 +01:00

280 lines
9.6 KiB
Go

// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// This file implements Protected Resource Metadata.
// See https://www.rfc-editor.org/rfc/rfc9728.html.
//go:build mcp_go_client_oauth
package oauthex
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"unicode"
"github.com/modelcontextprotocol/go-sdk/internal/util"
)
const defaultProtectedResourceMetadataURI = "/.well-known/oauth-protected-resource"
// GetProtectedResourceMetadataFromID issues a GET request to retrieve protected resource
// metadata from a resource server by its ID.
// The resource ID is an HTTPS URL, typically with a host:port and possibly a path.
// For example:
//
// https://example.com/server
//
// This function, following the spec (§3), inserts the default well-known path into the
// URL. In our example, the result would be
//
// https://example.com/.well-known/oauth-protected-resource/server
//
// It then retrieves the metadata at that location using the given client (or the
// default client if nil) and validates its resource field against resourceID.
//
// Deprecated: Use [GetProtectedResourceMetadata] instead. This function will be removed in v1.5.0.
func GetProtectedResourceMetadataFromID(ctx context.Context, resourceID string, c *http.Client) (_ *ProtectedResourceMetadata, err error) {
defer util.Wrapf(&err, "GetProtectedResourceMetadataFromID(%q)", resourceID)
u, err := url.Parse(resourceID)
if err != nil {
return nil, err
}
// Insert well-known URI into URL.
u.Path = path.Join(defaultProtectedResourceMetadataURI, u.Path)
return GetProtectedResourceMetadata(ctx, u.String(), resourceID, c)
}
// GetProtectedResourceMetadataFromHeader retrieves protected resource metadata
// using information in the given header, using the given client (or the default
// client if nil).
// It issues a GET request to a URL discovered by parsing the WWW-Authenticate headers in the given request.
// Per RFC 9728 section 3.3, it validates that the resource field of the resulting metadata
// matches the serverURL (the URL that the client used to make the original request to the resource server).
// If there is no metadata URL in the header, it returns nil, nil.
//
// Deprecated: Use [GetProtectedResourceMetadata] instead. This function will be removed in v1.5.0.
func GetProtectedResourceMetadataFromHeader(ctx context.Context, serverURL string, header http.Header, c *http.Client) (_ *ProtectedResourceMetadata, err error) {
headers := header[http.CanonicalHeaderKey("WWW-Authenticate")]
if len(headers) == 0 {
return nil, nil
}
cs, err := ParseWWWAuthenticate(headers)
if err != nil {
return nil, err
}
metadataURL := resourceMetadataURL(cs)
if metadataURL == "" {
return nil, nil
}
return GetProtectedResourceMetadata(ctx, metadataURL, serverURL, c)
}
// resourceMetadataURL returns a resource metadata URL from the given "WWW-Authenticate" header challenges,
// or the empty string if there is none.
func resourceMetadataURL(cs []Challenge) string {
for _, c := range cs {
if u := c.Params["resource_metadata"]; u != "" {
return u
}
}
return ""
}
// GetProtectedResourceMetadataFromID issues a GET request to retrieve protected resource
// metadata from a resource server.
// The metadataURL is typically a URL with a host:port and possibly a path.
// The resourceURL is the resource URI the metadataURL is for.
// The following checks are performed:
// - The metadataURL must use HTTPS or be a local address.
// - The resource field of the resulting metadata must match the resourceURL.
// - The authorization_servers field of the resulting metadata is checked for dangerous URL schemes.
func GetProtectedResourceMetadata(ctx context.Context, metadataURL, resourceURL string, c *http.Client) (_ *ProtectedResourceMetadata, err error) {
defer util.Wrapf(&err, "GetProtectedResourceMetadata(%q)", metadataURL)
u, err := url.Parse(metadataURL)
if err != nil {
return nil, err
}
// Only allow HTTP for local addresses (testing or development purposes).
if !util.IsLoopback(u.Host) && u.Scheme != "https" {
return nil, fmt.Errorf("metadataURL %q does not use HTTPS", metadataURL)
}
prm, err := getJSON[ProtectedResourceMetadata](ctx, c, metadataURL, 1<<20)
if err != nil {
return nil, err
}
// Validate the Resource field (see RFC 9728, section 3.3).
if prm.Resource != resourceURL {
return nil, fmt.Errorf("got metadata resource %q, want %q", prm.Resource, resourceURL)
}
// Validate the authorization server URLs to prevent XSS attacks (see #526).
for _, u := range prm.AuthorizationServers {
if err := checkURLScheme(u); err != nil {
return nil, err
}
}
return prm, nil
}
// ParseWWWAuthenticate parses a WWW-Authenticate header string.
// The header format is defined in RFC 9110, Section 11.6.1, and can contain
// one or more challenges, separated by commas.
// It returns a slice of challenges or an error if one of the headers is malformed.
func ParseWWWAuthenticate(headers []string) ([]Challenge, error) {
var challenges []Challenge
for _, h := range headers {
challengeStrings, err := splitChallenges(h)
if err != nil {
return nil, err
}
for _, cs := range challengeStrings {
if strings.TrimSpace(cs) == "" {
continue
}
challenge, err := parseSingleChallenge(cs)
if err != nil {
return nil, fmt.Errorf("failed to parse challenge %q: %w", cs, err)
}
challenges = append(challenges, challenge)
}
}
return challenges, nil
}
// splitChallenges splits a header value containing one or more challenges.
// It correctly handles commas within quoted strings and distinguishes between
// commas separating auth-params and commas separating challenges.
func splitChallenges(header string) ([]string, error) {
var challenges []string
inQuotes := false
start := 0
for i, r := range header {
if r == '"' {
if i > 0 && header[i-1] != '\\' {
inQuotes = !inQuotes
} else if i == 0 {
// A challenge begins with an auth-scheme, which is a token, which cannot contain
// a quote.
return nil, errors.New(`challenge begins with '"'`)
}
} else if r == ',' && !inQuotes {
// This is a potential challenge separator.
// A new challenge does not start with `key=value`.
// We check if the part after the comma looks like a parameter.
lookahead := strings.TrimSpace(header[i+1:])
eqPos := strings.Index(lookahead, "=")
isParam := false
if eqPos > 0 {
// Check if the part before '=' is a single token (no spaces).
token := lookahead[:eqPos]
if strings.IndexFunc(token, unicode.IsSpace) == -1 {
isParam = true
}
}
if !isParam {
// The part after the comma does not look like a parameter,
// so this comma separates challenges.
challenges = append(challenges, header[start:i])
start = i + 1
}
}
}
// Add the last (or only) challenge to the list.
challenges = append(challenges, header[start:])
return challenges, nil
}
// parseSingleChallenge parses a string containing exactly one challenge.
// challenge = auth-scheme [ 1*SP ( token68 / #auth-param ) ]
func parseSingleChallenge(s string) (Challenge, error) {
s = strings.TrimSpace(s)
if s == "" {
return Challenge{}, errors.New("empty challenge string")
}
scheme, paramsStr, found := strings.Cut(s, " ")
c := Challenge{Scheme: strings.ToLower(scheme)}
if !found {
return c, nil
}
params := make(map[string]string)
// Parse the key-value parameters.
for paramsStr != "" {
// Find the end of the parameter key.
keyEnd := strings.Index(paramsStr, "=")
if keyEnd <= 0 {
return Challenge{}, fmt.Errorf("malformed auth parameter: expected key=value, but got %q", paramsStr)
}
key := strings.TrimSpace(paramsStr[:keyEnd])
// Move the string past the key and the '='.
paramsStr = strings.TrimSpace(paramsStr[keyEnd+1:])
var value string
if strings.HasPrefix(paramsStr, "\"") {
// The value is a quoted string.
paramsStr = paramsStr[1:] // Consume the opening quote.
var valBuilder strings.Builder
i := 0
for ; i < len(paramsStr); i++ {
// Handle escaped characters.
if paramsStr[i] == '\\' && i+1 < len(paramsStr) {
valBuilder.WriteByte(paramsStr[i+1])
i++ // We've consumed two characters.
} else if paramsStr[i] == '"' {
// End of the quoted string.
break
} else {
valBuilder.WriteByte(paramsStr[i])
}
}
// A quoted string must be terminated.
if i == len(paramsStr) {
return Challenge{}, fmt.Errorf("unterminated quoted string in auth parameter")
}
value = valBuilder.String()
// Move the string past the value and the closing quote.
paramsStr = strings.TrimSpace(paramsStr[i+1:])
} else {
// The value is a token. It ends at the next comma or the end of the string.
commaPos := strings.Index(paramsStr, ",")
if commaPos == -1 {
value = paramsStr
paramsStr = ""
} else {
value = strings.TrimSpace(paramsStr[:commaPos])
paramsStr = strings.TrimSpace(paramsStr[commaPos:]) // Keep comma for next check
}
}
if value == "" {
return Challenge{}, fmt.Errorf("no value for auth param %q", key)
}
// Per RFC 9110, parameter keys are case-insensitive.
params[strings.ToLower(key)] = value
// If there is a comma, consume it and continue to the next parameter.
if strings.HasPrefix(paramsStr, ",") {
paramsStr = strings.TrimSpace(paramsStr[1:])
} else if paramsStr != "" {
// If there's content but it's not a new parameter, the format is wrong.
return Challenge{}, fmt.Errorf("malformed auth parameter: expected comma after value, but got %q", paramsStr)
}
}
// Per RFC 9110, the scheme is case-insensitive.
return Challenge{Scheme: strings.ToLower(scheme), Params: params}, nil
}