Skip to content

Commit 9c9993e

Browse files
committed
fix(agents): redact overlapping auth secrets
1 parent 14614c6 commit 9c9993e

3 files changed

Lines changed: 199 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Docs: https://docs.openclaw.ai
2929
- Update/installers: override npm `min-release-age` quarantine for OpenClaw-managed package installs, so `openclaw update`, plugin updates, and hosted installer scripts can install the requested latest release immediately.
3030
- Agents/sessions: preserve fresh post-compaction token snapshots across stale usage updates, preventing repeated auto-compaction after every message. Fixes #82576. (#82578) Thanks @njuboy11.
3131
- Agents/OpenAI Responses: log redacted diagnostics for detail-less `response.failed` events while preserving failed response ids, so operators can correlate provider-side failures. Fixes #82558.
32+
- Agents/auth: redact OAuth refresh failure causes against in-memory, attempted, and reloaded credentials before generic token masking while ensuring failed ACP dispatch cleanup closes initialized runtimes.
3233
- Telegram: cache successful startup bot identity by account and token fingerprint for up to 24 hours, so restarts can skip redundant `getMe` probes during Telegram API slow periods without permanently pinning renamed bots. Refs #82525.
3334
- Gateway/sessions: discard stale metadata when recreating dead main session rows, so replacement sessions do not inherit old labels or transcript paths.
3435
- Codex app-server: mark native context compaction completion events as successful, preventing false "Compaction incomplete" notices after successful Codex-managed compaction. Fixes #82470. (#81593) Thanks @Kyzcreig.

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

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import os from "node:os";
33
import path from "node:path";
44
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
import type { OpenClawConfig } from "../../config/types.openclaw.js";
6+
import { formatErrorMessage } from "../../infra/errors.js";
67
import { captureEnv } from "../../test-utils/env.js";
78
import { __testing as externalAuthTesting } from "./external-auth.js";
89
import {
@@ -186,6 +187,72 @@ describe("OAuthManagerRefreshError", () => {
186187
expect(error.message).not.toContain("store-refresh");
187188
expect(error.message).not.toContain("store-id-token");
188189
expect(error.message.match(/\[redacted\]/g)?.length).toBe(6);
190+
const surfacedCauseMessage = formatErrorMessage(error.cause);
191+
expect(surfacedCauseMessage).not.toContain("error-access");
192+
expect(surfacedCauseMessage).not.toContain("error-refresh");
193+
expect(surfacedCauseMessage).not.toContain("error-id-token");
194+
expect(surfacedCauseMessage).not.toContain("store-access");
195+
expect(surfacedCauseMessage).not.toContain("store-refresh");
196+
expect(surfacedCauseMessage).not.toContain("store-id-token");
197+
expect(surfacedCauseMessage.match(/\[redacted\]/g)?.length).toBe(6);
198+
});
199+
200+
it("redacts token-shaped credential secrets before generic masking", () => {
201+
const access = "sk-oauthreviewredaction1234567890zzzz";
202+
const refresh = "ya29.oauthreviewredaction1234567890yyyy";
203+
const error = new OAuthManagerRefreshError({
204+
credential: createCredential({ access, refresh }),
205+
profileId: "openai-codex:default",
206+
refreshedStore: { version: 1, profiles: {} },
207+
cause: new Error(`refresh rejected ${access} ${refresh}`, {
208+
cause: new Error(`nested failure ${access}`),
209+
}),
210+
});
211+
212+
const surfacedCauseMessage = formatErrorMessage(error.cause);
213+
for (const message of [error.message, surfacedCauseMessage]) {
214+
expect(message).not.toContain(access);
215+
expect(message).not.toContain(refresh);
216+
expect(message).not.toContain("sk-oau");
217+
expect(message).not.toContain("zzzz");
218+
expect(message).not.toContain("ya29.o");
219+
expect(message).not.toContain("yyyy");
220+
expect(message.match(/\[redacted\]/g)?.length).toBe(3);
221+
}
222+
});
223+
224+
it.each([undefined, Symbol("refresh-failed"), () => "refresh-failed"])(
225+
"formats non-json refresh failure values without throwing",
226+
(cause) => {
227+
const error = new OAuthManagerRefreshError({
228+
credential: createCredential({
229+
access: "sk-nonjsonredaction1234567890zzzz",
230+
}),
231+
profileId: "openai-codex:default",
232+
refreshedStore: { version: 1, profiles: {} },
233+
cause,
234+
});
235+
236+
expect(error.message).toContain("OAuth token refresh failed");
237+
},
238+
);
239+
240+
it("redacts overlapping credential secrets longest first", () => {
241+
const error = new OAuthManagerRefreshError({
242+
credential: createCredential({
243+
access: "abc123",
244+
refresh: "abc123456",
245+
}),
246+
profileId: "openai-codex:default",
247+
refreshedStore: { version: 1, profiles: {} },
248+
cause: new Error("refresh rejected abc123 abc123456"),
249+
});
250+
251+
expect(error.message).toContain("refresh rejected");
252+
expect(error.message).not.toContain("abc123");
253+
expect(error.message).not.toContain("abc123456");
254+
expect(error.message).not.toContain("[redacted]456");
255+
expect(error.message.match(/\[redacted\]/g)?.length).toBe(2);
189256
});
190257
});
191258

