Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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', '<svg></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('<svg></svg>');
});

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();
});
});
});
});
34 changes: 33 additions & 1 deletion packages/angular/build/src/utils/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<string | undefined> {
try {
return canonicalizePath(await realpath(pathString));
} catch {
return undefined;
}
}

/**
* Canonicalizes a file path by normalising Windows drive-letter casing to uppercase.
*
Expand Down
47 changes: 45 additions & 2 deletions packages/angular/build/src/utils/resolve-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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)) {
Expand All @@ -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) });
Expand Down
Loading
Loading