Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/auth/extauth/enterprise_handler.go

raw symbols SCIP
1 // Copyright 2026 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 // Package extauth provides OAuth handler implementations for MCP authorization extensions.
6 // This package implements Enterprise Managed Authorization as defined in SEP-990.
7
8 package extauth
9
10 import (
11 "context"
12 "errors"
13 "fmt"
14 "io"
15 "net/http"
16
17 "github.com/modelcontextprotocol/go-sdk/auth"
18 "github.com/modelcontextprotocol/go-sdk/oauthex"
19 "golang.org/x/oauth2"
20 )
21
22 // grantTypeJWTBearer is the grant type for RFC 7523 JWT Bearer authorization grant.
23 const grantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer"
24
25 // IDTokenFetcher is called to obtain an ID Token from the enterprise IdP.
26 // This is typically done via OIDC login flow where the user authenticates
27 // with their enterprise identity provider.
28 //
29 // Returns an oauth2.Token where Extra("id_token") contains the OpenID Connect ID Token (JWT).
30 type IDTokenFetcher func(ctx context.Context) (*oauth2.Token, error)
31
32 // EnterpriseHandlerConfig is the configuration for [EnterpriseHandler].
33 type EnterpriseHandlerConfig struct {
34 // IdP configuration (where the user authenticates)
35
36 // IdPIssuerURL is the enterprise IdP's issuer URL (e.g., "https://acme.okta.com").
37 // Used for OIDC discovery to find the token endpoint.
38 // REQUIRED.
39 IdPIssuerURL string
40
41 // IdPCredentials contains the MCP Client's credentials registered at the IdP.
42 // REQUIRED. These credentials are used for token exchange at the IdP.
43 // The ClientID is always required. ClientSecretAuth is optional and only needed
44 // if the IdP requires client authentication (confidential clients).
45 IdPCredentials *oauthex.ClientCredentials
46
47 // MCP Server configuration (the resource being accessed)
48
49 // MCPAuthServerURL is the MCP Server's authorization server issuer URL.
50 // Used as the audience for token exchange and for metadata discovery.
51 // REQUIRED.
52 MCPAuthServerURL string
53
54 // MCPResourceURI is the MCP Server's resource identifier (RFC 9728).
55 // Used as the resource parameter in token exchange.
56 // REQUIRED.
57 MCPResourceURI string
58
59 // MCPCredentials contains the MCP Client's credentials registered at the MCP Server.
60 // REQUIRED. These credentials are used for JWT Bearer grant at the MCP Server.
61 // The ClientID is always required. ClientSecretAuth is optional and only needed
62 // if the MCP Server requires client authentication.
63 MCPCredentials *oauthex.ClientCredentials
64
65 // MCPScopes is the list of scopes to request at the MCP Server.
66 // OPTIONAL.
67 MCPScopes []string
68
69 // IDTokenFetcher is called to obtain an ID Token when authorization is needed.
70 // The implementation should handle the OIDC login flow (e.g., browser redirect,
71 // callback handling) and return the ID token.
72 // REQUIRED.
73 IDTokenFetcher IDTokenFetcher
74
75 // HTTPClient is an optional HTTP client for customization.
76 // If nil, http.DefaultClient is used.
77 // OPTIONAL.
78 HTTPClient *http.Client
79 }
80
81 // EnterpriseHandler is an implementation of [auth.OAuthHandler] that uses
82 // Enterprise Managed Authorization (SEP-990) to obtain access tokens.
83 //
84 // The flow consists of:
85 // 1. OIDC Login: User authenticates with enterprise IdP → ID Token
86 // 2. Token Exchange (RFC 8693): ID Token → ID-JAG at IdP
87 // 3. JWT Bearer Grant (RFC 7523): ID-JAG → Access Token at MCP Server
88 type EnterpriseHandler struct {
89 config *EnterpriseHandlerConfig
90
91 // tokenSource is the token source obtained after authorization.
92 tokenSource oauth2.TokenSource
93 }
94
95 // Compile-time check that EnterpriseHandler implements auth.OAuthHandler.
96 var _ auth.OAuthHandler = (*EnterpriseHandler)(nil)
97
98 // NewEnterpriseHandler creates a new EnterpriseHandler.
99 // It performs validation of the configuration and returns an error if invalid.
100 func NewEnterpriseHandler(config *EnterpriseHandlerConfig) (*EnterpriseHandler, error) {
101 if config == nil {
102 return nil, errors.New("config must be provided")
103 }
104 if config.IdPIssuerURL == "" {
105 return nil, errors.New("IdPIssuerURL is required")
106 }
107 if config.IdPCredentials == nil {
108 return nil, errors.New("IdPCredentials is required")
109 }
110 if err := config.IdPCredentials.Validate(); err != nil {
111 return nil, fmt.Errorf("invalid IdPCredentials: %w", err)
112 }
113 if config.MCPAuthServerURL == "" {
114 return nil, errors.New("MCPAuthServerURL is required")
115 }
116 if config.MCPResourceURI == "" {
117 return nil, errors.New("MCPResourceURI is required")
118 }
119 if config.MCPCredentials == nil {
120 return nil, errors.New("MCPCredentials is required")
121 }
122 if err := config.MCPCredentials.Validate(); err != nil {
123 return nil, fmt.Errorf("invalid MCPCredentials: %w", err)
124 }
125 if config.IDTokenFetcher == nil {
126 return nil, errors.New("IDTokenFetcher is required")
127 }
128 return &EnterpriseHandler{config: config}, nil
129 }
130
131 // TokenSource returns the token source for outgoing requests.
132 // Returns nil if authorization has not been performed yet.
133 func (h *EnterpriseHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {
134 return h.tokenSource, nil
135 }
136
137 // Authorize performs the Enterprise Managed Authorization flow.
138 // It is called when a request fails with 401 or 403.
139 func (h *EnterpriseHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error {
140 defer resp.Body.Close()
141 defer io.Copy(io.Discard, resp.Body)
142
143 httpClient := h.config.HTTPClient
144 if httpClient == nil {
145 httpClient = http.DefaultClient
146 }
147
148 // Step 1: Get ID Token via the configured fetcher (e.g., OIDC login)
149 oidcToken, err := h.config.IDTokenFetcher(ctx)
150 if err != nil {
151 return fmt.Errorf("failed to obtain ID token: %w", err)
152 }
153
154 // Extract ID token from the oauth2.Token
155 idToken, ok := oidcToken.Extra("id_token").(string)
156 if !ok || idToken == "" {
157 return fmt.Errorf("id_token not found in OIDC token response")
158 }
159
160 // Step 2: Discover IdP token endpoint via OIDC discovery
161 idpMeta, err := auth.GetAuthServerMetadata(ctx, h.config.IdPIssuerURL, httpClient)
162 if err != nil {
163 return fmt.Errorf("failed to discover IdP metadata: %w", err)
164 }
165 if idpMeta == nil {
166 return fmt.Errorf("no authorization server metadata found for IdP: %s", h.config.IdPIssuerURL)
167 }
168
169 // Step 3: Token Exchange (ID Token → ID-JAG)
170 tokenExchangeReq := &oauthex.TokenExchangeRequest{
171 RequestedTokenType: oauthex.TokenTypeIDJAG,
172 Audience: h.config.MCPAuthServerURL,
173 Resource: h.config.MCPResourceURI,
174 Scope: h.config.MCPScopes,
175 SubjectToken: idToken,
176 SubjectTokenType: oauthex.TokenTypeIDToken,
177 }
178
179 idJAGToken, err := oauthex.ExchangeToken(
180 ctx,
181 idpMeta.TokenEndpoint,
182 tokenExchangeReq,
183 h.config.IdPCredentials,
184 httpClient,
185 )
186 if err != nil {
187 return fmt.Errorf("token exchange failed: %w", err)
188 }
189
190 // Step 4: Discover MCP Server token endpoint
191 mcpMeta, err := auth.GetAuthServerMetadata(ctx, h.config.MCPAuthServerURL, httpClient)
192 if err != nil {
193 return fmt.Errorf("failed to discover MCP auth server metadata: %w", err)
194 }
195 if mcpMeta == nil {
196 return fmt.Errorf("no authorization server metadata found for MCP server: %s", h.config.MCPAuthServerURL)
197 }
198
199 // Step 5: JWT Bearer Grant (ID-JAG → Access Token)
200 // The ID-JAG is in the AccessToken field of the token (despite the name)
201 accessToken, err := exchangeJWTBearer(
202 ctx,
203 mcpMeta.TokenEndpoint,
204 idJAGToken.AccessToken,
205 h.config.MCPCredentials,
206 httpClient,
207 )
208 if err != nil {
209 return fmt.Errorf("JWT bearer grant failed: %w", err)
210 }
211
212 // Store the token source for subsequent requests
213 h.tokenSource = oauth2.StaticTokenSource(accessToken)
214 return nil
215 }
216
217 // exchangeJWTBearer exchanges an Identity Assertion JWT Authorization Grant (ID-JAG)
218 // for an access token using JWT Bearer Grant per RFC 7523.
219 func exchangeJWTBearer(
220 ctx context.Context,
221 tokenEndpoint string,
222 assertion string,
223 clientCreds *oauthex.ClientCredentials,
224 httpClient *http.Client,
225 ) (*oauth2.Token, error) {
226 cfg := &oauth2.Config{
227 ClientID: clientCreds.ClientID,
228 Endpoint: oauth2.Endpoint{
229 TokenURL: tokenEndpoint,
230 AuthStyle: oauth2.AuthStyleInParams,
231 },
232 }
233 // Set ClientSecret if ClientSecretAuth is configured
234 if clientCreds.ClientSecretAuth != nil {
235 cfg.ClientSecret = clientCreds.ClientSecretAuth.ClientSecret
236 }
237
238 if httpClient == nil {
239 httpClient = http.DefaultClient
240 }
241 ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, httpClient)
242
243 token, err := cfg.Exchange(
244 ctxWithClient,
245 "",
246 oauth2.SetAuthURLParam("grant_type", grantTypeJWTBearer),
247 oauth2.SetAuthURLParam("assertion", assertion),
248 )
249 if err != nil {
250 return nil, fmt.Errorf("JWT bearer grant request failed: %w", err)
251 }
252
253 return token, nil
254 }