Skip to content

[Bug]: Anthropic OAuth DNS failure leaves a durable intent and permanently requires re-login #6570

Closed

Description

@atinseau

Summary

An Anthropic OAuth refresh that fails before connecting to the token endpoint with getaddrinfo ENOTFOUND api.anthropic.com leaves a durable refresh intent. The next refresh attempt marks the account needsReauth: true and throws OAuthLoginRequiredError without calling the token endpoint again, even when the mocked network has recovered.

This turns a DNS outage into a persistent manual-relogin requirement. It is distinct from an ambiguous timeout after a request might have reached Anthropic: the existing replay guard should remain for those ambiguous outcomes.

Environment

  • Client: OpenCodex dashboard / OAuth account resolver
  • Area: Authentication and account pool
  • Installed package: @bitkyc08/opencodex 2.76.0
  • OS: macOS 27.0.1, arm64
  • Reproduced with packaged Bun 1.4.0 and global Bun 1.4.2
  • Provider: Anthropic, authMode: "oauth", credential source: "oauth"; no model inference is needed

Observed live symptom and limits of attribution

The user reports recurrent Anthropic disconnections. Read-only inspection found:

GET /api/oauth/accounts?provider=anthropic -> HTTP 200
account count: 1
needsReauth: true
paused: false
credential source: oauth
refresh token present: true
access credential expired: true
pending auth.refresh.anthropic.<redacted>.lock.json: present
pending intent generation matches current credential generation: true

The service log also contains repeated TypeError: getaddrinfo ENOTFOUND api.anthropic.com errors from the quota endpoint (/api/oauth/usage) and timeout errors. The log does not record enough information to attribute the outstanding token refresh attempt conclusively to DNS failure rather than an ambiguous timeout or another interrupted attempt. No claim is made that the real saved refresh token is still accepted by Anthropic.

The deterministic reproduction below independently confirms the DNS failure handling defect. The live account and its replay guard were not deleted or modified, and its refresh token was not manually replayed.

Reproduction

Save the script below as anthropic-refresh-repro.mjs and run:

bun anthropic-refresh-repro.mjs /path/to/opencodex

The argument is the installed npm package directory or repository root containing src/. The script runs the real refreshAnthropicAccountWithLock and refreshAnthropicToken implementations against an isolated temporary auth store with fake credentials. Only the HTTP transport is stubbed; no account or external network is needed.

It tests three scenarios, each followed by a simulated recovered token endpoint:

First failure Fetch calls across two attempts Second result needsReauth Intent remains
Explicit HTTP 503 2 Success false false
DNS ENOTFOUND 1 OAuthLoginRequiredError true true
Ambiguous timeout (control) 1 OAuthLoginRequiredError true true

The script exits 1 at BUG: DNS failure before connecting must not permanently require re-login. Repeated runs produced the same result in under a second.

Code path

In installed 2.76.0, src/oauth/index.ts, refreshAnthropicAccountWithLock:

  1. Writes the durable intent before calling def.refresh.
  2. Sets refreshMayHaveReachedProvider = true before entering the adapter.
  3. The adapter in src/oauth/anthropic.ts propagates transport errors without structured evidence of whether the request could have reached the server.
  4. An ENOTFOUND error is nonterminal, but fails definitivelyAnswered(error), which accepts only an AnthropicTokenError with HTTP status. The intent remains.
  5. On the next call, the same-generation pending-intent branch marks the account as needing reauthentication before any network call.
  6. The token guardian subsequently skips accounts marked needsReauth; the flag and intent also survive process restart.

The same broad dispatch classification and pending-intent branches are present in the inspected upstream source at 06841165 (package version 2.77.0). The runnable reproduction was executed on installed 2.76.0, not on a full checkout of 2.77.0.

Expected behavior / suggested fix scope

Preserve structured evidence of a definitive pre-connection failure in the Anthropic token transport. Clear the corresponding attempt intent through the existing generation-safe cleanup path and allow retry/backoff for that narrow class of failure.

Do not clear intents for every network error: a timeout, dropped connection after dispatch, unreadable successful response, or persistence failure can conceal an already-rotated refresh token. Those cases still need the replay guard. Proxy, redirects, and transport retries must be considered before asserting that no request reached the token endpoint.

Also consider recording a sanitized refresh failure category and distinguishing an unknown refresh outcome from an explicitly rejected grant in the account-health UI. Currently the live state cannot explain which of those caused the reconnect requirement.

