Skip to content

Commit 0a61cbc

Browse files
authored
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`.
1 parent 3af8b4e commit 0a61cbc

8 files changed

Lines changed: 1261 additions & 64 deletions

File tree

‎packages/angular/cli/src/commands/mcp/host.ts‎

Lines changed: 655 additions & 54 deletions
Large diffs are not rendered by default.

‎packages/angular/cli/src/commands/mcp/host_spec.ts‎

Lines changed: 423 additions & 2 deletions
Large diffs are not rendered by default.

‎packages/angular/cli/src/commands/mcp/tools/run-target/build-target-strategy.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9+
import { CommandError } from '../../host';
910
import { getCommandErrorLogs } from '../../utils';
1011
import type { McpToolContext } from '../tool-registry';
1112
import { serializeOptions } from './options-serializer';
@@ -41,6 +42,10 @@ export class BuildTargetStrategy implements TargetStrategy {
4142
const result = await context.host.executeNgCommand(args, { cwd: input.workspacePath });
4243
logs = result.logs;
4344
} catch (e) {
45+
if (!(e instanceof CommandError)) {
46+
throw e;
47+
}
48+
4449
status = 'failure';
4550
logs = getCommandErrorLogs(e);
4651
}

‎packages/angular/cli/src/commands/mcp/tools/run-target/generic-target-strategy.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9+
import { CommandError } from '../../host';
910
import { getCommandErrorLogs } from '../../utils';
1011
import type { McpToolContext } from '../tool-registry';
1112
import { serializeOptions } from './options-serializer';
@@ -31,7 +32,12 @@ export class GenericTargetStrategy implements TargetStrategy {
3132
input: StrategyExecutionContext,
3233
context: McpToolContext,
3334
): Promise<RunTargetOutput> {
34-
if (input.targetName === 'serve' || input.options?.['watch'] === true) {
35+
const hasWatchOption =
36+
input.options !== undefined &&
37+
Object.entries(input.options).some(
38+
([key, value]) => key.toLowerCase().replace(/[-_]/g, '') === 'watch' && value === true,
39+
);
40+
if (input.targetName === 'serve' || hasWatchOption) {
3541
throw new Error(
3642
`Watch mode execution (serve target or watch option) is not yet supported by 'run_target'. ` +
3743
`Please use the legacy 'devserver_start' / 'devserver_wait_for_build' tools instead.`,
@@ -66,6 +72,10 @@ export class GenericTargetStrategy implements TargetStrategy {
6672
const result = await context.host.executeNgCommand(args, { cwd: input.workspacePath });
6773
logs = result.logs;
6874
} catch (e) {
75+
if (!(e instanceof CommandError)) {
76+
throw e;
77+
}
78+
6979
status = 'failure';
7080
logs = getCommandErrorLogs(e);
7181
}

‎packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,24 +21,35 @@ export function serializeOptions(
2121
return args;
2222
}
2323

24-
for (const [key, value] of Object.entries(options)) {
25-
if (excludeKeys.has(key)) {
26-
continue;
27-
}
24+
const normalizedExcludeKeys = new Set(
25+
[...excludeKeys].map((k) => k.toLowerCase().replace(/[-_]/g, '')),
26+
);
2827

29-
if (!/^[a-zA-Z0-9-_]+$/.test(key)) {
28+
for (const [key, value] of Object.entries(options)) {
29+
if (!/^[a-zA-Z0-9][a-zA-Z0-9-_]*$/.test(key)) {
3030
throw new Error(
31-
`Invalid option key: '${key}'. Option keys must be alphanumeric, hyphens, or underscores.`,
31+
`Invalid option key: '${key}'. Option keys must start with an alphanumeric character and ` +
32+
'contain only alphanumeric characters, hyphens, or underscores.',
3233
);
3334
}
3435

36+
if (normalizedExcludeKeys.has(key.toLowerCase().replace(/[-_]/g, ''))) {
37+
continue;
38+
}
39+
3540
if (typeof value === 'boolean') {
3641
args.push(value ? `--${key}` : `--no-${key}`);
3742
} else if (Array.isArray(value)) {
3843
for (const item of value) {
44+
if (typeof item === 'string' && item.includes('\0')) {
45+
throw new Error(`Invalid option value for '${key}': values must not contain null bytes.`);
46+
}
3947
args.push(`--${key}=${item}`);
4048
}
4149
} else if (value !== null && value !== undefined) {
50+
if (typeof value === 'string' && value.includes('\0')) {
51+
throw new Error(`Invalid option value for '${key}': values must not contain null bytes.`);
52+
}
4253
args.push(`--${key}=${value}`);
4354
}
4455
}

‎packages/angular/cli/src/commands/mcp/tools/run-target/options-serializer_spec.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,5 +45,27 @@ describe('run-target options-serializer', () => {
4545
/Invalid option key: 'fix --danger'/,
4646
);
4747
});
48+
49+
it('should throw an error if key starts with a hyphen or underscore', () => {
50+
expect(() => serializeOptions({ '-output-path': 'dist' })).toThrowError(
51+
/Invalid option key: '-output-path'/,
52+
);
53+
expect(() => serializeOptions({ '_output': 'dist' })).toThrowError(
54+
/Invalid option key: '_output'/,
55+
);
56+
});
57+
58+
it('should ignore excluded keys case-insensitively', () => {
59+
expect(serializeOptions({ WATCH: true, fix: true }, new Set(['watch']))).toEqual(['--fix']);
60+
});
61+
62+
it('should throw an error if a string option value contains a null byte', () => {
63+
expect(() => serializeOptions({ 'output-path': 'dist\0evil' })).toThrowError(
64+
/Invalid option value for 'output-path': values must not contain null bytes/,
65+
);
66+
expect(() => serializeOptions({ include: ['src', 'evil\0path'] })).toThrowError(
67+
/Invalid option value for 'include': values must not contain null bytes/,
68+
);
69+
});
4870
});
4971
});

‎packages/angular/cli/src/commands/mcp/tools/run-target/run-target_spec.ts‎

Lines changed: 123 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,17 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9-
import { CommandError } from '../../host';
9+
import assert from 'node:assert';
10+
import { mkdtempSync, rmSync } from 'node:fs';
11+
import { join } from 'node:path';
12+
import { AngularWorkspace } from '../../../../utilities/config';
13+
import { CommandError, createRootRestrictedHost } from '../../host';
1014
import type { MockHost } from '../../testing/mock-host';
1115
import {
1216
type MockMcpToolContext,
1317
addProjectToWorkspace,
1418
createMockContext,
19+
createMockHost,
1520
} from '../../testing/test-utils';
1621
import { runTarget } from './run-target';
1722

@@ -144,5 +149,122 @@ describe('Run Target Tool', () => {
144149
await expectAsync(
145150
runTarget({ target: 'build', options: { watch: true } }, mockContext),
146151
).toBeRejectedWithError(/Watch mode execution.*is not yet supported/);
152+
await expectAsync(
153+
runTarget({ target: 'build', options: { WATCH: true } }, mockContext),
154+
).toBeRejectedWithError(/Watch mode execution.*is not yet supported/);
155+
});
156+
157+
describe('root-restricted host option validation', () => {
158+
let tempRoot: string;
159+
let outsideDir: string;
160+
let baseHost: MockHost;
161+
let restrictedContext: MockMcpToolContext;
162+
163+
beforeEach(() => {
164+
const baseTmpDir = process.env['TEST_TMPDIR'];
165+
assert(baseTmpDir, 'TEST_TMPDIR is not set');
166+
tempRoot = mkdtempSync(join(baseTmpDir, 'angular-cli-run-target-root-'));
167+
outsideDir = mkdtempSync(join(baseTmpDir, 'angular-cli-run-target-outside-'));
168+
169+
baseHost = createMockHost();
170+
const restrictedHost = createRootRestrictedHost(baseHost, [tempRoot]);
171+
const mock = createMockContext();
172+
addProjectToWorkspace(mock.projects, 'my-app', {
173+
build: { builder: '@angular/build:application' },
174+
test: { builder: '@angular/build:unit-test' },
175+
'extract-i18n': { builder: '@angular/build:extract-i18n' },
176+
});
177+
178+
const workspace = new AngularWorkspace(
179+
{ projects: mock.projects, extensions: { defaultProject: 'my-app' } },
180+
join(tempRoot, 'angular.json'),
181+
);
182+
183+
restrictedContext = {
184+
...mock.context,
185+
host: restrictedHost,
186+
workspace,
187+
};
188+
});
189+
190+
afterEach(() => {
191+
rmSync(tempRoot, { recursive: true, force: true });
192+
rmSync(outsideDir, { recursive: true, force: true });
193+
});
194+
195+
it('should reject and propagate out-of-root output-path in BuildTargetStrategy', async () => {
196+
await expectAsync(
197+
runTarget(
198+
{
199+
target: 'build',
200+
options: { 'output-path': outsideDir },
201+
},
202+
restrictedContext,
203+
),
204+
).toBeRejectedWithError(/Access denied: option '--output-path'/);
205+
206+
expect(baseHost.executeNgCommand).not.toHaveBeenCalled();
207+
});
208+
209+
it('should reject and propagate out-of-root runner-config in UnitTestTargetStrategy', async () => {
210+
await expectAsync(
211+
runTarget(
212+
{
213+
target: 'test',
214+
options: { 'runner-config': join(outsideDir, 'evil.mjs') },
215+
},
216+
restrictedContext,
217+
),
218+
).toBeRejectedWithError(/Access denied: option '--runner-config'/);
219+
220+
await expectAsync(
221+
runTarget(
222+
{
223+
target: 'test',
224+
options: { reporters: [join(outsideDir, 'evil-reporter.mjs')] },
225+
},
226+
restrictedContext,
227+
),
228+
).toBeRejectedWithError(/Access denied: option '--reporters'/);
229+
230+
expect(baseHost.executeNgCommand).not.toHaveBeenCalled();
231+
});
232+
233+
it('should reject and propagate out-of-root output-path in GenericTargetStrategy', async () => {
234+
await expectAsync(
235+
runTarget(
236+
{
237+
target: 'extract-i18n',
238+
options: { 'output-path': '../escape' },
239+
},
240+
restrictedContext,
241+
),
242+
).toBeRejectedWithError(/Access denied: option '--output-path'/);
243+
244+
expect(baseHost.executeNgCommand).not.toHaveBeenCalled();
245+
});
246+
247+
it('should allow valid in-root output-path and base-href options', async () => {
248+
baseHost.executeNgCommand.and.resolveTo({
249+
logs: ['Output location: dist/custom'],
250+
});
251+
252+
const { structuredContent } = await runTarget(
253+
{
254+
target: 'build',
255+
options: {
256+
'output-path': 'dist/custom',
257+
'base-href': '/my-app/',
258+
},
259+
},
260+
restrictedContext,
261+
);
262+
263+
expect(structuredContent.status).toBe('success');
264+
expect(baseHost.executeNgCommand).toHaveBeenCalledWith(
265+
['build', 'my-app', '--output-path=dist/custom', '--base-href=/my-app/'],
266+
{ cwd: tempRoot },
267+
);
268+
});
147269
});
148270
});

‎packages/angular/cli/src/commands/mcp/tools/run-target/unit-test-strategy.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9+
import { CommandError } from '../../host';
910
import { getCommandErrorLogs } from '../../utils';
1011
import type { McpToolContext } from '../tool-registry';
1112
import { serializeOptions } from './options-serializer';
@@ -57,6 +58,10 @@ export class UnitTestTargetStrategy implements TargetStrategy {
5758
const result = await context.host.executeNgCommand(args, { cwd: input.workspacePath });
5859
logs = result.logs;
5960
} catch (e) {
61+
if (!(e instanceof CommandError)) {
62+
throw e;
63+
}
64+
6065
status = 'failure';
6166
logs = getCommandErrorLogs(e);
6267
}

0 commit comments

Comments
 (0)