Skip to content

Commit d1dcaf3

Browse files
JosephDoUrdenigupta-aideveloper-ishanclauderdimitrov
authored
fix(publisher): tolerate transient device-flow failures during login polling (#1588)
Follow-up to my analysis on #1543. Heads up on the shape first: this builds on #1290's poll-loop seams and github wont let me target a fork branch, so the diff shows its two commits too. Review only the last commit, the first two are #1290 unchanged, credit to @developer-ishan. Happy to rebase whichever way #1290 goes, or split differently if that's easier to review. What it does. pollForToken treats every non-pending answer as terminal, so one flaky response kills a login the user may already have approved in the browser. This spends a small grace budget (2 polls) on incorrect_device_code before giving up, retries 5xx with a growing backoff, and returns status plus body on other non-200s instead of dying inside json.Unmarshal on an html error page. Terminal errors now carry error_description and error_uri, and a timeout that happens after polling recovered reports a plain timeout, not a stale error from minutes earlier. Also honours the interval and expires_in GitHub returns with the device code (RFC 8628 3.2) instead of hardcoding 5/900, clamped (60s / 3600s) so a misbehaving response can't stall the CLI or overflow the duration math. One thing I changed my mind on from the issue comment: I wrote there that the client should wait one interval before the first poll. Dropped that. My own repro test showed 40s of clean polling before authorize, so the propagation theory doesn't hold, and the grace retry covers the same window without taxing every fast login. First poll stays immediate, pinned by a test. Root cause note: I can't prove the GitHub-side race (cli/cli#9302 is the same error class but was closed on an unconfirmed "platform race"). So this isn't claimed as a root-cause fix, it makes the login recoverable if the condition is transient and diagnosable if it isn't. Btw incorrect_device_code is a GitHub extension, not an RFC 8628 3.5 code, so there's no spec retry semantic being violated by the grace polls. ## Test 12 new tests in github_at_device_flow_internal_test.go, all green with -race (33 in the package). #1290's four tests pass unmodified. golangci-lint clean in the touched files under both v2.11.4 (this branch's CI pin) and v2.13.1 (what main pins now). ## AI Disclosure AI assistance (Claude) was used for issue research and during development. All changes were reviewed and tested by the author. Fixes #1543 --------- Co-authored-by: developer-ishan <[email protected]> Co-authored-by: Ishan Gupta <[email protected]> Co-authored-by: developer-ishan <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Radoslav Dimitrov <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 73aebc1 commit d1dcaf3

3 files changed

Lines changed: 658 additions & 7 deletions

File tree

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

Lines changed: 122 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,20 @@ const (
2626
// maximum to the implementation; this prevents a misbehaving auth server
2727
// from growing the interval unboundedly.
2828
maxPollInterval = 60
29+
// defaultExpiresIn is the device-code lifetime in seconds used when the
30+
// device-code response omits expires_in.
31+
defaultExpiresIn = 900
32+
// maxExpiresIn caps the device-code lifetime a response may claim. It sits
33+
// well past GitHub's documented 15 minutes; the cap stops a misbehaving or
34+
// hostile response from pushing the deadline (and the polling loop) far
35+
// into the future.
36+
maxExpiresIn = 3600
37+
// incorrectDeviceCodeGraceRetries is the total number of extra polls a
38+
// single login may spend on incorrect_device_code before giving up — a
39+
// budget for the whole login, not per occurrence. cli/cli#9302 reports the
40+
// same error for a code that had just been issued; a genuinely invalid code
41+
// still fails, only a few seconds later.
42+
incorrectDeviceCodeGraceRetries = 2
2943
)
3044

3145
// DeviceCodeResponse represents the response from GitHub's device code endpoint
@@ -43,6 +57,38 @@ type AccessTokenResponse struct {
4357
TokenType string `json:"token_type"`
4458
Scope string `json:"scope"`
4559
Error string `json:"error,omitempty"`
60+
// ErrorDescription and ErrorURI accompany Error in GitHub's responses;
61+
// surfacing them turns opaque failures like "incorrect_device_code" into
62+
// diagnosable reports.
63+
ErrorDescription string `json:"error_description,omitempty"`
64+
ErrorURI string `json:"error_uri,omitempty"`
65+
}
66+
67+
// errorDetail renders Error together with any error_description and error_uri
68+
// GitHub returned, so failures reach the user diagnosable rather than opaque.
69+
func (r AccessTokenResponse) errorDetail() string {
70+
detail := r.Error
71+
if r.ErrorDescription != "" {
72+
detail += ": " + r.ErrorDescription
73+
}
74+
if r.ErrorURI != "" {
75+
detail += " (" + r.ErrorURI + ")"
76+
}
77+
return detail
78+
}
79+
80+
func decodeAccessTokenResponse(statusCode int, body []byte) (AccessTokenResponse, error) {
81+
var tokenResp AccessTokenResponse
82+
// OAuth errors may use HTTP 400 (RFC 6749 §5.2), not just HTTP 200.
83+
if statusCode != http.StatusOK && statusCode != http.StatusBadRequest {
84+
return tokenResp, fmt.Errorf("token endpoint returned %d: %s", statusCode, body)
85+
}
86+
87+
err := json.Unmarshal(body, &tokenResp)
88+
if statusCode == http.StatusBadRequest && (err != nil || tokenResp.Error == "") {
89+
return tokenResp, fmt.Errorf("token endpoint returned %d: %s", statusCode, body)
90+
}
91+
return tokenResp, err
4692
}
4793

4894
// RegistryTokenResponse represents the response from registry's token exchange endpoint
@@ -61,9 +107,17 @@ type GitHubATProvider struct {
61107
// accessTokenURL is the GitHub access-token polling endpoint. It is a field
62108
// (rather than the package constant) so tests can point it at a mock server.
63109
accessTokenURL string
110+
// deviceCodeURL is the GitHub device-code endpoint, a field for the same
111+
// reason as accessTokenURL.
112+
deviceCodeURL string
64113
// pollInterval is the initial polling interval in seconds. Defaults to
65-
// defaultPollInterval; overridable in tests to avoid real delays.
114+
// defaultPollInterval; overridable in tests to avoid real delays. Updated
115+
// from the device-code response's interval when GitHub returns one.
66116
pollInterval int
117+
// expiresIn is the device-code lifetime in seconds. Defaults to
118+
// defaultExpiresIn; updated from the device-code response's expires_in
119+
// when GitHub returns one.
120+
expiresIn int
67121
// sleep abstracts time.Sleep so tests can run without real delays and
68122
// assert the back-off sequence. Defaults to time.Sleep.
69123
sleep func(time.Duration)
@@ -86,7 +140,9 @@ func NewGitHubATProvider(registryURL, token string) Provider {
86140
registryURL: registryURL,
87141
providedToken: token,
88142
accessTokenURL: GitHubAccessTokenURL,
143+
deviceCodeURL: GitHubDeviceCodeURL,
89144
pollInterval: defaultPollInterval,
145+
expiresIn: defaultExpiresIn,
90146
sleep: time.Sleep,
91147
}
92148
}
@@ -173,7 +229,7 @@ func (g *GitHubATProvider) requestDeviceCode(ctx context.Context) (string, strin
173229
return "", "", "", err
174230
}
175231

176-
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GitHubDeviceCodeURL, bytes.NewBuffer(jsonData))
232+
req, err := http.NewRequestWithContext(ctx, http.MethodPost, g.deviceCodeURL, bytes.NewBuffer(jsonData))
177233
if err != nil {
178234
return "", "", "", err
179235
}
@@ -202,6 +258,21 @@ func (g *GitHubATProvider) requestDeviceCode(ctx context.Context) (string, strin
202258
return "", "", "", err
203259
}
204260

