Skip to content

Commit 90763d0

Browse files
committed
fix(@angular/build): contain asset reads within the workspace root
Asset inputs are checked against the workspace root before they are globbed, but that check only compares paths as text. A symbolic link resolves to its target on disk, so a link committed inside an asset directory passes the check and the globber reads straight through it, copying files from outside the workspace into the build output. Turning off link following is not enough on its own. When a pattern has a static directory prefix, such as 'docs/**/*', the globber starts its walk inside that directory, and it reads through a directory it starts from even when that directory is a link. A pattern can also leave the input by itself, since only the input was ever checked: '../../outside/*' is joined onto it, and an absolute pattern replaces it entirely. Every match is now resolved to its real location and has to stay inside the workspace root, whatever 'followSymlinks' is set to. The option also defaults to 'false' now, which is what the builder schema has always documented. Schema defaults do not reach into the objects of the 'assets' array, so the value was arriving as 'undefined', and tinyglobby reads that as enabled. An input that points at a dependency is contained to its own resolved directory rather than the workspace root. Package managers keep the packages of a workspace at the repository root and link to them, so 'node_modules/<package>/assets' resolves outside of an application that lives below that root, and requiring it to stay inside would break every pnpm and npm workspace. The webpack builders in '@angular-devkit/build-angular' get the same containment. Localization there copies an already built directory, which it used to pass as an input with an empty root. That would have needed a weaker check, so it now passes the directory as the root instead. Fixes #34164
1 parent d968259 commit 90763d0

14 files changed

Lines changed: 703 additions & 16 deletions

File tree

