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): git helpers use argv exec with scope checks; find -exec regression test

Salman Qureshib0ba43c68c90
diff --git a/src/capabilities/git/git-diff.ts b/src/capabilities/git/git-diff.ts
index 8dab6b02..46a58eb9 100644
--- a/src/capabilities/git/git-diff.ts
+++ b/src/capabilities/git/git-diff.ts
@@ -1,8 +1,10 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
-import { execSync } from 'node:child_process';
+import { execFileSync } from 'node:child_process';
+import type { PermissionManager } from '../permissions.js';
+import { checkGitReadPath } from './git-path.js';
-export function createGitDiffTool(getCwd: () => string) {
+export function createGitDiffTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Show changes between commits, commit and working tree, etc. Shows what has been modified.',
inputSchema: zodSchema(z.object({
@@ -10,11 +12,17 @@ export function createGitDiffTool(getCwd: () => string) {
staged: z.boolean().optional().describe('Show staged changes (cached) instead of unstaged'),
})),
execute: async ({ path, staged }) => {
+ const args = ['diff'];
+ if (staged) args.push('--cached');
+ if (path) {
+ // Model-chosen path: read-scope check first, then a single argv
+ // element after `--` so it can never be parsed as an option.
+ const check = await checkGitReadPath(permissions, getCwd, path);
+ if (check.error) return check.error;
+ args.push('--', path);
+ }
try {
- let cmd = 'git diff';
- if (staged) cmd += ' --cached';
- if (path) cmd += ` -- "${path}"`;
- const result = execSync(cmd, { encoding: 'utf-8', timeout: 30000, cwd: getCwd() });
+ const result = execFileSync('git', args, { encoding: 'utf-8', timeout: 30000, cwd: getCwd() });
if (!result.trim()) return 'No differences found.';
const truncated = result.length > 15000 ? result.slice(0, 15000) + '\n... (truncated)' : result;
return truncated;
@@ -23,4 +31,4 @@ export function createGitDiffTool(getCwd: () => string) {
}
},
});
-}
\ No newline at end of file
+}
diff --git a/src/capabilities/git/git-helpers.test.ts b/src/capabilities/git/git-helpers.test.ts
new file mode 100644
index 00000000..5c30a85b
--- /dev/null
+++ b/src/capabilities/git/git-helpers.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { resolve } from 'node:path';
+
+// Regression tests for ROADMAP P0.4: the git helpers used to build a shell
+// string from a model-chosen path and run it through execSync with no
+// permission check. They must now (a) hand the path to git as one argv
+// element via execFileSync and (b) refuse out-of-scope paths before exec.
+
+vi.mock('node:child_process', () => ({
+ execFileSync: vi.fn(() => ''),
+ execSync: vi.fn(() => { throw new Error('execSync must not be used by git helpers'); }),
+}));
+
+import { execFileSync, execSync } from 'node:child_process';
+import { createGitStatusTool } from './git-status.js';
+import { createGitLogTool } from './git-log.js';
+import { createGitDiffTool } from './git-diff.js';
+import { createGitPushTool } from './git-push.js';
+import type { PermissionManager } from '../permissions.js';
+
+const CWD = '/repo';
+const INJECTED = '/tmp/x"; echo pwned; "';
+
+function fakePermissions(opts: { readAllowed: boolean; shellAllowed?: boolean }) {
+ return {
+ checkFsAccess: vi.fn(async () => ({ allowed: opts.readAllowed, reason: opts.readAllowed ? undefined : 'out of scope' })),
+ checkShellCommand: vi.fn(async () => ({ allowed: opts.shellAllowed ?? true, needsApproval: false })),
+ } as unknown as PermissionManager & { checkFsAccess: ReturnType<typeof vi.fn>; checkShellCommand: ReturnType<typeof vi.fn> };
+}
+
+const run = (t: any, input: Record<string, unknown>) => (t.execute as any)(input, { toolCallId: 't', messages: [] });
+
+beforeEach(() => {
+ vi.mocked(execFileSync).mockClear();
+ vi.mocked(execFileSync).mockImplementation(() => '' as any);
+ vi.mocked(execSync).mockClear();
+});
+
+describe('git helpers pass the path as a single argv element (no shell)', () => {
+ it('git_status: -C <path> is one argv element', async () => {
+ const permissions = fakePermissions({ readAllowed: true });
+ await run(createGitStatusTool(permissions, () => CWD), { path: INJECTED });
+
+ expect(execSync).not.toHaveBeenCalled();
+ expect(execFileSync).toHaveBeenCalledTimes(1);
+ const [file, args, opts] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[], any];
+ expect(file).toBe('git');
+ expect(args).toEqual(['-C', resolve(INJECTED), 'status', '--porcelain']);
+ expect(opts.cwd).toBe(CWD);
+ expect(opts.shell).toBeUndefined();
+ });
+
+ it('git_log: path follows `--` as one argv element', async () => {
+ const permissions = fakePermissions({ readAllowed: true });
+ await run(createGitLogTool(permissions, () => CWD), { path: INJECTED, count: 5 });
+
+ expect(execSync).not.toHaveBeenCalled();
+ const [file, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];
+ expect(file).toBe('git');
+ expect(args).toEqual(['log', '--oneline', '--decorate', '-5', '--', INJECTED]);
+ });
+
+ it('git_diff: path follows `--` as one argv element', async () => {
+ const permissions = fakePermissions({ readAllowed: true });
+ await run(createGitDiffTool(permissions, () => CWD), { path: INJECTED, staged: true });
+
+ expect(execSync).not.toHaveBeenCalled();
+ const [file, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];
+ expect(file).toBe('git');
+ expect(args).toEqual(['diff', '--cached', '--', INJECTED]);
+ });
+
+ it('git_push: remote and branch are argv elements, and options are refused', async () => {
+ const permissions = fakePermissions({ readAllowed: true, shellAllowed: true });
+ const push = createGitPushTool(permissions, () => CWD);
+
+ await run(push, { remote: 'origin; echo pwned', branch: 'main' });
+ expect(execSync).not.toHaveBeenCalled();
+ const [file, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];
+ expect(file).toBe('git');
+ expect(args).toEqual(['push', 'origin; echo pwned', 'main']);
+
+ vi.mocked(execFileSync).mockClear();
+ const result = await run(push, { remote: '--receive-pack=echo pwned', branch: 'main' });
+ expect(result).toMatch(/must be names/);
+ expect(execFileSync).not.toHaveBeenCalled();
+ });
+
+ it('git_status without a path runs plain `git status --porcelain` and skips the scope check', async () => {
+ const permissions = fakePermissions({ readAllowed: false });
+ await run(createGitStatusTool(permissions, () => CWD), {});
+ expect(permissions.checkFsAccess).not.toHaveBeenCalled();
+ const [, args] = vi.mocked(execFileSync).mock.calls[0] as unknown as [string, string[]];
+ expect(args).toEqual(['status', '--porcelain']);
+ });
+});
+
+describe('git helpers reject out-of-scope paths before any exec', () => {
+ const OUTSIDE = '/etc/secret';
+ const DENIED = /^Error: Permission denied for read access to \/etc\/secret\. Use the approve_scope tool/;
+
+ it.each([
+ ['git_status', (p: PermissionManager) => createGitStatusTool(p, () => CWD), { path: OUTSIDE }],
+ ['git_log', (p: PermissionManager) => createGitLogTool(p, () => CWD), { path: OUTSIDE }],
+ ['git_diff', (p: PermissionManager) => createGitDiffTool(p, () => CWD), { path: OUTSIDE }],
+ ])('%s denies with the read_file-style message and never execs', async (_name, make, input) => {
+ const permissions = fakePermissions({ readAllowed: false });
+ const result = await run(make(permissions), input);
+
+ expect(result).toMatch(DENIED);
+ expect(permissions.checkFsAccess).toHaveBeenCalledWith(OUTSIDE, 'read');
+ expect(execFileSync).not.toHaveBeenCalled();
+ expect(execSync).not.toHaveBeenCalled();
+ });
+
+ it('resolves relative paths against the tool cwd before checking scope', async () => {
+ const permissions = fakePermissions({ readAllowed: false });
+ await run(createGitLogTool(permissions, () => CWD), { path: '../outside' });
+ expect(permissions.checkFsAccess).toHaveBeenCalledWith('/outside', 'read');
+ expect(execFileSync).not.toHaveBeenCalled();
+ });
+
+ it('git_push denies before exec when the shell permission check fails', async () => {
+ const permissions = fakePermissions({ readAllowed: true, shellAllowed: false });
+ const result = await run(createGitPushTool(permissions, () => CWD), {});
+ expect(result).toMatch(/^Error:/);
+ expect(permissions.checkShellCommand).toHaveBeenCalledWith('git push origin');
+ expect(execFileSync).not.toHaveBeenCalled();
+ });
+});
+
+describe('output format is unchanged', () => {
+ it('git_status reports a clean tree, git_log/git_diff report empty results', async () => {
+ const permissions = fakePermissions({ readAllowed: true });
+ expect(await run(createGitStatusTool(permissions, () => CWD), {})).toBe('Working tree clean — no changes.');
+ expect(await run(createGitLogTool(permissions, () => CWD), {})).toBe('No commits found.');
+ expect(await run(createGitDiffTool(permissions, () => CWD), {})).toBe('No differences found.');
+
+ // The pre-existing behaviour trims the whole result (including the
+ // leading porcelain status column); keep it byte-for-byte identical.
+ vi.mocked(execFileSync).mockImplementation(() => ' M src/a.ts\n?? new.ts\n' as any);
+ expect(await run(createGitStatusTool(permissions, () => CWD), {})).toBe('M src/a.ts\n?? new.ts');
+ });
+
+ it('surfaces git stderr as an Error line', async () => {
+ const permissions = fakePermissions({ readAllowed: true });
+ vi.mocked(execFileSync).mockImplementation(() => { throw Object.assign(new Error('boom'), { stderr: 'fatal: not a git repository\n' }); });
+ expect(await run(createGitDiffTool(permissions, () => CWD), {})).toBe('Error: fatal: not a git repository');
+ });
+});
diff --git a/src/capabilities/git/git-log.ts b/src/capabilities/git/git-log.ts
index 38f8d5aa..fef5c44f 100644
--- a/src/capabilities/git/git-log.ts
+++ b/src/capabilities/git/git-log.ts
@@ -1,8 +1,10 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
-import { execSync } from 'node:child_process';
+import { execFileSync } from 'node:child_process';
+import type { PermissionManager } from '../permissions.js';
+import { checkGitReadPath } from './git-path.js';
-export function createGitLogTool(getCwd: () => string) {
+export function createGitLogTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Show commit logs. Returns recent commit history with hash, author, date, and message.',
inputSchema: zodSchema(z.object({
@@ -10,11 +12,17 @@ export function createGitLogTool(getCwd: () => string) {
path: z.string().optional().describe('File or directory to show log for'),
})),
execute: async ({ count, path }) => {
+ const n = Math.max(1, Math.floor(count ?? 10));
+ const args = ['log', '--oneline', '--decorate', `-${n}`];
+ if (path) {
+ // Model-chosen path: read-scope check first, then a single argv
+ // element after `--` so it can never be parsed as an option.
+ const check = await checkGitReadPath(permissions, getCwd, path);
+ if (check.error) return check.error;
+ args.push('--', path);
+ }
try {
- const n = count ?? 10;
- let cmd = `git log --oneline --decorate -${n}`;
- if (path) cmd += ` -- "${path}"`;
- const result = execSync(cmd, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });
+ const result = execFileSync('git', args, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });
if (!result.trim()) return 'No commits found.';
return result.trim();
} catch (err: any) {
@@ -22,4 +30,4 @@ export function createGitLogTool(getCwd: () => string) {
}
},
});
-}
\ No newline at end of file
+}
diff --git a/src/capabilities/git/git-path.ts b/src/capabilities/git/git-path.ts
new file mode 100644
index 00000000..af949f38
--- /dev/null
+++ b/src/capabilities/git/git-path.ts
@@ -0,0 +1,35 @@
+import { resolve, isAbsolute } from 'node:path';
+import type { PermissionManager } from '../permissions.js';
+
+/**
+ * Resolve a model-chosen path against the tool cwd and run it through the
+ * same filesystem read check `read_file` / `list_dir` use, so a git helper
+ * can never inspect a tree the user has not approved for reading.
+ *
+ * Returns the resolved path on success, or the same denial message
+ * `read_file` returns so the model learns to call `approve_scope`.
+ */
+export async function checkGitReadPath(
+ permissions: PermissionManager,
+ getCwd: () => string,
+ path: string,
+): Promise<{ resolved: string; error?: undefined } | { resolved: string; error: string }> {
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
+ const check = await permissions.checkFsAccess(resolved, 'read');
+ if (!check.allowed) {
+ const parentDir = resolve(resolved, '..');
+ return {
+ resolved,
+ error: `Error: Permission denied for read access to ${resolved}. Use the approve_scope tool with path="${parentDir}" and mode="read" to request access from the user.`,
+ };
+ }
+ return { resolved };
+}
+
+/**
+ * Git positional arguments must never be allowed to masquerade as options
+ * (`--receive-pack=…`, `--upload-pack=…`, `--exec=…` run arbitrary programs).
+ */
+export function looksLikeGitOption(value: string): boolean {
+ return value.startsWith('-');
+}
diff --git a/src/capabilities/git/git-push.ts b/src/capabilities/git/git-push.ts
index 68533d28..5eb4d53c 100644
--- a/src/capabilities/git/git-push.ts
+++ b/src/capabilities/git/git-push.ts
@@ -1,7 +1,8 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
-import { execSync } from 'node:child_process';
+import { execFileSync } from 'node:child_process';
import type { PermissionManager } from '../permissions.js';
+import { looksLikeGitOption } from './git-path.js';
export function createGitPushTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
@@ -11,18 +12,25 @@ export function createGitPushTool(permissions: PermissionManager, getCwd: () =>
branch: z.string().optional().describe('Branch name (default: current branch)'),
})),
execute: async ({ remote, branch }) => {
- const cmd = `git push ${remote || 'origin'} ${branch || ''}`.trim();
+ const remoteName = remote || 'origin';
+ // Positional args only: `--receive-pack=…` or `--exec=…` smuggled in as
+ // a "remote" or "branch" would run an arbitrary program.
+ if (looksLikeGitOption(remoteName) || (branch && looksLikeGitOption(branch))) {
+ return 'Error: remote and branch must be names, not git options.';
+ }
+ const args = ['push', remoteName, ...(branch ? [branch] : [])];
+ const cmd = `git ${args.join(' ')}`;
const check = await permissions.checkShellCommand(cmd);
if (!check.allowed) {
return `Error: ${check.reason}`;
}
try {
- const result = execSync(cmd, { encoding: 'utf-8', timeout: 60000, cwd: getCwd() });
+ const result = execFileSync('git', args, { encoding: 'utf-8', timeout: 60000, cwd: getCwd() });
return result.trim() || 'Pushed successfully.';
} catch (err: any) {
return `Error: ${err.stderr?.trim() || err.message}`;
}
},
});
-}
\ No newline at end of file
+}
diff --git a/src/capabilities/git/git-status.ts b/src/capabilities/git/git-status.ts
index 4e49de1d..6d260676 100644
--- a/src/capabilities/git/git-status.ts
+++ b/src/capabilities/git/git-status.ts
@@ -1,17 +1,26 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
-import { execSync } from 'node:child_process';
+import { execFileSync } from 'node:child_process';
+import type { PermissionManager } from '../permissions.js';
+import { checkGitReadPath } from './git-path.js';
-export function createGitStatusTool(getCwd: () => string) {
+export function createGitStatusTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Show the working tree status. Returns staged, unstaged, and untracked files.',
inputSchema: zodSchema(z.object({
path: z.string().optional().describe('Path to check (defaults to current directory)'),
})),
execute: async ({ path }) => {
+ // The path is model-chosen: it must pass the read-scope check and reach
+ // git as a single argv element, never interpolated into a shell string.
+ const args = ['status', '--porcelain'];
+ if (path) {
+ const check = await checkGitReadPath(permissions, getCwd, path);
+ if (check.error) return check.error;
+ args.unshift('-C', check.resolved);
+ }
try {
- const cmd = path ? `git -C "${path}" status --porcelain` : 'git status --porcelain';
- const result = execSync(cmd, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });
+ const result = execFileSync('git', args, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });
if (!result.trim()) return 'Working tree clean — no changes.';
return result.trim();
} catch (err: any) {
@@ -19,4 +28,4 @@ export function createGitStatusTool(getCwd: () => string) {
}
},
});
-}
\ No newline at end of file
+}
diff --git a/src/capabilities/permissions.test.ts b/src/capabilities/permissions.test.ts
index 0b5555ad..6f98bb26 100644
--- a/src/capabilities/permissions.test.ts
+++ b/src/capabilities/permissions.test.ts
@@ -190,10 +190,15 @@ describe('PermissionManager remote safety', () => {
await expect(permissions.checkShellCommand('echo poisoned > AGENTS.md')).resolves.toMatchObject({ allowed: false });
await expect(permissions.checkShellCommand('echo poisoned>AGENTS.md')).resolves.toMatchObject({ allowed: false });
await expect(permissions.checkShellCommand('find . -delete')).resolves.toMatchObject({ allowed: false });
+ // find -exec/-execdir launch a subprocess — the advisory payload from
+ // issues #71/#77/#101 (and #110), minus the redirection so this exercises
+ // the find-flag rule on its own rather than the redirection rule.
+ await expect(permissions.checkShellCommand("find . -maxdepth 0 -exec sh -c 'id' ';'")).resolves.toMatchObject({ allowed: false });
+ await expect(permissions.checkShellCommand('find . -execdir touch canary \\;')).resolves.toMatchObject({ allowed: false });
await expect(permissions.checkShellCommand('git branch -D protected')).resolves.toMatchObject({ allowed: false });
await expect(permissions.checkShellCommand('git branch --delete protected')).resolves.toMatchObject({ allowed: false });
await expect(permissions.checkShellCommand('git branch new-branch')).resolves.toMatchObject({ allowed: false });
- expect(ask).toHaveBeenCalledTimes(6);
+ expect(ask).toHaveBeenCalledTimes(8);
});
it('does not classify wc --files0-from as a safe read (indirect path deref)', async () => {
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index d70c0336..75bdb1cf 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -241,9 +241,9 @@ export class CapabilityRegistry {
}
if (manifest.capabilities.git?.enabled) {
- this.tools.git_status = createGitStatusTool(() => this.getCwd());
- this.tools.git_diff = createGitDiffTool(() => this.getCwd());
- this.tools.git_log = createGitLogTool(() => this.getCwd());
+ this.tools.git_status = createGitStatusTool(this.permissions, () => this.getCwd());
+ this.tools.git_diff = createGitDiffTool(this.permissions, () => this.getCwd());
+ this.tools.git_log = createGitLogTool(this.permissions, () => this.getCwd());
this.tools.git_add = createGitAddTool(this.permissions, () => this.getCwd());
this.tools.git_commit = createGitCommitTool(this.permissions, () => this.getCwd());
this.tools.git_push = createGitPushTool(this.permissions, () => this.getCwd());