Skip to content

Commit cd01138

Browse files
authored
fix(auth): keep explicit-root operations isolated through activation and rollback (#131519)
* fix(auth): keep explicit state roots isolated through activation Carry canonical local and shared store ownership through persistence, publication, secrets activation, and rollback. Preserve newer local bookkeeping without importing credentials or migration state from another root. Fixes #131366. * fix(auth): defer alias discovery until profile ordering needs it Keep config-only auth profile staging independent of unrelated plugin state while preserving canonical alias ordering and mixed-mode promotion. Cover isolated mock staging against future and invalid outer stores. * test(secrets): verify cold profiles omit credential fields
1 parent 7573b91 commit cd01138

36 files changed

Lines changed: 3284 additions & 769 deletions

‎docs/auth-credential-semantics.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ Non-portable profiles remain available through the shared read-through base unle
6161

6262
`openclaw agent exec` preserves the original shared-store root when switching to temporary run state. Its bounded credential scope reads portable `api_key` and `token` profiles from that shared store without persisting copies; the configured agent's local profiles still win. Shared OAuth profiles are excluded from this temporary scope, even with `copyToAgents: true`, so the run does not acquire another refresh owner. `--auth-env-only` disables stored credential access entirely.
6363

64+
Auth writes that explicitly select a state directory, including isolated QA staging, use that directory's shared store for ownership and OAuth deduplication. Their runtime publication and rollback retain the same owner; another process-local state root is not an inherited base. An unrelated outer database may be older, newer, or unreadable without blocking an isolated write, but an unreadable or newer database in the selected target still fails closed. Writes without an explicit state directory retain the normal ambient state and agent-directory configuration.
65+
6466
## Config-only auth routes
6567

6668
`auth.profiles` entries with `mode: "aws-sdk"` are routing metadata, not stored credentials. They are valid when the target provider uses `models.providers.<id>.auth: "aws-sdk"`, the route the plugin-owned Amazon Bedrock setup writes. These profile ids may appear in `auth.order` and session overrides even when no matching entry exists in the credential store.

‎extensions/qa-lab/src/providers/shared/auth-store.test.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import { afterEach, describe, expect, it, vi } from "vitest";
1515
import { createTempDirHarness } from "../../temp-dir.test-helper.js";
1616
import { readQaAuthProfiles, writeQaAuthProfiles } from "./auth-store.js";
17+
import { stageQaMockAuthProfiles } from "./mock-auth.js";
1718

1819
const tempDirs = createTempDirHarness();
1920

@@ -83,6 +84,90 @@ describe("QA auth profile store", () => {
8384
});
8485
});
8586