@@ -380,4 +447,70 @@ describe("createOAuthManager", () => {
380447
expect(result.credential.access).toBe("rotated-access");
381448
expect(result.credential.refresh).toBe("rotated-refresh");
382449
});
450+
451+
it("redacts the external oauth credential attempted during refresh failures", async () => {
452+
const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "oauth-manager-refresh-redact-"));
453+
tempDirs.push(tempRoot);
454+
process.env.OPENCLAW_STATE_DIR = tempRoot;
455+
const agentDir = path.join(tempRoot, "agents", "sub", "agent");
456+
await fs.mkdir(agentDir, { recursive: true });
457+
const profileId = "minimax-portal:default";
458+
const localCredential = createCredential({
459+
provider: "minimax-portal",
460+
access: "fresh-local-access",
461+
refresh: "fresh-local-refresh",
462+
expires: Date.now() + 60_000,
463+
});
464+
const externalCredential = createCredential({
465+
provider: "minimax-portal",
466+
access: "external-attempt-access",
467+
refresh: "external-attempt-refresh",
468+
idToken: "external-attempt-id-token",
469+
expires: Date.now() - 30_000,
470+
});
471+
saveAuthProfileStore(
472+
{
473+
version: 1,
474+
profiles: {
475+
[profileId]: localCredential,
476+
},
477+
},
478+
agentDir,
479+
{ filterExternalAuthProfiles: false },
480+
);
481+
482+
const manager = createOAuthManager({
483+
buildApiKey: async (_provider, credential) => credential.access,
484+
refreshCredential: vi.fn(async () => {
485+
throw new Error(
486+
"refresh rejected external-attempt-access external-attempt-refresh external-attempt-id-token",
487+
);
488+
}),
489+
readBootstrapCredential: () => externalCredential,
490+
isRefreshTokenReusedError: () => false,
491+
});
492+
493+
try {
494+
await manager.resolveOAuthAccess({
495+
store: ensureAuthProfileStore(agentDir),
496+
profileId,
497+
credential: localCredential,
498+
agentDir,
499+
forceRefresh: true,
500+
});
501+
throw new Error("Expected refresh failure");
502+
} catch (caught) {
503+
if (!(caught instanceof OAuthManagerRefreshError)) {
504+
throw caught;
505+
}
506+
expect(caught.message).toContain("refresh rejected");
507+
expect(caught.message).not.toContain("external-attempt-access");
508+
expect(caught.message).not.toContain("external-attempt-refresh");
509+
expect(caught.message).not.toContain("external-attempt-id-token");
510+
const surfacedCauseMessage = formatErrorMessage(caught.cause);
511+
expect(surfacedCauseMessage).not.toContain("external-attempt-access");
512+
expect(surfacedCauseMessage).not.toContain("external-attempt-refresh");
513+
expect(surfacedCauseMessage).not.toContain("external-attempt-id-token");
514+
}
515+
});
383516
});

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