Related issue

Issue #209 describes a similar user-visible symptom on an older release. This report concerns the durable-intent / pre-connection failure path in 2.76.0, with a runnable reproduction and an HTTP-503 control.

No secrets, actual account identifiers, email addresses, user paths, or original credential files are included.

Reproduction script

// Run with Bun; argument: installed opencodex package directory or repository root.
// Uses only fake credentials in a temporary directory. No external network calls.
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import assert from 'node:assert/strict';

const root = resolve(process.argv[2] ?? '.');
const scratch = mkdtempSync(join(tmpdir(), 'ocx-anthropic-repro-'));
process.env.OPENCODEX_HOME = scratch;
const scenarios = ['http503', 'dns-enotfound', 'ambiguous-timeout'];
const credential = {access:'fake-access',refresh:'fake-refresh',expires:Date.now()-60_000,source:'oauth'};
writeFileSync(join(scratch,'auth.json'),JSON.stringify({anthropic:{activeAccountId:scenarios[0],accounts:scenarios.map(id=>({id,credential}))}}),{mode:0o600});
const realFetch = globalThis.fetch;
try {
  const {refreshAnthropicAccountWithLock} = await import(pathToFileURL(join(root,'src/oauth/index.ts')).href);
  const {refreshAnthropicToken} = await import(pathToFileURL(join(root,'src/oauth/anthropic.ts')).href);
  const {getAccountCredentialWithStatus,readOAuthRefreshIntent} = await import(pathToFileURL(join(root,'src/oauth/store.ts')).href);
  const results=[];
  for(const scenario of scenarios){
    let calls=0;
    globalThis.fetch=async url=>{
      assert.equal(String(url),'https://api.anthropic.com/v1/oauth/token');
      calls++;
      if(calls===1){
        if(scenario==='http503')return new Response('{"error":"temporarily_unavailable"}',{status:503});
        if(scenario==='dns-enotfound')throw Object.assign(new TypeError('getaddrinfo ENOTFOUND api.anthropic.com'),{code:'ENOTFOUND',syscall:'getaddrinfo',hostname:'api.anthropic.com'});
        throw new DOMException('The operation timed out.','TimeoutError');
      }
      return Response.json({access_token:'fake-new-access',refresh_token:'fake-new-refresh',expires_in:3600});
    };
    const errors=[];
    for(let attempt=0;attempt<2;attempt++){
      try{await refreshAnthropicAccountWithLock('anthropic',scenario,{refresh:refreshAnthropicToken},credential);errors.push(null);}
      catch(e){errors.push(e.name);}
    }
    const row=getAccountCredentialWithStatus('anthropic',scenario);
    results.push({scenario,fetchCalls:calls,errors,needsReauth:row.needsReauth,pendingIntent:!!readOAuthRefreshIntent('anthropic',scenario),recovered:row.credential.access==='fake-new-access'});
  }
  console.log(JSON.stringify(results,null,2));
  assert.equal(results[0].recovered,true,'Control: explicit HTTP 503 should recover');
  assert.equal(results[2].pendingIntent,true,'Ambiguous timeout must preserve replay guard');
  assert.equal(results[1].recovered,true,'BUG: DNS failure before connecting must not permanently require re-login');
} finally {
  globalThis.fetch=realFetch;
  rmSync(scratch,{recursive:true,force:true});
}

