Skip to content

Commit a040b03

Browse files
authored
fix(auth): preserve custom provider SecretRefs in Doctor
Fixes #135079. Thanks @dannevang for the detailed report and two-provider reproduction. ## Problem After an upgrade, `openclaw doctor` could treat custom-provider environment references and generated catalog values as plaintext API keys. It persisted them as auth profiles, and those profiles could shadow the provider's direct environment credential. ## Root cause Config substitution discarded the fact that a resolved string came from an authored environment SecretRef. Doctor then classified model catalog strings without the provider's authored resolution facts. Runtime planning and status also treated stored profiles as usable ahead of an unqualified provider SecretRef. ## Fix - Record resolved environment SecretRef provenance during config substitution. - Make Doctor keep an authored provider SecretRef authoritative over root and plugin catalogs. - Remove only persisted profiles whose values exactly match that provider's reference markers. - Make runtime planning and model status prefer the authored provider SecretRef. - Reuse the already loaded authored model config during status readback. The production delta is +122 lines. The added code carries provider-specific pending/resolved provenance across config and worker boundaries and performs exact-value cleanup at the credential-migration owner. A global marker heuristic or downstream guard would not preserve this ownership or safely repair existing rows. ## Proof - Baseline main `9d10dcb5d39d09be94f48a1bfce1dbfd7a256903`: Doctor migrated two `${VAR}` references plus stale or bare generated values; model status selected stored profiles over fresh direct environment values. - Exact head `fc74120ab55d071e7c876b2f00c9db47032b8bb8`: Doctor migrated no model credentials, preserved both authored references, left no `authProfiles.store` row, and status selected two distinct environment credentials with zero profiles. - Main commits after the baseline did not touch any changed file. - Regression tests were red before the fix and green at the exact head. - Focused tests, the remote changed-scope gate, and the exact-head remote build passed. The first PR CI run exposed source-authority and max-lines defects; the exact failing tests now pass locally. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 51566e0 commit a040b03

13 files changed

Lines changed: 436 additions & 159 deletions

‎src/agents/model-auth-provider-config.ts‎

