Skip to content

[wrangler] Reuse OAuth credentials refreshed by another process - #16874

Merged
petebacondarwin merged 2 commits into
mainfrom
codex/oauth-refresh-followups
Nov 14, 2026
Merged

petebacondarwin merged 2 commits into
mainfrom
codex/oauth-refresh-followups

Conversation

@petebacondarwin

Copy link
Copy Markdown
Contributor

Addresses #15089. Alternative approach to #15136.

When another Wrangler process has already refreshed our credentials, reuse its valid access token instead of immediately refreshing again. This prevents an unnecessary extra rotation that can leave an already-used refresh token on disk.

How the failure happens

The expiry check and refresh-token read currently happen separately. A process can decide to refresh using an old expiry time, then read a newer refresh token written by a sibling. It goes ahead with a refresh that is no longer needed.

For example, A, B, and C all start with expired credentials and refresh token T0:

  1. A and B exchange T0. The server returns the same replacement, T1, to both.
  2. B saves a valid access token and T1. A has not saved its response yet.
  3. C continues from its earlier expiry check. It rereads T1, exchanges it for T2, and saves T2.
  4. A finally saves its T1 over T2.
  5. Later, another process reads T1 from disk. C already used it, and the server's reuse tolerance has elapsed, so the refresh fails.

The refresh requests can all be quick. The stale token remains on disk until a later refresh needs it.

What changes

Immediately before an exchange, refreshToken() now reads the complete credential snapshot again:

  • If its access token is still valid, return successfully without making a refresh request or writing the snapshot back.
  • If it is expired, exchange the refresh token from that same snapshot. The token-exchange helper receives that value directly, so there is no second independent read.

In the example above, C sees B's valid access token and skips step 3. T1 is never consumed by C. A's late write consequently saves the same, still-unused T1 already on disk, and the later refresh succeeds.

The fresh-read behavior introduced by #13910 is preserved. Both the expiry decision and token selection now use that fresh read.

Why prefer this to a file lock for this failure?

The problem in this sequence is the unnecessary T1 → T2 refresh. Checking current credentials removes that request, which also removes the opportunity for A to overwrite its result.

This uses the existing credential-storage interface, including file and keyring-backed storage. It adds no lock files, ownership records, PID checks, stale-lock recovery, waiting, or lock timeouts. There is no new dependency or platform-specific coordination to maintain.

This does not serialize every refresh. Ordinary overlapping exchanges of the same token remain possible; in five production trials, both requests returned the same usable replacement. The change prevents a caller that has already fallen behind a sibling from unnecessarily advancing to another token generation.

Validation

  • Seven targeted Vitest tests pass: five new regression cases and the two existing token-exchange tests. The new tests cover both authentication entry points, no request or write when a sibling has saved valid credentials, and refreshing the latest token when its access token is expired, expires exactly now, or has no expiry.
  • Targeted strict TypeScript, formatting, and lint checks pass. The full workspace checks have not been run with this checkout's partial dependency installation.
  • A controlled worker-thread experiment using the actual OAuth flow, real atomic file writes, and a local provider reproduced the original late-write failure. With this change, C made no refresh request and no write, and the later refresh succeeded. Both implementations passed the matching control. The provider's 65-second wait was simulated in this comparison.
  • Separate production endpoint experiments confirmed the token behavior: after A/B both received T1, C exchanged it for T2; deliberately saving A's held T1 over T2 caused invalid_grant after a real 65-second wait. Retaining T2 passed the matching control. All three initial HTTP requests in the failing trial took less than a second.

Scope: this fixes the reproduced unnecessary-refresh sequence. The issue's logs do not establish that exact ordering, and this is not a guarantee against every possible long process suspension after reading a token. A full cross-process lock provides broader serialization guarantees. Keeping this as a draft allows validation against the original workload before deciding whether those broader guarantees are needed.


  • Tests
    • Tests included/updated
    • Automated tests not possible - manual testing has been completed as follows:
    • Additional testing not necessary because:
  • Public documentation
    • Cloudflare docs PR(s):
    • Documentation not necessary because: this is an internal OAuth refresh fix with no new user-facing configuration or workflow.

