Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/oauthex/oauthex_test.go

raw symbols SCIP
1 // Copyright 2025 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 "bytes"
9 "crypto/sha256"
10 "encoding/base64"
11 "encoding/json"
12 "fmt"
13 "net/http"
14 "strings"
15 "sync"
16 "time"
17
18 "github.com/golang-jwt/jwt/v5"
19 )
20
21 const (
22 tokenExpiry = time.Hour
23 )
24
25 var jwtSigningKey = []byte("fake-secret-key")
26
27 type authCodeInfo struct {
28 codeChallenge string
29 redirectURI string
30 }
31
32 type state struct {
33 mu sync.Mutex
34 authCodes map[string]authCodeInfo
35 }
36
37 // NewFakeMCPServerMux constructs a ServeMux that implements an MCP server
38 // with an integrated OAuth 2.1 authentication server. It should be used with
39 // [httptest.NewTLSServer].
40 func NewFakeMCPServerMux() *http.ServeMux {
41 s := &state{authCodes: make(map[string]authCodeInfo)}
42 mux := http.NewServeMux()
43 mux.HandleFunc("/mcp", s.handleMCP)
44 mux.HandleFunc("/.well-known/oauth-protected-resource", s.handleProtectedResourceMetadata)
45 mux.HandleFunc("/.well-known/oauth-authorization-server", s.handleServerMetadata)
46 mux.HandleFunc("/register", s.handleDynamicClientRegistration)
47 mux.HandleFunc("/authorize", s.handleAuthorize)
48 mux.HandleFunc("/token", s.handleToken)
49 return mux
50 }
51
52 // handleMCP is the protected resource endpoint. It requires a valid Bearer token.
53 // If the token is missing or invalid, it returns a 401 Unauthorized response
54 // with a WWW-Authenticate header pointing to the resource metadata.
55 func (s *state) handleMCP(w http.ResponseWriter, r *http.Request) {
56 authHeader := r.Header.Get("Authorization")
57 tokenString := strings.TrimPrefix(authHeader, "Bearer ")
58
59 token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
60 if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
61 return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
62 }
63 return jwtSigningKey, nil
64 })
65
66 if err != nil || !token.Valid {
67 metadataURL := getBaseURL(r) + "/.well-known/oauth-protected-resource"
68 w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer resource_metadata="%s", scope="openid profile email"`, metadataURL))
69 http.Error(w, "Unauthorized", http.StatusUnauthorized)
70 return
71 }
72
73 // Token is valid, serve the resource.
74 w.Header().Set("Content-Type", "text/plain")
75 w.WriteHeader(http.StatusOK)
76 fmt.Fprintln(w, "Hello from a protected MCP server!")
77 }
78
79 // handleProtectedResourceMetadata serves the OAuth 2.0 Protected Resource Metadata document,
80 // as defined in RFC 9728.
81 func (s *state) handleProtectedResourceMetadata(w http.ResponseWriter, r *http.Request) {
82 // Construct the authorization server issuer URL dynamically.
83 authServerIssuer := getBaseURL(r)
84
85 metadata := ProtectedResourceMetadata{
86 ScopesSupported: []string{"openid", "profile", "email"},
87 AuthorizationServers: []string{authServerIssuer},
88 }
89 var buf bytes.Buffer
90 if err := json.NewEncoder(&buf).Encode(metadata); err != nil {
91 http.Error(w, err.Error(), http.StatusInternalServerError)
92 return
93 }
94 w.Header().Set("Content-Type", "application/json")
95 w.WriteHeader(http.StatusOK)
96 w.Write(buf.Bytes())
97 }
98
99 func (s *state) handleServerMetadata(w http.ResponseWriter, r *http.Request) {
100 issuer := getBaseURL(r)
101 metadata := AuthServerMeta{
102 Issuer: issuer,
103 AuthorizationEndpoint: issuer + "/authorize",
104 TokenEndpoint: issuer + "/token",
105 RegistrationEndpoint: issuer + "/register",
106 JWKSURI: issuer + "/.well-known/jwks.json",
107 ScopesSupported: []string{"openid", "profile", "email"},
108 ResponseTypesSupported: []string{"code"},
109 GrantTypesSupported: []string{"authorization_code"},
110 TokenEndpointAuthMethodsSupported: []string{"none"},
111 CodeChallengeMethodsSupported: []string{"S256"},
112 }
113 var buf bytes.Buffer
114 if err := json.NewEncoder(&buf).Encode(metadata); err != nil {
115 http.Error(w, err.Error(), http.StatusInternalServerError)
116 return
117 }
118 w.Header().Set("Content-Type", "application/json")
119 w.Write(buf.Bytes())
120 }
121
122 // handleDynamicClientRegistration handles dynamic client registration requests,
123 // as defined in RFC 7591.
124 func (s *state) handleDynamicClientRegistration(w http.ResponseWriter, r *http.Request) {
125 if r.Method != http.MethodPost {
126 http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
127 return
128 }
129
130 var crm ClientRegistrationMetadata
131 if err := json.NewDecoder(r.Body).Decode(&crm); err != nil {
132 http.Error(w, fmt.Sprintf("invalid JSON in request body: %v", err), http.StatusBadRequest)
133 return
134 }
135 clientID := fmt.Sprintf("fake-client-%d", time.Now().UnixNano())
136
137 response := ClientRegistrationResponse{
138 ClientRegistrationMetadata: crm,
139 ClientID: clientID,
140 ClientIDIssuedAt: time.Now(),
141 ClientSecret: "fake-registration-access-secret",
142 }
143 var buf bytes.Buffer
144 if err := json.NewEncoder(&buf).Encode(response); err != nil {
145 http.Error(w, err.Error(), http.StatusInternalServerError)
146 return
147 }
148 w.Header().Set("Content-Type", "application/json")
149 w.WriteHeader(http.StatusCreated)
150 w.Write(buf.Bytes())
151 }
152
153 func (s *state) handleToken(w http.ResponseWriter, r *http.Request) {
154 r.ParseForm()
155 grantType := r.Form.Get("grant_type")
156 code := r.Form.Get("code")
157 codeVerifier := r.Form.Get("code_verifier")
158 // Ignore redirect_uri; it is not required in 2.1.
159 // https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-13.html#redirect-uri-in-token-request
160
161 if grantType != "authorization_code" {
162 http.Error(w, "unsupported_grant_type", http.StatusBadRequest)
163 return
164 }
165 s.mu.Lock()
166 authCodeInfo, ok := s.authCodes[code]
167 if !ok {
168 http.Error(w, "invalid_grant", http.StatusBadRequest)
169 return
170 }
171 delete(s.authCodes, code)
172 s.mu.Unlock()
173
174 // PKCE verification.
175 hasher := sha256.New()
176 hasher.Write([]byte(codeVerifier))
177 calculatedChallenge := base64.RawURLEncoding.EncodeToString(hasher.Sum(nil))
178 if calculatedChallenge != authCodeInfo.codeChallenge {
179 http.Error(w, "invalid_grant", http.StatusBadRequest)
180 return
181 }
182
183 // Issue JWT.
184 now := time.Now()
185 claims := jwt.MapClaims{
186 "iss": getBaseURL(r),
187 "sub": "fake-user-id",
188 "aud": "fake-client-id",
189 "exp": now.Add(tokenExpiry).Unix(),
190 "iat": now.Unix(),
191 }
192 token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
193 accessToken, err := token.SignedString(jwtSigningKey)
194 if err != nil {
195 http.Error(w, "server_error", http.StatusInternalServerError)
196 return
197 }
198
199 tokenResponse := map[string]any{
200 "access_token": accessToken,
201 "token_type": "Bearer",
202 "expires_in": int(tokenExpiry.Seconds()),
203 }
204 var buf bytes.Buffer
205 if err := json.NewEncoder(&buf).Encode(tokenResponse); err != nil {
206 http.Error(w, err.Error(), http.StatusInternalServerError)
207 return
208 }
209 w.Header().Set("Content-Type", "application/json")
210 w.Write(buf.Bytes())
211 }
212
213 func (s *state) handleAuthorize(w http.ResponseWriter, r *http.Request) {
214 query := r.URL.Query()
215 responseType := query.Get("response_type")
216 redirectURI := query.Get("redirect_uri")
217 codeChallenge := query.Get("code_challenge")
218 codeChallengeMethod := query.Get("code_challenge_method")
219
220 if responseType != "code" {
221 http.Error(w, "unsupported_response_type", http.StatusBadRequest)
222 return
223 }
224 if redirectURI == "" {
225 http.Error(w, "invalid_request (no redirect_uri)", http.StatusBadRequest)
226 return
227 }
228 if codeChallenge == "" || codeChallengeMethod != "S256" {
229 http.Error(w, "invalid_request (code challenge is not S256)", http.StatusBadRequest)
230 return
231 }
232 if query.Get("client_id") == "" {
233 http.Error(w, "invalid_request (missing client_id)", http.StatusBadRequest)
234 return
235 }
236
237 authCode := "fake-auth-code-" + fmt.Sprintf("%d", time.Now().UnixNano())
238 s.mu.Lock()
239 s.authCodes[authCode] = authCodeInfo{
240 codeChallenge: codeChallenge,
241 redirectURI: redirectURI,
242 }
243 s.mu.Unlock()
244
245 redirectURL := fmt.Sprintf("%s?code=%s&state=%s", redirectURI, authCode, query.Get("state"))
246 http.Redirect(w, r, redirectURL, http.StatusFound)
247 }
248
249 // getBaseURL constructs the base URL (scheme://host) from the request.
250 func getBaseURL(r *http.Request) string {
251 scheme := "http"
252 if r.TLS != nil {
253 scheme = "https"
254 }
255 return scheme + "://" + r.Host
256 }