Skip to content

Commit d754e78

Browse files
committed
fix(auth): clean refresh contention diagnostics
1 parent b3fc9fe commit d754e78

5 files changed

Lines changed: 207 additions & 16 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ Docs: https://docs.openclaw.ai
104104
- QA-Lab: stage Multipass transfer scripts under OpenClaw's preferred temp root instead of raw OS temp paths, keeping the VM runner inside temp-path guardrails. (#64098) Thanks @ImLukeF.
105105
- Agents/replies: keep surviving reply media and append a warning when other media references fail, so partial media normalization no longer drops failures silently. Thanks @Jerry-Xin.
106106
- Config/models: accept `thinkingFormat: "together"` in model compat config so Together routes can opt into the Together-specific thinking response shape.
107+
- Agents/auth: keep OAuth refresh-contention diagnostics deterministic and redact file-lock paths from user-facing refresh failures.
107108
- Plugins/tokenjuice: bump the bundled tokenjuice runtime to 0.7.1, bringing Codex hook approval compatibility, pre-tool command wrapping fixes, and Rolldown/Vitest output compaction improvements into the OpenClaw plugin.
108109
- Agents/OpenAI: stop post-processing GPT-5 final replies with hardcoded brevity caps, preserving full channel responses instead of appending synthetic ellipses, and log when strict-agentic GPT-5 execution activates. Fixes #82910.
109110
- Mac app: refine the Settings General and Connection panes with cleaner status panels, card rows, and a single native titlebar sidebar toggle.

‎src/agents/auth-profiles/oauth-manager.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
import { resolveOAuthDir } from "../../config/paths.js";
66
import type { OpenClawConfig } from "../../config/types.openclaw.js";
77
import { formatErrorMessage } from "../../infra/errors.js";
8+
import { FILE_LOCK_TIMEOUT_ERROR_CODE } from "../../infra/file-lock.js";
89
import { captureEnv } from "../../test-utils/env.js";
910
import { __testing as externalAuthTesting } from "./external-auth.js";
1011
import { legacyOAuthSidecarTestUtils } from "./legacy-oauth-sidecar.js";
@@ -263,6 +264,68 @@ describe("OAuthManagerRefreshError", () => {
263264
expect(error.message).not.toContain("[redacted]456");
264265
expect(error.message.match(/\[redacted\]/g)?.length).toBe(2);
265266
});
267+
268+
it("does not flatten refresh contention lock paths into surfaced diagnostics", () => {
269+
const lockPath = "/tmp/openclaw-refresh-contention.lock";
270+
const lockCause = Object.assign(new Error(`file lock timeout for ${lockPath}`), {
271+
code: FILE_LOCK_TIMEOUT_ERROR_CODE,
272+
lockPath,
273+
});
274+
const error = new OAuthManagerRefreshError({
275+
credential: createCredential(),
276+
profileId: "openai-codex:default",
277+
refreshedStore: { version: 1, profiles: {} },
278+
cause: Object.assign(
279+
new Error(
280+
"OAuth refresh failed (refresh_contention): another process is already refreshing openai-codex for openai-codex:default. Please wait for the in-flight refresh to finish and retry.",
281+
{ cause: lockCause },
282+
),
283+
{
284+
code: "refresh_contention",
285+
cause: lockCause,
286+
},
287+
),
288+
});
289+
290+
expect(error.code).toBe("refresh_contention");
291+
expect(error.lockPath).toBe(lockPath);
292+
expect(error.message).toContain("refresh_contention");
293+
expect(error.message).not.toContain(lockPath);
294+
expect(error.message).not.toContain("file lock timeout");
295+
const surfacedCauseMessage = formatErrorMessage(error.cause);
296+
expect(surfacedCauseMessage).toContain("refresh_contention");
297+
expect(surfacedCauseMessage).not.toContain(lockPath);
298+
expect(surfacedCauseMessage).not.toContain("file lock timeout");
299+
});
300+
301+
it("does not flatten structured refresh contention causes into surfaced diagnostics", () => {
302+
const lockPath = "/tmp/openclaw-refresh-contention.lock";
303+
const error = new OAuthManagerRefreshError({
304+
credential: createCredential(),
305+
profileId: "openai-codex:default",
306+
refreshedStore: { version: 1, profiles: {} },
307+
cause: {
308+
code: "refresh_contention",
309+
message:
310+
"OAuth refresh failed (refresh_contention): another process is already refreshing openai-codex for openai-codex:default. Please wait for the in-flight refresh to finish and retry.",
311+
cause: {
312+
code: FILE_LOCK_TIMEOUT_ERROR_CODE,
313+
lockPath,
314+
message: `file lock timeout for ${lockPath}`,
315+
},
316+
},
317+
});
318+
319+
expect(error.code).toBe("refresh_contention");
320+
expect(error.lockPath).toBe(lockPath);
321+
expect(error.message).toContain("refresh_contention");
322+
expect(error.message).not.toContain(lockPath);
323+
expect(error.message).not.toContain("file lock timeout");
324+
const surfacedCauseMessage = formatErrorMessage(error.cause);
325+
expect(surfacedCauseMessage).toContain("refresh_contention");
326+
expect(surfacedCauseMessage).not.toContain(lockPath);
327+
expect(surfacedCauseMessage).not.toContain("file lock timeout");
328+
});
266329
});
267330

