| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package auth |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"encoding/json" |
| 10 |
"errors" |
| 11 |
"net/http" |
| 12 |
"net/http/httptest" |
| 13 |
"strings" |
| 14 |
"testing" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/modelcontextprotocol/go-sdk/oauthex" |
| 18 |
) |
| 19 |
|
| 20 |
func TestVerify(t *testing.T) { |
| 21 |
verifier := func(_ context.Context, token string, _ *http.Request) (*TokenInfo, error) { |
| 22 |
switch token { |
| 23 |
case "valid": |
| 24 |
return &TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil |
| 25 |
case "invalid": |
| 26 |
return nil, ErrInvalidToken |
| 27 |
case "oauth": |
| 28 |
return nil, ErrOAuth |
| 29 |
case "noexp": |
| 30 |
return &TokenInfo{}, nil |
| 31 |
case "expired": |
| 32 |
return &TokenInfo{Expiration: time.Now().Add(-time.Hour)}, nil |
| 33 |
default: |
| 34 |
return nil, errors.New("unknown") |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
for _, tt := range []struct { |
| 39 |
name string |
| 40 |
opts *RequireBearerTokenOptions |
| 41 |
header string |
| 42 |
wantMsg string |
| 43 |
wantCode int |
| 44 |
}{ |
| 45 |
{ |
| 46 |
"valid", nil, "Bearer valid", |
| 47 |
"", 0, |
| 48 |
}, |
| 49 |
{ |
| 50 |
"bad header", nil, "Barer valid", |
| 51 |
"no bearer token", 401, |
| 52 |
}, |
| 53 |
{ |
| 54 |
"invalid", nil, "bearer invalid", |
| 55 |
"invalid token", 401, |
| 56 |
}, |
| 57 |
{ |
| 58 |
"oauth error", nil, "Bearer oauth", |
| 59 |
"oauth error", 400, |
| 60 |
}, |
| 61 |
{ |
| 62 |
"no expiration", nil, "Bearer noexp", |
| 63 |
"token missing expiration", 401, |
| 64 |
}, |
| 65 |
{ |
| 66 |
"expired", nil, "Bearer expired", |
| 67 |
"token expired", 401, |
| 68 |
}, |
| 69 |
{ |
| 70 |
"missing scope", &RequireBearerTokenOptions{Scopes: []string{"s1"}}, "Bearer valid", |
| 71 |
"insufficient scope", 403, |
| 72 |
}, |
| 73 |
} { |
| 74 |
t.Run(tt.name, func(t *testing.T) { |
| 75 |
_, gotMsg, gotCode := verify(&http.Request{ |
| 76 |
Header: http.Header{"Authorization": {tt.header}}, |
| 77 |
}, verifier, tt.opts) |
| 78 |
if gotMsg != tt.wantMsg || gotCode != tt.wantCode { |
| 79 |
t.Errorf("got (%q, %d), want (%q, %d)", gotMsg, gotCode, tt.wantMsg, tt.wantCode) |
| 80 |
} |
| 81 |
}) |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
func TestProtectedResourceMetadataHandler(t *testing.T) { |
| 86 |
metadata := &oauthex.ProtectedResourceMetadata{ |
| 87 |
Resource: "https://example.com/mcp", |
| 88 |
AuthorizationServers: []string{ |
| 89 |
"https://auth.example.com/.well-known/openid-configuration", |
| 90 |
}, |
| 91 |
ScopesSupported: []string{"read", "write"}, |
| 92 |
} |
| 93 |
|
| 94 |
handler := ProtectedResourceMetadataHandler(metadata) |
| 95 |
|
| 96 |
tests := []struct { |
| 97 |
name string |
| 98 |
method string |
| 99 |
wantStatus int |
| 100 |
checkJSON bool |
| 101 |
}{ |
| 102 |
{ |
| 103 |
name: "GET returns metadata", |
| 104 |
method: http.MethodGet, |
| 105 |
wantStatus: http.StatusOK, |
| 106 |
checkJSON: true, |
| 107 |
}, |
| 108 |
{ |
| 109 |
name: "OPTIONS for CORS preflight", |
| 110 |
method: http.MethodOptions, |
| 111 |
wantStatus: http.StatusNoContent, |
| 112 |
}, |
| 113 |
{ |
| 114 |
name: "POST not allowed", |
| 115 |
method: http.MethodPost, |
| 116 |
wantStatus: http.StatusMethodNotAllowed, |
| 117 |
}, |
| 118 |
{ |
| 119 |
name: "PUT not allowed", |
| 120 |
method: http.MethodPut, |
| 121 |
wantStatus: http.StatusMethodNotAllowed, |
| 122 |
}, |
| 123 |
{ |
| 124 |
name: "DELETE not allowed", |
| 125 |
method: http.MethodDelete, |
| 126 |
wantStatus: http.StatusMethodNotAllowed, |
| 127 |
}, |
| 128 |
} |
| 129 |
|
| 130 |
for _, tt := range tests { |
| 131 |
t.Run(tt.name, func(t *testing.T) { |
| 132 |
req := httptest.NewRequest(tt.method, "/.well-known/oauth-protected-resource", nil) |
| 133 |
rec := httptest.NewRecorder() |
| 134 |
|
| 135 |
handler.ServeHTTP(rec, req) |
| 136 |
|
| 137 |
if rec.Code != tt.wantStatus { |
| 138 |
t.Errorf("status = %d, want %d", rec.Code, tt.wantStatus) |
| 139 |
} |
| 140 |
|
| 141 |
|
| 142 |
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "*" { |
| 143 |
t.Errorf("Access-Control-Allow-Origin = %q, want %q", got, "*") |
| 144 |
} |
| 145 |
|
| 146 |
if got := rec.Header().Get("Access-Control-Allow-Methods"); got != "GET, OPTIONS" { |
| 147 |
t.Errorf("Access-Control-Allow-Methods = %q, want %q", got, "GET, OPTIONS") |
| 148 |
} |
| 149 |
|
| 150 |
|
| 151 |
if tt.wantStatus == http.StatusMethodNotAllowed { |
| 152 |
if !strings.Contains(rec.Body.String(), "Method not allowed") { |
| 153 |
t.Errorf("error body = %q, want to contain %q", rec.Body.String(), "Method not allowed") |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
if tt.checkJSON { |
| 158 |
if got := rec.Header().Get("Content-Type"); got != "application/json" { |
| 159 |
t.Errorf("Content-Type = %q, want %q", got, "application/json") |
| 160 |
} |
| 161 |
|
| 162 |
var got oauthex.ProtectedResourceMetadata |
| 163 |
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil { |
| 164 |
t.Fatalf("failed to decode response: %v", err) |
| 165 |
} |
| 166 |
|
| 167 |
if got.Resource != metadata.Resource { |
| 168 |
t.Errorf("Resource = %q, want %q", got.Resource, metadata.Resource) |
| 169 |
} |
| 170 |
|
| 171 |
if len(got.AuthorizationServers) != len(metadata.AuthorizationServers) { |
| 172 |
t.Errorf("AuthorizationServers length = %d, want %d", |
| 173 |
len(got.AuthorizationServers), len(metadata.AuthorizationServers)) |
| 174 |
} |
| 175 |
|
| 176 |
for i, server := range got.AuthorizationServers { |
| 177 |
if server != metadata.AuthorizationServers[i] { |
| 178 |
t.Errorf("AuthorizationServers[%d] = %q, want %q", |
| 179 |
i, server, metadata.AuthorizationServers[i]) |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
if len(got.ScopesSupported) != len(metadata.ScopesSupported) { |
| 184 |
t.Errorf("ScopesSupported length = %d, want %d", |
| 185 |
len(got.ScopesSupported), len(metadata.ScopesSupported)) |
| 186 |
} |
| 187 |
} |
| 188 |
}) |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
func TestRequireBearerToken(t *testing.T) { |
| 193 |
verifier := func(_ context.Context, token string, _ *http.Request) (*TokenInfo, error) { |
| 194 |
if token == "valid" { |
| 195 |
return &TokenInfo{Expiration: time.Now().Add(time.Hour), Scopes: []string{"read"}}, nil |
| 196 |
} |
| 197 |
return nil, ErrInvalidToken |
| 198 |
} |
| 199 |
|
| 200 |
tests := []struct { |
| 201 |
name string |
| 202 |
opts *RequireBearerTokenOptions |
| 203 |
authHeader string |
| 204 |
wantHeader string |
| 205 |
wantStatus int |
| 206 |
}{ |
| 207 |
{ |
| 208 |
name: "no middleware options", |
| 209 |
opts: nil, |
| 210 |
authHeader: "Bearer invalid", |
| 211 |
wantHeader: "", |
| 212 |
wantStatus: http.StatusUnauthorized, |
| 213 |
}, |
| 214 |
{ |
| 215 |
name: "metadata only", |
| 216 |
opts: &RequireBearerTokenOptions{ |
| 217 |
ResourceMetadataURL: "https://example.com/resource-metadata", |
| 218 |
}, |
| 219 |
authHeader: "Bearer invalid", |
| 220 |
wantHeader: "Bearer resource_metadata=\"https://example.com/resource-metadata\"", |
| 221 |
wantStatus: http.StatusUnauthorized, |
| 222 |
}, |
| 223 |
{ |
| 224 |
name: "scopes only", |
| 225 |
opts: &RequireBearerTokenOptions{ |
| 226 |
Scopes: []string{"read", "write"}, |
| 227 |
}, |
| 228 |
authHeader: "Bearer invalid", |
| 229 |
wantHeader: "Bearer scope=\"read write\"", |
| 230 |
wantStatus: http.StatusUnauthorized, |
| 231 |
}, |
| 232 |
{ |
| 233 |
name: "metadata and scopes", |
| 234 |
opts: &RequireBearerTokenOptions{ |
| 235 |
ResourceMetadataURL: "https://example.com/resource-metadata", |
| 236 |
Scopes: []string{"read", "write"}, |
| 237 |
}, |
| 238 |
authHeader: "Bearer invalid", |
| 239 |
wantHeader: "Bearer resource_metadata=\"https://example.com/resource-metadata\", scope=\"read write\"", |
| 240 |
wantStatus: http.StatusUnauthorized, |
| 241 |
}, |
| 242 |
{ |
| 243 |
name: "insufficient scope", |
| 244 |
opts: &RequireBearerTokenOptions{ |
| 245 |
Scopes: []string{"admin"}, |
| 246 |
}, |
| 247 |
authHeader: "Bearer valid", |
| 248 |
wantHeader: "Bearer scope=\"admin\"", |
| 249 |
wantStatus: http.StatusForbidden, |
| 250 |
}, |
| 251 |
{ |
| 252 |
name: "success", |
| 253 |
opts: &RequireBearerTokenOptions{ |
| 254 |
Scopes: []string{"read"}, |
| 255 |
}, |
| 256 |
authHeader: "Bearer valid", |
| 257 |
wantHeader: "", |
| 258 |
wantStatus: http.StatusOK, |
| 259 |
}, |
| 260 |
} |
| 261 |
|
| 262 |
for _, tt := range tests { |
| 263 |
t.Run(tt.name, func(t *testing.T) { |
| 264 |
handler := RequireBearerToken(verifier, tt.opts)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 265 |
w.WriteHeader(http.StatusOK) |
| 266 |
})) |
| 267 |
|
| 268 |
req := httptest.NewRequest("GET", "/", nil) |
| 269 |
if tt.authHeader != "" { |
| 270 |
req.Header.Set("Authorization", tt.authHeader) |
| 271 |
} |
| 272 |
rec := httptest.NewRecorder() |
| 273 |
|
| 274 |
handler.ServeHTTP(rec, req) |
| 275 |
|
| 276 |
if rec.Code != tt.wantStatus { |
| 277 |
t.Errorf("status = %d, want %d", rec.Code, tt.wantStatus) |
| 278 |
} |
| 279 |
|
| 280 |
got := rec.Header().Get("WWW-Authenticate") |
| 281 |
if got != tt.wantHeader { |
| 282 |
t.Errorf("WWW-Authenticate = %q, want %q", got, tt.wantHeader) |
| 283 |
} |
| 284 |
}) |
| 285 |
} |
| 286 |
} |