Skip to content

Commit 8a8ea8d

Browse files
committed
fix(auth): honor shared-store ownership in temp-state exec and agent deletion
Two follow-ups from #130264: agent exec temporary state now preserves the original shared auth root, so temp-state runs read-through portable static profiles (local precedence and cooldowns preserved, no inherited-secret copies); and agent deletion safety consults resolveSharedAuthStoreOwnership, so the implicit legacy main owner is protected only while the legacy store owns credentials — post-relocation main is deletable and shared credentials provably survive. Explicitly bound inheritance owners stay protected.
1 parent 99a2434 commit 8a8ea8d

11 files changed

Lines changed: 551 additions & 276 deletions

‎docs/auth-credential-semantics.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ Explicit copy flows, such as `openclaw agents add`, use this portability policy:
5959

6060
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

62+
`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.
63+
6264
## Config-only auth routes
6365

6466
`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.

‎src/agents/agent-delete-safety.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@ import { isPathInside } from "../infra/path-guards.js";
44
import { normalizeAgentId } from "../routing/session-key.js";
55
import { isSameOpenClawAgentDatabasePath } from "../state/openclaw-agent-db-registry.js";
66
import { listAgentEntries, resolveAgentWorkspaceDir } from "./agent-scope.js";
7-
import type { SharedAuthStoreOwnership } from "./auth-profiles/path-resolve.js";
7+
import {
8+
resolveSharedAuthStoreOwnership,
9+
type SharedAuthStoreOwnership,
10+
} from "./auth-profiles/path-resolve.js";
11+
import { resolveLegacyInheritedAuthAgentId } from "./legacy-inherited-auth-dir.js";
812
import { resolveCanonicalWorkspacePath } from "./workspace-state-identity.js";
913

1014
/** True when deleting this agent database would remove the legacy shared auth store. */
@@ -23,6 +27,14 @@ export function formatSharedAuthStoreOwnerDeleteError(agentId: string): string {
2327
return `Agent "${agentId}" owns the legacy shared auth store and cannot be deleted. Run openclaw doctor --fix to migrate shared auth, then retry.`;
2428
}
2529

