Skip to content

Commit 62ecb31

Browse files
authored
fix: doctor loops forever on legacy OAuth profiles with missing sidecars (#123093)
* fix(doctor): converge missing OAuth sidecar migration Persist missing-sidecar OAuth profiles as cold SQLite rows and make startup migration warnings deterministic. * test(doctor): restore OAuth sidecar fixture id
1 parent 7a7f6df commit 62ecb31

4 files changed

Lines changed: 124 additions & 154 deletions

File tree

‎src/commands/doctor-auth-flat-profiles.test.ts‎

Lines changed: 95 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import fs from "node:fs";
33
import path from "node:path";
44
import { DatabaseSync } from "node:sqlite";
55
import { afterEach, describe, expect, it, vi } from "vitest";
6+
import { listAuthProfileStoresRequiringMigration } from "../agents/auth-profiles/legacy-source-diagnostic.js";
7+
import { resolveAuthProfileEligibility } from "../agents/auth-profiles/order.js";
68
import { loadPersistedAuthProfileStore } from "../agents/auth-profiles/persisted.js";
79
import { clearRuntimeAuthProfileStoreSnapshots } from "../agents/auth-profiles/runtime-snapshots.js";
810
import {
@@ -285,8 +287,9 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
285287
type: "oauth",
286288
provider: "openai",
287289
oauthRef: {
290+
source: "openclaw-credentials",
288291
id: "0123456789abcdef0123456789abcdef",
289-
provider: "openai",
292+
provider: "openai-codex",
290293
},
291294
},
292295
},
@@ -305,16 +308,21 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
305308
env: state.env,
306309
});
307310

308-
expect(result.warnings).toEqual([
309-
expect.stringContaining("legacy OAuth sidecar profile"),
310-
expect.stringContaining("no importable auth profiles or state"),
311-
expect.stringContaining("Deferred shared legacy OAuth migration"),
312-
]);
313-
expect(loadPersistedAuthProfileStore(state.agentDir())).toBeNull();
314-
expect(fs.existsSync(authPath)).toBe(true);
315-
expect(fs.existsSync(oauthPath)).toBe(true);
316-
expectNoMigratedArchive(authPath);
317-
expectNoMigratedArchive(oauthPath);
311+
expect(result.warnings).toEqual([expect.stringContaining("legacy OAuth sidecar profile")]);
312+
expect(
313+
loadPersistedAuthProfileStore(state.agentDir())?.profiles["openai:default"],
314+
).toMatchObject({
315+
type: "oauth",
316+
provider: "openai",
317+
oauthRef: {
318+
source: "openclaw-credentials",
319+
provider: "openai-codex",
320+
},
321+
});
322+
expect(fs.existsSync(authPath)).toBe(false);
323+
expect(fs.existsSync(oauthPath)).toBe(false);
324+
expectMigratedArchive(authPath);
325+
expectMigratedArchive(oauthPath);
318326
});
319327

320328
it("preserves state-only profile IDs while migrating shared OAuth", async () => {
@@ -701,7 +709,7 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
701709
expect(fs.existsSync(authPath)).toBe(false);
702710
});
703711

704-
it("leaves unresolved legacy OAuth sidecar refs in JSON", async () => {
712+
it("migrates unresolved legacy OAuth sidecar refs so startup can proceed cold", async () => {
705713
const state = await makeTestState();
706714
const authPath = await writeLegacyAuthProfilesJson(state, {
707715
version: 1,
@@ -711,8 +719,9 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
711719
provider: "openai",
712720
713721
oauthRef: {
722+
source: "openclaw-credentials",
714723
id: "0123456789abcdef0123456789abcdef",
715-
provider: "openai",
724+
provider: "openai-codex",
716725
},
717726
},
718727
},
@@ -725,14 +734,36 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
725734
});
726735

727736
expect(result.detected).toEqual([authPath]);
728-
expect(result.changes).toEqual([]);
737+
expect(result.changes).toEqual([expect.stringContaining("Migrated auth profile JSON")]);
729738
expect(result.warnings).toEqual([
730-
expect.stringContaining("legacy OAuth sidecar profile"),
731-
expect.stringContaining("no importable auth profiles or state"),
739+
expect.stringContaining("Migrated 1 legacy OAuth sidecar profile"),
732740
]);
733-
expect(loadPersistedAuthProfileStore(state.agentDir())).toBeNull();
734-
expect(fs.existsSync(authPath)).toBe(true);
735-
expectNoMigratedArchive(authPath);
741+
expect(result.warnings[0]).toContain("re-authenticate");
742+
const store = loadPersistedAuthProfileStore(state.agentDir());
743+
expect(store?.profiles["openai:[email protected]"]).toMatchObject({
744+
type: "oauth",
745+
provider: "openai",
746+
747+
oauthRef: {
748+
source: "openclaw-credentials",
749+
provider: "openai-codex",
750+
},
751+
});
752+
expect(
753+
resolveAuthProfileEligibility({
754+
store: store!,
755+
provider: "openai",
756+
profileId: "openai:[email protected]",
757+
}),
758+
).toEqual({ eligible: false, reasonCode: "unresolved_ref" });
759+
expect(fs.existsSync(authPath)).toBe(false);
760+
expectMigratedArchive(authPath);
761+
expect(
762+
listAuthProfileStoresRequiringMigration({
763+
agentDirs: [state.agentDir()],
764+
env: state.env,
765+
}),
766+
).toEqual([]);
736767
});
737768

738769
it("imports valid profiles when one legacy OAuth sidecar ref is unresolved", async () => {
@@ -750,8 +781,9 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
750781
provider: "openai",
751782
752783
oauthRef: {
784+
source: "openclaw-credentials",
753785
id: "0123456789abcdef0123456789abcdef",
754-
provider: "openai",
786+
provider: "openai-codex",
755787
},
756788
},
757789
},
@@ -774,19 +806,28 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
774806
provider: "openai",
775807
key: "sk-imported",
776808
},
809+
"openai:[email protected]": {
810+
type: "oauth",
811+
provider: "openai",
812+
813+
oauthRef: {
814+
source: "openclaw-credentials",
815+
id: "0123456789abcdef0123456789abcdef",
816+
provider: "openai-codex",
817+
},
818+
},
777819
},
778-
order: { openai: ["openai:default"] },
820+
order: { openai: ["openai:default", "openai:[email protected]"] },
779821
lastGood: { openai: "openai:default" },
780822
});
781-
expect(fs.existsSync(authPath)).toBe(true);
782-
expectNoMigratedArchive(authPath);
783-
const remaining = JSON.parse(fs.readFileSync(authPath, "utf8"));
784-
expect(remaining.profiles).toHaveProperty("openai:default");
785-
expect(remaining.profiles).toHaveProperty("openai:[email protected]");
786-
expect(remaining.order).toEqual({
787-
openai: ["openai:default", "openai:[email protected]"],
788-
});
789-
expect(remaining.lastGood).toEqual({ openai: "openai:default" });
823+
expect(fs.existsSync(authPath)).toBe(false);
824+
expectMigratedArchive(authPath);
825+
expect(
826+
listAuthProfileStoresRequiringMigration({
827+
agentDirs: [state.agentDir()],
828+
env: state.env,
829+
}),
830+
).toEqual([]);
790831
});
791832

792833
it("keeps existing SQLite credentials when importing stale JSON", async () => {
@@ -2031,7 +2072,7 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
20312072
});
20322073
});
20332074

2034-
it("does not rebind unresolved sidecar accounts when another Codex account migrates", async () => {
2075+
it("canonicalizes unresolved sidecar accounts while keeping them cold", async () => {
20352076
const state = await makeTestState();
20362077
const storePath = path.join(state.sessionsDir(), "sessions.json");
20372078
const readySessionKey = "agent:main:main";
@@ -2089,7 +2130,7 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
20892130
authProfileIdMap: profileIdMap,
20902131
});
20912132

2092-
expect(result.repairedSessions).toBe(1);
2133+
expect(result.repairedSessions).toBe(2);
20932134
expect(
20942135
loadSessionEntry({ storePath, sessionKey: readySessionKey, env: state.env }),
20952136
).toMatchObject({
@@ -2098,9 +2139,17 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
20982139
expect(
20992140
loadSessionEntry({ storePath, sessionKey: pendingSessionKey, env: state.env }),
21002141
).toMatchObject({
2101-
authProfileOverride: "openai-codex:pending",
2142+
authProfileOverride: "openai:pending",
21022143
authProfileOverrideSource: "user",
21032144
});
2145+
const coldStore = loadPersistedAuthProfileStore(state.agentDir());
2146+
expect(
2147+
resolveAuthProfileEligibility({
2148+
store: coldStore!,
2149+
provider: "openai",
2150+
profileId: "openai:pending",
2151+
}),
2152+
).toEqual({ eligible: false, reasonCode: "missing_credential" });
21042153
});
21052154

21062155
it("repairs an already-migrated selected account from its verified auth archive", async () => {
@@ -2265,6 +2314,7 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
22652314
provider: "openai-codex",
22662315
accountId: "failed-different-account",
22672316
oauthRef: {
2317+
source: "openclaw-credentials",
22682318
id: "0123456789abcdef0123456789abcdef",
22692319
provider: "openai-codex",
22702320
},
@@ -2326,8 +2376,8 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
23262376
shouldRepair: true,
23272377
authProfileIdMap: profileIdMap,
23282378
});
2329-
expect(repair.repairedSessions).toBe(3);
2330-
for (const agentId of ["main", "inherited", "dedup"]) {
2379+
expect(repair.repairedSessions).toBe(4);
2380+
for (const agentId of ["main", "failed", "inherited", "dedup"]) {
23312381
expect(
23322382
loadSessionEntry({
23332383
storePath: path.join(state.sessionsDir(agentId), "sessions.json"),
@@ -2339,15 +2389,16 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
23392389
authProfileOverrideSource: "user",
23402390
});
23412391
}
2342-
expect(
2343-
loadSessionEntry({
2344-
storePath: path.join(state.sessionsDir("failed"), "sessions.json"),
2345-
sessionKey: "agent:failed:main",
2346-
env: state.env,
2347-
}),
2348-
).toMatchObject({
2349-
authProfileOverride: "openai-codex:shared",
2350-
authProfileOverrideSource: "user",
2392+
expect(loadPersistedAuthProfileStore(state.agentDir("failed"))?.profiles).toMatchObject({
2393+
"openai:shared": {
2394+
type: "oauth",
2395+
provider: "openai",
2396+
accountId: "failed-different-account",
2397+
oauthRef: {
2398+
source: "openclaw-credentials",
2399+
provider: "openai-codex",
2400+
},
2401+
},
23512402
});
23522403
});
23532404

‎src/commands/doctor-auth-flat-profiles.ts‎

Lines changed: 11 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -618,80 +618,6 @@ function formatMissingAuthProfileSqliteVerification(params: {
618618
return parts.length > 0 ? parts.join("; ") : null;
619619
}
620620

621-
function filterRawAuthProfileState(
622-
raw: Record<string, unknown>,
623-
shouldKeepProfileId: (profileId: string) => boolean,
624-
): void {
625-
if (isRecord(raw.order)) {
626-
for (const [provider, profileIds] of Object.entries(raw.order)) {
627-
if (!Array.isArray(profileIds)) {
628-
continue;
629-
}
630-
const kept = profileIds.filter(
631-
(profileId): profileId is string =>
632-
typeof profileId === "string" && shouldKeepProfileId(profileId),
633-
);
634-
if (kept.length > 0) {
635-
raw.order[provider] = kept;
636-
} else {
637-
delete raw.order[provider];
638-
}
639-
}
640-
if (Object.keys(raw.order).length === 0) {
641-
delete raw.order;
642-
}
643-
}
644-
if (isRecord(raw.lastGood)) {
645-
for (const [provider, profileId] of Object.entries(raw.lastGood)) {
646-
if (typeof profileId !== "string" || !shouldKeepProfileId(profileId)) {
647-
delete raw.lastGood[provider];
648-
}
649-
}
650-
if (Object.keys(raw.lastGood).length === 0) {
651-
delete raw.lastGood;
652-
}
653-
}
654-
if (isRecord(raw.usageStats)) {
655-
for (const profileId of Object.keys(raw.usageStats)) {
656-
if (!shouldKeepProfileId(profileId)) {
657-
delete raw.usageStats[profileId];
658-
}
659-
}
660-
if (Object.keys(raw.usageStats).length === 0) {
661-
delete raw.usageStats;
662-
}
663-
}
664-
}
665-
666-
function pruneRawAuthProfileIds(raw: unknown, profileIds: ReadonlySet<string>): void {
667-
if (!isRecord(raw) || !isRecord(raw.profiles)) {
668-
return;
669-
}
670-
for (const profileId of profileIds) {
671-
delete raw.profiles[profileId];
672-
}
673-
filterRawAuthProfileState(raw, (profileId) => !profileIds.has(profileId));
674-
}
675-
676-
function pickRawAuthProfileIds(
677-
raw: unknown,
678-
profileIds: ReadonlySet<string>,
679-
): Record<string, unknown> | null {
680-
if (!isRecord(raw) || !isRecord(raw.profiles)) {
681-
return null;
682-
}
683-
const profiles = Object.fromEntries(
684-
Object.entries(raw.profiles).filter(([profileId]) => profileIds.has(profileId)),
685-
);
686-
if (Object.keys(profiles).length === 0) {
687-
return null;
688-
}
689-
const next = structuredClone(raw);
690-
next.profiles = profiles;
691-
filterRawAuthProfileState(next, (profileId) => profileIds.has(profileId));
692-
return next;
693-
}
694-
695621
function collectUnresolvedLegacyOAuthSidecarProfileIds(raw: unknown): string[] {
696622
if (!isRecord(raw) || !isRecord(raw.profiles)) {
697623
return [];
@@ -971,7 +897,7 @@ function migrateLockedLegacyOAuthFile(params: {
971897
* Imports legacy auth profile JSON and state files into the per-agent SQLite store.
972898
*
973899
* JSON files are verified and atomically renamed to timestamped archives only after import.
974-
* OAuth profiles that still depend on unresolved sidecar secrets remain as a migration input.
900+
* OAuth profiles that still depend on missing sidecar secrets migrate as unavailable ref-only rows.
975901
*/
976902
export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
977903
cfg: OpenClawConfig;
@@ -1099,17 +1025,10 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
10991025
const unresolvedSidecarProfileIds = new Set(
11001026
collectUnresolvedLegacyOAuthSidecarProfileIds(rawStore),
11011027
);
1102-
const unresolvedSidecarRawStore =
1028+
const unresolvedSidecarWarning =
11031029
unresolvedSidecarProfileIds.size > 0
1104-
? pickRawAuthProfileIds(rawStore, unresolvedSidecarProfileIds)
1105-
: null;
1106-
if (unresolvedSidecarProfileIds.size > 0) {
1107-
// Sidecar-backed OAuth entries cannot move into SQLite until their secret material exists.
1108-
pruneRawAuthProfileIds(rawStore, unresolvedSidecarProfileIds);
1109-
result.warnings.push(
1110-
`Left ${unresolvedSidecarProfileIds.size} legacy OAuth sidecar profile${unresolvedSidecarProfileIds.size === 1 ? "" : "s"} in ${shortenHomePath(candidate.authPath)}; rerun ${formatCliCommand("openclaw doctor --fix")} after sidecar migration or re-authenticate those profiles.`,
1111-
);
1112-
}
1030+
? `Migrated ${unresolvedSidecarProfileIds.size} legacy OAuth sidecar profile${unresolvedSidecarProfileIds.size === 1 ? "" : "s"} from ${shortenHomePath(candidate.authPath)} into SQLite as configured-unavailable without credentials; re-authenticate ${unresolvedSidecarProfileIds.size === 1 ? "this profile" : "these profiles"} to restore access.`
1031+
: undefined;
11131032
const awsSdkMarkerStore =
11141033
isRecord(rawStore) && isRecord(rawStore.profiles)
11151034
? resolveAwsSdkAuthProfileMarkerStore(candidate)
@@ -1154,15 +1073,16 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
11541073
!hasAuthProfileState(state) &&
11551074
!awsSdkMarkerStore
11561075
) {
1157-
if (!unresolvedSidecarRawStore && sourceReceipts.length > 0) {
1076+
if (sourceReceipts.length > 0) {
11581077
const archived = sourceReceipts.map((receipt) => {
11591078
finalizeAuthProfileMigrationSource(receipt, "archived-unparsed", {
11601079
sourceLocked: true,
11611080
});
11621081
return receipt.archivePath;
11631082
});
11641083
result.warnings.push(
1165-
`Archived unparseable auth profile input without import for ${shortenHomePath(candidate.authPath)} (${archived.map(shortenHomePath).join(", ")}).`,
1084+
unresolvedSidecarWarning ??
1085+
`Archived unparseable auth profile input without import for ${shortenHomePath(candidate.authPath)} (${archived.map(shortenHomePath).join(", ")}).`,
11661086
);
11671087
continue;
11681088
}
@@ -1354,11 +1274,8 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
13541274
receipt.expectedStateSha256 = expectedStateSha256;
13551275
}
13561276
}
1357-
const archivalReceipts = unresolvedSidecarRawStore
1358-
? sourceReceipts.filter((receipt) => receipt.sourcePath !== candidate.authPath)
1359-
: sourceReceipts;
13601277
assertAuthProfileMigrationSourcesUnchanged(candidate, sourceReceipts);
1361-
const archives = archivalReceipts.map((receipt) =>
1278+
const archives = sourceReceipts.map((receipt) =>
13621279
archiveVerifiedAuthProfileSource(receipt, true),
13631280
);
13641281
const archiveText =
@@ -1368,6 +1285,9 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
13681285
result.changes.push(
13691286
`Migrated auth profile JSON for ${shortenHomePath(candidate.authPath)} into SQLite (${archiveText}).`,
13701287
);
1288+
if (unresolvedSidecarWarning) {
1289+
result.warnings.push(unresolvedSidecarWarning);
1290+
}
13711291
if (openAIProviderRepair !== null) {
13721292
result.changes.push(
13731293
`Migrated ${openAIProviderRepair} OpenAI Codex auth profile(s) in ${shortenHomePath(candidate.authPath)} to provider "openai".`,

0 commit comments

Comments
 (0)