Skip to content

Commit 3826b52

Browse files
authored
fix(auth): inherit the shared auth store once it owns credentials (#130264)
* fix(auth): inherit the shared auth store once it owns credentials resolveLegacyInheritedAuthDir unconditionally selected the legacy main-agent directory as the read-through base, so on fresh installs (and post-relocation installs) the empty agent DB shadowed the canonical shared auth store: models auth paste-api-key printed success while every turn failed with missing-provider-auth. The resolver now returns the legacy directory only while resolveSharedAuthStoreOwnership reports legacy-main ownership; otherwise inheritance read-throughs to the shared store per docs/auth-credential-semantics.md. Sibling shadow sites in the models list catalog paths fixed with the same predicate; stale AGENTS.md security line corrected. Regression proves fresh shared credentials resolve with no agent-local profile, populated legacy stores stay authoritative pre-relocation, and local profiles still override the shared base. * test(gateway): reset shared discovery state in the fixture-reset owner The chat.history thinkingDefault regression on CI was a pre-existing isolate:false leak: a sibling test's agentDiscoveryMock catalog fixture (reasoning:false) survived on globalThis and clamped the level to off. The shared fixture-reset owner now clears discovery state for both full and suite-backed resets, and the test publishes its own catalog fixture.
1 parent c581010 commit 3826b52

17 files changed

Lines changed: 136 additions & 23 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ Mechanics only; policy lives above.
335335
## Security / Release
336336

337337
- Never commit real phone numbers, videos, credentials, live config.
338-
- Secrets: channel/provider creds in `~/.openclaw/credentials/`; model auth profiles in `~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite` (`auth_profile_store`).
338+
- Secrets: channel/provider creds in `~/.openclaw/credentials/`; shared model auth profiles in `~/.openclaw/state/openclaw.sqlite`, with agent-local profiles overriding the shared read-through base; see `docs/auth-credential-semantics.md`.
339339
- SecretRef failures isolate to the smallest known owning surface; unknown ownership fails closed. Gateway starts degraded (exact owner marked configured-unavailable, typed redacted diagnostic, no implicit credential fallback) rather than refusing startup, except for its own ingress protection or structurally invalid config. Doctor and status list every degraded owner. Full doctrine: `docs/gateway/secrets.md`.
340340
- Dependency patches/overrides/vendor changes need explicit approval. `pnpm-workspace.yaml` patched dependencies use exact versions only.
341341
- Release/package guards: no hard-coded retired-package denylists; use generic artifact/dependency checks or fix build source.

‎src/agents/legacy-inherited-auth-dir.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { resolveStateDir } from "../config/paths.js";
55
import type { OpenClawConfig } from "../config/types.openclaw.js";
66
import { normalizeAgentId } from "../routing/session-key.js";
77
import { resolveAgentDir } from "./agent-scope-config.js";
8+
import { resolveSharedAuthStoreOwnership } from "./auth-profiles/path-resolve.js";
89

910
export function resolveLegacyInheritedAuthAgentId(config: OpenClawConfig): string {
1011
return (
@@ -14,13 +15,22 @@ export function resolveLegacyInheritedAuthAgentId(config: OpenClawConfig): strin
1415
);
1516
}
1617

17-
export function resolveLegacyInheritedAuthDir(
18+
export function resolveLegacyInheritedAuthAgentDir(
1819
config: OpenClawConfig,
1920
env: NodeJS.ProcessEnv = process.env,
2021
): string {
2122
return resolveAgentDir(config, resolveLegacyInheritedAuthAgentId(config), env);
2223
}
2324

25+
export function resolveLegacyInheritedAuthDir(
26+
config: OpenClawConfig,
27+
env: NodeJS.ProcessEnv = process.env,
28+
): string | undefined {
29+
return resolveSharedAuthStoreOwnership(env).location === "legacy-main"
30+
? resolveLegacyInheritedAuthAgentDir(config, env)
31+
: undefined;
32+
}
33+
2434
export function pinLegacyInheritedAuthOwnerForRosterTransition(
2535
sourceConfig: OpenClawConfig,
2636
targetConfig: OpenClawConfig,

‎src/agents/model-auth.profiles.test.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,20 @@ import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths
1010
import { withEnvAsync } from "../test-utils/env.js";
1111
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
1212
import { clearRuntimeAuthProfileStoreSnapshots } from "./auth-profiles/runtime-snapshots.js";
13+
import {
14+
inspectPersistedAuthProfileStoreRaw,
15+
writePersistedAuthProfileStoreRaw,
16+
} from "./auth-profiles/sqlite.js";
1317
import { ensureAuthProfileStore } from "./auth-profiles/store.js";
1418
import type {
1519
AuthProfileCredential,
1620
AuthProfileStore,
1721
OAuthCredential,
1822
RuntimeAuthProfileStore,
1923
} from "./auth-profiles/types.js";
24+
import { upsertAuthProfileWithLockOrThrow } from "./auth-profiles/upsert-with-lock.js";
2025
import { resolveInlineProviderApiKeyUsageId } from "./auth-profiles/usage.js";
26+
import { resolveLegacyInheritedAuthDir } from "./legacy-inherited-auth-dir.js";
2127
import {
2228
createRuntimeProviderAuthLookup,
2329
getApiKeyForModelCore,
@@ -414,6 +420,92 @@ async function resolveDemoLocalApiKey(params: {
414420
});
415421
}
416422

423+
describe("shared auth profile read-through", () => {
424+
it.each([
425+
{
426+
name: "resolves a freshly pasted shared API key without an agent-local profile",
427+
baseKey: "shared-state-key",
428+
legacy: false,
429+
localKey: undefined,
430+
},
431+
{
432+
name: "keeps the populated legacy main store authoritative before relocation",
433+
baseKey: "legacy-main-key",
434+
legacy: true,
435+
localKey: undefined,
436+
},
437+
{
438+
name: "lets an agent-local profile override its shared read-through base",
439+
baseKey: "shared-state-key",
440+
legacy: false,
441+
localKey: "agent-local-key",
442+
},
443+
])("$name", async ({ baseKey, legacy, localKey }) => {
444+
await withOpenClawTestState(
445+
{
446+
layout: "state-only",
447+
prefix: "openclaw-auth-read-through-",
448+
agentEnv: "main",
449+
env: { OPENAI_API_KEY: undefined },
450+
},
451+
async (state) => {
452+
const profileId = "openai:manual";
453+
const mainAgentDir = state.agentDir();
454+
const agentDir = state.agentDir("worker");
455+
const credential = {
456+
type: "api_key" as const,
457+
provider: "openai",
458+
key: baseKey,
459+
};
460+
461+
if (legacy) {
462+
writePersistedAuthProfileStoreRaw(
463+
{ version: 1, profiles: { [profileId]: credential } },
464+
mainAgentDir,
465+
);
466+
}
467+
await upsertAuthProfileWithLockOrThrow({
468+
profileId,
469+
credential,
470+
agentDir: mainAgentDir,
471+
});
472+
if (localKey) {
473+
writePersistedAuthProfileStoreRaw(
474+
{
475+
version: 1,
476+
profiles: { [profileId]: { ...credential, key: localKey } },
477+
},
478+
agentDir,
479+
);
480+
}
481+
482+
expect(inspectPersistedAuthProfileStoreRaw(mainAgentDir).status).toBe(
483+
legacy ? "readable" : "missing",
484+
);
485+
expect(inspectPersistedAuthProfileStoreRaw(agentDir).status).toBe(
486+
localKey ? "readable" : "missing",
487+
);
488+
489+
const inheritedAuthDir = resolveLegacyInheritedAuthDir({}, state.env);
490+
const store = ensureAuthProfileStore(agentDir, {
491+
allowKeychainPrompt: false,
492+
syncExternalCli: false,
493+
...(inheritedAuthDir ? { inheritedAuthDir } : {}),
494+
});
495+
const resolved = await resolveApiKeyForProviderCore({
496+
provider: "openai",
497+
cfg: {},
498+
agentDir,
499+
store,
500+
});
501+
502+
expect(resolved.apiKey).toBe(localKey ?? baseKey);
503+
expect(resolved.source).toBe(`profile:${profileId}`);
504+
},
505+
);
506+
});
507+
});
508+
417509
describe("getApiKeyForModelCore", () => {
418510
it("reads oauth auth-profiles entries from auth-profiles.json via explicit profile", async () => {
419511
await withOpenClawTestState(

‎src/agents/prepared-model-catalog-worker.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ describe("prepared model catalog worker input", () => {
8484
expect(cloned.input.runtimePluginSelections).toEqual([
8585
{ provider: "selected", modelId: "model" },
8686
]);
87+
expect(cloned.input).not.toHaveProperty("inheritedAuthDir");
8788
expect(cloned.input).not.toHaveProperty("loadRuntimePlugins");
8889
});
8990
});

‎src/agents/prepared-model-catalog-worker.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ export function createPreparedModelCatalogWorkerInput(params: {
102102
const input: PreparedModelRuntimeInput = {
103103
...(source.agentId ? { agentId: source.agentId } : {}),
104104
agentDir: source.agentDir,
105-
inheritedAuthDir: source.inheritedAuthDir ?? source.agentDir,
105+
...(source.inheritedAuthDir ? { inheritedAuthDir: source.inheritedAuthDir } : {}),
106106
...(source.workspaceDir ? { workspaceDir: source.workspaceDir } : {}),
107107
...(source.readOnly ? { readOnly: true } : {}),
108108
skipCredentials: true,

‎src/commands/doctor-auth-flat-profiles.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ import type {
5050
AuthProfileState,
5151
AuthProfileStore,
5252
} from "../agents/auth-profiles/types.js";
53-
import { resolveLegacyInheritedAuthDir } from "../agents/legacy-inherited-auth-dir.js";
53+
import { resolveLegacyInheritedAuthAgentDir } from "../agents/legacy-inherited-auth-dir.js";
5454
import { splitTrailingAuthProfile } from "../agents/model-ref-profile.js";
5555
import { formatCliCommand } from "../cli/command-format.js";
5656
import type { AuthProfileConfig } from "../config/types.auth.js";
@@ -450,7 +450,7 @@ function isDefaultAgentCandidate(
450450
): boolean {
451451
return (
452452
candidate.agentDir === undefined ||
453-
path.resolve(candidate.agentDir) === path.resolve(resolveLegacyInheritedAuthDir(cfg, env))
453+
path.resolve(candidate.agentDir) === path.resolve(resolveLegacyInheritedAuthAgentDir(cfg, env))
454454
);
455455
}
456456

‎src/commands/doctor-auth-legacy-paths.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import path from "node:path";
33
import { readNonBlankString } from "@openclaw/normalization-core/string-coerce";
44
import { listAgentIds, resolveAgentDir } from "../agents/agent-scope.js";
55
import { resolveSharedMainAuthAgentDir } from "../agents/auth-profiles/shared-main-dir.js";
6-
import { resolveLegacyInheritedAuthDir } from "../agents/legacy-inherited-auth-dir.js";
6+
import { resolveLegacyInheritedAuthAgentDir } from "../agents/legacy-inherited-auth-dir.js";
77
import { resolveStateDir } from "../config/paths.js";
88
import type { OpenClawConfig } from "../config/types.openclaw.js";
99
import { resolveUserPath } from "../utils.js";
@@ -67,7 +67,7 @@ export function listAuthProfileRepairCandidates(
6767
// The shared-main default store (undefined agentDir) must stay first so the
6868
// canonical location wins the per-path dedupe over agent-scoped aliases.
6969
addCandidate(candidates, undefined);
70-
addCandidate(candidates, resolveLegacyInheritedAuthDir(cfg, env));
70+
addCandidate(candidates, resolveLegacyInheritedAuthAgentDir(cfg, env));
7171
const envAgentDir =
7272
readNonBlankString(env.OPENCLAW_AGENT_DIR) ?? readNonBlankString(env.PI_CODING_AGENT_DIR);
7373
if (envAgentDir) {

‎src/commands/models/list.list-command.forward-compat.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,9 @@ describe("modelsListCommand forward-compat", () => {
428428
expect(mocks.resolveModelsTargetAgent).toHaveBeenCalledWith(mocks.resolvedConfig, "research", {
429429
kind: "read",
430430
});
431-
expect(mocks.ensureAuthProfileStore).toHaveBeenCalledWith("/tmp/openclaw-agent-research");
431+
expect(mocks.ensureAuthProfileStore).toHaveBeenCalledWith("/tmp/openclaw-agent-research", {
432+
inheritedAuthDir: expect.any(String),
433+
});
432434
});
433435

434436
it("rejects unknown provider filters before loading the model registry", async () => {

‎src/commands/models/list.list-command.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
33
import { sanitizeTerminalText } from "../../../packages/terminal-core/src/safe-text.js";
44
import { DEFAULT_PROVIDER } from "../../agents/defaults.js";
5+
import { resolveLegacyInheritedAuthDir } from "../../agents/legacy-inherited-auth-dir.js";
56
import { parseModelRef } from "../../agents/model-selection-normalize.js";
67
import { formatCliCommand } from "../../cli/command-format.js";
78
import { ExpectedCliError } from "../../cli/failure-output.js";
@@ -119,7 +120,10 @@ export async function modelsListCommand(
119120
throw new ExpectedCliError({ message, humanOutput: message, machineOutput: message });
120121
}
121122
}
122-
const authStore = loadAuthProfileStoreWithoutExternalProfiles(agentDir);
123+
const inheritedAuthDir = resolveLegacyInheritedAuthDir(cfg);
124+
const authStore = inheritedAuthDir
125+
? loadAuthProfileStoreWithoutExternalProfiles(agentDir, { inheritedAuthDir })
126+
: loadAuthProfileStoreWithoutExternalProfiles(agentDir);
123127
const authIndex = createModelListAuthIndex({
124128
cfg,
125129
authStore,
@@ -215,7 +219,7 @@ export async function modelsListCommand(
215219
cfg,
216220
agentId,
217221
agentDir,
218-
inheritedAuthDir: agentDir,
222+
...(inheritedAuthDir ? { inheritedAuthDir } : {}),
219223
authIndex,
220224
providerDiscoveryProviderIds,
221225
providerRuntimeDiscoveryProviderIds,

‎src/commands/models/list.rows.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1026,7 +1026,6 @@ describe("appendAuthenticatedCatalogRows", () => {
10261026
expect(mocks.loadScopedModelCatalogSnapshot).toHaveBeenCalledWith({
10271027
cfg: {},
10281028
agentDir: "/tmp/openclaw-agent",
1029-
inheritedAuthDir: "/tmp/openclaw-agent",
10301029
workspaceDir: "/tmp/openclaw-workspace",
10311030
providerIds: ["local-openai"],
10321031
runtimeProviderIds: ["local-openai"],

0 commit comments

Comments
 (0)