30+
export function isInheritedAuthStoreOwner(cfg: OpenClawConfig, agentId: string): boolean {
31+
// Relocation retires the implicit agent owner, but explicit bindings must be re-pointed.
32+
const explicitOwner = cfg.agents?.defaults?.authInheritance?.agentId?.trim();
33+
if (!explicitOwner && resolveSharedAuthStoreOwnership().location !== "legacy-main") {
34+
return false;
35+
}
36+
return agentId === normalizeAgentId(resolveLegacyInheritedAuthAgentId(cfg));
37+
}
2638
function workspacePathsOverlap(left: string, right: string): boolean {
2739
const normalizedLeft = resolveCanonicalWorkspacePath(left.replaceAll("\0", ""));
2840
const normalizedRight = resolveCanonicalWorkspacePath(right.replaceAll("\0", ""));

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ function isCredentialSource(source: LegacyAuthProfileSource): boolean {
2424
return source.kind !== "auth-state";
2525
}
2626

27-
function resolveAuthProfileOwnerPath(agentDir?: string): string {
28-
return agentDir ? resolveAuthProfileDatabasePath(agentDir) : resolveSharedAuthStorePath();
27+
function resolveAuthProfileOwnerPath(agentDir?: string, env?: NodeJS.ProcessEnv): string {
28+
return agentDir ? resolveAuthProfileDatabasePath(agentDir) : resolveSharedAuthStorePath(env);
2929
}
3030

3131
export function hasLegacyAuthProfileCredentialSource(agentDir?: string): boolean {
@@ -121,9 +121,9 @@ export class AuthProfileStoreUnreadableError extends Error {
121121
readonly code = "AUTH_PROFILE_STORE_UNREADABLE" as const;
122122
readonly action = AUTH_PROFILE_MIGRATION_COMMAND;
123123

124-
constructor(agentDir?: string) {
124+
constructor(agentDir?: string, env?: NodeJS.ProcessEnv) {
125125
super(
126-
`Auth profile store ${shortenHomePath(resolveAuthProfileOwnerPath(agentDir))} is unreadable; run ${AUTH_PROFILE_MIGRATION_COMMAND}.`,
126+
`Auth profile store ${shortenHomePath(resolveAuthProfileOwnerPath(agentDir, env))} is unreadable; run ${AUTH_PROFILE_MIGRATION_COMMAND}.`,
127127
);
128128
this.name = "AuthProfileStoreUnreadableError";
129129
}

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

Lines changed: 101 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,17 @@ import {
3636
shouldUseMainOwnerForLocalOAuthCredential,
3737
type PersistedAuthProfileStores,
3838
} from "./ownership.js";
39-
import { resolveSharedAuthStorePath as resolveSharedAuthPath } from "./path-resolve.js";
39+
import {
40+
resolveSharedAuthStoreOwnership,
41+
resolveSharedAuthStorePath as resolveSharedAuthPath,
42+
} from "./path-resolve.js";
4043
import {
4144
buildPersistedAuthProfileSecretsStore,
4245
loadPersistedAuthProfileStore,
46+
loadPersistedSharedAuthProfileStore,
4347
mergeAuthProfileStores,
4448
} from "./persisted.js";
49+
import { resolveAuthProfilePortability } from "./portability.js";
4550
import {
4651
getRuntimeExternalCliProfileIds,
4752
mergeRuntimeExternalProfileReferences,
@@ -64,6 +69,7 @@ import {
6469
deferAuthProfilePostCommitPublication,
6570
deletePersistedAuthProfileStoreRaw,
6671
inspectPersistedAuthProfileStoreRaw,
72+
inspectPersistedSharedAuthProfileStoreRaw,
6773
readPersistedAuthProfileStoreRaw,
6874
readPersistedAuthProfileStateRaw,
6975
resolveAuthProfileDatabasePath as resolveAgentAuthPath,
@@ -97,7 +103,9 @@ type SaveAuthProfileStoreOptions = {
97103
};
98104

99105
const INLINE_OAUTH_TOKEN_FIELDS = ["access", "refresh", "idToken"] as const;
100-
type AuthProfileRuntimeMode = { kind: "env-only" } | { kind: "agent-dir"; agentDir: string };
106+
type AuthProfileRuntimeMode =
107+
| { kind: "env-only" }
108+
| { kind: "agent-dir"; agentDir: string; sharedStore?: AuthProfileStore };
101109

102110
const authProfileRuntimeMode = new AsyncLocalStorage<AuthProfileRuntimeMode>();
103111

@@ -111,8 +119,50 @@ export function withEnvOnlyAuthProfileStore<T>(run: () => T): T {
111119
}
112120

113121
/** Run a bounded operation against one existing persisted auth store. */
114-
export function withAuthProfileStoreAgentDir<T>(agentDir: string, run: () => T): T {
115-
return authProfileRuntimeMode.run({ kind: "agent-dir", agentDir }, run);
122+
export function withAuthProfileStoreAgentDir<T>(
123+
agentDir: string,
124+
sharedStateDir: string,
125+
run: () => T,
126+
): T {
127+
const env = { ...process.env, OPENCLAW_STATE_DIR: sharedStateDir };
128+
let sharedStore: AuthProfileStore | undefined;
129+
if (resolveSharedAuthStoreOwnership(env).location === "state-db") {
130+
const shared = loadPersistedSharedAuthProfileStore(env);
131+
if (!shared && inspectPersistedSharedAuthProfileStoreRaw(env).status !== "missing") {
132+
throw new AuthProfileStoreUnreadableError(undefined, env);
133+
}
134+
sharedStore = shared ?? createEmptyAuthProfileStore();
135+
}
136+
// Temporary runs must not acquire a second OAuth refresh owner. Keep this
137+
// read-through view in the operation scope, never in a persisted agent store.
138+
if (sharedStore) {
139+
sharedStore.profiles = Object.fromEntries(
140+
Object.entries(sharedStore.profiles).filter(
141+
([, credential]) =>
142+
resolveAuthProfilePortability(credential).reason === "portable-static-credential",
143+
),
144+
);
145+
pruneAuthProfileStoreReferences(sharedStore, new Set(Object.keys(sharedStore.profiles)));
146+
}
147+
return authProfileRuntimeMode.run({ kind: "agent-dir", agentDir, sharedStore }, run);
148+
}
149+
150+
function getScopedSharedAuthStore(): AuthProfileStore | undefined {
151+
const mode = authProfileRuntimeMode.getStore();
152+
return mode?.kind === "agent-dir" ? mode.sharedStore : undefined;
153+
}
154+
155+
function applyScopedAuthReadThrough(store: AuthProfileStore): AuthProfileStore {
156+
const shared = getScopedSharedAuthStore();
157+
if (!shared) {
158+
return store;
159+
}
160+
const merged = mergeAuthProfileStores(cloneAuthProfileStore(shared), store);
161+
return setRuntimeLocalProfileMetadata(
162+
merged,
163+
Object.keys(store.profiles),
164+
runtimeStoreInheritsMainState(merged, store),
165+
);
116166
}
117167

118168
function isEnvOnlyAuthProfileRuntime(): boolean {
@@ -286,6 +336,11 @@ function resolveRuntimeAuthProfileStore(
286336
agentDir?: string,
287337
options?: Pick<LoadAuthProfileStoreOptions, "allowKeychainPrompt" | "inheritedAuthDir">,
288338
): AuthProfileStore | null {
339+
// Ambient snapshots may include non-portable shared profiles. A bounded exec
340+
// scope composes its view from the actual local store and its filtered base.
341+
if (getScopedSharedAuthStore()) {
342+
return null;
343+
}
289344
const mainKey = options?.inheritedAuthDir
290345
? resolveAgentAuthPath(options.inheritedAuthDir)
291346
: resolveSharedAuthPath();
@@ -471,6 +526,18 @@ function shouldKeepProfileInLocalStore(params: {
471526
persistedStores: PersistedAuthProfileStores;
472527
externalProfiles: () => RuntimeExternalOAuthProfile[];
473528
}): boolean {
529+
const inherited = getScopedSharedAuthStore()?.profiles[params.profileId];
530+
if (inherited && !params.persistedStores.localStore?.profiles[params.profileId]) {
531+
// Runtime state updates must not turn read-through credentials into local copies.
532+
// Compare persisted shapes so a materialized SecretRef stays inherited too.
533+
const secrets = buildPersistedAuthProfileSecretsStore({
534+
version: AUTH_STORE_VERSION,
535+
profiles: { [params.profileId]: params.credential },
536+
});
537+
if (isDeepStrictEqual(secrets.profiles[params.profileId], inherited)) {
538+
return false;
539+
}
540+
}
474541
if (params.credential.type !== "oauth") {
475542
return true;
476543
}
@@ -715,9 +782,12 @@ function runtimeStoreInheritsMainState(
715782
}
716783

717784
function listRuntimeLocalProfileIds(
718-
store: AuthProfileStore,
785+
store: RuntimeAuthProfileStore,
719786
mainStore?: AuthProfileStore,
720787
): string[] {
788+
if (store.runtimeLocalProfileIds) {
789+
return store.runtimeLocalProfileIds;
790+
}
721791
return Object.entries(store.profiles).flatMap(([profileId, credential]) =>
722792
mainStore &&
723793
shouldUseMainOwnerForLocalOAuthCredential({
@@ -917,13 +987,11 @@ export function loadAuthProfileStore(): AuthProfileStore {
917987
return createEmptyAuthProfileStore();
918988
}
919989
const agentDir = resolveRuntimeAuthProfileAgentDir();
920-
const asStore = loadPersistedAuthProfileStore(agentDir);
921-
if (asStore) {
922-
return overlayExternalAuthProfiles(markRuntimePersistedProfiles(asStore), { agentDir });
923-
}
924-
925-
const store: AuthProfileStore = { version: AUTH_STORE_VERSION, profiles: {} };
926-
return overlayExternalAuthProfiles(markRuntimePersistedProfiles(store), { agentDir });
990+
const store = loadPersistedAuthProfileStore(agentDir) ?? createEmptyAuthProfileStore();
991+
return overlayExternalAuthProfiles(
992+
applyScopedAuthReadThrough(markRuntimePersistedProfiles(store)),
993+
{ agentDir },
994+
);
927995
}
928996

929997
function loadAuthProfileStoreForAgent(
@@ -936,64 +1004,39 @@ function loadAuthProfileStoreForAgent(
9361004
const effectiveAgentDir = resolveRuntimeAuthProfileAgentDir(agentDir);
9371005
const effectiveOptions = resolveRuntimeAuthProfileLoadOptions(options);
9381006
assertAuthProfileMigrationReady(effectiveAgentDir);
939-
const asStore = loadPersistedAuthProfileStore(
1007+
const store = loadPersistedAuthProfileStore(
9401008
effectiveAgentDir,
9411009
resolvePersistedLoadOptions(effectiveOptions),
9421010
);
943-
if (asStore) {
944-
const legacySources = listLegacyAuthProfileSources({ agentDir: effectiveAgentDir });
945-
const credentialSources = legacySources.filter((source) => source.kind !== "auth-state");
946-
// A populated canonical store already owns this agent's credentials, so a
947-
// retired file beside it is unarchived bytes rather than pending migration.
948-
// Only an empty store means the credentials still live solely in that file.
949-
if (credentialSources.length > 0 && Object.keys(asStore.profiles).length === 0) {
950-
const migrationError = new AuthProfileMigrationRequiredError({
951-
agentDir: effectiveAgentDir,
952-
sources: credentialSources,
953-
});
954-
markAuthProfileMigrationRequired(effectiveAgentDir, migrationError);
955-
throw migrationError;
956-
}
957-
warnLegacyAuthProfileSourcesIgnored({
958-
agentDir: effectiveAgentDir,
959-
sources: legacySources,
960-
});
961-
clearAuthProfileMigrationRequired(effectiveAgentDir);
962-
const synced = maybeSyncPersistedExternalCliAuthProfiles({
963-
store: asStore,
964-
agentDir: effectiveAgentDir,
965-
options: effectiveOptions,
966-
});
967-
return markRuntimePersistedProfiles(synced.store);
968-
}
969-
970-
const inspection = inspectPersistedAuthProfileStoreRaw(
971-
effectiveAgentDir,
972-
effectiveOptions?.database,
973-
);
974-
if (inspection.status !== "missing") {
1011+
if (
1012+
!store &&
1013+
inspectPersistedAuthProfileStoreRaw(effectiveAgentDir, effectiveOptions?.database).status !==
1014+
"missing"
1015+
) {
9751016
throw new AuthProfileStoreUnreadableError(effectiveAgentDir);
9761017
}
9771018
const legacySources = listLegacyAuthProfileSources({ agentDir: effectiveAgentDir });
9781019
const credentialSources = legacySources.filter((source) => source.kind !== "auth-state");
979-
if (credentialSources.length > 0) {
980-
throw new AuthProfileMigrationRequiredError({
1020+
// A populated canonical store owns credentials; retired files beside it are
1021+
// unarchived bytes. An empty or absent store still requires migration.
1022+
if (credentialSources.length > 0 && (!store || Object.keys(store.profiles).length === 0)) {
1023+
const migrationError = new AuthProfileMigrationRequiredError({
9811024
agentDir: effectiveAgentDir,
9821025
sources: credentialSources,
9831026
});
1027+
if (store) {
1028+
markAuthProfileMigrationRequired(effectiveAgentDir, migrationError);
1029+
}
1030+
throw migrationError;
9841031
}
9851032
warnLegacyAuthProfileSourcesIgnored({ agentDir: effectiveAgentDir, sources: legacySources });
9861033
clearAuthProfileMigrationRequired(effectiveAgentDir);
987-
const store: AuthProfileStore = {
988-
version: AUTH_STORE_VERSION,
989-
profiles: {},
990-
};
9911034
const synced = maybeSyncPersistedExternalCliAuthProfiles({
992-
store,
1035+
store: store ?? createEmptyAuthProfileStore(),
9931036
agentDir: effectiveAgentDir,
9941037
options: effectiveOptions,
9951038
});
996-
return markRuntimePersistedProfiles(synced.store);
1039+
return applyScopedAuthReadThrough(markRuntimePersistedProfiles(synced.store));
9971040
}
9981041

9991042
/** Loads the effective runtime store for an agent, including inherited main profiles. */
@@ -1129,6 +1172,7 @@ export function ensureAuthProfileStore(
11291172
);
11301173
if (!runtimeStore) {
11311174
if (
1175+
!getScopedSharedAuthStore() &&
11321176
hasScopedExternalCliOverlay(externalCli) &&
11331177
(store.runtimeExternalProfileIds?.length ?? 0) > 0
11341178
) {
@@ -1210,6 +1254,10 @@ export function findPersistedAuthProfileCredential(params: {
12101254
const agentDir = resolveRuntimeAuthProfileAgentDir(params.agentDir);
12111255
const requestedStore = loadPersistedAuthProfileStore(agentDir);
12121256
const requestedProfile = requestedStore?.profiles[params.profileId];
1257+
const scopedSharedStore = getScopedSharedAuthStore();
1258+
if (scopedSharedStore) {
1259+
return requestedProfile ?? scopedSharedStore.profiles[params.profileId];
1260+
}
12131261
if (requestedProfile || !agentDir) {
12141262
return requestedProfile;
12151263
}

0 commit comments

Comments
 (0)