Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/oauthex/token_exchange.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 // This file implements Token Exchange (RFC 8693) for Enterprise Managed Authorization.
6 // See https://datatracker.ietf.org/doc/html/rfc8693
7
8 package oauthex
9
10 import (
11 "context"
12 "fmt"
13 "net/http"
14 "strings"
15
16 "golang.org/x/oauth2"
17 )
18
19 // Token type identifiers defined by RFC 8693 and SEP-990.
20 const (
21 // TokenTypeIDToken is the URN for OpenID Connect ID Tokens.
22 TokenTypeIDToken = "urn:ietf:params:oauth:token-type:id_token"
23
24 // TokenTypeSAML2 is the URN for SAML 2.0 assertions.
25 TokenTypeSAML2 = "urn:ietf:params:oauth:token-type:saml2"
26
27 // TokenTypeIDJAG is the URN for Identity Assertion JWT Authorization Grants.
28 // This is the token type returned by IdP during token exchange for SEP-990.
29 TokenTypeIDJAG = "urn:ietf:params:oauth:token-type:id-jag"
30
31 // GrantTypeTokenExchange is the grant type for RFC 8693 token exchange.
32 GrantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
33 )
34
35 // TokenExchangeRequest represents a Token Exchange request per RFC 8693.
36 // This is used for Enterprise Managed Authorization (SEP-990) where an MCP Client
37 // exchanges an ID Token from an enterprise IdP for an ID-JAG that can be used
38 // to obtain an access token from an MCP Server's authorization server.
39 type TokenExchangeRequest struct {
40 // RequestedTokenType indicates the type of security token being requested.
41 // For SEP-990, this MUST be TokenTypeIDJAG.
42 RequestedTokenType string
43
44 // Audience is the logical name of the target service where the client
45 // intends to use the requested token. For SEP-990, this MUST be the
46 // Issuer URL of the MCP Server's authorization server.
47 Audience string
48
49 // Resource is the physical location or identifier of the target resource.
50 // For SEP-990, this MUST be the RFC9728 Resource Identifier of the MCP Server.
51 Resource string
52
53 // Scope is a list of space-separated scopes for the requested token.
54 // This is OPTIONAL per RFC 8693 but commonly used in SEP-990.
55 Scope []string
56
57 // SubjectToken is the security token that represents the identity of the
58 // party on behalf of whom the request is being made. For SEP-990, this is
59 // typically an OpenID Connect ID Token.
60 SubjectToken string
61
62 // SubjectTokenType is the type of the security token in SubjectToken.
63 // For SEP-990 with OIDC, this MUST be TokenTypeIDToken.
64 SubjectTokenType string
65 }
66
67 // ExchangeToken performs a token exchange request per RFC 8693 for Enterprise
68 // Managed Authorization (SEP-990). It exchanges an identity assertion (typically
69 // an ID Token) for an Identity Assertion JWT Authorization Grant (ID-JAG) that
70 // can be used to obtain an access token from an MCP Server.
71 //
72 // The tokenEndpoint parameter should be the IdP's token endpoint (typically
73 // obtained from the IdP's authorization server metadata).
74 //
75 // Returns an oauth2.Token where:
76 // - Extra("issued_token_type") contains the type of the issued token (e.g., TokenTypeIDJAG)
77 // - AccessToken contains the ID-JAG JWT (despite the name, this is not an OAuth access token)
78 // - TokenType is typically "N_A" for SEP-990
79 // - Extra("scope") may contain the scope if different from the request
80 // - Expiry is when the token expires
81 func ExchangeToken(
82 ctx context.Context,
83 tokenEndpoint string,
84 req *TokenExchangeRequest,
85 clientCreds *ClientCredentials,
86 httpClient *http.Client,
87 ) (*oauth2.Token, error) {
88 if tokenEndpoint == "" {
89 return nil, fmt.Errorf("token endpoint is required")
90 }
91 if req == nil {
92 return nil, fmt.Errorf("token exchange request is required")
93 }
94 if clientCreds == nil {
95 return nil, fmt.Errorf("client credentials are required")
96 }
97 if err := clientCreds.Validate(); err != nil {
98 return nil, fmt.Errorf("invalid client credentials: %w", err)
99 }
100
101 // Validate required fields per SEP-990 Section 4.
102 if req.RequestedTokenType == "" {
103 return nil, fmt.Errorf("requested_token_type is required")
104 }
105 if req.Audience == "" {
106 return nil, fmt.Errorf("audience is required")
107 }
108 if req.Resource == "" {
109 return nil, fmt.Errorf("resource is required")
110 }
111 if req.SubjectToken == "" {
112 return nil, fmt.Errorf("subject_token is required")
113 }
114 if req.SubjectTokenType == "" {
115 return nil, fmt.Errorf("subject_token_type is required")
116 }
117
118 // Validate URL schemes to prevent XSS attacks (see #526).
119 if err := checkURLScheme(tokenEndpoint); err != nil {
120 return nil, fmt.Errorf("invalid token endpoint: %w", err)
121 }
122 if err := checkURLScheme(req.Audience); err != nil {
123 return nil, fmt.Errorf("invalid audience: %w", err)
124 }
125 if err := checkURLScheme(req.Resource); err != nil {
126 return nil, fmt.Errorf("invalid resource: %w", err)
127 }
128
129 // Per RFC 6749 Section 3.2, parameters sent without a value (like the empty
130 // "code" parameter) MUST be treated as if they were omitted from the request.
131 // The oauth2 library's Exchange method sends an empty code, but compliant
132 // servers should ignore it.
133 cfg := &oauth2.Config{
134 ClientID: clientCreds.ClientID,
135 Endpoint: oauth2.Endpoint{
136 TokenURL: tokenEndpoint,
137 AuthStyle: oauth2.AuthStyleInParams,
138 },
139 }
140 // Set ClientSecret if ClientSecretAuth is configured.
141 if clientCreds.ClientSecretAuth != nil {
142 cfg.ClientSecret = clientCreds.ClientSecretAuth.ClientSecret
143 }
144
145 // Use custom HTTP client if provided.
146 if httpClient == nil {
147 httpClient = http.DefaultClient
148 }
149 ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, httpClient)
150
151 // Build token exchange parameters per RFC 8693.
152 opts := []oauth2.AuthCodeOption{
153 oauth2.SetAuthURLParam("grant_type", GrantTypeTokenExchange),
154 oauth2.SetAuthURLParam("requested_token_type", req.RequestedTokenType),
155 oauth2.SetAuthURLParam("audience", req.Audience),
156 oauth2.SetAuthURLParam("resource", req.Resource),
157 oauth2.SetAuthURLParam("subject_token", req.SubjectToken),
158 oauth2.SetAuthURLParam("subject_token_type", req.SubjectTokenType),
159 }
160 if len(req.Scope) > 0 {
161 opts = append(opts, oauth2.SetAuthURLParam("scope", strings.Join(req.Scope, " ")))
162 }
163
164 // Exchange with token exchange grant type.
165 // SetAuthURLParam overrides the default grant_type and adds all required parameters.
166 token, err := cfg.Exchange(
167 ctxWithClient,
168 "", // empty code - per RFC 6749 Section 3.2, empty params should be ignored
169 opts...,
170 )
171 if err != nil {
172 return nil, fmt.Errorf("token exchange request failed: %w", err)
173 }
174
175 // Validate that issued_token_type is present in the response.
176 // The oauth2 library stores additional response fields in Extra.
177 issuedTokenType, _ := token.Extra("issued_token_type").(string)
178 if issuedTokenType == "" {
179 return nil, fmt.Errorf("response missing required field: issued_token_type")
180 }
181
182 return token, nil
183 }