261+
// Per RFC 8628 §3.2 interval and expires_in are bound to this device code,
262+
// so reset any pacing left over from a previous code before adopting them.
263+
// Clamp both: a hostile or buggy response must not grow the interval past
264+
// maxPollInterval (the invariant maxPollInterval exists for) nor push the
265+
// deadline unboundedly into the future, and clamping also keeps the
266+
// derived time.Duration well clear of int64 overflow.
267+
g.pollInterval = defaultPollInterval
268+
g.expiresIn = defaultExpiresIn
269+
if deviceCodeResp.Interval > 0 {
270+
g.pollInterval = min(deviceCodeResp.Interval, maxPollInterval)
271+
}
272+
if deviceCodeResp.ExpiresIn > 0 {
273+
g.expiresIn = min(deviceCodeResp.ExpiresIn, maxExpiresIn)
274+
}
275+
205276
return deviceCodeResp.DeviceCode, deviceCodeResp.UserCode, deviceCodeResp.VerificationURI, nil
206277
}
207278

@@ -222,11 +293,26 @@ func (g *GitHubATProvider) pollForToken(ctx context.Context, deviceCode string)
222293
return "", err
223294
}
224295

225-
// Default polling interval and expiration time
296+
// Pacing comes from the device-code response (via requestDeviceCode),
297+
// falling back to GitHub's documented defaults.
226298
interval := g.pollInterval
227-
expiresIn := 900 // 15 minutes
299+
expiresIn := g.expiresIn
300+
// Zero-value fallback: providers built directly rather than through
301+
// requestDeviceCode (the test seam) carry no lifetime. Keep this guard.
302+
if expiresIn <= 0 {
303+
expiresIn = defaultExpiresIn
304+
}
228305
deadline := time.Now().Add(time.Duration(expiresIn) * time.Second)
229306