‎packages/angular/build/src/builders/application/schema.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,7 @@
633633
"followSymlinks": {
634634
"type": "boolean",
635635
"default": false,
636-
"description": "Allow glob patterns to follow symlink directories. This allows subdirectories of the symlink to be searched."
636+
"description": "Allow glob patterns to follow symlink directories. This allows subdirectories of the symlink to be searched. Symlinks that resolve outside of the workspace root are not allowed."
637637
},
638638
"glob": {
639639
"type": "string",

‎packages/angular/build/src/builders/application/tests/options/assets_spec.ts‎

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

9+
import * as fs from 'node:fs';
10+
import * as path from 'node:path';
911
import { buildApplication } from '../../index';
1012
import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup';
1113

@@ -409,5 +411,131 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {
409411
harness.expectFile('dist/browser/test.svg').toNotExist();
410412
});
411413
});
414+
415+
describe('symbolic links', () => {
416+
let outsideDirectory: string;
417+
418+
beforeEach(() => {
419+
// The target has to stay inside the Bazel sandbox. Bazel patches Node's file system
420+
// module so that a link leaving the sandbox is reported as a regular file, which
421+
// would hide the link from the builder under test. A sibling of the workspace root
422+
// is outside of the workspace while remaining inside the sandbox.
423+
outsideDirectory = fs.mkdtempSync(
424+
path.join(path.dirname(harness.resolvePath('.')), 'outside-workspace-'),
425+
);
426+
fs.writeFileSync(path.join(outsideDirectory, 'secret.txt'), 'secret');
427+
});
428+
429+
afterEach(() => {
430+
fs.rmSync(outsideDirectory, { recursive: true, force: true });
431+
});
432+
433+
it('does not copy files behind a directory link by default', async () => {
434+
await harness.writeFile('public/favicon.ico', 'icon');
435+
fs.symlinkSync(outsideDirectory, harness.resolvePath('public/docs'), 'junction');
436+
437+
harness.useTarget('build', {
438+
...BASE_OPTIONS,
439+
assets: [{ glob: '**/*', input: 'public', output: '.' }],
440+
});
441+
442+
const { result } = await harness.executeOnce();
443+
444+
expect(result?.success).toBe(true);
445+
446+
harness.expectFile('dist/browser/favicon.ico').toExist();
447+
harness.expectFile('dist/browser/docs/secret.txt').toNotExist();
448+
});
449+
450+
it('does not copy a file link by default', async () => {
451+
await harness.writeFile('public/favicon.ico', 'icon');
452+
fs.symlinkSync(
453+
path.join(outsideDirectory, 'secret.txt'),
454+
harness.resolvePath('public/notes.txt'),
455+
);
456+
457+
harness.useTarget('build', {
458+
...BASE_OPTIONS,
459+
assets: [{ glob: '**/*', input: 'public', output: '.' }],
460+
});
461+
462+
const { result } = await harness.executeOnce();
463+
464+
expect(result?.success).toBe(true);
465+
466+
harness.expectFile('dist/browser/favicon.ico').toExist();
467+
harness.expectFile('dist/browser/notes.txt').toNotExist();
468+
});
469+
470+
it('copies files behind a directory link within the workspace root when enabled', async () => {
471+
await harness.writeFile('public/favicon.ico', 'icon');
472+
await harness.writeFile('shared/logo.svg', '<svg></svg>');
473+
fs.symlinkSync(
474+
harness.resolvePath('shared'),
475+
harness.resolvePath('public/branding'),
476+
'junction',
477+
);
478+
479+
harness.useTarget('build', {
480+
...BASE_OPTIONS,
481+
assets: [{ glob: '**/*', input: 'public', output: '.', followSymlinks: true }],
482+
});
483+
484+
const { result } = await harness.executeOnce();
485+
486+
expect(result?.success).toBe(true);
487+
488+
harness.expectFile('dist/browser/branding/logo.svg').content.toBe('<svg></svg>');
489+
});
490+
491+
it('fails if asset input option is a link outside workspace root', async () => {
492+
fs.symlinkSync(outsideDirectory, harness.resolvePath('public'), 'junction');
493+
494+
harness.useTarget('build', {
495+
...BASE_OPTIONS,
496+
assets: [{ glob: '**/*', input: 'public', output: '.' }],
497+
});
498+
499+
const { error } = await harness.executeOnce({ outputLogsOnException: false });
500+
501+
expect(error?.message).toContain('asset path must be within the workspace root');
502+
503+
harness.expectFile('dist/browser/secret.txt').toNotExist();
504+
});
505+
506+
it('fails if a glob rooted in a directory link resolves outside workspace root', async () => {
507+
await harness.writeFile('public/favicon.ico', 'icon');
508+
fs.symlinkSync(outsideDirectory, harness.resolvePath('public/docs'), 'junction');
509+
510+
// A static directory prefix makes the globber start its walk inside the link, which
511+
// is read through even though links are not followed.
512+
harness.useTarget('build', {
513+
...BASE_OPTIONS,
514+
assets: [{ glob: 'docs/**/*', input: 'public', output: '.' }],
515+
});
516+
517+
const { error } = await harness.executeOnce({ outputLogsOnException: false });
518+
519+
expect(error?.message).toContain('asset path must be within the workspace root');
520+
521+
harness.expectFile('dist/browser/docs/secret.txt').toNotExist();
522+
});
523+
524+
it('fails if a followed link resolves outside workspace root', async () => {
525+
await harness.writeFile('public/favicon.ico', 'icon');
526+
fs.symlinkSync(outsideDirectory, harness.resolvePath('public/docs'), 'junction');
527+
528+
harness.useTarget('build', {
529+
...BASE_OPTIONS,
530+
assets: [{ glob: '**/*', input: 'public', output: '.', followSymlinks: true }],
531+
});
532+
533+
const { error } = await harness.executeOnce({ outputLogsOnException: false });
534+
535+
expect(error?.message).toContain('asset path must be within the workspace root');
536+
537+
harness.expectFile('dist/browser/docs/secret.txt').toNotExist();
538+
});
539+
});
412540
});
413541
});

‎packages/angular/build/src/utils/path.ts‎

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

9-
import { isAbsolute, posix, relative, resolve } from 'node:path';
9+
import { realpath } from 'node:fs/promises';
10+
import { isAbsolute, normalize, posix, relative, resolve } from 'node:path';
1011
import { platform } from 'node:process';
1112

1213
const WINDOWS_PATH_SEPERATOR_REGEXP = /\\/g;
@@ -51,6 +52,37 @@ export function isSubDirectory(parent: string, child: string): boolean {
5152
return relativePath !== '..' && !relativePath.startsWith('../') && !isAbsolute(relativePath);
5253
}
5354

