Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/auth/auth.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 auth
6
7 import (
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "net/http"
13 "slices"
14 "strings"
15 "time"
16
17 "github.com/modelcontextprotocol/go-sdk/oauthex"
18 )
19
20 // TokenInfo holds information from a bearer token.
21 type TokenInfo struct {
22 Scopes []string
23 Expiration time.Time
24 // UserID is an optional identifier for the authenticated user.
25 // If set by a TokenVerifier, it can be used by transports to prevent
26 // session hijacking by ensuring that all requests for a given session
27 // come from the same user.
28 UserID string
29 Extra map[string]any
30 }
31
32 // The error that a TokenVerifier should return if the token cannot be verified.
33 var ErrInvalidToken = errors.New("invalid token")
34
35 // The error that a TokenVerifier should return for OAuth-specific protocol errors.
36 var ErrOAuth = errors.New("oauth error")
37
38 // A TokenVerifier checks the validity of a bearer token, and extracts information
39 // from it. If verification fails, it should return an error that unwraps to ErrInvalidToken.
40 // The HTTP request is provided in case verifying the token involves checking it.
41 type TokenVerifier func(ctx context.Context, token string, req *http.Request) (*TokenInfo, error)
42
43 // RequireBearerTokenOptions are options for [RequireBearerToken].
44 type RequireBearerTokenOptions struct {
45 // The URL for the resource server metadata OAuth flow, to be returned as part
46 // of the WWW-Authenticate header.
47 ResourceMetadataURL string
48 // The required scopes.
49 Scopes []string
50 }
51
52 type tokenInfoKey struct{}
53
54 // TokenInfoFromContext returns the [TokenInfo] stored in ctx, or nil if none.
55 func TokenInfoFromContext(ctx context.Context) *TokenInfo {
56 ti := ctx.Value(tokenInfoKey{})
57 if ti == nil {
58 return nil
59 }
60 return ti.(*TokenInfo)
61 }
62
63 // RequireBearerToken returns a piece of middleware that verifies a bearer token using the verifier.
64 // If verification succeeds, the [TokenInfo] is added to the request's context and the request proceeds.
65 // If verification fails, the request fails with a 401 Unauthenticated, and the WWW-Authenticate header
66 // is populated to enable [protected resource metadata].
67 //
68 // [protected resource metadata]: https://datatracker.ietf.org/doc/rfc9728
69 func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler {
70 // Based on typescript-sdk/src/server/auth/middleware/bearerAuth.ts.
71
72 return func(handler http.Handler) http.Handler {
73 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
74 tokenInfo, errmsg, code := verify(r, verifier, opts)
75 if code != 0 {
76 if code == http.StatusUnauthorized || code == http.StatusForbidden {
77 if opts != nil {
78 var params []string
79 if opts.ResourceMetadataURL != "" {
80 params = append(params, fmt.Sprintf("resource_metadata=%q", opts.ResourceMetadataURL))
81 }
82 if len(opts.Scopes) > 0 {
83 params = append(params, fmt.Sprintf("scope=%q", strings.Join(opts.Scopes, " ")))
84 }
85 if len(params) > 0 {
86 w.Header().Add("WWW-Authenticate", "Bearer "+strings.Join(params, ", "))
87 }
88 }
89 }
90 http.Error(w, errmsg, code)
91 return
92 }
93 r = r.WithContext(context.WithValue(r.Context(), tokenInfoKey{}, tokenInfo))
94 handler.ServeHTTP(w, r)
95 })
96 }
97 }
98
99 func verify(req *http.Request, verifier TokenVerifier, opts *RequireBearerTokenOptions) (_ *TokenInfo, errmsg string, code int) {
100 // Extract bearer token.
101 authHeader := req.Header.Get("Authorization")
102 fields := strings.Fields(authHeader)
103 if len(fields) != 2 || strings.ToLower(fields[0]) != "bearer" {
104 return nil, "no bearer token", http.StatusUnauthorized
105 }
106
107 // Verify the token and get information from it.
108 tokenInfo, err := verifier(req.Context(), fields[1], req)
109 if err != nil {
110 if errors.Is(err, ErrInvalidToken) {
111 return nil, err.Error(), http.StatusUnauthorized
112 }
113 if errors.Is(err, ErrOAuth) {
114 return nil, err.Error(), http.StatusBadRequest
115 }
116 return nil, err.Error(), http.StatusInternalServerError
117 }
118 if tokenInfo == nil {
119 return nil, "token validation failed", http.StatusInternalServerError
120 }
121
122 // Check scopes. All must be present.
123 if opts != nil {
124 // Note: quadratic, but N is small.
125 for _, s := range opts.Scopes {
126 if !slices.Contains(tokenInfo.Scopes, s) {
127 return nil, "insufficient scope", http.StatusForbidden
128 }
129 }
130 }
131
132 // Check expiration.
133 if tokenInfo.Expiration.IsZero() {
134 return nil, "token missing expiration", http.StatusUnauthorized
135 }
136 if tokenInfo.Expiration.Before(time.Now()) {
137 return nil, "token expired", http.StatusUnauthorized
138 }
139 return tokenInfo, "", 0
140 }
141
142 // ProtectedResourceMetadataHandler returns an http.Handler that serves OAuth 2.0
143 // protected resource metadata (RFC 9728) with CORS support.
144 //
145 // This handler allows cross-origin requests from any origin (Access-Control-Allow-Origin: *)
146 // because OAuth metadata is public information intended for client discovery (RFC 9728 ยง3.1).
147 // The metadata contains only non-sensitive configuration data about authorization servers
148 // and supported scopes.
149 //
150 // No validation of metadata fields is performed; ensure metadata accuracy at configuration time.
151 //
152 // For more sophisticated CORS policies or to restrict origins, wrap this handler with a
153 // CORS middleware like github.com/rs/cors or github.com/jub0bs/cors.
154 func ProtectedResourceMetadataHandler(metadata *oauthex.ProtectedResourceMetadata) http.Handler {
155 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
156 // Set CORS headers for cross-origin client discovery.
157 // OAuth metadata is public information, so allowing any origin is safe.
158 w.Header().Set("Access-Control-Allow-Origin", "*")
159 w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
160 w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
161
162 // Handle CORS preflight requests
163 if r.Method == http.MethodOptions {
164 w.WriteHeader(http.StatusNoContent)
165 return
166 }
167
168 // Only GET allowed for metadata retrieval
169 if r.Method != http.MethodGet {
170 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
171 return
172 }
173
174 w.Header().Set("Content-Type", "application/json")
175 if err := json.NewEncoder(w).Encode(metadata); err != nil {
176 http.Error(w, "Failed to encode metadata", http.StatusInternalServerError)
177 return
178 }
179 })
180 }