| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 21 |
type TokenInfo struct { |
| 22 |
Scopes []string |
| 23 |
Expiration time.Time |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
UserID string |
| 29 |
Extra map[string]any |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
var ErrInvalidToken = errors.New("invalid token") |
| 34 |
|
| 35 |
|
| 36 |
var ErrOAuth = errors.New("oauth error") |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
type TokenVerifier func(ctx context.Context, token string, req *http.Request) (*TokenInfo, error) |
| 42 |
|
| 43 |
|
| 44 |
type RequireBearerTokenOptions struct { |
| 45 |
|
| 46 |
|
| 47 |
ResourceMetadataURL string |
| 48 |
|
| 49 |
Scopes []string |
| 50 |
} |
| 51 |
|
| 52 |
type tokenInfoKey struct{} |
| 53 |
|
| 54 |
|
| 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 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
func RequireBearerToken(verifier TokenVerifier, opts *RequireBearerTokenOptions) func(http.Handler) http.Handler { |
| 70 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 123 |
if opts != nil { |
| 124 |
|
| 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 |
|
| 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 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
. |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
func ProtectedResourceMetadataHandler(metadata *oauthex.ProtectedResourceMetadata) http.Handler { |
| 155 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 156 |
|
| 157 |
|
| 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 |
|
| 163 |
if r.Method == http.MethodOptions { |
| 164 |
w.WriteHeader(http.StatusNoContent) |
| 165 |
return |
| 166 |
} |
| 167 |
|
| 168 |
|
| 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 |
} |