Skip to content

Commit 7e87d77

Browse files
authored
fix(auth): report the database that actually holds an agent's profiles (#126918)
`openclaw models auth list` printed `Auth state store: <state>/agents/main/agent/openclaw-agent.sqlite` on every install created since a8a9f28, and that file does not exist. Credentials now persist in the shared state database, so an operator debugging auth was sent to the wrong file while the listed profiles resolved correctly from somewhere else. `resolveAuthStorePathForDisplay` and `resolveAuthStatePathForDisplay` named the agent-local file whenever an agent dir was supplied. That matched storage before shared-auth ownership moved and stopped matching afterwards. The same helpers feed `models auth order`, `models list --status`, the auth overview, two auto-reply directive surfaces, and the `path` field of doctor's auth HealthFindings, so structured diagnostics pointed at the wrong file too. Display now mirrors the loader's own selection: an agent with a local auth store shows its own database, otherwise the shared owner. Both helpers move to the `paths.ts` barrel so they can consult `hasLocalAuthProfileStoreSource` without a cycle back through `path-resolve`. Nothing about storage or loading changes. `model-auth-provider` no longer derives the agent dir from the store path -- that would have reported the state directory once the shared owner is selected -- and uses the caller's agent dir instead. Production -4 LOC.
1 parent a042125 commit 7e87d77

10 files changed

Lines changed: 150 additions & 67 deletions

‎extensions/migrate-hermes/secrets.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,7 @@ describe("Hermes migration secret items", () => {
658658
reportDir,
659659
});
660660
const plan = await provider.plan(ctx);
661+
const plannedTarget = authProfileTarget(agentDir, "openai:hermes-import");
661662
writeAuthProfileStore(agentDir, {
662663
version: 1,
663664
profiles: {
@@ -677,7 +678,7 @@ describe("Hermes migration secret items", () => {
677678
kind: "secret",
678679
action: "create",
679680
source: path.join(source, ".env"),
680-
target: authProfileTarget(agentDir, "openai:hermes-import"),
681+
target: plannedTarget,
681682
status: "conflict",
682683
sensitive: true,
683684
reason: HERMES_REASON_AUTH_PROFILE_EXISTS,

‎src/agents/auth-profiles/path-resolve.shared-store.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1+
import { existsSync } from "node:fs";
12
import path from "node:path";
23
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
34
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
45
import { writeConfigMachineState } from "../../state/config-machine-state.js";
56
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
67
import { resolveOpenClawStateSqlitePath } from "../../state/openclaw-state-db.paths.js";
8+
import { withEnv } from "../../test-utils/env.js";
9+
import { resolveAuthStatePathForDisplay, resolveAuthStorePathForDisplay } from "./paths.js";
10+
import { writePersistedAuthProfileStoreRaw } from "./sqlite.js";
711

812
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
913

@@ -38,6 +42,14 @@ describe("shared auth store path resolution", () => {
3842
expect(resolveSharedAuthStorePath(aliasEnv)).toBe(
3943
path.join(legacyDir, "openclaw-agent.sqlite"),
4044
);
45+
46+
withEnv({ OPENCLAW_STATE_DIR: env.OPENCLAW_STATE_DIR, OPENCLAW_AGENT_DIR: undefined }, () => {
47+
writePersistedAuthProfileStoreRaw({ version: 1, profiles: {} }, legacyDir);
48+
const expectedPath = path.join(legacyDir, "openclaw-agent.sqlite");
49+
expect(resolveAuthStorePathForDisplay(legacyDir)).toBe(expectedPath);
50+
expect(resolveAuthStatePathForDisplay(legacyDir)).toBe(expectedPath);
51+
expect(existsSync(expectedPath)).toBe(true);
52+
});
4153
});
4254

4355
it("resolves the relocated store to the canonical shared state database", async () => {
@@ -48,6 +60,29 @@ describe("shared auth store path resolution", () => {
4860

4961
expect(resolveSharedAuthStoreOwnership(env)).toEqual({ location: "state-db" });
5062
expect(resolveSharedAuthStorePath(env)).toBe(resolveOpenClawStateSqlitePath(env));
63+
64+
withEnv({ OPENCLAW_STATE_DIR: env.OPENCLAW_STATE_DIR, OPENCLAW_AGENT_DIR: undefined }, () => {
65+
writePersistedAuthProfileStoreRaw({ version: 1, profiles: {} });
66+
const agentDir = path.join(env.OPENCLAW_STATE_DIR ?? "", "agents", "helper", "agent");
67+
const expectedPath = resolveOpenClawStateSqlitePath(env);
68+
expect(resolveAuthStorePathForDisplay(agentDir)).toBe(expectedPath);
69+
expect(resolveAuthStatePathForDisplay(agentDir)).toBe(expectedPath);
70+
expect(existsSync(expectedPath)).toBe(true);
71+
});
72+
});
73+
74+
it("keeps an agent-local store local under shared-state ownership", async () => {
75+
const env = makeStateEnv();
76+
writeConfigMachineState("auth.sharedStore", { location: "state-db" }, { env });
77+
const agentDir = path.join(env.OPENCLAW_STATE_DIR ?? "", "agents", "helper", "agent");
78+
79+
withEnv({ OPENCLAW_STATE_DIR: env.OPENCLAW_STATE_DIR, OPENCLAW_AGENT_DIR: undefined }, () => {
80+
writePersistedAuthProfileStoreRaw({ version: 1, profiles: {} }, agentDir);
81+
const expectedPath = path.join(agentDir, "openclaw-agent.sqlite");
82+
expect(resolveAuthStorePathForDisplay(agentDir)).toBe(expectedPath);
83+
expect(resolveAuthStatePathForDisplay(agentDir)).toBe(expectedPath);
84+
expect(existsSync(expectedPath)).toBe(true);
85+
});
5186
});
5287

5388
it("caches ownership independently for each canonical state root", async () => {

‎src/agents/auth-profiles/path-resolve.ts‎

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
/**
22
* Auth profile path resolution.
3-
* Centralizes canonical SQLite display paths and cross-agent OAuth refresh lock paths.
3+
* Centralizes canonical shared SQLite and cross-agent OAuth refresh lock paths.
44
*/
55
import path from "node:path";
66
import { isRecord } from "@openclaw/normalization-core/record-coerce";
77
import { resolveStateDir } from "../../config/paths.js";
88
import { readConfigMachineState } from "../../state/config-machine-state.js";
99
import { resolveOpenClawStateSqlitePath } from "../../state/openclaw-state-db.paths.js";
10-
import { resolveUserPath } from "../../utils.js";
1110
import { resolveSharedMainAuthAgentDir } from "./shared-main-dir.js";
1211

1312
export const SHARED_AUTH_STORE_STATE_KEY = "auth.sharedStore";
@@ -84,22 +83,6 @@ export function resolveSharedAuthStorePath(env: NodeJS.ProcessEnv = process.env)
8483
return path.join(resolveSharedMainAuthAgentDir(env), "openclaw-agent.sqlite");
8584
}
8685

87-
/** Resolve the user-facing auth profile database path. */
88-
export function resolveAuthStorePathForDisplay(agentDir?: string): string {
89-
const pathname = agentDir
90-
? path.join(resolveUserPath(agentDir), "openclaw-agent.sqlite")
91-
: resolveSharedAuthStorePath();
92-
return pathname.startsWith("~") ? pathname : resolveUserPath(pathname);
93-
}
94-
95-
/** Resolve the user-facing auth state database path. */
96-
export function resolveAuthStatePathForDisplay(agentDir?: string): string {
97-
const pathname = agentDir
98-
? path.join(resolveUserPath(agentDir), "openclaw-agent.sqlite")
99-
: resolveSharedAuthStorePath();
100-
return pathname.startsWith("~") ? pathname : resolveUserPath(pathname);
101-
}
102-
10386
/**
10487
* Resolve the path of the cross-agent, per-profile OAuth refresh coordination
10588
* lock. The filename digests a JSON tuple of `[provider, profileId]` so it is

‎src/agents/auth-profiles/paths-direct-import.test.ts‎

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,27 @@
11
/**
22
* Direct-import tests for auth profile path helpers.
3-
* Calls path-resolve exports directly so coverage attribution stays honest
4-
* despite the public paths.ts re-export barrel.
3+
* Calls the owning modules directly so coverage attribution stays honest.
54
*/
6-
import fs from "node:fs/promises";
7-
import os from "node:os";
85
import path from "node:path";
96
import { afterEach, beforeEach, describe, expect, it } from "vitest";
7+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
108
import {
119
resolveLegacyAuthProfilesPath as resolveAuthStorePath,
1210
resolveLegacyAuthStatePath as resolveAuthStatePath,
1311
resolveLegacyFlatAuthPath as resolveLegacyAuthStorePath,
1412
} from "../../commands/doctor-auth-legacy-paths.js";
1513
import { withEnv } from "../../test-utils/env.js";
16-
import { resolveAuthStatePathForDisplay, resolveAuthStorePathForDisplay } from "./path-resolve.js";
14+
import { resolveSharedAuthStorePath } from "./path-resolve.js";
15+
import { resolveAuthStatePathForDisplay, resolveAuthStorePathForDisplay } from "./paths.js";
16+
import { writePersistedAuthProfileStoreRaw } from "./sqlite.js";
1717

18-
describe("path-resolve helpers (direct-import coverage attribution)", () => {
19-
let stateDir = "";
18+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
2019

21-
beforeEach(async () => {
22-
stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-path-direct-"));
23-
});
20+
describe("auth profile path helpers (direct-import coverage attribution)", () => {
21+
let stateDir = "";
2422

25-
afterEach(async () => {
26-
await fs.rm(stateDir, { recursive: true, force: true });
23+
beforeEach(() => {
24+
stateDir = tempDirs.make("openclaw-path-direct-");
2725
});
2826

2927
it("resolveAuthStorePath joins agentDir with the auth-profiles filename", () => {
@@ -80,22 +78,23 @@ describe("path-resolve helpers (direct-import coverage attribution)", () => {
8078
});
8179
});
8280

83-
it("resolveAuthStorePathForDisplay returns the resolved path for a non-tilde input", () => {
81+
it("uses one database path for an agent-local auth store and its runtime state", () => {
8482
const agentDir = path.join(stateDir, "agents", "main", "agent");
85-
const resolved = resolveAuthStorePathForDisplay(agentDir);
86-
expect(resolved.startsWith(stateDir)).toBe(true);
87-
expect(path.basename(resolved)).toBe("openclaw-agent.sqlite");
88-
});
89-
90-
it("resolveAuthStorePathForDisplay expands a tilde-rooted agent dir to the sqlite store", () => {
91-
const tildeAgentDir = "~fake-openclaw-no-expand";
92-
const resolved = resolveAuthStorePathForDisplay(tildeAgentDir);
93-
expect(resolved).toBe(path.resolve(tildeAgentDir, "openclaw-agent.sqlite"));
83+
withEnv({ OPENCLAW_STATE_DIR: stateDir }, () => {
84+
writePersistedAuthProfileStoreRaw({ version: 1, profiles: {} }, agentDir);
85+
const expectedPath = path.join(agentDir, "openclaw-agent.sqlite");
86+
expect(resolveAuthStorePathForDisplay(agentDir)).toBe(expectedPath);
87+
expect(resolveAuthStatePathForDisplay(agentDir)).toBe(expectedPath);
88+
});
9489
});
9590

96-
it("resolveAuthStatePathForDisplay returns the sqlite auth state store", () => {
97-
const agentDir = path.join(stateDir, "agents", "main", "agent");
98-
const resolved = resolveAuthStatePathForDisplay(agentDir);
99-
expect(resolved).toBe(path.join(agentDir, "openclaw-agent.sqlite"));
91+
it("falls back to the shared owner for an agent dir that has no local store", () => {
92+
withEnv({ OPENCLAW_STATE_DIR: stateDir }, () => {
93+
// A tilde-rooted dir resolveUserPath cannot expand still must not be reported as the owner:
94+
// without a local store the loader reads the shared database, so display must name that.
95+
const resolved = resolveAuthStorePathForDisplay("~fake-openclaw-no-expand");
96+
expect(resolved).toBe(resolveSharedAuthStorePath());
97+
expect(resolved.startsWith("~")).toBe(false);
98+
});
10099
});
101100
});

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

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,23 @@
22
* Public path barrel for auth-profile stores.
33
* Import through this file for canonical SQLite display and lock paths.
44
*/
5-
export {
6-
resolveAuthStatePathForDisplay,
7-
resolveAuthStorePathForDisplay,
8-
resolveOAuthRefreshLockPath,
9-
} from "./path-resolve.js";
5+
import path from "node:path";
6+
import { resolveUserPath } from "../../utils.js";
7+
import { resolveOAuthRefreshLockPath, resolveSharedAuthStorePath } from "./path-resolve.js";
8+
import { hasLocalAuthProfileStoreSource } from "./source-check.js";
9+
10+
export { resolveOAuthRefreshLockPath };
11+
12+
/** Resolve the user-facing path for the database selected by the auth store loader. */
13+
export function resolveAuthStorePathForDisplay(agentDir?: string): string {
14+
const pathname =
15+
agentDir && hasLocalAuthProfileStoreSource(agentDir)
16+
? path.join(resolveUserPath(agentDir), "openclaw-agent.sqlite")
17+
: resolveSharedAuthStorePath();
18+
return pathname.startsWith("~") ? pathname : resolveUserPath(pathname);
19+
}
20+
21+
/** Retained name for callers that present auth runtime state from the same selected store. */
22+
export function resolveAuthStatePathForDisplay(agentDir?: string): string {
23+
return resolveAuthStorePathForDisplay(agentDir);
24+
}

‎src/agents/model-auth-provider.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
/**
22
* Ordered credential resolution for one provider request.
33
*/
4-
import path from "node:path";
54
import { formatCliCommand } from "../cli/command-format.js";
65
import type { OpenClawConfig } from "../config/types.openclaw.js";
76
import { formatErrorMessage } from "../infra/errors.js";
@@ -12,6 +11,7 @@ import {
1211
} from "../plugins/provider-runtime.js";
1312
import { resolveOwningPluginIdsForProviderRef } from "../plugins/providers.js";
1413
import { SecretSurfaceUnavailableError } from "../secrets/runtime-degraded-state.js";
14+
import { resolveUserPath } from "../utils.js";
1515
import { resolveDefaultAgentDir } from "./agent-scope-config.js";
1616
import {
1717
type AuthProfileStore,
@@ -603,13 +603,13 @@ export async function resolveApiKeyForProviderCore(params: {
603603
}
604604

605605
const authStorePath = resolveAuthStorePathForDisplay(agentDir);
606-
const resolvedAgentDir = path.dirname(authStorePath);
606+
const agentDirContext = agentDir ? ` (agentDir: ${resolveUserPath(agentDir)})` : "";
607607
throw new ProviderAuthError(
608608
"missing-provider-auth",
609609
provider,
610610
[
611611
`No API key found for provider "${provider}".`,
612-
`Auth store: ${authStorePath} (agentDir: ${resolvedAgentDir}).`,
612+
`Auth store: ${authStorePath}${agentDirContext}.`,
613613
`Configure auth for this agent (${formatCliCommand("openclaw agents add <id>")}) or copy only portable static auth profiles from the main agentDir.`,
614614
].join(" "),
615615
);

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

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import path from "node:path";
55
import type { Model } from "openclaw/plugin-sdk/llm";
66
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
77
import type { OpenClawConfig } from "../config/types.openclaw.js";
8+
import { writeConfigMachineState } from "../state/config-machine-state.js";
9+
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
810
import { withEnvAsync } from "../test-utils/env.js";
911
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
1012
import { clearRuntimeAuthProfileStoreSnapshots } from "./auth-profiles/runtime-snapshots.js";
@@ -730,12 +732,20 @@ describe("getApiKeyForModelCore", () => {
730732
OPENAI_API_KEY: undefined,
731733
},
732734
},
733-
async () => {
734-
await expect(resolveApiKeyForProviderCore({ provider: "openai" })).rejects.toMatchObject({
735+
async (state) => {
736+
writeConfigMachineState("auth.sharedStore", { location: "state-db" }, { env: state.env });
737+
const error = await resolveApiKeyForProviderCore({
738+
provider: "openai",
739+
agentDir: state.agentDir(),
740+
}).catch((caught: unknown) => caught);
741+
expect(error).toMatchObject({
735742
code: "missing-provider-auth",
736-
message: expect.stringContaining('No API key found for provider "openai".'),
737743
provider: "openai",
738744
});
745+
expect(error).toBeInstanceOf(Error);
746+
expect((error as Error).message).toContain(
747+
`Auth store: ${resolveOpenClawStateSqlitePath(state.env)} (agentDir: ${state.agentDir()}).`,
748+
);
739749
},
740750
);
741751

‎src/commands/doctor-auth.profile-health.test.ts‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
// Doctor auth profile-health tests cover stale profile detection, repair notes, and store health.
22
import fs from "node:fs";
3-
import os from "node:os";
43
import path from "node:path";
54
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
6+
import { writePersistedAuthProfileStoreRaw } from "../agents/auth-profiles/sqlite.js";
67
import type { AuthProfileFailureReason, AuthProfileStore } from "../agents/auth-profiles/types.js";
78
import type { OpenClawConfig } from "../config/types.openclaw.js";
9+
import { writeConfigMachineState } from "../state/config-machine-state.js";
10+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
11+
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
812
import type { DoctorPrompter } from "./doctor-prompter.js";
913

1014
const authProfileMocks = vi.hoisted(() => ({
@@ -40,12 +44,14 @@ import { note } from "../../packages/terminal-core/src/note.js";
4044
import { collectAuthProfileHealthFindings, noteAuthProfileHealth } from "./doctor-auth.js";
4145

4246
const noteMock = vi.mocked(note);
47+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
4348

4449
describe("noteAuthProfileHealth", () => {
4550
let tempDir: string;
4651

4752
beforeEach(() => {
48-
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-doctor-auth-"));
53+
tempDir = tempDirs.make("openclaw-doctor-auth-");
54+
vi.stubEnv("OPENCLAW_STATE_DIR", tempDir);
4955
authProfileMocks.ensureAuthProfileStore.mockReset();
5056
authProfileMocks.hasAnyAuthProfileStoreSource.mockReset();
5157
authProfileMocks.hasAnyAuthProfileStoreSource.mockReturnValue(false);
@@ -57,13 +63,14 @@ describe("noteAuthProfileHealth", () => {
5763
});
5864

5965
afterEach(() => {
66+
closeOpenClawStateDatabaseForTest();
67+
vi.unstubAllEnvs();
6068
vi.restoreAllMocks();
61-
fs.rmSync(tempDir, { recursive: true, force: true });
6269
});
6370

6471
function writeAuthStore(agentDir: string): void {
6572
fs.mkdirSync(agentDir, { recursive: true });
66-
fs.writeFileSync(path.join(agentDir, "auth-profiles.json"), "{}\n", "utf8");
73+
writePersistedAuthProfileStoreRaw({ version: 1, profiles: {} }, agentDir);
6774
}
6875

6976
function expectedAuthStorePath(agentDir: string): string {
@@ -89,6 +96,7 @@ describe("noteAuthProfileHealth", () => {
8996
const now = 1_700_000_000_000;
9097
vi.spyOn(Date, "now").mockReturnValue(now);
9198
const mainDir = path.join(tempDir, "main-agent");
99+
writeAuthStore(mainDir);
92100
authProfileMocks.hasAnyAuthProfileStoreSource.mockReturnValue(true);
93101
authProfileMocks.ensureAuthProfileStore.mockReturnValue(
94102
expiredStore("openai:default", now - 60_000),
@@ -114,6 +122,30 @@ describe("noteAuthProfileHealth", () => {
114122
]);
115123
});
116124

125+
it("points shared-store findings at the existing shared state database", async () => {
126+
const now = 1_700_000_000_000;
127+
vi.spyOn(Date, "now").mockReturnValue(now);
128+
const mainDir = path.join(tempDir, "main-agent");
129+
writeConfigMachineState("auth.sharedStore", { location: "state-db" });
130+
writePersistedAuthProfileStoreRaw({ version: 1, profiles: {} });
131+
authProfileMocks.hasAnyAuthProfileStoreSource.mockReturnValue(true);
132+
authProfileMocks.ensureAuthProfileStore.mockReturnValue(
133+
expiredStore("openai:default", now - 60_000),
134+
);
135+
136+
const findings = await collectAuthProfileHealthFindings({
137+
cfg: {
138+
agents: {
139+
list: [{ id: "main", default: true, agentDir: mainDir }],
140+
},
141+
} as OpenClawConfig,
142+
});
143+
const sharedPath = resolveOpenClawStateSqlitePath();
144+
145+
expect(findings).toEqual([expect.objectContaining({ path: sharedPath })]);
146+
expect(fs.existsSync(sharedPath)).toBe(true);
147+
});
148+
117149
it("does not warn while Claude CLI owns refresh of an expiring access token", async () => {
118150
const now = 1_700_000_000_000;
119151
vi.spyOn(Date, "now").mockReturnValue(now);
@@ -213,6 +245,7 @@ describe("noteAuthProfileHealth", () => {
213245
const now = 1_700_000_000_000;
214246
vi.spyOn(Date, "now").mockReturnValue(now);
215247
const mainDir = path.join(tempDir, "main-agent");
248+
writeAuthStore(mainDir);
216249
authProfileMocks.hasAnyAuthProfileStoreSource.mockReturnValue(true);
217250
authProfileMocks.resolveProfileUnusableUntilForDisplay.mockReturnValue(now + 5 * 60_000);
218251
authProfileMocks.ensureAuthProfileStore.mockReturnValue({
@@ -427,6 +460,7 @@ describe("noteAuthProfileHealth", () => {
427460

428461
it("maps malformed API-key auth profiles to structured findings", async () => {
429462
const mainDir = path.join(tempDir, "main-agent");
463+
writeAuthStore(mainDir);
430464
authProfileMocks.hasAnyAuthProfileStoreSource.mockReturnValue(true);
431465
authProfileMocks.ensureAuthProfileStore.mockReturnValue({
432466
version: 1,

0 commit comments

Comments
 (0)