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(security): IDE git routes no longer run request input through a shell

Salman Qureshi7f0b13e9095f
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index d4d67db9..e625a978 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -1,5 +1,6 @@
import { Hono } from 'hono';
import { scopedProgrammingState } from '../../core/programming-mode.js';
+import { isInsideWorkspace } from './workspace-ide.js';
import { storeInlineAttachments, attachmentRefs, resolveUploadRef, uploadMime } from './uploads.js';
import type { WebChannel } from '../../channels/web.js';
import type { ProgrammingMode, ProgrammingModeState } from '../../core/programming-mode.js';
@@ -502,7 +503,7 @@ chat.get('/api/workspace/tree', (c) => {
const targetDir = subPath ? resolve(rootDir, subPath) : rootDir;
// Security: ensure target is within workspace
- if (!targetDir.startsWith(rootDir)) {
+ if (!isInsideWorkspace(targetDir, rootDir)) {
return c.json({ error: 'Path outside workspace' }, 403);
}
@@ -556,7 +557,7 @@ chat.get('/api/workspace/file', (c) => {
const fullPath = resolve(rootDir, filePath);
// Security: ensure within workspace
- if (!fullPath.startsWith(rootDir)) {
+ if (!isInsideWorkspace(fullPath, rootDir)) {
return c.json({ error: 'Path outside workspace' }, 403);
}
diff --git a/src/web/api/workspace-ide.test.ts b/src/web/api/workspace-ide.test.ts
new file mode 100644
index 00000000..f47d2292
--- /dev/null
+++ b/src/web/api/workspace-ide.test.ts
@@ -0,0 +1,84 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { isInsideWorkspace, isSafeRefName } from './workspace-ide.js';
+
+/**
+ * The IDE's git routes take file names, branch names and commit messages
+ * from the request. They must never reach a shell, and paths must stay in
+ * the workspace.
+ */
+describe('workspace and git hardening', () => {
+ let home: string;
+ let repo: string;
+ const previous = process.env.MERCURY_HOME;
+
+ // One home for the file: the module reads its settings path once at import.
+ beforeAll(() => {
+ home = mkdtempSync(join(tmpdir(), 'mercury-ide-'));
+ repo = join(home, 'project');
+ mkdirSync(repo);
+ process.env.MERCURY_HOME = home;
+ writeFileSync(join(home, 'web-chat-settings.json'), JSON.stringify({ workspace: repo }));
+ execFileSync('git', ['init', '-q'], { cwd: repo });
+ execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: repo });
+ execFileSync('git', ['config', 'user.name', 'T'], { cwd: repo });
+ writeFileSync(join(repo, 'a.txt'), 'one\n');
+ execFileSync('git', ['add', '.'], { cwd: repo });
+ execFileSync('git', ['commit', '-qm', 'init'], { cwd: repo });
+ });
+
+ afterAll(() => {
+ if (previous === undefined) delete process.env.MERCURY_HOME;
+ else process.env.MERCURY_HOME = previous;
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it('containment is real, not a prefix match', () => {
+ expect(isInsideWorkspace('src/a.ts', '/w/project')).toBe(true);
+ expect(isInsideWorkspace('/w/project', '/w/project')).toBe(true);
+ expect(isInsideWorkspace('../project-evil/x', '/w/project')).toBe(false);
+ expect(isInsideWorkspace('/w/project-evil/x', '/w/project')).toBe(false);
+ expect(isInsideWorkspace('../../etc/passwd', '/w/project')).toBe(false);
+ });
+
+ it('branch and remote names cannot be options or shell syntax', () => {
+ expect(isSafeRefName('feat/desktop-app')).toBe(true);
+ expect(isSafeRefName('origin')).toBe(true);
+ for (const bad of ['-b', '--upload-pack=touch /tmp/x', 'a;rm -rf /', '$(id)', '`id`', 'a b', 'x..y', 'x@{1}', 'x.lock', '']) {
+ expect(isSafeRefName(bad)).toBe(false);
+ }
+ });
+
+ it('a file name with shell syntax is passed to git as a name, never run', async () => {
+ const { default: ide } = await import('./workspace-ide.js');
+ const marker = join(home, 'pwned');
+ const evil = `a.txt$(touch ${marker})`;
+ await ide.request(`http://127.0.0.1/api/git/diff?file=${encodeURIComponent(evil)}`);
+ await ide.request('http://127.0.0.1/api/git/stage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ files: [evil] }) });
+ expect(existsSync(marker)).toBe(false);
+ });
+
+ it('commit messages with quotes and $() are stored literally', async () => {
+ const { default: ide } = await import('./workspace-ide.js');
+ const marker = join(home, 'pwned-commit');
+ writeFileSync(join(repo, 'a.txt'), 'two\n');
+ execFileSync('git', ['add', 'a.txt'], { cwd: repo });
+ const message = `say "hi" $(touch ${marker}) \`id\``;
+ const res = await ide.request('http://127.0.0.1/api/git/commit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message }) });
+ expect(res.status).toBe(200);
+ expect(existsSync(marker)).toBe(false);
+ const subject = execFileSync('git', ['log', '-1', '--format=%s'], { cwd: repo, encoding: 'utf8' }).trim();
+ expect(subject).toBe(message);
+ });
+
+ it('rejects an option-shaped branch and a path outside the workspace', async () => {
+ const { default: ide } = await import('./workspace-ide.js');
+ const checkout = await ide.request('http://127.0.0.1/api/git/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ branch: '--orphan=x' }) });
+ expect(checkout.status).toBe(400);
+ const diff = await ide.request(`http://127.0.0.1/api/git/diff?file=${encodeURIComponent('../outside.txt')}`);
+ expect(diff.status).toBe(403);
+ });
+});
diff --git a/src/web/api/workspace-ide.ts b/src/web/api/workspace-ide.ts
index 78492428..6f780ee1 100644
--- a/src/web/api/workspace-ide.ts
+++ b/src/web/api/workspace-ide.ts
@@ -1,7 +1,7 @@
import { Hono } from 'hono';
-import { execSync, spawn } from 'node:child_process';
+import { execFileSync, execSync, spawn } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync, statSync } from 'node:fs';
-import { join, resolve, relative, extname, basename } from 'node:path';
+import { join, resolve, relative, extname, basename, isAbsolute } from 'node:path';
import { getMercuryHome, loadConfig } from '../../utils/config.js';
import { generateText } from 'ai';
import type { ProviderRegistry } from '../../providers/registry.js';
@@ -13,31 +13,57 @@ export function setIDEProviders(pr: ProviderRegistry): void {
providerRegistry = pr;
}
-const CHAT_SETTINGS_FILE = join(getMercuryHome(), 'web-chat-settings.json');
+/** Resolved per call so MERCURY_HOME (tests, profiles) is honoured after import. */
+const chatSettingsFile = (): string => join(getMercuryHome(), 'web-chat-settings.json');
function getWorkspaceRoot(): string {
try {
- if (existsSync(CHAT_SETTINGS_FILE)) {
- const raw = JSON.parse(readFileSync(CHAT_SETTINGS_FILE, 'utf8'));
+ const file = chatSettingsFile();
+ if (existsSync(file)) {
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
if (raw.workspace) return raw.workspace;
}
} catch {}
return process.cwd();
}
-function git(args: string, cwd?: string): string {
- return execSync(`git ${args}`, {
+/**
+ * Run git WITHOUT a shell: arguments are passed as an array, so request
+ * input (file names, branch names, commit messages) is never parsed as
+ * shell syntax. This used to be `execSync(\`git ${args}\`)` with request
+ * fields interpolated — a file name like `$(cmd)` ran `cmd`.
+ */
+export function git(args: readonly string[], cwd?: string): string {
+ return execFileSync('git', [...args], {
cwd: cwd || getWorkspaceRoot(),
encoding: 'utf8',
timeout: 15000,
maxBuffer: 5 * 1024 * 1024,
+ windowsHide: true,
}).trim();
}
-function isInsideWorkspace(filePath: string): boolean {
- const root = getWorkspaceRoot();
- const resolved = resolve(root, filePath);
- return resolved.startsWith(root);
+/** True when the path resolves inside the workspace (not merely shares its prefix). */
+export function isInsideWorkspace(filePath: string, root: string = getWorkspaceRoot()): boolean {
+ const rel = relative(resolve(root), resolve(root, filePath));
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
+}
+
+/**
+ * A ref or remote name a client may name. Never an option (`-x`, `--upload-pack=…`),
+ * never shell or revision syntax; git's own check-ref-format rules do the rest.
+ */
+export function isSafeRefName(name: unknown): name is string {
+ return typeof name === 'string'
+ && name.length > 0
+ && name.length <= 200
+ && !name.startsWith('-')
+ && /^[A-Za-z0-9._/@+-]+$/.test(name)
+ && !name.includes('..')
+ && !name.includes('@{')
+ && !name.endsWith('.lock')
+ && !name.endsWith('/')
+ && !name.endsWith('.');
}
const ide = new Hono();
@@ -50,7 +76,7 @@ const ide = new Hono();
ide.get('/api/git/status', (c) => {
try {
const cwd = getWorkspaceRoot();
- const porcelain = git('status --porcelain -b', cwd);
+ const porcelain = git(['status', '--porcelain', '-b'], cwd);
const lines = porcelain.split('\n').filter(Boolean);
let branch = '';
@@ -112,7 +138,7 @@ function mapStatus(ch: string): string {
ide.get('/api/git/branches', (c) => {
try {
const cwd = getWorkspaceRoot();
- const raw = git('branch -a --format="%(refname:short) %(HEAD) %(upstream:short)"', cwd);
+ const raw = git(['branch', '-a', '--format=%(refname:short) %(HEAD) %(upstream:short)'], cwd);
const branches = raw.split('\n').filter(Boolean).map(line => {
const parts = line.split(' ');
const name = parts[0];
@@ -131,9 +157,9 @@ ide.post('/api/git/checkout', async (c) => {
try {
const body = await c.req.json<{ branch: string; create?: boolean }>();
if (!body.branch) return c.json({ error: 'branch is required' }, 400);
+ if (!isSafeRefName(body.branch)) return c.json({ error: 'Invalid branch name' }, 400);
const cwd = getWorkspaceRoot();
- const flag = body.create ? '-b ' : '';
- const result = git(`checkout ${flag}${body.branch}`, cwd);
+ const result = git(body.create ? ['checkout', '-b', body.branch] : ['checkout', body.branch, '--'], cwd);
return c.json({ success: true, message: result || `Switched to ${body.branch}` });
} catch (err: any) {
return c.json({ error: err.message }, 500);
@@ -146,9 +172,10 @@ ide.get('/api/git/diff', (c) => {
const cwd = getWorkspaceRoot();
const staged = c.req.query('staged') === 'true';
const filePath = c.req.query('file');
- let cmd = staged ? 'diff --cached' : 'diff';
- if (filePath) cmd += ` -- ${filePath}`;
- const diff = git(cmd, cwd);
+ if (filePath && !isInsideWorkspace(filePath, cwd)) return c.json({ error: 'File outside workspace' }, 403);
+ const args = staged ? ['diff', '--cached'] : ['diff'];
+ if (filePath) args.push('--', filePath);
+ const diff = git(args, cwd);
return c.json({ diff });
} catch (err: any) {
return c.json({ error: err.message }, 500);
@@ -159,8 +186,9 @@ ide.get('/api/git/diff', (c) => {
ide.get('/api/git/log', (c) => {
try {
const cwd = getWorkspaceRoot();
- const count = Math.min(parseInt(c.req.query('count') || '20', 10), 100);
- const raw = git(`log --oneline --format="%H||%h||%an||%ae||%ar||%s" -${count}`, cwd);
+ const parsed = parseInt(c.req.query('count') || '20', 10);
+ const count = Number.isFinite(parsed) ? Math.max(1, Math.min(parsed, 100)) : 20;
+ const raw = git(['log', '--format=%H||%h||%an||%ae||%ar||%s', `-n${count}`], cwd);
const commits = raw.split('\n').filter(Boolean).map(line => {
const [hash, short, author, email, date, ...msgParts] = line.split('||');
return { hash, short, author, email, date, message: msgParts.join('||') };
@@ -178,9 +206,9 @@ ide.post('/api/git/stage', async (c) => {
if (!body.files?.length) return c.json({ error: 'files array required' }, 400);
const cwd = getWorkspaceRoot();
for (const f of body.files) {
- if (!isInsideWorkspace(f)) return c.json({ error: `File outside workspace: ${f}` }, 403);
+ if (typeof f !== 'string' || !isInsideWorkspace(f, cwd)) return c.json({ error: `File outside workspace: ${f}` }, 403);
}
- git(`add ${body.files.map(f => `"${f}"`).join(' ')}`, cwd);
+ git(['add', '--', ...body.files], cwd);
return c.json({ success: true });
} catch (err: any) {
return c.json({ error: err.message }, 500);
@@ -193,7 +221,10 @@ ide.post('/api/git/unstage', async (c) => {
const body = await c.req.json<{ files: string[] }>();
if (!body.files?.length) return c.json({ error: 'files array required' }, 400);
const cwd = getWorkspaceRoot();
- git(`reset HEAD ${body.files.map(f => `"${f}"`).join(' ')}`, cwd);
+ for (const f of body.files) {
+ if (typeof f !== 'string' || !isInsideWorkspace(f, cwd)) return c.json({ error: `File outside workspace: ${f}` }, 403);
+ }
+ git(['reset', 'HEAD', '--', ...body.files], cwd);
return c.json({ success: true });
} catch (err: any) {
return c.json({ error: err.message }, 500);
@@ -207,7 +238,7 @@ ide.post('/api/git/commit', async (c) => {
if (!body.message?.trim()) return c.json({ error: 'message is required' }, 400);
const cwd = getWorkspaceRoot();
const fullMessage = `${body.message.trim()}\n\nCo-authored-by: Mercury <[email protected]>`;
- const result = git(`commit -m "${fullMessage.replace(/"/g, '\\"')}"`, cwd);
+ const result = git(['commit', '-m', fullMessage], cwd);
return c.json({ success: true, message: result });
} catch (err: any) {
return c.json({ error: err.message }, 500);
@@ -220,10 +251,13 @@ ide.post('/api/git/push', async (c) => {
const body = await c.req.json<{ remote?: string; branch?: string; setUpstream?: boolean }>();
const cwd = getWorkspaceRoot();
const remote = body.remote || 'origin';
- let cmd = `push ${remote}`;
- if (body.branch) cmd += ` ${body.branch}`;
- if (body.setUpstream) cmd += ' -u';
- const result = git(cmd, cwd);
+ if (!isSafeRefName(remote)) return c.json({ error: 'Invalid remote name' }, 400);
+ if (body.branch !== undefined && body.branch !== '' && !isSafeRefName(body.branch)) return c.json({ error: 'Invalid branch name' }, 400);
+ const args = ['push'];
+ if (body.setUpstream) args.push('-u');
+ args.push(remote);
+ if (body.branch) args.push(body.branch);
+ const result = git(args, cwd);
return c.json({ success: true, message: result || 'Pushed successfully' });
} catch (err: any) {
return c.json({ error: err.message }, 500);
@@ -234,7 +268,7 @@ ide.post('/api/git/push', async (c) => {
ide.post('/api/git/pull', async (c) => {
try {
const cwd = getWorkspaceRoot();
- const result = git('pull', cwd);
+ const result = git(['pull'], cwd);
return c.json({ success: true, message: result || 'Already up to date.' });
} catch (err: any) {
return c.json({ error: err.message }, 500);
@@ -251,7 +285,7 @@ ide.put('/api/workspace/file', async (c) => {
if (!body.path) return c.json({ error: 'path is required' }, 400);
const root = getWorkspaceRoot();
const fullPath = resolve(root, body.path);
- if (!fullPath.startsWith(root)) {
+ if (!isInsideWorkspace(fullPath, root)) {
return c.json({ error: 'Path outside workspace' }, 403);
}
writeFileSync(fullPath, body.content, 'utf8');
@@ -272,7 +306,7 @@ ide.post('/api/terminal/exec', async (c) => {
const root = getWorkspaceRoot();
const cwd = body.cwd ? resolve(root, body.cwd) : root;
- if (!cwd.startsWith(root)) {
+ if (!isInsideWorkspace(cwd, root)) {
return c.json({ error: 'cwd outside workspace' }, 403);
}
@@ -308,12 +342,12 @@ ide.get('/api/workspace/info', (c) => {
let remoteUrl = '';
try {
- branch = git('rev-parse --abbrev-ref HEAD', cwd);
+ branch = git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd);
isGit = true;
} catch {}
try {
- remoteUrl = git('remote get-url origin', cwd);
+ remoteUrl = git(['remote', 'get-url', 'origin'], cwd);
} catch {}
// Detect project type
@@ -355,10 +389,10 @@ ide.post('/api/git/generate-commit-message', async (c) => {
// Get staged diff
let diff = '';
try {
- diff = git('diff --cached --stat', cwd);
+ diff = git(['diff', '--cached', '--stat'], cwd);
if (!diff.trim()) {
// Fallback to unstaged diff if nothing staged
- diff = git('diff --stat', cwd);
+ diff = git(['diff', '--stat'], cwd);
}
} catch {}
@@ -369,9 +403,9 @@ ide.post('/api/git/generate-commit-message', async (c) => {
// Also get the detailed diff (limited)
let detailedDiff = '';
try {
- detailedDiff = git('diff --cached', cwd);
+ detailedDiff = git(['diff', '--cached'], cwd);
if (!detailedDiff.trim()) {
- detailedDiff = git('diff', cwd);
+ detailedDiff = git(['diff'], cwd);
}
} catch {}