Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/internal/oauthtest/fake_authorization_server.go

raw symbols SCIP
1 // Copyright 2026 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by the license
3 // that can be found in the LICENSE file.
4
5 package oauthtest
6
7 import (
8 "crypto/rand"
9 "crypto/sha256"
10 "encoding/base64"
11 "encoding/json"
12 "errors"
13 "fmt"
14 "io"
15 "maps"
16 "net/http"
17 "net/http/httptest"
18 "slices"
19 "testing"
20
21 internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
22 "github.com/modelcontextprotocol/go-sdk/oauthex"
23 )
24
25 type ClientInfo struct {
26 Secret string
27 RedirectURIs []string
28 }
29
30 type MetadataEndpointConfig struct {
31 // Whether to serve the OAuth Authorization Server Metadata at
32 // /.well-known/oauth-authorization-server + issuerPath.
33 ServeOAuthInsertedEndpoint bool
34 // Whether to serve the OAuth Authorization Server Metadata at
35 // /.well-known/openid-configuration + issuerPath.
36 ServeOpenIDInsertedEndpoint bool
37 // Whether to serve the OAuth Authorization Server Metadata at
38 // issuerPath + /.well-known/openid-configuration.
39 // Should be used when issuerPath is not empty.
40 ServeOpenIDAppendedEndpoint bool
41 }
42
43 type RegistrationConfig struct {
44 // Whether the client ID metadata document is supported.
45 ClientIDMetadataDocumentSupported bool
46 // PreregisteredClients is a map of valid ClientIDs to ClientSecrets.
47 PreregisteredClients map[string]ClientInfo
48 // Whether dynamic client registration is enabled.
49 DynamicClientRegistrationEnabled bool
50 }
51
52 // JWTBearerConfig configures support for the JWT Bearer grant type (RFC 7523)
53 // on a [FakeAuthorizationServer].
54 type JWTBearerConfig struct {
55 // ValidAssertions is the set of assertion values that are accepted.
56 // If empty, any non-empty assertion is accepted.
57 ValidAssertions []string
58 }
59
60 // ClientCredentialsConfig configures support for the client_credentials
61 // grant type (RFC 6749 Section 4.4) on a [FakeAuthorizationServer].
62 type ClientCredentialsConfig struct {
63 // Enabled controls whether the /token endpoint accepts
64 // grant_type=client_credentials and returns an access token
65 // if client authentication succeeds.
66 Enabled bool
67 }
68
69 // Config holds configuration for FakeAuthorizationServer.
70 type Config struct {
71 // The optional path component of the issuer URL.
72 // If non-empty, it should start with a "/". It should not end with a "/".
73 // It affects the paths of the server endpoints.
74 IssuerPath string
75 // Configuration of the metadata endpoint.
76 MetadataEndpointConfig *MetadataEndpointConfig
77 // Configuration for client registration.
78 RegistrationConfig *RegistrationConfig
79 // JWTBearerConfig enables RFC 7523 JWT Bearer grant at the /token endpoint.
80 // If non-nil, the server accepts grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer.
81 JWTBearerConfig *JWTBearerConfig
82 // ClientCredentialsConfig enables RFC 6749 Section 4.4 client credentials
83 // grant at the /token endpoint.
84 ClientCredentialsConfig *ClientCredentialsConfig
85 }
86
87 // FakeAuthorizationServer is a fake OAuth 2.0 Authorization Server for testing.
88 type FakeAuthorizationServer struct {
89 server *httptest.Server
90 Mux *http.ServeMux
91 config Config
92 clients map[string]ClientInfo
93 codes map[string]codeInfo
94 }
95
96 type codeInfo struct {
97 CodeChallenge string
98 }
99
100 // NewFakeAuthorizationServer creates a new FakeAuthorizationServer.
101 // The server is simple and should not be used outside of testing.
102 // It supports:
103 // - Only the authorization Code Grant
104 // - PKCE verification
105 // - Client tracking & dynamic registration
106 // - Client authentication
107 func NewFakeAuthorizationServer(config Config) *FakeAuthorizationServer {
108 s := &FakeAuthorizationServer{
109 Mux: http.NewServeMux(),
110 config: config,
111 codes: make(map[string]codeInfo),
112 }
113 if config.RegistrationConfig != nil {
114 s.clients = maps.Clone(config.RegistrationConfig.PreregisteredClients)
115 }
116 if s.clients == nil {
117 s.clients = make(map[string]ClientInfo)
118 }
119
120 s.Mux.HandleFunc(s.config.IssuerPath+"/authorize", s.handleAuthorize)
121 s.Mux.HandleFunc(s.config.IssuerPath+"/token", s.handleToken)
122 if config.MetadataEndpointConfig != nil {
123 if config.MetadataEndpointConfig.ServeOAuthInsertedEndpoint {
124 s.Mux.HandleFunc("/.well-known/oauth-authorization-server"+s.config.IssuerPath, s.handleMetadata)
125 }
126 if config.MetadataEndpointConfig.ServeOpenIDInsertedEndpoint {
127 s.Mux.HandleFunc("/.well-known/openid-configuration"+s.config.IssuerPath, s.handleMetadata)
128 }
129 if config.MetadataEndpointConfig.ServeOpenIDAppendedEndpoint && s.config.IssuerPath != "" {
130 s.Mux.HandleFunc(s.config.IssuerPath+"/.well-known/openid-configuration", s.handleMetadata)
131 }
132 } else {
133 // Serve the default OAuth endpoint.
134 s.Mux.HandleFunc("/.well-known/oauth-authorization-server", s.handleMetadata)
135 }
136 if config.RegistrationConfig != nil && config.RegistrationConfig.DynamicClientRegistrationEnabled {
137 s.Mux.HandleFunc(s.config.IssuerPath+"/register", s.handleRegister)
138 }
139 s.server = httptest.NewUnstartedServer(s.Mux)
140
141 return s
142 }
143
144 // Start starts the HTTP server and registers a cleanup function on t to close the server.
145 func (s *FakeAuthorizationServer) Start(t testing.TB) {
146 s.server.Start()
147 t.Cleanup(s.server.Close)
148 }
149
150 // URL returns the base URL of the server (Issuer).
151 func (s *FakeAuthorizationServer) URL() string {
152 return s.server.URL
153 }
154
155 func (s *FakeAuthorizationServer) handleMetadata(w http.ResponseWriter, r *http.Request) {
156 cimdSupported := false
157 var registrationEndpoint string
158 if s.config.RegistrationConfig != nil {
159 cimdSupported = s.config.RegistrationConfig.ClientIDMetadataDocumentSupported
160 if s.config.RegistrationConfig.DynamicClientRegistrationEnabled {
161 registrationEndpoint = s.URL() + s.config.IssuerPath + "/register"
162 }
163 }
164 meta := &oauthex.AuthServerMeta{
165 Issuer: s.URL() + s.config.IssuerPath,
166 AuthorizationEndpoint: s.URL() + s.config.IssuerPath + "/authorize",
167 TokenEndpoint: s.URL() + s.config.IssuerPath + "/token",
168 RegistrationEndpoint: registrationEndpoint,
169 ResponseTypesSupported: []string{"code"},
170 CodeChallengeMethodsSupported: []string{"S256"},
171 ClientIDMetadataDocumentSupported: cimdSupported,
172 TokenEndpointAuthMethodsSupported: []string{"client_secret_post", "client_secret_basic"},
173 }
174 // Set CORS headers for cross-origin client discovery.
175 w.Header().Set("Access-Control-Allow-Origin", "*")
176 w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
177 w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
178
179 // Handle CORS preflight requests
180 if r.Method == http.MethodOptions {
181 w.WriteHeader(http.StatusNoContent)
182 return
183 }
184
185 // Only GET allowed for metadata retrieval
186 if r.Method != http.MethodGet {
187 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
188 return
189 }
190
191 w.Header().Set("Content-Type", "application/json")
192 if err := json.NewEncoder(w).Encode(meta); err != nil {
193 http.Error(w, "Failed to encode metadata", http.StatusInternalServerError)
194 return
195 }
196 }
197
198 func (s *FakeAuthorizationServer) handleRegister(w http.ResponseWriter, r *http.Request) {
199 if r.Method != http.MethodPost {
200 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
201 return
202 }
203 var metadata oauthex.ClientRegistrationMetadata
204 body, err := io.ReadAll(r.Body)
205 if err != nil {
206 http.Error(w, "failed to read request body", http.StatusBadRequest)
207 return
208 }
209 if err := internaljson.Unmarshal(body, &metadata); err != nil {
210 http.Error(w, "failed to parse request", http.StatusBadRequest)
211 return
212 }
213 w.Header().Set("Content-Type", "application/json")
214 w.WriteHeader(http.StatusCreated)
215 clientID := rand.Text()
216 ci := ClientInfo{
217 Secret: rand.Text(),
218 RedirectURIs: metadata.RedirectURIs,
219 }
220 s.clients[clientID] = ci
221 metadata.TokenEndpointAuthMethod = "client_secret_basic"
222 json.NewEncoder(w).Encode(&oauthex.ClientRegistrationResponse{
223 ClientID: clientID,
224 ClientSecret: ci.Secret,
225 ClientRegistrationMetadata: metadata,
226 })
227 }
228
229 func (s *FakeAuthorizationServer) handleAuthorize(w http.ResponseWriter, r *http.Request) {
230 if r.Method != http.MethodGet {
231 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
232 return
233 }
234 clientID := r.URL.Query().Get("client_id")
235 clientInfo, ok := s.clients[clientID]
236 if !ok {
237 http.Error(w, "unknown client_id", http.StatusBadRequest)
238 return
239 }
240
241 redirectURI := r.URL.Query().Get("redirect_uri")
242 if redirectURI == "" {
243 http.Error(w, "missing redirect_uri", http.StatusBadRequest)
244 return
245 }
246 if !slices.Contains(clientInfo.RedirectURIs, redirectURI) {
247 http.Error(w, "invalid redirect_uri", http.StatusBadRequest)
248 return
249 }
250 codeChallenge := r.URL.Query().Get("code_challenge")
251 if codeChallenge == "" {
252 http.Error(w, "missing code_challenge", http.StatusBadRequest)
253 return
254 }
255 code := rand.Text()
256 s.codes[code] = codeInfo{
257 CodeChallenge: codeChallenge,
258 }
259
260 state := r.URL.Query().Get("state")
261
262 redirectURL := fmt.Sprintf("%s?code=%s&state=%s", redirectURI, code, state)
263 http.Redirect(w, r, redirectURL, http.StatusFound)
264 }
265
266 func (s *FakeAuthorizationServer) handleToken(w http.ResponseWriter, r *http.Request) {
267 if err := r.ParseForm(); err != nil {
268 http.Error(w, "failed to parse form", http.StatusBadRequest)
269 return
270 }
271 if r.Method != http.MethodPost {
272 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
273 return
274 }
275 if err := s.authenticateClient(r); err != nil {
276 http.Error(w, err.Error(), http.StatusUnauthorized)
277 return
278 }
279
280 grantType := r.Form.Get("grant_type")
281 switch grantType {
282 case "authorization_code":
283 s.handleAuthorizationCodeGrant(w, r)
284 case "urn:ietf:params:oauth:grant-type:jwt-bearer":
285 s.handleJWTBearerGrant(w, r)
286 case "client_credentials":
287 s.handleClientCredentialsGrant(w, r)
288 default:
289 http.Error(w, fmt.Sprintf("unsupported grant_type: %s", grantType), http.StatusBadRequest)
290 }
291 }
292
293 func (s *FakeAuthorizationServer) handleAuthorizationCodeGrant(w http.ResponseWriter, r *http.Request) {
294 code := r.Form.Get("code")
295 if code == "" {
296 http.Error(w, "missing code", http.StatusBadRequest)
297 return
298 }
299 codeInfo, ok := s.codes[code]
300 if !ok {
301 http.Error(w, "unknown authorization code", http.StatusBadRequest)
302 return
303 }
304 verifier := r.Form.Get("code_verifier")
305 if verifier == "" {
306 http.Error(w, "missing code_verifier", http.StatusBadRequest)
307 return
308 }
309 sha := sha256.Sum256([]byte(verifier))
310 expectedChallenge := base64.RawURLEncoding.EncodeToString(sha[:])
311 if expectedChallenge != codeInfo.CodeChallenge {
312 http.Error(w, "PKCE verification failed", http.StatusBadRequest)
313 return
314 }
315
316 w.Header().Set("Content-Type", "application/json")
317 json.NewEncoder(w).Encode(map[string]any{
318 "access_token": "test_access_token",
319 "token_type": "Bearer",
320 "expires_in": 3600,
321 })
322 }
323
324 func (s *FakeAuthorizationServer) handleJWTBearerGrant(w http.ResponseWriter, r *http.Request) {
325 if s.config.JWTBearerConfig == nil {
326 http.Error(w, "JWT bearer grant not supported", http.StatusBadRequest)
327 return
328 }
329 assertion := r.Form.Get("assertion")
330 if assertion == "" {
331 http.Error(w, "missing assertion", http.StatusBadRequest)
332 return
333 }
334 if len(s.config.JWTBearerConfig.ValidAssertions) > 0 {
335 if !slices.Contains(s.config.JWTBearerConfig.ValidAssertions, assertion) {
336 http.Error(w, "invalid assertion", http.StatusBadRequest)
337 return
338 }
339 }
340
341 w.Header().Set("Content-Type", "application/json")
342 json.NewEncoder(w).Encode(map[string]any{
343 "access_token": "test_access_token",
344 "token_type": "Bearer",
345 "expires_in": 3600,
346 })
347 }
348
349 func (s *FakeAuthorizationServer) handleClientCredentialsGrant(w http.ResponseWriter, r *http.Request) {
350 if s.config.ClientCredentialsConfig == nil || !s.config.ClientCredentialsConfig.Enabled {
351 http.Error(w, "client_credentials grant not supported", http.StatusBadRequest)
352 return
353 }
354 // Client was already authenticated in handleToken.
355 w.Header().Set("Content-Type", "application/json")
356 json.NewEncoder(w).Encode(map[string]any{
357 "access_token": "test_access_token",
358 "token_type": "Bearer",
359 "expires_in": 3600,
360 })
361 }
362
363 func (s *FakeAuthorizationServer) authenticateClient(r *http.Request) error {
364 clientID, clientSecret, ok := r.BasicAuth()
365 if !ok {
366 clientID = r.Form.Get("client_id")
367 clientSecret = r.Form.Get("client_secret")
368 }
369
370 clientInfo, ok := s.clients[clientID]
371 if !ok || clientInfo.Secret != clientSecret {
372 return errors.New("client not found")
373 }
374 return nil
375 }