From 196b357057b867013088f700badad38cfbe07668 Mon Sep 17 00:00:00 2001 From: Matthieu Riegler Date: Sun, 22 Nov 2026 14:03:37 +0000 Subject: [PATCH] fix(@angular/cli): validate path options against MCP roots in host execution Ensure `createRootRestrictedHost` validates path-bearing CLI flags passed to `executeNgCommand` and `startNgProcess` against the active allowed MCP roots, instead of checking only the effective `cwd`. Previously, the `run_target` MCP tool forwarded client-supplied options directly to the spawned `ng` process (for example, `--output-path=/outside/root`). Because builders such as `@angular/build:application` resolve `outputPath` via `path.resolve(workspaceRoot, outputPath)` and recursively clear it via `deleteOutputDir`, an out-of-root path escaped MCP root confinement. Changes: - Validate path-bearing, glob-based, and output-directory CLI flags (both `--flag=value` and `--flag value`, camelCase/kebab-case/snake_case, negation, dot-notation, `--runner-args`, and passthrough args) in `createRootRestrictedHost.executeNgCommand` and `startNgProcess`. - Reject output directory flags (`--output-path`, `--output-dir`, etc.) that resolve outside allowed roots or equal/are an ancestor of the workspace directory or any allowed root. - Preserve non-filesystem flags such as `--base-href`, `--deploy-url`, `--serve-path`, `--route`, `--filter`, and boolean literals on boolean-or-path options. - Harden canonical path resolution in `createRootRestrictedHost` to resolve dangling symlinks, handle intermediate symlinks prior to `..` segments, and check exact path separator boundaries. - Tighten `serializeOptions` key validation to require a leading alphanumeric character, reject null bytes in string option values, and normalize `excludeKeys` comparison. - Propagate non-`CommandError` rejections (such as root access-denied errors) from the `run_target` target strategies instead of swallowing them as command failures. --- packages/angular/cli/src/commands/mcp/host.ts | 594 ++++++++++++++++-- .../angular/cli/src/commands/mcp/host_spec.ts | 355 ++++++++++- .../tools/run-target/build-target-strategy.ts | 5 + .../run-target/generic-target-strategy.ts | 5 + .../tools/run-target/options-serializer.ts | 23 +- .../run-target/options-serializer_spec.ts | 22 + .../mcp/tools/run-target/run-target_spec.ts | 111 +++- .../tools/run-target/unit-test-strategy.ts | 5 + 8 files changed, 1070 insertions(+), 50 deletions(-) diff --git a/packages/angular/cli/src/commands/mcp/host.ts b/packages/angular/cli/src/commands/mcp/host.ts index 6f3313640510..032c170fcee7 100644 --- a/packages/angular/cli/src/commands/mcp/host.ts +++ b/packages/angular/cli/src/commands/mcp/host.ts @@ -14,11 +14,17 @@ */ import { ChildProcess, spawn } from 'node:child_process'; -import { Stats, existsSync as nodeExistsSync, realpathSync } from 'node:fs'; +import { + Stats, + lstatSync, + existsSync as nodeExistsSync, + readlinkSync, + realpathSync, +} from 'node:fs'; import { glob as nodeGlob, readFile as nodeReadFile, stat } from 'node:fs/promises'; import { createRequire } from 'node:module'; import { createServer } from 'node:net'; -import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path'; import { createInterface } from 'node:readline'; import { stripVTControlCharacters } from 'node:util'; @@ -281,62 +287,566 @@ export const LocalWorkspaceHost: Host = { }, }; +const MAX_SYMLINK_DEPTH = 40; +const MAX_RUNNER_ARGS_DEPTH = 4; +const PATH_SEPARATOR_PATTERN = sep === '\\' ? /[\\/]+/ : /\/+/; +const DOT_DOT_SEGMENT_PATTERN = + sep === '\\' ? /(?:^|[\\/])\.\.(?:[\\/]|$)/ : /(?:^|\/)\.\.(?:\/|$)/; + +/** + * Normalized option names (lowercase, without hyphens/underscores) that represent non-filesystem + * values such as URL paths, booleans, enums, or Architect targets. + */ +const NON_PATH_OPTIONS = new Set([ + 'basehref', + 'browsertarget', + 'browserviewport', + 'browsers', + 'buildtarget', + 'configuration', + 'deleteoutputpath', + 'deployurl', + 'dumpvirtualfiles', + 'filter', + 'host', + 'outputhashing', + 'outputmode', + 'publichost', + 'route', + 'routes', + 'runner', + 'servepath', + 'servertarget', +]); + +/** + * Normalized option names representing output directories that builders may clean recursively + * before writing output files. + */ +const OUTPUT_DIR_OPTIONS = new Set([ + 'dest', + 'destination', + 'outdir', + 'outpath', + 'outputdir', + 'outputdirectory', + 'outputpath', +]); + +/** + * Normalized option names resolved relative to the effective output directory and workspace root. + */ +const OUTPUT_RELATIVE_OPTIONS = new Set(['outfile', 'resourcesoutputpath']); + +/** + * Normalized option names that accept filesystem paths. + */ +const EXACT_PATH_OPTIONS = new Set([ + 'appmodulebundle', + 'assets', + 'browser', + 'cachelocation', + 'config', + 'configdir', + 'configfile', + 'coveragedir', + 'coveragedirectory', + 'eslintconfig', + 'filereplacements', + 'index', + 'inputindexpath', + 'karmaconfig', + 'main', + 'ngswconfigpath', + 'out', + 'outputfile', + 'outputindexpath', + 'polyfills', + 'project', + 'providersfile', + 'proxyconfig', + 'routesfile', + 'runnerconfig', + 'scripts', + 'server', + 'serviceworker', + 'setupfiles', + 'sslcert', + 'sslkey', + 'styles', + 'tsconfig', + 'webpackconfig', + 'webworkertsconfig', +]); + +/** + * Normalized option names that accept glob patterns. + */ +const GLOB_PATH_OPTIONS = new Set([ + 'codecoverageexclude', + 'coverageexclude', + 'coverageinclude', + 'exclude', + 'include', + 'lintfilepatterns', +]); + +/** + * Normalized option names whose schema allows both boolean literals (`true`/`false`) and file paths. + */ +const BOOLEAN_OR_PATH_OPTIONS = new Set(['index', 'runnerconfig', 'server', 'serviceworker']); + +/** + * Word-boundary suffix tokens used to identify custom/third-party builder path options + * (e.g., `--eslint-config`, `--output-dir`, `--report-file`, `--cache-location`). + */ +const PATH_OPTION_SUFFIX_TOKENS = new Set([ + 'config', + 'dest', + 'destination', + 'dir', + 'directory', + 'dirs', + 'file', + 'files', + 'location', + 'path', + 'paths', + 'root', +]); + +type OptionPathKind = 'none' | 'path' | 'output-dir' | 'output-relative' | 'glob' | 'runner-args'; + +function normalizeOptionKey(key: string): string { + return key.toLowerCase().replace(/[-_]/g, ''); +} + +function getOptionKeyTokens(key: string): string[] { + return key + .replace(/([a-z0-9])([A-Z])/g, '$1-$2') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2') + .toLowerCase() + .split(/[-_]+/) + .filter(Boolean); +} + +function stripNegationPrefix(segment: string): string { + return segment.toLowerCase().startsWith('no-') ? segment.slice(3) : segment; +} + +function classifySingleKey(rawSegment: string): OptionPathKind { + const segment = stripNegationPrefix(rawSegment); + const compact = normalizeOptionKey(segment); + + if (!compact || NON_PATH_OPTIONS.has(compact)) { + return 'none'; + } + if (compact === 'runnerargs') { + return 'runner-args'; + } + if (OUTPUT_DIR_OPTIONS.has(compact)) { + return 'output-dir'; + } + if (OUTPUT_RELATIVE_OPTIONS.has(compact)) { + return 'output-relative'; + } + if (GLOB_PATH_OPTIONS.has(compact)) { + return 'glob'; + } + if (EXACT_PATH_OPTIONS.has(compact) || compact === 'o') { + return 'path'; + } + + const lastToken = getOptionKeyTokens(segment).at(-1); + if (lastToken && PATH_OPTION_SUFFIX_TOKENS.has(lastToken)) { + return 'path'; + } + + return 'none'; +} + +function classifyOptionKey(rawKey: string): OptionPathKind { + const dotSegments = rawKey.split('.'); + if (dotSegments.length === 1) { + return classifySingleKey(dotSegments[0]); + } + + const rootKind = classifySingleKey(dotSegments[0]); + const leafSegment = dotSegments.at(-1) ?? ''; + const leafCompact = normalizeOptionKey(leafSegment); + + if (rootKind === 'output-dir') { + return leafCompact === 'base' ? 'output-dir' : 'output-relative'; + } + + const leafKind = classifySingleKey(leafSegment); + if (leafKind !== 'none') { + return leafKind; + } + + if ( + rootKind !== 'none' || + leafCompact === 'entry' || + leafCompact === 'input' || + leafCompact === 'output' + ) { + return leafCompact === 'output' && normalizeOptionKey(dotSegments[0]) === 'index' + ? 'output-relative' + : 'path'; + } + + return 'none'; +} + +function isPathWithinRoot(root: string, targetPath: string): boolean { + const rel = relative(root, targetPath); + + return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); +} + +/** + * Resolves a path to its canonical real path, preserving trailing non-existent segments and + * following symlinks (including dangling symlinks) so targets outside allowed roots cannot bypass + * confinement. + */ +function resolveRealPath(targetPath: string, depth = 0): string { + if (targetPath.includes('\0')) { + throw new Error('Access denied: path contains a null byte.'); + } + if (depth > MAX_SYMLINK_DEPTH) { + throw new Error( + `Access denied: too many symbolic links encountered resolving '${targetPath}'.`, + ); + } + + const resolvedPath = resolve(targetPath); + try { + return realpathSync(resolvedPath); + } catch (e) { + if ((e as Error & { code?: string }).code !== 'ENOENT') { + throw e; + } + } + + const missingSegments: string[] = []; + let current = resolvedPath; + + while (true) { + try { + const entryStats = lstatSync(current); + if (entryStats.isSymbolicLink()) { + const linkTarget = readlinkSync(current); + const parentDir = realpathSync(dirname(current)); + const resolvedLink = resolveRealPath(resolve(parentDir, linkTarget), depth + 1); + + return join(resolvedLink, ...missingSegments); + } + + return join(realpathSync(current), ...missingSegments); + } catch (e) { + if ((e as Error & { code?: string }).code !== 'ENOENT') { + throw e; + } + + const parent = dirname(current); + if (parent === current) { + return resolvedPath; + } + + missingSegments.unshift(basename(current)); + current = parent; + } + } +} + +/** + * Walks an un-normalized path resolving intermediate symlinks BEFORE collapsing `..` segments, + * matching OS-level path resolution (e.g. catching `symlink/../secret` escaping via `symlink`). + */ +function resolvePathFollowingSymlinks(rawPath: string, realBaseDir: string): string { + let current: string; + let remainder: string; + + if (isAbsolute(rawPath)) { + const parsedRoot = parse(rawPath).root; + current = parsedRoot; + remainder = rawPath.slice(parsedRoot.length); + } else { + current = realBaseDir; + remainder = rawPath; + } + + const segments = remainder.split(PATH_SEPARATOR_PATTERN); + for (const segment of segments) { + if (!segment || segment === '.') { + continue; + } + if (segment === '..') { + current = dirname(current); + continue; + } + + current = join(current, segment); + try { + if (lstatSync(current).isSymbolicLink()) { + current = resolveRealPath(current); + } + } catch (e) { + if ((e as Error & { code?: string }).code !== 'ENOENT') { + throw e; + } + } + } + + return resolveRealPath(current); +} + function resolveRoots(roots: string[]): string[] { return roots.map((r) => { try { - return realpathSync(resolve(r)); + return resolveRealPath(r); } catch { return resolve(r); } }); } -export function createRootRestrictedHost( - baseHost: Host, - initialRoots: string[] = [process.cwd()], -): Host { - const defaultRoots = resolveRoots(initialRoots); - let roots = defaultRoots; +function isAllowedRealPath(roots: readonly string[], realPath: string): boolean { + return roots.some((root) => isPathWithinRoot(root, realPath)); +} - function checkPath(path: string) { - const resolvedPath = resolve(path); - let realPath: string; - try { - realPath = realpathSync(resolvedPath); - } catch (e) { - if ((e as Error & { code?: string }).code === 'ENOENT') { - // Path does not exist. Find the first existing ancestor. - let current = resolvedPath; - while (current) { - try { - realPath = realpathSync(current); +function assertRealPathAllowed( + roots: readonly string[], + targetPath: string, + errorLabel?: string, +): string { + const realPath = resolveRealPath(targetPath); + + if (!isAllowedRealPath(roots, realPath)) { + if (errorLabel) { + throw new Error(`Access denied: ${errorLabel} is outside allowed roots.`); + } + + throw new Error(`Access denied: path '${targetPath}' is outside allowed roots.`); + } + + return realPath; +} + +function validateOptionPathValue( + roots: readonly string[], + flag: string, + rawValue: string, + baseDir: string, + realBaseDir: string, +): { realPath: string; walkedPath: string | undefined } { + if (rawValue.includes('\0')) { + throw new Error(`Access denied: option '${flag}' contains a null byte.`); + } + + const label = `option '${flag}' path '${rawValue}'`; + const realPath = assertRealPathAllowed(roots, resolve(baseDir, rawValue), label); + + let walkedPath: string | undefined; + if (DOT_DOT_SEGMENT_PATTERN.test(rawValue)) { + walkedPath = resolvePathFollowingSymlinks(rawValue, realBaseDir); + if (!isAllowedRealPath(roots, walkedPath)) { + throw new Error(`Access denied: ${label} is outside allowed roots.`); + } + } + + return { realPath, walkedPath }; +} + +function assertNotWorkspaceOrRootAncestor( + roots: readonly string[], + flag: string, + rawValue: string, + candidatePath: string, + realCwd: string, +): void { + if (isPathWithinRoot(candidatePath, realCwd)) { + throw new Error( + `Access denied: option '${flag}' path '${rawValue}' must not be the workspace directory ` + + 'or a parent of it.', + ); + } + + if (roots.some((root) => isPathWithinRoot(candidatePath, root))) { + throw new Error( + `Access denied: option '${flag}' path '${rawValue}' must not be an allowed root directory ` + + 'or a parent of it.', + ); + } +} + +function validateGlobOptionValue( + roots: readonly string[], + flag: string, + pattern: string, + cwd: string, + realCwd: string, +): void { + if (pattern.includes('\0')) { + throw new Error(`Access denied: option '${flag}' contains a null byte.`); + } + + const normalized = pattern.startsWith('!') ? pattern.slice(1) : pattern; + if (!normalized) { + return; + } + + const label = `option '${flag}' pattern '${pattern}'`; + const firstWildcardIndex = normalized.search(/[*?[{]/); + const basePath = firstWildcardIndex >= 0 ? normalized.slice(0, firstWildcardIndex) : normalized; + + if (firstWildcardIndex >= 0) { + const wildcardTail = normalized.slice(firstWildcardIndex); + if (/(?:^|[\\/{,])\.\.(?:[\\/},]|$)/.test(wildcardTail)) { + throw new Error(`Access denied: ${label} contains path traversal sequences.`); + } + + if (normalized.startsWith('{')) { + let braceDepth = 0; + let braceCloseIndex = normalized.length; + for (let i = 0; i < normalized.length; i++) { + if (normalized[i] === '{') { + braceDepth++; + } else if (normalized[i] === '}') { + braceDepth--; + if (braceDepth === 0) { + braceCloseIndex = i; break; - } catch (err) { - if ((err as Error & { code?: string }).code !== 'ENOENT') { - throw err; - } - const parent = dirname(current); - if (parent === current) { - // Reached filesystem root - throw err; - } - current = parent; } } - } else { - throw e; } + + const braceContent = normalized.slice(1, braceCloseIndex); + for (const token of braceContent.split(/[{},]/)) { + if (!token) { + continue; + } + const tokenWildcard = token.search(/[*?[]/); + const tokenBase = tokenWildcard >= 0 ? token.slice(0, tokenWildcard) : token; + if (tokenBase) { + assertRealPathAllowed(roots, resolve(cwd, tokenBase), label); + } + } + } + } + + assertRealPathAllowed(roots, resolve(cwd, basePath), label); + if (DOT_DOT_SEGMENT_PATTERN.test(basePath)) { + const walkedBase = resolvePathFollowingSymlinks(basePath, realCwd); + if (!isAllowedRealPath(roots, walkedBase)) { + throw new Error(`Access denied: ${label} is outside allowed roots.`); } + } +} - const isAllowed = roots.some((root) => { - const rel = relative(root, realPath); +function validateNgCommandArgs( + roots: readonly string[], + args: readonly string[], + cwd: string, + realCwd: string, + depth = 0, +): void { + if (depth > MAX_RUNNER_ARGS_DEPTH) { + throw new Error('Access denied: nested runner argument depth exceeded.'); + } - return !rel.startsWith('..') && !isAbsolute(rel); - }); + const outputDirs: Array<{ raw: string; real: string }> = []; + const outputRelativeChecks: Array<{ flag: string; value: string }> = []; + const nestedRunnerArgs: string[] = []; - if (!isAllowed) { - throw new Error(`Access denied: path '${path}' is outside allowed roots.`); + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (!arg.startsWith('-') || arg === '-' || arg === '--') { + continue; + } + + const withoutPrefix = arg.startsWith('--') ? arg.slice(2) : arg.slice(1); + const eqIndex = withoutPrefix.indexOf('='); + const hasEquals = eqIndex !== -1; + const rawKey = hasEquals ? withoutPrefix.slice(0, eqIndex) : withoutPrefix; + const kind = classifyOptionKey(rawKey); + if (kind === 'none') { + continue; + } + + const flag = arg.startsWith('--') ? `--${rawKey}` : `-${rawKey}`; + const isNegated = rawKey.toLowerCase().startsWith('no-'); + + let value: string | undefined; + if (hasEquals) { + value = withoutPrefix.slice(eqIndex + 1); + } else if (!isNegated && i + 1 < args.length && !args[i + 1].startsWith('-')) { + value = args[++i]; + } + + if (kind === 'runner-args') { + if (value !== undefined) { + nestedRunnerArgs.push(value); + } + continue; + } + + if (kind === 'output-dir') { + if (isNegated && !hasEquals) { + continue; + } + const rawDir = value ?? ''; + const { realPath, walkedPath } = validateOptionPathValue(roots, flag, rawDir, cwd, realCwd); + assertNotWorkspaceOrRootAncestor(roots, flag, rawDir, realPath, realCwd); + if (walkedPath) { + assertNotWorkspaceOrRootAncestor(roots, flag, rawDir, walkedPath, realCwd); + } + outputDirs.push({ raw: resolve(cwd, rawDir), real: realPath }); + continue; } + + if (value === undefined) { + continue; + } + + const compactKey = normalizeOptionKey(stripNegationPrefix(rawKey)); + if ( + BOOLEAN_OR_PATH_OPTIONS.has(compactKey) && + (value === 'true' || value === 'false' || value === '') + ) { + continue; + } + + if (kind === 'glob') { + validateGlobOptionValue(roots, flag, value, cwd, realCwd); + } else if (kind === 'output-relative') { + validateOptionPathValue(roots, flag, value, cwd, realCwd); + outputRelativeChecks.push({ flag, value }); + } else { + validateOptionPathValue(roots, flag, value, cwd, realCwd); + } + } + + for (const { flag, value } of outputRelativeChecks) { + for (const outputDir of outputDirs) { + validateOptionPathValue(roots, flag, value, outputDir.raw, outputDir.real); + } + } + + if (nestedRunnerArgs.length > 0) { + validateNgCommandArgs(roots, nestedRunnerArgs, cwd, realCwd, depth + 1); + } +} + +export function createRootRestrictedHost( + baseHost: Host, + initialRoots: string[] = [process.cwd()], +): Host { + const defaultRoots = resolveRoots(initialRoots); + let roots = defaultRoots; + + function checkPath(path: string): string { + return assertRealPathAllowed(roots, path); } return { @@ -381,13 +891,15 @@ export function createRootRestrictedHost( options: Parameters[1] = {}, ) { const effectiveCwd = options?.cwd ?? process.cwd(); - checkPath(effectiveCwd); + const realCwd = checkPath(effectiveCwd); + validateNgCommandArgs(roots, args, effectiveCwd, realCwd); return baseHost.executeNgCommand(args, options); }, startNgProcess(args: readonly string[], options: Parameters[1] = {}) { const effectiveCwd = options?.cwd ?? process.cwd(); - checkPath(effectiveCwd); + const realCwd = checkPath(effectiveCwd); + validateNgCommandArgs(roots, args, effectiveCwd, realCwd); return baseHost.startNgProcess(args, options); }, diff --git a/packages/angular/cli/src/commands/mcp/host_spec.ts b/packages/angular/cli/src/commands/mcp/host_spec.ts index f04f712ed0fa..d856c58654c9 100644 --- a/packages/angular/cli/src/commands/mcp/host_spec.ts +++ b/packages/angular/cli/src/commands/mcp/host_spec.ts @@ -7,9 +7,10 @@ */ import assert from 'node:assert'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { LocalWorkspaceHost, createRootRestrictedHost } from './host'; +import { type Host, LocalWorkspaceHost, createRootRestrictedHost } from './host'; +import { createMockHost } from './testing/test-utils'; describe('createRootRestrictedHost', () => { let root1: string; @@ -41,6 +42,14 @@ describe('createRootRestrictedHost', () => { expect(host.existsSync(join(root2, 'file2.txt'))).toBeTrue(); }); + it('should allow entries whose names start with two dots inside a root', () => { + const dotDotFile = join(root1, '..hidden.txt'); + writeFileSync(dotDotFile, 'content'); + const host = createRootRestrictedHost(LocalWorkspaceHost, [root1]); + + expect(host.existsSync(dotDotFile)).toBeTrue(); + }); + it('should reject file access outside of the configured roots', () => { const host = createRootRestrictedHost(LocalWorkspaceHost, [root1, root2]); @@ -51,6 +60,15 @@ describe('createRootRestrictedHost', () => { ); }); + it('should reject dangling symlinks pointing outside configured roots', () => { + const danglingLink = join(root1, 'dangling-out'); + symlinkSync(join(outsideDir, 'does-not-exist'), danglingLink, 'junction'); + const host = createRootRestrictedHost(LocalWorkspaceHost, [root1]); + + expect(() => host.existsSync(danglingLink)).toThrowError(/Access denied/); + expect(() => host.existsSync(join(danglingLink, 'nested'))).toThrowError(/Access denied/); + }); + it('should fall back to initial roots when setRoots is called with an empty array', () => { const host = createRootRestrictedHost(LocalWorkspaceHost, [root1, root2]); @@ -59,4 +77,337 @@ describe('createRootRestrictedHost', () => { expect(host.existsSync(join(root1, 'file1.txt'))).toBeTrue(); expect(host.existsSync(join(root2, 'file2.txt'))).toBeTrue(); }); + + describe('command argument validation', () => { + let baseHost: ReturnType; + let restrictedHost: Host; + + beforeEach(() => { + baseHost = createMockHost(); + restrictedHost = createRootRestrictedHost(baseHost, [root1]); + }); + + it('should allow valid output-path values inside the allowed root', async () => { + await restrictedHost.executeNgCommand(['build', 'my-app', '--output-path=dist/my-app'], { + cwd: root1, + }); + await restrictedHost.executeNgCommand( + ['build', 'my-app', `--output-path=${join(root1, 'dist/abs')}`], + { cwd: root1 }, + ); + + expect(baseHost.executeNgCommand).toHaveBeenCalledTimes(2); + }); + + it('should allow non-filesystem URL, enum, and boolean options', async () => { + await restrictedHost.executeNgCommand( + [ + 'build', + 'my-app', + '--base-href=/my-app/', + '--deploy-url=/assets/', + '--serve-path=/app', + '--delete-output-path=false', + '--output-hashing=all', + '--output-mode=static', + '--configuration=production', + '--define=API_BASE=/v1', + '--filter=/AppComponent/', + '--route=/shell', + '--routes=/home', + '--profile', + '--runner-config=false', + '--index=false', + '--server=true', + '--service-worker=true', + '--no-delete-output-path', + '--no-runner-config', + ], + { cwd: root1 }, + ); + + expect(baseHost.executeNgCommand).toHaveBeenCalledTimes(1); + }); + + it('should reject absolute output-path values outside allowed roots', () => { + const outsideTarget = join(outsideDir, 'target'); + + for (const args of [ + ['build', 'my-app', `--output-path=${outsideTarget}`], + ['build', 'my-app', `--outputPath=${outsideTarget}`], + ['build', 'my-app', `--output_path=${outsideTarget}`], + ['build', 'my-app', `--OUTPUT-PATH=${outsideTarget}`], + ['build', 'my-app', '--output-path', outsideTarget], + ['build', 'my-app', '--output-path=dist/ok', `--output-path=${outsideTarget}`], + ['build', 'my-app', `--no-output-path=${outsideTarget}`], + ['build', 'my-app', `--output-path.base=${outsideTarget}`], + ]) { + expect(() => restrictedHost.executeNgCommand(args, { cwd: root1 })).toThrowError( + /Access denied: option .* is outside allowed roots/, + ); + } + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should reject relative traversal output-path values outside allowed roots', () => { + expect(() => + restrictedHost.executeNgCommand(['build', 'my-app', '--output-path=../outside'], { + cwd: root1, + }), + ).toThrowError(/Access denied: option '--output-path' path '\.\.\/outside' is outside/); + + expect(() => + restrictedHost.executeNgCommand(['build', 'my-app', '--output-path=dist/../../outside'], { + cwd: root1, + }), + ).toThrowError(/Access denied: option '--output-path'/); + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should reject output-path equal to or ancestor of the workspace or root directory', () => { + const monoWorkspace = join(root1, 'apps', 'web'); + mkdirSync(monoWorkspace, { recursive: true }); + + for (const value of ['', '.', './', '..', '../..', root1]) { + expect(() => + restrictedHost.executeNgCommand(['build', 'web', `--output-path=${value}`], { + cwd: monoWorkspace, + }), + ).toThrowError(/Access denied: option '--output-path'/); + } + + // Bare flag without a value defaults to empty string (`cwd`). + expect(() => + restrictedHost.executeNgCommand(['build', 'web', '--output-path'], { cwd: monoWorkspace }), + ).toThrowError(/Access denied: option '--output-path'/); + + // Multi-root: must not target another root directory directly. + restrictedHost.setRoots([root1, root2]); + expect(() => + restrictedHost.executeNgCommand(['build', 'web', `--output-path=${root2}`], { + cwd: monoWorkspace, + }), + ).toThrowError(/must not be an allowed root directory/); + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should allow monorepo sibling output paths strictly inside the allowed root', async () => { + const monoWorkspace = join(root1, 'apps', 'web'); + mkdirSync(monoWorkspace, { recursive: true }); + + await restrictedHost.executeNgCommand(['build', 'web', '--output-path=../../dist/web'], { + cwd: monoWorkspace, + }); + + expect(baseHost.executeNgCommand).toHaveBeenCalledTimes(1); + }); + + it('should reject symlinks inside root pointing outside roots or to workspace root', () => { + const linkOut = join(root1, 'link-out'); + const danglingOut = join(root1, 'dangling-out'); + const linkSelf = join(root1, 'link-self'); + const outsideNested = join(outsideDir, 'sub'); + mkdirSync(outsideNested, { recursive: true }); + const linkNested = join(root1, 'link-nested'); + + symlinkSync(outsideDir, linkOut, 'junction'); + symlinkSync(join(outsideDir, 'missing'), danglingOut, 'junction'); + symlinkSync(root1, linkSelf, 'junction'); + symlinkSync(outsideNested, linkNested, 'junction'); + + expect(() => + restrictedHost.executeNgCommand(['build', 'my-app', '--output-path=link-out'], { + cwd: root1, + }), + ).toThrowError(/Access denied/); + + expect(() => + restrictedHost.executeNgCommand(['build', 'my-app', '--output-path=link-out/nested'], { + cwd: root1, + }), + ).toThrowError(/Access denied/); + + expect(() => + restrictedHost.executeNgCommand(['build', 'my-app', '--output-path=dangling-out'], { + cwd: root1, + }), + ).toThrowError(/Access denied/); + + expect(() => + restrictedHost.executeNgCommand(['build', 'my-app', '--output-path=link-self'], { + cwd: root1, + }), + ).toThrowError(/must not be the workspace directory/); + + // Lexical `link-nested/../secret` must still be caught when walking via the symlink target. + expect(() => + restrictedHost.executeNgCommand( + ['build', 'my-app', '--output-path=link-nested/../secret'], + { + cwd: root1, + }, + ), + ).toThrowError(/Access denied/); + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should reject compound output-path and out-file traversal regardless of flag order', () => { + const monoWorkspace = join(root1, 'apps', 'web'); + mkdirSync(monoWorkspace, { recursive: true }); + + expect(() => + restrictedHost.executeNgCommand( + ['extract-i18n', 'web', '--output-path=../../dist', '--out-file=../../evil.xlf'], + { cwd: monoWorkspace }, + ), + ).toThrowError(/Access denied: option '--out-file'/); + + expect(() => + restrictedHost.executeNgCommand( + ['extract-i18n', 'web', '--out-file=../../evil.xlf', '--output-path=../../dist'], + { cwd: monoWorkspace }, + ), + ).toThrowError(/Access denied: option '--out-file'/); + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should reject other path-bearing builder and third-party options outside roots', () => { + const extPath = join(outsideDir, 'file'); + + for (const flag of [ + `--out-file=${extPath}`, + `--output-file=${extPath}`, + `--ts-config=${extPath}`, + `--karma-config=${extPath}`, + `--runner-config=${extPath}`, + `--webpack-config=${extPath}`, + `--proxy-config=${extPath}`, + `--ssl-key=${extPath}`, + `--ssl-cert=${extPath}`, + `--providers-file=${extPath}`, + `--setup-files=${extPath}`, + `--routes-file=${extPath}`, + `--browser=${extPath}`, + `--server=${extPath}`, + `--main=${extPath}`, + `--index=${extPath}`, + `--service-worker=${extPath}`, + `--project=${extPath}`, + `--ngsw-config-path=${extPath}`, + `--resources-output-path=${extPath}`, + `--eslint-config=${extPath}`, + `--cache-location=${extPath}`, + `--output-dir=${extPath}`, + `--config-dir=${extPath}`, + `--dest=${extPath}`, + `-o=${extPath}`, + ]) { + expect(() => + restrictedHost.executeNgCommand(['run', 'my-app:custom', flag], { cwd: root1 }), + ).toThrowError(/Access denied/); + } + + expect(() => + restrictedHost.executeNgCommand(['lint', 'my-app', '-o', extPath], { cwd: root1 }), + ).toThrowError(/Access denied/); + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should validate glob-based path options while allowing normal patterns', async () => { + const linkOut = join(root1, 'link-out'); + symlinkSync(outsideDir, linkOut, 'junction'); + + await restrictedHost.executeNgCommand( + [ + 'test', + 'my-app', + '--include=src/**/*.spec.ts', + '--include=src/foo..bar.spec.ts', + '--exclude=!src/ignored.spec.ts', + ], + { cwd: root1 }, + ); + expect(baseHost.executeNgCommand).toHaveBeenCalledTimes(1); + + for (const badPattern of [ + '../outside/*.spec.ts', + join(outsideDir, '*.spec.ts'), + 'src/*/../../../outside/*.spec.ts', + `{${outsideDir},src}/*.spec.ts`, + `{a,{b,c},${outsideDir}}/*.spec.ts`, + '{link-out,src}/*.spec.ts', + '!../outside/*.spec.ts', + ]) { + expect(() => + restrictedHost.executeNgCommand(['test', 'my-app', `--include=${badPattern}`], { + cwd: root1, + }), + ).toThrowError(/Access denied/); + } + }); + + it('should validate nested runner-args and passthrough args after --', async () => { + await restrictedHost.executeNgCommand( + ['test', 'my-app', '--runner-args=--update', '--runner-args=--bail=1'], + { cwd: root1 }, + ); + expect(baseHost.executeNgCommand).toHaveBeenCalledTimes(1); + + const extConfig = join(outsideDir, 'vitest.config.mjs'); + expect(() => + restrictedHost.executeNgCommand(['test', 'my-app', `--runner-args=--config=${extConfig}`], { + cwd: root1, + }), + ).toThrowError(/Access denied/); + + expect(() => + restrictedHost.executeNgCommand( + ['test', 'my-app', '--runner-args=--outputFile', `--runner-args=${extConfig}`], + { cwd: root1 }, + ), + ).toThrowError(/Access denied/); + + expect(() => + restrictedHost.executeNgCommand(['test', 'my-app', '--', `--config=${extConfig}`], { + cwd: root1, + }), + ).toThrowError(/Access denied/); + }); + + it('should validate arguments in startNgProcess and allow valid devserver flags', () => { + restrictedHost.startNgProcess(['serve', 'my-app', '--port=12345', '-o'], { cwd: root1 }); + expect(baseHost.startNgProcess).toHaveBeenCalledTimes(1); + + expect(() => + restrictedHost.startNgProcess( + ['serve', 'my-app', `--proxy-config=${join(outsideDir, 'proxy.json')}`], + { cwd: root1 }, + ), + ).toThrowError(/Access denied/); + + expect(baseHost.startNgProcess).toHaveBeenCalledTimes(1); + }); + + it('should enforce updated roots after setRoots is called', async () => { + const targetInRoot2 = join(root2, 'dist/app'); + expect(() => + restrictedHost.executeNgCommand(['build', 'my-app', `--output-path=${targetInRoot2}`], { + cwd: root1, + }), + ).toThrowError(/Access denied/); + + restrictedHost.setRoots([root1, root2]); + await restrictedHost.executeNgCommand(['build', 'my-app', `--output-path=${targetInRoot2}`], { + cwd: root1, + }); + + expect(baseHost.executeNgCommand).toHaveBeenCalledTimes(1); + }); + }); }); diff --git a/packages/angular/cli/src/commands/mcp/tools/run-target/build-target-strategy.ts b/packages/angular/cli/src/commands/mcp/tools/run-target/build-target-strategy.ts index 2e280927f466..e432f5e1b5f4 100644 --- a/packages/angular/cli/src/commands/mcp/tools/run-target/build-target-strategy.ts +++ b/packages/angular/cli/src/commands/mcp/tools/run-target/build-target-strategy.ts @@ -6,6 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ +import { CommandError } from '../../host'; import { getCommandErrorLogs } from '../../utils'; import type { McpToolContext } from '../tool-registry'; import { serializeOptions } from './options-serializer'; @@ -41,6 +42,10 @@ export class BuildTargetStrategy implements TargetStrategy { const result = await context.host.executeNgCommand(args, { cwd: input.workspacePath }); logs = result.logs; } catch (e) { + if (!(e instanceof CommandError)) { + throw e; + } + status = 'failure'; logs = getCommandErrorLogs(e); } diff --git a/packages/angular/cli/src/commands/mcp/tools/run-target/generic-target-strategy.ts b/packages/angular/cli/src/commands/mcp/tools/run-target/generic-target-strategy.ts index 365253131248..29775982b788 100644 --- a/packages/angular/cli/src/commands/mcp/tools/run-target/generic-target-strategy.ts +++ b/packages/angular/cli/src/commands/mcp/tools/run-target/generic-target-strategy.ts @@ -6,6 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ +import { CommandError } from '../../host'; import { getCommandErrorLogs } from '../../utils'; import type { McpToolContext } from '../tool-registry'; import { serializeOptions } from './options-serializer'; @@ -66,6 +67,10 @@ export class GenericTargetStrategy implements TargetStrategy { const result = await context.host.executeNgCommand(args, { cwd: input.workspacePath }); logs = result.logs; } catch (e) { + if (!(e instanceof CommandError)) { + throw e; + } + status = 'failure'; logs = getCommandErrorLogs(e); } diff --git a/packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer.ts b/packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer.ts index b5f5a7414b97..0e3e745e701f 100644 --- a/packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer.ts +++ b/packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer.ts @@ -21,24 +21,35 @@ export function serializeOptions( return args; } - for (const [key, value] of Object.entries(options)) { - if (excludeKeys.has(key)) { - continue; - } + const normalizedExcludeKeys = new Set( + [...excludeKeys].map((k) => k.toLowerCase().replace(/[-_]/g, '')), + ); - if (!/^[a-zA-Z0-9-_]+$/.test(key)) { + for (const [key, value] of Object.entries(options)) { + if (!/^[a-zA-Z0-9][a-zA-Z0-9-_]*$/.test(key)) { throw new Error( - `Invalid option key: '${key}'. Option keys must be alphanumeric, hyphens, or underscores.`, + `Invalid option key: '${key}'. Option keys must start with an alphanumeric character and ` + + 'contain only alphanumeric characters, hyphens, or underscores.', ); } + if (normalizedExcludeKeys.has(key.toLowerCase().replace(/[-_]/g, ''))) { + continue; + } + if (typeof value === 'boolean') { args.push(value ? `--${key}` : `--no-${key}`); } else if (Array.isArray(value)) { for (const item of value) { + if (typeof item === 'string' && item.includes('\0')) { + throw new Error(`Invalid option value for '${key}': values must not contain null bytes.`); + } args.push(`--${key}=${item}`); } } else if (value !== null && value !== undefined) { + if (typeof value === 'string' && value.includes('\0')) { + throw new Error(`Invalid option value for '${key}': values must not contain null bytes.`); + } args.push(`--${key}=${value}`); } } diff --git a/packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer_spec.ts b/packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer_spec.ts index 197a3855799a..253b87bc0543 100644 --- a/packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer_spec.ts +++ b/packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer_spec.ts @@ -45,5 +45,27 @@ describe('run-target options-serializer', () => { /Invalid option key: 'fix --danger'/, ); }); + + it('should throw an error if key starts with a hyphen or underscore', () => { + expect(() => serializeOptions({ '-output-path': 'dist' })).toThrowError( + /Invalid option key: '-output-path'/, + ); + expect(() => serializeOptions({ '_output': 'dist' })).toThrowError( + /Invalid option key: '_output'/, + ); + }); + + it('should ignore excluded keys case-insensitively', () => { + expect(serializeOptions({ WATCH: true, fix: true }, new Set(['watch']))).toEqual(['--fix']); + }); + + it('should throw an error if a string option value contains a null byte', () => { + expect(() => serializeOptions({ 'output-path': 'dist\0evil' })).toThrowError( + /Invalid option value for 'output-path': values must not contain null bytes/, + ); + expect(() => serializeOptions({ include: ['src', 'evil\0path'] })).toThrowError( + /Invalid option value for 'include': values must not contain null bytes/, + ); + }); }); }); diff --git a/packages/angular/cli/src/commands/mcp/tools/run-target/run-target_spec.ts b/packages/angular/cli/src/commands/mcp/tools/run-target/run-target_spec.ts index 91ccbac4584a..84b77e1e2c0c 100644 --- a/packages/angular/cli/src/commands/mcp/tools/run-target/run-target_spec.ts +++ b/packages/angular/cli/src/commands/mcp/tools/run-target/run-target_spec.ts @@ -6,12 +6,17 @@ * found in the LICENSE file at https://angular.dev/license */ -import { CommandError } from '../../host'; +import assert from 'node:assert'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { AngularWorkspace } from '../../../../utilities/config'; +import { CommandError, createRootRestrictedHost } from '../../host'; import type { MockHost } from '../../testing/mock-host'; import { type MockMcpToolContext, addProjectToWorkspace, createMockContext, + createMockHost, } from '../../testing/test-utils'; import { runTarget } from './run-target'; @@ -145,4 +150,108 @@ describe('Run Target Tool', () => { runTarget({ target: 'build', options: { watch: true } }, mockContext), ).toBeRejectedWithError(/Watch mode execution.*is not yet supported/); }); + + describe('root-restricted host option validation', () => { + let tempRoot: string; + let outsideDir: string; + let baseHost: MockHost; + let restrictedContext: MockMcpToolContext; + + beforeEach(() => { + const baseTmpDir = process.env['TEST_TMPDIR']; + assert(baseTmpDir, 'TEST_TMPDIR is not set'); + tempRoot = mkdtempSync(join(baseTmpDir, 'angular-cli-run-target-root-')); + outsideDir = mkdtempSync(join(baseTmpDir, 'angular-cli-run-target-outside-')); + + baseHost = createMockHost(); + const restrictedHost = createRootRestrictedHost(baseHost, [tempRoot]); + const mock = createMockContext(); + addProjectToWorkspace(mock.projects, 'my-app', { + build: { builder: '@angular/build:application' }, + test: { builder: '@angular/build:unit-test' }, + 'extract-i18n': { builder: '@angular/build:extract-i18n' }, + }); + + const workspace = new AngularWorkspace( + { projects: mock.projects, extensions: { defaultProject: 'my-app' } }, + join(tempRoot, 'angular.json'), + ); + + restrictedContext = { + ...mock.context, + host: restrictedHost, + workspace, + }; + }); + + afterEach(() => { + rmSync(tempRoot, { recursive: true, force: true }); + rmSync(outsideDir, { recursive: true, force: true }); + }); + + it('should reject and propagate out-of-root output-path in BuildTargetStrategy', async () => { + await expectAsync( + runTarget( + { + target: 'build', + options: { 'output-path': outsideDir }, + }, + restrictedContext, + ), + ).toBeRejectedWithError(/Access denied: option '--output-path'/); + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should reject and propagate out-of-root runner-config in UnitTestTargetStrategy', async () => { + await expectAsync( + runTarget( + { + target: 'test', + options: { 'runner-config': join(outsideDir, 'evil.mjs') }, + }, + restrictedContext, + ), + ).toBeRejectedWithError(/Access denied: option '--runner-config'/); + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should reject and propagate out-of-root output-path in GenericTargetStrategy', async () => { + await expectAsync( + runTarget( + { + target: 'extract-i18n', + options: { 'output-path': '../escape' }, + }, + restrictedContext, + ), + ).toBeRejectedWithError(/Access denied: option '--output-path'/); + + expect(baseHost.executeNgCommand).not.toHaveBeenCalled(); + }); + + it('should allow valid in-root output-path and base-href options', async () => { + baseHost.executeNgCommand.and.resolveTo({ + logs: ['Output location: dist/custom'], + }); + + const { structuredContent } = await runTarget( + { + target: 'build', + options: { + 'output-path': 'dist/custom', + 'base-href': '/my-app/', + }, + }, + restrictedContext, + ); + + expect(structuredContent.status).toBe('success'); + expect(baseHost.executeNgCommand).toHaveBeenCalledWith( + ['build', 'my-app', '--output-path=dist/custom', '--base-href=/my-app/'], + { cwd: tempRoot }, + ); + }); + }); }); diff --git a/packages/angular/cli/src/commands/mcp/tools/run-target/unit-test-strategy.ts b/packages/angular/cli/src/commands/mcp/tools/run-target/unit-test-strategy.ts index 1023cdd7956c..7e8e3180174f 100644 --- a/packages/angular/cli/src/commands/mcp/tools/run-target/unit-test-strategy.ts +++ b/packages/angular/cli/src/commands/mcp/tools/run-target/unit-test-strategy.ts @@ -6,6 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ +import { CommandError } from '../../host'; import { getCommandErrorLogs } from '../../utils'; import type { McpToolContext } from '../tool-registry'; import { serializeOptions } from './options-serializer'; @@ -57,6 +58,10 @@ export class UnitTestTargetStrategy implements TargetStrategy { const result = await context.host.executeNgCommand(args, { cwd: input.workspacePath }); logs = result.logs; } catch (e) { + if (!(e instanceof CommandError)) { + throw e; + } + status = 'failure'; logs = getCommandErrorLogs(e); }