@changeset-bot

changeset-bot Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: f450170

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@cloudflare/workers-auth Patch
wrangler Patch
@cloudflare/remote-bindings Patch
@cloudflare/vitest-plugin Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@ask-bonk

ask-bonk Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

LGTM

github run

@pkg-pr-new

pkg-pr-new Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
@cloudflare/autoconfig

npm i https://pkg.pr.new/@cloudflare/autoconfig@16874

@cloudflare/build-output-utils

npm i https://pkg.pr.new/@cloudflare/build-output-utils@16874

@cloudflare/codemods

npm i https://pkg.pr.new/@cloudflare/codemods@16874

@cloudflare/config

npm i https://pkg.pr.new/@cloudflare/config@16874

@cloudflare/containers-shared

npm i https://pkg.pr.new/@cloudflare/containers-shared@16874

create-cloudflare

npm i https://pkg.pr.new/create-cloudflare@16874

@cloudflare/deploy-helpers

npm i https://pkg.pr.new/@cloudflare/deploy-helpers@16874

@cloudflare/kv-asset-handler

npm i https://pkg.pr.new/@cloudflare/kv-asset-handler@16874

miniflare

npm i https://pkg.pr.new/miniflare@16874

@cloudflare/pages-functions

npm i https://pkg.pr.new/@cloudflare/pages-functions@16874

@cloudflare/pages-shared

npm i https://pkg.pr.new/@cloudflare/pages-shared@16874

@cloudflare/runtime-types

npm i https://pkg.pr.new/@cloudflare/runtime-types@16874

@cloudflare/unenv-preset

npm i https://pkg.pr.new/@cloudflare/unenv-preset@16874

@cloudflare/vite-plugin

npm i https://pkg.pr.new/@cloudflare/vite-plugin@16874

@cloudflare/vitest-plugin

npm i https://pkg.pr.new/@cloudflare/vitest-plugin@16874

@cloudflare/workers-auth

npm i https://pkg.pr.new/@cloudflare/workers-auth@16874

@cloudflare/workers-editor-shared

npm i https://pkg.pr.new/@cloudflare/workers-editor-shared@16874

@cloudflare/workers-utils

npm i https://pkg.pr.new/@cloudflare/workers-utils@16874

wrangler

npm i https://pkg.pr.new/wrangler@16874

commit: f450170

@petebacondarwin
petebacondarwin marked this pull request as ready for review November 12, 2026 16:42
@workers-devprod
workers-devprod requested review from a team and dario-piotrowicz and removed request for a team November 12, 2026 16:42
@workers-devprod

workers-devprod commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Codeowners approval required for this PR:

  • ✅ @cloudflare/wrangler
Show detailed file reviewers

clanky-the-clanker[bot]

This comment was marked as resolved.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

Co-authored-by: clanky-the-clanker[bot] <342202840+clanky-the-clanker[bot]@users.noreply.github.com>

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approved — The earlier import cleanup has been made, and nothing new turned up. The recheck logic is correct and well tested.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security issues found. The change only narrows when a refresh token is exchanged. It does not change how credentials are stored or sent.


📖 AGENTS.md: ✅ LGTM

This change does not need any AGENTS.md updates.


📋 Code Quality: ✅ LGTM

The earlier note is fixed: token-exchange.ts now has a single import type { AccessToken, OAuthFlowState, RefreshToken } from "./state". refreshToken() in flow.ts uses one stored-credential read both to decide whether to skip the refresh and to pick the token to exchange. Missing, invalid and exactly-now expiries all still go on to refresh, and the tests cover each case.


⚡ Performance: ✅ LGTM

No performance issues found. The extra storage read happens only on the refresh path, and it replaces the read that exchangeRefreshTokenForAccessToken used to do.


📝 Documentation: ✅ LGTM

The changeset and JSDoc match the new behaviour.


Reviewed commit: f4501704

@workers-devprod workers-devprod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codeowners reviews satisfied

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants