oauthex: move internal/oauthex to oauthex (#559)

This PR relocates oauthex and moves DCR logic into dcr.go.

Fixes #558
This commit is contained in:
Sam Thanawalla 2025-10-07 08:39:49 -04:00 • committed by GitHub
commit 9348d33b75
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 272 additions and 239 deletions

View file

@ -12,7 +12,7 @@ import (
"net/http"
"sync"
"github.com/modelcontextprotocol/go-sdk/internal/oauthex"
"github.com/modelcontextprotocol/go-sdk/oauthex"
"golang.org/x/oauth2"
)

147
oauthex/auth_meta.go Normal file
View file

@ -0,0 +1,147 @@
// 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
//
// [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"`
// 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"`
}
var wellKnownPaths = []string{
"/.well-known/oauth-authorization-server",
"/.well-known/openid-configuration",
}
// GetAuthServerMeta issues a GET request to retrieve authorization server metadata
// from an OAuth authorization server with the given issuerURL.
//
// 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.
//
// [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)
}
return asm, nil
}
errs = append(errs, err)
}
return nil, fmt.Errorf("failed to get auth server metadata from %q: %w", issuerURL, errors.Join(errs...))
}

30
oauthex/auth_meta_test.go Normal file
View file

@ -0,0 +1,30 @@
// 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.
//go:build mcp_go_client_oauth
package oauthex
import (
"encoding/json"
"os"
"path/filepath"
"testing"
)
func TestAuthMetaParse(t *testing.T) {
// Verify that we parse Google's auth server metadata.
data, err := os.ReadFile(filepath.FromSlash("testdata/google-auth-meta.json"))
if err != nil {
t.Fatal(err)
}
var a AuthServerMeta
if err := json.Unmarshal(data, &a); err != nil {
t.Fatal(err)
}
// Spot check.
if g, w := a.Issuer, "https://accounts.google.com"; g != w {
t.Errorf("got %q, want %q", g, w)
}
}

223
oauthex/dcr.go Normal file
View file

@ -0,0 +1,223 @@
// 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"
)
// ClientRegistrationMetadata represents the client metadata fields for the DCR POST request (RFC 7591).
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 := json.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 := json.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")
}
return &regResponse, nil
}
if resp.StatusCode == http.StatusBadRequest {
var regError ClientRegistrationError
if err := json.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))
}

217
oauthex/dcr_test.go Normal file
View file

