|
| 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 auth |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "errors" |
| 10 | + "net/http" |
| 11 | + "slices" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +type TokenInfo struct { |
| 17 | + Scopes []string |
| 18 | + Expiration time.Time |
| 19 | +} |
| 20 | + |
| 21 | +type TokenVerifier func(ctx context.Context, token string) (*TokenInfo, error) |
| 22 | + |
| 23 | +type RequireBearerTokenOptions struct { |
| 24 | + Scopes []string |
| 25 | + ResourceMetadataURL string |
| 26 | +} |
| 27 | + |
| 28 | +var ErrInvalidToken = errors.New("invalid token") |
| 29 | + |
| 30 | +type tokenInfoKey struct{} |
| 31 | + |
| 32 | +// RequireBearerToken returns a piece of middleware that verifies a bearer token using the verifier. |
| 33 | +// If verification succeeds, the [TokenInfo] is added to the request's context and the request proceeds. |
| 34 | +// If verification fails, the request fails with a 401 Unauthenticated, and the WWW-Authenticate header |
| 35 | +// is populated to enable [protected resource metadata]. |
| 36 | +// |
| 37 | +// [protected resource metadata]: https://datatracker.ietf.org/doc/rfc9728 |
| 38 | +func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler { |
| 39 | + // Based on typescript-sdk/src/server/auth/middleware/bearerAuth.ts. |
| 40 | + |
| 41 | + return func(handler http.Handler) http.Handler { |
| 42 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 43 | + tokenInfo, errmsg, code := verify(r.Context(), verifier, opts, r.Header.Get("Authorization")) |
| 44 | + if code != 0 { |
| 45 | + if code == http.StatusUnauthorized || code == http.StatusForbidden { |
| 46 | + if opts != nil && opts.ResourceMetadataURL != "" { |
| 47 | + w.Header().Add("WWW-Authenticate", "Bearer resource_metadata="+opts.ResourceMetadataURL) |
| 48 | + } |
| 49 | + } |
| 50 | + http.Error(w, errmsg, code) |
| 51 | + return |
| 52 | + } |
| 53 | + r = r.WithContext(context.WithValue(r.Context(), tokenInfoKey{}, tokenInfo)) |
| 54 | + handler.ServeHTTP(w, r) |
| 55 | + }) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +func verify(ctx context.Context, verifier TokenVerifier, opts *RequireBearerTokenOptions, authHeader string) (_ *TokenInfo, errmsg string, code int) { |
| 60 | + // Extract bearer token. |
| 61 | + fields := strings.Fields(authHeader) |
| 62 | + if len(fields) != 2 || strings.ToLower(fields[0]) != "bearer" { |
| 63 | + return nil, "no bearer token", http.StatusUnauthorized |
| 64 | + } |
| 65 | + |
| 66 | + // Verify the token and get information from it. |
| 67 | + tokenInfo, err := verifier(ctx, fields[1]) |
| 68 | + if err != nil { |
| 69 | + if errors.Is(err, ErrInvalidToken) { |
| 70 | + return nil, err.Error(), http.StatusUnauthorized |
| 71 | + } |
| 72 | + // TODO: the TS SDK distinguishes another error, OAuthError, and returns a 400. |
| 73 | + // Investigate how that works. |
| 74 | + // See typescript-sdk/src/server/auth/middleware/bearerAuth.ts. |
| 75 | + return nil, err.Error(), http.StatusInternalServerError |
| 76 | + } |
| 77 | + |
| 78 | + // Check scopes. |
| 79 | + if opts != nil { |
| 80 | + // Note: quadratic, but N is small. |
| 81 | + for _, s := range opts.Scopes { |
| 82 | + if !slices.Contains(tokenInfo.Scopes, s) { |
| 83 | + return nil, "insufficient scope", http.StatusForbidden |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + // Check expiration. |
| 89 | + if tokenInfo.Expiration.IsZero() { |
| 90 | + return nil, "token missing expiration", http.StatusUnauthorized |
| 91 | + } |
| 92 | + if tokenInfo.Expiration.Before(time.Now()) { |
| 93 | + return nil, "token expired", http.StatusUnauthorized |
| 94 | + } |
| 95 | + return tokenInfo, "", 0 |
| 96 | +} |
0 commit comments