Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/auth/authorization_code.go

raw symbols SCIP
1 // Copyright 2026 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by the license
3 // that can be found in the LICENSE file.
4
5 package auth
6
7 import (
8 "context"
9 "crypto/rand"
10 "errors"
11 "fmt"
12 "io"
13 "net/http"
14 "net/url"
15 "slices"
16 "strings"
17
18 "github.com/modelcontextprotocol/go-sdk/internal/util"
19 "github.com/modelcontextprotocol/go-sdk/oauthex"
20 "golang.org/x/oauth2"
21 )
22
23 // ClientIDMetadataDocumentConfig is used to configure the Client ID Metadata Document
24 // based client registration per
25 // https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#client-id-metadata-documents.
26 // See https://client.dev/ for more information.
27 type ClientIDMetadataDocumentConfig struct {
28 // URL is the client identifier URL as per
29 // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00#section-3.
30 URL string
31 }
32
33 // DynamicClientRegistrationConfig is used to configure dynamic client registration per
34 // https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#dynamic-client-registration.
35 type DynamicClientRegistrationConfig struct {
36 // Metadata to be used in dynamic client registration request as per
37 // https://datatracker.ietf.org/doc/html/rfc7591#section-2.
38 //
39 // If Metadata.ApplicationType is empty, it will be inferred from
40 // Metadata.RedirectURIs. When set, it will be validated against the inferred type
41 // and an error will be returned if they conflict.
42 Metadata *oauthex.ClientRegistrationMetadata
43 }
44
45 // AuthorizationResult is the result of an authorization flow.
46 // It is returned by [AuthorizationCodeHandler].AuthorizationCodeFetcher implementations.
47 type AuthorizationResult struct {
48 // Code is the authorization code obtained from the authorization server.
49 Code string
50 // State string returned by the authorization server.
51 State string
52 }
53
54 // AuthorizationArgs is the input to [AuthorizationCodeFetcher].
55 type AuthorizationArgs struct {
56 // Authorization URL to be opened in a browser for the user to start the authorization process.
57 URL string
58 }
59
60 // AuthorizationCodeFetcher is called to initiate the OAuth authorization flow.
61 // It is responsible for directing the user to the authorization URL (e.g., opening
62 // in a browser) and returning the authorization code and state once the Authorization
63 // Server redirects back to the configured RedirectURL.
64 type AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error)
65
66 // AuthorizationCodeHandlerConfig is the configuration for [AuthorizationCodeHandler].
67 type AuthorizationCodeHandlerConfig struct {
68 // Client registration configuration.
69 // It is attempted in the following order:
70 // 1. Client ID Metadata Document
71 // 2. Preregistration
72 // 3. Dynamic Client Registration
73 // At least one method must be configured.
74 ClientIDMetadataDocumentConfig *ClientIDMetadataDocumentConfig
75 PreregisteredClient *oauthex.ClientCredentials
76 DynamicClientRegistrationConfig *DynamicClientRegistrationConfig
77
78 // RedirectURL is a required URL to redirect to after authorization.
79 // The caller is responsible for handling the redirect out of band.
80 //
81 // If Dynamic Client Registration is used:
82 // - this field is permitted to be empty, in which case it will be set
83 // to the first redirect URI from
84 // DynamicClientRegistrationConfig.Metadata.RedirectURIs.
85 // - if the field is not empty, it must be one of the redirect URIs in
86 // DynamicClientRegistrationConfig.Metadata.RedirectURIs.
87 RedirectURL string
88
89 // AuthorizationCodeFetcher is a required function called to initiate the authorization flow.
90 // See [AuthorizationCodeFetcher] for details.
91 AuthorizationCodeFetcher AuthorizationCodeFetcher
92
93 // Client is an optional HTTP client to use for HTTP requests.
94 // It is used for the following requests:
95 // - Fetching Protected Resource Metadata
96 // - Fetching Authorization Server Metadata
97 // - Registering a client dynamically
98 // - Exchanging an authorization code for an access token
99 // - Refreshing an access token
100 // Custom clients can include additional security configurations,
101 // such as SSRF protections, see
102 // https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices#server-side-request-forgery-ssrf
103 // If not provided, http.DefaultClient will be used.
104 Client *http.Client
105 }
106
107 // AuthorizationCodeHandler is an implementation of [OAuthHandler] that uses
108 // the authorization code flow to obtain access tokens.
109 type AuthorizationCodeHandler struct {
110 config *AuthorizationCodeHandlerConfig
111
112 // tokenSource is the token source to use for authorization.
113 tokenSource oauth2.TokenSource
114 }
115
116 var _ OAuthHandler = (*AuthorizationCodeHandler)(nil)
117
118 func (h *AuthorizationCodeHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {
119 return h.tokenSource, nil
120 }
121
122 // NewAuthorizationCodeHandler creates a new AuthorizationCodeHandler.
123 // It performs validation of the configuration and returns an error if it is invalid.
124 // The passed config is consumed by the handler and should not be modified after.
125 func NewAuthorizationCodeHandler(config *AuthorizationCodeHandlerConfig) (*AuthorizationCodeHandler, error) {
126 if config == nil {
127 return nil, errors.New("config must be provided")
128 }
129 if config.ClientIDMetadataDocumentConfig == nil &&
130 config.PreregisteredClient == nil &&
131 config.DynamicClientRegistrationConfig == nil {
132 return nil, errors.New("at least one client registration configuration must be provided")
133 }
134 if config.AuthorizationCodeFetcher == nil {
135 return nil, errors.New("AuthorizationCodeFetcher is required")
136 }
137 if config.ClientIDMetadataDocumentConfig != nil && !isNonRootHTTPSURL(config.ClientIDMetadataDocumentConfig.URL) {
138 return nil, fmt.Errorf("client ID metadata document URL must be a non-root HTTPS URL")
139 }
140 if config.PreregisteredClient != nil {
141 if err := config.PreregisteredClient.Validate(); err != nil {
142 return nil, fmt.Errorf("invalid PreregisteredClient configuration: %w", err)
143 }
144 }
145 dCfg := config.DynamicClientRegistrationConfig
146 if dCfg != nil {
147 if dCfg.Metadata == nil {
148 return nil, errors.New("dynamic client registration requires non-nil Metadata")
149 }
150 if len(dCfg.Metadata.RedirectURIs) == 0 {
151 return nil, errors.New("Metadata.RedirectURIs is required for dynamic client registration")
152 }
153 if config.RedirectURL == "" {
154 config.RedirectURL = dCfg.Metadata.RedirectURIs[0]
155 } else if !slices.Contains(dCfg.Metadata.RedirectURIs, config.RedirectURL) {
156 return nil, fmt.Errorf("RedirectURL %q is not in the list of allowed redirect URIs for dynamic client registration", config.RedirectURL)
157 }
158 applicationType := inferApplicationType(dCfg.Metadata.RedirectURIs)
159 if dCfg.Metadata.ApplicationType == "" {
160 dCfg.Metadata.ApplicationType = applicationType
161 } else if dCfg.Metadata.ApplicationType != applicationType {
162 return nil, fmt.Errorf("application type %q conflicts with the application type inferred from redirect URIs", dCfg.Metadata.ApplicationType)
163 }
164 }
165 if config.RedirectURL == "" {
166 // If the RedirectURL was supposed to be set by the dynamic client registration,
167 // it should have been set by now. Otherwise, it is required.
168 return nil, errors.New("RedirectURL is required")
169 }
170 if config.Client == nil {
171 config.Client = http.DefaultClient
172 }
173 return &AuthorizationCodeHandler{config: config}, nil
174 }
175
176 func isNonRootHTTPSURL(u string) bool {
177 pu, err := url.Parse(u)
178 if err != nil {
179 return false
180 }
181 return pu.Scheme == "https" && pu.Path != ""
182 }
183
184 // inferApplicationType returns an application type based on the redirect URIs.
185 func inferApplicationType(redirectURIs []string) string {
186 hasNative := false
187 hasWeb := false
188 for _, uri := range redirectURIs {
189 u, err := url.Parse(uri)
190 if err != nil {
191 return ""
192 }
193 switch u.Scheme {
194 case "http", "https":
195 if util.IsLoopback(u.Hostname()) {
196 hasNative = true
197 } else {
198 hasWeb = true
199 }
200 default:
201 hasNative = true
202 }
203 }
204
205 if hasNative && hasWeb {
206 return ""
207 }
208 if hasNative {
209 return "native"
210 }
211 return "web"
212 }
213
214 // Authorize performs the authorization flow.
215 // It is designed to perform the whole Authorization Code Grant flow.
216 // On success, [AuthorizationCodeHandler.TokenSource] will return a token source with the fetched token.
217 func (h *AuthorizationCodeHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error {
218 defer resp.Body.Close()
219 defer io.Copy(io.Discard, resp.Body)
220
221 wwwChallenges, err := oauthex.ParseWWWAuthenticate(resp.Header[http.CanonicalHeaderKey("WWW-Authenticate")])
222 if err != nil {
223 return fmt.Errorf("failed to parse WWW-Authenticate header: %v", err)
224 }
225
226 if resp.StatusCode == http.StatusForbidden && errorFromChallenges(wwwChallenges) != "insufficient_scope" {
227 // We only want to perform step-up authorization for insufficient_scope errors.
228 // Returning nil, so that the call is retried immediately and the response
229 // is handled appropriately by the connection.
230 // Step-up authorization is defined at
231 // https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#step-up-authorization-flow
232 return nil
233 }
234
235 prm, err := h.getProtectedResourceMetadata(ctx, wwwChallenges, req.URL.String())
236 if err != nil {
237 return err
238 }
239
240 asm, err := GetAuthServerMetadata(ctx, prm.AuthorizationServers[0], h.config.Client)
241 if err != nil {
242 return fmt.Errorf("failed to get authorization server metadata: %w", err)
243 }
244 if asm == nil {
245 // Fallback to 2025-03-26 spec: predefined endpoints.
246 // https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#fallbacks-for-servers-without-metadata-discovery
247 authServerURL := prm.AuthorizationServers[0]
248 asm = &oauthex.AuthServerMeta{
249 Issuer: authServerURL,
250 AuthorizationEndpoint: authServerURL + "/authorize",
251 TokenEndpoint: authServerURL + "/token",
252 RegistrationEndpoint: authServerURL + "/register",
253 }
254 }
255
256 resolvedClientConfig, err := h.handleRegistration(ctx, asm)
257 if err != nil {
258 return err
259 }
260
261 scps := scopesFromChallenges(wwwChallenges)
262 if len(scps) == 0 && len(prm.ScopesSupported) > 0 {
263 scps = prm.ScopesSupported
264 }
265
266 cfg := &oauth2.Config{
267 ClientID: resolvedClientConfig.clientID,
268 ClientSecret: resolvedClientConfig.clientSecret,
269
270 Endpoint: oauth2.Endpoint{
271 AuthURL: asm.AuthorizationEndpoint,
272 TokenURL: asm.TokenEndpoint,
273 AuthStyle: resolvedClientConfig.authStyle,
274 },
275 RedirectURL: h.config.RedirectURL,
276 Scopes: scps,
277 }
278
279 authRes, err := h.getAuthorizationCode(ctx, cfg, prm.Resource)
280 if err != nil {
281 // Purposefully leaving the error unwrappable so it can be handled by the caller.
282 return err
283 }
284
285 return h.exchangeAuthorizationCode(ctx, cfg, authRes, prm.Resource)
286 }
287
288 // resourceMetadataURLFromChallenges returns a resource metadata URL from the given "WWW-Authenticate" header challenges,
289 // or the empty string if there is none.
290 func resourceMetadataURLFromChallenges(cs []oauthex.Challenge) string {
291 for _, c := range cs {
292 if u := c.Params["resource_metadata"]; u != "" {
293 return u
294 }
295 }
296 return ""
297 }
298
299 // scopesFromChallenges returns the scopes from the given "WWW-Authenticate" header challenges.
300 // It only looks at challenges with the "Bearer" scheme.
301 func scopesFromChallenges(cs []oauthex.Challenge) []string {
302 for _, c := range cs {
303 if c.Scheme == "bearer" && c.Params["scope"] != "" {
304 return strings.Fields(c.Params["scope"])
305 }
306 }
307 return nil
308 }
309
310 // errorFromChallenges returns the error from the given "WWW-Authenticate" header challenges.
311 // It only looks at challenges with the "Bearer" scheme.
312 func errorFromChallenges(cs []oauthex.Challenge) string {
313 for _, c := range cs {
314 if c.Scheme == "bearer" && c.Params["error"] != "" {
315 return c.Params["error"]
316 }
317 }
318 return ""
319 }
320
321 // getProtectedResourceMetadata returns the protected resource metadata.
322 // If no metadata was found or the fetched metadata fails security checks,
323 // it returns an error.
324 func (h *AuthorizationCodeHandler) getProtectedResourceMetadata(ctx context.Context, wwwChallenges []oauthex.Challenge, mcpServerURL string) (*oauthex.ProtectedResourceMetadata, error) {
325 // Use MCP server URL as the resource URI per
326 // https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#canonical-server-uri.
327 for _, url := range protectedResourceMetadataURLs(resourceMetadataURLFromChallenges(wwwChallenges), mcpServerURL) {
328 prm, err := oauthex.GetProtectedResourceMetadata(ctx, url.URL, url.Resource, h.config.Client)
329 if err != nil {
330 continue
331 }
332 if prm == nil {
333 continue
334 }
335 if len(prm.AuthorizationServers) == 0 {
336 // If we found PRM, we enforce the 2025-11-25 spec and not search further.
337 return nil, fmt.Errorf("protected resource metadata has no authorization servers specified")
338 }
339 return prm, nil
340 }
341 // Fallback to 2025-03-26 spec MCP server root is the Authorization Server:
342 // https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#server-metadata-discovery
343 u, err := url.Parse(mcpServerURL)
344 if err != nil {
345 return nil, fmt.Errorf("failed to parse MCP server URL: %v", err)
346 }
347 u.Path = ""
348 prm := &oauthex.ProtectedResourceMetadata{
349 AuthorizationServers: []string{u.String()},
350 Resource: mcpServerURL,
351 }
352 return prm, nil
353 }
354
355 type prmURL struct {
356 // URL represents a URL where Protected Resource Metadata may be retrieved.
357 URL string
358 // Resource represents the corresponding resource URL for [URL].
359 // It is required to perform validation described in RFC 9728, section 3.3.
360 Resource string
361 }
362
363 // protectedResourceMetadataURLs returns a list of URLs to try when looking for
364 // protected resource metadata as mandated by the MCP specification:
365 // https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#protected-resource-metadata-discovery-requirements
366 func protectedResourceMetadataURLs(metadataURL, resourceURL string) []prmURL {
367 var urls []prmURL
368 if metadataURL != "" {
369 urls = append(urls, prmURL{
370 URL: metadataURL,
371 Resource: resourceURL,
372 })
373 }
374 ru, err := url.Parse(resourceURL)
375 if err != nil {
376 return urls
377 }
378 mu := *ru
379 // "At the path of the server's MCP endpoint".
380 mu.Path = "/.well-known/oauth-protected-resource/" + strings.TrimLeft(ru.Path, "/")
381 urls = append(urls, prmURL{
382 URL: mu.String(),
383 Resource: resourceURL,
384 })
385 // "At the root".
386 mu.Path = "/.well-known/oauth-protected-resource"
387 ru.Path = ""
388 urls = append(urls, prmURL{
389 URL: mu.String(),
390 Resource: ru.String(),
391 })
392 return urls
393 }
394
395 type registrationType int
396
397 const (
398 registrationTypeClientIDMetadataDocument registrationType = iota
399 registrationTypePreregistered
400 registrationTypeDynamic
401 )
402
403 type resolvedClientConfig struct {
404 registrationType registrationType
405 clientID string
406 clientSecret string
407 authStyle oauth2.AuthStyle
408 }
409
410 func selectTokenAuthMethod(supported []string) oauth2.AuthStyle {
411 prefOrder := []string{
412 // Preferred in OAuth 2.1 draft: https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-14.html#name-client-secret.
413 "client_secret_post",
414 "client_secret_basic",
415 }
416 for _, method := range prefOrder {
417 if slices.Contains(supported, method) {
418 return authMethodToStyle(method)
419 }
420 }
421 return oauth2.AuthStyleAutoDetect
422 }
423
424 func authMethodToStyle(method string) oauth2.AuthStyle {
425 switch method {
426 case "client_secret_post":
427 return oauth2.AuthStyleInParams
428 case "client_secret_basic":
429 return oauth2.AuthStyleInHeader
430 case "none":
431 // "none" is equivalent to "client_secret_post" but without sending client secret.
432 return oauth2.AuthStyleInParams
433 default:
434 // "client_secret_basic" is the default per https://datatracker.ietf.org/doc/html/rfc7591#section-2.
435 return oauth2.AuthStyleInHeader
436 }
437 }
438
439 // handleRegistration handles client registration.
440 // The provided authorization server metadata must be non-nil.
441 // Support for different registration methods is defined as follows:
442 // - Client ID Metadata Document: metadata must have
443 // `ClientIDMetadataDocumentSupported` set to true.
444 // - Pre-registered client: assumed to be supported.
445 // - Dynamic client registration: metadata must have
446 // `RegistrationEndpoint` set to a non-empty value.
447 func (h *AuthorizationCodeHandler) handleRegistration(ctx context.Context, asm *oauthex.AuthServerMeta) (*resolvedClientConfig, error) {
448 // 1. Attempt to use Client ID Metadata Document (SEP-991).
449 cimdCfg := h.config.ClientIDMetadataDocumentConfig
450 if cimdCfg != nil && asm.ClientIDMetadataDocumentSupported {
451 return &resolvedClientConfig{
452 registrationType: registrationTypeClientIDMetadataDocument,
453 clientID: cimdCfg.URL,
454 }, nil
455 }
456 // 2. Attempt to use pre-registered client configuration.
457 preCfg := h.config.PreregisteredClient
458 if preCfg != nil {
459 authStyle := selectTokenAuthMethod(asm.TokenEndpointAuthMethodsSupported)
460 clientSecret := ""
461 if preCfg.ClientSecretAuth != nil {
462 clientSecret = preCfg.ClientSecretAuth.ClientSecret
463 }
464 return &resolvedClientConfig{
465 registrationType: registrationTypePreregistered,
466 clientID: preCfg.ClientID,
467 clientSecret: clientSecret,
468 authStyle: authStyle,
469 }, nil
470 }
471 // 3. Attempt to use dynamic client registration.
472 dcrCfg := h.config.DynamicClientRegistrationConfig
473 if dcrCfg != nil && asm.RegistrationEndpoint != "" {
474 regResp, err := oauthex.RegisterClient(ctx, asm.RegistrationEndpoint, dcrCfg.Metadata, h.config.Client)
475 if err != nil {
476 return nil, fmt.Errorf("failed to register client: %w", err)
477 }
478 cfg := &resolvedClientConfig{
479 registrationType: registrationTypeDynamic,
480 clientID: regResp.ClientID,
481 clientSecret: regResp.ClientSecret,
482 authStyle: authMethodToStyle(regResp.TokenEndpointAuthMethod),
483 }
484 return cfg, nil
485 }
486 return nil, fmt.Errorf("no configured client registration methods are supported by the authorization server")
487 }
488
489 type authResult struct {
490 *AuthorizationResult
491 // usedCodeVerifier is the PKCE code verifier used to obtain the authorization code.
492 // It is preserved for the token exchange step.
493 usedCodeVerifier string
494 }
495
496 // getAuthorizationCode uses the [AuthorizationCodeHandler.AuthorizationCodeFetcher]
497 // to obtain an authorization code.
498 func (h *AuthorizationCodeHandler) getAuthorizationCode(ctx context.Context, cfg *oauth2.Config, resourceURL string) (*authResult, error) {
499 codeVerifier := oauth2.GenerateVerifier()
500 state := rand.Text()
501
502 authURL := cfg.AuthCodeURL(state,
503 oauth2.S256ChallengeOption(codeVerifier),
504 oauth2.SetAuthURLParam("resource", resourceURL),
505 )
506
507 authRes, err := h.config.AuthorizationCodeFetcher(ctx, &AuthorizationArgs{URL: authURL})
508 if err != nil {
509 // Purposefully leaving the error unwrappable so it can be handled by the caller.
510 return nil, err
511 }
512 if authRes.State != state {
513 return nil, fmt.Errorf("state mismatch")
514 }
515 return &authResult{
516 AuthorizationResult: authRes,
517 usedCodeVerifier: codeVerifier,
518 }, nil
519 }
520
521 // exchangeAuthorizationCode exchanges the authorization code for a token
522 // and stores it in a token source.
523 func (h *AuthorizationCodeHandler) exchangeAuthorizationCode(ctx context.Context, cfg *oauth2.Config, authResult *authResult, resourceURL string) error {
524 opts := []oauth2.AuthCodeOption{
525 oauth2.VerifierOption(authResult.usedCodeVerifier),
526 oauth2.SetAuthURLParam("resource", resourceURL),
527 }
528 clientCtx := context.WithValue(ctx, oauth2.HTTPClient, h.config.Client)
529 token, err := cfg.Exchange(clientCtx, authResult.Code, opts...)
530 if err != nil {
531 return fmt.Errorf("token exchange failed: %w", err)
532 }
533 h.tokenSource = cfg.TokenSource(clientCtx, token)
534 return nil
535 }