87+
it.each(["future", "invalid"] as const)(
88+
"stages concurrent isolated profiles and config without reading %s outer state",
89+
async (outerKind) => {
90+
const hostStateDir = await tempDirs.makeTempDir("openclaw-qa-auth-unreadable-host-");
91+
const hostDatabasePath = path.join(hostStateDir, "state", "openclaw.sqlite");
92+
await fs.mkdir(path.dirname(hostDatabasePath), { recursive: true });
93+
if (outerKind === "future") {
94+
const database = new DatabaseSync(hostDatabasePath);
95+
database.exec("PRAGMA user_version = 999");
96+
database.close();
97+
} else {
98+
await fs.writeFile(hostDatabasePath, "not a SQLite database");
99+
}
100+
const hostBefore = await fs.readFile(hostDatabasePath);
101+
const qaRoots = await Promise.all([
102+
tempDirs.makeTempDir("openclaw-qa-auth-first-"),
103+
tempDirs.makeTempDir("openclaw-qa-auth-second-"),
104+
]);
105+
vi.stubEnv("OPENCLAW_STATE_DIR", hostStateDir);
106+
vi.stubEnv("OPENCLAW_AGENT_DIR", path.join(hostStateDir, "relocated-agent"));
107+
108+
const configs = await Promise.all(
109+
qaRoots.map((stateDir, index) =>
110+
stageQaMockAuthProfiles({
111+
cfg: {},
112+
agentIds: ["qa"],
113+
stateDir,
114+
providers: [index === 0 ? "openai" : "anthropic"],
115+
}),
116+
),
117+
);
118+
119+
for (const [index, stateDir] of qaRoots.entries()) {
120+
const provider = index === 0 ? "openai" : "anthropic";
121+
const profileId = `qa-mock-${provider}`;
122+
const store = readQaAuthProfiles(path.join(stateDir, "agents", "qa", "agent"));
123+
expect(Object.keys(store.profiles)).toEqual([profileId]);
124+
expect(configs[index]?.auth).toEqual({
125+
profiles: {
126+
[profileId]: {
127+
provider,
128+
mode: "api_key",
129+
displayName: `QA mock ${provider} credential`,
130+
},
131+
},
132+
});
133+
}
134+
expect(await fs.readFile(hostDatabasePath)).toEqual(hostBefore);
135+
expect(process.env.OPENCLAW_STATE_DIR).toBe(hostStateDir);
136+
expect(process.env.OPENCLAW_AGENT_DIR).toBe(path.join(hostStateDir, "relocated-agent"));
137+
},
138+
);
139+
140+
it.each(["future", "invalid"] as const)(
141+
"still refuses an explicit %s target auth database",
142+
async (targetKind) => {
143+
const { agentDir, agentId, stateDir } = await createQaAuthState();
144+
await fs.mkdir(agentDir, { recursive: true });
145+
const databasePath = path.join(agentDir, "openclaw-agent.sqlite");
146+
if (targetKind === "future") {
147+
const database = new DatabaseSync(databasePath);
148+
database.exec("PRAGMA user_version = 999");
149+
database.close();
150+
} else {
151+
await fs.writeFile(databasePath, "not a SQLite database");
152+
}
153+
const before = await fs.readFile(databasePath);
154+
await expect(
155+
writeQaAuthProfiles({
156+
agentId,
157+
stateDir,
158+
profiles: {
159+
"qa-mock-openai": {
160+
type: "api_key",
161+
provider: "openai",
162+
key: "qa-mock-not-a-real-key",
163+
},
164+
},
165+
}),
166+
).rejects.toThrow("unreadable");
167+
expect(await fs.readFile(databasePath)).toEqual(before);
168+
},
169+
);
170+
86171
it("writes new auth profiles to SQLite without creating legacy JSON", async () => {
87172
const { agentDir, agentId, stateDir } = await createQaAuthState();
88173

‎extensions/qa-lab/src/providers/shared/mock-auth.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ export function applyQaMockAuthProfileConfig(params: {
3434
* In mock provider modes the qa suite runs against an embedded mock server
3535
* instead of a real provider API. The mock does not validate credentials, but
3636
* the agent auth layer still needs a matching `api_key` auth profile in
37-
* `auth-profiles.json` before it will route the request through
37+
* the canonical SQLite auth store before it will route the request through
3838
* `providerBaseUrl`. Without this staging step, every scenario fails with
3939
* `FailoverError: No API key found for provider "openai"` before the mock
4040
* server ever sees a request.

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

Lines changed: 62 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
1+
import fs from "node:fs";
12
import { isRecord } from "@openclaw/normalization-core/record-coerce";
23
import { createSubsystemLogger } from "../../logging/subsystem.js";
34
import { shortenHomePath } from "../../utils.js";
45
import {
56
listLegacyAuthProfileSources,
7+
resolveLegacyAuthProfileSourceCandidates,
68
type LegacyAuthProfileSource,
79
type LegacyAuthProfileSourceKind,
810
} from "./legacy-source-files.js";
911
import { resolveSharedAuthStorePath } from "./path-resolve.js";
1012
import { resolveSharedMainAuthAgentDir } from "./shared-main-dir.js";
11-
import { inspectPersistedAuthProfileStoreRaw, resolveAuthProfileDatabasePath } from "./sqlite.js";
13+
import {
14+
inspectPersistedAuthProfileStoreRaw,
15+
inspectPersistedSharedAuthProfileStoreRaw,
16+
resolveAuthProfileDatabasePath,
17+
} from "./sqlite.js";
1218

1319
export {
1420
listLegacyAuthProfileArchives,
@@ -38,10 +44,13 @@ export function hasLegacyAuthProfileCredentialSource(agentDir?: string): boolean
3844
* has not archived yet, not unmigrated credentials: failing runtime closed there
3945
* would strand a working store over a file nothing reads.
4046
*/
41-
function hasMigratedAuthProfileCredentials(agentDir?: string): boolean {
47+
function hasMigratedAuthProfileCredentials(agentDir?: string, env?: NodeJS.ProcessEnv): boolean {
4248
let inspection: ReturnType<typeof inspectPersistedAuthProfileStoreRaw>;
4349
try {
44-
inspection = inspectPersistedAuthProfileStoreRaw(agentDir);
50+
inspection =
51+
!agentDir && env
52+
? inspectPersistedSharedAuthProfileStoreRaw(env)
53+
: inspectPersistedAuthProfileStoreRaw(agentDir);
4554
} catch {
4655
// An unreadable store is handled by its own canonical error; treat it as
4756
// "cannot serve credentials" so the legacy source stays fail-closed.
@@ -105,8 +114,15 @@ export class AuthProfileMigrationRequiredError extends Error {
105114
readonly ownerId: string;
106115
readonly sourceKinds: LegacyAuthProfileSourceKind[];
107116

108-
constructor(params: { agentDir?: string; sources: readonly LegacyAuthProfileSource[] }) {
109-
const ownerId = shortenHomePath(resolveAuthProfileOwnerPath(params.agentDir));
117+
constructor(params: {
118+
databasePath?: string;
119+
agentDir?: string;
120+
env?: NodeJS.ProcessEnv;
121+
sources: readonly LegacyAuthProfileSource[];
122+
}) {
123+
const ownerId = shortenHomePath(
124+
params.databasePath ?? resolveAuthProfileOwnerPath(params.agentDir, params.env),
125+
);
110126
const sourceKinds = [...new Set(params.sources.map((source) => source.kind))].toSorted();
111127
super(
112128
`Auth profile store ${ownerId} requires legacy credential migration; run ${AUTH_PROFILE_MIGRATION_COMMAND}.`,
@@ -121,9 +137,9 @@ export class AuthProfileStoreUnreadableError extends Error {
121137
readonly code = "AUTH_PROFILE_STORE_UNREADABLE" as const;
122138
readonly action = AUTH_PROFILE_MIGRATION_COMMAND;
123139

124-
constructor(agentDir?: string, env?: NodeJS.ProcessEnv) {
140+
constructor(databasePath: string) {
125141
super(
126-
`Auth profile store ${shortenHomePath(resolveAuthProfileOwnerPath(agentDir, env))} is unreadable; run ${AUTH_PROFILE_MIGRATION_COMMAND}.`,
142+
`Auth profile store ${shortenHomePath(databasePath)} is unreadable; run ${AUTH_PROFILE_MIGRATION_COMMAND}.`,
127143
);
128144
this.name = "AuthProfileStoreUnreadableError";
129145
}
@@ -133,13 +149,16 @@ const migrationRequiredByDatabase = new Map<string, AuthProfileMigrationRequired
133149
const warnedLegacySourceDatabases = new Set<string>();
134150

135151
export function warnLegacyAuthProfileSourcesIgnored(params: {
152+
databasePath?: string;
136153
agentDir?: string;
154+
env?: NodeJS.ProcessEnv;
137155
sources: readonly LegacyAuthProfileSource[];
138156
}): void {
139157
if (params.sources.length === 0) {
140158
return;
141159
}
142-
const databasePath = resolveAuthProfileOwnerPath(params.agentDir);
160+
const databasePath =
161+
params.databasePath ?? resolveAuthProfileOwnerPath(params.agentDir, params.env);
143162
if (warnedLegacySourceDatabases.has(databasePath)) {
144163
return;
145164
}
@@ -155,41 +174,66 @@ export function warnLegacyAuthProfileSourcesIgnored(params: {
155174
export function markAuthProfileMigrationRequired(
156175
agentDir: string | undefined,
157176
error: AuthProfileMigrationRequiredError,
177+
env?: NodeJS.ProcessEnv,
158178
): void {
159-
const databasePath = resolveAuthProfileOwnerPath(agentDir);
179+
const databasePath = resolveAuthProfileOwnerPath(agentDir, env);
160180
migrationRequiredByDatabase.set(databasePath, error);
161181
}
162182

163-
export function clearAuthProfileMigrationRequired(agentDir?: string): void {
164-
const databasePath = resolveAuthProfileOwnerPath(agentDir);
183+
export function clearAuthProfileMigrationRequired(
184+
agentDir?: string,
185+
env?: NodeJS.ProcessEnv,
186+
): void {
187+
const databasePath = resolveAuthProfileOwnerPath(agentDir, env);
165188
migrationRequiredByDatabase.delete(databasePath);
166189
}
167190

168-
export function assertAuthProfileMigrationReady(agentDir?: string): void {
169-
const databasePath = resolveAuthProfileOwnerPath(agentDir);
191+
/** Publication must honor a recorded refusal without rediscovering an ambient owner. */
192+
export function assertAuthProfileMigrationStateAtDatabasePath(databasePath: string): void {
170193
const error = migrationRequiredByDatabase.get(databasePath);
171194
if (error) {
172195
// The activated secrets snapshot for this owner is empty. Only an explicit
173196
// lifecycle clear/reload may remove the error and publish migrated SQLite rows.
174197
throw error;
175198
}
199+
}
200+
201+
export function assertAuthProfileMigrationCandidates(params: {
202+
databasePath: string;
203+
candidates: readonly LegacyAuthProfileSource[];
204+
hasCredentials: () => boolean;
205+
}): void {
206+
assertAuthProfileMigrationStateAtDatabasePath(params.databasePath);
176207
// Older shipped processes and restores can recreate these three fixed files
177208
// after startup, so this credential boundary deliberately rechecks their names.
178-
const sources = listLegacyAuthProfileSources({ agentDir }).filter(isCredentialSource);
209+
const sources = params.candidates.filter(
210+
(source) => isCredentialSource(source) && fs.existsSync(source.path),
211+
);
179212
if (sources.length === 0) {
180213
return;
181214
}
182215
// The store read only happens once a retired file actually exists, so the
183216
// healthy majority keeps the plain name check on this hot path.
184-
if (hasMigratedAuthProfileCredentials(agentDir)) {
185-
warnLegacyAuthProfileSourcesIgnored({ agentDir, sources });
217+
if (params.hasCredentials()) {
218+
warnLegacyAuthProfileSourcesIgnored({ databasePath: params.databasePath, sources });
186219
return;
187220
}
188-
const migrationError = new AuthProfileMigrationRequiredError({ agentDir, sources });
189-
markAuthProfileMigrationRequired(agentDir, migrationError);
221+
const migrationError = new AuthProfileMigrationRequiredError({
222+
databasePath: params.databasePath,
223+
sources,
224+
});
225+
migrationRequiredByDatabase.set(params.databasePath, migrationError);
190226
throw migrationError;
191227
}
192228

229+
export function assertAuthProfileMigrationReady(agentDir?: string, env?: NodeJS.ProcessEnv): void {
230+
assertAuthProfileMigrationCandidates({
231+
databasePath: resolveAuthProfileOwnerPath(agentDir, env),
232+
candidates: resolveLegacyAuthProfileSourceCandidates({ agentDir, env }),
233+
hasCredentials: () => hasMigratedAuthProfileCredentials(agentDir, env),
234+
});
235+
}
236+
193237
export function clearAuthProfileMigrationDiagnostics(): void {
194238
migrationRequiredByDatabase.clear();
195239
warnedLegacySourceDatabases.clear();

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

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ function resolveLegacySourceAgentDir(
2626
return agentDir ? resolveUserPath(agentDir) : resolveSharedMainAuthAgentDir(env);
2727
}
2828

29-
/** Detects retired auth files by name only; runtime code must never read their contents. */
30-
export function listLegacyAuthProfileSources(params: {
29+
/** Capture the fixed legacy candidates before the producer's environment can change. */
30+
export function resolveLegacyAuthProfileSourceCandidates(params: {
3131
agentDir?: string;
3232
env?: NodeJS.ProcessEnv;
3333
}): LegacyAuthProfileSource[] {
@@ -41,7 +41,17 @@ export function listLegacyAuthProfileSources(params: {
4141
if (path.resolve(agentDir) === path.resolve(sharedMainDir)) {
4242
candidates.push({ kind: "legacy-oauth", path: resolveLegacyOAuthPath(params.env) });
4343
}
44-
return candidates.filter((candidate) => fs.existsSync(candidate.path));
44+
return candidates;
45+
}
46+
47+
/** Detects retired auth files by name only; runtime code must never read their contents. */
48+
export function listLegacyAuthProfileSources(params: {
49+
agentDir?: string;
50+
env?: NodeJS.ProcessEnv;
51+
}): LegacyAuthProfileSource[] {
52+
return resolveLegacyAuthProfileSourceCandidates(params).filter((candidate) =>
53+
fs.existsSync(candidate.path),
54+
);
4555
}
4656

4757
export function listLegacyAuthProfileArchives(params: {

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ import { suggestOAuthProfileIdForLegacyDefault } from "./repair.js";
4343
import {
4444
getRuntimeAuthProfileStoreSnapshotCore,
4545
hasRuntimeAuthProfileStoreSnapshot,
46-
setRuntimeAuthProfileStoreSnapshot,
46+
updateRuntimeAuthProfileStoreSnapshot,
4747
} from "./runtime-snapshots.js";
4848
import {
4949
loadAuthProfileStoreForSecretsRuntime,
@@ -543,7 +543,7 @@ export async function resolveApiKeyForProfile(
543543
if (Object.keys(snapshot.lastGood).length === 0) {
544544
snapshot.lastGood = undefined;
545545
}
546-
setRuntimeAuthProfileStoreSnapshot(snapshot, params.agentDir);
546+
updateRuntimeAuthProfileStoreSnapshot(snapshot, params.agentDir);
547547
}
548548
}
549549
if (clearedLastGood) {

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,18 @@ const SHARED_AUTH_STORE_OWNERSHIP_CACHE_LIMIT = 256;
1414

1515
export type SharedAuthStoreOwnership = { location: "legacy-main" } | { location: "state-db" };
1616

17+
/** Pure producer facts; capturing a supplied runtime snapshot must not open SQLite. */
18+
export type AuthProfileOwnerScope = { stateDir: string; sharedMainDir: string };
19+
20+
export function captureAuthProfileOwnerScope(
21+
env: NodeJS.ProcessEnv = process.env,
22+
): AuthProfileOwnerScope {
23+
return {
24+
stateDir: path.resolve(resolveStateDir(env)),
25+
sharedMainDir: path.resolve(resolveSharedMainAuthAgentDir(env)),
26+
};
27+
}
28+
1729
// Explicit env callers can address another state root in the same process.
1830
// Pin each root once so later row changes require an owner-controlled restart.
1931
const sharedAuthStoreOwnershipByDatabasePath = new Map<string, SharedAuthStoreOwnership>();

0 commit comments

Comments
 (0)