@ -0,0 +1,217 @@
// 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.
//go:build mcp_go_client_oauth
package oauthex
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
func TestClientRegistrationMetadataParse(t *testing.T) {
// Verify that we can parse a typical client metadata JSON.
data, err := os.ReadFile(filepath.FromSlash("testdata/client-auth-meta.json"))
if err != nil {
t.Fatal(err)
}
var a ClientRegistrationMetadata
if err := json.Unmarshal(data, &a); err != nil {
t.Fatal(err)
}
// Spot check
if g, w := a.ClientName, "My Test App"; g != w {
t.Errorf("got ClientName %q, want %q", g, w)
}
if g, w := len(a.RedirectURIs), 2; g != w {
t.Errorf("got %d RedirectURIs, want %d", g, w)
}
}
func TestRegisterClient(t *testing.T) {
testCases := []struct {
name string
handler http.HandlerFunc
clientMeta *ClientRegistrationMetadata
wantClientID string
wantErr string
}{
{
name: "Success",
handler: func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Errorf("Expected POST, got %s", r.Method)
}
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatal(err)
}
var receivedMeta ClientRegistrationMetadata
if err := json.Unmarshal(body, &receivedMeta); err != nil {
t.Fatalf("Failed to unmarshal request body: %v", err)
}
if receivedMeta.ClientName != "Test App" {
t.Errorf("Expected ClientName 'Test App', got '%s'", receivedMeta.ClientName)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"client_id":"test-client-id","client_secret":"test-client-secret","client_name":"Test App"}`))
},
clientMeta: &ClientRegistrationMetadata{ClientName: "Test App", RedirectURIs: []string{"http://localhost/cb"}},
wantClientID: "test-client-id",
},
{
name: "Missing ClientID in Response",
handler: func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"client_secret":"test-client-secret"}`)) // No client_id
},
clientMeta: &ClientRegistrationMetadata{RedirectURIs: []string{"http://localhost/cb"}},
wantErr: "registration response is missing required 'client_id' field",
},
{
name: "Standard OAuth Error",
handler: func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"invalid_redirect_uri","error_description":"Redirect URI is not valid."}`))
},
clientMeta: &ClientRegistrationMetadata{RedirectURIs: []string{"http://invalid/cb"}},
wantErr: "registration failed: invalid_redirect_uri (Redirect URI is not valid.)",
},
{
name: "Non-JSON Server Error",
handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
},
clientMeta: &ClientRegistrationMetadata{RedirectURIs: []string{"http://localhost/cb"}},
wantErr: "registration failed with status 500 Internal Server Error",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(tc.handler)
defer server.Close()
info, err := RegisterClient(context.Background(), server.URL, tc.clientMeta, server.Client())
if tc.wantErr != "" {
if err == nil {
t.Fatalf("Expected an error containing '%s', but got nil", tc.wantErr)
}
if !strings.Contains(err.Error(), tc.wantErr) {
t.Errorf("Expected error to contain '%s', got '%v'", tc.wantErr, err)
}
return
}
if err != nil {
t.Fatalf("Expected no error, but got: %v", err)
}
if info.ClientID != tc.wantClientID {
t.Errorf("Expected client_id '%s', got '%s'", tc.wantClientID, info.ClientID)
}
})
}
t.Run("No Endpoint", func(t *testing.T) {
_, err := RegisterClient(context.Background(), "", &ClientRegistrationMetadata{}, nil)
if err == nil {
t.Fatal("Expected an error for missing registration endpoint, got nil")
}
expectedErr := "registration_endpoint is required"
if err.Error() != expectedErr {
t.Errorf("Expected error '%s', got '%v'", expectedErr, err)
}
})
}
func TestClientRegistrationResponseJSON(t *testing.T) {
testCases := []struct {
name string
in ClientRegistrationResponse
wantJSON string
}{
{
name: "full response",
in: ClientRegistrationResponse{
ClientID: "test-client-id",
ClientSecret: "test-client-secret",
ClientIDIssuedAt: time.Unix(1758840047, 0),
ClientSecretExpiresAt: time.Unix(1790376047, 0),
},
wantJSON: `{"client_id":"test-client-id","client_secret":"test-client-secret","client_id_issued_at":1758840047,"client_secret_expires_at":1790376047, "redirect_uris": null}`,
},
{
name: "minimal response with only required fields",
in: ClientRegistrationResponse{
ClientID: "test-client-id-minimal",
},
wantJSON: `{"client_id":"test-client-id-minimal", "redirect_uris":null}`,
},
{
name: "response with a secret that does not expire",
in: ClientRegistrationResponse{
ClientID: "test-client-id-no-expiry",
ClientSecret: "test-secret-no-expiry",
},
wantJSON: `{"client_id":"test-client-id-no-expiry","client_secret":"test-secret-no-expiry", "redirect_uris":null}`,
},
{
name: "unmarshal with zero timestamp",
in: ClientRegistrationResponse{ClientID: "client-id-zero"},
wantJSON: `{"client_id":"client-id-zero", "redirect_uris":null}`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Test MarshalJSON
t.Run("marshal", func(t *testing.T) {
b, err := json.Marshal(&tc.in)
if err != nil {
t.Fatalf("Marshal() error = %v", err)
}
var gotMap, wantMap map[string]any
if err := json.Unmarshal(b, &gotMap); err != nil {
t.Fatalf("failed to unmarshal actual result: %v", err)
}
if err := json.Unmarshal([]byte(tc.wantJSON), &wantMap); err != nil {
t.Fatalf("failed to unmarshal expected result: %v", err)
}
if diff := cmp.Diff(wantMap, gotMap); diff != "" {
t.Errorf("Marshal() mismatch (-want +got):\n%s", diff)
}
})
// Test UnmarshalJSON
t.Run("unmarshal", func(t *testing.T) {
var got ClientRegistrationResponse
if err := json.Unmarshal([]byte(tc.wantJSON), &got); err != nil {
t.Fatalf("Unmarshal() error = %v", err)
}
if diff := cmp.Diff(tc.in, got); diff != "" {
t.Errorf("Unmarshal() mismatch (-want +got):\n%s", diff)
}
})
})
}
}

88
oauthex/oauth2.go Normal file
View file

@ -0,0 +1,88 @@
// 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"
"net/http"
"net/url"
"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 += "/"
}
u.Path = p + strings.TrimLeft(u.Path, "/")
return u.String(), nil
}
// 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()
// Specs require a 200.
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bad status %s", res.Status)
}
// Specs require application/json.
if ct := res.Header.Get("Content-Type"); ct != "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
}

272
oauthex/oauth2_test.go Normal file
View file

@ -0,0 +1,272 @@
// 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.
//go:build mcp_go_client_oauth
package oauthex
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
func TestSplitChallenges(t *testing.T) {
tests := []struct {
name string
input string
want []string
}{
{
name: "single challenge no params",
input: `Basic`,
want: []string{`Basic`},
},
{
name: "single challenge with params",
input: `Bearer realm="example.com", error="invalid_token"`,
want: []string{`Bearer realm="example.com", error="invalid_token"`},
},
{
name: "single challenge with comma in quoted string",
input: `Bearer realm="example, with comma"`,
want: []string{`Bearer realm="example, with comma"`},
},
{
name: "two challenges",
input: `Basic, Bearer realm="example"`,
want: []string{`Basic`, ` Bearer realm="example"`},
},
{
name: "multiple challenges complex",
input: `Newauth realm="apps", Basic, Bearer realm="example.com", error="invalid_token"`,
want: []string{`Newauth realm="apps"`, ` Basic`, ` Bearer realm="example.com", error="invalid_token"`},
},
{
name: "challenge with escaped quote",
input: `Bearer realm="example \"quoted\""`,
want: []string{`Bearer realm="example \"quoted\""`},
},
{
name: "empty input",
input: "",
want: []string{""},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := splitChallenges(tt.input)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("splitChallenges() = %v, want %v", got, tt.want)
}
})
}
}
func TestSplitChallengesError(t *testing.T) {
if _, err := splitChallenges(`"Bearer"`); err == nil {
t.Fatal("got nil, want error")
}
}
func TestParseSingleChallenge(t *testing.T) {
tests := []struct {
name string
input string
want challenge
wantErr bool
}{
{
name: "scheme only",
input: "Basic",
want: challenge{
Scheme: "basic",
},
wantErr: false,
},
{
name: "scheme with one quoted param",
input: `Bearer realm="example.com"`,
want: challenge{
Scheme: "bearer",
Params: map[string]string{"realm": "example.com"},
},
wantErr: false,
},
{
name: "scheme with one unquoted param",
input: `Bearer realm=example.com`,
want: challenge{
Scheme: "bearer",
Params: map[string]string{"realm": "example.com"},
},
wantErr: false,
},
{
name: "scheme with multiple params",
input: `Bearer realm="example", error="invalid_token", error_description="The token expired"`,
want: challenge{
Scheme: "bearer",
Params: map[string]string{
"realm": "example",
"error": "invalid_token",
"error_description": "The token expired",
},
},
wantErr: false,
},
{
name: "scheme with multiple unquoted params",
input: `Bearer realm=example, error=invalid_token, error_description=The token expired`,
want: challenge{
Scheme: "bearer",
Params: map[string]string{
"realm": "example",
"error": "invalid_token",
"error_description": "The token expired",
},
},
wantErr: false,
},
{
name: "case-insensitive scheme and keys",
input: `BEARER ReAlM="example"`,
want: challenge{
Scheme: "bearer",
Params: map[string]string{"realm": "example"},
},
wantErr: false,
},
{
name: "param with escaped quote",
input: `Bearer realm="example \"foo\" bar"`,
want: challenge{
Scheme: "bearer",
Params: map[string]string{"realm": `example "foo" bar`},
},
wantErr: false,
},
{
name: "param without quotes (token)",
input: "Bearer realm=example.com",
want: challenge{
Scheme: "bearer",
Params: map[string]string{"realm": "example.com"},
},
wantErr: false,
},
{
name: "malformed param - no value",
input: "Bearer realm=",
wantErr: true,
},
{
name: "malformed param - unterminated quote",
input: `Bearer realm="example`,
wantErr: true,
},
{
name: "malformed param - missing comma",
input: `Bearer realm="a" error="b"`,
wantErr: true,
},
{
name: "malformed param - initial equal",
input: `Bearer ="a"`,
wantErr: true,
},
{
name: "empty input",
input: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseSingleChallenge(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("parseSingleChallenge() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseSingleChallenge() = %v, want %v", got, tt.want)
}
})
}
}
func TestGetProtectedResourceMetadata(t *testing.T) {
ctx := context.Background()
t.Run("FromHeader", func(t *testing.T) {
h := &fakeResourceHandler{serveWWWAuthenticate: true}
server := httptest.NewTLSServer(h)
h.installHandlers(server.URL)
client := server.Client()
res, err := client.Get(server.URL + "/resource")
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusUnauthorized {
t.Fatal("want unauth")
}
prm, err := GetProtectedResourceMetadataFromHeader(ctx, res.Header, client)
if err != nil {
t.Fatal(err)
}
if prm == nil {
t.Fatal("nil prm")
}
})
t.Run("FromID", func(t *testing.T) {
h := &fakeResourceHandler{serveWWWAuthenticate: false}
server := httptest.NewTLSServer(h)
h.installHandlers(server.URL)
client := server.Client()
prm, err := GetProtectedResourceMetadataFromID(ctx, server.URL, client)
if err != nil {
t.Fatal(err)
}
if prm == nil {
t.Fatal("nil prm")
}
})
}
type fakeResourceHandler struct {
http.ServeMux
serveWWWAuthenticate bool
}
func (h *fakeResourceHandler) installHandlers(serverURL string) {
path := "/.well-known/oauth-protected-resource"
url := serverURL + path
h.Handle("GET /resource", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h.serveWWWAuthenticate {
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer resource_metadata="%s"`, url))
}
w.WriteHeader(http.StatusUnauthorized)
}))
h.Handle("GET "+path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// If there is a WWW-Authenticate header, the resource field is the value of that header.
// If not, it's the server URL without the "/.well-known/..." part.
resource := serverURL
if h.serveWWWAuthenticate {
resource = url
}
prm := &ProtectedResourceMetadata{Resource: resource}
if err := json.NewEncoder(w).Encode(prm); err != nil {
panic(err)
}
}))
}

View file

@ -5,10 +5,88 @@
// Package oauthex implements extensions to OAuth2.
package oauthex
import (
"github.com/modelcontextprotocol/go-sdk/internal/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.
type ProtectedResourceMetadata = oauthex.ProtectedResourceMetadata
//
// 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"`
}

280
oauthex/resource_meta.go Normal file
View file

@ -0,0 +1,280 @@
// 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.
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 getPRM(ctx, u.String(), c, resourceID)
}
// 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,
// It then validates the resource field of the resulting metadata against the given URL.
// If there is no URL in the request, it returns nil, nil.
func GetProtectedResourceMetadataFromHeader(ctx context.Context, 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
}
cs, err := ParseWWWAuthenticate(headers)
if err != nil {
return nil, err
}
url := ResourceMetadataURL(cs)
if url == "" {
return nil, nil
}
return getPRM(ctx, url, c, url)
}
// 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)
}
prm, err := getJSON[ProtectedResourceMetadata](ctx, c, purl, 1<<20)
if err != nil {
return nil, err
}
// Validate the Resource field to thwart impersonation attacks (section 3.3).
if prm.Resource != wantResource {
return nil, fmt.Errorf("got metadata resource %q, want %q", prm.Resource, wantResource)
}
// 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
}
// 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
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) {
// GENERATED BY GEMINI 2.5.
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) {
// GENERATED BY GEMINI 2.5, human-tweaked.
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
}

