|
| 1 | +// Copyright 2026 The Go MCP SDK Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by an MIT-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package extauth |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "net/http" |
| 12 | + "strings" |
| 13 | + |
| 14 | + "github.com/modelcontextprotocol/go-sdk/auth" |
| 15 | + "github.com/modelcontextprotocol/go-sdk/oauthex" |
| 16 | + "golang.org/x/oauth2" |
| 17 | + "golang.org/x/oauth2/clientcredentials" |
| 18 | +) |
| 19 | + |
| 20 | +// ClientCredentialsHandlerConfig is the configuration for [ClientCredentialsHandler]. |
| 21 | +type ClientCredentialsHandlerConfig struct { |
| 22 | + // Credentials contains the pre-registered client ID and secret. |
| 23 | + // REQUIRED. Both ClientID and ClientSecretAuth must be set, since the |
| 24 | + // client credentials grant requires a confidential client. |
| 25 | + Credentials *oauthex.ClientCredentials |
| 26 | + |
| 27 | + // Scopes is the list of scopes to request at the authorization server. |
| 28 | + // OPTIONAL. |
| 29 | + Scopes []string |
| 30 | + |
| 31 | + // AuthServerURL is the authorization server issuer URL. |
| 32 | + // If set, the token endpoint is discovered via OAuth 2.0 Authorization |
| 33 | + // Server Metadata (RFC 8414). Either AuthServerURL or TokenEndpoint must |
| 34 | + // be provided, but not both. |
| 35 | + AuthServerURL string |
| 36 | + |
| 37 | + // TokenEndpoint is the token endpoint URL to use directly, skipping |
| 38 | + // metadata discovery. Either AuthServerURL or TokenEndpoint must be |
| 39 | + // provided, but not both. |
| 40 | + TokenEndpoint string |
| 41 | + |
| 42 | + // HTTPClient is an optional HTTP client for customization. |
| 43 | + // If nil, http.DefaultClient is used. |
| 44 | + // OPTIONAL. |
| 45 | + HTTPClient *http.Client |
| 46 | +} |
| 47 | + |
| 48 | +// ClientCredentialsHandler is an implementation of [auth.OAuthHandler] that |
| 49 | +// uses the OAuth 2.0 Client Credentials grant (RFC 6749 Section 4.4) to |
| 50 | +// obtain access tokens. |
| 51 | +// |
| 52 | +// This handler is intended for service-to-service authentication where the |
| 53 | +// client has pre-registered credentials (client ID and secret) and does not |
| 54 | +// require user interaction. It bypasses both dynamic client registration and |
| 55 | +// the authorization code flow. |
| 56 | +// |
| 57 | +// See the ext-auth specification SEP-1046 for details. |
| 58 | +type ClientCredentialsHandler struct { |
| 59 | + config *ClientCredentialsHandlerConfig |
| 60 | + tokenSource oauth2.TokenSource |
| 61 | +} |
| 62 | + |
| 63 | +// Compile-time check that ClientCredentialsHandler implements auth.OAuthHandler. |
| 64 | +var _ auth.OAuthHandler = (*ClientCredentialsHandler)(nil) |
| 65 | + |
| 66 | +// NewClientCredentialsHandler creates a new ClientCredentialsHandler. |
| 67 | +// It validates the configuration and returns an error if invalid. |
| 68 | +func NewClientCredentialsHandler(config *ClientCredentialsHandlerConfig) (*ClientCredentialsHandler, error) { |
| 69 | + if config == nil { |
| 70 | + return nil, fmt.Errorf("config must be provided") |
| 71 | + } |
| 72 | + if config.Credentials == nil { |
| 73 | + return nil, fmt.Errorf("credentials is required") |
| 74 | + } |
| 75 | + if err := config.Credentials.Validate(); err != nil { |
| 76 | + return nil, fmt.Errorf("invalid credentials: %w", err) |
| 77 | + } |
| 78 | + if config.Credentials.ClientSecretAuth == nil { |
| 79 | + return nil, fmt.Errorf("clientSecretAuth is required for client credentials grant") |
| 80 | + } |
| 81 | + if config.AuthServerURL == "" && config.TokenEndpoint == "" { |
| 82 | + return nil, fmt.Errorf("either authServerURL or tokenEndpoint must be provided") |
| 83 | + } |
| 84 | + if config.AuthServerURL != "" && config.TokenEndpoint != "" { |
| 85 | + return nil, fmt.Errorf("authServerURL and tokenEndpoint are mutually exclusive") |
| 86 | + } |
| 87 | + return &ClientCredentialsHandler{config: config}, nil |
| 88 | +} |
| 89 | + |
| 90 | +// TokenSource returns the token source for outgoing requests. |
| 91 | +// Returns nil if authorization has not been performed yet. |
| 92 | +func (h *ClientCredentialsHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) { |
| 93 | + return h.tokenSource, nil |
| 94 | +} |
| 95 | + |
| 96 | +// Authorize performs the Client Credentials grant to obtain an access token. |
| 97 | +// It is called when a request fails with 401 or 403. |
| 98 | +func (h *ClientCredentialsHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error { |
| 99 | + defer resp.Body.Close() |
| 100 | + defer io.Copy(io.Discard, resp.Body) |
| 101 | + |
| 102 | + httpClient := h.config.HTTPClient |
| 103 | + if httpClient == nil { |
| 104 | + httpClient = http.DefaultClient |
| 105 | + } |
| 106 | + |
| 107 | + tokenEndpoint := h.config.TokenEndpoint |
| 108 | + if tokenEndpoint == "" { |
| 109 | + // Discover token endpoint via authorization server metadata. |
| 110 | + meta, err := auth.GetAuthServerMetadata(ctx, h.config.AuthServerURL, httpClient) |
| 111 | + if err != nil { |
| 112 | + return fmt.Errorf("failed to discover auth server metadata: %w", err) |
| 113 | + } |
| 114 | + if meta == nil { |
| 115 | + return fmt.Errorf("no authorization server metadata found for: %s", h.config.AuthServerURL) |
| 116 | + } |
| 117 | + tokenEndpoint = meta.TokenEndpoint |
| 118 | + if tokenEndpoint == "" { |
| 119 | + return fmt.Errorf("token_endpoint not found in authorization server metadata") |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + creds := h.config.Credentials |
| 124 | + cfg := &clientcredentials.Config{ |
| 125 | + ClientID: creds.ClientID, |
| 126 | + ClientSecret: creds.ClientSecretAuth.ClientSecret, |
| 127 | + TokenURL: tokenEndpoint, |
| 128 | + Scopes: h.config.Scopes, |
| 129 | + } |
| 130 | + |
| 131 | + ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, httpClient) |
| 132 | + h.tokenSource = cfg.TokenSource(ctxWithClient) |
| 133 | + |
| 134 | + // Eagerly fetch a token to surface errors immediately. |
| 135 | + if _, err := h.tokenSource.Token(); err != nil { |
| 136 | + h.tokenSource = nil |
| 137 | + return fmt.Errorf("client credentials token request failed: %w", err) |
| 138 | + } |
| 139 | + return nil |
| 140 | +} |
| 141 | + |
| 142 | +// AuthStyle returns the recommended auth style based on a list of supported |
| 143 | +// token endpoint auth methods from the authorization server metadata. |
| 144 | +// Returns [oauth2.AuthStyleInHeader] (HTTP Basic) by default, which is the |
| 145 | +// recommended method per RFC 6749 Section 2.3.1. |
| 146 | +func AuthStyle(methods []string) oauth2.AuthStyle { |
| 147 | + for _, m := range methods { |
| 148 | + if strings.EqualFold(m, "client_secret_post") { |
| 149 | + return oauth2.AuthStyleInParams |
| 150 | + } |
| 151 | + } |
| 152 | + return oauth2.AuthStyleInHeader |
| 153 | +} |
0 commit comments