Skip to content

Commit a8a9f28

Browse files
authored
fix(auth): create a fresh install with canonical shared-auth ownership (#126783)
* fix(auth): create a fresh install with canonical shared-auth ownership A brand-new install was born in the retired shape. `parseSharedAuthStoreOwnership(undefined)` returns `legacy-main`, which is the correct compat answer for an existing install whose profiles really do live in the main agent database -- but a new install has no ownership row and no legacy data either, so onboarding wrote its first credential into `agents/main/agent/openclaw-agent.sqlite` and the operator's very first `openclaw doctor` told them to run a migration for state OpenClaw had created seconds earlier. The main agent also stayed undeletable until they did. Record `auth.sharedStore = {"location":"state-db"}` when the shared store is first written and the legacy source provably holds nothing: no `auth_profile_store` row, no `auth_profile_state` row, and no unfinished cleanup ledger entry. Any legacy row, or any inspection error, leaves ownership alone so doctor keeps owning the relocation. The check is memoized per ownership generation with a WeakSet keyed on the process-stable ownership object, so a legacy root is inspected once per process and doctor's committed flip naturally invalidates it. The legacy row inspection moves out of `state-migrations.shared-auth-store.ts` into the auth-profiles owner so doctor and runtime share one contract instead of runtime importing migration code. Explicit main-agent credential writes now follow the shared target, which is a no-op on legacy roots where both routes already resolve to the same file. No SQLite schema change; the ownership row is data. Existing installs take exactly the path they take today. * fix(auth): preserve JSON-era shared credentials * docs(auth): explain why doctor names the main agent dir during a shared JSON import * test(auth): assert shared-owner runtime reads * test(doctor): read migrated catalog credentials through the shared owner A fresh root records state-db shared ownership, so the model-catalog credential migration persists into the shared store rather than the agent file. The assertion read the agent file directly and saw an empty store while all three credentials were present and correct in state/openclaw.sqlite. Read through the owner for that state root instead of pinning storage layout; the credential contents are still asserted exactly.
1 parent 1d3d65e commit a8a9f28

16 files changed

Lines changed: 743 additions & 266 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3347,7 +3347,7 @@ src/infra/state-migrations.meeting-transcripts.ts 2
33473347
src/infra/state-migrations.node-host.ts 2
33483348
src/infra/state-migrations.runtime-state.ts 7
33493349
src/infra/state-migrations.session-store.ts 12
3350-
src/infra/state-migrations.shared-auth-store.ts 2
3350+
src/infra/state-migrations.shared-auth-store.ts 1
33513351
src/infra/state-migrations.source-snapshot.ts 1
33523352
src/infra/state-migrations.state-dir.ts 1
33533353
src/infra/state-migrations.storage.ts 21

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

Lines changed: 248 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ 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 {
15+
detectSharedAuthStoreMigration,
16+
migrateSharedAuthStore,
17+
} from "../infra/state-migrations.shared-auth-store.js";
1418
import { writeConfigMachineState } from "../state/config-machine-state.js";
1519
import {
1620
closeOpenClawAgentDatabasesForTest,
@@ -30,13 +34,19 @@ import {
3034
inspectPersistedAuthProfileStateRaw,
3135
inspectPersistedAuthProfileStoreRaw,
3236
resolveAuthProfileDatabasePath,
37+
writePersistedAuthProfileStateRaw,
38+
writePersistedAuthProfileStoreRaw,
3339
} from "./auth-profiles/sqlite.js";
3440
import {
3541
ensureAuthProfileStore,
3642
getRuntimeAuthProfileStoreSnapshotRevision,
3743
saveAuthProfileStore,
3844
} from "./auth-profiles/store.js";
39-
import type { AuthProfileStore, OAuthCredential } from "./auth-profiles/types.js";
45+
import type { ApiKeyCredential, AuthProfileStore, OAuthCredential } from "./auth-profiles/types.js";
46+
import {
47+
persistAuthProfileBatch,
48+
upsertAuthProfileWithLockOrThrow,
49+
} from "./auth-profiles/upsert-with-lock.js";
4050

4151
type RuntimeOnlyOverlay = {
4252
profileId: string;
@@ -59,20 +69,23 @@ vi.mock("../plugins/provider-runtime.js", () => ({
5969
resolveExternalAuthProfilesWithPlugins: () => [],
6070
}));
6171

72+
function apiKeyCredential(key: string): ApiKeyCredential {
73+
return { type: "api_key", provider: "openai", key };
74+
}
75+
6276
function apiKeyStore(key: string): AuthProfileStore {
6377
return {
6478
version: 1,
6579
profiles: {
66-
"openai:default": {
67-
type: "api_key",
68-
provider: "openai",
69-
key,
70-
},
80+
"openai:default": apiKeyCredential(key),
7181
},
7282
};
7383
}
7484

75-
async function withAgentDirEnv(prefix: string, run: (agentDir: string) => void | Promise<void>) {
85+
async function withAgentDirEnv(
86+
prefix: string,
87+
run: (agentDir: string, stateDir: string) => void | Promise<void>,
88+
) {
7689
const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
7790
const agentDir = path.join(root, "agents", "main", "agent");
7891
try {
@@ -82,7 +95,7 @@ async function withAgentDirEnv(prefix: string, run: (agentDir: string) => void |
8295
OPENCLAW_STATE_DIR: root,
8396
OPENCLAW_AGENT_DIR: agentDir,
8497
},
85-
async () => await run(agentDir),
98+
async () => await run(agentDir, root),
8699
);
87100
} finally {
88101
clearRuntimeAuthProfileStoreSnapshots();
@@ -127,11 +140,22 @@ describe("auth profile sqlite store", () => {
127140
});
128141
});
129142

130-
it("persists the relocated shared store through the shared-state adapter", async () => {
131-
await withAgentDirEnv("openclaw-auth-shared-state-", () => {
132-
writeConfigMachineState("auth.sharedStore", { location: "state-db" });
133-
saveAuthProfileStore({
134-
...apiKeyStore("sk-shared"),
143+
it.each([
144+
{ label: "pre-recorded ownership", recordOwnership: true },
145+
{ label: "fresh ownership", recordOwnership: false },
146+
])("persists the shared store through the shared-state adapter with $label", async (testCase) => {
147+
await withAgentDirEnv("openclaw-auth-shared-state-", async (agentDir) => {
148+
if (testCase.recordOwnership) {
149+
writeConfigMachineState("auth.sharedStore", { location: "state-db" });
150+
}
151+
await persistAuthProfileBatch({
152+
agentDir,
153+
profiles: [
154+
{
155+
profileId: "openai:default",
156+
credential: apiKeyCredential("sk-shared"),
157+
},
158+
],
135159
order: { openai: ["openai:default"] },
136160
});
137161

@@ -150,7 +174,218 @@ describe("auth profile sqlite store", () => {
150174
.prepare("SELECT store_key FROM auth_profile_state WHERE store_key = 'shared'")
151175
.get(),
152176
).toEqual({ store_key: "shared" });
177+
expect(
178+
database
179+
.prepare(
180+
"SELECT value_json FROM config_machine_state WHERE state_key = 'auth.sharedStore'",
181+
)
182+
.get(),
183+
).toEqual({ value_json: JSON.stringify({ location: "state-db" }) });
153184
database.close();
185+
expect(fs.existsSync(resolveAuthProfileDatabasePath(agentDir))).toBe(false);
186+
});
187+
});
188+
189+
it.each([
190+
{
191+
label: "credential row",
192+
seed: (agentDir: string) =>
193+
writePersistedAuthProfileStoreRaw(apiKeyStore("sk-legacy"), agentDir),
194+
},
195+
{
196+
label: "runtime-state row",
197+
seed: (agentDir: string) =>
198+
writePersistedAuthProfileStateRaw(
199+
{ version: 1, order: { openai: ["openai:legacy"] } },
200+
agentDir,
201+
),
202+
},
203+
])("keeps legacy ownership when the main agent has a $label", async (testCase) => {
204+
await withAgentDirEnv("openclaw-auth-shared-legacy-", async (agentDir) => {
205+
testCase.seed(agentDir);
206+
207+
await upsertAuthProfileWithLockOrThrow({
208+
agentDir,
209+
profileId: "openai:default",
210+
credential: apiKeyCredential("sk-updated"),
211+
});
212+
213+
const sharedDatabase = new DatabaseSync(resolveOpenClawStateSqlitePath());
214+
expect(
215+
sharedDatabase
216+
.prepare(
217+
"SELECT value_json FROM config_machine_state WHERE state_key = 'auth.sharedStore'",
218+
)
219+
.get(),
220+
).toBeUndefined();
221+
expect(
222+
sharedDatabase
223+
.prepare("SELECT store_key FROM auth_profile_stores WHERE store_key = 'shared'")
224+
.get(),
225+
).toBeUndefined();
226+
sharedDatabase.close();
227+
expect(inspectPersistedAuthProfileStoreRaw(agentDir).status).toBe("readable");
228+
});
229+
});
230+
231+
it("memoizes legacy inspection and follows Doctor's ownership flip", async () => {
232+
await withAgentDirEnv("openclaw-auth-shared-memo-", async (agentDir, stateDir) => {
233+
const sourcePath = resolveAuthProfileDatabasePath(agentDir);
234+
writePersistedAuthProfileStoreRaw(apiKeyStore("sk-legacy"), agentDir);
235+
const realLstat = fs.lstatSync;
236+
let sourceInspections = 0;
237+
const lstatSpy = vi.spyOn(fs, "lstatSync").mockImplementation((pathname, options) => {
238+
if (path.resolve(String(pathname)) === path.resolve(sourcePath)) {
239+
sourceInspections += 1;
240+
}
241+
return realLstat(pathname, options as never);
242+
});
243+
244+
try {
245+
for (const key of ["sk-first", "sk-second"]) {
246+
await upsertAuthProfileWithLockOrThrow({
247+
agentDir,
248+
profileId: "openai:default",
249+
credential: apiKeyCredential(key),
250+
});
251+
}
252+
expect(sourceInspections).toBe(1);
253+
254+
const detected = detectSharedAuthStoreMigration({
255+
stateDir,
256+
doctorOnlyStateMigrations: true,
257+
});
258+
await migrateSharedAuthStore({ detected, stateDir });
259+
const inspectionsAfterDoctor = sourceInspections;
260+
261+
await upsertAuthProfileWithLockOrThrow({
262+
agentDir,
263+
profileId: "openai:default",
264+
credential: apiKeyCredential("sk-after-doctor"),
265+
});
266+
267+
expect(sourceInspections).toBe(inspectionsAfterDoctor);
268+
expect(ensureAuthProfileStore(undefined, { syncExternalCli: false })).toMatchObject({
269+
profiles: { "openai:default": { key: "sk-after-doctor" } },
270+
});
271+
expect(inspectPersistedAuthProfileStoreRaw(agentDir).status).toBe("missing");
272+
} finally {
273+
lstatSpy.mockRestore();
274+
}
275+
});
276+
});
277+
278+
it("keeps legacy ownership while shared-auth cleanup is pending", async () => {
279+
await withAgentDirEnv("openclaw-auth-shared-pending-", async (agentDir) => {
280+
const sourcePath = resolveAuthProfileDatabasePath(agentDir);
281+
writeConfigMachineState("test.seed", true);
282+
const sharedDatabase = new DatabaseSync(resolveOpenClawStateSqlitePath());
283+
sharedDatabase
284+
.prepare(
285+
`INSERT INTO migration_runs (id, started_at, finished_at, status, report_json)
286+
VALUES ('shared-auth-pending', 1, NULL, 'copied', '{}')`,
287+
)
288+
.run();
289+
sharedDatabase
290+
.prepare(
291+
`INSERT INTO migration_sources
292+
(source_key, migration_kind, source_path, target_table, source_sha256,
293+
source_size_bytes, source_record_count, last_run_id, status, imported_at,
294+
removed_source, report_json)
295+
VALUES ('shared-auth-pending:store', 'shared-auth-store-state-db', ?,
296+
'auth_profile_stores', NULL, NULL, NULL, 'shared-auth-pending',
297+
'copied', 1, 0, '{}')`,
298+
)
299+
.run(sourcePath);
300+
sharedDatabase.close();
301+
302+
await upsertAuthProfileWithLockOrThrow({
303+
agentDir,
304+
profileId: "openai:default",
305+
credential: apiKeyCredential("sk-after-crash"),
306+
});
307+
308+
const after = new DatabaseSync(resolveOpenClawStateSqlitePath());
309+
expect(
310+
after
311+
.prepare(
312+
"SELECT value_json FROM config_machine_state WHERE state_key = 'auth.sharedStore'",
313+
)
314+
.get(),
315+
).toBeUndefined();
316+
expect(
317+
after.prepare("SELECT store_key FROM auth_profile_stores WHERE store_key = 'shared'").get(),
318+
).toBeUndefined();
319+
after.close();
320+
expect(inspectPersistedAuthProfileStoreRaw(agentDir).status).toBe("readable");
321+
});
322+
});
323+
324+
it("keeps legacy ownership when the main-agent source is unreadable", async () => {
325+
await withAgentDirEnv("openclaw-auth-shared-unreadable-", async (agentDir) => {
326+
const sourcePath = resolveAuthProfileDatabasePath(agentDir);
327+
const realLstat = fs.lstatSync;
328+
const lstatSpy = vi.spyOn(fs, "lstatSync").mockImplementation((pathname, options) => {
329+
if (path.resolve(String(pathname)) === path.resolve(sourcePath)) {
330+
throw Object.assign(new Error("permission denied"), { code: "EACCES" });
331+
}
332+
return realLstat(pathname, options as never);
333+
});
334+
335+
try {
336+
await upsertAuthProfileWithLockOrThrow({
337+
agentDir,
338+
profileId: "openai:default",
339+
credential: apiKeyCredential("sk-unreadable"),
340+
});
341+
} finally {
342+
lstatSpy.mockRestore();
343+
}
344+
345+
const sharedDatabase = new DatabaseSync(resolveOpenClawStateSqlitePath());
346+
expect(
347+
sharedDatabase
348+
.prepare(
349+
"SELECT value_json FROM config_machine_state WHERE state_key = 'auth.sharedStore'",
350+
)
351+
.get(),
352+
).toBeUndefined();
353+
sharedDatabase.close();
354+
expect(inspectPersistedAuthProfileStoreRaw(agentDir).status).toBe("readable");
355+
});
356+
});
357+
358+
it("keeps legacy ownership when a retired-file probe fails", async () => {
359+
await withAgentDirEnv("openclaw-auth-shared-file-probe-error-", async (agentDir) => {
360+
const authPath = path.join(agentDir, "auth-profiles.json");
361+
const realExistsSync = fs.existsSync.bind(fs);
362+
let authPathProbes = 0;
363+
const existsSpy = vi.spyOn(fs, "existsSync").mockImplementation((pathname) => {
364+
if (path.resolve(String(pathname)) === path.resolve(authPath)) {
365+
authPathProbes += 1;
366+
throw Object.assign(new Error("permission denied"), { code: "EACCES" });
367+
}
368+
return realExistsSync(pathname);
369+
});
370+
371+
try {
372+
writePersistedAuthProfileStoreRaw(apiKeyStore("sk-first"));
373+
writePersistedAuthProfileStoreRaw(apiKeyStore("sk-second"));
374+
expect(authPathProbes).toBe(1);
375+
} finally {
376+
existsSpy.mockRestore();
377+
}
378+
379+
const sharedDatabase = new DatabaseSync(resolveOpenClawStateSqlitePath());
380+
expect(
381+
sharedDatabase
382+
.prepare(
383+
"SELECT value_json FROM config_machine_state WHERE state_key = 'auth.sharedStore'",
384+
)
385+
.get(),
386+
).toBeUndefined();
387+
sharedDatabase.close();
388+
expect(inspectPersistedAuthProfileStoreRaw(agentDir).status).toBe("readable");
154389
});
155390
});
156391

0 commit comments

Comments
 (0)