Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pkg/http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,8 @@ func PATScopeFilter(b *inventory.Builder, r *http.Request, fetcher scopes.Fetche

scopesList, err := fetcher.FetchTokenScopes(ctx, tokenInfo.Token)
if err != nil {
return b
// Fail closed: with no verified scopes, withhold every scope-gated tool.
scopesList = nil
}

return b.WithFilter(github.CreateToolScopeFilter(scopesList))
Expand Down
30 changes: 30 additions & 0 deletions pkg/http/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package http
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
Expand Down Expand Up @@ -1680,3 +1681,32 @@ func TestMaxRequestBodySizeEnforcement(t *testing.T) {
assert.True(t, mcpServerFactoryCalled, "the MCP server should be constructed for an allowed request")
})
}

type errScopeFetcher struct{}

func (errScopeFetcher) FetchTokenScopes(_ context.Context, _ string) ([]string, error) {
return nil, errors.New("scope endpoint unavailable")
}

func TestPATScopeFilterWithholdsScopeGatedToolsWhenScopeFetchErrors(t *testing.T) {
gated := mockTool("scoped_tool", "repos", true)
gated.ScopeAccess = scopes.RequireAll(scopes.Repo)
ungated := mockTool("unscoped_tool", "repos", true)
ungated.ScopeAccess = scopes.NoScopes()

req := httptest.NewRequest(http.MethodPost, "/", nil)
req = req.WithContext(ghcontext.WithTokenInfo(req.Context(), &ghcontext.TokenInfo{ //nolint:gosec // G101: synthetic fixture, not a credential.
Token: "ghp_test",
TokenType: utils.TokenTypePersonalAccessToken,
}))

builder := inventory.NewBuilder().SetTools([]inventory.ServerTool{gated, ungated}).WithToolsets([]string{"all"})
inv, err := PATScopeFilter(builder, req, errScopeFetcher{}).Build()
require.NoError(t, err)

var names []string
for _, tool := range inv.AvailableTools(req.Context()) {
names = append(names, tool.Tool.Name)
}
assert.Equal(t, []string{"unscoped_tool"}, names)
}
13 changes: 11 additions & 2 deletions pkg/http/middleware/scope_challenge.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package middleware
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -82,11 +83,19 @@ func WithScopeChallenge(oauthCfg *oauth.Config, scopeFetcher scopes.FetcherInter

// Get OAuth scopes for Token. First check if scopes are already in context, then fetch from GitHub if not present.
// This allows Remote Server to pass scope info to avoid redundant GitHub API calls.
// A non-nil empty slice is an explicit "no scopes"; only a missing or nil
// value falls back to the GitHub lookup.
activeScopes, ok := ghcontext.GetTokenScopes(ctx)
if !ok || (len(activeScopes) == 0 && tokenInfo.Token != "") {
if !ok || (activeScopes == nil && tokenInfo.Token != "") {
fetchedScopes, err := scopeFetcher.FetchTokenScopes(ctx, tokenInfo.Token)
if err != nil {
next.ServeHTTP(w, r)
if errors.Is(err, scopes.ErrInvalidToken) {
// An expired or revoked token needs a new credential, not a retry.
sendAuthChallenge(w, r, oauthCfg)
return
}
// Fail closed: an unverifiable token must not reach the tool handler.
http.Error(w, "scope verification unavailable", http.StatusServiceUnavailable)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e4aebb0. FetchTokenScopes now returns the sentinel scopes.ErrInvalidToken for a 401, and WithScopeChallenge maps it to the sendAuthChallenge 401 response with the WWW-Authenticate resource metadata header. Other fetch errors still return 503.

Test: TestWithScopeChallengeReturns401ForInvalidToken. On the previous commit it failed with 503 and no challenge header; it passes now. Full go test ./... and script/lint are green.

return
}
activeScopes = fetchedScopes
Expand Down
71 changes: 71 additions & 0 deletions pkg/http/middleware/scope_challenge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -429,3 +430,73 @@ func scopeChallengeContextWithScopes(ctx context.Context, activeScopes []string)
ctx = ghcontext.WithTokenScopes(ctx, activeScopes)
return ctx
}

func TestWithScopeChallengeFailsClosedWhenScopeFetchErrors(t *testing.T) {
setScopeTestMap(t, scopes.RequireAll(scopes.Repo))

nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusNoContent)
})
body := `{"jsonrpc":"2.0","method":"tools/call","params":{"name":"write_file","arguments":{}}}`
request := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
request = request.WithContext(ghcontext.WithTokenInfo(request.Context(), &ghcontext.TokenInfo{ //nolint:gosec // G101: synthetic fixture, not a credential.
Token: "oauth-token",
TokenType: utils.TokenTypeOAuthAccessToken,
}))
response := httptest.NewRecorder()

