From 33cdbfe5538155c7a0ff55fa573e26030237cc65 Mon Sep 17 00:00:00 2001 From: Anika Reiter Date: Wed, 18 Nov 2026 08:12:55 +0100 Subject: [PATCH] Emit HTTP 401 for invalid/expired tokens so OAuth clients refresh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When GitHub rejects a credential with 401, tool calls currently return HTTP 200 with isError: true, which OAuth clients never treat as a signal to refresh โ€” so sessions silently break once a short-lived token expires. Add a pre-dispatch middleware that probes token validity on tools/call and responds with a transport-level 401 + WWW-Authenticate (error="invalid_token", RFC 6750) when GitHub returns 401. It must run before dispatch because tool responses stream as SSE: the status is flushed before the handler runs and cannot be rewritten afterward. The check is deliberately narrow โ€” only a 401 challenges. All other errors (404, 409, 422, rate limits, business logic) keep returning isError: true per the project's error model (#420). Classic PATs reuse the existing WithPATScopes probe; ghu_/gho_/fine-grained tokens get a lightweight HEAD. Fixes #3677 --- pkg/http/handler.go | 2 + pkg/http/middleware/auth_challenge.go | 66 ++++++++++ pkg/http/middleware/auth_challenge_test.go | 143 +++++++++++++++++++++ pkg/http/middleware/token.go | 14 ++ pkg/scopes/fetcher.go | 8 +- pkg/scopes/fetcher_test.go | 19 ++- 6 files changed, 244 insertions(+), 8 deletions(-) create mode 100644 pkg/http/middleware/auth_challenge.go create mode 100644 pkg/http/middleware/auth_challenge_test.go diff --git a/pkg/http/handler.go b/pkg/http/handler.go index 25c02f254c..1636c88860 100644 --- a/pkg/http/handler.go +++ b/pkg/http/handler.go @@ -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 { diff --git a/pkg/http/middleware/auth_challenge.go b/pkg/http/middleware/auth_challenge.go new file mode 100644 index 0000000000..ec0bf8d723 --- /dev/null +++ b/pkg/http/middleware/auth_challenge.go @@ -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 + } + + // Success, network error, or 5xx must not become a 401. + next.ServeHTTP(w, r) + } + return http.HandlerFunc(fn) + } +} diff --git a/pkg/http/middleware/auth_challenge_test.go b/pkg/http/middleware/auth_challenge_test.go new file mode 100644 index 0000000000..ac8e155cb9 --- /dev/null +++ b/pkg/http/middleware/auth_challenge_test.go @@ -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") + } + }) + } +} diff --git a/pkg/http/middleware/token.go b/pkg/http/middleware/token.go index 951a86e34a..9665a22788 100644 --- a/pkg/http/middleware/token.go +++ b/pkg/http/middleware/token.go @@ -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) +} diff --git a/pkg/scopes/fetcher.go b/pkg/scopes/fetcher.go index 5701c4afa2..a92b104f30 100644 --- a/pkg/scopes/fetcher.go +++ b/pkg/scopes/fetcher.go @@ -2,6 +2,7 @@ package scopes import ( "context" + "errors" "fmt" "net/http" "net/url" @@ -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 @@ -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 { diff --git a/pkg/scopes/fetcher_test.go b/pkg/scopes/fetcher_test.go index 7ef910a569..32a60834fe 100644 --- a/pkg/scopes/fetcher_test.go +++ b/pkg/scopes/fetcher_test.go @@ -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", @@ -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", @@ -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)