diff --git a/internal/cliauth/backend.go b/internal/cliauth/backend.go index 5bc5a3cf..fc9c5111 100644 --- a/internal/cliauth/backend.go +++ b/internal/cliauth/backend.go @@ -24,12 +24,14 @@ const browserLoginTimeout = 10 * time.Minute // /token until the grant is approved; there is no loopback callback). const browserPollInterval = 2 * time.Second -// maxConsecutivePollFailures caps back-to-back transport-level poll failures -// (timeouts, connection resets, dropped connections — anything that is not an -// *APIError) tolerated by the login poll loops. A single stalled request must -// not kill an otherwise healthy login (observed live: the 30s client timeout -// tripping once on device/poll), but a real outage should still surface -// instead of silently polling until the grant expires. +// maxConsecutivePollFailures caps back-to-back poll failures tolerated by the +// login poll loops: transport-level failures (timeouts, connection resets, +// dropped connections — anything that is not an *APIError) and server-side +// 5xx answers (see retryablePollError). A single stalled request or database +// blip must not kill an otherwise healthy login (observed live: the 30s client +// timeout tripping once on device/poll; a 503 on the grant read during the +// 2026-11-11 database outage), but a real outage should still surface instead +// of silently polling until the grant expires. const maxConsecutivePollFailures = 4 // Platform auth endpoint paths (state-api-contract.md §1). Browser-loopback @@ -320,6 +322,46 @@ func cliCodePending(err error) bool { return true } +// retryablePollError reports whether an *APIError answering a login poll is a +// transient server-side failure that says nothing about the grant: any HTTP +// 5xx, or the platform's internal_error code. The platform answers a database +// blip on the grant read with 503 internal_error, so the poll loops treat it +// like a dropped connection — count it against maxConsecutivePollFailures and +// poll again — instead of ending the login. Answers about the grant itself +// stay terminal whatever their code: 401 (unknown or used code), 403 +// (denied), 404 and 410 (expired) are never retried. +func retryablePollError(apiErr *APIError) bool { + if apiErr == nil { + return false + } + switch apiErr.Status { + case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusGone: + return false + } + if apiErr.Status >= 500 && apiErr.Status <= 599 { + return true + } + return strings.EqualFold(strings.TrimSpace(apiErr.Code), "internal_error") +} + +// pollRetryWait is how long a login poll loop sleeps after a retryable +// failure: its own poll cadence, stretched to the server's Retry-After when +// that is longer, and never past the grant deadline (the loop then reports +// the grant expired rather than sleeping beyond it). +func pollRetryWait(interval, retryAfter time.Duration, deadline time.Time) time.Duration { + wait := interval + if retryAfter > wait { + wait = retryAfter + } + if remaining := time.Until(deadline); remaining < wait { + wait = remaining + } + if wait < 0 { + return 0 + } + return wait +} + // StartDeviceFlow starts the platform device flow (POST /v1/auth/cli/device/start, // RFC-8628, OP1). func (c *BackendClient) StartDeviceFlow(ctx context.Context) (*DeviceStartResponse, error) { @@ -670,7 +712,7 @@ func BrowserLogin(ctx context.Context, backendURL, version string, out io.Writer defer cancel() deadline := start.deadline(time.Now()) - transportFails := 0 + pollFails := 0 for { if time.Now().After(deadline) { return nil, fmt.Errorf("browser login expired before approval") @@ -684,7 +726,7 @@ func BrowserLogin(ctx context.Context, backendURL, version string, out io.Writer return creds, nil } if cliCodePending(err) { - transportFails = 0 + pollFails = 0 if !sleepCtx(loginCtx, browserPollInterval) { if errors.Is(loginCtx.Err(), context.DeadlineExceeded) { return nil, fmt.Errorf("browser login timed out") @@ -694,22 +736,28 @@ func BrowserLogin(ctx context.Context, backendURL, version string, out io.Writer continue } var apiErr *APIError - if !errors.As(err, &apiErr) { - // Transport-level failure (timeout, reset, dropped connection): - // the backend never answered, so this poll proves nothing about - // the grant. Retry a few times before surfacing a real outage. - // Context expiry/cancellation is never retried. + isAPIErr := errors.As(err, &apiErr) + if !isAPIErr || retryablePollError(apiErr) { + // Transport-level failure (timeout, reset, dropped connection) or + // a server-side 5xx (a database blip answers 503 internal_error): + // either way this poll proves nothing about the grant. Retry a + // few times, honoring Retry-After, before surfacing a real + // outage. Context expiry/cancellation is never retried. if loginCtx.Err() != nil { if errors.Is(loginCtx.Err(), context.DeadlineExceeded) { return nil, fmt.Errorf("browser login timed out") } return nil, loginCtx.Err() } - transportFails++ - if transportFails >= maxConsecutivePollFailures { - return nil, fmt.Errorf("redeem Orun login: giving up after %d consecutive poll failures: %w", transportFails, err) + pollFails++ + if pollFails >= maxConsecutivePollFailures { + return nil, fmt.Errorf("redeem Orun login: giving up after %d consecutive poll failures: %w", pollFails, err) } - if !sleepCtx(loginCtx, browserPollInterval) { + var retryAfter time.Duration + if isAPIErr { + retryAfter = apiErr.RetryAfter + } + if !sleepCtx(loginCtx, pollRetryWait(browserPollInterval, retryAfter, deadline)) { if errors.Is(loginCtx.Err(), context.DeadlineExceeded) { return nil, fmt.Errorf("browser login timed out") } @@ -725,7 +773,7 @@ func BrowserLogin(ctx context.Context, backendURL, version string, out io.Writer // Retry-After when present, never polling faster than the // browser cadence, and keep going: the loop is already bounded // by the grant deadline. (Mirrors the device-flow handling.) - transportFails = 0 + pollFails = 0 wait := apiErr.RetryAfter if wait < browserPollInterval { wait = browserPollInterval @@ -761,7 +809,7 @@ func DeviceLogin(ctx context.Context, backendURL, version string, out io.Writer) interval = 5 } deadline := start.deadline(time.Now()) - transportFails := 0 + pollFails := 0 for { if time.Now().After(deadline) { return nil, fmt.Errorf("device login expired") @@ -769,7 +817,8 @@ func DeviceLogin(ctx context.Context, backendURL, version string, out io.Writer) session, pending, err := client.PollDeviceFlow(ctx, start.DeviceCode) if err != nil { var apiErr *APIError - if errors.As(err, &apiErr) { + isAPIErr := errors.As(err, &apiErr) + if isAPIErr { // Terminal denials (OP1): 403 access_denied, 410 expired. switch { case apiErr.Status == http.StatusForbidden || @@ -797,25 +846,32 @@ func DeviceLogin(ctx context.Context, backendURL, version string, out io.Writer) } continue } - return nil, err + if !retryablePollError(apiErr) { + return nil, err + } } - // Transport-level failure (timeout, reset, dropped connection): - // the backend never answered, so this poll proves nothing about - // the grant. Retry a few times before surfacing a real outage. - // Parent-context cancellation is never retried. + // Transport-level failure (timeout, reset, dropped connection) or + // a server-side 5xx (a database blip answers 503 internal_error): + // either way this poll proves nothing about the grant. Retry a + // few times, honoring Retry-After, before surfacing a real + // outage. Parent-context cancellation is never retried. if ctx.Err() != nil { return nil, ctx.Err() } - transportFails++ - if transportFails >= maxConsecutivePollFailures { - return nil, fmt.Errorf("device login: giving up after %d consecutive poll failures: %w", transportFails, err) + pollFails++ + if pollFails >= maxConsecutivePollFailures { + return nil, fmt.Errorf("device login: giving up after %d consecutive poll failures: %w", pollFails, err) } - if !sleepCtx(ctx, time.Duration(interval)*time.Second) { + var retryAfter time.Duration + if isAPIErr { + retryAfter = apiErr.RetryAfter + } + if !sleepCtx(ctx, pollRetryWait(time.Duration(interval)*time.Second, retryAfter, deadline)) { return nil, ctx.Err() } continue } - transportFails = 0 + pollFails = 0 if pending != nil { // RFC-8628 slow_down: back off the poll interval. if strings.EqualFold(pending.Error, "slow_down") { diff --git a/internal/cliauth/login_test.go b/internal/cliauth/login_test.go index 71b1a6bc..dbebbeba 100644 --- a/internal/cliauth/login_test.go +++ b/internal/cliauth/login_test.go @@ -60,6 +60,16 @@ type platformAuthServer struct { // identity scope on the very poll that would redeem an approved grant. browserRateLimitFirst int + // browserUnavailable / deviceUnavailable are the number of polls answered + // 503 internal_error — the platform's answer to a database blip on the + // grant read. Unlike the other failure knobs they apply AFTER the pending + // polls, so the blip lands mid-poll, on the very poll that would redeem the + // already-approved grant. unavailableRetryAfter, when set, is sent as the + // Retry-After header on those 503s. + browserUnavailable int + deviceUnavailable int + unavailableRetryAfter string + // refresh rotation state. currentRefresh string rotateTo string @@ -131,11 +141,16 @@ func newPlatformAuthServer(t *testing.T) *platformAuthServer { writeError(w, 429, "rate_limited", "Too many requests") return } - if int(n) <= p.browserDropFirst+p.browserRateLimitFirst+p.browserApproveAfter { + pendingEnd := p.browserDropFirst + p.browserRateLimitFirst + p.browserApproveAfter + if int(n) <= pendingEnd { // Pending: platform returns HTTP 400 "Not yet approved". writeError(w, 400, "validation_failed", "Not yet approved") return } + if int(n) <= pendingEnd+p.browserUnavailable { + p.writeUnavailable(w) + return + } writeData(w, 200, p.session) default: writeError(w, 422, "validation_failed", "Must be 'cli_code' or 'refresh_token'") @@ -174,11 +189,16 @@ func newPlatformAuthServer(t *testing.T) *platformAuthServer { writeError(w, 429, "rate_limited", "Too many requests") return } - if int(n) <= p.deviceDropFirst+p.deviceRateLimitFirst+p.deviceApproveAfter { + pendingEnd := p.deviceDropFirst + p.deviceRateLimitFirst + p.deviceApproveAfter + if int(n) <= pendingEnd { // Pending: status under data, error mirrors RFC-8628. writeData(w, 200, map[string]any{"status": "pending", "error": "authorization_pending"}) return } + if int(n) <= pendingEnd+p.deviceUnavailable { + p.writeUnavailable(w) + return + } // Complete: the session is NESTED under data.session. writeData(w, 200, map[string]any{"status": "complete", "session": p.session}) }) @@ -192,6 +212,16 @@ func newPlatformAuthServer(t *testing.T) *platformAuthServer { return p } +// writeUnavailable answers a poll the way the platform answers a database +// blip on the grant read: 503 internal_error, with Retry-After when the test +// set one. +func (p *platformAuthServer) writeUnavailable(w http.ResponseWriter) { + if p.unavailableRetryAfter != "" { + w.Header().Set("Retry-After", p.unavailableRetryAfter) + } + writeError(w, 503, "internal_error", "Service temporarily unavailable") +} + // dropConn hijacks the connection and closes it without writing a response, // so the client sees a transport-level error (EOF/connection reset) rather // than any HTTP status. @@ -612,6 +642,159 @@ func TestBrowserLogin_RateLimitedRedeemRetried(t *testing.T) { } } +func TestBrowserLogin_UnavailableMidPollRetried(t *testing.T) { + fileStoreHome(t) + p := newPlatformAuthServer(t) + p.session = sampleSession() + // One pending poll, then the platform's database blips on the grant read + // and answers 503 internal_error on the poll that would redeem the + // approved grant. The 503 says nothing about the grant, so the CLI must + // poll again and redeem rather than end the login. + p.browserApproveAfter = 1 + p.browserUnavailable = 1 + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + creds, err := BrowserLogin(ctx, p.srv.URL, "test", nil, func(string) error { return nil }) + if err != nil { + t.Fatalf("BrowserLogin error = %v; a mid-poll 503 must not kill the flow", err) + } + if creds.AccessToken != "access-tok" { + t.Errorf("AccessToken = %q, want access-tok", creds.AccessToken) + } + // 1 pending + 1 unavailable + 1 redeem. + if got := atomic.LoadInt32(&p.browserPolls); got != 3 { + t.Errorf("polls = %d, want 3 (pending + 503 + redeem)", got) + } +} + +func TestBrowserLogin_UnavailableOutageTerminal(t *testing.T) { + fileStoreHome(t) + p := newPlatformAuthServer(t) + p.session = sampleSession() + // Every poll answers 503: a real outage, not a blip. The flow must give + // up after maxConsecutivePollFailures with the server's error attached, + // not poll silently until the grant expires. + p.browserUnavailable = 1 << 20 + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + _, err := BrowserLogin(ctx, p.srv.URL, "test", nil, func(string) error { return nil }) + if err == nil || !strings.Contains(err.Error(), "giving up after 4 consecutive poll failures") { + t.Fatalf("BrowserLogin error = %v, want a consecutive-poll-failures error", err) + } + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.Status != http.StatusServiceUnavailable { + t.Errorf("error = %v, want it to wrap the 503 *APIError", err) + } + if got := atomic.LoadInt32(&p.browserPolls); got != maxConsecutivePollFailures { + t.Errorf("polls = %d, want exactly %d before giving up", got, maxConsecutivePollFailures) + } +} + +func TestDeviceLogin_UnavailableMidPollRetried(t *testing.T) { + fileStoreHome(t) + p := newPlatformAuthServer(t) + p.session = sampleSession() + // One pending poll, then a 503 internal_error carrying Retry-After: 2, + // then approval. The CLI must keep polling, and wait the 2s the server + // asked for rather than the grant's 1s interval. + p.deviceApproveAfter = 1 + p.deviceUnavailable = 1 + p.unavailableRetryAfter = "2" + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + start := time.Now() + creds, err := DeviceLogin(ctx, p.srv.URL, "test", nil) + if err != nil { + t.Fatalf("DeviceLogin error = %v; a mid-poll 503 must not kill the flow", err) + } + if creds.AccessToken != "access-tok" { + t.Errorf("AccessToken = %q, want access-tok", creds.AccessToken) + } + // 1 pending + 1 unavailable + 1 complete. + if got := atomic.LoadInt32(&p.devicePolls); got != 3 { + t.Errorf("polls = %d, want 3 (pending + 503 + complete)", got) + } + // 1s after the pending poll + 2s Retry-After after the 503. + if elapsed := time.Since(start); elapsed < 3*time.Second { + t.Errorf("device login took %s, want >= 3s (Retry-After on the 503 not honored)", elapsed) + } +} + +func TestDeviceLogin_UnavailableOutageTerminal(t *testing.T) { + fileStoreHome(t) + p := newPlatformAuthServer(t) + p.session = sampleSession() + // Every poll answers 503: give up after maxConsecutivePollFailures. + p.deviceUnavailable = 1 << 20 + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + _, err := DeviceLogin(ctx, p.srv.URL, "test", nil) + if err == nil || !strings.Contains(err.Error(), "giving up after 4 consecutive poll failures") { + t.Fatalf("DeviceLogin error = %v, want a consecutive-poll-failures error", err) + } + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.Status != http.StatusServiceUnavailable { + t.Errorf("error = %v, want it to wrap the 503 *APIError", err) + } + if got := atomic.LoadInt32(&p.devicePolls); got != maxConsecutivePollFailures { + t.Errorf("polls = %d, want exactly %d before giving up", got, maxConsecutivePollFailures) + } +} + +func TestRetryablePollError(t *testing.T) { + cases := []struct { + status int + code string + want bool + }{ + {500, "internal_error", true}, + {502, "HTTP_502", true}, + {503, "internal_error", true}, + {504, "HTTP_504", true}, + {400, "internal_error", true}, // the code alone marks a server-side failure + {400, "validation_failed", false}, + {401, "unauthenticated", false}, + {401, "internal_error", false}, // grant answers stay terminal whatever the code + {403, "access_denied", false}, + {404, "not_found", false}, + {410, "expired", false}, + {422, "validation_failed", false}, + {429, "rate_limited", false}, // has its own branch in both loops + } + for _, c := range cases { + got := retryablePollError(&APIError{Status: c.status, Code: c.code}) + if got != c.want { + t.Errorf("retryablePollError(%d %s) = %v, want %v", c.status, c.code, got, c.want) + } + } + if retryablePollError(nil) { + t.Error("retryablePollError(nil) = true, want false") + } +} + +func TestPollRetryWait(t *testing.T) { + far := time.Now().Add(time.Hour) + if got := pollRetryWait(2*time.Second, 0, far); got != 2*time.Second { + t.Errorf("no Retry-After: wait = %v, want the 2s interval", got) + } + if got := pollRetryWait(2*time.Second, time.Second, far); got != 2*time.Second { + t.Errorf("short Retry-After: wait = %v, want the 2s interval floor", got) + } + if got := pollRetryWait(2*time.Second, 10*time.Second, far); got != 10*time.Second { + t.Errorf("long Retry-After: wait = %v, want 10s", got) + } + if got := pollRetryWait(2*time.Second, time.Hour, time.Now().Add(5*time.Second)); got > 5*time.Second { + t.Errorf("Retry-After past the deadline: wait = %v, want <= 5s", got) + } + if got := pollRetryWait(2*time.Second, 0, time.Now().Add(-time.Second)); got != 0 { + t.Errorf("deadline passed: wait = %v, want 0", got) + } +} + func TestParseRetryAfter(t *testing.T) { cases := []struct { in string