268331
describe("createOAuthManager", () => {

‎src/agents/auth-profiles/oauth-manager.ts‎

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -78,19 +78,22 @@ export class OAuthManagerRefreshError extends Error {
7878
typeof params.cause === "object" && params.cause !== null
7979
? (params.cause as { code?: unknown; lockPath?: unknown; cause?: unknown })
8080
: undefined;
81+
const isRefreshContention = structuredCause?.code === "refresh_contention";
8182
const delegatedCause =
82-
structuredCause?.code === "refresh_contention" && structuredCause.cause
83-
? structuredCause.cause
84-
: params.cause;
83+
isRefreshContention && structuredCause.cause ? structuredCause : params.cause;
8584
const storedCredential = params.refreshedStore.profiles[params.profileId];
8685
const secrets = collectOAuthCredentialSecrets(
8786
params.credential,
8887
...(params.attemptedCredentials ?? []),
8988
storedCredential?.type === "oauth" ? storedCredential : undefined,
9089
);
91-
const causeMessage = formatRedactedOAuthRefreshError(params.cause, secrets);
90+
const causeMessage = formatRedactedOAuthRefreshError(params.cause, secrets, {
91+
includeCauses: !isRefreshContention,
92+
});
9293
super(`OAuth token refresh failed for ${params.credential.provider}: ${causeMessage}`, {
93-
cause: createRedactedOAuthRefreshCause(delegatedCause, secrets),
94+
cause: createRedactedOAuthRefreshCause(delegatedCause, secrets, {
95+
includeCauses: !isRefreshContention,
96+
}),
9497
});
9598
this.name = "OAuthManagerRefreshError";
9699
this.#credential = params.credential;
@@ -184,9 +187,12 @@ function redactOAuthCredentialSecrets(message: string, secrets: string[]): strin
184187
return redacted;
185188
}
186189

187-
function formatRawErrorMessage(error: unknown): string {
190+
function formatRawErrorMessage(error: unknown, options: { includeCauses?: boolean } = {}): string {
188191
if (error instanceof Error) {
189192
let formatted = error.message || error.name || "Error";
193+
if (options.includeCauses === false) {
194+
return formatted;
195+
}
190196
let cause: unknown = error.cause;
191197
const seen = new Set<unknown>([error]);
192198
while (cause && !seen.has(cause)) {
@@ -205,6 +211,20 @@ function formatRawErrorMessage(error: unknown): string {
205211
}
206212
return formatted;
207213
}
214+
if (options.includeCauses === false && typeof error === "object" && error !== null) {
215+
const structured = error as Record<string, unknown>;
216+
if (typeof structured.message === "string" && structured.message.length > 0) {
217+
return structured.message;
218+
}
219+
const sanitized = Object.fromEntries(
220+
Object.entries(structured).filter(([key]) => key !== "cause" && key !== "lockPath"),
221+
);
222+
try {
223+
return JSON.stringify(sanitized);
224+
} catch {
225+
return "unserializable error object";
226+
}
227+
}
208228
if (
209229
typeof error === "string" ||
210230
typeof error === "number" ||
@@ -220,12 +240,22 @@ function formatRawErrorMessage(error: unknown): string {
220240
}
221241
}
222242

223-
function formatRedactedOAuthRefreshError(error: unknown, secrets: string[]): string {
224-
return redactSensitiveText(redactOAuthCredentialSecrets(formatRawErrorMessage(error), secrets));
243+
function formatRedactedOAuthRefreshError(
244+
error: unknown,
245+
secrets: string[],
246+
options: { includeCauses?: boolean } = {},
247+
): string {
248+
return redactSensitiveText(
249+
redactOAuthCredentialSecrets(formatRawErrorMessage(error, options), secrets),
250+
);
225251
}
226252

227-
function createRedactedOAuthRefreshCause(cause: unknown, secrets: string[]): Error {
228-
const redacted = formatRedactedOAuthRefreshError(cause, secrets);
253+
function createRedactedOAuthRefreshCause(
254+
cause: unknown,
255+
secrets: string[],
256+
options: { includeCauses?: boolean } = {},
257+
): Error {
258+
const redacted = formatRedactedOAuthRefreshError(cause, secrets, options);
229259
const sanitized = new Error(redacted);
230260
if (cause instanceof Error && cause.name) {
231261
sanitized.name = cause.name;

‎src/agents/auth-profiles/oauth.test.ts‎

Lines changed: 94 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1-
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
25
import type { OpenClawConfig } from "../../config/config.js";
6+
import { FILE_LOCK_TIMEOUT_ERROR_CODE } from "../../infra/file-lock.js";
7+
import { clearRuntimeAuthProfileStoreSnapshots, saveAuthProfileStore } from "./store.js";
38
import type { AuthProfileStore } from "./types.js";
49

510
vi.mock("../cli-credentials.js", () => ({
@@ -9,12 +14,16 @@ vi.mock("../cli-credentials.js", () => ({
914
resetCliCredentialCachesForTest: () => undefined,
1015
}));
1116

12-
vi.mock("../../plugins/provider-runtime.runtime.js", () => ({
13-
formatProviderAuthProfileApiKeyWithPlugin: async (params: { context?: { access?: string } }) =>
14-
params.context?.access,
15-
refreshProviderOAuthCredentialWithPlugin: async () => null,
17+
const providerRuntimeMocks = vi.hoisted(() => ({
18+
buildProviderAuthDoctorHintWithPlugin: vi.fn(async () => ""),
19+
formatProviderAuthProfileApiKeyWithPlugin: vi.fn(
20+
async (params: { context?: { access?: string } }) => params.context?.access,
21+
),
22+
refreshProviderOAuthCredentialWithPlugin: vi.fn(async () => null),
1623
}));
1724

25+
vi.mock("../../plugins/provider-runtime.runtime.js", () => providerRuntimeMocks);
26+
1827
let resolveApiKeyForProfile: typeof import("./oauth.js").resolveApiKeyForProfile;
1928

2029
async function loadOAuthModuleForTest() {
@@ -112,6 +121,14 @@ async function expectResolvedApiKey(params: {
112121

113122
beforeAll(loadOAuthModuleForTest);
114123

124+
beforeEach(() => {
125+
providerRuntimeMocks.buildProviderAuthDoctorHintWithPlugin.mockResolvedValue("");
126+
providerRuntimeMocks.formatProviderAuthProfileApiKeyWithPlugin.mockImplementation(
127+
async (params: { context?: { access?: string } }) => params.context?.access,
128+
);
129+
providerRuntimeMocks.refreshProviderOAuthCredentialWithPlugin.mockResolvedValue(null);
130+
});
131+
115132
afterAll(() => {
116133
vi.doUnmock("../cli-credentials.js");
117134
vi.doUnmock("../../plugins/provider-runtime.runtime.js");
@@ -493,3 +510,75 @@ describe("resolveApiKeyForProfile secret refs", () => {
493510
}
494511
});
495512
});
513+
514+
describe("resolveApiKeyForProfile refresh diagnostics", () => {
515+
it("surfaces refresh contention once without lock-path details", async () => {
516+
const profileId = "openai-codex:default";
517+
const provider = "openai-codex";
518+
const lockPath = "/tmp/openclaw-refresh-contention.lock";
519+
const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "oauth-refresh-contention-"));
520+
const previousStateDir = process.env.OPENCLAW_STATE_DIR;
521+
process.env.OPENCLAW_STATE_DIR = tempRoot;
522+
const agentDir = path.join(tempRoot, "agents", "default", "agent");
523+
await fs.mkdir(agentDir, { recursive: true });
524+
const lockCause = Object.assign(new Error(`file lock timeout for ${lockPath}`), {
525+
code: FILE_LOCK_TIMEOUT_ERROR_CODE,
526+
lockPath,
527+
});
528+
providerRuntimeMocks.refreshProviderOAuthCredentialWithPlugin.mockRejectedValue(
529+
Object.assign(
530+
new Error(
531+
`OAuth refresh failed (refresh_contention): another process is already refreshing ${provider} for ${profileId}. Please wait for the in-flight refresh to finish and retry.`,
532+
{ cause: lockCause },
533+
),
534+
{
535+
code: "refresh_contention",
536+
cause: lockCause,
537+
},
538+
),
539+
);
540+
541+
const store: AuthProfileStore = {
542+
version: 1,
543+
profiles: {
544+
[profileId]: {
545+
type: "oauth",
546+
provider,
547+
access: "expired-access",
548+
refresh: "refresh-token",
549+
expires: Date.now() - 60_000,
550+
},
551+
},
552+
};
553+
saveAuthProfileStore(store, agentDir, { filterExternalAuthProfiles: false });
554+
555+
try {
556+
await resolveApiKeyForProfile({
557+
cfg: cfgFor(profileId, provider, "oauth"),
558+
store,
559+
profileId,
560+
agentDir,
561+
forceRefresh: true,
562+
});
563+
} catch (error) {
564+
const message = error instanceof Error ? error.message : String(error);
565+
expect(message).toContain(
566+
`OAuth token refresh failed for ${provider}: OAuth refresh failed (refresh_contention)`,
567+
);
568+
expect(message.match(/OAuth token refresh failed/g)?.length).toBe(1);
569+
expect(message.match(/OAuth refresh failed \(refresh_contention\)/g)?.length).toBe(1);
570+
expect(message).not.toContain(lockPath);
571+
expect(message).not.toContain("file lock timeout");
572+
return;
573+
} finally {
574+
clearRuntimeAuthProfileStoreSnapshots();
575+
if (previousStateDir === undefined) {
576+
delete process.env.OPENCLAW_STATE_DIR;
577+
} else {
578+
process.env.OPENCLAW_STATE_DIR = previousStateDir;
579+
}
580+
await fs.rm(tempRoot, { recursive: true, force: true });
581+
}
582+
throw new Error("expected OAuth refresh contention failure");
583+
});
584+
});

‎src/agents/auth-profiles/oauth.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,11 @@ function extractErrorMessage(error: unknown): string {
122122
return formatErrorMessage(error);
123123
}
124124

125+
function stripOAuthRefreshFailurePrefix(message: string, provider: string): string {
126+
const prefix = `OAuth token refresh failed for ${provider}: `;
127+
return message.startsWith(prefix) ? message.slice(prefix.length) : message;
128+
}
129+
125130
export function isRefreshTokenReusedError(error: unknown): boolean {
126131
const message = normalizeLowercaseStringOrEmpty(extractErrorMessage(error));
127132
return (
@@ -411,7 +416,10 @@ export async function resolveApiKeyForProfile(
411416
}
412417
}
413418

414-
const message = extractErrorMessage(surfacedMessageError);
419+
const message =
420+
error instanceof OAuthManagerRefreshError && error.code === "refresh_contention"
421+
? stripOAuthRefreshFailurePrefix(error.message, cred.provider)
422+
: extractErrorMessage(surfacedMessageError);
415423
const hint = await formatAuthDoctorHint({
416424
cfg,
417425
store: refreshedStore,

0 commit comments

Comments
 (0)