all: stabilize client OAuth support (#861)

Also fix lint errors that were hidden because of the build tag.
This commit is contained in:
Maciej Kisiel 2026-03-31 12:36:31 +02:00 • committed by GitHub
commit 638d404e0d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 387 additions and 915 deletions

View file

@ -2,8 +2,6 @@
// Use of this source code is governed by the license
// that can be found in the LICENSE file.
//go:build mcp_go_client_oauth
package auth
import (
@ -142,7 +140,7 @@ func NewAuthorizationCodeHandler(config *AuthorizationCodeHandlerConfig) (*Autho
dCfg := config.DynamicClientRegistrationConfig
if dCfg != nil {
if dCfg.Metadata == nil {
return nil, errors.New("Metadata is required for dynamic client registration")
return nil, errors.New("dynamic client registration requires non-nil Metadata")
}
if len(dCfg.Metadata.RedirectURIs) == 0 {
return nil, errors.New("Metadata.RedirectURIs is required for dynamic client registration")
@ -283,17 +281,14 @@ func errorFromChallenges(cs []oauthex.Challenge) string {
// If no metadata was found or the fetched metadata fails security checks,
// it returns an error.
func (h *AuthorizationCodeHandler) getProtectedResourceMetadata(ctx context.Context, wwwChallenges []oauthex.Challenge, mcpServerURL string) (*oauthex.ProtectedResourceMetadata, error) {
var errs []error
// Use MCP server URL as the resource URI per
// https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#canonical-server-uri.
for _, url := range protectedResourceMetadataURLs(resourceMetadataURLFromChallenges(wwwChallenges), mcpServerURL) {
prm, err := oauthex.GetProtectedResourceMetadata(ctx, url.URL, url.Resource, h.config.Client)
if err != nil {
errs = append(errs, err)
continue
}
if prm == nil {
errs = append(errs, fmt.Errorf("protected resource metadata is nil"))
continue
}
if len(prm.AuthorizationServers) == 0 {

View file

@ -2,8 +2,6 @@
// Use of this source code is governed by the license
// that can be found in the LICENSE file.
//go:build mcp_go_client_oauth
package auth
import (

View file

@ -1,135 +0,0 @@
// 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 auth
import (
"bytes"
"errors"
"io"
"net/http"
"sync"
"golang.org/x/oauth2"
)
// An OAuthHandlerLegacy conducts an OAuth flow and returns a [oauth2.TokenSource] if the authorization
// is approved, or an error if not.
// The handler receives the HTTP request and response that triggered the authentication flow.
// To obtain the protected resource metadata, call [oauthex.GetProtectedResourceMetadataFromHeader].
//
// Deprecated: Please use the new [OAuthHandler] abstraction that is built
// into the streamable transport. This struct will be removed in v1.5.0.
type OAuthHandlerLegacy func(req *http.Request, res *http.Response) (oauth2.TokenSource, error)
// HTTPTransport is an [http.RoundTripper] that follows the MCP
// OAuth protocol when it encounters a 401 Unauthorized response.
//
// Deprecated: Please use the new [OAuthHandler] abstraction that is built
// into the streamable transport. This struct will be removed in v1.5.0.
type HTTPTransport struct {
handler OAuthHandlerLegacy
mu sync.Mutex // protects opts.Base
opts HTTPTransportOptions
}
// NewHTTPTransport returns a new [*HTTPTransport].
// The handler is invoked when an HTTP request results in a 401 Unauthorized status.
// It is called only once per transport. Once a TokenSource is obtained, it is used
// for the lifetime of the transport; subsequent 401s are not processed.
//
// Deprecated: Please use the new [OAuthHandler] abstraction that is built
// into the streamable transport. This struct will be removed in v1.5.0.
func NewHTTPTransport(handler OAuthHandlerLegacy, opts *HTTPTransportOptions) (*HTTPTransport, error) {
if handler == nil {
return nil, errors.New("handler cannot be nil")
}
t := &HTTPTransport{
handler: handler,
}
if opts != nil {
t.opts = *opts
}
if t.opts.Base == nil {
t.opts.Base = http.DefaultTransport
}
return t, nil
}
// HTTPTransportOptions are options to [NewHTTPTransport].
//
// Deprecated: Please use the new [OAuthHandler] abstraction that is built
// into the streamable transport. This struct will be removed in v1.5.0.
type HTTPTransportOptions struct {
// Base is the [http.RoundTripper] to use.
// If nil, [http.DefaultTransport] is used.
Base http.RoundTripper
}
func (t *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
t.mu.Lock()
base := t.opts.Base
t.mu.Unlock()
var (
// If haveBody is set, the request has a nontrivial body, and we need avoid
// reading (or closing) it multiple times. In that case, bodyBytes is its
// content.
haveBody bool
bodyBytes []byte
)
if req.Body != nil && req.Body != http.NoBody {
// if we're setting Body, we must mutate first.
req = req.Clone(req.Context())
haveBody = true
var err error
bodyBytes, err = io.ReadAll(req.Body)
if err != nil {
return nil, err
}
// Now that we've read the request body, http.RoundTripper requires that we
// close it.
req.Body.Close() // ignore error
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
}
resp, err := base.RoundTrip(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusUnauthorized {
return resp, nil
}
if _, ok := base.(*oauth2.Transport); ok {
// We failed to authorize even with a token source; give up.
return resp, nil
}
resp.Body.Close()
// Try to authorize.
t.mu.Lock()
defer t.mu.Unlock()
// If we don't have a token source, get one by following the OAuth flow.
// (We may have obtained one while t.mu was not held above.)
// TODO: We hold the lock for the entire OAuth flow. This could be a long
// time. Is there a better way?
if _, ok := t.opts.Base.(*oauth2.Transport); !ok {
ts, err := t.handler(req, resp)
if err != nil {
return nil, err
}
t.opts.Base = &oauth2.Transport{Base: t.opts.Base, Source: ts}
}
// If we don't have a body, the request is reusable, though it will be cloned
// by the base. However, if we've had to read the body, we must clone.
if haveBody {
req = req.Clone(req.Context())
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
}
return t.opts.Base.RoundTrip(req)
}

View file

@ -1,153 +0,0 @@
// 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 auth
import (
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"golang.org/x/oauth2"
)
// A basicReader is an io.Reader to be used as a non-rereadable request body.
//
// net/http has special handling for strings.Reader that we want to avoid.
type basicReader struct {
r *strings.Reader
}
func (r *basicReader) Read(p []byte) (n int, err error) { return r.r.Read(p) }
// TestHTTPTransport validates the OAuth HTTPTransport.
func TestHTTPTransport(t *testing.T) {
const testToken = "test-token-123"
fakeTokenSource := oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: testToken,
TokenType: "Bearer",
})
// authServer simulates a resource that requires OAuth.
authServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
// Ensure that the body was properly cloned, by reading it completely.
// If the body is not cloned, reading it the second time may yield no
// bytes.
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(body) == 0 {
http.Error(w, "empty body", http.StatusBadRequest)
return
}
}
authHeader := r.Header.Get("Authorization")
if authHeader == fmt.Sprintf("Bearer %s", testToken) {
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("WWW-Authenticate", `Bearer resource_metadata="http://metadata.example.com"`)
w.WriteHeader(http.StatusUnauthorized)
}))
defer authServer.Close()
t.Run("successful auth flow", func(t *testing.T) {
var handlerCalls int
handler := func(req *http.Request, res *http.Response) (oauth2.TokenSource, error) {
handlerCalls++
// Verify that the response has the expected WWW-Authenticate header
if res.Header.Get("WWW-Authenticate") != `Bearer resource_metadata="http://metadata.example.com"` {
t.Errorf("handler got WWW-Authenticate header %q", res.Header.Get("WWW-Authenticate"))
}
return fakeTokenSource, nil
}
transport, err := NewHTTPTransport(handler, nil)
if err != nil {
t.Fatalf("NewHTTPTransport() failed: %v", err)
}
client := &http.Client{Transport: transport}
resp, err := client.Get(authServer.URL)
if err != nil {
t.Fatalf("client.Get() failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusOK)
}
if handlerCalls != 1 {
t.Errorf("handler was called %d times, want 1", handlerCalls)
}
// Second request should reuse the token and not call the handler again.
resp2, err := client.Get(authServer.URL)
if err != nil {
t.Fatalf("second client.Get() failed: %v", err)
}
defer resp2.Body.Close()
if resp2.StatusCode != http.StatusOK {
t.Errorf("second request got status %d, want %d", resp2.StatusCode, http.StatusOK)
}
if handlerCalls != 1 {
t.Errorf("handler should still be called only once, but was %d", handlerCalls)
}
})
t.Run("request body is cloned", func(t *testing.T) {
handler := func(req *http.Request, res *http.Response) (oauth2.TokenSource, error) {
// Verify that the response has the expected WWW-Authenticate header
if res.Header.Get("WWW-Authenticate") != `Bearer resource_metadata="http://metadata.example.com"` {
t.Errorf("handler got WWW-Authenticate header %q", res.Header.Get("WWW-Authenticate"))
}
return fakeTokenSource, nil
}
transport, err := NewHTTPTransport(handler, nil)
if err != nil {
t.Fatalf("NewHTTPTransport() failed: %v", err)
}
client := &http.Client{Transport: transport}
resp, err := client.Post(authServer.URL, "application/json", &basicReader{strings.NewReader("{}")})
if err != nil {
t.Fatalf("client.Post() failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusOK)
}
})
t.Run("handler returns error", func(t *testing.T) {
handlerErr := errors.New("user rejected auth")
handler := func(req *http.Request, res *http.Response) (oauth2.TokenSource, error) {
return nil, handlerErr
}
transport, err := NewHTTPTransport(handler, nil)
if err != nil {
t.Fatalf("NewHTTPTransport() failed: %v", err)
}
client := &http.Client{Transport: transport}
_, err = client.Get(authServer.URL)
if !errors.Is(err, handlerErr) {
t.Errorf("client.Get() returned error %v, want %v", err, handlerErr)
}
})
}

View file

@ -5,8 +5,6 @@
// Package extauth provides OAuth handler implementations for MCP authorization extensions.
// This package implements Enterprise Managed Authorization as defined in SEP-990.
//go:build mcp_go_client_oauth
package extauth
import (

View file

@ -2,8 +2,6 @@
// 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 extauth
import (

View file

@ -6,8 +6,6 @@
// as part of Enterprise Managed Authorization (SEP-990).
// See https://openid.net/specs/openid-connect-core-1_0.html
//go:build mcp_go_client_oauth
package extauth
import (
@ -121,11 +119,11 @@ func initiateOIDCLogin(
return nil, nil, fmt.Errorf("RedirectURL is required")
}
if len(config.Scopes) == 0 {
return nil, nil, fmt.Errorf("Scopes is required (must include 'openid')")
return nil, nil, fmt.Errorf("at least one scope is required (must include 'openid')")
}
if !slices.Contains(config.Scopes, "openid") {
return nil, nil, fmt.Errorf("Scopes must include 'openid' for OIDC")
return nil, nil, fmt.Errorf("the 'openid' scope is required for OIDC")
}
if err := checkURLScheme(config.IssuerURL); err != nil {

View file

@ -2,8 +2,6 @@
// 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 extauth
import (
@ -161,7 +159,7 @@ func TestInitiateOIDCLogin(t *testing.T) {
c.Credentials = &oauthex.ClientCredentials{ClientID: "test"}
c.RedirectURL = "http://localhost:8080/callback"
},
expectErr: "Scopes is required",
expectErr: "at least one scope is required",
},
}
for _, tt := range tests {

View file

@ -4,8 +4,6 @@
// This file contains shared utilities for OAuth handlers.
//go:build mcp_go_client_oauth
package auth
import (

View file

@ -2,8 +2,6 @@
// 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 auth
import (