Skip to content

Commit ca5c071

Browse files
committed
fix: strip api keys from generated models json
1 parent 7811e31 commit ca5c071

4 files changed

Lines changed: 81 additions & 15 deletions

‎src/agents/models-config.applies-config-env-vars.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,51 @@ describe("models-config", () => {
246246
]);
247247
});
248248

249+
it("strips apiKey fields from the models.json write payload", async () => {
250+
const plan = await planOpenClawModelsJsonWithDeps(
251+
{
252+
cfg: {
253+
models: {
254+
providers: {
255+
custom: {
256+
baseUrl: "https://custom.example/v1",
257+
api: "openai-completions",
258+
apiKey: "sk-config-secret", // pragma: allowlist secret
259+
models: [
260+
{
261+
id: "custom-model",
262+
name: "Custom model",
263+
input: ["text"],
264+
apiKey: "sk-model-secret", // pragma: allowlist secret
265+
},
266+
],
267+
} as unknown as ProviderConfig,
268+
},
269+
},
270+
},
271+
agentDir: "/tmp/openclaw-models-config-env-vars-test",
272+
env: {},
273+
existingRaw: "",
274+
existingParsed: null,
275+
},
276+
{
277+
resolveImplicitProviders: async () => ({}),
278+
},
279+
);
280+
281+
expect(plan.action).toBe("write");
282+
if (plan.action !== "write") {
283+
throw new Error("Expected models.json write plan");
284+
}
285+
expect(plan.contents).not.toContain("sk-config-secret");
286+
expect(plan.contents).not.toContain("sk-model-secret");
287+
const parsed = JSON.parse(plan.contents) as {
288+
providers?: Record<string, { apiKey?: unknown; models?: Array<{ apiKey?: unknown }> }>;
289+
};
290+
expect(parsed.providers?.custom?.apiKey).toBeUndefined();
291+
expect(parsed.providers?.custom?.models?.[0]?.apiKey).toBeUndefined();
292+
});
293+
249294
it("uses config env.vars entries for implicit provider discovery without mutating process.env", async () => {
250295
await withTempEnv(["OPENROUTER_API_KEY", TEST_ENV_VAR], async () => {
251296
unsetEnv(["OPENROUTER_API_KEY", TEST_ENV_VAR]);

‎src/agents/models-config.plan.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ import {
1616
} from "./models-config.providers.js";
1717

1818
type ModelsConfig = NonNullable<OpenClawConfig["models"]>;
19+
type ModelsJsonValue =
20+
| string
21+
| number
22+
| boolean
23+
| null
24+
| ModelsJsonValue[]
25+
| { [key: string]: ModelsJsonValue };
1926
export type ResolveImplicitProvidersForModelsJson = (params: {
2027
agentDir: string;
2128
config: OpenClawConfig;
@@ -105,6 +112,24 @@ function resolveProvidersForMode(params: {
105112
});
106113
}
107114

115+
function stripApiKeysForModelsJson(value: unknown): ModelsJsonValue {
116+
if (Array.isArray(value)) {
117+
return value.map((entry) => stripApiKeysForModelsJson(entry));
118+
}
119+
if (!isRecord(value)) {
120+
return value as ModelsJsonValue;
121+
}
122+
123+
const next: Record<string, ModelsJsonValue> = {};
124+
for (const [key, entry] of Object.entries(value)) {
125+
if (key === "apiKey") {
126+
continue;
127+
}
128+
next[key] = stripApiKeysForModelsJson(entry);
129+
}
130+
return next;
131+
}
132+
108133
export async function planOpenClawModelsJsonWithDeps(
109134
params: {
110135
cfg: OpenClawConfig;
@@ -178,7 +203,8 @@ export async function planOpenClawModelsJsonWithDeps(
178203
secretRefManagedProviders,
179204
}) ?? normalizedMergedProviders;
180205
const finalProviders = applyNativeStreamingUsageCompat(secretEnforcedProviders);
181-
const nextContents = `${JSON.stringify({ providers: finalProviders }, null, 2)}\n`;
206+
const modelsJsonProviders = stripApiKeysForModelsJson(finalProviders);
207+
const nextContents = `${JSON.stringify({ providers: modelsJsonProviders }, null, 2)}\n`;
182208

183209
if (params.existingRaw === nextContents) {
184210
return { action: "noop" };

‎src/agents/models-config.runtime-source-snapshot.test.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -171,15 +171,12 @@ function withGatewayTokenMode(config: OpenClawConfig): OpenClawConfig {
171171
};
172172
}
173173

174-
async function expectGeneratedProviderApiKey(
175-
agentDir: string,
176-
providerId: string,
177-
expected: string,
178-
) {
174+
async function expectGeneratedProviderHasNoApiKey(agentDir: string, providerId: string) {
179175
const parsed = await readGeneratedModelsJson<{
180176
providers: Record<string, { apiKey?: string }>;
181177
}>(agentDir);
182-
expect(parsed.providers[providerId]?.apiKey).toBe(expected);
178+
expect(parsed.providers[providerId]).toBeDefined();
179+
expect(parsed.providers[providerId]?.apiKey).toBeUndefined();
183180
}
184181

185182
async function planGeneratedProviders(params: {
@@ -272,7 +269,7 @@ describe("models-config runtime source snapshot", () => {
272269
try {
273270
setRuntimeConfigSnapshot(runtimeConfig, sourceConfig);
274271
await ensureOpenClawModelsJson(clonedRuntimeConfig, agentDir);
275-
await expectGeneratedProviderApiKey(agentDir, "openai", "OPENAI_API_KEY"); // pragma: allowlist secret
272+
await expectGeneratedProviderHasNoApiKey(agentDir, "openai");
276273
} finally {
277274
clearRuntimeConfigSnapshot();
278275
clearConfigCache();
@@ -325,7 +322,7 @@ describe("models-config runtime source snapshot", () => {
325322
>;
326323
}>(agentDir);
327324
expect(parsed.providers.openai?.baseUrl).toBe("https://api.openai.com/v1");
328-
expect(parsed.providers.openai?.apiKey).toBe("OPENAI_API_KEY"); // pragma: allowlist secret
325+
expect(parsed.providers.openai?.apiKey).toBeUndefined();
329326
expect(parsed.providers.openai?.headers?.["X-OpenClaw-Test"]).toBe("one");
330327

331328
// Header changes still rewrite models.json, but merge mode preserves the existing baseUrl.
@@ -337,7 +334,7 @@ describe("models-config runtime source snapshot", () => {
337334
>;
338335
}>(agentDir);
339336
expect(parsed.providers.openai?.baseUrl).toBe("https://api.openai.com/v1");
340-
expect(parsed.providers.openai?.apiKey).toBe("OPENAI_API_KEY"); // pragma: allowlist secret
337+
expect(parsed.providers.openai?.apiKey).toBeUndefined();
341338
expect(parsed.providers.openai?.headers?.["X-OpenClaw-Test"]).toBe("two");
342339
} finally {
343340
clearRuntimeConfigSnapshot();
@@ -359,7 +356,7 @@ describe("models-config runtime source snapshot", () => {
359356
config: createOpenAiRuntimeConfigWithHeadersAndApiKey(),
360357
sourceConfigForSecrets: withGatewayTokenMode(createOpenAiSourceConfigWithHeadersAndApiKey()),
361358
});
362-
expect(providers.openai?.apiKey).toBe("OPENAI_API_KEY"); // pragma: allowlist secret
359+
expect(providers.openai?.apiKey).toBeUndefined();
363360
expectOpenAiHeaderMarkers(providers);
364361
});
365362
});

‎src/agents/models-config.skips-writing-models-json-no-env-token.test.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,6 @@ async function runEnvProviderCase(params: {
102102
envVar: "MINIMAX_API_KEY" | "SYNTHETIC_API_KEY";
103103
envValue: string;
104104
providerKey: "minimax" | "synthetic";
105-
expectedApiKeyRef: string;
106105
}) {
107106
const previousValue = process.env[params.envVar];
108107
process.env[params.envVar] = params.envValue;
@@ -113,7 +112,8 @@ async function runEnvProviderCase(params: {
113112
const raw = await fs.readFile(modelPath, "utf8");
114113
const parsed = JSON.parse(raw) as { providers: Record<string, ParsedProviderConfig> };
115114
const provider = parsed.providers[params.providerKey];
116-
expect(provider?.apiKey).toBe(params.expectedApiKeyRef);
115+
expect(provider).toBeDefined();
116+
expect(provider?.apiKey).toBeUndefined();
117117
} finally {
118118
if (previousValue === undefined) {
119119
delete process.env[params.envVar];
@@ -211,7 +211,6 @@ describe("models-config", () => {
211211
envVar: "MINIMAX_API_KEY",
212212
envValue: "sk-minimax-test",
213213
providerKey: "minimax",
214-
expectedApiKeyRef: "MINIMAX_API_KEY", // pragma: allowlist secret
215214
});
216215
});
217216
});
@@ -222,7 +221,6 @@ describe("models-config", () => {
222221
envVar: "SYNTHETIC_API_KEY",
223222
envValue: "sk-synthetic-test",
224223
providerKey: "synthetic",
225-
expectedApiKeyRef: "SYNTHETIC_API_KEY", // pragma: allowlist secret
226224
});
227225
});
228226
});

0 commit comments

Comments
 (0)