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/enterprise_auth.go b/auth/enterprise_auth.go new file mode 100644 index 00000000..21005702 --- /dev/null +++ b/auth/enterprise_auth.go @@ -0,0 +1,181 @@ +// 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 the client-side Enterprise Managed Authorization flow +// for MCP as specified in SEP-990. + +//go:build mcp_go_client_oauth + +package auth + +import ( + "context" + "fmt" + "net/http" + + "github.com/modelcontextprotocol/go-sdk/oauthex" + "golang.org/x/oauth2" +) + +// EnterpriseAuthConfig contains configuration for Enterprise Managed Authorization +// (SEP-990). This configures both the IdP (for token exchange) and the MCP Server +// (for JWT Bearer grant). +type EnterpriseAuthConfig struct { + // IdP configuration (where the user authenticates) + IdPIssuerURL string // e.g., "https://acme.okta.com" + IdPClientID string // MCP Client's ID at the IdP + IdPClientSecret string // MCP Client's secret at the IdP + + // MCP Server configuration (the resource being accessed) + MCPAuthServerURL string // MCP Server's auth server issuer URL + MCPResourceURI string // MCP Server's resource identifier + MCPClientID string // MCP Client's ID at the MCP Server + MCPClientSecret string // MCP Client's secret at the MCP Server + MCPScopes []string // Requested scopes at the MCP Server + + // Optional HTTP client for customization + HTTPClient *http.Client +} + +// EnterpriseAuthFlow performs the complete Enterprise Managed Authorization flow: +// 1. Token Exchange: ID Token → ID-JAG at IdP +// 2. JWT Bearer: ID-JAG → Access Token at MCP Server +// +// This function takes an ID Token that was obtained via SSO (e.g., OIDC login) +// and exchanges it for an access token that can be used to call the MCP Server. +// +// There are two ways to obtain an ID Token for use with this function: +// +// Option 1: Use the OIDC login helper functions (full flow with SSO): +// +// // Step 1: Initiate OIDC login +// oidcConfig := &OIDCLoginConfig{ +// IssuerURL: "https://acme.okta.com", +// ClientID: "client-id", +// RedirectURL: "http://localhost:8080/callback", +// Scopes: []string{"openid", "profile", "email"}, +// } +// authReq, err := InitiateOIDCLogin(ctx, oidcConfig) +// if err != nil { +// log.Fatal(err) +// } +// +// // Step 2: Direct user to authReq.AuthURL for authentication +// fmt.Printf("Visit: %s\n", authReq.AuthURL) +// +// // Step 3: After redirect, complete login with authorization code +// tokens, err := CompleteOIDCLogin(ctx, oidcConfig, authCode, authReq.CodeVerifier) +// if err != nil { +// log.Fatal(err) +// } +// +// // Step 4: Use ID token for enterprise auth +// enterpriseConfig := &EnterpriseAuthConfig{ +// IdPIssuerURL: "https://acme.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 := EnterpriseAuthFlow(ctx, enterpriseConfig, tokens.IDToken) +// if err != nil { +// log.Fatal(err) +// } +// +// Option 2: Bring your own ID Token (if you already have one): +// +// config := &EnterpriseAuthConfig{ +// IdPIssuerURL: "https://acme.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"}, +// } +// +// // If you already obtained an ID token through your own means +// accessToken, err := EnterpriseAuthFlow(ctx, config, myIDToken) +// if err != nil { +// log.Fatal(err) +// } +// +// // Use accessToken to call MCP Server APIs +func EnterpriseAuthFlow( + ctx context.Context, + config *EnterpriseAuthConfig, + idToken string, +) (*oauth2.Token, error) { + if config == nil { + return nil, fmt.Errorf("config is required") + } + if idToken == "" { + return nil, fmt.Errorf("idToken is required") + } + // Validate configuration + if config.IdPIssuerURL == "" { + return nil, fmt.Errorf("IdPIssuerURL is required") + } + if config.MCPAuthServerURL == "" { + return nil, fmt.Errorf("MCPAuthServerURL is required") + } + if config.MCPResourceURI == "" { + return nil, fmt.Errorf("MCPResourceURI is required") + } + httpClient := config.HTTPClient + if httpClient == nil { + httpClient = http.DefaultClient + } + + // Step 1: Discover IdP token endpoint via OIDC discovery + idpMeta, err := GetAuthServerMetadataForIssuer(ctx, config.IdPIssuerURL, httpClient) + if err != nil { + return nil, fmt.Errorf("failed to discover IdP metadata: %w", err) + } + + // Step 2: Token Exchange (ID Token → ID-JAG) + tokenExchangeReq := &oauthex.TokenExchangeRequest{ + RequestedTokenType: oauthex.TokenTypeIDJAG, + Audience: config.MCPAuthServerURL, + Resource: config.MCPResourceURI, + Scope: config.MCPScopes, + SubjectToken: idToken, + SubjectTokenType: oauthex.TokenTypeIDToken, + } + + tokenExchangeResp, err := oauthex.ExchangeToken( + ctx, + idpMeta.TokenEndpoint, + tokenExchangeReq, + config.IdPClientID, + config.IdPClientSecret, + httpClient, + ) + if err != nil { + return nil, fmt.Errorf("token exchange failed: %w", err) + } + + // Step 3: JWT Bearer Grant (ID-JAG → Access Token) + mcpMeta, err := GetAuthServerMetadataForIssuer(ctx, config.MCPAuthServerURL, httpClient) + if err != nil { + return nil, fmt.Errorf("failed to discover MCP auth server metadata: %w", err) + } + + accessToken, err := oauthex.ExchangeJWTBearer( + ctx, + mcpMeta.TokenEndpoint, + tokenExchangeResp.AccessToken, + config.MCPClientID, + config.MCPClientSecret, + httpClient, + ) + if err != nil { + return nil, fmt.Errorf("JWT bearer grant failed: %w", err) + } + return accessToken, nil +} diff --git a/auth/enterprise_auth_test.go b/auth/enterprise_auth_test.go new file mode 100644 index 00000000..61274c0c --- /dev/null +++ b/auth/enterprise_auth_test.go @@ -0,0 +1,224 @@ +// 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 auth + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/modelcontextprotocol/go-sdk/oauthex" +) + +// TestEnterpriseAuthFlow tests the complete enterprise auth flow. +func TestEnterpriseAuthFlow(t *testing.T) { + // Create test servers for IdP and MCP Server + idpServer := createMockIdPServer(t) + defer idpServer.Close() + mcpServer := createMockMCPServer(t) + defer mcpServer.Close() + // Create a test ID Token + idToken := createTestIDToken() + // Configure enterprise auth + config := &EnterpriseAuthConfig{ + IdPIssuerURL: idpServer.URL, + IdPClientID: "test-idp-client", + IdPClientSecret: "test-idp-secret", + MCPAuthServerURL: mcpServer.URL, + MCPResourceURI: "https://mcp.example.com", + MCPClientID: "test-mcp-client", + MCPClientSecret: "test-mcp-secret", + MCPScopes: []string{"read", "write"}, + HTTPClient: idpServer.Client(), + } + // Test successful flow + t.Run("successful flow", func(t *testing.T) { + token, err := EnterpriseAuthFlow(context.Background(), config, idToken) + if err != nil { + t.Fatalf("EnterpriseAuthFlow failed: %v", err) + } + if token.AccessToken != "mcp-access-token" { + t.Errorf("expected access token 'mcp-access-token', got '%s'", token.AccessToken) + } + if token.TokenType != "Bearer" { + t.Errorf("expected token type 'Bearer', got '%s'", token.TokenType) + } + }) + // Test missing config + t.Run("nil config", func(t *testing.T) { + _, err := EnterpriseAuthFlow(context.Background(), nil, idToken) + if err == nil { + t.Error("expected error for nil config, got nil") + } + }) + // Test missing ID token + t.Run("empty ID token", func(t *testing.T) { + _, err := EnterpriseAuthFlow(context.Background(), config, "") + if err == nil { + t.Error("expected error for empty ID token, got nil") + } + }) + // Test missing IdP issuer + t.Run("missing IdP issuer", func(t *testing.T) { + badConfig := *config + badConfig.IdPIssuerURL = "" + _, err := EnterpriseAuthFlow(context.Background(), &badConfig, idToken) + if err == nil { + t.Error("expected error for missing IdP issuer, got nil") + } + }) +} + +// createMockIdPServer creates a mock IdP server for testing. +func createMockIdPServer(t *testing.T) *httptest.Server { + var serverURL string + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Handle OIDC discovery endpoint + if r.URL.Path == "/.well-known/openid-configuration" { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "issuer": serverURL, // Use actual server URL + "token_endpoint": serverURL + "/oauth2/v1/token", + "jwks_uri": serverURL + "/.well-known/jwks.json", + "code_challenge_methods_supported": []string{"S256"}, + "grant_types_supported": []string{ + "authorization_code", + "urn:ietf:params:oauth:grant-type:token-exchange", + }, + "response_types_supported": []string{"code"}, + }) + return + } + + // Handle token exchange endpoint + if r.URL.Path != "/oauth2/v1/token" { + http.NotFound(w, r) + return + } + + if err := r.ParseForm(); err != nil { + http.Error(w, "failed to parse form", http.StatusBadRequest) + return + } + grantType := r.FormValue("grant_type") + if grantType != oauthex.GrantTypeTokenExchange { + http.Error(w, "invalid grant type", http.StatusBadRequest) + return + } + + // Return a mock ID-JAG + now := time.Now().Unix() + header := map[string]string{"typ": "oauth-id-jag+jwt", "alg": "RS256"} + claims := map[string]interface{}{ + "iss": "https://test.okta.com", + "sub": "test-user", + "aud": r.FormValue("audience"), + "resource": r.FormValue("resource"), + "client_id": r.FormValue("client_id"), + "jti": "test-jti", + "exp": now + 300, + "iat": now, + "scope": r.FormValue("scope"), + } + headerJSON, _ := json.Marshal(header) + claimsJSON, _ := json.Marshal(claims) + headerB64 := base64.RawURLEncoding.EncodeToString(headerJSON) + claimsB64 := base64.RawURLEncoding.EncodeToString(claimsJSON) + mockIDJAG := fmt.Sprintf("%s.%s.mock-signature", headerB64, claimsB64) + + resp := oauthex.TokenExchangeResponse{ + IssuedTokenType: oauthex.TokenTypeIDJAG, + AccessToken: mockIDJAG, + TokenType: "N_A", + ExpiresIn: 300, + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(resp) + })) + serverURL = server.URL // Capture server URL for discovery response + return server +} + +// createMockMCPServer creates a mock MCP Server for testing. +func createMockMCPServer(t *testing.T) *httptest.Server { + var serverURL string + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Handle OIDC discovery endpoint + if r.URL.Path == "/.well-known/openid-configuration" { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]interface{}{ + "issuer": serverURL, // Use actual server URL + "token_endpoint": serverURL + "/v1/token", + "jwks_uri": serverURL + "/.well-known/jwks.json", + "code_challenge_methods_supported": []string{"S256"}, + "grant_types_supported": []string{ + "urn:ietf:params:oauth:grant-type:jwt-bearer", + }, + }) + return + } + + // Handle JWT Bearer endpoint + if r.URL.Path != "/v1/token" { + http.NotFound(w, r) + return + } + + if err := r.ParseForm(); err != nil { + http.Error(w, "failed to parse form", http.StatusBadRequest) + return + } + grantType := r.FormValue("grant_type") + if grantType != oauthex.GrantTypeJWTBearer { + http.Error(w, "invalid grant type", http.StatusBadRequest) + return + } + + resp := struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in,omitempty"` + Scope string `json:"scope,omitempty"` + RefreshToken string `json:"refresh_token,omitempty"` + }{ + AccessToken: "mcp-access-token", + TokenType: "Bearer", + ExpiresIn: 3600, + Scope: "read write", + RefreshToken: "mcp-refresh-token", + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(resp) + })) + serverURL = server.URL // Capture server URL for discovery response + return server +} + +// createTestIDToken creates a mock ID Token for testing. +func createTestIDToken() string { + now := time.Now().Unix() + header := map[string]string{"typ": "JWT", "alg": "RS256"} + claims := map[string]interface{}{ + "iss": "https://test.okta.com", + "sub": "test-user", + "aud": "test-client", + "exp": now + 3600, + "iat": now, + "email": "test@example.com", + } + headerJSON, _ := json.Marshal(header) + claimsJSON, _ := json.Marshal(claims) + headerB64 := base64.RawURLEncoding.EncodeToString(headerJSON) + claimsB64 := base64.RawURLEncoding.EncodeToString(claimsJSON) + + return fmt.Sprintf("%s.%s.mock-signature", headerB64, claimsB64) +} diff --git a/auth/extauth/enterprise_handler.go b/auth/extauth/enterprise_handler.go new file mode 100644 index 00000000..f1382ab0 --- /dev/null +++ b/auth/extauth/enterprise_handler.go @@ -0,0 +1,194 @@ +// 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" +) + +// 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) (string, 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) + idToken, 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.GetAuthServerMetadataForIssuer(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: idToken, + SubjectTokenType: oauthex.TokenTypeIDToken, + } + + tokenExchangeResp, err := oauthex.ExchangeToken( + ctx, + idpMeta.TokenEndpoint, + tokenExchangeReq, + h.config.IdPClientID, + 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.GetAuthServerMetadataForIssuer(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 := oauthex.ExchangeJWTBearer( + ctx, + mcpMeta.TokenEndpoint, + tokenExchangeResp.AccessToken, + h.config.MCPClientID, + 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 +} diff --git a/auth/extauth/oidc_login.go b/auth/extauth/oidc_login.go new file mode 100644 index 00000000..f71ecd57 --- /dev/null +++ b/auth/extauth/oidc_login.go @@ -0,0 +1,397 @@ +// 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 an OPTIONAL step before calling EnterpriseAuthFlow. +// Users can alternatively obtain ID tokens through their own methods. +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 +} + +// OIDCAuthorizationRequest represents the result of initiating an OIDC +// authorization code flow. Users must direct the end-user to AuthURL +// to complete authentication. +type OIDCAuthorizationRequest struct { + // AuthURL is the URL the user should visit to authenticate. + // This URL includes the authorization request parameters. + AuthURL string + // State is the OAuth2 state parameter for CSRF protection. + // Users MUST validate that the state returned from the IdP matches this value. + State string + // CodeVerifier is the PKCE code verifier for secure authorization code exchange. + // This must be provided to CompleteOIDCLogin along with the authorization code. + CodeVerifier string +} + +// 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 EnterpriseAuthFlow for token exchange. + 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 +} + +// InitiateOIDCLogin initiates an OIDC Authorization Code flow with PKCE. +// This is the first step for users who want to use SSO to obtain an ID token. +// +// The returned AuthURL should be presented to the user (e.g., opened in a browser). +// After the user authenticates, the IdP will redirect to the RedirectURL with +// an authorization code and state parameter. +// +// Example: +// +// config := &OIDCLoginConfig{ +// IssuerURL: "https://acme.okta.com", +// ClientID: "client-id", +// RedirectURL: "http://localhost:8080/callback", +// Scopes: []string{"openid", "profile", "email"}, +// } +// +// authReq, err := InitiateOIDCLogin(ctx, config) +// if err != nil { +// log.Fatal(err) +// } +// +// // Direct user to authReq.AuthURL +// fmt.Printf("Visit this URL to login: %s\n", authReq.AuthURL) +// +// // After user completes login, IdP redirects to RedirectURL with code & state +// // Extract code and state from the redirect, then call CompleteOIDCLogin +func InitiateOIDCLogin( + ctx context.Context, + config *OIDCLoginConfig, +) (*OIDCAuthorizationRequest, error) { + if config == nil { + return nil, fmt.Errorf("config is required") + } + // Validate required fields + if config.IssuerURL == "" { + return nil, fmt.Errorf("IssuerURL is required") + } + if config.ClientID == "" { + return nil, fmt.Errorf("ClientID is required") + } + if config.RedirectURL == "" { + return nil, fmt.Errorf("RedirectURL is required") + } + if len(config.Scopes) == 0 { + return nil, fmt.Errorf("Scopes is required (must include 'openid')") + } + // Validate that "openid" scope is present (required for OIDC) + hasOpenID := false + for _, scope := range config.Scopes { + if scope == "openid" { + hasOpenID = true + break + } + } + if !hasOpenID { + return nil, fmt.Errorf("Scopes must include 'openid' for OIDC") + } + // Validate URL schemes to prevent XSS attacks + if err := oauthex.CheckURLScheme(config.IssuerURL); err != nil { + return nil, fmt.Errorf("invalid IssuerURL: %w", err) + } + if err := oauthex.CheckURLScheme(config.RedirectURL); err != nil { + return nil, fmt.Errorf("invalid RedirectURL: %w", err) + } + // Discover OIDC endpoints via .well-known + httpClient := config.HTTPClient + if httpClient == nil { + httpClient = http.DefaultClient + } + meta, err := auth.GetAuthServerMetadataForIssuer(ctx, config.IssuerURL, httpClient) + if err != nil { + return nil, fmt.Errorf("failed to discover OIDC metadata: %w", err) + } + if meta.AuthorizationEndpoint == "" { + return nil, fmt.Errorf("authorization_endpoint not found in OIDC metadata") + } + + // Generate PKCE code verifier (RFC 7636) + codeVerifier := oauth2.GenerateVerifier() + + // Generate state for CSRF protection (RFC 6749 Section 10.12) + state := rand.Text() + + // Build oauth2.Config to use standard library's AuthCodeURL. + oauth2Config := &oauth2.Config{ + ClientID: config.ClientID, + ClientSecret: config.ClientSecret, + RedirectURL: config.RedirectURL, + Scopes: config.Scopes, + Endpoint: oauth2.Endpoint{ + AuthURL: meta.AuthorizationEndpoint, + TokenURL: meta.TokenEndpoint, + }, + } + + // Build authorization URL using oauth2.Config.AuthCodeURL with PKCE. + // S256ChallengeOption automatically computes the S256 challenge from the verifier. + 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, + }, nil +} + +// CompleteOIDCLogin completes the OIDC Authorization Code flow by exchanging +// the authorization code for tokens. This is the second step after the user +// has authenticated and been redirected back to the application. +// +// The authCode and returnedState parameters should come from the redirect URL +// query parameters. The state MUST match the state from InitiateOIDCLogin +// for CSRF protection. +// +// Example: +// +// // In your redirect handler (e.g., http://localhost:8080/callback) +// authCode := r.URL.Query().Get("code") +// returnedState := r.URL.Query().Get("state") +// +// // Validate state matches what we sent +// if returnedState != authReq.State { +// log.Fatal("State mismatch - possible CSRF attack") +// } +// +// // Exchange code for tokens +// tokens, err := CompleteOIDCLogin(ctx, config, authCode, authReq.CodeVerifier) +// if err != nil { +// log.Fatal(err) +// } +// +// // Now use tokens.IDToken with EnterpriseAuthFlow +// accessToken, err := EnterpriseAuthFlow(ctx, enterpriseConfig, tokens.IDToken) +func CompleteOIDCLogin( + ctx context.Context, + config *OIDCLoginConfig, + authCode string, + codeVerifier string, +) (*OIDCTokenResponse, error) { + if config == nil { + return nil, fmt.Errorf("config is required") + } + if authCode == "" { + return nil, fmt.Errorf("authCode is required") + } + if codeVerifier == "" { + return nil, fmt.Errorf("codeVerifier is required") + } + // Validate required fields + if config.IssuerURL == "" { + return nil, fmt.Errorf("IssuerURL is required") + } + if config.ClientID == "" { + return nil, fmt.Errorf("ClientID is required") + } + if config.RedirectURL == "" { + return nil, fmt.Errorf("RedirectURL is required") + } + // Discover token endpoint + httpClient := config.HTTPClient + if httpClient == nil { + httpClient = http.DefaultClient + } + meta, err := auth.GetAuthServerMetadataForIssuer(ctx, config.IssuerURL, httpClient) + if err != nil { + return nil, fmt.Errorf("failed to discover OIDC metadata: %w", err) + } + if meta.TokenEndpoint == "" { + return nil, fmt.Errorf("token_endpoint not found in OIDC metadata") + } + + // Build oauth2.Config for token exchange. + oauth2Config := &oauth2.Config{ + ClientID: config.ClientID, + ClientSecret: config.ClientSecret, + RedirectURL: config.RedirectURL, + Scopes: config.Scopes, + Endpoint: oauth2.Endpoint{ + AuthURL: meta.AuthorizationEndpoint, + TokenURL: meta.TokenEndpoint, + }, + } + + // Use custom HTTP client if provided + ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, httpClient) + + // Exchange authorization code for tokens using oauth2.Config.Exchange. + // VerifierOption provides the PKCE code_verifier for the token request. + oauth2Token, err := oauth2Config.Exchange( + ctxWithClient, + authCode, + oauth2.VerifierOption(codeVerifier), + ) + if err != nil { + return nil, fmt.Errorf("token exchange failed: %w", err) + } + + // Extract ID Token from response. + // oauth2.Token.Extra() provides access to additional fields like id_token. + 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 +} + +// OIDCAuthorizationResult contains the authorization code and state returned +// from the IdP after user authentication. +type OIDCAuthorizationResult struct { + // Code is the authorization code returned by the IdP. + Code string + // State is the state parameter returned by the IdP. + // This MUST match the state sent in the authorization request. + State string +} + +// 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 authURL (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 OIDCAuthorizationResult +// +// The expectedState parameter is provided for CSRF validation. Implementations +// MUST verify that the returned state matches expectedState. +type AuthorizationCodeFetcher func(ctx context.Context, authURL string, expectedState string) (*OIDCAuthorizationResult, error) + +// PerformOIDCLogin performs the complete OIDC Authorization Code flow with PKCE +// in a single function call. This is the recommended approach for most use cases. +// +// 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 +// +// Example: +// +// config := &OIDCLoginConfig{ +// IssuerURL: "https://acme.okta.com", +// ClientID: "client-id", +// RedirectURL: "http://localhost:8080/callback", +// Scopes: []string{"openid", "profile", "email"}, +// } +// +// tokens, err := PerformOIDCLogin(ctx, config, func(ctx context.Context, authURL, expectedState string) (*OIDCAuthorizationResult, error) { +// // Open browser for user +// fmt.Printf("Please visit: %s\n", authURL) +// +// // Start local server to receive callback +// code, state := waitForCallback(ctx) +// +// // Validate state for CSRF protection +// if state != expectedState { +// return nil, fmt.Errorf("state mismatch") +// } +// +// return &OIDCAuthorizationResult{Code: code, State: state}, nil +// }) +// if err != nil { +// log.Fatal(err) +// } +// +// // Use tokens.IDToken with EnterpriseHandler +func PerformOIDCLogin( + ctx context.Context, + config *OIDCLoginConfig, + authCodeFetcher AuthorizationCodeFetcher, +) (*OIDCTokenResponse, error) { + if authCodeFetcher == nil { + return nil, fmt.Errorf("authCodeFetcher is required") + } + + // Step 1: Initiate the OIDC flow to get the authorization URL + authReq, err := InitiateOIDCLogin(ctx, config) + if err != nil { + return nil, fmt.Errorf("failed to initiate OIDC login: %w", err) + } + + // Step 2: Use callback to get authorization code from user interaction + authResult, err := authCodeFetcher(ctx, authReq.AuthURL, authReq.State) + if err != nil { + return nil, fmt.Errorf("failed to fetch authorization code: %w", err) + } + + // Step 3: Validate state for CSRF protection + if authResult.State != authReq.State { + return nil, fmt.Errorf("state mismatch: expected %q, got %q", authReq.State, authResult.State) + } + + // Step 4: Exchange authorization code for tokens + tokens, err := CompleteOIDCLogin(ctx, config, authResult.Code, authReq.CodeVerifier) + if err != nil { + return nil, fmt.Errorf("failed to complete OIDC login: %w", err) + } + + return tokens, nil +} diff --git a/auth/extauth/oidc_login_test.go b/auth/extauth/oidc_login_test.go new file mode 100644 index 00000000..a82a8456 --- /dev/null +++ b/auth/extauth/oidc_login_test.go @@ -0,0 +1,476 @@ +// 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" +) + +// 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) { + tokens, err := CompleteOIDCLogin( + context.Background(), + config, + "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("nil config", func(t *testing.T) { + _, err := CompleteOIDCLogin( + context.Background(), + nil, + "test-auth-code", + "test-code-verifier", + ) + if err == nil { + t.Error("expected error for nil config, got nil") + } + }) + t.Run("missing parameters", func(t *testing.T) { + 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, + 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, 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, + 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, authURL, expectedState string) (*OIDCAuthorizationResult, error) { + // Validate authURL has required parameters + u, err := url.Parse(authURL) + 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 &OIDCAuthorizationResult{ + Code: "mock-auth-code", + State: expectedState, // Return the expected state + }, 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, authURL, expectedState string) (*OIDCAuthorizationResult, error) { + // Return wrong state to simulate CSRF attack + return &OIDCAuthorizationResult{ + 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, authURL, expectedState string) (*OIDCAuthorizationResult, 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..c0b6e68b --- /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" +) + +// GetAuthServerMetadataForIssuer 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 GetAuthServerMetadataForIssuer(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/jwt_bearer.go b/oauthex/jwt_bearer.go new file mode 100644 index 00000000..7b71a0d1 --- /dev/null +++ b/oauthex/jwt_bearer.go @@ -0,0 +1,104 @@ +// 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 JWT Bearer Authorization Grant (RFC 7523) for Enterprise Managed Authorization. +// See https://datatracker.ietf.org/doc/html/rfc7523 + +//go:build mcp_go_client_oauth + +package oauthex + +import ( + "context" + "fmt" + "net/http" + + "golang.org/x/oauth2" +) + +// GrantTypeJWTBearer is the grant type for RFC 7523 JWT Bearer authorization grant. +// This is used in SEP-990 to exchange an ID-JAG for an access token at the MCP Server. +const GrantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer" + +// ExchangeJWTBearer exchanges an Identity Assertion JWT Authorization Grant (ID-JAG) +// for an access token using JWT Bearer Grant per RFC 7523. This is the second step +// in Enterprise Managed Authorization (SEP-990) after obtaining the ID-JAG from the +// IdP via token exchange. +// +// The tokenEndpoint parameter should be the MCP Server's token endpoint (typically +// obtained from the MCP Server's authorization server metadata). +// +// The assertion parameter should be the ID-JAG JWT obtained from the token exchange +// step with the enterprise IdP. +// +// Client authentication must be performed by the caller by including appropriate +// credentials in the request (e.g., using Basic auth via the Authorization header, +// or including client_id and client_secret in the form data). +// +// Example: +// +// // First, get ID-JAG via token exchange +// idJAG := tokenExchangeResp.AccessToken +// +// // Then exchange ID-JAG for access token +// token, err := ExchangeJWTBearer( +// ctx, +// "https://auth.mcpserver.example/oauth2/token", +// idJAG, +// "mcp-client-id", +// "mcp-client-secret", +// nil, +// ) +func ExchangeJWTBearer( + ctx context.Context, + tokenEndpoint string, + assertion string, + clientID string, + clientSecret string, + httpClient *http.Client, +) (*oauth2.Token, error) { + if tokenEndpoint == "" { + return nil, fmt.Errorf("token endpoint is required") + } + if assertion == "" { + return nil, fmt.Errorf("assertion is required") + } + // Validate URL scheme to prevent XSS attacks (see #526) + if err := checkURLScheme(tokenEndpoint); err != nil { + return nil, fmt.Errorf("invalid token endpoint: %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: clientID, + ClientSecret: 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) + + // Exchange with JWT Bearer grant type and assertion. + // SetAuthURLParam overrides the default grant_type and adds the assertion parameter. + token, err := cfg.Exchange( + ctxWithClient, + "", // empty code - per RFC 6749 Section 3.2, empty params should be ignored + 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/oauthex/jwt_bearer_test.go b/oauthex/jwt_bearer_test.go new file mode 100644 index 00000000..8a04732a --- /dev/null +++ b/oauthex/jwt_bearer_test.go @@ -0,0 +1,163 @@ +// 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" + "time" +) + +// TestExchangeJWTBearer tests the JWT Bearer grant flow. +func TestExchangeJWTBearer(t *testing.T) { + // Create a test MCP Server auth server that accepts JWT Bearer grants + 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 grant type per RFC 7523 + grantType := r.FormValue("grant_type") + if grantType != GrantTypeJWTBearer { + t.Errorf("expected grant_type %s, got %s", GrantTypeJWTBearer, grantType) + writeJWTBearerErrorResponse(w, "unsupported_grant_type", "grant type not supported") + return + } + // Verify assertion is provided + assertion := r.FormValue("assertion") + if assertion == "" { + t.Error("assertion is required") + writeJWTBearerErrorResponse(w, "invalid_request", "missing assertion") + return + } + // Verify client authentication + clientID := r.FormValue("client_id") + clientSecret := r.FormValue("client_secret") + if clientID == "" || clientSecret == "" { + t.Error("client authentication required") + writeJWTBearerErrorResponse(w, "invalid_client", "client authentication failed") + return + } + if clientID != "mcp-client-id" || clientSecret != "mcp-client-secret" { + t.Error("invalid client credentials") + writeJWTBearerErrorResponse(w, "invalid_client", "invalid credentials") + return + } + // Return successful OAuth token response + resp := struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in,omitempty"` + Scope string `json:"scope,omitempty"` + RefreshToken string `json:"refresh_token,omitempty"` + }{ + AccessToken: "mcp-access-token-123", + TokenType: "Bearer", + ExpiresIn: 3600, + Scope: "read write", + RefreshToken: "mcp-refresh-token-456", + } + 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 JWT Bearer grant + t.Run("successful exchange", func(t *testing.T) { + token, err := ExchangeJWTBearer( + context.Background(), + server.URL, + "fake-id-jag-jwt", + "mcp-client-id", + "mcp-client-secret", + server.Client(), + ) + if err != nil { + t.Fatalf("ExchangeJWTBearer failed: %v", err) + } + if token.AccessToken != "mcp-access-token-123" { + t.Errorf("expected access_token 'mcp-access-token-123', got %s", token.AccessToken) + } + if token.TokenType != "Bearer" { + t.Errorf("expected token_type 'Bearer', got %s", token.TokenType) + } + if token.RefreshToken != "mcp-refresh-token-456" { + t.Errorf("expected refresh_token 'mcp-refresh-token-456', got %s", token.RefreshToken) + } + // Check expiration (should be ~1 hour from now) + expectedExpiry := time.Now().Add(3600 * time.Second) + if token.Expiry.Before(time.Now()) || token.Expiry.After(expectedExpiry.Add(5*time.Second)) { + t.Errorf("unexpected expiry time: %v", token.Expiry) + } + // Check scope in extra data + scope, ok := token.Extra("scope").(string) + if !ok || scope != "read write" { + t.Errorf("expected scope 'read write', got %v", token.Extra("scope")) + } + }) + // Test missing assertion + t.Run("missing assertion", func(t *testing.T) { + _, err := ExchangeJWTBearer( + context.Background(), + server.URL, + "", // empty assertion + "mcp-client-id", + "mcp-client-secret", + server.Client(), + ) + if err == nil { + t.Error("expected error for missing assertion, got nil") + } + }) + // Test invalid URL scheme + t.Run("invalid token endpoint URL", func(t *testing.T) { + _, err := ExchangeJWTBearer( + context.Background(), + "javascript:alert(1)", + "fake-id-jag-jwt", + "mcp-client-id", + "mcp-client-secret", + server.Client(), + ) + if err == nil { + t.Error("expected error for invalid URL scheme, got nil") + } + }) +} + +// writeJWTBearerErrorResponse writes an OAuth 2.0 error response per RFC 6749 Section 5.2. +func writeJWTBearerErrorResponse(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/oauth2.go b/oauthex/oauth2.go index d8aeb3c2..fc3b45ee 100644 --- a/oauthex/oauth2.go +++ b/oauthex/oauth2.go @@ -94,3 +94,9 @@ func checkHTTPSOrLoopback(addr string) error { } return nil } + +// CheckURLScheme validates a URL scheme for security. +// This is exported for use by the auth package. +func CheckURLScheme(u string) error { + return checkURLScheme(u) +} diff --git a/oauthex/token_exchange.go b/oauthex/token_exchange.go new file mode 100644 index 00000000..de723d12 --- /dev/null +++ b/oauthex/token_exchange.go @@ -0,0 +1,233 @@ +// 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" +) + +// 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). +// +// Client authentication must be performed by the caller by including appropriate +// credentials in the request (e.g., using Basic auth via the Authorization header, +// or including client_id and client_secret in the form data). +// +// Example: +// +// req := &TokenExchangeRequest{ +// RequestedTokenType: TokenTypeIDJAG, +// Audience: "https://auth.mcpserver.example/", +// Resource: "https://mcp.mcpserver.example/", +// Scope: []string{"read", "write"}, +// SubjectToken: idToken, +// SubjectTokenType: TokenTypeIDToken, +// } +// +// resp, err := ExchangeToken(ctx, idpTokenEndpoint, req, clientID, clientSecret, nil) +func ExchangeToken( + ctx context.Context, + tokenEndpoint string, + req *TokenExchangeRequest, + clientID string, + clientSecret string, + 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") + } + + // 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: clientID, + ClientSecret: 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..a0403fdc --- /dev/null +++ b/oauthex/token_exchange_test.go @@ -0,0 +1,223 @@ +// 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, + "test-client-id", + "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, + "test-client-id", + "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, + "test-client-id", + "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) +}