Skip to content

Commit 371e7f8

Browse files
committed
fix: omit api keys from generated models json
1 parent d0f7c8f commit 371e7f8

4 files changed

Lines changed: 120 additions & 16 deletions

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

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

249+
it("omits provider apiKey fields from serialized models.json plans", async () => {
250+
const plan = await planOpenClawModelsJsonWithDeps(
251+
{
252+
cfg: {
253+
models: {
254+
mode: "merge",
255+
providers: {
256+
"custom-proxy": {
257+
baseUrl: "https://custom.example/v1",
258+
api: "openai-completions",
259+
apiKey: "sk-custom-config-secret", // pragma: allowlist secret
260+
models: [
261+
{
262+
id: "custom-model",
263+
name: "Custom Model",
264+
input: ["text"],
265+
reasoning: false,
266+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
267+
contextWindow: 8192,
268+
maxTokens: 4096,
269+
},
270+
],
271+
},
272+
},
273+
},
274+
},
275+
agentDir: "/tmp/openclaw-models-config-env-vars-test",
276+
env: {},
277+
existingRaw: "",
278+
existingParsed: {
279+
providers: {
280+
legacy: {
281+
baseUrl: "https://legacy.example/v1",
282+
api: "openai-completions",
283+
apiKey: "sk-existing-models-json-secret", // pragma: allowlist secret
284+
models: [
285+
{
286+
id: "legacy-model",
287+
name: "Legacy Model",
288+
input: ["text"],
289+
reasoning: false,
290+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
291+
contextWindow: 8192,
292+
maxTokens: 4096,
293+
},
294+
],
295+
},
296+
},
297+
},
298+
},
299+
{
300+
resolveImplicitProviders: async () => ({
301+
openai: {
302+
baseUrl: "https://api.openai.com/v1",
303+
api: "openai-responses",
304+
apiKey: "OPENAI_API_KEY", // pragma: allowlist secret
305+
models: [
306+
{
307+
id: "gpt-5.5",
308+
name: "GPT-5.5",
309+
input: ["text"],
310+
reasoning: true,
311+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
312+
contextWindow: 400000,
313+
maxTokens: 128000,
314+
},
315+
],
316+
},
317+
}),
318+
},
319+
);
320+
321+
expect(plan.action).toBe("write");
322+
if (plan.action !== "write") {
323+
throw new Error("Expected models.json write plan");
324+
}
325+
const parsed = JSON.parse(plan.contents) as {
326+
providers?: Record<string, { apiKey?: string; baseUrl?: string; models?: unknown[] }>;
327+
};
328+
expect(plan.contents).not.toContain("apiKey");
329+
expect(plan.contents).not.toContain("OPENAI_API_KEY");
330+
expect(plan.contents).not.toContain("sk-custom-config-secret");
331+
expect(plan.contents).not.toContain("sk-existing-models-json-secret");
332+
expect(parsed.providers?.openai?.baseUrl).toBe("https://api.openai.com/v1");
333+
expect(parsed.providers?.["custom-proxy"]?.models).toHaveLength(1);
334+
expect(parsed.providers?.legacy?.baseUrl).toBe("https://legacy.example/v1");
335+
});
336+
249337
it("uses config env.vars entries for implicit provider discovery without mutating process.env", async () => {
250338
await withTempEnv(["OPENROUTER_API_KEY", TEST_ENV_VAR], async () => {
251339
unsetEnv(["OPENROUTER_API_KEY", TEST_ENV_VAR]);

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

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,25 @@ function resolveProvidersForMode(params: {
105105
});
106106
}
107107

108+
function omitProviderApiKeysForModelsJson(
109+
providers: Record<string, ProviderConfig>,
110+
): Record<string, ProviderConfig> {
111+
let sanitized: Record<string, ProviderConfig> | undefined;
112+
for (const [key, provider] of Object.entries(providers)) {
113+
if (!Object.prototype.hasOwnProperty.call(provider, "apiKey")) {
114+
if (sanitized) {
115+
sanitized[key] = provider;
116+
}
117+
continue;
118+
}
119+
sanitized ??= { ...providers };
120+
const nextProvider = { ...provider };
121+
delete nextProvider.apiKey;
122+
sanitized[key] = nextProvider;
123+
}
124+
return sanitized ?? providers;
125+
}
126+
108127
export async function planOpenClawModelsJsonWithDeps(
109128
params: {
110129
cfg: OpenClawConfig;
@@ -178,7 +197,8 @@ export async function planOpenClawModelsJsonWithDeps(
178197
secretRefManagedProviders,
179198
}) ?? normalizedMergedProviders;
180199
const finalProviders = applyNativeStreamingUsageCompat(secretEnforcedProviders);
181-
const nextContents = `${JSON.stringify({ providers: finalProviders }, null, 2)}\n`;
200+
const providersForModelsJson = omitProviderApiKeysForModelsJson(finalProviders);
201+
const nextContents = `${JSON.stringify({ providers: providersForModelsJson }, null, 2)}\n`;
182202

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

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

Lines changed: 8 additions & 11 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 expectGeneratedProviderOmitsApiKey(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]).not.toHaveProperty("apiKey");
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 expectGeneratedProviderOmitsApiKey(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).not.toHaveProperty("apiKey");
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).not.toHaveProperty("apiKey");
341338
expect(parsed.providers.openai?.headers?.["X-OpenClaw-Test"]).toBe("two");
342339
} finally {
343340
clearRuntimeConfigSnapshot();
@@ -354,12 +351,12 @@ describe("models-config runtime source snapshot", () => {
354351
expectOpenAiHeaderMarkers(providers);
355352
});
356353

357-
it("keeps source markers when runtime projection is skipped for incompatible top-level shape", async () => {
354+
it("keeps header source markers but omits provider apiKey markers in models.json plans", async () => {
358355
const providers = await planGeneratedProviders({
359356
config: createOpenAiRuntimeConfigWithHeadersAndApiKey(),
360357
sourceConfigForSecrets: withGatewayTokenMode(createOpenAiSourceConfigWithHeadersAndApiKey()),
361358
});
362-
expect(providers.openai?.apiKey).toBe("OPENAI_API_KEY"); // pragma: allowlist secret
359+
expect(providers.openai).not.toHaveProperty("apiKey");
363360
expectOpenAiHeaderMarkers(providers);
364361
});
365362
});

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

Lines changed: 3 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,9 @@ 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).not.toHaveProperty("apiKey");
117+
expect(provider?.models?.[0]?.id).toBe("test-model");
117118
} finally {
118119
if (previousValue === undefined) {
119120
delete process.env[params.envVar];
@@ -211,7 +212,6 @@ describe("models-config", () => {
211212
envVar: "MINIMAX_API_KEY",
212213
envValue: "sk-minimax-test",
213214
providerKey: "minimax",
214-
expectedApiKeyRef: "MINIMAX_API_KEY", // pragma: allowlist secret
215215
});
216216
});
217217
});
@@ -222,7 +222,6 @@ describe("models-config", () => {
222222
envVar: "SYNTHETIC_API_KEY",
223223
envValue: "sk-synthetic-test",
224224
providerKey: "synthetic",
225-
expectedApiKeyRef: "SYNTHETIC_API_KEY", // pragma: allowlist secret
226225
});
227226
});
228227
});

0 commit comments

Comments
 (0)