Lines changed: 32 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
*/
44
import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
55
import { resolveMergedModelProviderEntry } from "../config/model-provider-config.js";
6-
import { resolveConfigSecretRef } from "../config/resolution-facts.js";
6+
import {
7+
getResolvedConfigEnvSecretRef,
8+
resolveConfigSecretRef,
9+
} from "../config/resolution-facts.js";
710
import {
811
getRuntimeConfigSnapshot,
912
getRuntimeConfigSourceSnapshot,
@@ -100,15 +103,19 @@ export function resolveProviderConfigSecretInput(
100103
) {
101104
const sourceConfig = resolveProviderSourceConfig(cfg, provider);
102105
const entry = resolveMergedModelProviderEntry(sourceConfig, provider);
106+
const path = entry ? `models.providers.${entry.providerKey}.apiKey` : "";
107+
const resolvedEnvRef = entry ? getResolvedConfigEnvSecretRef(sourceConfig, path) : null;
103108
return {
104109
providerConfig: resolveProviderConfig(cfg, provider),
110+
resolvedEnvRef,
105111
ref: entry
106-
? resolveConfigSecretRef({
112+
? (resolvedEnvRef ??
113+
resolveConfigSecretRef({
107114
config: sourceConfig,
108-
path: `models.providers.${entry.providerKey}.apiKey`,
115+
path,
109116
value: entry.providerConfig.apiKey,
110117
defaults: sourceConfig?.secrets?.defaults,
111-
})
118+
}))
112119
: null,
113120
};
114121
}
@@ -141,41 +148,41 @@ export function resolveUsableCustomProviderApiKey(params: {
141148
env?: NodeJS.ProcessEnv;
142149
secretSentinels?: boolean;
143150
}): ResolvedCustomProviderApiKey | null {
144-
const { providerConfig: customProviderConfig, ref: apiKeyRef } = resolveProviderConfigSecretInput(
145-
params.cfg,
146-
params.provider,
147-
);
151+
const input = resolveProviderConfigSecretInput(params.cfg, params.provider);
152+
const { providerConfig: customProviderConfig, ref: apiKeyRef } = input;
148153
if (apiKeyRef) {
149-
if (apiKeyRef.source !== "env") {
150-
return null;
151-
}
152-
const envVarName = apiKeyRef.id.trim();
154+
const envVarName = apiKeyRef.source === "env" ? apiKeyRef.id.trim() : "";
153155
if (!envVarName) {
154156
return null;
155157
}
156-
if (
157-
!canResolveEnvSecretRefInReadOnlyPath({
158+
const canResolve =
159+
input.resolvedEnvRef ||
160+
canResolveEnvSecretRefInReadOnlyPath({
158161
cfg: params.cfg,
159162
provider: apiKeyRef.provider,
160163
id: envVarName,
161-
})
162-
) {
164+
});
165+
if (!canResolve) {
163166
return null;
164167
}
165-
const envValue = normalizeOptionalSecretInput((params.env ?? process.env)[envVarName]);
168+
const envValue = normalizeOptionalSecretInput(
169+
input.resolvedEnvRef ? customProviderConfig?.apiKey : (params.env ?? process.env)[envVarName],
170+
);
166171
if (!envValue) {
167172
return null;
168173
}
169-
const applied = new Set(getShellEnvAppliedKeys());
174+
const source = input.resolvedEnvRef
175+
? "models.json"
176+
: resolveEnvSourceLabel({
177+
applied: new Set(getShellEnvAppliedKeys()),
178+
envVars: [envVarName],
179+
label: `${envVarName} (models.json secretref)`,
180+
});
170181
return {
171182
apiKey: params.secretSentinels
172183
? mintSecretSentinel(envValue, { label: `model-auth:${params.provider}` })
173184
: envValue,
174-
source: resolveEnvSourceLabel({
175-
applied,
176-
envVars: [envVarName],
177-
label: `${envVarName} (models.json secretref)`,
178-
}),
185+
source,
179186
};
180187
}
181188

@@ -217,13 +224,11 @@ export function resolveUsableCustomProviderApiKey(params: {
217224
}
218225

219226
/** True when a custom provider has a literal/env/local key available now. */
220-
export function hasUsableCustomProviderApiKey(
227+
export const hasUsableCustomProviderApiKey = (
221228
cfg: OpenClawConfig | undefined,
222229
provider: string,
223230
env?: NodeJS.ProcessEnv,
224-
): boolean {
225-
return Boolean(resolveUsableCustomProviderApiKey({ cfg, provider, env }));
226-
}
231+
) => Boolean(resolveUsableCustomProviderApiKey({ cfg, provider, env }));
227232

228233
/** True when explicit provider config should outrank profile/environment auth. */
229234
export function shouldPreferExplicitConfigApiKeyAuth(

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { readConfigFileSnapshotFromContext } from "../config/io.snapshot.js";
66
import {
77
getAuthoredConfigSecretRef,
88
getConfigResolutionFacts,
9+
getResolvedConfigEnvSecretRef,
910
} from "../config/resolution-facts.js";
1011
import {
1112
clearRuntimeConfigSnapshot,
@@ -52,7 +53,7 @@ describe("serialized catalog credential provenance", () => {
5253
owner: "config" | "profile";
5354
label: string;
5455
value: string;
55-
loader?: { authored: string; env?: NodeJS.ProcessEnv; pending?: boolean };
56+
loader?: { authored: string; env?: NodeJS.ProcessEnv; pending?: boolean; resolved?: boolean };
5657
}>([
5758
{ owner: "config", label: "literal bytes", value: "synthetic-worker-config-key" },
5859
{ owner: "config", label: "marker bytes", value: NON_ENV_SECRETREF_MARKER },
@@ -62,7 +63,11 @@ describe("serialized catalog credential provenance", () => {
6263
owner: "config",
6364
label: "loader-substituted literal",
6465
value: "${LITERAL_KEY}",
65-
loader: { authored: "${SOURCE_KEY}", env: { SOURCE_KEY: "${LITERAL_KEY}" } },
66+
loader: {
67+
authored: "${SOURCE_KEY}",
68+
env: { SOURCE_KEY: "${LITERAL_KEY}" },
69+
resolved: true,
70+
},
6671
},
6772
{
6873
owner: "config",
@@ -331,12 +336,19 @@ module.exports = {
331336
serialized.input.config,
332337
`models.providers.${provider}.apiKey`,
333338
),
339+
resolvedEnvRef: getResolvedConfigEnvSecretRef(
340+
serialized.input.config,
341+
`models.providers.${provider}.apiKey`,
342+
),
334343
}).toEqual({
335344
nativeAuthMatches: true,
336345
nativeRequests: loader.pending ? [] : [true],
337346
workerAuthMatches: true,
338347
workerRequests: loader.pending ? [] : [true],
339348
authoredRef: expectedRef,
349+
resolvedEnvRef: loader.resolved
350+
? { source: "env", provider: "default", id: "SOURCE_KEY" }
351+
: null,
340352
});
341353
if (loader.pending) {
342354
return;

‎src/agents/runtime-plan/prepare-auth.test.ts‎

Lines changed: 67 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -518,28 +518,33 @@ describe("prepareAgentRuntimeAuthPlan", () => {
518518
).toThrow(/temporarily unavailable/u);
519519
});
520520

521-
it("does not bypass an all-cooldown auth order through direct provider auth", () => {
522-
expect(() =>
523-
prepareAgentRuntimeAuthPlan({
524-
...openAIPlatformAuthFixture(),
525-
config: {
526-
models: {
527-
providers: {
528-
openai: {
529-
apiKey: { source: "env", provider: "default", id: "DIRECT_OPENAI_KEY" },
530-
baseUrl: "",
531-
models: [],
532-
},
521+
it("keeps an explicit provider SecretRef ahead of an all-cooldown auth order", () => {
522+
const plan = prepareAgentRuntimeAuthPlan({
523+
...openAIPlatformAuthFixture(),
524+
config: {
525+
models: {
526+
providers: {
527+
openai: {
528+
apiKey: { source: "env", provider: "default", id: "DIRECT_OPENAI_KEY" },
529+
baseUrl: "",
530+
models: [],
533531
},
534532
},
535-
secrets: { providers: { default: { source: "env" } } },
536-
} as OpenClawConfig,
537-
env: { DIRECT_OPENAI_KEY: "sk-direct" },
538-
harnessId: "codex",
539-
harnessRuntime: "codex",
540-
authProfileStore: allCooldownOpenAIStore(),
541-
}),
542-
).toThrow(/temporarily unavailable/u);
533+
},
534+
secrets: { providers: { default: { source: "env" } } },
535+
} as OpenClawConfig,
536+
env: { DIRECT_OPENAI_KEY: "sk-direct" },
537+
harnessId: "codex",
538+
harnessRuntime: "codex",
539+
authProfileStore: allCooldownOpenAIStore(),
540+
});
541+
542+
expect(plan.forwardedAuthProfileId).toBeUndefined();
543+
expect(plan.credentialSource).toEqual({
544+
kind: "direct",
545+
evidence: "environment",
546+
authorization: "declared",
547+
});
543548
});
544549

545550
it("does not let clear OAuth auth hide a cooldown Platform tier before literal fallback", () => {
@@ -790,43 +795,48 @@ describe("prepareAgentRuntimeAuthPlan", () => {
790795
});
791796
});
792797

793-
it("rejects an all-invalid auth order before configured direct auth", () => {
794-
expect(() =>
795-
prepareAgentRuntimeAuthPlan({
796-
...openAIPlatformAuthFixture(),
797-
config: {
798-
auth: { order: { openai: ["openai:ordered"] } },
799-
secrets: {
800-
providers: {
801-
default: { source: "env" },
802-
vault: { source: "file", path: "/tmp/secrets.json", mode: "json" },
803-
},
798+
it("keeps an explicit provider SecretRef ahead of an all-invalid auth order", () => {
799+
const plan = prepareAgentRuntimeAuthPlan({
800+
...openAIPlatformAuthFixture(),
801+
config: {
802+
auth: { order: { openai: ["openai:ordered"] } },
803+
secrets: {
804+
providers: {
805+
default: { source: "env" },
806+
vault: { source: "file", path: "/tmp/secrets.json", mode: "json" },
804807
},
805-
models: {
806-
providers: {
807-
openai: {
808-
apiKey: { source: "env", provider: "default", id: "DIRECT_OPENAI_KEY" },
809-
baseUrl: "https://api.openai.com/v1",
810-
models: [],
811-
},
808+
},
809+
models: {
810+
providers: {
811+
openai: {
812+
apiKey: { source: "env", provider: "default", id: "DIRECT_OPENAI_KEY" },
813+
baseUrl: "https://api.openai.com/v1",
814+
models: [],
812815
},
813816
},
814-
} as OpenClawConfig,
815-
env: { DIRECT_OPENAI_KEY: "sk-direct" },
816-
harnessId: "codex",
817-
harnessRuntime: "codex",
818-
authProfileStore: authStore(
819-
{
820-
"openai:ordered": {
821-
type: "api_key",
822-
provider: "openai",
823-
keyRef: { source: "env", provider: "vault", id: "ORDERED_OPENAI_KEY" },
824-
},
817+
},
818+
} as OpenClawConfig,
819+
env: { DIRECT_OPENAI_KEY: "sk-direct" },
820+
harnessId: "codex",
821+
harnessRuntime: "codex",
822+
authProfileStore: authStore(
823+
{
824+
"openai:ordered": {
825+
type: "api_key",
826+
provider: "openai",
827+
keyRef: { source: "env", provider: "vault", id: "ORDERED_OPENAI_KEY" },
825828
},
826-
{ openai: ["openai:ordered"] },
827-
),
828-
}),
829-
).toThrow(/explicit auth order.*no usable profiles/iu);
829+
},
830+
{ openai: ["openai:ordered"] },
831+
),
832+
});
833+
834+
expect(plan.forwardedAuthProfileId).toBeUndefined();
835+
expect(plan.credentialSource).toEqual({
836+
kind: "direct",
837+
evidence: "environment",
838+
authorization: "declared",
839+
});
830840
});
831841

832842
it("does not cross to an incompatible auth route for a user pin", () => {
@@ -1561,7 +1571,7 @@ describe("prepareAgentRuntimeAuthPlan", () => {
15611571
}
15621572
});
15631573

1564-
it("keeps a provider apiKey SecretRef after API-key-compatible profiles", () => {
1574+
it("keeps a provider apiKey SecretRef ahead of API-key-compatible profiles", () => {
15651575
const prepared = prepareAgentRuntimeAuth({
15661576
...openAIChatGptAuthFixture(),
15671577
config: {
@@ -1595,19 +1605,18 @@ describe("prepareAgentRuntimeAuthPlan", () => {
15951605
});
15961606

15971607
expect(prepared.plan).toMatchObject({
1598-
forwardedAuthProfileId: "openai:platform",
1599-
selectedAuthMode: "api_key",
1608+
forwardedAuthProfileId: undefined,
1609+
selectedAuthMode: "api-key",
16001610
modelRoute: {
16011611
api: "openai-responses",
16021612
authRequirement: "api-key",
16031613
},
16041614
});
16051615
expect(prepared.attempts).toMatchObject([
1606-
{ kind: "profile", profileId: "openai:platform" },
16071616
{
16081617
kind: "direct",
16091618
allowAuthProfileFallback: false,
1610-
requiresPriorProfileAttempt: true,
1619+
requiresPriorProfileAttempt: false,
16111620
},
16121621
]);
16131622
});

‎src/agents/runtime-plan/prepare-auth.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ export function prepareAgentRuntimeAuth(
283283
const providerBindingSuppressesProfiles =
284284
(providerBinding.kind === "literal" && explicitConfigApiKeyAuth) ||
285285
providerHasUsableMarker ||
286-
(providerHasApiKeySecretRef && explicitConfigApiKeyAuth);
286+
providerHasApiKeySecretRef;
287287
const providerBindingNeedsNonProfileFallback =
288288
providerHasDirectMaterial && !providerBindingSuppressesProfiles;
289289
// Explicit auth owns the physical route; apiKey is only its bearer material.

0 commit comments

Comments
 (0)