| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
type ClientIDMetadataDocumentConfig struct { |
| 28 |
|
| 29 |
|
| 30 |
URL string |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
type DynamicClientRegistrationConfig struct { |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
Metadata *oauthex.ClientRegistrationMetadata |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
type AuthorizationResult struct { |
| 48 |
|
| 49 |
Code string |
| 50 |
|
| 51 |
State string |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
type AuthorizationArgs struct { |
| 56 |
|
| 57 |
URL string |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
type AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error) |
| 65 |
|
| 66 |
|
| 67 |
type AuthorizationCodeHandlerConfig struct { |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
ClientIDMetadataDocumentConfig *ClientIDMetadataDocumentConfig |
| 75 |
PreregisteredClient *oauthex.ClientCredentials |
| 76 |
DynamicClientRegistrationConfig *DynamicClientRegistrationConfig |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
RedirectURL string |
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
AuthorizationCodeFetcher AuthorizationCodeFetcher |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
Client *http.Client |
| 105 |
} |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
type AuthorizationCodeHandler struct { |
| 110 |
config *AuthorizationCodeHandlerConfig |
| 111 |
|
| 112 |
|
| 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 |
|
| 123 |
|
| 124 |
|
| 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 |
|
| 167 |
|
| 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 |
|
| 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 |
|
| 215 |
|
| 216 |
|
| 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 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 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 |
|
| 246 |
|
| 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 |
|
| 282 |
return err |
| 283 |
} |
| 284 |
|
| 285 |
return h.exchangeAuthorizationCode(ctx, cfg, authRes, prm.Resource) |
| 286 |
} |
| 287 |
|
| 288 |
|
| 289 |
|
| 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 |
|
| 300 |
|
| 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 |
|
| 311 |
|
| 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 |
|
| 322 |
|
| 323 |
|
| 324 |
func (h *AuthorizationCodeHandler) getProtectedResourceMetadata(ctx context.Context, wwwChallenges []oauthex.Challenge, mcpServerURL string) (*oauthex.ProtectedResourceMetadata, error) { |
| 325 |
|
| 326 |
|
| 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 |
|
| 337 |
return nil, fmt.Errorf("protected resource metadata has no authorization servers specified") |
| 338 |
} |
| 339 |
return prm, nil |
| 340 |
} |
| 341 |
|
| 342 |
|
| 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 |
|
| 357 |
URL string |
| 358 |
|
| 359 |
|
| 360 |
Resource string |
| 361 |
} |
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 432 |
return oauth2.AuthStyleInParams |
| 433 |
default: |
| 434 |
|
| 435 |
return oauth2.AuthStyleInHeader |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
func (h *AuthorizationCodeHandler) handleRegistration(ctx context.Context, asm *oauthex.AuthServerMeta) (*resolvedClientConfig, error) { |
| 448 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 492 |
|
| 493 |
usedCodeVerifier string |
| 494 |
} |
| 495 |
|
| 496 |
|
| 497 |
|
| 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 |
|
| 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 |
|
| 522 |
|
| 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 |
} |