55+
/**
56+
* Determines if a path points into an installed dependency, that is, if it goes through a
57+
* `node_modules` directory.
58+
*
59+
* A package manager links dependencies to wherever it stores them, which for a pnpm or npm
60+
* workspace is the repository root rather than the workspace being built. Those links are
61+
* created by the tool, so a path that asks for one is allowed to resolve outside of the
62+
* workspace root, while a path into the project's own sources is not.
63+
*
64+
* @param pathString - The path to check, as it was configured.
65+
* @returns `true` if the path goes through a `node_modules` directory, `false` otherwise.
66+
*/
67+
export function isDependencyPath(pathString: string): boolean {
68+
return toPosixPath(normalize(pathString)).split(posix.sep).includes('node_modules');
69+
}
70+
71+
/**
72+
* Resolves a path to its real location on disk, following any symbolic links.
73+
*
74+
* @param pathString - The file path to resolve.
75+
* @returns The canonicalized real path, or `undefined` when the path cannot be resolved,
76+
* for instance because it does not exist.
77+
*/
78+
export async function resolveRealPath(pathString: string): Promise<string | undefined> {
79+
try {
80+
return canonicalizePath(await realpath(pathString));
81+
} catch {
82+
return undefined;
83+
}
84+
}
85+
5486
/**
5587
* Canonicalizes a file path by normalising Windows drive-letter casing to uppercase.
5688
*

‎packages/angular/build/src/utils/resolve-assets.ts‎

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
import path from 'node:path';
1010
import { glob } from 'tinyglobby';
11-
import { isSubDirectory } from './path';
11+
import { isDependencyPath, isSubDirectory, resolveRealPath } from './path';
1212

1313
export async function resolveAssets(
1414
entries: {
@@ -24,6 +24,8 @@ export async function resolveAssets(
2424
const defaultIgnore = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'];
2525

2626
const outputFiles: { source: string; destination: string }[] = [];
27+
const resolvedRoot = path.resolve(root);
28+
const realRoot = (await resolveRealPath(resolvedRoot)) ?? resolvedRoot;
2729

2830
for (const entry of entries) {
2931
if (!isSubDirectory(root, entry.input)) {
@@ -32,15 +34,56 @@ export async function resolveAssets(
3234

3335
const cwd = path.resolve(root, entry.input);
3436

37+
// The check above compares paths textually, while a symbolic link only resolves to its
38+
// target on disk. An input that appears to be inside the workspace root can therefore
39+
// still point outside of it. A path that cannot be resolved does not exist and has
40+
// nothing to read.
41+
const realCwd = await resolveRealPath(cwd);
42+
43+
// An input that asks for a dependency is allowed to resolve out of the workspace root,
44+
// and what it resolves to becomes the boundary for its own matches instead.
45+
const dependencyRoot = isDependencyPath(entry.input) ? realCwd : undefined;
46+
47+
if (
48+
dependencyRoot === undefined &&
49+
realCwd !== undefined &&
50+
!isSubDirectory(realRoot, realCwd)
51+
) {
52+
throw new Error(
53+
`The ${entry.input} asset path must be within the workspace root. ` +
54+
`It resolves to '${realCwd}' through a symbolic link.`,
55+
);
56+
}
57+
3558
const files = await glob(entry.glob, {
3659
cwd,
3760
dot: true,
3861
ignore: entry.ignore ? defaultIgnore.concat(entry.ignore) : defaultIgnore,
39-
followSymbolicLinks: entry.followSymlinks,
62+
// Schema defaults are not applied to builder options, so the documented default of
63+
// 'false' has to be provided here. Without it the globber follows symbolic links.
64+
followSymbolicLinks: entry.followSymlinks ?? false,
4065
});
4166

4267
for (const file of files) {
4368
const src = path.join(cwd, file);
69+
70+
// Only the input is checked above, and a match can leave the workspace root without
71+
// it. A pattern that walks back out, such as '../../outside/*', is joined to the
72+
// input, and a pattern with a static directory prefix, such as 'docs/**/*', makes the
73+
// globber start from that directory, which is read through even when it is a link and
74+
// links are not followed. Every match is therefore resolved and checked.
75+
const realSrc = await resolveRealPath(src);
76+
if (
77+
realSrc !== undefined &&
78+
!isSubDirectory(realRoot, realSrc) &&
79+
!(dependencyRoot !== undefined && isSubDirectory(dependencyRoot, realSrc))
80+
) {
81+
throw new Error(
82+
`The ${entry.input} asset path must be within the workspace root. ` +
83+
`'${file}' resolves to '${realSrc}', which is outside of it.`,
84+
);
85+
}
86+
4487
const filePath = entry.flatten ? path.basename(file) : file;
4588

4689
outputFiles.push({ source: src, destination: path.join(entry.output, filePath) });

0 commit comments

Comments
 (0)