307+
graceRetries := 0
308+
// serverErrorInterval grows the wait between consecutive 5xx retries and is
309+
// reset by any other response.
310+
serverErrorInterval := interval
311+
// lastErr holds the most recent retryable failure so a deadline reached
312+
// mid-retry reports that diagnostic instead of a bare "timed out". It is
313+
// cleared whenever polling recovers, so a genuine user timeout after a
314+
// recovered blip still reports plainly.
315+
var lastErr error
230316
for time.Now().Before(deadline) {
231317
req, err := http.NewRequestWithContext(ctx, http.MethodPost, g.accessTokenURL, bytes.NewBuffer(jsonData))
232318
if err != nil {
@@ -247,8 +333,20 @@ func (g *GitHubATProvider) pollForToken(ctx context.Context, deviceCode string)
247333
return "", err
248334
}
249335

250-
var tokenResp AccessTokenResponse
251-
err = json.Unmarshal(body, &tokenResp)
336+
// A transient 5xx must not abandon a login the user may already have
337+
// approved in the browser. Each consecutive 5xx grows the wait by 5s up
338+
// to maxPollInterval, so a sustained outage costs a couple of dozen
339+
// requests rather than hundreds; the deadline bounds the number of
340+
// these retries.
341+
if resp.StatusCode >= http.StatusInternalServerError {
342+
lastErr = fmt.Errorf("token endpoint returned %d", resp.StatusCode)
343+
serverErrorInterval = min(serverErrorInterval+5, maxPollInterval)
344+
g.sleep(time.Duration(serverErrorInterval) * time.Second)
345+
continue
346+
}
347+
serverErrorInterval = interval
348+
349+
tokenResp, err := decodeAccessTokenResponse(resp.StatusCode, body)
252350
if err != nil {
253351
return "", err
254352
}
@@ -263,12 +361,26 @@ func (g *GitHubATProvider) pollForToken(ctx context.Context, deviceCode string)
263361
interval = maxPollInterval
264362
}
265363
}
364+
lastErr = nil
266365
g.sleep(time.Duration(interval) * time.Second)
267366
continue
268367
}
269368

270369
if tokenResp.Error != "" {
271-
return "", fmt.Errorf("token request failed: %s", tokenResp.Error)
370+
failure := fmt.Errorf("token request failed: %s", tokenResp.errorDetail())
371+
372+
// incorrect_device_code has been reported for codes that were in
373+
// fact valid (cli/cli#9302; cause never confirmed), so spend a
374+
// couple of grace polls before abandoning a login the user may
375+
// have approved.
376+
if tokenResp.Error == "incorrect_device_code" && graceRetries < incorrectDeviceCodeGraceRetries {
377+
graceRetries++
378+
lastErr = failure
379+
g.sleep(time.Duration(interval) * time.Second)
380+
continue
381+
}
382+
383+
return "", failure
272384
}
273385

274386
if tokenResp.AccessToken != "" {
@@ -279,6 +391,9 @@ func (g *GitHubATProvider) pollForToken(ctx context.Context, deviceCode string)
279391
return "", fmt.Errorf("failed to obtain access token")
280392
}
281393

394+
if lastErr != nil {
395+
return "", fmt.Errorf("device code authorization timed out; last response: %w", lastErr)
396+
}
282397
return "", fmt.Errorf("device code authorization timed out")
283398
}
284399

0 commit comments

Comments
 (0)