You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
bug: github external auth intermittently fails to refresh token #17069
Occasionally when running a git command in workspace a user is prompted to re-authenticate with GitHub, but when they try, they get Failed to validate oauth access token error. From the logs it seems that token refresh request times out. The issue fixes itself after about 10-15 minutes, but clicking login or unlinking and reenabling external auth does not seem to help. Only small number of users are affected.
Additionally, when they go to Account settings in Coder they see a similar token failed to validate error:
Relevant Log Output
2025-03-24 09:43:35.035 [warn] coderd: GET host=coder.example.org path=/api/v2/workspaceagents/me/external-auth proto=HTTP/1.1 remote_addr=X.X.X.X start="2025-03-24T09:43:34.876944956Z" took=158.437119ms status_code=500 latency_ms=158 response_body="{\"message\":\"Failed to refresh external auth token.\",\"detail\":\"validate external auth token: Get \\\"https://api.github.com/user\\\": context canceled\"}\n" request_id=f0f95513-5235-4f20-ba1e-b301dd87794a
Expected Behavior
No response
Steps to Reproduce
We have not found what causes the issue initially. But after it happens any of the below commands stop returning access token for the next 10-15 minutes:
GIT_PREFIX= coder "Username for https://github.com/:"
curl -X GET "$CODER_AGENT_URL"'/api/v2/workspaceagents/me/external-auth?match=github.com' -H 'Accept: application/json' -H "Coder-Session-Token: $CODER_AGENT_TOKEN"
We investigated and reproduced this issue on a live Coder deployment (v2.31.3) running a GitHub App for external auth. Here's what we found — three related bugs that compound to cause the reported symptoms.
Bug 1: Concurrent token refresh race condition
GitHub App user-to-server tokens (ghu_ prefix) expire after 8 hours and use single-use refresh tokens — once a refresh token is used, it's invalidated. The Go oauth2 library triggers a refresh when the token is within 10 seconds of expiry (expiryDelta).
When a user has multiple terminals, IDE connections, or workspaces open simultaneously, multiple concurrent requests hit GET /api/v2/workspaceagents/me/external-auth at the moment the token nears expiry. Each request independently calls RefreshToken(), which calls TokenSource().Token() to refresh with GitHub. The first request (the "winner") succeeds, but all subsequent requests (the "losers") get bad_refresh_token from GitHub because the single-use refresh token was already consumed.
The losers then cache this bad_refresh_token error in the oauth_refresh_failure_reason column of the external_auth_links table and clear the refresh token. This poisons the database — subsequent refresh attempts see the cached failure and return an error without even trying. The user is stuck until they manually re-authenticate.
Evidence from the database: All 7 affected users (out of 64 total) had the same cached error: oauth2: "bad_refresh_token" "The refresh token passed is incorrect or expired." — and 5 of 7 failures occurred within 5–10 seconds of token expiry, matching the expiryDelta window. Users with more workspaces were disproportionately affected.
Reproduction: We set oauth_expiry = NOW() + interval '5 seconds' and fired 10 concurrent requests. All 10 returned a valid token (the winner refreshed), but the database was left with the cached bad_refresh_token failure and an empty refresh token.
Bug 2: ValidateToken uses wrong context
In coderd/externalauth/externalauth.go:269, after a successful token refresh, ValidateToken is called with the caller's HTTP request context (ctx) instead of the dedicated retryCtx (which has a 1-second timeout). If the workspace agent's request is cancelled during validation, the validation fails with context canceled, which is the error originally reported in this issue:
validate external auth token: Get "https://api.github.com/user": context canceled
Bug 3: Rate limit 403 treated as invalid token (explains the "10-15 minute" self-heal)
ValidateToken treats any HTTP 403 from the validation endpoint as "token is no longer valid." However, GitHub returns 403 for both "bad token" and "rate limit exceeded." When the concurrent refresh race fires many requests, it can exhaust the IP-based unauthenticated rate limit (60 requests/hour). After that, everyValidateToken call gets a rate-limit 403, which the code misinterprets as an invalid token.
This explains:
Why re-authentication doesn't help: The OAuth callback stores a valid token, but the immediate post-callback validation call hits the rate limit → 403 → "Failed to validate oauth access token" error in the UI.
Why it self-heals after 10-15 minutes: It's the GitHub IP-based rate limit reset window (resets hourly). Once the rate limit resets, validation succeeds again.
Why it's worse in shared-IP environments: All workspace agents and the Coder server share the same IP-based rate limit pool.
Race detection: Before caching a bad_refresh_token failure, re-read the external auth link from the database. If the refresh token has changed (concurrent winner), return the winner's token instead of poisoning the database.
Context fix: Use retryCtx instead of the caller's HTTP request context for ValidateToken.
Rate limit handling: Distinguish rate-limit 403 from auth-failure 403 by checking the X-RateLimit-Remaining: 0 header. Return a transient error instead of permanently marking the token as invalid.
Activity
jasonwbarnett commentedon Apr 9, 2026
Root Cause Analysis
We investigated and reproduced this issue on a live Coder deployment (v2.31.3) running a GitHub App for external auth. Here's what we found — three related bugs that compound to cause the reported symptoms.
Bug 1: Concurrent token refresh race condition
GitHub App user-to-server tokens (
ghu_prefix) expire after 8 hours and use single-use refresh tokens — once a refresh token is used, it's invalidated. The Gooauth2library triggers a refresh when the token is within 10 seconds of expiry (expiryDelta).When a user has multiple terminals, IDE connections, or workspaces open simultaneously, multiple concurrent requests hit
GET /api/v2/workspaceagents/me/external-authat the moment the token nears expiry. Each request independently callsRefreshToken(), which callsTokenSource().Token()to refresh with GitHub. The first request (the "winner") succeeds, but all subsequent requests (the "losers") getbad_refresh_tokenfrom GitHub because the single-use refresh token was already consumed.The losers then cache this
bad_refresh_tokenerror in theoauth_refresh_failure_reasoncolumn of theexternal_auth_linkstable and clear the refresh token. This poisons the database — subsequent refresh attempts see the cached failure and return an error without even trying. The user is stuck until they manually re-authenticate.Evidence from the database: All 7 affected users (out of 64 total) had the same cached error:
oauth2: "bad_refresh_token" "The refresh token passed is incorrect or expired."— and 5 of 7 failures occurred within 5–10 seconds of token expiry, matching theexpiryDeltawindow. Users with more workspaces were disproportionately affected.Reproduction: We set
oauth_expiry = NOW() + interval '5 seconds'and fired 10 concurrent requests. All 10 returned a valid token (the winner refreshed), but the database was left with the cachedbad_refresh_tokenfailure and an empty refresh token.Bug 2: ValidateToken uses wrong context
In
coderd/externalauth/externalauth.go:269, after a successful token refresh,ValidateTokenis called with the caller's HTTP request context (ctx) instead of the dedicatedretryCtx(which has a 1-second timeout). If the workspace agent's request is cancelled during validation, the validation fails withcontext canceled, which is the error originally reported in this issue:Bug 3: Rate limit 403 treated as invalid token (explains the "10-15 minute" self-heal)
ValidateTokentreats any HTTP 403 from the validation endpoint as "token is no longer valid." However, GitHub returns 403 for both "bad token" and "rate limit exceeded." When the concurrent refresh race fires many requests, it can exhaust the IP-based unauthenticated rate limit (60 requests/hour). After that, everyValidateTokencall gets a rate-limit 403, which the code misinterprets as an invalid token.This explains:
Fix
PR: #24228
bad_refresh_tokenfailure, re-read the external auth link from the database. If the refresh token has changed (concurrent winner), return the winner's token instead of poisoning the database.retryCtxinstead of the caller's HTTP request context forValidateToken.X-RateLimit-Remaining: 0header. Return a transient error instead of permanently marking the token as invalid.fix(coderd/externalauth): detect concurrent refresh race to prevent c…