diff --git a/auth/authorization_code.go b/auth/authorization_code.go index ac51ea12..bc80a859 100644 --- a/auth/authorization_code.go +++ b/auth/authorization_code.go @@ -11,6 +11,7 @@ import ( "crypto/rand" "errors" "fmt" + "io" "net/http" "net/url" "slices" @@ -198,6 +199,7 @@ func isNonRootHTTPSURL(u string) bool { // On success, [AuthorizationCodeHandler.TokenSource] will return a token source with the fetched token. func (h *AuthorizationCodeHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error { defer resp.Body.Close() + defer io.Copy(io.Discard, resp.Body) wwwChallenges, err := oauthex.ParseWWWAuthenticate(resp.Header[http.CanonicalHeaderKey("WWW-Authenticate")]) if err != nil { @@ -395,40 +397,6 @@ func (h *AuthorizationCodeHandler) getAuthServerMetadata(ctx context.Context, pr return asm, nil } -// authorizationServerMetadataURLs returns a list of URLs to try when looking for -// authorization server metadata as mandated by the MCP specification: -// https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#authorization-server-metadata-discovery. -func authorizationServerMetadataURLs(issuerURL string) []string { - var urls []string - - baseURL, err := url.Parse(issuerURL) - if err != nil { - return nil - } - - if baseURL.Path == "" { - // "OAuth 2.0 Authorization Server Metadata". - baseURL.Path = "/.well-known/oauth-authorization-server" - urls = append(urls, baseURL.String()) - // "OpenID Connect Discovery 1.0". - baseURL.Path = "/.well-known/openid-configuration" - urls = append(urls, baseURL.String()) - return urls - } - - originalPath := baseURL.Path - // "OAuth 2.0 Authorization Server Metadata with path insertion". - baseURL.Path = "/.well-known/oauth-authorization-server/" + strings.TrimLeft(originalPath, "/") - urls = append(urls, baseURL.String()) - // "OpenID Connect Discovery 1.0 with path insertion". - baseURL.Path = "/.well-known/openid-configuration/" + strings.TrimLeft(originalPath, "/") - urls = append(urls, baseURL.String()) - // "OpenID Connect Discovery 1.0 with path appending". - baseURL.Path = "/" + strings.Trim(originalPath, "/") + "/.well-known/openid-configuration" - urls = append(urls, baseURL.String()) - return urls -} - type registrationType int const ( diff --git a/auth/client.go b/auth/client.go index 0af6963f..778a2cd0 100644 --- a/auth/client.go +++ b/auth/client.go @@ -40,3 +40,10 @@ type OAuthHandler interface { // The function is responsible for closing the response body. Authorize(context.Context, *http.Request, *http.Response) error } + +// OAuthHandlerBase is an embeddable type that satisfies the private method +// requirement of [OAuthHandler]. Extension packages should embed this type +// in their handler structs to implement OAuthHandler. +type OAuthHandlerBase struct{} + +func (OAuthHandlerBase) isOAuthHandler() {} diff --git a/auth/extauth/enterprise_handler.go b/auth/extauth/enterprise_handler.go new file mode 100644 index 00000000..11c7c8e0 --- /dev/null +++ b/auth/extauth/enterprise_handler.go @@ -0,0 +1,243 @@ +// Copyright 2026 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 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 ( + "context" + "errors" + "fmt" + "io" + "net/http" + + "github.com/modelcontextprotocol/go-sdk/auth" + "github.com/modelcontextprotocol/go-sdk/oauthex" + "golang.org/x/oauth2" +) + +// grantTypeJWTBearer is the grant type for RFC 7523 JWT Bearer authorization grant. +const grantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" + +// IDTokenResult contains the ID token obtained from OIDC login. +type IDTokenResult struct { + // Token is the OpenID Connect ID Token (JWT). + Token string +} + +// IDTokenFetcher is called to obtain an ID Token from the enterprise IdP. +// This is typically done via OIDC login flow where the user authenticates +// with their enterprise identity provider. +type IDTokenFetcher func(ctx context.Context) (*IDTokenResult, error) + +// EnterpriseHandlerConfig is the configuration for [EnterpriseHandler]. +type EnterpriseHandlerConfig struct { + // IdP configuration (where the user authenticates) + + // IdPIssuerURL is the enterprise IdP's issuer URL (e.g., "https://acme.okta.com"). + // Used for OIDC discovery to find the token endpoint. + // REQUIRED. + IdPIssuerURL string + + // IdPClientID is the MCP Client's ID registered at the IdP. + // OPTIONAL. Required if the IdP requires client authentication for token exchange. + IdPClientID string + + // IdPClientSecret is the MCP Client's secret registered at the IdP. + // OPTIONAL. Required if the IdP requires client authentication for token exchange. + IdPClientSecret string + + // MCP Server configuration (the resource being accessed) + + // MCPAuthServerURL is the MCP Server's authorization server issuer URL. + // Used as the audience for token exchange and for metadata discovery. + // REQUIRED. + MCPAuthServerURL string + + // MCPResourceURI is the MCP Server's resource identifier (RFC 9728). + // Used as the resource parameter in token exchange. + // REQUIRED. + MCPResourceURI string + + // MCPClientID is the MCP Client's ID registered at the MCP Server. + // OPTIONAL. Required if the MCP Server requires client authentication. + MCPClientID string + + // MCPClientSecret is the MCP Client's secret registered at the MCP Server. + // OPTIONAL. Required if the MCP Server requires client authentication. + MCPClientSecret string + + // MCPScopes is the list of scopes to request at the MCP Server. + // OPTIONAL. + MCPScopes []string + + // IDTokenFetcher is called to obtain an ID Token when authorization is needed. + // The implementation should handle the OIDC login flow (e.g., browser redirect, + // callback handling) and return the ID token. + // REQUIRED. + IDTokenFetcher IDTokenFetcher + + // HTTPClient is an optional HTTP client for customization. + // If nil, http.DefaultClient is used. + // OPTIONAL. + HTTPClient *http.Client +} + +// EnterpriseHandler is an implementation of [auth.OAuthHandler] that uses +// Enterprise Managed Authorization (SEP-990) to obtain access tokens. +// +// The flow consists of: +// 1. OIDC Login: User authenticates with enterprise IdP → ID Token +// 2. Token Exchange (RFC 8693): ID Token → ID-JAG at IdP +// 3. JWT Bearer Grant (RFC 7523): ID-JAG → Access Token at MCP Server +type EnterpriseHandler struct { + auth.OAuthHandlerBase + config *EnterpriseHandlerConfig + + // tokenSource is the token source obtained after authorization. + tokenSource oauth2.TokenSource +} + +// Compile-time check that EnterpriseHandler implements auth.OAuthHandler. +var _ auth.OAuthHandler = (*EnterpriseHandler)(nil) + +// NewEnterpriseHandler creates a new EnterpriseHandler. +// It performs validation of the configuration and returns an error if invalid. +func NewEnterpriseHandler(config *EnterpriseHandlerConfig) (*EnterpriseHandler, error) { + if config == nil { + return nil, errors.New("config must be provided") + } + if config.IdPIssuerURL == "" { + return nil, errors.New("IdPIssuerURL is required") + } + if config.MCPAuthServerURL == "" { + return nil, errors.New("MCPAuthServerURL is required") + } + if config.MCPResourceURI == "" { + return nil, errors.New("MCPResourceURI is required") + } + if config.IDTokenFetcher == nil { + return nil, errors.New("IDTokenFetcher is required") + } + return &EnterpriseHandler{config: config}, nil +} + +// TokenSource returns the token source for outgoing requests. +// Returns nil if authorization has not been performed yet. +func (h *EnterpriseHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) { + return h.tokenSource, nil +} + +// Authorize performs the Enterprise Managed Authorization flow. +// It is called when a request fails with 401 or 403. +func (h *EnterpriseHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error { + defer resp.Body.Close() + defer io.Copy(io.Discard, resp.Body) + + httpClient := h.config.HTTPClient + if httpClient == nil { + httpClient = http.DefaultClient + } + + // Step 1: Get ID Token via the configured fetcher (e.g., OIDC login) + idTokenResult, err := h.config.IDTokenFetcher(ctx) + if err != nil { + return fmt.Errorf("failed to obtain ID token: %w", err) + } + + // Step 2: Discover IdP token endpoint via OIDC discovery + idpMeta, err := auth.GetAuthServerMetadata(ctx, h.config.IdPIssuerURL, httpClient) + if err != nil { + return fmt.Errorf("failed to discover IdP metadata: %w", err) + } + + // Step 3: Token Exchange (ID Token → ID-JAG) + tokenExchangeReq := &oauthex.TokenExchangeRequest{ + RequestedTokenType: oauthex.TokenTypeIDJAG, + Audience: h.config.MCPAuthServerURL, + Resource: h.config.MCPResourceURI, + Scope: h.config.MCPScopes, + SubjectToken: idTokenResult.Token, + SubjectTokenType: oauthex.TokenTypeIDToken, + } + + tokenExchangeResp, err := oauthex.ExchangeToken( + ctx, + idpMeta.TokenEndpoint, + tokenExchangeReq, + &oauthex.ClientCredentials{ + ClientID: h.config.IdPClientID, + ClientSecret: h.config.IdPClientSecret, + }, + httpClient, + ) + if err != nil { + return fmt.Errorf("token exchange failed: %w", err) + } + + // Step 4: Discover MCP Server token endpoint + mcpMeta, err := auth.GetAuthServerMetadata(ctx, h.config.MCPAuthServerURL, httpClient) + if err != nil { + return fmt.Errorf("failed to discover MCP auth server metadata: %w", err) + } + + // Step 5: JWT Bearer Grant (ID-JAG → Access Token) + accessToken, err := exchangeJWTBearer( + ctx, + mcpMeta.TokenEndpoint, + tokenExchangeResp.AccessToken, + &oauthex.ClientCredentials{ + ClientID: h.config.MCPClientID, + ClientSecret: h.config.MCPClientSecret, + }, + httpClient, + ) + if err != nil { + return fmt.Errorf("JWT bearer grant failed: %w", err) + } + + // Store the token source for subsequent requests + h.tokenSource = oauth2.StaticTokenSource(accessToken) + return nil +} + +// exchangeJWTBearer exchanges an Identity Assertion JWT Authorization Grant (ID-JAG) +// for an access token using JWT Bearer Grant per RFC 7523. +func exchangeJWTBearer( + ctx context.Context, + tokenEndpoint string, + assertion string, + clientCreds *oauthex.ClientCredentials, + httpClient *http.Client, +) (*oauth2.Token, error) { + cfg := &oauth2.Config{ + ClientID: clientCreds.ClientID, + ClientSecret: clientCreds.ClientSecret, + Endpoint: oauth2.Endpoint{ + TokenURL: tokenEndpoint, + AuthStyle: oauth2.AuthStyleInParams, + }, + } + + if httpClient == nil { + httpClient = http.DefaultClient + } + ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, httpClient) + + token, err := cfg.Exchange( + ctxWithClient, + "", + oauth2.SetAuthURLParam("grant_type", grantTypeJWTBearer), + oauth2.SetAuthURLParam("assertion", assertion), + ) + if err != nil { + return nil, fmt.Errorf("JWT bearer grant request failed: %w", err) + } + + return token, nil +} diff --git a/auth/extauth/oidc_login.go b/auth/extauth/oidc_login.go new file mode 100644 index 00000000..e738de40 --- /dev/null +++ b/auth/extauth/oidc_login.go @@ -0,0 +1,253 @@ +// Copyright 2026 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 OIDC Authorization Code flow for obtaining ID tokens +// 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 ( + "context" + "crypto/rand" + "fmt" + "net/http" + + "github.com/modelcontextprotocol/go-sdk/auth" + "github.com/modelcontextprotocol/go-sdk/oauthex" + "golang.org/x/oauth2" +) + +// OIDCLoginConfig configures the OIDC Authorization Code flow for obtaining +// an ID Token. This is used with [PerformOIDCLogin] to authenticate users +// with an enterprise IdP before calling the Enterprise Managed Authorization flow. +type OIDCLoginConfig struct { + // IssuerURL is the IdP's issuer URL (e.g., "https://acme.okta.com"). + // REQUIRED. + IssuerURL string + // ClientID is the MCP Client's ID registered at the IdP. + // REQUIRED. + ClientID string + // ClientSecret is the MCP Client's secret at the IdP. + // OPTIONAL. Only required if the client is confidential. + ClientSecret string + // RedirectURL is the OAuth2 redirect URI registered with the IdP. + // This must match exactly what was registered with the IdP. + // REQUIRED. + RedirectURL string + // Scopes are the OAuth2/OIDC scopes to request. + // "openid" is REQUIRED for OIDC. Common values: ["openid", "profile", "email"] + // REQUIRED. + Scopes []string + // LoginHint is a hint to the IdP about the user's identity. + // Some IdPs may require this (e.g., as an email address for routing to SSO providers). + // Example: "user@example.com" + // OPTIONAL. + LoginHint string + // HTTPClient is the HTTP client for making requests. + // If nil, http.DefaultClient is used. + // OPTIONAL. + HTTPClient *http.Client +} + +// OIDCTokenResponse contains the tokens returned from a successful OIDC login. +type OIDCTokenResponse struct { + // IDToken is the OpenID Connect ID Token (JWT). + // This can be passed to EnterpriseHandler's IDTokenFetcher. + IDToken string + // AccessToken is the OAuth2 access token (if issued by IdP). + // This is typically not needed for SEP-990, but may be useful for other IdP APIs. + AccessToken string + // RefreshToken is the OAuth2 refresh token (if issued by IdP). + RefreshToken string + // TokenType is the token type (typically "Bearer"). + TokenType string + // ExpiresAt is when the ID token expires. + ExpiresAt int64 +} + +// AuthorizationCodeFetcher is a callback function that handles directing the user +// to the authorization URL and returning the authorization result. +// +// Implementations should: +// 1. Direct the user to args.URL (e.g., open in browser) +// 2. Wait for the IdP redirect to the configured RedirectURL +// 3. Extract the code and state from the redirect query parameters +// 4. Return them in auth.AuthorizationResult +// +// The implementation MUST verify that the returned state matches the state +// sent in the authorization request (available via parsing args.URL). +type AuthorizationCodeFetcher func(ctx context.Context, args auth.AuthorizationArgs) (*auth.AuthorizationResult, error) + +// PerformOIDCLogin performs the complete OIDC Authorization Code flow with PKCE +// in a single function call. This is the recommended approach for obtaining an +// ID Token for use with [EnterpriseHandler]. +// +// The authCodeFetcher callback handles the user interaction: +// - Directing the user to the IdP login page +// - Waiting for the redirect with the authorization code +// - Validating CSRF state and returning the result +func PerformOIDCLogin( + ctx context.Context, + config *OIDCLoginConfig, + authCodeFetcher AuthorizationCodeFetcher, +) (*OIDCTokenResponse, error) { + if authCodeFetcher == nil { + return nil, fmt.Errorf("authCodeFetcher is required") + } + + authReq, oauth2Config, err := initiateOIDCLogin(ctx, config) + if err != nil { + return nil, fmt.Errorf("failed to initiate OIDC login: %w", err) + } + + authResult, err := authCodeFetcher(ctx, auth.AuthorizationArgs{URL: authReq.authURL}) + if err != nil { + return nil, fmt.Errorf("failed to fetch authorization code: %w", err) + } + + if authResult.State != authReq.state { + return nil, fmt.Errorf("state mismatch: expected %q, got %q", authReq.state, authResult.State) + } + + tokens, err := completeOIDCLogin(ctx, config, oauth2Config, authResult.Code, authReq.codeVerifier) + if err != nil { + return nil, fmt.Errorf("failed to complete OIDC login: %w", err) + } + + return tokens, nil +} + +// oidcAuthorizationRequest holds internal state for OIDC authorization. +type oidcAuthorizationRequest struct { + authURL string + state string + codeVerifier string +} + +// initiateOIDCLogin initiates an OIDC Authorization Code flow with PKCE. +func initiateOIDCLogin( + ctx context.Context, + config *OIDCLoginConfig, +) (*oidcAuthorizationRequest, *oauth2.Config, error) { + if config == nil { + return nil, nil, fmt.Errorf("config is required") + } + if config.IssuerURL == "" { + return nil, nil, fmt.Errorf("IssuerURL is required") + } + if config.ClientID == "" { + return nil, nil, fmt.Errorf("ClientID is required") + } + if config.RedirectURL == "" { + return nil, nil, fmt.Errorf("RedirectURL is required") + } + if len(config.Scopes) == 0 { + return nil, nil, fmt.Errorf("Scopes is required (must include 'openid')") + } + + hasOpenID := false + for _, scope := range config.Scopes { + if scope == "openid" { + hasOpenID = true + break + } + } + if !hasOpenID { + return nil, nil, fmt.Errorf("Scopes must include 'openid' for OIDC") + } + + if err := oauthex.CheckURLScheme(config.IssuerURL); err != nil { + return nil, nil, fmt.Errorf("invalid IssuerURL: %w", err) + } + if err := oauthex.CheckURLScheme(config.RedirectURL); err != nil { + return nil, nil, fmt.Errorf("invalid RedirectURL: %w", err) + } + + httpClient := config.HTTPClient + if httpClient == nil { + httpClient = http.DefaultClient + } + meta, err := auth.GetAuthServerMetadata(ctx, config.IssuerURL, httpClient) + if err != nil { + return nil, nil, fmt.Errorf("failed to discover OIDC metadata: %w", err) + } + if meta.AuthorizationEndpoint == "" { + return nil, nil, fmt.Errorf("authorization_endpoint not found in OIDC metadata") + } + + codeVerifier := oauth2.GenerateVerifier() + state := rand.Text() + + oauth2Config := &oauth2.Config{ + ClientID: config.ClientID, + ClientSecret: config.ClientSecret, + RedirectURL: config.RedirectURL, + Scopes: config.Scopes, + Endpoint: oauth2.Endpoint{ + AuthURL: meta.AuthorizationEndpoint, + TokenURL: meta.TokenEndpoint, + }, + } + + authURLOpts := []oauth2.AuthCodeOption{ + oauth2.S256ChallengeOption(codeVerifier), + } + if config.LoginHint != "" { + authURLOpts = append(authURLOpts, oauth2.SetAuthURLParam("login_hint", config.LoginHint)) + } + authURL := oauth2Config.AuthCodeURL(state, authURLOpts...) + + return &oidcAuthorizationRequest{ + authURL: authURL, + state: state, + codeVerifier: codeVerifier, + }, oauth2Config, nil +} + +// completeOIDCLogin completes the OIDC Authorization Code flow by exchanging +// the authorization code for tokens. +func completeOIDCLogin( + ctx context.Context, + config *OIDCLoginConfig, + oauth2Config *oauth2.Config, + authCode string, + codeVerifier string, +) (*OIDCTokenResponse, error) { + if authCode == "" { + return nil, fmt.Errorf("authCode is required") + } + if codeVerifier == "" { + return nil, fmt.Errorf("codeVerifier is required") + } + + httpClient := config.HTTPClient + if httpClient == nil { + httpClient = http.DefaultClient + } + ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, httpClient) + + oauth2Token, err := oauth2Config.Exchange( + ctxWithClient, + authCode, + oauth2.VerifierOption(codeVerifier), + ) + if err != nil { + return nil, fmt.Errorf("token exchange failed: %w", err) + } + + idToken, ok := oauth2Token.Extra("id_token").(string) + if !ok || idToken == "" { + return nil, fmt.Errorf("id_token not found in token response") + } + return &OIDCTokenResponse{ + IDToken: idToken, + AccessToken: oauth2Token.AccessToken, + RefreshToken: oauth2Token.RefreshToken, + TokenType: oauth2Token.TokenType, + ExpiresAt: oauth2Token.Expiry.Unix(), + }, nil +} diff --git a/auth/extauth/oidc_login_test.go b/auth/extauth/oidc_login_test.go new file mode 100644 index 00000000..5645b457 --- /dev/null +++ b/auth/extauth/oidc_login_test.go @@ -0,0 +1,478 @@ +// Copyright 2026 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 extauth + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/modelcontextprotocol/go-sdk/auth" +) + +// TestInitiateOIDCLogin tests the OIDC authorization request generation. +func TestInitiateOIDCLogin(t *testing.T) { + // Create mock IdP server + idpServer := createMockOIDCServer(t) + defer idpServer.Close() + config := &OIDCLoginConfig{ + IssuerURL: idpServer.URL, + ClientID: "test-client", + RedirectURL: "http://localhost:8080/callback", + Scopes: []string{"openid", "profile", "email"}, + HTTPClient: idpServer.Client(), + } + t.Run("successful initiation", func(t *testing.T) { + authReq, _, err := initiateOIDCLogin(context.Background(), config) + if err != nil { + t.Fatalf("initiateOIDCLogin failed: %v", err) + } + // Validate authURL + if authReq.authURL == "" { + t.Error("authURL is empty") + } + // Parse and validate URL parameters + u, err := url.Parse(authReq.authURL) + if err != nil { + t.Fatalf("Failed to parse authURL: %v", err) + } + q := u.Query() + if q.Get("response_type") != "code" { + t.Errorf("expected response_type 'code', got '%s'", q.Get("response_type")) + } + if q.Get("client_id") != "test-client" { + t.Errorf("expected client_id 'test-client', got '%s'", q.Get("client_id")) + } + if q.Get("redirect_uri") != "http://localhost:8080/callback" { + t.Errorf("expected redirect_uri 'http://localhost:8080/callback', got '%s'", q.Get("redirect_uri")) + } + if q.Get("scope") != "openid profile email" { + t.Errorf("expected scope 'openid profile email', got '%s'", q.Get("scope")) + } + if q.Get("code_challenge_method") != "S256" { + t.Errorf("expected code_challenge_method 'S256', got '%s'", q.Get("code_challenge_method")) + } + // Validate state is generated + if authReq.state == "" { + t.Error("state is empty") + } + if q.Get("state") != authReq.state { + t.Errorf("state in URL doesn't match returned state") + } + // Validate PKCE parameters + if authReq.codeVerifier == "" { + t.Error("codeVerifier is empty") + } + if q.Get("code_challenge") == "" { + t.Error("code_challenge is empty") + } + }) + t.Run("with login_hint", func(t *testing.T) { + configWithHint := *config + configWithHint.LoginHint = "user@example.com" + authReq, _, err := initiateOIDCLogin(context.Background(), &configWithHint) + if err != nil { + t.Fatalf("initiateOIDCLogin failed: %v", err) + } + u, err := url.Parse(authReq.authURL) + if err != nil { + t.Fatalf("Failed to parse authURL: %v", err) + } + q := u.Query() + if q.Get("login_hint") != "user@example.com" { + t.Errorf("expected login_hint 'user@example.com', got '%s'", q.Get("login_hint")) + } + }) + t.Run("without login_hint", func(t *testing.T) { + authReq, _, err := initiateOIDCLogin(context.Background(), config) + if err != nil { + t.Fatalf("initiateOIDCLogin failed: %v", err) + } + u, err := url.Parse(authReq.authURL) + if err != nil { + t.Fatalf("Failed to parse authURL: %v", err) + } + q := u.Query() + if q.Has("login_hint") { + t.Errorf("expected no login_hint parameter, but got '%s'", q.Get("login_hint")) + } + }) + t.Run("nil config", func(t *testing.T) { + _, _, err := initiateOIDCLogin(context.Background(), nil) + if err == nil { + t.Error("expected error for nil config, got nil") + } + }) + t.Run("missing openid scope", func(t *testing.T) { + badConfig := *config + badConfig.Scopes = []string{"profile", "email"} // Missing "openid" + _, _, err := initiateOIDCLogin(context.Background(), &badConfig) + if err == nil { + t.Error("expected error for missing openid scope, got nil") + } + if !strings.Contains(err.Error(), "openid") { + t.Errorf("expected error about missing 'openid', got: %v", err) + } + }) + t.Run("missing required fields", func(t *testing.T) { + tests := []struct { + name string + mutate func(*OIDCLoginConfig) + expectErr string + }{ + { + name: "missing IssuerURL", + mutate: func(c *OIDCLoginConfig) { c.IssuerURL = "" }, + expectErr: "IssuerURL is required", + }, + { + name: "missing ClientID", + mutate: func(c *OIDCLoginConfig) { c.ClientID = "" }, + expectErr: "ClientID is required", + }, + { + name: "missing RedirectURL", + mutate: func(c *OIDCLoginConfig) { c.RedirectURL = "" }, + expectErr: "RedirectURL is required", + }, + { + name: "missing Scopes", + mutate: func(c *OIDCLoginConfig) { c.Scopes = nil }, + expectErr: "Scopes is required", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + badConfig := *config + tt.mutate(&badConfig) + _, _, err := initiateOIDCLogin(context.Background(), &badConfig) + if err == nil { + t.Error("expected error, got nil") + } + if !strings.Contains(err.Error(), tt.expectErr) { + t.Errorf("expected error containing '%s', got: %v", tt.expectErr, err) + } + }) + } + }) +} + +// TestCompleteOIDCLogin tests the authorization code exchange. +func TestCompleteOIDCLogin(t *testing.T) { + // Create mock IdP server + idpServer := createMockOIDCServerWithToken(t) + defer idpServer.Close() + config := &OIDCLoginConfig{ + IssuerURL: idpServer.URL, + ClientID: "test-client", + ClientSecret: "test-secret", + RedirectURL: "http://localhost:8080/callback", + Scopes: []string{"openid", "profile", "email"}, + HTTPClient: idpServer.Client(), + } + t.Run("successful code exchange", func(t *testing.T) { + // First initiate to get oauth2Config + _, oauth2Config, err := initiateOIDCLogin(context.Background(), config) + if err != nil { + t.Fatalf("initiateOIDCLogin failed: %v", err) + } + + tokens, err := completeOIDCLogin( + context.Background(), + config, + oauth2Config, + "test-auth-code", + "test-code-verifier", + ) + if err != nil { + t.Fatalf("completeOIDCLogin failed: %v", err) + } + // Validate tokens + if tokens.IDToken == "" { + t.Error("IDToken is empty") + } + if tokens.AccessToken == "" { + t.Error("AccessToken is empty") + } + if tokens.TokenType != "Bearer" { + t.Errorf("expected TokenType 'Bearer', got '%s'", tokens.TokenType) + } + if tokens.ExpiresAt == 0 { + t.Error("ExpiresAt is zero") + } + }) + t.Run("missing parameters", func(t *testing.T) { + _, oauth2Config, _ := initiateOIDCLogin(context.Background(), config) + + tests := []struct { + name string + authCode string + codeVerifier string + expectErr string + }{ + { + name: "missing authCode", + authCode: "", + codeVerifier: "test-verifier", + expectErr: "authCode is required", + }, + { + name: "missing codeVerifier", + authCode: "test-code", + codeVerifier: "", + expectErr: "codeVerifier is required", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := completeOIDCLogin( + context.Background(), + config, + oauth2Config, + tt.authCode, + tt.codeVerifier, + ) + if err == nil { + t.Error("expected error, got nil") + } + if !strings.Contains(err.Error(), tt.expectErr) { + t.Errorf("expected error containing '%s', got: %v", tt.expectErr, err) + } + }) + } + }) +} + +// TestOIDCLoginE2E tests the complete OIDC login flow end-to-end. +func TestOIDCLoginE2E(t *testing.T) { + // Create mock IdP server + idpServer := createMockOIDCServerWithToken(t) + defer idpServer.Close() + config := &OIDCLoginConfig{ + IssuerURL: idpServer.URL, + ClientID: "test-client", + ClientSecret: "test-secret", + RedirectURL: "http://localhost:8080/callback", + Scopes: []string{"openid", "profile", "email"}, + HTTPClient: idpServer.Client(), + } + // Step 1: Initiate login + authReq, oauth2Config, err := initiateOIDCLogin(context.Background(), config) + if err != nil { + t.Fatalf("initiateOIDCLogin failed: %v", err) + } + // Step 2: Simulate user authentication and redirect + // (In real flow, user would visit authReq.authURL and IdP would redirect back) + // Here we just use a mock authorization code + mockAuthCode := "mock-authorization-code" + // Step 3: Complete login with authorization code + tokens, err := completeOIDCLogin( + context.Background(), + config, + oauth2Config, + mockAuthCode, + authReq.codeVerifier, + ) + if err != nil { + t.Fatalf("completeOIDCLogin failed: %v", err) + } + // Validate we got an ID token + if tokens.IDToken == "" { + t.Error("Expected ID token, got empty string") + } + // Validate ID token is a JWT (has 3 parts) + parts := strings.Split(tokens.IDToken, ".") + if len(parts) != 3 { + t.Errorf("Expected JWT with 3 parts, got %d parts", len(parts)) + } +} + +// createMockOIDCServer creates a mock OIDC server for testing initiateOIDCLogin. +func createMockOIDCServer(t *testing.T) *httptest.Server { + var serverURL string + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Handle OIDC discovery + if r.URL.Path == "/.well-known/openid-configuration" { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "issuer": serverURL, + "authorization_endpoint": serverURL + "/authorize", + "token_endpoint": serverURL + "/token", + "jwks_uri": serverURL + "/.well-known/jwks.json", + "response_types_supported": []string{"code"}, + "code_challenge_methods_supported": []string{"S256"}, + "grant_types_supported": []string{"authorization_code"}, + }) + return + } + http.NotFound(w, r) + })) + serverURL = server.URL + return server +} + +// createMockOIDCServerWithToken creates a mock OIDC server that also handles token exchange. +func createMockOIDCServerWithToken(t *testing.T) *httptest.Server { + var serverURL string + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Handle OIDC discovery + if r.URL.Path == "/.well-known/openid-configuration" { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "issuer": serverURL, + "authorization_endpoint": serverURL + "/authorize", + "token_endpoint": serverURL + "/token", + "jwks_uri": serverURL + "/.well-known/jwks.json", + "response_types_supported": []string{"code"}, + "code_challenge_methods_supported": []string{"S256"}, + "grant_types_supported": []string{"authorization_code"}, + }) + return + } + // Handle token endpoint + if r.URL.Path == "/token" { + if err := r.ParseForm(); err != nil { + http.Error(w, "failed to parse form", http.StatusBadRequest) + return + } + // Validate grant type + if r.FormValue("grant_type") != "authorization_code" { + http.Error(w, "invalid grant_type", http.StatusBadRequest) + return + } + // Create mock ID token (JWT) + now := time.Now().Unix() + idToken := fmt.Sprintf("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.%s.mock-signature", + base64EncodeClaims(map[string]interface{}{ + "iss": serverURL, + "sub": "test-user", + "aud": "test-client", + "exp": now + 3600, + "iat": now, + "email": "test@example.com", + })) + // Return token response + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "mock-access-token", + "token_type": "Bearer", + "expires_in": 3600, + "refresh_token": "mock-refresh-token", + "id_token": idToken, + }) + return + } + http.NotFound(w, r) + })) + serverURL = server.URL + return server +} + +// base64EncodeClaims encodes JWT claims for testing. +func base64EncodeClaims(claims map[string]interface{}) string { + claimsJSON, _ := json.Marshal(claims) + return base64.RawURLEncoding.EncodeToString(claimsJSON) +} + +// TestPerformOIDCLogin tests the combined OIDC login flow with callback. +func TestPerformOIDCLogin(t *testing.T) { + // Create mock IdP server + idpServer := createMockOIDCServerWithToken(t) + defer idpServer.Close() + config := &OIDCLoginConfig{ + IssuerURL: idpServer.URL, + ClientID: "test-client", + ClientSecret: "test-secret", + RedirectURL: "http://localhost:8080/callback", + Scopes: []string{"openid", "profile", "email"}, + HTTPClient: idpServer.Client(), + } + + t.Run("successful flow", func(t *testing.T) { + tokens, err := PerformOIDCLogin(context.Background(), config, + func(ctx context.Context, args auth.AuthorizationArgs) (*auth.AuthorizationResult, error) { + // Validate authURL has required parameters + u, err := url.Parse(args.URL) + if err != nil { + return nil, fmt.Errorf("invalid authURL: %w", err) + } + q := u.Query() + if q.Get("response_type") != "code" { + return nil, fmt.Errorf("missing response_type") + } + if q.Get("state") == "" { + return nil, fmt.Errorf("missing state") + } + + // Simulate successful user authentication + return &auth.AuthorizationResult{ + Code: "mock-auth-code", + State: q.Get("state"), // Return the expected state from URL + }, nil + }) + + if err != nil { + t.Fatalf("PerformOIDCLogin failed: %v", err) + } + + if tokens.IDToken == "" { + t.Error("IDToken is empty") + } + if tokens.AccessToken == "" { + t.Error("AccessToken is empty") + } + }) + + t.Run("state mismatch", func(t *testing.T) { + _, err := PerformOIDCLogin(context.Background(), config, + func(ctx context.Context, args auth.AuthorizationArgs) (*auth.AuthorizationResult, error) { + // Return wrong state to simulate CSRF attack + return &auth.AuthorizationResult{ + Code: "mock-auth-code", + State: "wrong-state", + }, nil + }) + + if err == nil { + t.Error("expected error for state mismatch, got nil") + } + if !strings.Contains(err.Error(), "state mismatch") { + t.Errorf("expected state mismatch error, got: %v", err) + } + }) + + t.Run("fetcher error", func(t *testing.T) { + _, err := PerformOIDCLogin(context.Background(), config, + func(ctx context.Context, args auth.AuthorizationArgs) (*auth.AuthorizationResult, error) { + return nil, fmt.Errorf("user cancelled") + }) + + if err == nil { + t.Error("expected error, got nil") + } + if !strings.Contains(err.Error(), "user cancelled") { + t.Errorf("expected 'user cancelled' error, got: %v", err) + } + }) + + t.Run("nil fetcher", func(t *testing.T) { + _, err := PerformOIDCLogin(context.Background(), config, nil) + if err == nil { + t.Error("expected error for nil fetcher, got nil") + } + if !strings.Contains(err.Error(), "authCodeFetcher is required") { + t.Errorf("expected 'authCodeFetcher is required' error, got: %v", err) + } + }) +} diff --git a/auth/shared.go b/auth/shared.go new file mode 100644 index 00000000..fc0a482f --- /dev/null +++ b/auth/shared.go @@ -0,0 +1,69 @@ +// Copyright 2026 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 contains shared utilities for OAuth handlers. + +//go:build mcp_go_client_oauth + +package auth + +import ( + "context" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/modelcontextprotocol/go-sdk/oauthex" +) + +// GetAuthServerMetadata fetches authorization server metadata for the given issuer URL. +// It tries standard well-known endpoints (OAuth 2.0 and OIDC) and returns the first successful result. +func GetAuthServerMetadata(ctx context.Context, issuerURL string, httpClient *http.Client) (*oauthex.AuthServerMeta, error) { + for _, metadataURL := range authorizationServerMetadataURLs(issuerURL) { + asm, err := oauthex.GetAuthServerMeta(ctx, metadataURL, issuerURL, httpClient) + if err != nil { + return nil, fmt.Errorf("failed to get authorization server metadata: %w", err) + } + if asm != nil { + return asm, nil + } + } + return nil, fmt.Errorf("no authorization server metadata found for %s", issuerURL) +} + +// authorizationServerMetadataURLs returns a list of URLs to try when looking for +// authorization server metadata as mandated by the MCP specification: +// https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization#authorization-server-metadata-discovery. +func authorizationServerMetadataURLs(issuerURL string) []string { + var urls []string + + baseURL, err := url.Parse(issuerURL) + if err != nil { + return nil + } + + if baseURL.Path == "" { + // "OAuth 2.0 Authorization Server Metadata". + baseURL.Path = "/.well-known/oauth-authorization-server" + urls = append(urls, baseURL.String()) + // "OpenID Connect Discovery 1.0". + baseURL.Path = "/.well-known/openid-configuration" + urls = append(urls, baseURL.String()) + return urls + } + + originalPath := baseURL.Path + // "OAuth 2.0 Authorization Server Metadata with path insertion". + baseURL.Path = "/.well-known/oauth-authorization-server/" + strings.TrimLeft(originalPath, "/") + urls = append(urls, baseURL.String()) + // "OpenID Connect Discovery 1.0 with path insertion". + baseURL.Path = "/.well-known/openid-configuration/" + strings.TrimLeft(originalPath, "/") + urls = append(urls, baseURL.String()) + // "OpenID Connect Discovery 1.0 with path appending". + baseURL.Path = "/" + strings.Trim(originalPath, "/") + "/.well-known/openid-configuration" + urls = append(urls, baseURL.String()) + + return urls +} diff --git a/docs/protocol.md b/docs/protocol.md index f316e3f8..cc487ccb 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -357,6 +357,41 @@ session, err := client.Connect(ctx, transport, nil) The `auth.AuthorizationCodeHandler` automatically manages token refreshing and step-up authentication (when the server returns `insufficient_scope` error). +#### Enterprise Authentication Flow (SEP-990) + +For enterprise SSO scenarios, the SDK provides an +[`EnterpriseAuthFlow`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth#EnterpriseAuthFlow) +function that implements the complete token exchange flow: + +1. **Token Exchange** at IdP: ID Token → ID-JAG +2. **JWT Bearer Grant** at MCP Server: ID-JAG → Access Token + +This flow is typically used after obtaining an ID Token via OIDC login: + +```go +// Step 1: Obtain ID token via OIDC (see auth.InitiateOIDCLogin and auth.CompleteOIDCLogin) +idToken := "..." // from OIDC login + +// Step 2: Exchange for MCP access token +config := &auth.EnterpriseAuthConfig{ + IdPIssuerURL: "https://company.okta.com", + IdPClientID: "client-id-at-idp", + IdPClientSecret: "secret-at-idp", + MCPAuthServerURL: "https://auth.mcpserver.example", + MCPResourceURI: "https://mcp.mcpserver.example", + MCPClientID: "client-id-at-mcp", + MCPClientSecret: "secret-at-mcp", + MCPScopes: []string{"read", "write"}, +} + +accessToken, err := auth.EnterpriseAuthFlow(ctx, config, idToken) +// Use accessToken with MCP client +``` + +Helper functions are provided for OIDC login: +- [`InitiateOIDCLogin`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth#InitiateOIDCLogin) - Generate authorization URL with PKCE +- [`CompleteOIDCLogin`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth#CompleteOIDCLogin) - Exchange authorization code for tokens + ## Security Here we discuss the mitigations described under @@ -575,3 +610,4 @@ func Example_progress() { // frobbing widgets 2/2 } ``` + diff --git a/internal/docs/protocol.src.md b/internal/docs/protocol.src.md index 98078619..1511a304 100644 --- a/internal/docs/protocol.src.md +++ b/internal/docs/protocol.src.md @@ -282,6 +282,41 @@ session, err := client.Connect(ctx, transport, nil) The `auth.AuthorizationCodeHandler` automatically manages token refreshing and step-up authentication (when the server returns `insufficient_scope` error). +#### Enterprise Authentication Flow (SEP-990) + +For enterprise SSO scenarios, the SDK provides an +[`EnterpriseAuthFlow`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth#EnterpriseAuthFlow) +function that implements the complete token exchange flow: + +1. **Token Exchange** at IdP: ID Token → ID-JAG +2. **JWT Bearer Grant** at MCP Server: ID-JAG → Access Token + +This flow is typically used after obtaining an ID Token via OIDC login: + +```go +// Step 1: Obtain ID token via OIDC (see auth.InitiateOIDCLogin and auth.CompleteOIDCLogin) +idToken := "..." // from OIDC login + +// Step 2: Exchange for MCP access token +config := &auth.EnterpriseAuthConfig{ + IdPIssuerURL: "https://company.okta.com", + IdPClientID: "client-id-at-idp", + IdPClientSecret: "secret-at-idp", + MCPAuthServerURL: "https://auth.mcpserver.example", + MCPResourceURI: "https://mcp.mcpserver.example", + MCPClientID: "client-id-at-mcp", + MCPClientSecret: "secret-at-mcp", + MCPScopes: []string{"read", "write"}, +} + +accessToken, err := auth.EnterpriseAuthFlow(ctx, config, idToken) +// Use accessToken with MCP client +``` + +Helper functions are provided for OIDC login: +- [`InitiateOIDCLogin`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth#InitiateOIDCLogin) - Generate authorization URL with PKCE +- [`CompleteOIDCLogin`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth#CompleteOIDCLogin) - Exchange authorization code for tokens + ## Security Here we discuss the mitigations described under @@ -398,3 +433,4 @@ or Issue #460 discusses some potential ergonomic improvements to this API. %include ../../mcp/mcp_example_test.go progress - + diff --git a/oauthex/auth_meta.go b/oauthex/auth_meta.go index 36210576..da21ca54 100644 --- a/oauthex/auth_meta.go +++ b/oauthex/auth_meta.go @@ -185,7 +185,7 @@ func validateAuthServerMetaURLs(asm *AuthServerMeta) error { } for _, u := range urls { - if err := checkURLScheme(u.value); err != nil { + if err := CheckURLScheme(u.value); err != nil { return fmt.Errorf("%s: %w", u.name, err) } } diff --git a/oauthex/dcr.go b/oauthex/dcr.go index 6db30255..3159a07f 100644 --- a/oauthex/dcr.go +++ b/oauthex/dcr.go @@ -237,7 +237,7 @@ func RegisterClient(ctx context.Context, registrationEndpoint string, clientMeta func validateClientRegistrationURLs(meta *ClientRegistrationMetadata) error { // Validate redirect URIs for i, uri := range meta.RedirectURIs { - if err := checkURLScheme(uri); err != nil { + if err := CheckURLScheme(uri); err != nil { return fmt.Errorf("redirect_uris[%d]: %w", i, err) } } @@ -255,7 +255,7 @@ func validateClientRegistrationURLs(meta *ClientRegistrationMetadata) error { } for _, u := range urls { - if err := checkURLScheme(u.value); err != nil { + if err := CheckURLScheme(u.value); err != nil { return fmt.Errorf("%s: %w", u.name, err) } } diff --git a/oauthex/oauth2.go b/oauthex/oauth2.go index d8aeb3c2..39a91f35 100644 --- a/oauthex/oauth2.go +++ b/oauthex/oauth2.go @@ -63,10 +63,10 @@ func getJSON[T any](ctx context.Context, c *http.Client, url string, limit int64 return &t, nil } -// checkURLScheme ensures that its argument is a valid URL with a scheme +// CheckURLScheme ensures that its argument is a valid URL with a scheme // that prevents XSS attacks. // See #526. -func checkURLScheme(u string) error { +func CheckURLScheme(u string) error { if u == "" { return nil } diff --git a/oauthex/resource_meta.go b/oauthex/resource_meta.go index 4680c153..43557101 100644 --- a/oauthex/resource_meta.go +++ b/oauthex/resource_meta.go @@ -112,7 +112,7 @@ func GetProtectedResourceMetadata(ctx context.Context, metadataURL, resourceURL } // Validate the authorization server URLs to prevent XSS attacks (see #526). for i, u := range prm.AuthorizationServers { - if err := checkURLScheme(u); err != nil { + if err := CheckURLScheme(u); err != nil { return nil, fmt.Errorf("authorization_servers[%d]: %v", i, err) } if err := checkHTTPSOrLoopback(u); err != nil { diff --git a/oauthex/token_exchange.go b/oauthex/token_exchange.go new file mode 100644 index 00000000..aa58c386 --- /dev/null +++ b/oauthex/token_exchange.go @@ -0,0 +1,243 @@ +// Copyright 2026 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 Token Exchange (RFC 8693) for Enterprise Managed Authorization. +// See https://datatracker.ietf.org/doc/html/rfc8693 + +//go:build mcp_go_client_oauth + +package oauthex + +import ( + "context" + "fmt" + "net/http" + "strings" + + "golang.org/x/oauth2" +) + +// Token type identifiers defined by RFC 8693 and SEP-990. +const ( + // TokenTypeIDToken is the URN for OpenID Connect ID Tokens. + TokenTypeIDToken = "urn:ietf:params:oauth:token-type:id_token" + + // TokenTypeSAML2 is the URN for SAML 2.0 assertions. + TokenTypeSAML2 = "urn:ietf:params:oauth:token-type:saml2" + + // TokenTypeIDJAG is the URN for Identity Assertion JWT Authorization Grants. + // This is the token type returned by IdP during token exchange for SEP-990. + TokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag" + + // GrantTypeTokenExchange is the grant type for RFC 8693 token exchange. + GrantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" +) + +// ClientCredentials holds client authentication credentials for OAuth token requests. +type ClientCredentials struct { + // ClientID is the OAuth2 client identifier. + // REQUIRED. + ClientID string + + // ClientSecret is the OAuth2 client secret for confidential clients. + // OPTIONAL. Not required for public clients. + ClientSecret string +} + +// TokenExchangeRequest represents a Token Exchange request per RFC 8693. +// This is used for Enterprise Managed Authorization (SEP-990) where an MCP Client +// exchanges an ID Token from an enterprise IdP for an ID-JAG that can be used +// to obtain an access token from an MCP Server's authorization server. +type TokenExchangeRequest struct { + // RequestedTokenType indicates the type of security token being requested. + // For SEP-990, this MUST be TokenTypeIDJAG. + RequestedTokenType string + + // Audience is the logical name of the target service where the client + // intends to use the requested token. For SEP-990, this MUST be the + // Issuer URL of the MCP Server's authorization server. + Audience string + + // Resource is the physical location or identifier of the target resource. + // For SEP-990, this MUST be the RFC9728 Resource Identifier of the MCP Server. + Resource string + + // Scope is a list of space-separated scopes for the requested token. + // This is OPTIONAL per RFC 8693 but commonly used in SEP-990. + Scope []string + + // SubjectToken is the security token that represents the identity of the + // party on behalf of whom the request is being made. For SEP-990, this is + // typically an OpenID Connect ID Token. + SubjectToken string + + // SubjectTokenType is the type of the security token in SubjectToken. + // For SEP-990 with OIDC, this MUST be TokenTypeIDToken. + SubjectTokenType string +} + +// TokenExchangeResponse represents the response from a token exchange request +// per RFC 8693 Section 2.2. +type TokenExchangeResponse struct { + // IssuedTokenType is the type of the security token in AccessToken. + // For SEP-990, this MUST be TokenTypeIDJAG. + IssuedTokenType string `json:"issued_token_type"` + + // AccessToken is the security token issued by the authorization server. + // Despite the name "access_token" (required by RFC 8693), for SEP-990 + // this contains an ID-JAG JWT, not an OAuth access token. + AccessToken string `json:"access_token"` + + // TokenType indicates the type of token returned. For SEP-990, this is "N_A" + // because the issued token is not an OAuth access token. + TokenType string `json:"token_type"` + + // Scope is the scope of the issued token, if the issued token scope is + // different from the requested scope. Per RFC 8693, this SHOULD be included + // if the scope differs from the request. + Scope string `json:"scope,omitempty"` + + // ExpiresIn is the lifetime in seconds of the issued token. + ExpiresIn int `json:"expires_in,omitempty"` +} + +// ExchangeToken performs a token exchange request per RFC 8693 for Enterprise +// Managed Authorization (SEP-990). It exchanges an identity assertion (typically +// an ID Token) for an Identity Assertion JWT Authorization Grant (ID-JAG) that +// can be used to obtain an access token from an MCP Server. +// +// The tokenEndpoint parameter should be the IdP's token endpoint (typically +// obtained from the IdP's authorization server metadata). +// +// Example: +// +// req := &TokenExchangeRequest{ +// RequestedTokenType: TokenTypeIDJAG, +// Audience: "https://auth.mcpserver.example/", +// Resource: "https://mcp.mcpserver.example/", +// Scope: []string{"read", "write"}, +// SubjectToken: idToken, +// SubjectTokenType: TokenTypeIDToken, +// } +// clientCreds := &ClientCredentials{ClientID: "my-client", ClientSecret: "secret"} +// +// resp, err := ExchangeToken(ctx, idpTokenEndpoint, req, clientCreds, nil) +func ExchangeToken( + ctx context.Context, + tokenEndpoint string, + req *TokenExchangeRequest, + clientCreds *ClientCredentials, + httpClient *http.Client, +) (*TokenExchangeResponse, error) { + if tokenEndpoint == "" { + return nil, fmt.Errorf("token endpoint is required") + } + if req == nil { + return nil, fmt.Errorf("token exchange request is required") + } + if clientCreds == nil { + return nil, fmt.Errorf("client credentials are required") + } + + // Validate required fields per SEP-990 Section 4 + if req.RequestedTokenType == "" { + return nil, fmt.Errorf("requested_token_type is required") + } + if req.Audience == "" { + return nil, fmt.Errorf("audience is required") + } + if req.Resource == "" { + return nil, fmt.Errorf("resource is required") + } + if req.SubjectToken == "" { + return nil, fmt.Errorf("subject_token is required") + } + if req.SubjectTokenType == "" { + return nil, fmt.Errorf("subject_token_type is required") + } + + // Validate URL schemes to prevent XSS attacks (see #526) + if err := CheckURLScheme(tokenEndpoint); err != nil { + return nil, fmt.Errorf("invalid token endpoint: %w", err) + } + if err := CheckURLScheme(req.Audience); err != nil { + return nil, fmt.Errorf("invalid audience: %w", err) + } + if err := CheckURLScheme(req.Resource); err != nil { + return nil, fmt.Errorf("invalid resource: %w", err) + } + + // Per RFC 6749 Section 3.2, parameters sent without a value (like the empty + // "code" parameter) MUST be treated as if they were omitted from the request. + // The oauth2 library's Exchange method sends an empty code, but compliant + // servers should ignore it. + cfg := &oauth2.Config{ + ClientID: clientCreds.ClientID, + ClientSecret: clientCreds.ClientSecret, + Endpoint: oauth2.Endpoint{ + TokenURL: tokenEndpoint, + AuthStyle: oauth2.AuthStyleInParams, // Use POST body auth per SEP-990 + }, + } + + // Use custom HTTP client if provided + if httpClient == nil { + httpClient = http.DefaultClient + } + ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, httpClient) + + // Build token exchange parameters per RFC 8693 + opts := []oauth2.AuthCodeOption{ + oauth2.SetAuthURLParam("grant_type", GrantTypeTokenExchange), + oauth2.SetAuthURLParam("requested_token_type", req.RequestedTokenType), + oauth2.SetAuthURLParam("audience", req.Audience), + oauth2.SetAuthURLParam("resource", req.Resource), + oauth2.SetAuthURLParam("subject_token", req.SubjectToken), + oauth2.SetAuthURLParam("subject_token_type", req.SubjectTokenType), + } + if len(req.Scope) > 0 { + opts = append(opts, oauth2.SetAuthURLParam("scope", strings.Join(req.Scope, " "))) + } + + // Exchange with token exchange grant type. + // SetAuthURLParam overrides the default grant_type and adds all required parameters. + token, err := cfg.Exchange( + ctxWithClient, + "", // empty code - per RFC 6749 Section 3.2, empty params should be ignored + opts..., + ) + if err != nil { + return nil, fmt.Errorf("token exchange request failed: %w", err) + } + + // Extract issued_token_type from Token.Extra(). + // The oauth2 library stores additional response fields in Extra. + issuedTokenType, _ := token.Extra("issued_token_type").(string) + if issuedTokenType == "" { + return nil, fmt.Errorf("response missing required field: issued_token_type") + } + + // Build TokenExchangeResponse from oauth2.Token + resp := &TokenExchangeResponse{ + IssuedTokenType: issuedTokenType, + AccessToken: token.AccessToken, + TokenType: token.TokenType, + } + + // Extract optional fields from Extra + if scope, ok := token.Extra("scope").(string); ok { + resp.Scope = scope + } + + // Calculate expires_in from token.Expiry if available + if !token.Expiry.IsZero() { + resp.ExpiresIn = int(token.Expiry.Sub(token.Expiry).Seconds()) // This would be 0 + // Actually get the raw expires_in if available + if expiresIn, ok := token.Extra("expires_in").(float64); ok { + resp.ExpiresIn = int(expiresIn) + } + } + + return resp, nil +} diff --git a/oauthex/token_exchange_test.go b/oauthex/token_exchange_test.go new file mode 100644 index 00000000..8c646cad --- /dev/null +++ b/oauthex/token_exchange_test.go @@ -0,0 +1,229 @@ +// Copyright 2026 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" + "net/http" + "net/http/httptest" + "testing" +) + +// TestExchangeToken tests the basic token exchange flow. +func TestExchangeToken(t *testing.T) { + // Create a test IdP server that implements token exchange + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Verify request method and content type + if r.Method != http.MethodPost { + t.Errorf("expected POST request, got %s", r.Method) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + contentType := r.Header.Get("Content-Type") + if contentType != "application/x-www-form-urlencoded" { + t.Errorf("expected application/x-www-form-urlencoded, got %s", contentType) + http.Error(w, "invalid content type", http.StatusBadRequest) + return + } + + // Parse form data + if err := r.ParseForm(); err != nil { + http.Error(w, "failed to parse form", http.StatusBadRequest) + return + } + + // Verify required parameters per SEP-990 Section 4 + grantType := r.FormValue("grant_type") + if grantType != GrantTypeTokenExchange { + t.Errorf("expected grant_type %s, got %s", GrantTypeTokenExchange, grantType) + writeErrorResponse(w, "invalid_grant", "invalid grant_type") + return + } + + requestedTokenType := r.FormValue("requested_token_type") + if requestedTokenType != TokenTypeIDJAG { + t.Errorf("expected requested_token_type %s, got %s", TokenTypeIDJAG, requestedTokenType) + writeErrorResponse(w, "invalid_request", "invalid requested_token_type") + return + } + + audience := r.FormValue("audience") + if audience == "" { + t.Error("audience is required") + writeErrorResponse(w, "invalid_request", "missing audience") + return + } + + resource := r.FormValue("resource") + if resource == "" { + t.Error("resource is required") + writeErrorResponse(w, "invalid_request", "missing resource") + return + } + + subjectToken := r.FormValue("subject_token") + if subjectToken == "" { + t.Error("subject_token is required") + writeErrorResponse(w, "invalid_request", "missing subject_token") + return + } + + subjectTokenType := r.FormValue("subject_token_type") + if subjectTokenType != TokenTypeIDToken { + t.Errorf("expected subject_token_type %s, got %s", TokenTypeIDToken, subjectTokenType) + writeErrorResponse(w, "invalid_request", "invalid subject_token_type") + return + } + + // Verify client authentication + clientID := r.FormValue("client_id") + clientSecret := r.FormValue("client_secret") + if clientID == "" || clientSecret == "" { + t.Error("client authentication required") + writeErrorResponse(w, "invalid_client", "client authentication failed") + return + } + + if clientID != "test-client-id" || clientSecret != "test-client-secret" { + t.Error("invalid client credentials") + writeErrorResponse(w, "invalid_client", "invalid credentials") + return + } + + // Return successful token exchange response per SEP-990 Section 4.2 + resp := TokenExchangeResponse{ + IssuedTokenType: TokenTypeIDJAG, + AccessToken: "fake-id-jag-token", + TokenType: "N_A", + Scope: r.FormValue("scope"), + ExpiresIn: 300, + } + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Pragma", "no-cache") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(resp) + })) + defer server.Close() + + // Test successful token exchange + t.Run("successful exchange", func(t *testing.T) { + req := &TokenExchangeRequest{ + RequestedTokenType: TokenTypeIDJAG, + Audience: "https://auth.mcpserver.example/", + Resource: "https://mcp.mcpserver.example/", + Scope: []string{"read", "write"}, + SubjectToken: "fake-id-token", + SubjectTokenType: TokenTypeIDToken, + } + + resp, err := ExchangeToken( + context.Background(), + server.URL, + req, + &ClientCredentials{ + ClientID: "test-client-id", + ClientSecret: "test-client-secret", + }, + server.Client(), + ) + + if err != nil { + t.Fatalf("ExchangeToken failed: %v", err) + } + + if resp.IssuedTokenType != TokenTypeIDJAG { + t.Errorf("expected issued_token_type %s, got %s", TokenTypeIDJAG, resp.IssuedTokenType) + } + + if resp.AccessToken != "fake-id-jag-token" { + t.Errorf("expected access_token 'fake-id-jag-token', got %s", resp.AccessToken) + } + + if resp.TokenType != "N_A" { + t.Errorf("expected token_type 'N_A', got %s", resp.TokenType) + } + + if resp.Scope != "read write" { + t.Errorf("expected scope 'read write', got %s", resp.Scope) + } + + if resp.ExpiresIn != 300 { + t.Errorf("expected expires_in 300, got %d", resp.ExpiresIn) + } + }) + + // Test missing required fields + t.Run("missing audience", func(t *testing.T) { + req := &TokenExchangeRequest{ + RequestedTokenType: TokenTypeIDJAG, + Resource: "https://mcp.mcpserver.example/", + SubjectToken: "fake-id-token", + SubjectTokenType: TokenTypeIDToken, + } + + _, err := ExchangeToken( + context.Background(), + server.URL, + req, + &ClientCredentials{ + ClientID: "test-client-id", + ClientSecret: "test-client-secret", + }, + server.Client(), + ) + + if err == nil { + t.Error("expected error for missing audience, got nil") + } + }) + + // Test invalid URL schemes + t.Run("invalid audience URL scheme", func(t *testing.T) { + req := &TokenExchangeRequest{ + RequestedTokenType: TokenTypeIDJAG, + Audience: "javascript:alert(1)", + Resource: "https://mcp.mcpserver.example/", + SubjectToken: "fake-id-token", + SubjectTokenType: TokenTypeIDToken, + } + + _, err := ExchangeToken( + context.Background(), + server.URL, + req, + &ClientCredentials{ + ClientID: "test-client-id", + ClientSecret: "test-client-secret", + }, + server.Client(), + ) + + if err == nil { + t.Error("expected error for invalid audience URL scheme, got nil") + } + }) +} + +// writeErrorResponse writes an OAuth 2.0 error response per RFC 6749 Section 5.2. +func writeErrorResponse(w http.ResponseWriter, errorCode, errorDescription string) { + errResp := struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description,omitempty"` + }{ + Error: errorCode, + ErrorDescription: errorDescription, + } + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(errResp) +} diff --git a/oauthex/url_scheme_test.go b/oauthex/url_scheme_test.go index 83eeb5e1..c5221a62 100644 --- a/oauthex/url_scheme_test.go +++ b/oauthex/url_scheme_test.go @@ -15,7 +15,7 @@ import ( "testing" ) -// TestCheckURLScheme tests the checkURLScheme function directly. +// TestCheckURLScheme tests the CheckURLScheme function directly. func TestCheckURLScheme(t *testing.T) { tests := []struct { name string @@ -40,9 +40,9 @@ func TestCheckURLScheme(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := checkURLScheme(tt.url) + err := CheckURLScheme(tt.url) if (err != nil) != tt.wantErr { - t.Errorf("checkURLScheme(%q): got err %v, want err %v", tt.url, err != nil, tt.wantErr) + t.Errorf("CheckURLScheme(%q): got err %v, want err %v", tt.url, err != nil, tt.wantErr) } }) }