From d7b81171f86c78f816209e7506f28a6621650287 Mon Sep 17 00:00:00 2001
From: SkyZeroZx <73321943+SkyZeroZx@users.noreply.github.com>
Date: Thu, 24 Sep 2026 13:29:25 -0500
Subject: [PATCH] fix(@angular/build): contain asset reads within the workspace
root
Asset inputs are checked against the workspace root, but the check only compares paths as text. A symbolic link resolves 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 output.
Not following links does not help either. A pattern such as 'docs/**/*' makes the globber start 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 on its own, since only the input was ever checked.
Every match is now resolved to its real location and has to stay inside the workspace root. 'followSymlinks' also defaults to 'false', as the schema documents. An input that points into 'node_modules' is contained to its own resolved directory instead, because package managers link dependencies to the repository root and requiring them to stay inside would break pnpm and npm workspaces.
The webpack builders in '@angular-devkit/build-angular' get the same containment.
Fixes #34164
---
.../src/builders/application/schema.json | 2 +-
.../application/tests/options/assets_spec.ts | 128 ++++++++++++
packages/angular/build/src/utils/path.ts | 34 +++-
.../angular/build/src/utils/resolve-assets.ts | 47 ++++-
.../build/src/utils/resolve-assets_spec.ts | 182 ++++++++++++++++++
.../src/builders/browser-esbuild/schema.json | 2 +-
.../src/builders/browser/schema.json | 2 +-
.../src/builders/server/schema.json | 2 +-
.../build_angular/src/utils/asset-paths.ts | 46 +++++
.../build_angular/src/utils/copy-assets.ts | 29 ++-
.../src/utils/copy-assets_spec.ts | 143 ++++++++++++++
.../build_angular/src/utils/i18n-inlining.ts | 7 +-
.../src/utils/normalize-asset-patterns.ts | 27 ++-
.../utils/normalize-asset-patterns_spec.ts | 68 +++++++
14 files changed, 703 insertions(+), 16 deletions(-)
create mode 100644 packages/angular/build/src/utils/resolve-assets_spec.ts
create mode 100644 packages/angular_devkit/build_angular/src/utils/asset-paths.ts
create mode 100644 packages/angular_devkit/build_angular/src/utils/copy-assets_spec.ts
create mode 100644 packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns_spec.ts
diff --git a/packages/angular/build/src/builders/application/schema.json b/packages/angular/build/src/builders/application/schema.json
index 8458d385a3fc..7f496f86094d 100644
--- a/packages/angular/build/src/builders/application/schema.json
+++ b/packages/angular/build/src/builders/application/schema.json
@@ -633,7 +633,7 @@
"followSymlinks": {
"type": "boolean",
"default": false,
- "description": "Allow glob patterns to follow symlink directories. This allows subdirectories of the symlink to be searched."
+ "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."
},
"glob": {
"type": "string",
diff --git a/packages/angular/build/src/builders/application/tests/options/assets_spec.ts b/packages/angular/build/src/builders/application/tests/options/assets_spec.ts
index afa42cc1804e..ad4e54a11654 100644
--- a/packages/angular/build/src/builders/application/tests/options/assets_spec.ts
+++ b/packages/angular/build/src/builders/application/tests/options/assets_spec.ts
@@ -6,6 +6,8 @@
* found in the LICENSE file at https://angular.dev/license
*/
+import * as fs from 'node:fs';
+import * as path from 'node:path';
import { buildApplication } from '../../index';
import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup';
@@ -409,5 +411,131 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {
harness.expectFile('dist/browser/test.svg').toNotExist();
});
});
+
+ describe('symbolic links', () => {
+ let outsideDirectory: string;
+
+ beforeEach(() => {
+ // The target has to stay inside the Bazel sandbox. Bazel patches Node's file system
+ // module so that a link leaving the sandbox is reported as a regular file, which
+ // would hide the link from the builder under test. A sibling of the workspace root
+ // is outside of the workspace while remaining inside the sandbox.
+ outsideDirectory = fs.mkdtempSync(
+ path.join(path.dirname(harness.resolvePath('.')), 'outside-workspace-'),
+ );
+ fs.writeFileSync(path.join(outsideDirectory, 'secret.txt'), 'secret');
+ });
+
+ afterEach(() => {
+ fs.rmSync(outsideDirectory, { recursive: true, force: true });
+ });
+
+ it('does not copy files behind a directory link by default', async () => {
+ await harness.writeFile('public/favicon.ico', 'icon');
+ fs.symlinkSync(outsideDirectory, harness.resolvePath('public/docs'), 'junction');
+
+ harness.useTarget('build', {
+ ...BASE_OPTIONS,
+ assets: [{ glob: '**/*', input: 'public', output: '.' }],
+ });
+
+ const { result } = await harness.executeOnce();
+
+ expect(result?.success).toBe(true);
+
+ harness.expectFile('dist/browser/favicon.ico').toExist();
+ harness.expectFile('dist/browser/docs/secret.txt').toNotExist();
+ });
+
+ it('does not copy a file link by default', async () => {
+ await harness.writeFile('public/favicon.ico', 'icon');
+ fs.symlinkSync(
+ path.join(outsideDirectory, 'secret.txt'),
+ harness.resolvePath('public/notes.txt'),
+ );
+
+ harness.useTarget('build', {
+ ...BASE_OPTIONS,
+ assets: [{ glob: '**/*', input: 'public', output: '.' }],
+ });
+
+ const { result } = await harness.executeOnce();
+
+ expect(result?.success).toBe(true);
+
+ harness.expectFile('dist/browser/favicon.ico').toExist();
+ harness.expectFile('dist/browser/notes.txt').toNotExist();
+ });
+
+ it('copies files behind a directory link within the workspace root when enabled', async () => {
+ await harness.writeFile('public/favicon.ico', 'icon');
+ await harness.writeFile('shared/logo.svg', '');
+ fs.symlinkSync(
+ harness.resolvePath('shared'),
+ harness.resolvePath('public/branding'),
+ 'junction',
+ );
+
+ harness.useTarget('build', {
+ ...BASE_OPTIONS,
+ assets: [{ glob: '**/*', input: 'public', output: '.', followSymlinks: true }],
+ });
+
+ const { result } = await harness.executeOnce();
+
+ expect(result?.success).toBe(true);
+
+ harness.expectFile('dist/browser/branding/logo.svg').content.toBe('');
+ });
+
+ it('fails if asset input option is a link outside workspace root', async () => {
+ fs.symlinkSync(outsideDirectory, harness.resolvePath('public'), 'junction');
+
+ harness.useTarget('build', {
+ ...BASE_OPTIONS,
+ assets: [{ glob: '**/*', input: 'public', output: '.' }],
+ });
+
+ const { error } = await harness.executeOnce({ outputLogsOnException: false });
+
+ expect(error?.message).toContain('asset path must be within the workspace root');
+
+ harness.expectFile('dist/browser/secret.txt').toNotExist();
+ });
+
+ it('fails if a glob rooted in a directory link resolves outside workspace root', async () => {
+ await harness.writeFile('public/favicon.ico', 'icon');
+ fs.symlinkSync(outsideDirectory, harness.resolvePath('public/docs'), 'junction');
+
+ // A static directory prefix makes the globber start its walk inside the link, which
+ // is read through even though links are not followed.
+ harness.useTarget('build', {
+ ...BASE_OPTIONS,
+ assets: [{ glob: 'docs/**/*', input: 'public', output: '.' }],
+ });
+
+ const { error } = await harness.executeOnce({ outputLogsOnException: false });
+
+ expect(error?.message).toContain('asset path must be within the workspace root');
+
+ harness.expectFile('dist/browser/docs/secret.txt').toNotExist();
+ });
+
+ it('fails if a followed link resolves outside workspace root', async () => {
+ await harness.writeFile('public/favicon.ico', 'icon');
+ fs.symlinkSync(outsideDirectory, harness.resolvePath('public/docs'), 'junction');
+
+ harness.useTarget('build', {
+ ...BASE_OPTIONS,
+ assets: [{ glob: '**/*', input: 'public', output: '.', followSymlinks: true }],
+ });
+
+ const { error } = await harness.executeOnce({ outputLogsOnException: false });
+
+ expect(error?.message).toContain('asset path must be within the workspace root');
+
+ harness.expectFile('dist/browser/docs/secret.txt').toNotExist();
+ });
+ });
});
});
diff --git a/packages/angular/build/src/utils/path.ts b/packages/angular/build/src/utils/path.ts
index a236878d134e..279971a76ac1 100644
--- a/packages/angular/build/src/utils/path.ts
+++ b/packages/angular/build/src/utils/path.ts
@@ -6,7 +6,8 @@
* found in the LICENSE file at https://angular.dev/license
*/
-import { isAbsolute, posix, relative, resolve } from 'node:path';
+import { realpath } from 'node:fs/promises';
+import { isAbsolute, normalize, posix, relative, resolve } from 'node:path';
import { platform } from 'node:process';
const WINDOWS_PATH_SEPERATOR_REGEXP = /\\/g;
@@ -51,6 +52,37 @@ export function isSubDirectory(parent: string, child: string): boolean {
return relativePath !== '..' && !relativePath.startsWith('../') && !isAbsolute(relativePath);
}
+/**
+ * Determines if a path points into an installed dependency, that is, if it goes through a
+ * `node_modules` directory.
+ *
+ * A package manager links dependencies to wherever it stores them, which for a pnpm or npm
+ * workspace is the repository root rather than the workspace being built. Those links are
+ * created by the tool, so a path that asks for one is allowed to resolve outside of the
+ * workspace root, while a path into the project's own sources is not.
+ *
+ * @param pathString - The path to check, as it was configured.
+ * @returns `true` if the path goes through a `node_modules` directory, `false` otherwise.
+ */
+export function isDependencyPath(pathString: string): boolean {
+ return toPosixPath(normalize(pathString)).split(posix.sep).includes('node_modules');
+}
+
+/**
+ * Resolves a path to its real location on disk, following any symbolic links.
+ *
+ * @param pathString - The file path to resolve.
+ * @returns The canonicalized real path, or `undefined` when the path cannot be resolved,
+ * for instance because it does not exist.
+ */
+export async function resolveRealPath(pathString: string): Promise {
+ try {
+ return canonicalizePath(await realpath(pathString));
+ } catch {
+ return undefined;
+ }
+}
+
/**
* Canonicalizes a file path by normalising Windows drive-letter casing to uppercase.
*
diff --git a/packages/angular/build/src/utils/resolve-assets.ts b/packages/angular/build/src/utils/resolve-assets.ts
index 71b1c0e4768b..7f6bd297e6ed 100644
--- a/packages/angular/build/src/utils/resolve-assets.ts
+++ b/packages/angular/build/src/utils/resolve-assets.ts
@@ -8,7 +8,7 @@
import path from 'node:path';
import { glob } from 'tinyglobby';
-import { isSubDirectory } from './path';
+import { isDependencyPath, isSubDirectory, resolveRealPath } from './path';
export async function resolveAssets(
entries: {
@@ -24,6 +24,8 @@ export async function resolveAssets(
const defaultIgnore = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'];
const outputFiles: { source: string; destination: string }[] = [];
+ const resolvedRoot = path.resolve(root);
+ const realRoot = (await resolveRealPath(resolvedRoot)) ?? resolvedRoot;
for (const entry of entries) {
if (!isSubDirectory(root, entry.input)) {
@@ -32,15 +34,56 @@ export async function resolveAssets(
const cwd = path.resolve(root, entry.input);
+ // The check above compares paths textually, while a symbolic link only resolves to its
+ // target on disk. An input that appears to be inside the workspace root can therefore
+ // still point outside of it. A path that cannot be resolved does not exist and has
+ // nothing to read.
+ const realCwd = await resolveRealPath(cwd);
+
+ // An input that asks for a dependency is allowed to resolve out of the workspace root,
+ // and what it resolves to becomes the boundary for its own matches instead.
+ const dependencyRoot = isDependencyPath(entry.input) ? realCwd : undefined;
+
+ if (
+ dependencyRoot === undefined &&
+ realCwd !== undefined &&
+ !isSubDirectory(realRoot, realCwd)
+ ) {
+ throw new Error(
+ `The ${entry.input} asset path must be within the workspace root. ` +
+ `It resolves to '${realCwd}' through a symbolic link.`,
+ );
+ }
+
const files = await glob(entry.glob, {
cwd,
dot: true,
ignore: entry.ignore ? defaultIgnore.concat(entry.ignore) : defaultIgnore,
- followSymbolicLinks: entry.followSymlinks,
+ // Schema defaults are not applied to builder options, so the documented default of
+ // 'false' has to be provided here. Without it the globber follows symbolic links.
+ followSymbolicLinks: entry.followSymlinks ?? false,
});
for (const file of files) {
const src = path.join(cwd, file);
+
+ // Only the input is checked above, and a match can leave the workspace root without
+ // it. A pattern that walks back out, such as '../../outside/*', is joined to the
+ // input, and a pattern with a static directory prefix, such as 'docs/**/*', makes the
+ // globber start from that directory, which is read through even when it is a link and
+ // links are not followed. Every match is therefore resolved and checked.
+ const realSrc = await resolveRealPath(src);
+ if (
+ realSrc !== undefined &&
+ !isSubDirectory(realRoot, realSrc) &&
+ !(dependencyRoot !== undefined && isSubDirectory(dependencyRoot, realSrc))
+ ) {
+ throw new Error(
+ `The ${entry.input} asset path must be within the workspace root. ` +
+ `'${file}' resolves to '${realSrc}', which is outside of it.`,
+ );
+ }
+
const filePath = entry.flatten ? path.basename(file) : file;
outputFiles.push({ source: src, destination: path.join(entry.output, filePath) });
diff --git a/packages/angular/build/src/utils/resolve-assets_spec.ts b/packages/angular/build/src/utils/resolve-assets_spec.ts
new file mode 100644
index 000000000000..0c68f1f3390d
--- /dev/null
+++ b/packages/angular/build/src/utils/resolve-assets_spec.ts
@@ -0,0 +1,182 @@
+/**
+ * @license
+ * Copyright Google LLC All Rights Reserved.
+ *
+ * Use of this source code is governed by an MIT-style license that can be
+ * found in the LICENSE file at https://angular.dev/license
+ */
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { resolveAssets } from './resolve-assets';
+
+describe('resolveAssets', () => {
+ let tempDir: string;
+ let workspaceRoot: string;
+ let outsideDir: string;
+
+ beforeEach(() => {
+ tempDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'resolve-assets-')));
+
+ workspaceRoot = path.join(tempDir, 'workspace');
+ fs.mkdirSync(path.join(workspaceRoot, 'public'), { recursive: true });
+ fs.writeFileSync(path.join(workspaceRoot, 'public', 'favicon.ico'), 'icon');
+
+ outsideDir = path.join(tempDir, 'outside');
+ fs.mkdirSync(outsideDir, { recursive: true });
+ fs.writeFileSync(path.join(outsideDir, 'secret.txt'), 'secret');
+ });
+
+ afterEach(() => {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ const publicAssets = (followSymlinks?: boolean) => [
+ { glob: '**/*', input: 'public', output: '.', followSymlinks },
+ ];
+
+ it('resolves the files within the input directory', async () => {
+ const assets = await resolveAssets(publicAssets(), workspaceRoot);
+
+ expect(assets.map(({ destination }) => destination)).toEqual(['favicon.ico']);
+ });
+
+ it('does not follow a directory symlink by default', async () => {
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'public', 'docs'), 'junction');
+
+ const assets = await resolveAssets(publicAssets(), workspaceRoot);
+
+ expect(assets.map(({ destination }) => destination)).toEqual(['favicon.ico']);
+ });
+
+ it('does not follow a file symlink by default', async () => {
+ fs.symlinkSync(
+ path.join(outsideDir, 'secret.txt'),
+ path.join(workspaceRoot, 'public', 'notes.txt'),
+ );
+
+ const assets = await resolveAssets(publicAssets(), workspaceRoot);
+
+ expect(assets.map(({ destination }) => destination)).toEqual(['favicon.ico']);
+ });
+
+ it('follows a directory symlink that stays within the workspace root when enabled', async () => {
+ fs.mkdirSync(path.join(workspaceRoot, 'shared'));
+ fs.writeFileSync(path.join(workspaceRoot, 'shared', 'logo.svg'), '');
+ fs.symlinkSync(
+ path.join(workspaceRoot, 'shared'),
+ path.join(workspaceRoot, 'public', 'branding'),
+ 'junction',
+ );
+
+ const assets = await resolveAssets(publicAssets(true), workspaceRoot);
+
+ expect(assets.map(({ destination }) => destination).sort()).toEqual([
+ path.join('branding', 'logo.svg'),
+ 'favicon.ico',
+ ]);
+ });
+
+ it('fails when the input directory is a symlink outside the workspace root', async () => {
+ fs.rmSync(path.join(workspaceRoot, 'public'), { recursive: true });
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'public'), 'junction');
+
+ await expectAsync(resolveAssets(publicAssets(), workspaceRoot)).toBeRejectedWithError(
+ /asset path must be within the workspace root/,
+ );
+ });
+
+ it('fails when the glob itself reaches outside the workspace root', async () => {
+ // Only the input is checked against the workspace root, while the pattern is joined to
+ // it and can walk back out on its own, with no link involved.
+ await expectAsync(
+ resolveAssets([{ glob: '../../outside/*', input: 'public', output: '.' }], workspaceRoot),
+ ).toBeRejectedWithError(/asset path must be within the workspace root/);
+ });
+
+ it('fails when a glob rooted in a symlink resolves outside the workspace root', async () => {
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'public', 'docs'), 'junction');
+
+ // A static directory prefix makes the globber start its walk inside the link, which is
+ // read through even though links are not followed.
+ await expectAsync(
+ resolveAssets([{ glob: 'docs/**/*', input: 'public', output: '.' }], workspaceRoot),
+ ).toBeRejectedWithError(/asset path must be within the workspace root/);
+ });
+
+ it('fails when a followed symlink resolves outside the workspace root', async () => {
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'public', 'docs'), 'junction');
+
+ await expectAsync(resolveAssets(publicAssets(true), workspaceRoot)).toBeRejectedWithError(
+ /asset path must be within the workspace root/,
+ );
+ });
+
+ it('resolves a dependency linked outside the workspace root', async () => {
+ // A package manager keeps the packages of a workspace at the repository root and links
+ // to them, so a dependency resolves out of the workspace being built.
+ const packageDirectory = path.join(tempDir, 'packages', 'theme', 'assets');
+ fs.mkdirSync(packageDirectory, { recursive: true });
+ fs.writeFileSync(path.join(packageDirectory, 'logo.svg'), '');
+ fs.mkdirSync(path.join(workspaceRoot, 'node_modules', '@company'), { recursive: true });
+ fs.symlinkSync(
+ path.join(tempDir, 'packages', 'theme'),
+ path.join(workspaceRoot, 'node_modules', '@company', 'theme'),
+ 'junction',
+ );
+
+ const assets = await resolveAssets(
+ [{ glob: '**/*', input: 'node_modules/@company/theme/assets', output: 'assets' }],
+ workspaceRoot,
+ );
+
+ expect(assets.map(({ destination }) => destination)).toEqual([path.join('assets', 'logo.svg')]);
+ });
+
+ it('fails when a dependency links back out of itself', async () => {
+ fs.mkdirSync(path.join(workspaceRoot, 'node_modules', 'theme', 'assets'), { recursive: true });
+ fs.symlinkSync(
+ outsideDir,
+ path.join(workspaceRoot, 'node_modules', 'theme', 'assets', 'docs'),
+ 'junction',
+ );
+
+ await expectAsync(
+ resolveAssets(
+ [{ glob: 'docs/**/*', input: 'node_modules/theme/assets', output: 'assets' }],
+ workspaceRoot,
+ ),
+ ).toBeRejectedWithError(/asset path must be within the workspace root/);
+ });
+
+ it('resolves an input directory that does not exist', async () => {
+ const assets = await resolveAssets(
+ [{ glob: '**/*', input: 'not-created-yet', output: '.' }],
+ workspaceRoot,
+ );
+
+ expect(assets).toEqual([]);
+ });
+
+ it('resolves a missing input directory when the workspace root is reached through a symlink', async () => {
+ const linkedRoot = path.join(tempDir, 'linked-workspace');
+ fs.symlinkSync(workspaceRoot, linkedRoot, 'junction');
+
+ const assets = await resolveAssets(
+ [{ glob: '**/*', input: 'not-created-yet', output: '.' }],
+ linkedRoot,
+ );
+
+ expect(assets).toEqual([]);
+ });
+
+ it('resolves assets when the workspace root itself is reached through a symlink', async () => {
+ const linkedRoot = path.join(tempDir, 'linked-workspace');
+ fs.symlinkSync(workspaceRoot, linkedRoot, 'junction');
+
+ const assets = await resolveAssets(publicAssets(), linkedRoot);
+
+ expect(assets.map(({ destination }) => destination)).toEqual(['favicon.ico']);
+ });
+});
diff --git a/packages/angular_devkit/build_angular/src/builders/browser-esbuild/schema.json b/packages/angular_devkit/build_angular/src/builders/browser-esbuild/schema.json
index edb91222d954..4735a5f19a23 100644
--- a/packages/angular_devkit/build_angular/src/builders/browser-esbuild/schema.json
+++ b/packages/angular_devkit/build_angular/src/builders/browser-esbuild/schema.json
@@ -447,7 +447,7 @@
"followSymlinks": {
"type": "boolean",
"default": false,
- "description": "Allow glob patterns to follow symlink directories. This allows subdirectories of the symlink to be searched."
+ "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."
},
"glob": {
"type": "string",
diff --git a/packages/angular_devkit/build_angular/src/builders/browser/schema.json b/packages/angular_devkit/build_angular/src/builders/browser/schema.json
index 301eeafcc4f1..27b6b9315f84 100644
--- a/packages/angular_devkit/build_angular/src/builders/browser/schema.json
+++ b/packages/angular_devkit/build_angular/src/builders/browser/schema.json
@@ -435,7 +435,7 @@
"followSymlinks": {
"type": "boolean",
"default": false,
- "description": "Allow glob patterns to follow symlink directories. This allows subdirectories of the symlink to be searched."
+ "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."
},
"glob": {
"type": "string",
diff --git a/packages/angular_devkit/build_angular/src/builders/server/schema.json b/packages/angular_devkit/build_angular/src/builders/server/schema.json
index 2375e1176add..33f138c32912 100644
--- a/packages/angular_devkit/build_angular/src/builders/server/schema.json
+++ b/packages/angular_devkit/build_angular/src/builders/server/schema.json
@@ -232,7 +232,7 @@
"followSymlinks": {
"type": "boolean",
"default": false,
- "description": "Allow glob patterns to follow symlink directories. This allows subdirectories of the symlink to be searched."
+ "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."
},
"glob": {
"type": "string",
diff --git a/packages/angular_devkit/build_angular/src/utils/asset-paths.ts b/packages/angular_devkit/build_angular/src/utils/asset-paths.ts
new file mode 100644
index 000000000000..1b4d20ce5944
--- /dev/null
+++ b/packages/angular_devkit/build_angular/src/utils/asset-paths.ts
@@ -0,0 +1,46 @@
+/**
+ * @license
+ * Copyright Google LLC All Rights Reserved.
+ *
+ * Use of this source code is governed by an MIT-style license that can be
+ * found in the LICENSE file at https://angular.dev/license
+ */
+
+import { realpathSync } from 'node:fs';
+import * as path from 'node:path';
+
+/**
+ * Resolves a path to its real location on disk, following any symbolic links.
+ *
+ * Returns `undefined` when the path cannot be resolved, for instance because it does
+ * not exist.
+ */
+export function resolveRealPath(pathString: string): string | undefined {
+ try {
+ return realpathSync(pathString);
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Determines if a path is a subdirectory or file within a parent directory.
+ */
+export function isWithinDirectory(parent: string, child: string): boolean {
+ const relativePath = path.relative(parent, child);
+
+ return !relativePath.startsWith('..') && !path.isAbsolute(relativePath);
+}
+
+/**
+ * Determines if a path points into an installed dependency, that is, if it goes through a
+ * `node_modules` directory.
+ *
+ * A package manager links dependencies to wherever it stores them, which for a pnpm or npm
+ * workspace is the repository root rather than the workspace being built. Those links are
+ * created by the tool, so a path that asks for one is allowed to resolve outside of the
+ * workspace root, while a path into the project's own sources is not.
+ */
+export function isDependencyPath(pathString: string): boolean {
+ return path.normalize(pathString).split(/[\\/]/).includes('node_modules');
+}
diff --git a/packages/angular_devkit/build_angular/src/utils/copy-assets.ts b/packages/angular_devkit/build_angular/src/utils/copy-assets.ts
index ed739970cd09..335581e1c1d2 100644
--- a/packages/angular_devkit/build_angular/src/utils/copy-assets.ts
+++ b/packages/angular_devkit/build_angular/src/utils/copy-assets.ts
@@ -9,6 +9,7 @@
import fs from 'node:fs';
import path from 'node:path';
import { glob } from 'tinyglobby';
+import { isDependencyPath, isWithinDirectory, resolveRealPath } from './asset-paths';
export async function copyAssets(
entries: {
@@ -26,14 +27,22 @@ export async function copyAssets(
const defaultIgnore = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'];
const outputFiles: { source: string; destination: string }[] = [];
+ const resolvedRoot = path.resolve(root);
+ const realRoot = resolveRealPath(resolvedRoot) ?? resolvedRoot;
for (const entry of entries) {
const cwd = path.resolve(root, entry.input);
+
+ // An input that asks for a dependency is allowed to resolve out of the workspace root,
+ // and what it resolves to becomes the boundary for its own matches instead.
+ const dependencyRoot = isDependencyPath(entry.input) ? resolveRealPath(cwd) : undefined;
const files = await glob(entry.glob, {
cwd,
dot: true,
ignore: entry.ignore ? defaultIgnore.concat(entry.ignore) : defaultIgnore,
- followSymbolicLinks: entry.followSymlinks,
+ // Schema defaults are not applied to builder options, so the documented default of
+ // 'false' has to be provided here. Without it the globber follows symbolic links.
+ followSymbolicLinks: entry.followSymlinks ?? false,
});
const directoryExists = new Set();
@@ -44,6 +53,24 @@ export async function copyAssets(
continue;
}
+ // Only the input is checked by `normalizeAssetPatterns`, and a match can leave the
+ // workspace root without it. A pattern that walks back out, such as '../../outside/*',
+ // is joined to the input, and a pattern with a static directory prefix, such as
+ // 'docs/**/*', makes the globber start from that directory, which is read through even
+ // when it is a link and links are not followed. Every match is therefore resolved and
+ // checked.
+ const realSrc = resolveRealPath(src);
+ if (
+ realSrc !== undefined &&
+ !isWithinDirectory(realRoot, realSrc) &&
+ !(dependencyRoot !== undefined && isWithinDirectory(dependencyRoot, realSrc))
+ ) {
+ throw new Error(
+ `The ${entry.input} asset path must be within the workspace root. ` +
+ `'${file}' resolves to '${realSrc}', which is outside of it.`,
+ );
+ }
+
const filePath = entry.flatten ? path.basename(file) : file;
outputFiles.push({ source: src, destination: path.join(entry.output, filePath) });
diff --git a/packages/angular_devkit/build_angular/src/utils/copy-assets_spec.ts b/packages/angular_devkit/build_angular/src/utils/copy-assets_spec.ts
new file mode 100644
index 000000000000..d62335b08b01
--- /dev/null
+++ b/packages/angular_devkit/build_angular/src/utils/copy-assets_spec.ts
@@ -0,0 +1,143 @@
+/**
+ * @license
+ * Copyright Google LLC All Rights Reserved.
+ *
+ * Use of this source code is governed by an MIT-style license that can be
+ * found in the LICENSE file at https://angular.dev/license
+ */
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { copyAssets } from './copy-assets';
+
+describe('copyAssets', () => {
+ let tempDir: string;
+ let workspaceRoot: string;
+ let outputDir: string;
+ let outsideDir: string;
+
+ beforeEach(() => {
+ tempDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'copy-assets-')));
+
+ workspaceRoot = path.join(tempDir, 'workspace');
+ fs.mkdirSync(path.join(workspaceRoot, 'public'), { recursive: true });
+ fs.writeFileSync(path.join(workspaceRoot, 'public', 'favicon.ico'), 'icon');
+
+ outputDir = path.join(tempDir, 'output');
+ fs.mkdirSync(outputDir, { recursive: true });
+
+ outsideDir = path.join(tempDir, 'outside');
+ fs.mkdirSync(outsideDir, { recursive: true });
+ fs.writeFileSync(path.join(outsideDir, 'secret.txt'), 'secret');
+ });
+
+ afterEach(() => {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ const copyPublic = (glob = '**/*', followSymlinks?: boolean) =>
+ copyAssets(
+ [{ glob, input: 'public', output: '.', followSymlinks }],
+ [outputDir],
+ workspaceRoot,
+ );
+
+ it('copies the files within the input directory', async () => {
+ const assets = await copyPublic();
+
+ expect(assets.map(({ destination }) => destination)).toEqual(['favicon.ico']);
+ expect(fs.existsSync(path.join(outputDir, 'favicon.ico'))).toBeTrue();
+ });
+
+ it('does not follow a directory symlink by default', async () => {
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'public', 'docs'), 'junction');
+
+ const assets = await copyPublic();
+
+ expect(assets.map(({ destination }) => destination)).toEqual(['favicon.ico']);
+ expect(fs.existsSync(path.join(outputDir, 'docs', 'secret.txt'))).toBeFalse();
+ });
+
+ it('fails when the glob itself reaches outside the workspace root', async () => {
+ // Only the input is checked against the workspace root, while the pattern is joined to
+ // it and can walk back out on its own, with no link involved.
+ await expectAsync(copyPublic('../../outside/*')).toBeRejectedWithError(
+ /asset path must be within the workspace root/,
+ );
+
+ expect(fs.existsSync(path.join(outputDir, 'secret.txt'))).toBeFalse();
+ });
+
+ it('fails when a glob rooted in a symlink resolves outside the workspace root', async () => {
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'public', 'docs'), 'junction');
+
+ // A static directory prefix makes the globber start its walk inside the link, which is
+ // read through even though links are not followed.
+ await expectAsync(copyPublic('docs/**/*')).toBeRejectedWithError(
+ /asset path must be within the workspace root/,
+ );
+
+ expect(fs.existsSync(path.join(outputDir, 'docs', 'secret.txt'))).toBeFalse();
+ });
+
+ it('fails when a followed symlink resolves outside the workspace root', async () => {
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'public', 'docs'), 'junction');
+
+ await expectAsync(copyPublic('**/*', true)).toBeRejectedWithError(
+ /asset path must be within the workspace root/,
+ );
+
+ expect(fs.existsSync(path.join(outputDir, 'docs', 'secret.txt'))).toBeFalse();
+ });
+
+ it('follows a directory symlink that stays within the workspace root when enabled', async () => {
+ fs.mkdirSync(path.join(workspaceRoot, 'shared'));
+ fs.writeFileSync(path.join(workspaceRoot, 'shared', 'logo.svg'), '');
+ fs.symlinkSync(
+ path.join(workspaceRoot, 'shared'),
+ path.join(workspaceRoot, 'public', 'branding'),
+ 'junction',
+ );
+
+ const assets = await copyPublic('**/*', true);
+
+ expect(assets.map(({ destination }) => destination).sort()).toEqual([
+ path.join('branding', 'logo.svg'),
+ 'favicon.ico',
+ ]);
+ });
+
+ it('copies a directory that is given as the root', async () => {
+ // Localization copies an already built output directory by passing it as the root.
+ const assets = await copyAssets(
+ [{ glob: '**/*', input: '.', output: '' }],
+ [outputDir],
+ outsideDir,
+ );
+
+ expect(assets.map(({ destination }) => destination)).toEqual(['secret.txt']);
+ });
+
+ it('copies a dependency linked outside the workspace root', async () => {
+ // A package manager keeps the packages of a workspace at the repository root and links
+ // to them, so a dependency resolves out of the workspace being built.
+ const packageDirectory = path.join(tempDir, 'packages', 'theme', 'assets');
+ fs.mkdirSync(packageDirectory, { recursive: true });
+ fs.writeFileSync(path.join(packageDirectory, 'logo.svg'), '');
+ fs.mkdirSync(path.join(workspaceRoot, 'node_modules', '@company'), { recursive: true });
+ fs.symlinkSync(
+ path.join(tempDir, 'packages', 'theme'),
+ path.join(workspaceRoot, 'node_modules', '@company', 'theme'),
+ 'junction',
+ );
+
+ const assets = await copyAssets(
+ [{ glob: '**/*', input: 'node_modules/@company/theme/assets', output: 'assets' }],
+ [outputDir],
+ workspaceRoot,
+ );
+
+ expect(assets.map(({ destination }) => destination)).toEqual([path.join('assets', 'logo.svg')]);
+ });
+});
diff --git a/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts b/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts
index 9f639f16cb21..efbf870433cb 100644
--- a/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts
+++ b/packages/angular_devkit/build_angular/src/utils/i18n-inlining.ts
@@ -105,18 +105,19 @@ export async function i18nInlineEmittedFiles(
}
}
- // Copy any non-processed files into the output locations
+ // Copy any non-processed files into the output locations. The already built directory is
+ // the root, so that its own contents are what the copy is allowed to read.
await copyAssets(
[
{
glob: '**/*',
- input: emittedPath,
+ input: '.',
output: '',
ignore: [...processedFiles].map((f) => path.relative(emittedPath, f)),
},
],
outputPaths,
- '',
+ emittedPath,
);
} catch (err) {
assertIsError(err);
diff --git a/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns.ts b/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns.ts
index 20e97e1d5162..32ac2c0e0c5a 100644
--- a/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns.ts
+++ b/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns.ts
@@ -10,6 +10,7 @@ import assert from 'node:assert';
import { statSync } from 'node:fs';
import * as path from 'node:path';
import { AssetPattern, AssetPatternClass } from '../builders/browser/schema';
+import { isDependencyPath, isWithinDirectory, resolveRealPath } from './asset-paths';
export class MissingAssetSourceRootException extends Error {
constructor(path: string) {
@@ -27,11 +28,32 @@ export function normalizeAssetPatterns(
return [];
}
+ const resolvedWorkspaceRoot = path.resolve(workspaceRoot);
+ const realWorkspaceRoot = resolveRealPath(resolvedWorkspaceRoot) ?? resolvedWorkspaceRoot;
+
// When sourceRoot is not available, we default to ${projectRoot}/src.
const sourceRoot = projectSourceRoot || path.join(projectRoot, 'src');
const resolvedSourceRoot = path.resolve(workspaceRoot, sourceRoot);
return assetPatterns.map((assetPattern) => {
+ const inputPath = typeof assetPattern === 'string' ? assetPattern : assetPattern.input;
+ const resolvedInput = path.resolve(workspaceRoot, inputPath);
+ const realInput = resolveRealPath(resolvedInput);
+
+ // Resolving a path only compares it textually, while a symbolic link resolves to its
+ // target on disk. An input that appears to be inside the workspace root can therefore
+ // still point outside of it. An input that cannot be resolved does not exist and has
+ // nothing to read. An input that asks for a dependency is allowed to resolve out of the
+ // workspace root, because that is where a package manager keeps one.
+ if (
+ !isWithinDirectory(resolvedWorkspaceRoot, resolvedInput) ||
+ (realInput !== undefined &&
+ !isDependencyPath(inputPath) &&
+ !isWithinDirectory(realWorkspaceRoot, realInput))
+ ) {
+ throw new Error(`The ${inputPath} asset path must be within the workspace root.`);
+ }
+
// Normalize string asset patterns to objects.
if (typeof assetPattern === 'string') {
const assetPath = path.normalize(assetPattern);
@@ -68,11 +90,6 @@ export function normalizeAssetPatterns(
assetPattern = { glob, input, output };
} else {
- const resolvedInput = path.resolve(workspaceRoot, assetPattern.input);
- if (!resolvedInput.startsWith(workspaceRoot)) {
- throw new Error(`The ${assetPattern.input} asset path must be within the workspace root.`);
- }
-
assetPattern.output = path.join('.', assetPattern.output ?? '');
}
diff --git a/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns_spec.ts b/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns_spec.ts
new file mode 100644
index 000000000000..2f0c3c192175
--- /dev/null
+++ b/packages/angular_devkit/build_angular/src/utils/normalize-asset-patterns_spec.ts
@@ -0,0 +1,68 @@
+/**
+ * @license
+ * Copyright Google LLC All Rights Reserved.
+ *
+ * Use of this source code is governed by an MIT-style license that can be
+ * found in the LICENSE file at https://angular.dev/license
+ */
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { normalizeAssetPatterns } from './normalize-asset-patterns';
+
+describe('normalizeAssetPatterns', () => {
+ let tempDir: string;
+ let workspaceRoot: string;
+ let outsideDir: string;
+
+ beforeEach(() => {
+ tempDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'normalize-assets-')));
+
+ workspaceRoot = path.join(tempDir, 'workspace');
+ fs.mkdirSync(path.join(workspaceRoot, 'src', 'assets'), { recursive: true });
+
+ outsideDir = path.join(tempDir, 'outside');
+ fs.mkdirSync(outsideDir, { recursive: true });
+ fs.writeFileSync(path.join(outsideDir, 'secret.txt'), 'secret');
+ });
+
+ afterEach(() => {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ const normalize = (input: string) =>
+ normalizeAssetPatterns([{ glob: '**/*', input, output: '.' }], workspaceRoot, '', 'src');
+
+ it('normalizes an input within the workspace root', () => {
+ expect(normalize('src/assets')).toEqual([{ glob: '**/*', input: 'src/assets', output: '.' }]);
+ });
+
+ it('normalizes an input that does not exist', () => {
+ expect(normalize('src/not-created-yet')).toEqual([
+ { glob: '**/*', input: 'src/not-created-yet', output: '.' },
+ ]);
+ });
+
+ it('throws for an input outside of the workspace root', () => {
+ expect(() => normalize('../outside')).toThrowError(
+ /asset path must be within the workspace root/,
+ );
+ });
+
+ it('throws for an input that is a link outside of the workspace root', () => {
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'src', 'docs'), 'junction');
+
+ expect(() => normalize('src/docs')).toThrowError(
+ /asset path must be within the workspace root/,
+ );
+ });
+
+ it('throws for a shorthand pattern that is a link outside of the workspace root', () => {
+ fs.symlinkSync(outsideDir, path.join(workspaceRoot, 'src', 'docs'), 'junction');
+
+ expect(() => normalizeAssetPatterns(['src/docs'], workspaceRoot, '', 'src')).toThrowError(
+ /asset path must be within the workspace root/,
+ );
+ });
+});