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.
This commit is contained in:
parent
4e8b6ca17d
commit
c9317fb5b7
8 changed files with 2743 additions and 434 deletions
|
|
@ -14,6 +14,9 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/internal/util"
|
||||
)
|
||||
|
||||
// AuthServerMeta represents the metadata for an OAuth 2.0 authorization server,
|
||||
|
|
@ -28,8 +31,6 @@ import (
|
|||
//
|
||||
// [RFC 8414]: https://tools.ietf.org/html/rfc8414)
|
||||
type AuthServerMeta struct {
|
||||
// GENERATED BY GEMINI 2.5.
|
||||
|
||||
// Issuer is the REQUIRED URL identifying the authorization server.
|
||||
Issuer string `json:"issuer"`
|
||||
|
||||
|
|
@ -113,51 +114,61 @@ type AuthServerMeta struct {
|
|||
// CodeChallengeMethodsSupported is a RECOMMENDED JSON array of strings containing a list of
|
||||
// PKCE code challenge methods supported by this authorization server.
|
||||
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
|
||||
}
|
||||
|
||||
var wellKnownPaths = []string{
|
||||
"/.well-known/oauth-authorization-server",
|
||||
"/.well-known/openid-configuration",
|
||||
// ClientIDMetadataDocumentSupported is a boolean indicating whether the authorization server
|
||||
// supports client ID metadata documents.
|
||||
ClientIDMetadataDocumentSupported bool `json:"client_id_metadata_document_supported,omitempty"`
|
||||
}
|
||||
|
||||
// GetAuthServerMeta issues a GET request to retrieve authorization server metadata
|
||||
// from an OAuth authorization server with the given issuerURL.
|
||||
// from an OAuth authorization server with the given metadataURL.
|
||||
//
|
||||
// It follows [RFC 8414]:
|
||||
// - The well-known paths specified there are inserted into the URL's path, one at time.
|
||||
// The first to succeed is used.
|
||||
// - The Issuer field is checked against issuerURL.
|
||||
// - The metadataURL must use HTTPS or be a local address.
|
||||
// - The Issuer field is checked against metadataURL.Issuer.
|
||||
//
|
||||
// It also verifies that the authorization server supports PKCE and that the URLs
|
||||
// in the metadata don't use dangerous schemes.
|
||||
//
|
||||
// It returns an error if the request fails with a non-4xx status code or the fetched
|
||||
// metadata doesn't pass security validations.
|
||||
// It returns nil if the request fails with a 4xx status code.
|
||||
//
|
||||
// [RFC 8414]: https://tools.ietf.org/html/rfc8414
|
||||
func GetAuthServerMeta(ctx context.Context, issuerURL string, c *http.Client) (*AuthServerMeta, error) {
|
||||
var errs []error
|
||||
for _, p := range wellKnownPaths {
|
||||
u, err := prependToPath(issuerURL, p)
|
||||
if err != nil {
|
||||
// issuerURL is bad; no point in continuing.
|
||||
return nil, err
|
||||
}
|
||||
asm, err := getJSON[AuthServerMeta](ctx, c, u, 1<<20)
|
||||
if err == nil {
|
||||
if asm.Issuer != issuerURL { // section 3.3
|
||||
// Security violation; don't keep trying.
|
||||
return nil, fmt.Errorf("metadata issuer %q does not match issuer URL %q", asm.Issuer, issuerURL)
|
||||
}
|
||||
|
||||
if len(asm.CodeChallengeMethodsSupported) == 0 {
|
||||
return nil, fmt.Errorf("authorization server at %s does not implement PKCE", issuerURL)
|
||||
}
|
||||
|
||||
// Validate endpoint URLs to prevent XSS attacks (see #526).
|
||||
if err := validateAuthServerMetaURLs(asm); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return asm, nil
|
||||
}
|
||||
errs = append(errs, err)
|
||||
func GetAuthServerMeta(ctx context.Context, metadataURL, issuer string, c *http.Client) (*AuthServerMeta, error) {
|
||||
u, err := url.Parse(metadataURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get auth server metadata from %q: %w", issuerURL, errors.Join(errs...))
|
||||
// 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)
|
||||
}
|
||||
asm, err := getJSON[AuthServerMeta](ctx, c, metadataURL, 1<<20)
|
||||
if err != nil {
|
||||
var httpErr *httpStatusError
|
||||
if errors.As(err, &httpErr) {
|
||||
if 400 <= httpErr.StatusCode && httpErr.StatusCode < 500 {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("%v", err) // Do not expose error types.
|
||||
}
|
||||
if asm.Issuer != issuer {
|
||||
// Validate the Issuer field (see RFC 8414, section 3.3).
|
||||
return nil, fmt.Errorf("metadata issuer %q does not match issuer URL %q", asm.Issuer, issuer)
|
||||
}
|
||||
|
||||
if len(asm.CodeChallengeMethodsSupported) == 0 {
|
||||
return nil, fmt.Errorf("authorization server at %s does not implement PKCE", issuer)
|
||||
}
|
||||
|
||||
// Validate endpoint URLs to prevent XSS attacks (see #526).
|
||||
if err := validateAuthServerMetaURLs(asm); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return asm, nil
|
||||
}
|
||||
|
||||
// validateAuthServerMetaURLs validates all URL fields in AuthServerMeta
|
||||
|
|
|
|||
|
|
@ -86,6 +86,7 @@ func TestGetAuthServerMetaPKCESupport(t *testing.T) {
|
|||
// The fake server sets issuer to https://localhost:<port>, so compute that issuer.
|
||||
u, _ := url.Parse(ts.URL)
|
||||
issuer := "https://localhost:" + u.Port()
|
||||
metadataURL := issuer + "/.well-known/oauth-authorization-server"
|
||||
|
||||
// The fake server presents a cert for example.com; set ServerName accordingly.
|
||||
httpClient := ts.Client()
|
||||
|
|
@ -95,7 +96,7 @@ func TestGetAuthServerMetaPKCESupport(t *testing.T) {
|
|||
httpClient.Transport = clone
|
||||
}
|
||||
|
||||
meta, err := GetAuthServerMeta(ctx, issuer, httpClient)
|
||||
meta, err := GetAuthServerMeta(ctx, metadataURL, issuer, httpClient)
|
||||
if tt.wantError != "" {
|
||||
if err == nil {
|
||||
t.Fatal("wanted error but got none")
|
||||
|
|
|
|||
|
|
@ -19,21 +19,12 @@ import (
|
|||
"strings"
|
||||
)
|
||||
|
||||
// prependToPath prepends pre to the path of urlStr.
|
||||
// When pre is the well-known path, this is the algorithm specified in both RFC 9728
|
||||
// section 3.1 and RFC 8414 section 3.1.
|
||||
func prependToPath(urlStr, pre string) (string, error) {
|
||||
u, err := url.Parse(urlStr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p := "/" + strings.Trim(pre, "/")
|
||||
if u.Path != "" {
|
||||
p += "/"
|
||||
}
|
||||
type httpStatusError struct {
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
u.Path = p + strings.TrimLeft(u.Path, "/")
|
||||
return u.String(), nil
|
||||
func (e *httpStatusError) Error() string {
|
||||
return fmt.Sprintf("bad status %d", e.StatusCode)
|
||||
}
|
||||
|
||||
// getJSON retrieves JSON and unmarshals JSON from the URL, as specified in both
|
||||
|
|
@ -53,11 +44,9 @@ func getJSON[T any](ctx context.Context, c *http.Client, url string, limit int64
|
|||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
// Specs require a 200.
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("bad status %s", res.Status)
|
||||
return nil, &httpStatusError{StatusCode: res.StatusCode}
|
||||
}
|
||||
// Specs require application/json.
|
||||
ct := res.Header.Get("Content-Type")
|
||||
mediaType, _, err := mime.ParseMediaType(ct)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
|
|
|
|||
|
|
@ -82,13 +82,13 @@ func TestParseSingleChallenge(t *testing.T) {
|
|||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want challenge
|
||||
want Challenge
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "scheme only",
|
||||
input: "Basic",
|
||||
want: challenge{
|
||||
want: Challenge{
|
||||
Scheme: "basic",
|
||||
},
|
||||
wantErr: false,
|
||||
|
|
@ -96,7 +96,7 @@ func TestParseSingleChallenge(t *testing.T) {
|
|||
{
|
||||
name: "scheme with one quoted param",
|
||||
input: `Bearer realm="example.com"`,
|
||||
want: challenge{
|
||||
want: Challenge{
|
||||
Scheme: "bearer",
|
||||
Params: map[string]string{"realm": "example.com"},
|
||||
},
|
||||
|
|
@ -105,7 +105,7 @@ func TestParseSingleChallenge(t *testing.T) {
|
|||
{
|
||||
name: "scheme with one unquoted param",
|
||||
input: `Bearer realm=example.com`,
|
||||
want: challenge{
|
||||
want: Challenge{
|
||||
Scheme: "bearer",
|
||||
Params: map[string]string{"realm": "example.com"},
|
||||
},
|
||||
|
|
@ -114,7 +114,7 @@ func TestParseSingleChallenge(t *testing.T) {
|
|||
{
|
||||
name: "scheme with multiple params",
|
||||
input: `Bearer realm="example", error="invalid_token", error_description="The token expired"`,
|
||||
want: challenge{
|
||||
want: Challenge{
|
||||
Scheme: "bearer",
|
||||
Params: map[string]string{
|
||||
"realm": "example",
|
||||
|
|
@ -127,7 +127,7 @@ func TestParseSingleChallenge(t *testing.T) {
|
|||
{
|
||||
name: "scheme with multiple unquoted params",
|
||||
input: `Bearer realm=example, error=invalid_token, error_description=The token expired`,
|
||||
want: challenge{
|
||||
want: Challenge{
|
||||
Scheme: "bearer",
|
||||
Params: map[string]string{
|
||||
"realm": "example",
|
||||
|
|
@ -140,7 +140,7 @@ func TestParseSingleChallenge(t *testing.T) {
|
|||
{
|
||||
name: "case-insensitive scheme and keys",
|
||||
input: `BEARER ReAlM="example"`,
|
||||
want: challenge{
|
||||
want: Challenge{
|
||||
Scheme: "bearer",
|
||||
Params: map[string]string{"realm": "example"},
|
||||
},
|
||||
|
|
@ -149,7 +149,7 @@ func TestParseSingleChallenge(t *testing.T) {
|
|||
{
|
||||
name: "param with escaped quote",
|
||||
input: `Bearer realm="example \"foo\" bar"`,
|
||||
want: challenge{
|
||||
want: Challenge{
|
||||
Scheme: "bearer",
|
||||
Params: map[string]string{"realm": `example "foo" bar`},
|
||||
},
|
||||
|
|
@ -158,7 +158,7 @@ func TestParseSingleChallenge(t *testing.T) {
|
|||
{
|
||||
name: "param without quotes (token)",
|
||||
input: "Bearer realm=example.com",
|
||||
want: challenge{
|
||||
want: Challenge{
|
||||
Scheme: "bearer",
|
||||
Params: map[string]string{"realm": "example.com"},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -4,89 +4,3 @@
|
|||
|
||||
// Package oauthex implements extensions to OAuth2.
|
||||
package oauthex
|
||||
|
||||
// ProtectedResourceMetadata is the metadata for an OAuth 2.0 protected resource,
|
||||
// as defined in section 2 of https://www.rfc-editor.org/rfc/rfc9728.html.
|
||||
//
|
||||
// The following features are not supported:
|
||||
// - additional keys (§2, last sentence)
|
||||
// - human-readable metadata (§2.1)
|
||||
// - signed metadata (§2.2)
|
||||
type ProtectedResourceMetadata struct {
|
||||
// GENERATED BY GEMINI 2.5.
|
||||
|
||||
// Resource (resource) is the protected resource's resource identifier.
|
||||
// Required.
|
||||
Resource string `json:"resource"`
|
||||
|
||||
// AuthorizationServers (authorization_servers) is an optional slice containing a list of
|
||||
// OAuth authorization server issuer identifiers (as defined in RFC 8414) that can be
|
||||
// used with this protected resource.
|
||||
AuthorizationServers []string `json:"authorization_servers,omitempty"`
|
||||
|
||||
// JWKSURI (jwks_uri) is an optional URL of the protected resource's JSON Web Key (JWK) Set
|
||||
// document. This contains public keys belonging to the protected resource, such as
|
||||
// signing key(s) that the resource server uses to sign resource responses.
|
||||
JWKSURI string `json:"jwks_uri,omitempty"`
|
||||
|
||||
// ScopesSupported (scopes_supported) is a recommended slice containing a list of scope
|
||||
// values (as defined in RFC 6749) used in authorization requests to request access
|
||||
// to this protected resource.
|
||||
ScopesSupported []string `json:"scopes_supported,omitempty"`
|
||||
|
||||
// BearerMethodsSupported (bearer_methods_supported) is an optional slice containing
|
||||
// a list of the supported methods of sending an OAuth 2.0 bearer token to the
|
||||
// protected resource. Defined values are "header", "body", and "query".
|
||||
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
|
||||
|
||||
// ResourceSigningAlgValuesSupported (resource_signing_alg_values_supported) is an optional
|
||||
// slice of JWS signing algorithms (alg values) supported by the protected
|
||||
// resource for signing resource responses.
|
||||
ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
|
||||
|
||||
// ResourceName (resource_name) is a human-readable name of the protected resource
|
||||
// intended for display to the end user. It is RECOMMENDED that this field be included.
|
||||
// This value may be internationalized.
|
||||
ResourceName string `json:"resource_name,omitempty"`
|
||||
|
||||
// ResourceDocumentation (resource_documentation) is an optional URL of a page containing
|
||||
// human-readable information for developers using the protected resource.
|
||||
// This value may be internationalized.
|
||||
ResourceDocumentation string `json:"resource_documentation,omitempty"`
|
||||
|
||||
// ResourcePolicyURI (resource_policy_uri) is an optional URL of a page containing
|
||||
// human-readable policy information on how a client can use the data provided.
|
||||
// This value may be internationalized.
|
||||
ResourcePolicyURI string `json:"resource_policy_uri,omitempty"`
|
||||
|
||||
// ResourceTOSURI (resource_tos_uri) is an optional URL of a page containing the protected
|
||||
// resource's human-readable terms of service. This value may be internationalized.
|
||||
ResourceTOSURI string `json:"resource_tos_uri,omitempty"`
|
||||
|
||||
// TLSClientCertificateBoundAccessTokens (tls_client_certificate_bound_access_tokens) is an
|
||||
// optional boolean indicating support for mutual-TLS client certificate-bound
|
||||
// access tokens (RFC 8705). Defaults to false if omitted.
|
||||
TLSClientCertificateBoundAccessTokens bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`
|
||||
|
||||
// AuthorizationDetailsTypesSupported (authorization_details_types_supported) is an optional
|
||||
// slice of 'type' values supported by the resource server for the
|
||||
// 'authorization_details' parameter (RFC 9396).
|
||||
AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"`
|
||||
|
||||
// DPOPSigningAlgValuesSupported (dpop_signing_alg_values_supported) is an optional
|
||||
// slice of JWS signing algorithms supported by the resource server for validating
|
||||
// DPoP proof JWTs (RFC 9449).
|
||||
DPOPSigningAlgValuesSupported []string `json:"dpop_signing_alg_values_supported,omitempty"`
|
||||
|
||||
// DPOPBoundAccessTokensRequired (dpop_bound_access_tokens_required) is an optional boolean
|
||||
// specifying whether the protected resource always requires the use of DPoP-bound
|
||||
// access tokens (RFC 9449). Defaults to false if omitted.
|
||||
DPOPBoundAccessTokensRequired bool `json:"dpop_bound_access_tokens_required,omitempty"`
|
||||
|
||||
// SignedMetadata (signed_metadata) is an optional JWT containing metadata parameters
|
||||
// about the protected resource as claims. If present, these values take precedence
|
||||
// over values conveyed in plain JSON.
|
||||
// TODO:implement.
|
||||
// Note that §2.2 says it's okay to ignore this.
|
||||
// SignedMetadata string `json:"signed_metadata,omitempty"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@ const defaultProtectedResourceMetadataURI = "/.well-known/oauth-protected-resour
|
|||
//
|
||||
// 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)
|
||||
|
||||
|
|
@ -47,7 +49,7 @@ func GetProtectedResourceMetadataFromID(ctx context.Context, resourceID string,
|
|||
}
|
||||
// Insert well-known URI into URL.
|
||||
u.Path = path.Join(defaultProtectedResourceMetadataURI, u.Path)
|
||||
return getPRM(ctx, u.String(), c, resourceID)
|
||||
return GetProtectedResourceMetadata(ctx, u.String(), resourceID, c)
|
||||
}
|
||||
|
||||
// GetProtectedResourceMetadataFromHeader retrieves protected resource metadata
|
||||
|
|
@ -57,8 +59,9 @@ func GetProtectedResourceMetadataFromID(ctx context.Context, resourceID string,
|
|||
// 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) {
|
||||
defer util.Wrapf(&err, "GetProtectedResourceMetadataFromHeader")
|
||||
headers := header[http.CanonicalHeaderKey("WWW-Authenticate")]
|
||||
if len(headers) == 0 {
|
||||
return nil, nil
|
||||
|
|
@ -67,26 +70,49 @@ func GetProtectedResourceMetadataFromHeader(ctx context.Context, serverURL strin
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metadataURL := ResourceMetadataURL(cs)
|
||||
metadataURL := resourceMetadataURL(cs)
|
||||
if metadataURL == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return getPRM(ctx, metadataURL, c, serverURL)
|
||||
return GetProtectedResourceMetadata(ctx, metadataURL, serverURL, c)
|
||||
}
|
||||
|
||||
// getPRM makes a GET request to the given URL, and validates the response.
|
||||
// As part of the validation, it compares the returned resource field to wantResource.
|
||||
func getPRM(ctx context.Context, purl string, c *http.Client, wantResource string) (*ProtectedResourceMetadata, error) {
|
||||
if !strings.HasPrefix(strings.ToUpper(purl), "HTTPS://") {
|
||||
return nil, fmt.Errorf("resource URL %q does not use HTTPS", purl)
|
||||
// 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
|
||||
}
|
||||
}
|
||||
prm, err := getJSON[ProtectedResourceMetadata](ctx, c, purl, 1<<20)
|
||||
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 != wantResource {
|
||||
return nil, fmt.Errorf("got metadata resource %q, want %q", prm.Resource, wantResource)
|
||||
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 {
|
||||
|
|
@ -97,37 +123,12 @@ func getPRM(ctx context.Context, purl string, c *http.Client, wantResource strin
|
|||
return prm, nil
|
||||
}
|
||||
|
||||
// challenge represents a single authentication challenge from a WWW-Authenticate header.
|
||||
// As per RFC 9110, Section 11.6.1, a challenge consists of a scheme and optional parameters.
|
||||
type challenge struct {
|
||||
// GENERATED BY GEMINI 2.5.
|
||||
//
|
||||
// Scheme is the authentication scheme (e.g., "Bearer", "Basic").
|
||||
// It is case-insensitive. A parsed value will always be lower-case.
|
||||
Scheme string
|
||||
// Params is a map of authentication parameters.
|
||||
// Keys are case-insensitive. Parsed keys are always lower-case.
|
||||
Params map[string]string
|
||||
}
|
||||
|
||||
// ResourceMetadataURL returns a resource metadata URL from the given 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 ""
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// GENERATED BY GEMINI 2.5 (human-tweaked)
|
||||
var challenges []challenge
|
||||
func ParseWWWAuthenticate(headers []string) ([]Challenge, error) {
|
||||
var challenges []Challenge
|
||||
for _, h := range headers {
|
||||
challengeStrings, err := splitChallenges(h)
|
||||
if err != nil {
|
||||
|
|
@ -151,7 +152,6 @@ func ParseWWWAuthenticate(headers []string) ([]challenge, error) {
|
|||
// It correctly handles commas within quoted strings and distinguishes between
|
||||
// commas separating auth-params and commas separating challenges.
|
||||
func splitChallenges(header string) ([]string, error) {
|
||||
// GENERATED BY GEMINI 2.5.
|
||||
var challenges []string
|
||||
inQuotes := false
|
||||
start := 0
|
||||
|
|
@ -195,15 +195,14 @@ func splitChallenges(header string) ([]string, error) {
|
|||
|
||||
// parseSingleChallenge parses a string containing exactly one challenge.
|
||||
// challenge = auth-scheme [ 1*SP ( token68 / #auth-param ) ]
|
||||
func parseSingleChallenge(s string) (challenge, error) {
|
||||
// GENERATED BY GEMINI 2.5, human-tweaked.
|
||||
func parseSingleChallenge(s string) (Challenge, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return challenge{}, errors.New("empty challenge string")
|
||||
return Challenge{}, errors.New("empty challenge string")
|
||||
}
|
||||
|
||||
scheme, paramsStr, found := strings.Cut(s, " ")
|
||||
c := challenge{Scheme: strings.ToLower(scheme)}
|
||||
c := Challenge{Scheme: strings.ToLower(scheme)}
|
||||
if !found {
|
||||
return c, nil
|
||||
}
|
||||
|
|
@ -215,7 +214,7 @@ func parseSingleChallenge(s string) (challenge, error) {
|
|||
// 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)
|
||||
return Challenge{}, fmt.Errorf("malformed auth parameter: expected key=value, but got %q", paramsStr)
|
||||
}
|
||||
key := strings.TrimSpace(paramsStr[:keyEnd])
|
||||
|
||||
|
|
@ -243,7 +242,7 @@ func parseSingleChallenge(s string) (challenge, error) {
|
|||
|
||||
// A quoted string must be terminated.
|
||||
if i == len(paramsStr) {
|
||||
return challenge{}, fmt.Errorf("unterminated quoted string in auth parameter")
|
||||
return Challenge{}, fmt.Errorf("unterminated quoted string in auth parameter")
|
||||
}
|
||||
|
||||
value = valBuilder.String()
|
||||
|
|
@ -261,7 +260,7 @@ func parseSingleChallenge(s string) (challenge, error) {
|
|||
}
|
||||
}
|
||||
if value == "" {
|
||||
return challenge{}, fmt.Errorf("no value for auth param %q", key)
|
||||
return Challenge{}, fmt.Errorf("no value for auth param %q", key)
|
||||
}
|
||||
|
||||
// Per RFC 9110, parameter keys are case-insensitive.
|
||||
|
|
@ -272,10 +271,10 @@ func parseSingleChallenge(s string) (challenge, error) {
|
|||
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)
|
||||
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
|
||||
return Challenge{Scheme: strings.ToLower(scheme), Params: params}, nil
|
||||
}
|
||||
|
|
|
|||
105
oauthex/resource_meta_public.go
Normal file
105
oauthex/resource_meta_public.go
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
// 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.
|
||||
|
||||
// This is a temporary file to expose the required objects to the main package.
|
||||
|
||||
package oauthex
|
||||
|
||||
// ProtectedResourceMetadata is the metadata for an OAuth 2.0 protected resource,
|
||||
// as defined in section 2 of https://www.rfc-editor.org/rfc/rfc9728.html.
|
||||
//
|
||||
// The following features are not supported:
|
||||
// - additional keys (§2, last sentence)
|
||||
// - human-readable metadata (§2.1)
|
||||
// - signed metadata (§2.2)
|
||||
type ProtectedResourceMetadata struct {
|
||||
// Resource (resource) is the protected resource's resource identifier.
|
||||
// Required.
|
||||
Resource string `json:"resource"`
|
||||
|
||||
// AuthorizationServers (authorization_servers) is an optional slice containing a list of
|
||||
// OAuth authorization server issuer identifiers (as defined in RFC 8414) that can be
|
||||
// used with this protected resource.
|
||||
AuthorizationServers []string `json:"authorization_servers,omitempty"`
|
||||
|
||||
// JWKSURI (jwks_uri) is an optional URL of the protected resource's JSON Web Key (JWK) Set
|
||||
// document. This contains public keys belonging to the protected resource, such as
|
||||
// signing key(s) that the resource server uses to sign resource responses.
|
||||
JWKSURI string `json:"jwks_uri,omitempty"`
|
||||
|
||||
// ScopesSupported (scopes_supported) is a recommended slice containing a list of scope
|
||||
// values (as defined in RFC 6749) used in authorization requests to request access
|
||||
// to this protected resource.
|
||||
ScopesSupported []string `json:"scopes_supported,omitempty"`
|
||||
|
||||
// BearerMethodsSupported (bearer_methods_supported) is an optional slice containing
|
||||
// a list of the supported methods of sending an OAuth 2.0 bearer token to the
|
||||
// protected resource. Defined values are "header", "body", and "query".
|
||||
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
|
||||
|
||||
// ResourceSigningAlgValuesSupported (resource_signing_alg_values_supported) is an optional
|
||||
// slice of JWS signing algorithms (alg values) supported by the protected
|
||||
// resource for signing resource responses.
|
||||
ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`
|
||||
|
||||
// ResourceName (resource_name) is a human-readable name of the protected resource
|
||||
// intended for display to the end user. It is RECOMMENDED that this field be included.
|
||||
// This value may be internationalized.
|
||||
ResourceName string `json:"resource_name,omitempty"`
|
||||
|
||||
// ResourceDocumentation (resource_documentation) is an optional URL of a page containing
|
||||
// human-readable information for developers using the protected resource.
|
||||
// This value may be internationalized.
|
||||
ResourceDocumentation string `json:"resource_documentation,omitempty"`
|
||||
|
||||
// ResourcePolicyURI (resource_policy_uri) is an optional URL of a page containing
|
||||
// human-readable policy information on how a client can use the data provided.
|
||||
// This value may be internationalized.
|
||||
ResourcePolicyURI string `json:"resource_policy_uri,omitempty"`
|
||||
|
||||
// ResourceTOSURI (resource_tos_uri) is an optional URL of a page containing the protected
|
||||
// resource's human-readable terms of service. This value may be internationalized.
|
||||
ResourceTOSURI string `json:"resource_tos_uri,omitempty"`
|
||||
|
||||
// TLSClientCertificateBoundAccessTokens (tls_client_certificate_bound_access_tokens) is an
|
||||
// optional boolean indicating support for mutual-TLS client certificate-bound
|
||||
// access tokens (RFC 8705). Defaults to false if omitted.
|
||||
TLSClientCertificateBoundAccessTokens bool `json:"tls_client_certificate_bound_access_tokens,omitempty"`
|
||||
|
||||
// AuthorizationDetailsTypesSupported (authorization_details_types_supported) is an optional
|
||||
// slice of 'type' values supported by the resource server for the
|
||||
// 'authorization_details' parameter (RFC 9396).
|
||||
AuthorizationDetailsTypesSupported []string `json:"authorization_details_types_supported,omitempty"`
|
||||
|
||||
// DPOPSigningAlgValuesSupported (dpop_signing_alg_values_supported) is an optional
|
||||
// slice of JWS signing algorithms supported by the resource server for validating
|
||||
// DPoP proof JWTs (RFC 9449).
|
||||
DPOPSigningAlgValuesSupported []string `json:"dpop_signing_alg_values_supported,omitempty"`
|
||||
|
||||
// DPOPBoundAccessTokensRequired (dpop_bound_access_tokens_required) is an optional boolean
|
||||
// specifying whether the protected resource always requires the use of DPoP-bound
|
||||
// access tokens (RFC 9449). Defaults to false if omitted.
|
||||
DPOPBoundAccessTokensRequired bool `json:"dpop_bound_access_tokens_required,omitempty"`
|
||||
|
||||
// SignedMetadata (signed_metadata) is an optional JWT containing metadata parameters
|
||||
// about the protected resource as claims. If present, these values take precedence
|
||||
// over values conveyed in plain JSON.
|
||||
// TODO:implement.
|
||||
// Note that §2.2 says it's okay to ignore this.
|
||||
// SignedMetadata string `json:"signed_metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Challenge represents a single authentication challenge from a WWW-Authenticate header.
|
||||
// As per RFC 9110, Section 11.6.1, a challenge consists of a scheme and optional parameters.
|
||||
type Challenge struct {
|
||||
// Scheme is the authentication scheme (e.g., "Bearer", "Basic").
|
||||
// It is case-insensitive. A parsed value will always be lower-case.
|
||||
Scheme string
|
||||
// Params is a map of authentication parameters.
|
||||
// Keys are case-insensitive. Parsed keys are always lower-case.
|
||||
Params map[string]string
|
||||
}
|
||||
|
|
@ -226,7 +226,9 @@ func TestGetAuthServerMetaRejectsDangerousURLs(t *testing.T) {
|
|||
defer server.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
_, err := GetAuthServerMeta(ctx, server.URL, server.Client())
|
||||
issuer := server.URL
|
||||
metadataURL := issuer
|
||||
_, err := GetAuthServerMeta(ctx, metadataURL, issuer, server.Client())
|
||||
if err == nil {
|
||||
t.Fatal("GetAuthServerMeta(): got nil error, want error")
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue