Skip to content

Commit d2dad76

Browse files
authored
feat(doctor): relocate shared auth store into state DB (#123349)
* feat(doctor): relocate shared auth store into state DB * fix(doctor): make shared auth relocation crash-safe * fix(doctor): skip disabled shared auth inspection * fix(doctor): break shared auth migration cycle * fix(doctor): remove unused migration type export * fix(test): remove duplicate Codex attempt shard
1 parent f0076b0 commit d2dad76

44 files changed

Lines changed: 2621 additions & 799 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/auth-credential-semantics.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,15 @@ Token credentials (`type: "token"`) support inline `token` and/or `tokenRef`.
4949

5050
## Agent copy portability
5151

52-
Agent auth inheritance is read-through. When an agent has no local profile, it resolves profiles from the default/main agent store at runtime without copying secret material into its own credential store (`agents/<agentId>/agent/openclaw-agent.sqlite`).
52+
Agent auth inheritance is read-through. When an agent has no local profile, it resolves profiles from the shared auth store at runtime without copying secret material into its own credential store (`agents/<agentId>/agent/openclaw-agent.sqlite`). The shared store lives in `state/openclaw.sqlite` after `openclaw doctor --fix` performs the one-time relocation. Until then, doctor reports the legacy `agents/main/agent/openclaw-agent.sqlite` owner and leaves that agent undeletable.
5353

5454
Explicit copy flows, such as `openclaw agents add`, use this portability policy:
5555

5656
- `api_key` and `token` profiles are portable unless `copyToAgents: false`.
5757
- `oauth` profiles are not portable by default because refresh tokens can be single-use or rotation-sensitive.
5858
- Provider-owned OAuth flows may opt in with `copyToAgents: true` only when copying refresh material across agents is known safe; the opt-in only applies when the profile carries inline access/refresh material.
5959

60-
Non-portable profiles remain available through read-through inheritance unless the target agent signs in separately and creates its own local profile.
60+
Non-portable profiles remain available through the shared read-through base unless the target agent signs in separately and creates its own local profile.
6161

6262
## Config-only auth routes
6363

‎docs/cli/agents.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ Options: `--workspace <dir>`, `--model <id>`, `--agent-dir <dir>`, `--bind <chan
4444
- Passing any explicit add flag switches the command into the non-interactive path.
4545
- Non-interactive mode requires both an agent name and `--workspace`.
4646
- `main` is reserved and cannot be used as the new agent id.
47-
- Interactive mode seeds auth by copying only portable static credentials (`api_key` and static `token` profiles) unless a credential opts out with `copyToAgents: false`; OAuth refresh-token profiles are not copied unless a provider opts in with `copyToAgents: true`. Without a copy, OAuth stays available only through read-through inheritance from the real `main` agent store. If the configured default agent is not `main`, sign in separately for OAuth profiles on the new agent.
47+
- Interactive mode seeds auth by copying only portable static credentials (`api_key` and static `token` profiles) unless a credential opts out with `copyToAgents: false`; OAuth refresh-token profiles are not copied unless a provider opts in with `copyToAgents: true`. Without a copy, OAuth stays available through the shared auth base. If the configured default agent has its own local OAuth profile, sign in separately for the new agent.
4848

4949
### `agents bindings`
5050

@@ -66,9 +66,10 @@ Options: `--agent <id>`, `--workspace <dir>`, `--identity-file <path>`, `--from-
6666

6767
Options: `--force`, `--json`.
6868

69-
- `main` cannot be deleted.
69+
- The only configured agent cannot be deleted.
7070
- Without `--force`, interactive confirmation is required (fails in a non-TTY session; re-run with `--force`).
7171
- Workspace, agent state, and session transcript directories move to Trash, not hard-deleted. If Trash is unavailable, agent config deletion still succeeds and reports paths requiring manual cleanup.
72+
- On installations that have not migrated shared auth yet, the legacy owner cannot be deleted. Run `openclaw doctor --fix`; after relocation into shared state SQLite, `main` follows the same deletion rules as any other agent.
7273
- When the Gateway is reachable, deletion routes through the Gateway so config and session-store cleanup share the same writer as runtime traffic. If the Gateway is unreachable, the CLI falls back to the offline local path.
7374
- If another agent's workspace is the same path, inside this workspace, or contains this workspace, the workspace is retained, and `--json` reports `workspaceRetained`, `workspaceRetainedReason`, and `workspaceSharedWith`.
7475

‎docs/cli/doctor.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,8 @@ the container normally.
211211

212212
`openclaw doctor --fix` is the only owner for persistent file-to-SQLite migrations. It validates and claims each recognized source, writes and verifies canonical rows, records a migration receipt, then removes the retired source. Runtime code does not perform lazy imports or fallback reads.
213213

214+
Doctor also reports when shared auth still uses the legacy `agents/main/agent/openclaw-agent.sqlite` owner. `openclaw doctor --fix` copies its auth profile and runtime-state rows into `state/openclaw.sqlite`, verifies the exact payloads, removes the source rows, and records the new ownership only after the transaction succeeds. Auth resolution has no dual-read fallback: before migration the legacy database is complete; after migration the shared state database is complete. Once relocated, deleting `main` no longer risks fleet credentials.
215+
214216
For the retired QMD memory backend, including config rewrites and derived
215217
workspace cleanup, see [Migrating from QMD](/concepts/memory-builtin#migrating-from-qmd).
216218

‎docs/tools/subagents.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -517,10 +517,10 @@ children:
517517
Sub-agent auth is resolved by **agent id**, not by session type:
518518

519519
- The sub-agent session key is `agent:<agentId>:subagent:<uuid>`.
520-
- The auth store is loaded from that agent's `agentDir`.
521-
- The main agent's auth profiles are merged in as a **fallback**; agent profiles override main profiles on conflicts.
520+
- The local auth overlay is loaded from that agent's `agentDir`.
521+
- The shared auth profiles are merged in as a **fallback**; agent profiles override shared profiles on conflicts.
522522

523-
The merge is additive, so main profiles are always available as
523+
The merge is additive, so shared profiles are always available as
524524
fallbacks. Fully isolated auth per agent is not supported yet.
525525

526526
## Announce

‎src/agents/auth-profiles.sqlite-store.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { DatabaseSync } from "node:sqlite";
1111
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1212
import * as kyselySync from "../infra/kysely-sync.js";
1313
import * as nodeSqlite from "../infra/node-sqlite.js";
14+
import { writeConfigMachineState } from "../state/config-machine-state.js";
1415
import {
1516
closeOpenClawAgentDatabasesForTest,
1617
OPENCLAW_AGENT_SCHEMA_VERSION,
@@ -125,6 +126,33 @@ describe("auth profile sqlite store", () => {
125126
});
126127
});
127128

129+
it("persists the relocated shared store through the shared-state adapter", async () => {
130+
await withAgentDirEnv("openclaw-auth-shared-state-", () => {
131+
writeConfigMachineState("auth.sharedStore", { location: "state-db" });
132+
saveAuthProfileStore({
133+
...apiKeyStore("sk-shared"),
134+
order: { openai: ["openai:default"] },
135+
});
136+
137+
expect(ensureAuthProfileStore(undefined, { syncExternalCli: false })).toMatchObject({
138+
profiles: { "openai:default": { key: "sk-shared" } },
139+
order: { openai: ["openai:default"] },
140+
});
141+
const database = new DatabaseSync(resolveOpenClawStateSqlitePath());
142+
expect(
143+
database
144+
.prepare("SELECT store_key FROM auth_profile_stores WHERE store_key = 'shared'")
145+
.get(),
146+
).toEqual({ store_key: "shared" });
147+
expect(
148+
database
149+
.prepare("SELECT store_key FROM auth_profile_state WHERE store_key = 'shared'")
150+
.get(),
151+
).toEqual({ store_key: "shared" });
152+
database.close();
153+
});
154+
});
155+
128156
it("does not read legacy auth-profiles.json at runtime", async () => {
129157
await withAgentDirEnv("openclaw-auth-no-json-fallback-", (agentDir) => {
130158
fs.writeFileSync(

‎src/agents/auth-profiles/legacy-source-diagnostic.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { resolveOAuthDir } from "../../config/paths.js";
44
import { createSubsystemLogger } from "../../logging/subsystem.js";
55
import { shortenHomePath } from "../../utils.js";
66
import { resolveSharedAuthStorePath } from "./path-resolve.js";
7+
import { resolveSharedMainAuthAgentDir } from "./shared-main-dir.js";
78
import { resolveAuthProfileDatabasePath } from "./sqlite.js";
89

910
const AUTH_PROFILE_MIGRATION_REQUIRED_CODE = "AUTH_PROFILE_MIGRATION_REQUIRED" as const;
@@ -29,22 +30,27 @@ function resolveAuthProfileOwnerPath(agentDir?: string): string {
2930
return agentDir ? resolveAuthProfileDatabasePath(agentDir) : resolveSharedAuthStorePath();
3031
}
3132

32-
function resolveAgentDir(agentDir?: string): string {
33-
return path.dirname(resolveAuthProfileOwnerPath(agentDir));
33+
function resolveLegacySourceAgentDir(
34+
agentDir: string | undefined,
35+
env: NodeJS.ProcessEnv = process.env,
36+
): string {
37+
return agentDir
38+
? path.dirname(resolveAuthProfileOwnerPath(agentDir))
39+
: resolveSharedMainAuthAgentDir(env);
3440
}
3541

3642
/** Detects retired auth files by name only; runtime code must never read their contents. */
3743
export function listLegacyAuthProfileSources(params: {
3844
agentDir?: string;
3945
env?: NodeJS.ProcessEnv;
4046
}): LegacyAuthProfileSource[] {
41-
const agentDir = resolveAgentDir(params.agentDir);
47+
const agentDir = resolveLegacySourceAgentDir(params.agentDir, params.env);
4248
const candidates: LegacyAuthProfileSource[] = [
4349
{ kind: "auth-profiles", path: path.join(agentDir, "auth-profiles.json") },
4450
{ kind: "auth-state", path: path.join(agentDir, "auth-state.json") },
4551
{ kind: "legacy-auth", path: path.join(agentDir, "auth.json") },
4652
];
47-
const sharedMainDir = path.dirname(resolveSharedAuthStorePath(params.env));
53+
const sharedMainDir = resolveSharedMainAuthAgentDir(params.env);
4854
if (path.resolve(agentDir) === path.resolve(sharedMainDir)) {
4955
candidates.push({ kind: "legacy-oauth", path: resolveLegacyOAuthPath(params.env) });
5056
}
@@ -98,7 +104,7 @@ function listStartupLegacyAuthProfileSources(params: {
98104
sources: LegacyAuthProfileSource[];
99105
credentialSources: LegacyAuthProfileSource[];
100106
}> {
101-
const sharedMainDir = path.dirname(resolveSharedAuthStorePath(params.env));
107+
const sharedMainDir = resolveSharedMainAuthAgentDir(params.env);
102108
return [...new Set([...params.agentDirs, sharedMainDir])].map((agentDir) => {
103109
const sources = listLegacyAuthProfileSources({ agentDir, env: params.env });
104110
return { agentDir, sources, credentialSources: sources.filter(isCredentialSource) };

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

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
44
import { writeConfigMachineState } from "../../state/config-machine-state.js";
55
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
6+
import { resolveOpenClawStateSqlitePath } from "../../state/openclaw-state-db.paths.js";
67

78
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
89

@@ -22,12 +23,10 @@ describe("shared auth store path resolution", () => {
2223

2324
it("keeps the absent ownership record pinned to the shipped legacy-main path", async () => {
2425
const env = makeStateEnv();
25-
const { resolveSharedAuthStoreDir, resolveSharedAuthStorePath } =
26-
await import("./path-resolve.js");
26+
const { resolveSharedAuthStorePath } = await import("./path-resolve.js");
2727
const { resolveSharedMainAuthAgentDir } = await import("./shared-main-dir.js");
2828
const legacyDir = resolveSharedMainAuthAgentDir(env);
2929

30-
expect(resolveSharedAuthStoreDir(env)).toBe(legacyDir);
3130
expect(resolveSharedAuthStorePath(env)).toBe(path.join(legacyDir, "openclaw-agent.sqlite"));
3231

3332
writeConfigMachineState("auth.sharedStore", { location: "state-db" }, { env });
@@ -36,37 +35,19 @@ describe("shared auth store path resolution", () => {
3635
OPENCLAW_STATE_DIR: path.join(env.OPENCLAW_STATE_DIR ?? "", "."),
3736
};
3837

39-
expect(resolveSharedAuthStoreDir(aliasEnv)).toBe(legacyDir);
4038
expect(resolveSharedAuthStorePath(aliasEnv)).toBe(
4139
path.join(legacyDir, "openclaw-agent.sqlite"),
4240
);
4341
});
4442

45-
it("fails closed when the ownership record says state-db", async () => {
43+
it("resolves the relocated store to the canonical shared state database", async () => {
4644
const env = makeStateEnv();
4745
writeConfigMachineState("auth.sharedStore", { location: "state-db" }, { env });
48-
const {
49-
resolveSharedAuthStoreDir,
50-
resolveSharedAuthStoreOwnership,
51-
resolveSharedAuthStorePath,
52-
} = await import("./path-resolve.js");
46+
const { resolveSharedAuthStoreOwnership, resolveSharedAuthStorePath } =
47+
await import("./path-resolve.js");
5348

5449
expect(resolveSharedAuthStoreOwnership(env)).toEqual({ location: "state-db" });
55-
for (const resolvePath of [resolveSharedAuthStoreDir, resolveSharedAuthStorePath]) {
56-
try {
57-
resolvePath(env);
58-
throw new Error("expected relocated shared auth resolution to fail");
59-
} catch (error) {
60-
expect(error).toBeInstanceOf(Error);
61-
expect(error).toMatchObject({
62-
name: "SharedAuthStoreRelocatedUnsupportedError",
63-
code: "SHARED_AUTH_STORE_RELOCATED_UNSUPPORTED",
64-
action: "openclaw doctor --fix",
65-
location: "state-db",
66-
message: expect.stringContaining("this build cannot serve it"),
67-
});
68-
}
69-
}
50+
expect(resolveSharedAuthStorePath(env)).toBe(resolveOpenClawStateSqlitePath(env));
7051
});
7152

7253
it("caches ownership independently for each canonical state root", async () => {
@@ -81,7 +62,13 @@ describe("shared auth store path resolution", () => {
8162
{ env: secondEnv },
8263
);
8364

84-
expect(() => resolveSharedAuthStoreOwnership(secondEnv)).toThrow("auth.sharedStore is invalid");
65+
expect(() => resolveSharedAuthStoreOwnership(secondEnv)).toThrow(
66+
expect.objectContaining({
67+
name: "InvalidSharedAuthStoreOwnershipError",
68+
code: "INVALID_SHARED_AUTH_STORE_OWNERSHIP",
69+
action: "openclaw doctor --fix",
70+
}),
71+
);
8572
expect(resolveSharedAuthStoreOwnership(firstEnv)).toEqual({ location: "legacy-main" });
8673
});
8774
});

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

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { resolveOpenClawStateSqlitePath } from "../../state/openclaw-state-db.pa
1010
import { resolveUserPath } from "../../utils.js";
1111
import { resolveSharedMainAuthAgentDir } from "./shared-main-dir.js";
1212

13-
const SHARED_AUTH_STORE_STATE_KEY = "auth.sharedStore";
13+
export const SHARED_AUTH_STORE_STATE_KEY = "auth.sharedStore";
1414
const SHARED_AUTH_STORE_OWNERSHIP_CACHE_LIMIT = 256;
1515

1616
export type SharedAuthStoreOwnership = { location: "legacy-main" } | { location: "state-db" };
@@ -19,16 +19,16 @@ export type SharedAuthStoreOwnership = { location: "legacy-main" } | { location:
1919
// Pin each root once so later row changes require an owner-controlled restart.
2020
const sharedAuthStoreOwnershipByDatabasePath = new Map<string, SharedAuthStoreOwnership>();
2121

22-
class SharedAuthStoreRelocatedUnsupportedError extends Error {
23-
readonly code = "SHARED_AUTH_STORE_RELOCATED_UNSUPPORTED" as const;
22+
class InvalidSharedAuthStoreOwnershipError extends Error {
23+
readonly code = "INVALID_SHARED_AUTH_STORE_OWNERSHIP" as const;
2424
readonly action = "openclaw doctor --fix" as const;
25-
readonly location = "state-db" as const;
25+
readonly stateKey = SHARED_AUTH_STORE_STATE_KEY;
2626

27-
constructor() {
27+
constructor(value: unknown) {
2828
super(
29-
"Shared auth store is recorded as relocated, but this build cannot serve it; run openclaw doctor --fix.",
29+
`Config machine state ${SHARED_AUTH_STORE_STATE_KEY} has an invalid shared auth store location (${JSON.stringify(value)}); run openclaw doctor --fix.`,
3030
);
31-
this.name = "SharedAuthStoreRelocatedUnsupportedError";
31+
this.name = "InvalidSharedAuthStoreOwnershipError";
3232
}
3333
}
3434

@@ -43,9 +43,7 @@ function parseSharedAuthStoreOwnership(value: unknown): SharedAuthStoreOwnership
4343
) {
4444
return { location: value.location };
4545
}
46-
throw new Error(
47-
`Config machine state ${SHARED_AUTH_STORE_STATE_KEY} is invalid; run openclaw doctor --fix.`,
48-
);
46+
throw new InvalidSharedAuthStoreOwnershipError(value);
4947
}
5048

5149
/** Resolve the process-stable owner of the shared auth store. */
@@ -69,15 +67,19 @@ export function resolveSharedAuthStoreOwnership(
6967
return ownership;
7068
}
7169

72-
/** Resolve the legacy agent directory containing the shared auth store. */
73-
export function resolveSharedAuthStoreDir(env: NodeJS.ProcessEnv = process.env): string {
74-
return path.dirname(resolveSharedAuthStorePath(env));
70+
/** Update the process-stable cache after this process commits the ownership row. */
71+
export function noteCommittedSharedAuthStoreOwnership(
72+
ownership: SharedAuthStoreOwnership,
73+
env: NodeJS.ProcessEnv = process.env,
74+
): void {
75+
const databasePath = path.resolve(resolveOpenClawStateSqlitePath(env));
76+
sharedAuthStoreOwnershipByDatabasePath.set(databasePath, ownership);
7577
}
7678

77-
/** Resolve the shared auth database path, failing closed for unserved relocation. */
79+
/** Resolve the canonical shared auth database path. */
7880
export function resolveSharedAuthStorePath(env: NodeJS.ProcessEnv = process.env): string {
7981
if (resolveSharedAuthStoreOwnership(env).location === "state-db") {
80-
throw new SharedAuthStoreRelocatedUnsupportedError();
82+
return resolveOpenClawStateSqlitePath(env);
8183
}
8284
return path.join(resolveSharedMainAuthAgentDir(env), "openclaw-agent.sqlite");
8385
}

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

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import { isRecord } from "@openclaw/normalization-core/record-coerce";
88
import { readNonBlankString } from "@openclaw/normalization-core/string-coerce";
99
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
1010
import { coerceSecretRef } from "../../config/types.secrets.js";
11-
import type { OpenClawAgentDatabase } from "../../state/openclaw-agent-db.js";
1211
import { asBoolean } from "../../utils/boolean.js";
1312
import { AUTH_STORE_VERSION, authProfilesLog } from "./constants.js";
1413
import { hasUsableOAuthCredential } from "./credential-state.js";
@@ -23,7 +22,12 @@ import {
2322
getRuntimeExternalCliProfileIds,
2423
setRuntimeExternalCliProfileIds,
2524
} from "./runtime-external-profile-references.js";
26-
import { readPersistedAuthProfileStoreRaw } from "./sqlite.js";
25+
import {
26+
readPersistedAuthProfileStoreRaw,
27+
readPersistedSharedAuthProfileStateRaw,
28+
readPersistedSharedAuthProfileStoreRaw,
29+
type AuthProfileDatabase,
30+
} from "./sqlite.js";
2731
import {
2832
coerceAuthProfileState,
2933
loadPersistedAuthProfileState,
@@ -42,7 +46,7 @@ type LegacyAuthStore = Record<string, AuthProfileCredential>;
4246

4347
type LoadPersistedAuthProfileStoreOptions = {
4448
allowKeychainPrompt?: boolean;
45-
database?: OpenClawAgentDatabase;
49+
database?: AuthProfileDatabase;
4650
};
4751

4852
type CredentialRejectReason = "non_object" | "invalid_type" | "missing_provider";
@@ -806,4 +810,22 @@ export function loadPersistedAuthProfileStore(
806810
return merged;
807811
}
808812

813+
/** Load the shared auth store from an explicit state root. */
814+
export function loadPersistedSharedAuthProfileStore(
815+
env: NodeJS.ProcessEnv,
816+
): AuthProfileStore | null {
817+
const raw = readPersistedSharedAuthProfileStoreRaw(env);
818+
const store = coercePersistedAuthProfileStore(raw);
819+
if (!store) {
820+
return null;
821+
}
822+
return {
823+
...store,
824+
...mergeAuthProfileState(
825+
coerceAuthProfileState(raw),
826+
coerceAuthProfileState(readPersistedSharedAuthProfileStateRaw(env)),
827+
),
828+
};
829+
}
830+
809831
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

0 commit comments

Comments
 (0)