Lines changed: 65 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { OpenClawConfig } from "../../config/types.openclaw.js";
22
import { formatErrorMessage } from "../../infra/errors.js";
33
import { withFileLock } from "../../infra/file-lock.js";
4+
import { redactSensitiveText } from "../../logging/redact.js";
45
import {
56
AUTH_STORE_LOCK_OPTIONS,
67
OAUTH_REFRESH_CALL_TIMEOUT_MS,
@@ -68,6 +69,7 @@ export class OAuthManagerRefreshError extends Error {
6869

6970
constructor(params: {
7071
credential: OAuthCredential;
72+
attemptedCredentials?: OAuthCredential[];
7173
profileId: string;
7274
refreshedStore: AuthProfileStore;
7375
cause: unknown;
@@ -81,15 +83,14 @@ export class OAuthManagerRefreshError extends Error {
8183
? structuredCause.cause
8284
: params.cause;
8385
const storedCredential = params.refreshedStore.profiles[params.profileId];
84-
const causeMessage = redactOAuthCredentialSecrets(
85-
formatErrorMessage(params.cause),
86-
collectOAuthCredentialSecrets(
87-
params.credential,
88-
storedCredential?.type === "oauth" ? storedCredential : undefined,
89-
),
86+
const secrets = collectOAuthCredentialSecrets(
87+
params.credential,
88+
...(params.attemptedCredentials ?? []),
89+
storedCredential?.type === "oauth" ? storedCredential : undefined,
9090
);
91+
const causeMessage = formatRedactedOAuthRefreshError(params.cause, secrets);
9192
super(`OAuth token refresh failed for ${params.credential.provider}: ${causeMessage}`, {
92-
cause: delegatedCause,
93+
cause: createRedactedOAuthRefreshCause(delegatedCause, secrets),
9394
});
9495
this.name = "OAuthManagerRefreshError";
9596
this.#credential = params.credential;
@@ -172,7 +173,7 @@ function collectOAuthCredentialSecrets(
172173
}
173174
}
174175
}
175-
return Array.from(secrets);
176+
return Array.from(secrets).toSorted((a, b) => b.length - a.length);
176177
}
177178

178179
function redactOAuthCredentialSecrets(message: string, secrets: string[]): string {
@@ -183,6 +184,55 @@ function redactOAuthCredentialSecrets(message: string, secrets: string[]): strin
183184
return redacted;
184185
}
185186

187+
function formatRawErrorMessage(error: unknown): string {
188+
if (error instanceof Error) {
189+
let formatted = error.message || error.name || "Error";
190+
let cause: unknown = error.cause;
191+
const seen = new Set<unknown>([error]);
192+
while (cause && !seen.has(cause)) {
193+
seen.add(cause);
194+
if (cause instanceof Error) {
195+
if (cause.message) {
196+
formatted += ` | ${cause.message}`;
197+
}
198+
cause = cause.cause;
199+
} else if (typeof cause === "string") {
200+
formatted += ` | ${cause}`;
201+
break;
202+
} else {
203+
break;
204+
}
205+
}
206+
return formatted;
207+
}
208+
if (
209+
typeof error === "string" ||
210+
typeof error === "number" ||
211+
typeof error === "boolean" ||
212+
typeof error === "bigint"
213+
) {
214+
return String(error);
215+
}
216+
try {
217+
return JSON.stringify(error) ?? String(error);
218+
} catch {
219+
return Object.prototype.toString.call(error);
220+
}
221+
}
222+
223+
function formatRedactedOAuthRefreshError(error: unknown, secrets: string[]): string {
224+
return redactSensitiveText(redactOAuthCredentialSecrets(formatRawErrorMessage(error), secrets));
225+
}
226+
227+
function createRedactedOAuthRefreshCause(cause: unknown, secrets: string[]): Error {
228+
const redacted = formatRedactedOAuthRefreshError(cause, secrets);
229+
const sanitized = new Error(redacted);
230+
if (cause instanceof Error && cause.name) {
231+
sanitized.name = cause.name;
232+
}
233+
return sanitized;
234+
}
235+
186236
async function loadFreshStoredOAuthCredential(params: {
187237
profileId: string;
188238
agentDir?: string;
@@ -367,6 +417,7 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
367417
agentDir?: string;
368418
cfg?: OpenClawConfig;
369419
forceRefresh?: boolean;
420+
attemptedCredentials?: OAuthCredential[];
370421
}): Promise<ResolvedOAuthAccess | null> {
371422
const ownerAgentDir = resolvePersistedAuthProfileOwnerAgentDir(params);
372423
const authPath = resolveAuthStorePath(ownerAgentDir);
@@ -479,6 +530,7 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
479530
`refreshOAuthCredential(${cred.provider})`,
480531
OAUTH_REFRESH_CALL_TIMEOUT_MS,
481532
async () => {
533+
params.attemptedCredentials?.push(credentialToRefresh);
482534
const refreshed = await adapter.refreshCredential(credentialToRefresh);
483535
return refreshed
484536
? ({
@@ -530,6 +582,7 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
530582
agentDir?: string;
531583
cfg?: OpenClawConfig;
532584
forceRefresh?: boolean;
585+
attemptedCredentials?: OAuthCredential[];
533586
}): Promise<ResolvedOAuthAccess | null> {
534587
const key = refreshQueueKey(params.provider, params.profileId);
535588
const prev = refreshQueues.get(key) ?? Promise.resolve();
@@ -569,6 +622,7 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
569622
credential: adoptedCredential,
570623
readBootstrapCredential: adapter.readBootstrapCredential,
571624
});
625+
const attemptedCredentials: OAuthCredential[] = [];
572626

573627
if (!params.forceRefresh && hasUsableOAuthCredential(effectiveCredential)) {
574628
return {
@@ -587,6 +641,7 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
587641
agentDir: params.agentDir,
588642
cfg: params.cfg,
589643
forceRefresh: params.forceRefresh,
644+
attemptedCredentials,
590645
});
591646
return refreshed;
592647
} catch (error) {
@@ -638,6 +693,7 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
638693
agentDir: params.agentDir,
639694
cfg: params.cfg,
640695
forceRefresh: params.forceRefresh,
696+
attemptedCredentials,
641697
});
642698
if (retried) {
643699
return retried;
@@ -712,6 +768,7 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
712768
}
713769
throw new OAuthManagerRefreshError({
714770
credential: params.credential,
771+
attemptedCredentials: [effectiveCredential, ...attemptedCredentials],
715772
profileId: params.profileId,
716773
refreshedStore,
717774
cause: error,

0 commit comments

Comments
 (0)