Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/oauthex/token_exchange_test.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 oauthex
6
7 import (
8 "context"
9 "encoding/json"
10 "net/http"
11 "net/http/httptest"
12 "testing"
13 )
14
15 // TestExchangeToken tests the basic token exchange flow.
16 func TestExchangeToken(t *testing.T) {
17 // Create a test IdP server that implements token exchange
18 server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
19 // Verify request method and content type
20 if r.Method != http.MethodPost {
21 t.Errorf("expected POST request, got %s", r.Method)
22 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
23 return
24 }
25
26 contentType := r.Header.Get("Content-Type")
27 if contentType != "application/x-www-form-urlencoded" {
28 t.Errorf("expected application/x-www-form-urlencoded, got %s", contentType)
29 http.Error(w, "invalid content type", http.StatusBadRequest)
30 return
31 }
32
33 // Parse form data
34 if err := r.ParseForm(); err != nil {
35 http.Error(w, "failed to parse form", http.StatusBadRequest)
36 return
37 }
38
39 // Verify required parameters per SEP-990 Section 4
40 grantType := r.FormValue("grant_type")
41 if grantType != GrantTypeTokenExchange {
42 t.Errorf("expected grant_type %s, got %s", GrantTypeTokenExchange, grantType)
43 writeErrorResponse(w, "invalid_grant", "invalid grant_type")
44 return
45 }
46
47 requestedTokenType := r.FormValue("requested_token_type")
48 if requestedTokenType != TokenTypeIDJAG {
49 t.Errorf("expected requested_token_type %s, got %s", TokenTypeIDJAG, requestedTokenType)
50 writeErrorResponse(w, "invalid_request", "invalid requested_token_type")
51 return
52 }
53
54 audience := r.FormValue("audience")
55 if audience == "" {
56 t.Error("audience is required")
57 writeErrorResponse(w, "invalid_request", "missing audience")
58 return
59 }
60
61 resource := r.FormValue("resource")
62 if resource == "" {
63 t.Error("resource is required")
64 writeErrorResponse(w, "invalid_request", "missing resource")
65 return
66 }
67
68 subjectToken := r.FormValue("subject_token")
69 if subjectToken == "" {
70 t.Error("subject_token is required")
71 writeErrorResponse(w, "invalid_request", "missing subject_token")
72 return
73 }
74
75 subjectTokenType := r.FormValue("subject_token_type")
76 if subjectTokenType != TokenTypeIDToken {
77 t.Errorf("expected subject_token_type %s, got %s", TokenTypeIDToken, subjectTokenType)
78 writeErrorResponse(w, "invalid_request", "invalid subject_token_type")
79 return
80 }
81
82 // Verify client authentication
83 clientID := r.FormValue("client_id")
84 clientSecret := r.FormValue("client_secret")
85 if clientID == "" || clientSecret == "" {
86 t.Error("client authentication required")
87 writeErrorResponse(w, "invalid_client", "client authentication failed")
88 return
89 }
90
91 if clientID != "test-client-id" || clientSecret != "test-client-secret" {
92 t.Error("invalid client credentials")
93 writeErrorResponse(w, "invalid_client", "invalid credentials")
94 return
95 }
96
97 // Return successful token exchange response per SEP-990 Section 4.2
98 resp := map[string]any{
99 "issued_token_type": TokenTypeIDJAG,
100 "access_token": "fake-id-jag-token",
101 "token_type": "N_A",
102 "scope": r.FormValue("scope"),
103 "expires_in": 300,
104 }
105
106 w.Header().Set("Content-Type", "application/json")
107 w.Header().Set("Cache-Control", "no-store")
108 w.Header().Set("Pragma", "no-cache")
109 w.WriteHeader(http.StatusOK)
110 json.NewEncoder(w).Encode(resp)
111 }))
112 defer server.Close()
113
114 // Test successful token exchange
115 t.Run("successful exchange", func(t *testing.T) {
116 req := &TokenExchangeRequest{
117 RequestedTokenType: TokenTypeIDJAG,
118 Audience: "https://auth.mcpserver.example/",
119 Resource: "https://mcp.mcpserver.example/",
120 Scope: []string{"read", "write"},
121 SubjectToken: "fake-id-token",
122 SubjectTokenType: TokenTypeIDToken,
123 }
124
125 token, err := ExchangeToken(
126 context.Background(),
127 server.URL,
128 req,
129 &ClientCredentials{
130 ClientID: "test-client-id",
131 ClientSecretAuth: &ClientSecretAuth{
132 ClientSecret: "test-client-secret",
133 },
134 },
135 server.Client(),
136 )
137
138 if err != nil {
139 t.Fatalf("ExchangeToken failed: %v", err)
140 }
141
142 issuedTokenType, ok := token.Extra("issued_token_type").(string)
143 if !ok || issuedTokenType != TokenTypeIDJAG {
144 t.Errorf("expected issued_token_type %s, got %s", TokenTypeIDJAG, issuedTokenType)
145 }
146
147 if token.AccessToken != "fake-id-jag-token" {
148 t.Errorf("expected access_token 'fake-id-jag-token', got %s", token.AccessToken)
149 }
150
151 if token.TokenType != "N_A" {
152 t.Errorf("expected token_type 'N_A', got %s", token.TokenType)
153 }
154
155 scope, ok := token.Extra("scope").(string)
156 if !ok || scope != "read write" {
157 t.Errorf("expected scope 'read write', got %s", scope)
158 }
159
160 // expires_in should be available in Extra
161 expiresIn, ok := token.Extra("expires_in").(float64)
162 if !ok || int(expiresIn) != 300 {
163 t.Errorf("expected expires_in 300, got %v", expiresIn)
164 }
165 })
166
167 // Test missing required fields
168 t.Run("missing audience", func(t *testing.T) {
169 req := &TokenExchangeRequest{
170 RequestedTokenType: TokenTypeIDJAG,
171 Resource: "https://mcp.mcpserver.example/",
172 SubjectToken: "fake-id-token",
173 SubjectTokenType: TokenTypeIDToken,
174 }
175
176 _, err := ExchangeToken(
177 context.Background(),
178 server.URL,
179 req,
180 &ClientCredentials{
181 ClientID: "test-client-id",
182 ClientSecretAuth: &ClientSecretAuth{
183 ClientSecret: "test-client-secret",
184 },
185 },
186 server.Client(),
187 )
188
189 if err == nil {
190 t.Error("expected error for missing audience, got nil")
191 }
192 })
193
194 // Test invalid URL schemes
195 t.Run("invalid audience URL scheme", func(t *testing.T) {
196 req := &TokenExchangeRequest{
197 RequestedTokenType: TokenTypeIDJAG,
198 Audience: "javascript:alert(1)",
199 Resource: "https://mcp.mcpserver.example/",
200 SubjectToken: "fake-id-token",
201 SubjectTokenType: TokenTypeIDToken,
202 }
203
204 _, err := ExchangeToken(
205 context.Background(),
206 server.URL,
207 req,
208 &ClientCredentials{
209 ClientID: "test-client-id",
210 ClientSecretAuth: &ClientSecretAuth{
211 ClientSecret: "test-client-secret",
212 },
213 },
214 server.Client(),
215 )
216
217 if err == nil {
218 t.Error("expected error for invalid audience URL scheme, got nil")
219 }
220 })
221 }
222
223 // writeErrorResponse writes an OAuth 2.0 error response per RFC 6749 Section 5.2.
224 func writeErrorResponse(w http.ResponseWriter, errorCode, errorDescription string) {
225 errResp := struct {
226 Error string `json:"error"`
227 ErrorDescription string `json:"error_description,omitempty"`
228 }{
229 Error: errorCode,
230 ErrorDescription: errorDescription,
231 }
232
233 w.Header().Set("Content-Type", "application/json")
234 w.Header().Set("Cache-Control", "no-store")
235 w.WriteHeader(http.StatusBadRequest)
236 json.NewEncoder(w).Encode(errResp)
237 }