Skip to content

Commit 73aebc1

Browse files
developer-ishanigupta-aiclaude
authored
fix(publisher): treat GitHub device-flow slow_down as retriable (modelcontextprotocol#1290)
## Summary - Handle GitHub's OAuth device-flow `slow_down` response per [RFC 8628 §3.5](https://datatracker.ietf.org/doc/html/rfc8628#section-3.5) — treat it as retriable and bump the polling interval by 5 seconds, instead of bailing with a fatal error. Fixes modelcontextprotocol#1289. ## Why `pollForToken` in `cmd/publisher/auth/github-at.go` only treats `authorization_pending` as retriable. Every other response from GitHub's token endpoint — including the non-terminal `slow_down` signal — falls through to: ```go return "", fmt.Errorf("token request failed: %s", tokenResp.Error) ``` So users hitting GitHub's polling rate-limit get: ``` Error: login failed: error polling for token: token request failed: slow_down ``` …and have to re-run `mcp-publisher login github` from scratch, which is especially painful because `slow_down` is more likely when the user takes more than a few seconds to enter and authorize the device code. Per RFC 8628 §3.5, `slow_down` is defined as: > A variant of "authorization_pending", the authorization request is still pending and polling should continue, but the interval MUST be increased by 5 seconds for this and all subsequent requests. ## Change Treat `slow_down` the same as `authorization_pending` but increase `interval` by 5 seconds before sleeping, matching the RFC exactly. A possible follow-up (not in this PR, to keep the diff minimal): seed the initial `interval` from `DeviceCodeResponse.Interval` (already parsed but currently unused) instead of hardcoding `5`. Happy to do that here or as a separate PR if preferred. ## Test plan - [x] `go build ./cmd/publisher/...` — clean - [x] `go test ./cmd/publisher/auth/...` — passes - [x] `gofmt -d` and `go vet ./cmd/publisher/auth/...` — clean - [ ] CI `make check` (lint + integration tests) I could not exercise `pollForToken` from a unit test without refactoring `GitHubAccessTokenURL` to be injectable, which felt out of scope for a bug-fix PR. Glad to add that refactor + a table-driven test for `authorization_pending` / `slow_down` / fatal errors in a follow-up if maintainers want it. --------- Co-authored-by: developer-ishan <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
1 parent cabf060 commit 73aebc1

2 files changed

Lines changed: 170 additions & 7 deletions

File tree

‎cmd/publisher/auth/github-at.go‎

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,17 @@ const (
1717
GitHubAccessTokenURL = "https://github.com/login/oauth/access_token" // #nosec:G101
1818
)
1919

20+
const (
21+
// defaultPollInterval is the initial device-flow polling interval in
22+
// seconds, per RFC 8628 §3.5.
23+
defaultPollInterval = 5
24+
// maxPollInterval caps how large the polling interval may grow. RFC 8628
25+
// §3.5 mandates a 5-second increase on each slow_down but leaves the
26+
// maximum to the implementation; this prevents a misbehaving auth server
27+
// from growing the interval unboundedly.
28+
maxPollInterval = 60
29+
)
30+
2031
// DeviceCodeResponse represents the response from GitHub's device code endpoint
2132
type DeviceCodeResponse struct {
2233
DeviceCode string `json:"device_code"`
@@ -46,6 +57,16 @@ type GitHubATProvider struct {
4657
registryURL string
4758
providedToken string // Token provided via --token flag or MCP_GITHUB_TOKEN env var
4859
githubToken string // In-memory GitHub token set by Login()
60+
61+
// accessTokenURL is the GitHub access-token polling endpoint. It is a field
62+
// (rather than the package constant) so tests can point it at a mock server.
63+
accessTokenURL string
64+
// pollInterval is the initial polling interval in seconds. Defaults to
65+
// defaultPollInterval; overridable in tests to avoid real delays.
66+
pollInterval int
67+
// sleep abstracts time.Sleep so tests can run without real delays and
68+
// assert the back-off sequence. Defaults to time.Sleep.
69+
sleep func(time.Duration)
4970
}
5071

5172
// ServerHealthResponse represents the response from the health endpoint
@@ -62,8 +83,11 @@ func NewGitHubATProvider(registryURL, token string) Provider {
6283
}
6384

6485
return &GitHubATProvider{
65-
registryURL: registryURL,
66-
providedToken: token,
86+
registryURL: registryURL,
87+
providedToken: token,
88+
accessTokenURL: GitHubAccessTokenURL,
89+
pollInterval: defaultPollInterval,
90+
sleep: time.Sleep,
6791
}
6892
}
6993

@@ -199,12 +223,12 @@ func (g *GitHubATProvider) pollForToken(ctx context.Context, deviceCode string)
199223
}
200224

