fix(security): daily scan 2026-11-06 — 2 fixes (#4846)

* fix(security): path traversal in hooks_build-agents

outputDir passed validatePath, which allows absolute paths, and format was
spliced unvalidated into each config file name, so an MCP caller could make
the tool create directories and overwrite files outside the project.
Contain the real output directory in the real project root and restrict
format to yaml/json.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MfPHVKUis3yTcrY8a2cNer

* fix(security): argv option injection and URL scheme check in browser adapter

AgentBrowserAdapter passed caller values (selectors, text, URLs, paths)
straight into agent-browser's argv, which parses options anywhere, so a
value beginning with -- was read as an option. open/newTab also accepted
any URL scheme, letting the exported browser MCP tools read local files.
Reject unexpected options in command argv and allow only web URLs,
mirroring the CLI's browser-argv guard.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01MfPHVKUis3yTcrY8a2cNer

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
rUvandClaude authored and GitHub committed 2026-11-06 07:10:38 -06:00
1 parent 206e59259a
commit bccf17adfa
5 files changed
+135 -3

No files matched your search

@@ -19,6 +19,7 @@ import type {
BrowserSession,
NetworkRouteInput,
} from '../domain/types.js';
import { browserUrlError, commandArgvError } from './argv-guard.js';
export interface AgentBrowserAdapterOptions {
session?: string;
@@ -55,6 +56,9 @@ export class AgentBrowserAdapter {
private async exec<T = unknown>(args: string[], jsonOutput = true): Promise<ActionResult<T>> {
const startTime = Date.now();
// Caller values must not be parsed as agent-browser options.
const argvError = commandArgvError(args);
if (argvError) return { success: false, error: argvError, duration: 0 };
const fullArgs = [
'--session', this.session,
...(this.timeout ? ['--timeout', String(this.timeout)] : []),
@@ -106,6 +110,8 @@ export class AgentBrowserAdapter {
// ===========================================================================
async open(input: OpenInput): Promise<ActionResult> {
const urlError = browserUrlError(input.url);
if (urlError) return { success: false, error: urlError, duration: 0 };
const args = ['open', input.url];
if (input.waitUntil) args.push('--wait', input.waitUntil);
if (input.headers) args.push('--headers', JSON.stringify(input.headers));
@@ -461,7 +467,11 @@ export class AgentBrowserAdapter {
async newTab(url?: string): Promise<ActionResult> {
const args = ['tab', 'new'];
if (url) args.push(url);
if (url) {
const urlError = browserUrlError(url);
if (urlError) return { success: false, error: urlError, duration: 0 };
args.push(url);
}
return this.exec(args);
}
@@ -0,0 +1,52 @@
/**
* @claude-flow/browser - agent-browser argv guard
*
* agent-browser reads its own options anywhere in argv, so a caller value
* (selector, typed text, URL, path) that starts with "--" would be parsed
* as an option such as --executable-path. Values reach the adapter from MCP
* tool input, so command argv may only carry the options the adapter itself
* emits. Mirrors @claude-flow/cli's browser-argv.ts.
*/
/** Options the adapter emits after a subcommand. Global options (--session, --executable-path, ...) are excluded. */
const COMMAND_FLAGS: ReadonlySet<string> = new Set([
'--abort', '--body', '--button', '--clear', '--click-count', '--delay',
'--exact', '--filter', '--fn', '--force', '--full', '--headers', '--load',
'--name', '--status', '--text', '--url', '--wait', '--with-deps',
'-c', '-d', '-i', '-s',
]);
/** Returns an error when command argv contains an option the adapter did not mean to pass. */
export function commandArgvError(args: readonly unknown[]): string | null {
for (const arg of args) {
if (typeof arg !== 'string') return 'browser command arguments must be strings';
if (arg.startsWith('--')) {
const name = arg.split('=', 1)[0];
if (!COMMAND_FLAGS.has(name)) return `value must not start with "--": ${JSON.stringify(arg.slice(0, 80))}`;
} else if (/^-[A-Za-z]$/.test(arg) && !COMMAND_FLAGS.has(arg)) {
return `value must not be an option: ${JSON.stringify(arg)}`;
}
}
return null;
}
/**
* Returns an error when a navigation target is not a web page. Page text is
* returned to the caller, so file:, view-source:, chrome:, data: and similar
* schemes would read local files or browser state. Accepts http(s),
* about:blank, and scheme-less targets such as example.com/path or
* localhost:3000.
*/
export function browserUrlError(value: unknown): string | null {
if (typeof value !== 'string' || !value.trim()) return 'url must be a non-empty string';
// Chromium drops tabs/newlines anywhere and trims leading control chars and spaces.
const url = value.replace(/[\t\n\r]/g, '').replace(/^[\u0000- ]+/, '');
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url);
if (!scheme) return null;
const name = scheme[1].toLowerCase();
if (name === 'http' || name === 'https') return null;
if (url.toLowerCase() === 'about:blank') return null;
// host:port with no scheme; host must be localhost or contain a dot.
if ((name === 'localhost' || name.includes('.')) && /^[a-z0-9.-]+:\d{1,5}(?:[/?#]|$)/i.test(url)) return null;
return `url scheme not allowed: ${JSON.stringify(name.slice(0, 40))} (use http or https)`;
}
@@ -46,6 +46,46 @@ describe('AgentBrowserAdapter', () => {
});
});
describe('argv and URL guards', () => {
it('refuses a caller value that would be parsed as an agent-browser option', async () => {
const result = await adapter.fill({ target: '--executable-path=/tmp/x', value: 'v' } as any);
expect(result.success).toBe(false);
expect(result.error).toMatch(/must not start with "--"/);
expect(mockExecSync).not.toHaveBeenCalled();
});
it('refuses a single-letter option smuggled in as a value', async () => {
const result = await adapter.click({ target: '-x' } as any);
expect(result.success).toBe(false);
expect(mockExecSync).not.toHaveBeenCalled();
});
it.each(['file:///etc/passwd', 'view-source:https://example.com', 'chrome://settings', 'data:text/html,hi', ' \tfile:///etc/hosts'])(
'refuses to open non-web URL %s',
async (url) => {
expect((await adapter.open({ url })).success).toBe(false);
expect((await adapter.newTab(url)).success).toBe(false);
expect(mockExecSync).not.toHaveBeenCalled();
},
);
it.each(['https://example.com', 'http://localhost:3000/app', 'example.com/path', 'localhost:8080', 'about:blank'])(
'still opens web URL %s',
async (url) => {
mockExecSync.mockReturnValue(JSON.stringify({ success: true }));
expect((await adapter.open({ url })).success).toBe(true);
expect(mockExecSync).toHaveBeenCalled();
},
);
it('still passes the adapter\'s own command flags', async () => {
mockExecSync.mockReturnValue(JSON.stringify({ success: true }));
const result = await adapter.open({ url: 'https://example.com', waitUntil: 'load' } as any);
expect(result.success).toBe(true);
expect(mockExecSync.mock.calls[0][1]).toContain('--wait');
});
});
describe('navigation', () => {
it('should open a URL', async () => {
mockExecSync.mockReturnValue(JSON.stringify({
@@ -6,7 +6,7 @@
* - reported patternsApplied = agents * 3 although no pretrain data is read.
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { existsSync, mkdtempSync, readdirSync } from 'node:fs';
import { existsSync, mkdtempSync, readdirSync, symlinkSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -55,6 +55,25 @@ describe('hooks_build-agents (#4558)', () => {
expect(r._note).toMatch(/templates/);
});
it('rejects an absolute outputDir outside the project without writing', async () => {
const r = await build({ outputDir: join(elsewhere, 'out') });
expect(r).toMatchObject({ success: false, error: expect.stringMatching(/inside the project/) });
expect(existsSync(join(elsewhere, 'out'))).toBe(false);
});
it('rejects an outputDir that escapes the project through a symlink', async () => {
symlinkSync(elsewhere, join(project, 'link'));
const r = await build({ outputDir: 'link/out' });
expect(r).toMatchObject({ success: false, error: expect.stringMatching(/inside the project/) });
expect(existsSync(join(elsewhere, 'out'))).toBe(false);
});
it('rejects a format other than yaml/json (it is spliced into file names)', async () => {
const r = await build({ format: 'json/../../x' });
expect(r).toMatchObject({ success: false, error: expect.stringMatching(/format/) });
expect(existsSync(join(project, 'agents'))).toBe(false);
});
it('still honours an explicit absolute outputDir (control)', async () => {
const out = join(project, 'custom');
const r = await build({ outputDir: out, format: 'json', focus: 'security' });
@@ -2436,8 +2436,19 @@ export const hooksBuildAgents: MCPTool = {
if (!v.valid) return { success: false, error: v.error };
}
const outputDir = resolve(getProjectCwd(), (params.outputDir as string) || './agents');
// validatePath allows absolute paths, so keep the real output dir inside
// the real project root (CWE-22/59): configs are only ever project files.
let realProjectRoot: string;
try { realProjectRoot = nodeFs.realpathSync(getProjectCwd()); } catch { realProjectRoot = getProjectCwd(); }
if (!isInsideRealRoot(realProjectRoot, outputDir)) {
return { success: false, error: 'outputDir must be inside the project directory' };
}
const focus = (params.focus as string) || 'all';
const format = (params.format as string) || 'yaml';
// format is spliced into each file name; only the two supported formats.
const format = params.format === undefined ? 'yaml' : params.format;
if (format !== 'yaml' && format !== 'json') {
return { success: false, error: 'format must be "yaml" or "json"' };
}
const persist = params.persist !== false; // Default to true
const agents = [