fix(go.sum): update ResolveSpec dependency to v1.0.87
CI / build-and-test (push) Failing after 1s
Release / release (push) Failing after 19m26s

This commit is contained in:
Hein
2026-06-23 13:17:16 +02:00
parent 0227912325
commit 1adf50e3db
2436 changed files with 1078758 additions and 114 deletions
+210
View File
@@ -0,0 +1,210 @@
// 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 Authorization Server Metadata.
// See https://www.rfc-editor.org/rfc/rfc8414.html.
//go:build mcp_go_client_oauth
package oauthex
import (
"context"
"errors"
"fmt"
"net/http"
)
// AuthServerMeta represents the metadata for an OAuth 2.0 authorization server,
// as defined in [RFC 8414].
//
// Not supported:
// - signed metadata
//
// Note: URL fields in this struct are validated by validateAuthServerMetaURLs to
// prevent XSS attacks. If you add a new URL field, you must also add it to that
// function.
//
// [RFC 8414]: https://tools.ietf.org/html/rfc8414)
type AuthServerMeta struct {
// Issuer is the REQUIRED URL identifying the authorization server.
Issuer string `json:"issuer"`
// AuthorizationEndpoint is the REQUIRED URL of the server's OAuth 2.0 authorization endpoint.
AuthorizationEndpoint string `json:"authorization_endpoint"`
// TokenEndpoint is the REQUIRED URL of the server's OAuth 2.0 token endpoint.
TokenEndpoint string `json:"token_endpoint"`
// JWKSURI is the REQUIRED URL of the server's JSON Web Key Set [JWK] document.
JWKSURI string `json:"jwks_uri"`
// RegistrationEndpoint is the RECOMMENDED URL of the server's OAuth 2.0 Dynamic Client Registration endpoint.
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
// ScopesSupported is a RECOMMENDED JSON array of strings containing a list of the OAuth 2.0
// "scope" values that this server supports.
ScopesSupported []string `json:"scopes_supported,omitempty"`
// ResponseTypesSupported is a REQUIRED JSON array of strings containing a list of the OAuth 2.0
// "response_type" values that this server supports.
ResponseTypesSupported []string `json:"response_types_supported"`
// ResponseModesSupported is a RECOMMENDED JSON array of strings containing a list of the OAuth 2.0
// "response_mode" values that this server supports.
ResponseModesSupported []string `json:"response_modes_supported,omitempty"`
// GrantTypesSupported is a RECOMMENDED JSON array of strings containing a list of the OAuth 2.0
// grant type values that this server supports.
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
// TokenEndpointAuthMethodsSupported is a RECOMMENDED JSON array of strings containing a list of
// client authentication methods supported by this token endpoint.
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
// TokenEndpointAuthSigningAlgValuesSupported is a RECOMMENDED JSON array of strings containing
// a list of the JWS signing algorithms ("alg" values) supported by the token endpoint for
// the signature on the JWT used to authenticate the client.
TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`
// ServiceDocumentation is a RECOMMENDED URL of a page containing human-readable documentation
// for the service.
ServiceDocumentation string `json:"service_documentation,omitempty"`
// UILocalesSupported is a RECOMMENDED JSON array of strings representing supported
// BCP47 [RFC5646] language tag values for display in the user interface.
UILocalesSupported []string `json:"ui_locales_supported,omitempty"`
// OpPolicyURI is a RECOMMENDED URL that the server provides to the person registering
// the client to read about the server's operator policies.
OpPolicyURI string `json:"op_policy_uri,omitempty"`
// OpTOSURI is a RECOMMENDED URL that the server provides to the person registering the
// client to read about the server's terms of service.
OpTOSURI string `json:"op_tos_uri,omitempty"`
// RevocationEndpoint is a RECOMMENDED URL of the server's OAuth 2.0 revocation endpoint.
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
// RevocationEndpointAuthMethodsSupported is a RECOMMENDED JSON array of strings containing
// a list of client authentication methods supported by this revocation endpoint.
RevocationEndpointAuthMethodsSupported []string `json:"revocation_endpoint_auth_methods_supported,omitempty"`
// RevocationEndpointAuthSigningAlgValuesSupported is a RECOMMENDED JSON array of strings
// containing a list of the JWS signing algorithms ("alg" values) supported by the revocation
// endpoint for the signature on the JWT used to authenticate the client.
RevocationEndpointAuthSigningAlgValuesSupported []string `json:"revocation_endpoint_auth_signing_alg_values_supported,omitempty"`
// IntrospectionEndpoint is a RECOMMENDED URL of the server's OAuth 2.0 introspection endpoint.
IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`
// IntrospectionEndpointAuthMethodsSupported is a RECOMMENDED JSON array of strings containing
// a list of client authentication methods supported by this introspection endpoint.
IntrospectionEndpointAuthMethodsSupported []string `json:"introspection_endpoint_auth_methods_supported,omitempty"`
// IntrospectionEndpointAuthSigningAlgValuesSupported is a RECOMMENDED JSON array of strings
// containing a list of the JWS signing algorithms ("alg" values) supported by the introspection
// endpoint for the signature on the JWT used to authenticate the client.
IntrospectionEndpointAuthSigningAlgValuesSupported []string `json:"introspection_endpoint_auth_signing_alg_values_supported,omitempty"`
// 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"`
// 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 metadataURL.
//
// It follows [RFC 8414]:
// - 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, metadataURL, issuer string, c *http.Client) (*AuthServerMeta, error) {
// Only allow HTTP for local addresses (testing or development purposes).
if err := checkHTTPSOrLoopback(metadataURL); err != nil {
return nil, fmt.Errorf("metadataURL: %v", err)
}
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
// to ensure they don't use dangerous schemes that could enable XSS attacks.
// It also validates that URLs likely to be called by the client use
// HTTPS or are loopback addresses.
func validateAuthServerMetaURLs(asm *AuthServerMeta) error {
urls := []struct {
name string
value string
}{
{"authorization_endpoint", asm.AuthorizationEndpoint},
{"token_endpoint", asm.TokenEndpoint},
{"jwks_uri", asm.JWKSURI},
{"registration_endpoint", asm.RegistrationEndpoint},
{"service_documentation", asm.ServiceDocumentation},
{"op_policy_uri", asm.OpPolicyURI},
{"op_tos_uri", asm.OpTOSURI},
{"revocation_endpoint", asm.RevocationEndpoint},
{"introspection_endpoint", asm.IntrospectionEndpoint},
}
for _, u := range urls {
if err := checkURLScheme(u.value); err != nil {
return fmt.Errorf("%s: %w", u.name, err)
}
}
urls = []struct {
name string
value string
}{
{"authorization_endpoint", asm.AuthorizationEndpoint},
{"token_endpoint", asm.TokenEndpoint},
{"registration_endpoint", asm.RegistrationEndpoint},
{"introspection_endpoint", asm.IntrospectionEndpoint},
}
for _, u := range urls {
if err := checkHTTPSOrLoopback(u.value); err != nil {
return fmt.Errorf("%s: %w", u.name, err)
}
}
return nil
}
+263
View File
@@ -0,0 +1,263 @@
// 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 Authorization Server Metadata.
// See https://www.rfc-editor.org/rfc/rfc8414.html.
//go:build mcp_go_client_oauth
package oauthex
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
)
// ClientRegistrationMetadata represents the client metadata fields for the DCR POST request (RFC 7591).
//
// Note: URL fields in this struct are validated by validateClientRegistrationURLs
// to prevent XSS attacks. If you add a new URL field, you must also add it to
// that function.
type ClientRegistrationMetadata struct {
// RedirectURIs is a REQUIRED JSON array of redirection URI strings for use in
// redirect-based flows (such as the authorization code grant).
RedirectURIs []string `json:"redirect_uris"`
// TokenEndpointAuthMethod is an OPTIONAL string indicator of the requested
// authentication method for the token endpoint.
// If omitted, the default is "client_secret_basic".
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
// GrantTypes is an OPTIONAL JSON array of OAuth 2.0 grant type strings
// that the client will restrict itself to using.
// If omitted, the default is ["authorization_code"].
GrantTypes []string `json:"grant_types,omitempty"`
// ResponseTypes is an OPTIONAL JSON array of OAuth 2.0 response type strings
// that the client will restrict itself to using.
// If omitted, the default is ["code"].
ResponseTypes []string `json:"response_types,omitempty"`
// ClientName is a RECOMMENDED human-readable name of the client to be presented
// to the end-user.
ClientName string `json:"client_name,omitempty"`
// ClientURI is a RECOMMENDED URL of a web page providing information about the client.
ClientURI string `json:"client_uri,omitempty"`
// LogoURI is an OPTIONAL URL of a logo for the client, which may be displayed
// to the end-user.
LogoURI string `json:"logo_uri,omitempty"`
// Scope is an OPTIONAL string containing a space-separated list of scope values
// that the client will restrict itself to using.
Scope string `json:"scope,omitempty"`
// Contacts is an OPTIONAL JSON array of strings representing ways to contact
// people responsible for this client (e.g., email addresses).
Contacts []string `json:"contacts,omitempty"`
// TOSURI is an OPTIONAL URL that the client provides to the end-user
// to read about the client's terms of service.
TOSURI string `json:"tos_uri,omitempty"`
// PolicyURI is an OPTIONAL URL that the client provides to the end-user
// to read about the client's privacy policy.
PolicyURI string `json:"policy_uri,omitempty"`
// JWKSURI is an OPTIONAL URL for the client's JSON Web Key Set [JWK] document.
// This is preferred over the 'jwks' parameter.
JWKSURI string `json:"jwks_uri,omitempty"`
// JWKS is an OPTIONAL client's JSON Web Key Set [JWK] document, passed by value.
// This is an alternative to providing a JWKSURI.
JWKS string `json:"jwks,omitempty"`
// SoftwareID is an OPTIONAL unique identifier string for the client software,
// constant across all instances and versions.
SoftwareID string `json:"software_id,omitempty"`
// SoftwareVersion is an OPTIONAL version identifier string for the client software.
SoftwareVersion string `json:"software_version,omitempty"`
// SoftwareStatement is an OPTIONAL JWT that asserts client metadata values.
// Values in the software statement take precedence over other metadata values.
SoftwareStatement string `json:"software_statement,omitempty"`
}
// ClientRegistrationResponse represents the fields returned by the Authorization Server
// (RFC 7591, Section 3.2.1 and 3.2.2).
type ClientRegistrationResponse struct {
// ClientRegistrationMetadata contains all registered client metadata, returned by the
// server on success, potentially with modified or defaulted values.
ClientRegistrationMetadata
// ClientID is the REQUIRED newly issued OAuth 2.0 client identifier.
ClientID string `json:"client_id"`
// ClientSecret is an OPTIONAL client secret string.
ClientSecret string `json:"client_secret,omitempty"`
// ClientIDIssuedAt is an OPTIONAL Unix timestamp when the ClientID was issued.
ClientIDIssuedAt time.Time `json:"client_id_issued_at,omitempty"`
// ClientSecretExpiresAt is the REQUIRED (if client_secret is issued) Unix
// timestamp when the secret expires, or 0 if it never expires.
ClientSecretExpiresAt time.Time `json:"client_secret_expires_at,omitempty"`
}
func (r *ClientRegistrationResponse) MarshalJSON() ([]byte, error) {
type alias ClientRegistrationResponse
var clientIDIssuedAt int64
var clientSecretExpiresAt int64
if !r.ClientIDIssuedAt.IsZero() {
clientIDIssuedAt = r.ClientIDIssuedAt.Unix()
}
if !r.ClientSecretExpiresAt.IsZero() {
clientSecretExpiresAt = r.ClientSecretExpiresAt.Unix()
}
return json.Marshal(&struct {
ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`
ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
*alias
}{
ClientIDIssuedAt: clientIDIssuedAt,
ClientSecretExpiresAt: clientSecretExpiresAt,
alias: (*alias)(r),
})
}
func (r *ClientRegistrationResponse) UnmarshalJSON(data []byte) error {
type alias ClientRegistrationResponse
aux := &struct {
ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`
ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
*alias
}{
alias: (*alias)(r),
}
if err := internaljson.Unmarshal(data, &aux); err != nil {
return err
}
if aux.ClientIDIssuedAt != 0 {
r.ClientIDIssuedAt = time.Unix(aux.ClientIDIssuedAt, 0)
}
if aux.ClientSecretExpiresAt != 0 {
r.ClientSecretExpiresAt = time.Unix(aux.ClientSecretExpiresAt, 0)
}
return nil
}
// ClientRegistrationError is the error response from the Authorization Server
// for a failed registration attempt (RFC 7591, Section 3.2.2).
type ClientRegistrationError struct {
// ErrorCode is the REQUIRED error code if registration failed (RFC 7591, 3.2.2).
ErrorCode string `json:"error"`
// ErrorDescription is an OPTIONAL human-readable error message.
ErrorDescription string `json:"error_description,omitempty"`
}
func (e *ClientRegistrationError) Error() string {
return fmt.Sprintf("registration failed: %s (%s)", e.ErrorCode, e.ErrorDescription)
}
// RegisterClient performs Dynamic Client Registration according to RFC 7591.
func RegisterClient(ctx context.Context, registrationEndpoint string, clientMeta *ClientRegistrationMetadata, c *http.Client) (*ClientRegistrationResponse, error) {
if registrationEndpoint == "" {
return nil, fmt.Errorf("registration_endpoint is required")
}
if c == nil {
c = http.DefaultClient
}
payload, err := json.Marshal(clientMeta)
if err != nil {
return nil, fmt.Errorf("failed to marshal client metadata: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", registrationEndpoint, bytes.NewBuffer(payload))
if err != nil {
return nil, fmt.Errorf("failed to create registration request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.Do(req)
if err != nil {
return nil, fmt.Errorf("registration request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read registration response body: %w", err)
}
if resp.StatusCode == http.StatusCreated {
var regResponse ClientRegistrationResponse
if err := internaljson.Unmarshal(body, &regResponse); err != nil {
return nil, fmt.Errorf("failed to decode successful registration response: %w (%s)", err, string(body))
}
if regResponse.ClientID == "" {
return nil, fmt.Errorf("registration response is missing required 'client_id' field")
}
// Validate URL fields to prevent XSS attacks (see #526).
if err := validateClientRegistrationURLs(&regResponse.ClientRegistrationMetadata); err != nil {
return nil, err
}
return &regResponse, nil
}
if resp.StatusCode == http.StatusBadRequest {
var regError ClientRegistrationError
if err := internaljson.Unmarshal(body, &regError); err != nil {
return nil, fmt.Errorf("failed to decode registration error response: %w (%s)", err, string(body))
}
return nil, &regError
}
return nil, fmt.Errorf("registration failed with status %s: %s", resp.Status, string(body))
}
// validateClientRegistrationURLs validates all URL fields in ClientRegistrationMetadata
// to ensure they don't use dangerous schemes that could enable XSS attacks.
func validateClientRegistrationURLs(meta *ClientRegistrationMetadata) error {
// Validate redirect URIs
for i, uri := range meta.RedirectURIs {
if err := checkURLScheme(uri); err != nil {
return fmt.Errorf("redirect_uris[%d]: %w", i, err)
}
}
// Validate other URL fields
urls := []struct {
name string
value string
}{
{"client_uri", meta.ClientURI},
{"logo_uri", meta.LogoURI},
{"tos_uri", meta.TOSURI},
{"policy_uri", meta.PolicyURI},
{"jwks_uri", meta.JWKSURI},
}
for _, u := range urls {
if err := checkURLScheme(u.value); err != nil {
return fmt.Errorf("%s: %w", u.name, err)
}
}
return nil
}
+96
View File
@@ -0,0 +1,96 @@
// 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.
// Package oauthex implements extensions to OAuth2.
//go:build mcp_go_client_oauth
package oauthex
import (
"context"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strings"
"github.com/modelcontextprotocol/go-sdk/internal/util"
)
type httpStatusError struct {
StatusCode int
}
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
// RFC 9728 and RFC 8414.
// It will not read more than limit bytes from the body.
func getJSON[T any](ctx context.Context, c *http.Client, url string, limit int64) (*T, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
if c == nil {
c = http.DefaultClient
}
res, err := c.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, &httpStatusError{StatusCode: res.StatusCode}
}
ct := res.Header.Get("Content-Type")
mediaType, _, err := mime.ParseMediaType(ct)
if err != nil || mediaType != "application/json" {
return nil, fmt.Errorf("bad content type %q", ct)
}
var t T
dec := json.NewDecoder(io.LimitReader(res.Body, limit))
if err := dec.Decode(&t); err != nil {
return nil, err
}
return &t, nil
}
// checkURLScheme ensures that its argument is a valid URL with a scheme
// that prevents XSS attacks.
// See #526.
func checkURLScheme(u string) error {
if u == "" {
return nil
}
uu, err := url.Parse(u)
if err != nil {
return err
}
scheme := strings.ToLower(uu.Scheme)
if scheme == "javascript" || scheme == "data" || scheme == "vbscript" {
return fmt.Errorf("URL has disallowed scheme %q", scheme)
}
return nil
}
func checkHTTPSOrLoopback(addr string) error {
if addr == "" {
return nil
}
u, err := url.Parse(addr)
if err != nil {
return err
}
if !util.IsLoopback(u.Host) && u.Scheme != "https" {
return fmt.Errorf("URL %q does not use HTTPS or is not a loopback address", addr)
}
return nil
}
+6
View File
@@ -0,0 +1,6 @@
// 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.
// Package oauthex implements extensions to OAuth2.
package oauthex
+279
View File
@@ -0,0 +1,279 @@
// 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)
// Only allow HTTP for local addresses (testing or development purposes).
if err := checkHTTPSOrLoopback(metadataURL); err != nil {
return nil, fmt.Errorf("metadataURL: %v", err)
}
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 i, u := range prm.AuthorizationServers {
if err := checkURLScheme(u); err != nil {
return nil, fmt.Errorf("authorization_servers[%d]: %v", i, err)
}
if err := checkHTTPSOrLoopback(u); err != nil {
return nil, fmt.Errorf("authorization_servers[%d]: %v", i, 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
}
@@ -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
}