Activity

  1. added
    bug
    account-pool
    on Oct 4, 2026
  2. Ingwannu commented on Oct 4, 2026

    @Ingwannu
    Owner

    Confirmed the reported state transition against current trusted dev 33185c2ccf7085f94357d9e56512803949b22cc5, not only installed 2.76.0. I used the actual refresh/store implementations in a detached checkout, fake credentials in private homes, and a fully stubbed token transport on Linux/Bun 1.4.0.

    Injected first result HTTP calls across two attempts Second result Reauth / pending intent
    HTTP 503 2 success false / false
    ENOTFOUND 1 OAuthLoginRequiredError true / true
    ambiguous timeout 1 OAuthLoginRequiredError true / true

    The recovered-DNS assertion fails as reported (exit 1); both controls satisfy their assertions. In current src/oauth/index.ts, definitivelyAnswered at line 737 accepts only a structured HTTP response, dispatch is conservatively marked before def.refresh at line 1010, and known-failure intent cleanup at line 1041 excludes this raw transport error. The next same-generation intent branch refuses without another HTTP call.

    This independently validates the mocked DNS-handling path. It does not establish the cause of the saved live account state or prove that every ENOTFOUND emitted by a real proxy/redirect/retry transport is pre-dispatch. Please keep the fix narrow: transport-owned evidence of a definitively unsent attempt, generation-safe known-failure cleanup, and regressions preserving unknown-outcome, rotated-token/persistence and superseding-owner guards. Do not delete a live intent or blanket-retry network errors. A change to this refresh contract still needs the required independent boundary review; this reproduction supplies no waiver or approval.

    The probe ran sequentially under CPU75%, MemoryHigh1280M/MemoryMax1536M, swap0, Tasks64, IOWeight20, nice10 and a 120s limit, with new private HOME/CODEX_HOME/OPENCODEX_HOME/TMPDIR and Claude config directories. Protected real-home snapshots are unchanged. No actual account/provider call, live repair, UI change or security/privacy scan was performed. The issue remains open; no fix or release is claimed.

  3. atinseau commented on Oct 4, 2026

    @atinseau
    ContributorAuthor

    Local fix proposal, tested against installed 2.76.0. Thanks for independently confirming the reproduction.

    The original reproduction posted above fails before this patch and passes unchanged afterwards. The expanded check also passes through getValidAccessTokenForAccount with packaged Bun 1.4.0 (and the refresh-lock seam with Bun 1.4.2).

    The candidate patch:

    • Adds transport-owned requestNotSent evidence only for the structured ENOTFOUND + getaddrinfo + exact token-endpoint hostname case, caught around the initial fetch only.
    • Uses redirect: "error" and keepalive: false for the token exchange to avoid classifying a redirect failure or a reused-connection retry as an initial DNS failure.
    • Uses the existing generation-safe known-failure intent cleanup, with the pre-dispatch reason. It does not assign a fake HTTP status.
    • Keeps unknown outcomes protected: timeout, unstructured DNS text, a different hostname, failure while reading a response body, and invalid_grant do not replay the token.
    Scenario Fetch calls Final state after two attempts
    Explicit HTTP 503 2 renewed; no intent; no reauth
    Initial structured DNS failure 2 renewed; no intent; no reauth
    Ambiguous timeout 1 blocked; intent preserved
    invalid_grant 1 reauth required
    Wrong-host DNS error 1 blocked; intent preserved
    Unstructured error mentioning DNS 1 blocked; intent preserved
    DNS-shaped error reading an already-returned response 1 blocked; intent preserved

    A real fetch to a reserved .invalid name using packaged Bun 1.4.0 produced the same structured error fields as the fixture; no credentials were sent. This verifies the error shape, not every possible proxy/retry transport path.

    Limits: this is a local candidate, not an independently reviewed upstream fix. Full repository typecheck/privacy suites were unavailable in the installed npm distribution. I have not replayed or deleted the existing live account's uncertain intent, and this patch cannot prove the historical live outage was DNS rather than timeout. Please retain the requested boundary review, particularly for Bun/proxy retry behavior and generation/ownership races.

    Patch (relative to 2.76.0):

    --- a/src/oauth/anthropic.ts
    +++ b/src/oauth/anthropic.ts
    @@ -39,6 +39,7 @@
         message: string,
         readonly httpStatus: number | undefined,
         readonly oauthError: string | undefined,
    +    readonly requestNotSent = false,
       ) {
         super(message);
         this.name = "AnthropicTokenError";
    @@ -46,12 +47,26 @@
     }
     
     async function postJson(url: string, body: Record<string, string | number>): Promise<string> {
    -  const response = await fetch(url, {
    -    method: "POST",
    -    headers: { "Content-Type": "application/json", Accept: "application/json" },
    -    body: JSON.stringify(body),
    -    signal: AbortSignal.timeout(30_000),
    -  });
    +  let response: Response;
    +  try {
    +    response = await fetch(url, {
    +      method: "POST",
    +      headers: { "Content-Type": "application/json", Accept: "application/json" },
    +      body: JSON.stringify(body),
    +      signal: AbortSignal.timeout(30_000),
    +      // Keep a DNS failure attributable to this initial connection, not a redirect
    +      // or a retry of a previously used keep-alive socket.
    +      redirect: "error",
    +      keepalive: false,
    +    });
    +  } catch (error) {
    +    const failure = error as { code?: unknown; syscall?: unknown; hostname?: unknown } | null;
    +    if (failure?.code === "ENOTFOUND" && failure.syscall === "getaddrinfo"
    +      && failure.hostname === new URL(url).hostname) {
    +      throw new AnthropicTokenError("Anthropic OAuth DNS lookup failed before connection", undefined, undefined, true);
    +    }
    +    throw error;
    +  }
       const responseBody = await response.text();
       if (!response.ok) {
         let oauthError: string | undefined;
    --- a/src/oauth/index.ts
    +++ b/src/oauth/index.ts
    @@ -1025,18 +1025,20 @@
             // OAuthLoginRequiredError. One 503 locked the account out of refresh until manual
             // re-auth even after upstream recovered.
             //
    -        // Only clear the intent when the server DEFINITIVELY answered and rejected the
    -        // request. The adapter attaches an HTTP status only to that explicit non-success
    +        // Only clear the intent when the adapter proves no request was sent, or when the
    +        // server definitively rejected it. HTTP status describes that explicit non-success
             // response. A timeout, a dropped connection, or an unreadable/unparseable body
             // carries no status: the server may already have
             // rotated the token, and replaying it could trip refresh-token-reuse revocation.
             // Those outcomes keep the intent so the guard still refuses a blind replay.
    -        if ((!refreshMayHaveReachedProvider || definitivelyAnswered(error)) && attemptIntent) {
    +        const requestNotSent = !refreshMayHaveReachedProvider
    +          || (error instanceof AnthropicTokenError && error.requestNotSent);
    +        if ((requestNotSent || definitivelyAnswered(error)) && attemptIntent) {
               await clearAnthropicRefreshIntentForKnownFailure(
                 provider,
                 accountId,
                 attemptIntent,
    -            refreshMayHaveReachedProvider ? "definitive-rejection" : "pre-dispatch",
    +            requestNotSent ? "pre-dispatch" : "definitive-rejection",
                 error,
               );
             }

    Local activation validation: after the user completed a fresh OAuth login (the old uncertain token was never replayed), a single real refresh through refreshAnthropicAccountWithLock rotated credentials, persisted them with needsReauth: false, left no pending intent, and the new access token received HTTP 200 from Anthropic’s usage endpoint. This validates a normal real refresh after login; it is not an induced real-network-outage test.

  4. Ingwannu commented on Oct 4, 2026

    @Ingwannu
    Owner

    The local candidate is useful additional evidence, but is not yet an upstream fix or independent approval. Please open a focused PR against current dev 33185c2ccf7085f94357d9e56512803949b22cc5, carrying the seven scenarios into permanent repository tests and updating the owning refresh documentation. Keep both test-layout registrations and the existing generation-safe cleanup/ownership regressions intact; the installed-2.76.0 patch is not a substitute for current-source integration.

    Current Bun fetch documentation describes keepalive: false as disabling connection reuse. That supports the intent of the option, but does not by itself prove that every supported-version direct/proxied transport path could not already have dispatched a request before emitting these error fields. Please make the pinned-runtime and proxy/redirect/retry assumptions explicit, and retain refusal for any outcome that cannot be proven unsent. No blanket network-error cleanup or fabricated HTTP status.

    Your normal real refresh after a fresh login is separate from outage/replay recovery. I have not independently executed this patched candidate, induced a real provider outage, inspected your live account or replayed/deleted its uncertain intent. Required independent refresh-boundary review remains before acceptance; this is correctness triage, not sponsorship, a security scan or permission to change a live account.

  5. lidge-jun commented on Oct 4, 2026

    @lidge-jun
    Owner

    Fixed on dev by #6586 (989bb24), carrying your patch with credit: a refresh intent is released only when a DNS failure proves the request never left the machine; ambiguous outcomes keep the replay guard. Closing manually because PRs target dev; it ships in the next release. Thank you for the detailed report and patch!

  6. atinseau commented on Oct 5, 2026

    @atinseau
    ContributorAuthor

    Fixed on dev by #6586 (989bb24), carrying your patch with credit: a refresh intent is released only when a DNS failure proves the request never left the machine; ambiguous outcomes keep the replay guard. Closing manually because PRs target dev; it ships in the next release. Thank you for the detailed report and patch!

    Thank you to you for this incredible tool ;)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    account-poolbug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions