Skip to content
Closed
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
2 changes: 2 additions & 0 deletions pkg/http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ func (h *Handler) RegisterMiddleware(r chi.Router) {
middleware.WithRequestConfig,
middleware.WithMCPParse(),
middleware.WithPATScopes(h.logger, h.scopeFetcher),
// After WithPATScopes so it reuses the classic-PAT probe.
middleware.WithInvalidTokenChallenge(h.oauthCfg, h.scopeFetcher),
)

if h.config.ScopeChallenge {
Expand Down
66 changes: 66 additions & 0 deletions pkg/http/middleware/auth_challenge.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package middleware

import (
"errors"
"net/http"

ghcontext "github.com/github/github-mcp-server/v2/pkg/context"
"github.com/github/github-mcp-server/v2/pkg/http/oauth"
"github.com/github/github-mcp-server/v2/pkg/scopes"
)

// WithInvalidTokenChallenge responds with a transport-level HTTP 401 when GitHub
// rejects the token as invalid or expired, so OAuth clients refresh instead of
// seeing isError: true inside an HTTP 200 (which never triggers a refresh).
//
// It must run before dispatch: tool responses stream as SSE, so the status is
// flushed before the handler runs and cannot be rewritten afterward. The check
// is narrow by design — only a 401 challenges; every other error stays
// isError: true per the project's error model (#420).
func WithInvalidTokenChallenge(oauthCfg *oauth.Config, scopeFetcher scopes.FetcherInterface) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()

// Skip health check endpoints.
if r.URL.Path == "/_ping" {
next.ServeHTTP(w, r)
return
}

tokenInfo, ok := ghcontext.GetTokenInfo(ctx)
if !ok || tokenInfo == nil || tokenInfo.Token == "" {
// Missing tokens are handled upstream by ExtractUserToken.
next.ServeHTTP(w, r)
return
}

// Only tools/call needs a valid credential; discovery methods
// (tools/list, initialize) must stay reachable pre-auth.
methodInfo, ok := ghcontext.MCPMethod(ctx)
if !ok || methodInfo == nil || methodInfo.Method != "tools/call" {
next.ServeHTTP(w, r)
return
}

// Classic PATs were already probed by WithPATScopes; scopes in
// context mean the token authenticated, so skip a second call.
if _, ok := ghcontext.GetTokenScopes(ctx); ok {
next.ServeHTTP(w, r)
return
}

// Other token types (ghu_, gho_, fine-grained) have no prior probe.
// FetchTokenScopes returns ErrInvalidToken on 401.
_, err := scopeFetcher.FetchTokenScopes(ctx, tokenInfo.Token)
if errors.Is(err, scopes.ErrInvalidToken) {
sendInvalidTokenChallenge(w, r, oauthCfg)
return
}
Comment on lines +55 to +59

// Success, network error, or 5xx must not become a 401.
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
143 changes: 143 additions & 0 deletions pkg/http/middleware/auth_challenge_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package middleware

import (
"errors"
"net/http"
"net/http/httptest"
"testing"

ghcontext "github.com/github/github-mcp-server/v2/pkg/context"
"github.com/github/github-mcp-server/v2/pkg/http/oauth"
"github.com/github/github-mcp-server/v2/pkg/scopes"
"github.com/github/github-mcp-server/v2/pkg/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestWithInvalidTokenChallenge(t *testing.T) {
oauthCfg := &oauth.Config{BaseURL: "https://mcp.example.com", ResourcePath: "/mcp"}

// toolsCall builds a request whose context carries a ghu_ token and a
// tools/call method, the common shape the middleware actually probes.
toolsCall := func(tokenType utils.TokenType, token string) *http.Request {
req := httptest.NewRequest(http.MethodPost, "/mcp", nil)
ctx := ghcontext.WithTokenInfo(req.Context(), &ghcontext.TokenInfo{
Token: token,
TokenType: tokenType,
})
ctx = ghcontext.WithMCPMethodInfo(ctx, &ghcontext.MCPMethodInfo{
Method: "tools/call",
ItemName: "get_me",
})
return req.WithContext(ctx)
}

tests := []struct {
name string
request func() *http.Request
fetcher *mockScopeFetcher
expectNext bool
expectStatus int
expectInvalid bool // WWW-Authenticate carries error="invalid_token"
}{
{
name: "invalid ghu_ token on tools/call returns 401 invalid_token",
request: func() *http.Request { return toolsCall(utils.TokenTypeUserToServerGitHubAppToken, "ghu_expired") },
fetcher: &mockScopeFetcher{err: scopes.ErrInvalidToken},
expectNext: false,
expectStatus: http.StatusUnauthorized,
expectInvalid: true,
},
{
name: "valid ghu_ token passes through",
request: func() *http.Request { return toolsCall(utils.TokenTypeUserToServerGitHubAppToken, "ghu_good") },
fetcher: &mockScopeFetcher{scopes: []string{}},
expectNext: true,
expectStatus: http.StatusOK,
},
{
name: "network error is not turned into a 401",
request: func() *http.Request { return toolsCall(utils.TokenTypeUserToServerGitHubAppToken, "ghu_good") },
fetcher: &mockScopeFetcher{err: errors.New("dial tcp: connection refused")},
expectNext: true,
expectStatus: http.StatusOK,
},
{
name: "classic PAT with scopes already in context is not probed again",
request: func() *http.Request {
req := toolsCall(utils.TokenTypePersonalAccessToken, "ghp_good")
ctx := ghcontext.WithTokenScopes(req.Context(), []string{"repo"})
return req.WithContext(ctx)
},
// err would fire if the middleware probed; it must not.
fetcher: &mockScopeFetcher{err: scopes.ErrInvalidToken},
expectNext: true,
expectStatus: http.StatusOK,
},
{
name: "non tools/call method passes through without probing",
request: func() *http.Request {
req := httptest.NewRequest(http.MethodPost, "/mcp", nil)
ctx := ghcontext.WithTokenInfo(req.Context(), &ghcontext.TokenInfo{
Token: "ghu_whatever",
TokenType: utils.TokenTypeUserToServerGitHubAppToken,
})
ctx = ghcontext.WithMCPMethodInfo(ctx, &ghcontext.MCPMethodInfo{Method: "tools/list"})
return req.WithContext(ctx)
},
fetcher: &mockScopeFetcher{err: scopes.ErrInvalidToken},
expectNext: true,
expectStatus: http.StatusOK,
},
{
name: "missing token info passes through",
request: func() *http.Request {
req := httptest.NewRequest(http.MethodPost, "/mcp", nil)
ctx := ghcontext.WithMCPMethodInfo(req.Context(), &ghcontext.MCPMethodInfo{Method: "tools/call"})
return req.WithContext(ctx)
},
fetcher: &mockScopeFetcher{err: scopes.ErrInvalidToken},
expectNext: true,
expectStatus: http.StatusOK,
},
{
name: "health check endpoint is never probed",
request: func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "/_ping", nil)
ctx := ghcontext.WithTokenInfo(req.Context(), &ghcontext.TokenInfo{
Token: "ghu_whatever",
TokenType: utils.TokenTypeUserToServerGitHubAppToken,
})
return req.WithContext(ctx)
},
fetcher: &mockScopeFetcher{err: scopes.ErrInvalidToken},
expectNext: true,
expectStatus: http.StatusOK,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var nextCalled bool
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
})

handler := WithInvalidTokenChallenge(oauthCfg, tt.fetcher)(next)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, tt.request())

assert.Equal(t, tt.expectNext, nextCalled, "next handler invocation")
assert.Equal(t, tt.expectStatus, rr.Code)

if tt.expectInvalid {
wwwAuth := rr.Header().Get("WWW-Authenticate")
require.NotEmpty(t, wwwAuth, "expected WWW-Authenticate header")
assert.Contains(t, wwwAuth, `error="invalid_token"`)
assert.Contains(t, wwwAuth, "resource_metadata=")
assert.Contains(t, wwwAuth, "/.well-known/oauth-protected-resource")
}
})
}
}
14 changes: 14 additions & 0 deletions pkg/http/middleware/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,17 @@ func sendAuthChallenge(w http.ResponseWriter, r *http.Request, oauthCfg *oauth.C
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer resource_metadata=%q`, resourceMetadataURL))
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}

// sendInvalidTokenChallenge sends a 401 for a token GitHub rejected as invalid
// or expired. Unlike sendAuthChallenge, it sets error="invalid_token" (RFC 6750
// §3.1) so clients refresh the stale token rather than re-authorizing.
func sendInvalidTokenChallenge(w http.ResponseWriter, r *http.Request, oauthCfg *oauth.Config) {
resourcePath := oauth.ResolveResourcePath(r, oauthCfg)
resourceMetadataURL := oauth.BuildResourceMetadataURL(r, oauthCfg, resourcePath)
w.Header().Set("WWW-Authenticate", fmt.Sprintf(
`Bearer error="invalid_token", error_description=%q, resource_metadata=%q`,
"The access token is invalid or expired",
resourceMetadataURL,
))
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
8 changes: 7 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 @@ -15,6 +16,11 @@ import (
// OAuthScopesHeader is the HTTP response header containing the token's OAuth scopes.
const OAuthScopesHeader = "X-OAuth-Scopes"

// ErrInvalidToken is returned by FetchTokenScopes when GitHub rejects the token
// with HTTP 401. Match it with errors.Is to tell a credential failure apart from
// a network or server error.
var ErrInvalidToken = errors.New("invalid or expired token")

// DefaultFetchTimeout is the default timeout for scope fetching requests.
const DefaultFetchTimeout = 10 * time.Second

Expand Down Expand Up @@ -90,7 +96,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
19 changes: 12 additions & 7 deletions pkg/scopes/fetcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,12 @@ func TestParseScopeHeader(t *testing.T) {

func TestFetcher_FetchTokenScopes(t *testing.T) {
tests := []struct {
name string
handler http.HandlerFunc
expectedScopes []string
expectError bool
errorContains string
name string
handler http.HandlerFunc
expectedScopes []string
expectError bool
errorContains string
expectInvalidToken bool
}{
{
name: "successful fetch with multiple scopes",
Expand Down Expand Up @@ -123,8 +124,9 @@ func TestFetcher_FetchTokenScopes(t *testing.T) {
handler: func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
},
expectError: true,
errorContains: "invalid or expired token",
expectError: true,
errorContains: "invalid or expired token",
expectInvalidToken: true,
},
{
name: "server error",
Expand Down Expand Up @@ -177,6 +179,9 @@ func TestFetcher_FetchTokenScopes(t *testing.T) {
if tt.errorContains != "" {
assert.Contains(t, err.Error(), tt.errorContains)
}
if tt.expectInvalidToken {
assert.ErrorIs(t, err, ErrInvalidToken)
}
} else {
require.NoError(t, err)
assert.Equal(t, tt.expectedScopes, scopes)
Expand Down