@@ -11,6 +11,10 @@ import { DatabaseSync } from "node:sqlite";
1111import { afterEach , beforeEach , describe , expect , it , vi } from "vitest" ;
1212import * as kyselySync from "../infra/kysely-sync.js" ;
1313import * as nodeSqlite from "../infra/node-sqlite.js" ;
14+ import {
15+ detectSharedAuthStoreMigration ,
16+ migrateSharedAuthStore ,
17+ } from "../infra/state-migrations.shared-auth-store.js" ;
1418import { writeConfigMachineState } from "../state/config-machine-state.js" ;
1519import {
1620 closeOpenClawAgentDatabasesForTest ,
@@ -30,13 +34,19 @@ import {
3034 inspectPersistedAuthProfileStateRaw ,
3135 inspectPersistedAuthProfileStoreRaw ,
3236 resolveAuthProfileDatabasePath ,
37+ writePersistedAuthProfileStateRaw ,
38+ writePersistedAuthProfileStoreRaw ,
3339} from "./auth-profiles/sqlite.js" ;
3440import {
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
4151type 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+
6276function 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