View file

@ -0,0 +1,8 @@
{
"client_name": "My Test App",
"redirect_uris": [
"https://client.example.org/callback",
"https://client.example.org/callback2"
],
"scope": "read write"
}

57
oauthex/testdata/google-auth-meta.json vendored Normal file
View file

@ -0,0 +1,57 @@
{
"issuer": "https://accounts.google.com",
"authorization_endpoint": "https://accounts.google.com/o/oauth2/v2/auth",
"device_authorization_endpoint": "https://oauth2.googleapis.com/device/code",
"token_endpoint": "https://oauth2.googleapis.com/token",
"userinfo_endpoint": "https://openidconnect.googleapis.com/v1/userinfo",
"revocation_endpoint": "https://oauth2.googleapis.com/revoke",
"jwks_uri": "https://www.googleapis.com/oauth2/v3/certs",
"response_types_supported": [
"code",
"token",
"id_token",
"code token",
"code id_token",
"token id_token",
"code token id_token",
"none"
],
"subject_types_supported": [
"public"
],
"id_token_signing_alg_values_supported": [
"RS256"
],
"scopes_supported": [
"openid",
"email",
"profile"
],
"token_endpoint_auth_methods_supported": [
"client_secret_post",
"client_secret_basic"
],
"claims_supported": [
"aud",
"email",
"email_verified",
"exp",
"family_name",
"given_name",
"iat",
"iss",
"name",
"picture",
"sub"
],
"code_challenge_methods_supported": [
"plain",
"S256"
],
"grant_types_supported": [
"authorization_code",
"refresh_token",
"urn:ietf:params:oauth:grant-type:device_code",
"urn:ietf:params:oauth:grant-type:jwt-bearer"
]
}