fetcher := &mockScopeFetcher{err: errors.New("scope endpoint unavailable")}
WithMCPParse()(WithScopeChallenge(&oauth.Config{}, fetcher)(next)).ServeHTTP(response, request)

assert.False(t, nextCalled, "tool call must not proceed when scopes cannot be verified")
assert.Equal(t, http.StatusServiceUnavailable, response.Code)
}

func TestWithScopeChallengeReturns401ForInvalidToken(t *testing.T) {
setScopeTestMap(t, scopes.RequireAll(scopes.Repo))

nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusNoContent)
})
body := `{"jsonrpc":"2.0","method":"tools/call","params":{"name":"write_file","arguments":{}}}`
request := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
request = request.WithContext(ghcontext.WithTokenInfo(request.Context(), &ghcontext.TokenInfo{ //nolint:gosec // G101: synthetic fixture, not a credential.
Token: "oauth-token",
TokenType: utils.TokenTypeOAuthAccessToken,
}))
response := httptest.NewRecorder()

fetcher := &mockScopeFetcher{err: scopes.ErrInvalidToken}
WithMCPParse()(WithScopeChallenge(&oauth.Config{}, fetcher)(next)).ServeHTTP(response, request)

assert.False(t, nextCalled, "tool call must not proceed with an expired token")
assert.Equal(t, http.StatusUnauthorized, response.Code)
assert.Contains(t, response.Header().Get("WWW-Authenticate"), "resource_metadata=")
}

func TestWithScopeChallengeTreatsExplicitEmptyScopesAsKnown(t *testing.T) {
setScopeTestMap(t, scopes.RequireAll(scopes.Repo))

nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusNoContent)
})
body := `{"jsonrpc":"2.0","method":"tools/call","params":{"name":"write_file","arguments":{}}}`
request := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
// An empty but non-nil scope list means "this token has no scopes"; it must
// not be replaced by a GitHub lookup.
request = request.WithContext(scopeChallengeContextWithScopes(request.Context(), []string{}))
response := httptest.NewRecorder()

fetcher := &mockScopeFetcher{err: errors.New("scope endpoint must not be called")}
WithMCPParse()(WithScopeChallenge(&oauth.Config{}, fetcher)(next)).ServeHTTP(response, request)

assert.False(t, nextCalled)
assert.Equal(t, http.StatusForbidden, response.Code)
assert.Contains(t, response.Header().Get("WWW-Authenticate"), "insufficient_scope")
}
7 changes: 6 additions & 1 deletion pkg/scopes/fetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package scopes

import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
Expand All @@ -18,6 +19,10 @@ const OAuthScopesHeader = "X-OAuth-Scopes"
// DefaultFetchTimeout is the default timeout for scope fetching requests.
const DefaultFetchTimeout = 10 * time.Second

// ErrInvalidToken reports that GitHub rejected the token as expired or revoked.
// Callers must treat it as an authentication failure, not an outage.
var ErrInvalidToken = errors.New("invalid or expired token")

// FetcherOptions configures the scope fetcher.
type FetcherOptions struct {
// HTTPClient is the HTTP client to use for requests.
Expand Down Expand Up @@ -90,7 +95,7 @@ func (f *Fetcher) FetchTokenScopes(ctx context.Context, token string) ([]string,
defer resp.Body.Close()

if resp.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf("invalid or expired token")
return nil, ErrInvalidToken
}

if resp.StatusCode != http.StatusOK {
Expand Down