Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
709 changes: 655 additions & 54 deletions packages/angular/cli/src/commands/mcp/host.ts

Large diffs are not rendered by default.

425 changes: 423 additions & 2 deletions packages/angular/cli/src/commands/mcp/host_spec.ts

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -31,7 +32,12 @@ export class GenericTargetStrategy implements TargetStrategy {
input: StrategyExecutionContext,
context: McpToolContext,
): Promise<RunTargetOutput> {
if (input.targetName === 'serve' || input.options?.['watch'] === true) {
const hasWatchOption =
input.options !== undefined &&
Object.entries(input.options).some(
([key, value]) => key.toLowerCase().replace(/[-_]/g, '') === 'watch' && value === true,
);
if (input.targetName === 'serve' || hasWatchOption) {
throw new Error(
`Watch mode execution (serve target or watch option) is not yet supported by 'run_target'. ` +
`Please use the legacy 'devserver_start' / 'devserver_wait_for_build' tools instead.`,
Expand Down Expand Up @@ -66,6 +72,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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep this regex without . (contrary to the bot suggestion). Angular CLI disables 'dot-notation' in Yargs and ignores nested object properties in parseJsonSchemaToOptions, so dot-notation keys aren't accepted on the CLI anyway (and Vitest options like --sequence.shuffle are passed in runner-args values, not option keys).

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.',
);
}
Comment thread
alan-agius4 marked this conversation as resolved.
Resolved

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}`);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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/,
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -144,5 +149,122 @@ describe('Run Target Tool', () => {
await expectAsync(
runTarget({ target: 'build', options: { watch: true } }, mockContext),
).toBeRejectedWithError(/Watch mode execution.*is not yet supported/);
await expectAsync(
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'/);

await expectAsync(
runTarget(
{
target: 'test',
options: { reporters: [join(outsideDir, 'evil-reporter.mjs')] },
},
restrictedContext,
),
).toBeRejectedWithError(/Access denied: option '--reporters'/);

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 },
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
Expand Down
Loading