Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(models): validate provider and model before pinning (prototype pollution)

Salman Qureshi5e4b79d4189f
diff --git a/src/core/agent.ts b/src/core/agent.ts
index f18bbb0c..ea4c01fb 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -2002,9 +2002,22 @@ export class Agent {
/** Public wrapper for web API model switching. */
async switchProvider(providerName: string, model?: string): Promise<{ ok: boolean; message: string }> {
// Providers like Ollama Local serve many models; pin the requested one
- // before the registry is rebuilt from config.
- const pc = (this.config.providers as Record<string, unknown>)[providerName] as { model?: string } | undefined;
- if (model && pc && typeof pc === 'object') pc.model = model;
+ // before the registry is rebuilt from config. Both values come from the
+ // web API, so validate before writing: an unchecked key such as
+ // "__proto__" would write onto Object.prototype, and the model id is
+ // persisted to mercury.yaml.
+ if (model !== undefined) {
+ if (typeof model !== 'string' || model.length === 0 || model.length > 256 || [...model].some((ch) => ch.charCodeAt(0) < 32 || ch.charCodeAt(0) === 127)) {
+ return { ok: false, message: 'Invalid model id.' };
+ }
+ const providers = this.config.providers as unknown as Record<string, unknown>;
+ const configured = getActiveProviders(this.config).some((p) => p.name === providerName);
+ if (!configured || !Object.hasOwn(providers, providerName)) {
+ return { ok: false, message: `Provider \`${providerName}\` is not configured.` };
+ }
+ const pc = providers[providerName];
+ if (pc && typeof pc === 'object') (pc as { model?: string }).model = model;
+ }
return this.switchSessionProvider(providerName);
}
diff --git a/src/core/switch-provider-guard.test.ts b/src/core/switch-provider-guard.test.ts
new file mode 100644
index 00000000..e0795c3f
--- /dev/null
+++ b/src/core/switch-provider-guard.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+import { Agent } from './agent.js';
+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';
+
+/**
+ * #191: POST /api/chat/models/switch passes provider + model straight into
+ * Agent.switchProvider. The model pin must never write through an unknown
+ * key (e.g. "__proto__") or for a provider that isn't configured.
+ */
+function agentWith(config: MercuryConfig): Agent {
+ const agent = Object.create(Agent.prototype) as Agent;
+ Object.assign(agent, { config, switchSessionProvider: async (name: string) => ({ ok: true, message: `switched to ${name}` }) });
+ return agent;
+}
+
+describe('switchProvider model pin', () => {
+ it('rejects __proto__ without polluting Object.prototype', async () => {
+ const agent = agentWith(getDefaultConfig() as MercuryConfig);
+ const res = await agent.switchProvider('__proto__', 'evil');
+ expect(res.ok).toBe(false);
+ expect(({} as { model?: string }).model).toBeUndefined();
+ });
+
+ it('rejects providers that are not configured, and bad model ids', async () => {
+ const agent = agentWith(getDefaultConfig() as MercuryConfig);
+ expect((await agent.switchProvider('notAProvider', 'x')).ok).toBe(false);
+ expect((await agent.switchProvider('openai', 'a'.repeat(300))).ok).toBe(false);
+ expect((await agent.switchProvider('openai', 'bad\nid')).ok).toBe(false);
+ });
+
+ it('pins the model on a configured provider', async () => {
+ const config = getDefaultConfig() as MercuryConfig;
+ config.providers.openai.apiKey = 'sk-test';
+ config.providers.openai.enabled = true;
+ const agent = agentWith(config);
+ const res = await agent.switchProvider('openai', 'gpt-4.1');
+ expect(res.ok).toBe(true);
+ expect(config.providers.openai.model).toBe('gpt-4.1');
+ });
+});
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index ff06ddec..de8c4471 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -280,10 +280,13 @@ chat.post('/api/chat/models/switch', async (c) => {
if (!modelSwitchFn) {
return c.json({ error: 'Model switching not available' }, 503);
}
- const body = await c.req.json<{ provider: string; model?: string }>();
- if (!body.provider) {
+ const body = await c.req.json<{ provider?: unknown; model?: unknown }>().catch(() => null);
+ if (!body || typeof body.provider !== 'string' || !body.provider) {
return c.json({ error: 'provider is required' }, 400);
}
+ if (body.model !== undefined && typeof body.model !== 'string') {
+ return c.json({ error: 'model must be a string' }, 400);
+ }
const result = await modelSwitchFn(body.provider, body.model?.trim() || undefined);
return c.json(result);
});