Skip to content

Commit 9c5e9fc

Browse files
test(publisher): cover slow_down polling and cap the interval
Address review feedback on the device-flow slow_down fix: - Add regression tests for pollForToken (previously untested): - slow_down then success: confirms polling continues to success - slow_down / authorization_pending / slow_down then success: confirms the RFC 8628 §3.5 interval increment compounds across mixed retryable errors and is not reset between slow_down instances - repeated slow_down: confirms the interval is capped - non-retryable error: confirms polling stops immediately - Cap the polling interval at 60s so a misbehaving auth server returning slow_down repeatedly cannot grow it unboundedly (RFC 8628 §3.5 mandates the +5s increase but leaves the maximum to the implementation). To make pollForToken testable, the access-token URL, initial interval, and sleep function are now provider fields wired to defaults in the constructor; tests inject a mock server and capture the back-off sequence deterministically. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent 4c9b21a commit 9c5e9fc

2 files changed

Lines changed: 163 additions & 5 deletions

File tree

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

Lines changed: 32 additions & 5 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
}
@@ -235,8 +259,11 @@ func (g *GitHubATProvider) pollForToken(ctx context.Context, deviceCode string)
235259
if tokenResp.Error == "authorization_pending" || tokenResp.Error == "slow_down" {
236260
if tokenResp.Error == "slow_down" {
237261
interval += 5
262+
if interval > maxPollInterval {
263+
interval = maxPollInterval
264+
}
238265
}
239-
time.Sleep(time.Duration(interval) * time.Second)
266+
g.sleep(time.Duration(interval) * time.Second)
240267
continue
241268
}
242269

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)