201225
// Default polling interval and expiration time
202-
interval := 5 // seconds
226+
interval := g.pollInterval
203227
expiresIn := 900 // 15 minutes
204228
deadline := time.Now().Add(time.Duration(expiresIn) * time.Second)
205229

206230
for time.Now().Before(deadline) {
207-
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GitHubAccessTokenURL, bytes.NewBuffer(jsonData))
231+
req, err := http.NewRequestWithContext(ctx, http.MethodPost, g.accessTokenURL, bytes.NewBuffer(jsonData))
208232
if err != nil {
209233
return "", err
210234
}
@@ -229,9 +253,17 @@ func (g *GitHubATProvider) pollForToken(ctx context.Context, deviceCode string)
229253
return "", err
230254
}
231255

232-
if tokenResp.Error == "authorization_pending" {
233-
// User hasn't authorized yet, wait and retry
234-
time.Sleep(time.Duration(interval) * time.Second)
256+
// Per RFC 8628 §3.5, both authorization_pending and slow_down indicate
257+
// the client should keep polling. slow_down additionally requires that
258+
// the polling interval be increased by 5 seconds.
259+
if tokenResp.Error == "authorization_pending" || tokenResp.Error == "slow_down" {
260+
if tokenResp.Error == "slow_down" {
261+
interval += 5
262+
if interval > maxPollInterval {
263+
interval = maxPollInterval
264+
}
265+
}
266+
g.sleep(time.Duration(interval) * time.Second)
235267
continue
236268
}
237269

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
package auth
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"net/http"
7+
"net/http/httptest"
8+
"testing"
9+
"time"
10+
11+
"github.com/stretchr/testify/assert"
12+
"github.com/stretchr/testify/require"
13+
)
14+
15+
// newMockTokenServer returns an httptest.Server that serves the given sequence
16+
// of AccessTokenResponse values, one per request. Once the sequence is
17+
// exhausted the final response is reused for any extra requests.
18+
func newMockTokenServer(t *testing.T, responses []AccessTokenResponse) *httptest.Server {
19+
t.Helper()
20+
var i int
21+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
22+
resp := responses[len(responses)-1]
23+
if i < len(responses) {
24+
resp = responses[i]
25+
}
26+
i++
27+
w.Header().Set("Content-Type", "application/json")
28+
_ = json.NewEncoder(w).Encode(resp) // #nosec G117 -- test fixture token, not a real secret
29+
}))
30+
t.Cleanup(srv.Close)
31+
return srv
32+
}
33+
34+
// newPollTestProvider builds a provider wired to a mock token endpoint. The
35+
// initial poll interval is 0 (so the back-off starts from a known base) and
36+
// sleeps are captured rather than performed, making the tests deterministic and
37+
// instant. The returned slice records every interval passed to sleep.
38+
func newPollTestProvider(tokenURL string) (*GitHubATProvider, *[]time.Duration) {
39+
slept := &[]time.Duration{}
40+
p := &GitHubATProvider{
41+
clientID: "test-client-id",
42+
accessTokenURL: tokenURL,
43+
pollInterval: 0,
44+
sleep: func(d time.Duration) { *slept = append(*slept, d) },
45+
}
46+
return p, slept
47+
}
48+
49+
// TestPollForToken_SlowDownThenSuccess confirms that a slow_down response is
50+
// treated as retriable: polling continues and the success path is reached.
51+
func TestPollForToken_SlowDownThenSuccess(t *testing.T) {
52+
srv := newMockTokenServer(t, []AccessTokenResponse{
53+
{Error: "slow_down"},
54+
{AccessToken: "gh-token"},
55+
})
56+
p, slept := newPollTestProvider(srv.URL)
57+
58+
token, err := p.pollForToken(context.Background(), "device-code")
59+
require.NoError(t, err)
60+
assert.Equal(t, "gh-token", token)
61+
62+
// One slow_down => one back-off, interval bumped 0 -> 5.
63+
require.Len(t, *slept, 1)
64+
assert.Equal(t, 5*time.Second, (*slept)[0])
65+
}
66+
67+
// TestPollForToken_MixedRetryableErrorsCompoundInterval confirms the interval
68+
// increment compounds correctly across mixed retryable errors. Per RFC 8628
69+
// §3.5 the interval is increased by 5 seconds on each slow_down and is NOT
70+
// reset between slow_down instances, while authorization_pending leaves it
71+
// unchanged.
72+
func TestPollForToken_MixedRetryableErrorsCompoundInterval(t *testing.T) {
73+
srv := newMockTokenServer(t, []AccessTokenResponse{
74+
{Error: "slow_down"}, // 0 -> 5
75+
{Error: "authorization_pending"}, // stays 5
76+
{Error: "slow_down"}, // 5 -> 10
77+
{AccessToken: "gh-token"},
78+
})
79+
p, slept := newPollTestProvider(srv.URL)
80+
81+
token, err := p.pollForToken(context.Background(), "device-code")
82+
require.NoError(t, err)
83+
assert.Equal(t, "gh-token", token)
84+
85+
require.Len(t, *slept, 3)
86+
assert.Equal(t, 5*time.Second, (*slept)[0]) // after first slow_down
87+
assert.Equal(t, 5*time.Second, (*slept)[1]) // authorization_pending: unchanged
88+
assert.Equal(t, 10*time.Second, (*slept)[2]) // second slow_down: compounded
89+
}
90+
91+
// TestPollForToken_IntervalCappedAtMax confirms the polling interval is capped
92+
// so a misbehaving auth server returning slow_down repeatedly cannot grow it
93+
// without bound.
94+
func TestPollForToken_IntervalCappedAtMax(t *testing.T) {
95+
// 13 slow_downs starting from interval 0 would otherwise reach 65s
96+
// (5, 10, ..., 60, 65); the cap holds it at 60.
97+
responses := make([]AccessTokenResponse, 0, 14)
98+
for range [13]struct{}{} {
99+
responses = append(responses, AccessTokenResponse{Error: "slow_down"})
100+
}
101+
responses = append(responses, AccessTokenResponse{AccessToken: "gh-token"})
102+
103+
srv := newMockTokenServer(t, responses)
104+
p, slept := newPollTestProvider(srv.URL)
105+
106+
token, err := p.pollForToken(context.Background(), "device-code")
107+
require.NoError(t, err)
108+
assert.Equal(t, "gh-token", token)
109+
110+
require.Len(t, *slept, 13)
111+
for _, d := range *slept {
112+
assert.LessOrEqual(t, d, time.Duration(maxPollInterval)*time.Second)
113+
}
114+
// The last two back-offs are both pinned at the cap.
115+
assert.Equal(t, time.Duration(maxPollInterval)*time.Second, (*slept)[11])
116+
assert.Equal(t, time.Duration(maxPollInterval)*time.Second, (*slept)[12])
117+
}
118+
119+
// TestPollForToken_FatalErrorStopsPolling confirms a non-retryable error ends
120+
// polling immediately with an error.
121+
func TestPollForToken_FatalErrorStopsPolling(t *testing.T) {
122+
srv := newMockTokenServer(t, []AccessTokenResponse{
123+
{Error: "access_denied"},
124+
})
125+
p, slept := newPollTestProvider(srv.URL)
126+
127+
_, err := p.pollForToken(context.Background(), "device-code")
128+
require.Error(t, err)
129+
assert.Contains(t, err.Error(), "access_denied")
130+
assert.Empty(t, *slept, "fatal error should not trigger a back-off sleep")
131+
}

0 commit comments

Comments
 (0)