| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 32 |
|
| 33 |
ServeOAuthInsertedEndpoint bool |
| 34 |
|
| 35 |
|
| 36 |
ServeOpenIDInsertedEndpoint bool |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
ServeOpenIDAppendedEndpoint bool |
| 41 |
} |
| 42 |
|
| 43 |
type RegistrationConfig struct { |
| 44 |
|
| 45 |
ClientIDMetadataDocumentSupported bool |
| 46 |
|
| 47 |
PreregisteredClients map[string]ClientInfo |
| 48 |
|
| 49 |
DynamicClientRegistrationEnabled bool |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
type JWTBearerConfig struct { |
| 55 |
|
| 56 |
|
| 57 |
ValidAssertions []string |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
type ClientCredentialsConfig struct { |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
Enabled bool |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
type Config struct { |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
IssuerPath string |
| 75 |
|
| 76 |
MetadataEndpointConfig *MetadataEndpointConfig |
| 77 |
|
| 78 |
RegistrationConfig *RegistrationConfig |
| 79 |
|
| 80 |
|
| 81 |
JWTBearerConfig *JWTBearerConfig |
| 82 |
|
| 83 |
|
| 84 |
ClientCredentialsConfig *ClientCredentialsConfig |
| 85 |
} |
| 86 |
|
| 87 |
|
| 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 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 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 |
|
| 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 |
|
| 145 |
func (s *FakeAuthorizationServer) Start(t testing.TB) { |
| 146 |
s.server.Start() |
| 147 |
t.Cleanup(s.server.Close) |
| 148 |
} |
| 149 |
|
| 150 |
|
| 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 |
|
| 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 |
|
| 180 |
if r.Method == http.MethodOptions { |
| 181 |
w.WriteHeader(http.StatusNoContent) |
| 182 |
return |
| 183 |
} |
| 184 |
|
| 185 |
|
| 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 |
|
| 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 |
} |