An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): confine writes through dangling symlinks (#6513)
Joey7cd3516d68ac
diff --git a/.changeset/cli-spec-assert-within-dangling-symlinks.md b/.changeset/cli-spec-assert-within-dangling-symlinks.mdnew file mode 100644index 0000000000..63da701a52--- /dev/null+++ b/.changeset/cli-spec-assert-within-dangling-symlinks.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] Commands that write files no longer follow a dangling symlink out of the project: when the target, or a directory on the way to it, links to a missing path outside the project root, the command now fails with `ERR_PATH_TRAVERSAL` instead of creating the file there. A symlink escape reported by `integration add` now carries `ERR_PATH_TRAVERSAL` too, instead of an unregistered `PATH_TRAVERSAL` code.++@josephfarinadiff --git a/packages/cli/foundation/fs/path-safety.mjs b/packages/cli/foundation/fs/path-safety.mjsindex aab9d07015..d5b7277d95 100644--- a/packages/cli/foundation/fs/path-safety.mjs+++ b/packages/cli/foundation/fs/path-safety.mjs@@ -14,6 +14,7 @@import * as path from 'node:path';import * as fs from 'node:fs';+import {ERROR_CODES} from '../response/error-codes.mjs';/*** Error thrown by path-safety guards. Carries a stable `code`@@ -38,7 +39,7 @@ export class PathSafetyError extends Error {** - Absolute paths (e.g. `/tmp/x`) — re-rooted by `path.join` is silent;* better to fail loudly. Pass `{allowAbsolute: true}` to opt in.- * - Paths that escape via `..` segments.+ * - Paths that escape via `..` segments or a symlink, dangling or not.** Returns the resolved absolute path on success.*@@ -50,7 +51,8 @@ export class PathSafetyError extends Error {* @param {string} [options.label='path'] - Human-readable name of the arg* being checked (used in error messages, e.g. 'output directory').* @returns {string} Absolute resolved path inside `rootDir`.- * @throws {PathSafetyError}+ * @throws {PathSafetyError} An escape carries the registered+ * `ERR_PATH_TRAVERSAL`, so it reaches an envelope correctly even uncaught.*/export function assertWithin(targetPath, rootDir, options = {}) {const {allowAbsolute = false, label = 'path'} = options;@@ -83,42 +85,70 @@ export function assertWithin(targetPath, rootDir, options = {}) {throw new PathSafetyError(`Invalid ${label} "${targetPath}": resolves outside the project root ` +`(${absRoot}). Path traversal is not allowed.`,- 'PATH_TRAVERSAL',+ ERROR_CODES.ERR_PATH_TRAVERSAL,);}// path.resolve is purely lexical — it does NOT follow symlinks, so a symlink// INSIDE the root that points outside would pass the check above while the- // real write lands outside root. Canonicalize the deepest EXISTING ancestor- // (the target itself usually doesn't exist yet) and re-check against the- // realpath'd root. This closes the symlink-escape hole for every command that- // writes through this guard.+ // real write lands outside root. Canonicalize both paths through every+ // symlink, dangling ones included (a write through a dangling link creates+ // its target), and re-check.try {- const realRoot = fs.realpathSync(absRoot);- let existing = resolved;- while (!fs.existsSync(existing)) {- const parent = path.dirname(existing);- if (parent === existing) break;- existing = parent;- }- const realExisting = fs.realpathSync(existing);+ const realRoot = canonicalPath(absRoot);+ const realTarget = canonicalPath(resolved);const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : realRoot + path.sep;- if (realExisting !== realRoot && !realExisting.startsWith(realRootWithSep)) {+ if (realTarget !== realRoot && !realTarget.startsWith(realRootWithSep)) {throw new PathSafetyError(`Invalid ${label} "${targetPath}": resolves outside the project root ` +`(${absRoot}) via a symlink. Path traversal is not allowed.`,- 'PATH_TRAVERSAL',+ ERROR_CODES.ERR_PATH_TRAVERSAL,);}} catch (err) {if (err instanceof PathSafetyError) throw err;- // realpath can fail if the root doesn't exist (ENOENT) or on a race; fall- // back to the lexical result already validated above rather than crash.+ // A symlink loop, a permission error, or a race; fall back to the lexical+ // result already validated above rather than crash.}return resolved;}+/** Linux's MAXSYMLINKS; a longer chain is treated as a loop. */+const MAX_SYMLINK_HOPS = 40;++/**+ * `target` with every symlink resolved, including a dangling one, which+ * `fs.realpathSync` refuses. Components below the deepest existing entry are+ * appended as given.+ *+ * @param {string} target absolute path+ * @param {number} [hops] symlinks followed so far+ * @returns {string}+ * @throws when the chain exceeds {@link MAX_SYMLINK_HOPS} or `lstat` fails+ * for a reason other than a missing entry+ */+function canonicalPath(target, hops = 0) {+ if (hops > MAX_SYMLINK_HOPS) throw new Error(`Too many symlinks: ${target}`);+ let stat;+ try {+ stat = fs.lstatSync(target);+ } catch (err) {+ const code = /** @type {NodeJS.ErrnoException} */ (err).code;+ if (code !== 'ENOENT' && code !== 'ENOTDIR') throw err;+ const parent = path.dirname(target);+ if (parent === target) return target;+ return path.join(canonicalPath(parent, hops), path.basename(target));+ }+ try {+ return fs.realpathSync(target);+ } catch (err) {+ if (!stat.isSymbolicLink()) throw err;+ }+ const link = fs.readlinkSync(target);+ return canonicalPath(path.resolve(fs.realpathSync(path.dirname(target)), link), hops + 1);+}+/*** Validate a "name" argument (e.g. theme name, component name) that will* be embedded in a generated filename. Rejects names containing pathdiff --git a/packages/cli/foundation/fs/path-safety.test.mjs b/packages/cli/foundation/fs/path-safety.test.mjsindex 445a7c0f7c..f1822e1b8b 100644--- a/packages/cli/foundation/fs/path-safety.test.mjs+++ b/packages/cli/foundation/fs/path-safety.test.mjs@@ -19,6 +19,19 @@ afterEach(() => {fs.rmSync(tmpDir, {recursive: true, force: true});});+/**+ * The code a guard rejected with, or 'accepted'.+ * @param {() => unknown} fn+ */+function rejectionCode(fn) {+ try {+ fn();+ } catch (err) {+ return err instanceof PathSafetyError ? err.code : err;+ }+ return 'accepted';+}+describe('assertWithin', () => {it('accepts a relative path that stays inside root', () => {const result = assertWithin('subdir/file.txt', tmpDir);@@ -38,6 +51,14 @@ describe('assertWithin', () => {expect(() => assertWithin('a/b/../../../c', tmpDir)).toThrow(PathSafetyError);});+ it('reports an escape with the registered ERR_PATH_TRAVERSAL code', () => {+ // An uncaught guard error reaches the JSON envelope with this code as-is.+ expect(rejectionCode(() => assertWithin('../escaped', tmpDir))).toBe('ERR_PATH_TRAVERSAL');+ expect(+ rejectionCode(() => assertWithin('/etc/passwd', tmpDir, {allowAbsolute: true})),+ ).toBe('ERR_PATH_TRAVERSAL');+ });+it('rejects absolute paths by default', () => {expect(() => assertWithin('/tmp/elsewhere', tmpDir)).toThrow(/absolute paths are not allowed/i);});@@ -160,6 +181,7 @@ describe('assertWithin — symlink escape (realpath guard)', () => {// path.resolve is lexical and would pass this; the realpath check must catch it.expect(() => assertWithin('link/evil.txt', root)).toThrow(PathSafetyError);expect(() => assertWithin('link/evil.txt', root)).toThrow(/outside|symlink|traversal/i);+ expect(rejectionCode(() => assertWithin('link/evil.txt', root))).toBe('ERR_PATH_TRAVERSAL');});it('still accepts a legit non-existent nested path inside root', () => {@@ -169,4 +191,32 @@ describe('assertWithin — symlink escape (realpath guard)', () => {it('rejects a NUL byte in the path', () => {expect(() => assertWithin('a\u0000b', root)).toThrow(PathSafetyError);});++ it('rejects a dangling symlink whose target is outside root', () => {+ // A write through the link would create the missing target outside root.+ fs.symlinkSync(path.join(outside, 'created.txt'), path.join(root, 'leaf'));+ expect(rejectionCode(() => assertWithin('leaf', root))).toBe('ERR_PATH_TRAVERSAL');+ });++ it('rejects a path through a dangling directory symlink that points outside root', () => {+ fs.symlinkSync(path.join(outside, 'missing-dir'), path.join(root, 'dir'));+ expect(rejectionCode(() => assertWithin('dir/evil.txt', root))).toBe('ERR_PATH_TRAVERSAL');+ });++ it('follows a chain of links that ends in a dangling target outside root', () => {+ fs.symlinkSync(path.join(outside, 'missing.txt'), path.join(root, 'second'));+ fs.symlinkSync('second', path.join(root, 'first'));+ expect(rejectionCode(() => assertWithin('first', root))).toBe('ERR_PATH_TRAVERSAL');+ });++ it('accepts a dangling symlink whose target stays inside root', () => {+ fs.symlinkSync(path.join('sub', 'new.txt'), path.join(root, 'leaf'));+ expect(assertWithin('leaf', root)).toBe(path.join(root, 'leaf'));+ });++ it('terminates on a symlink loop', () => {+ fs.symlinkSync('loop', path.join(root, 'loop'));+ const result = rejectionCode(() => assertWithin('loop', root));+ expect(['accepted', 'ERR_PATH_TRAVERSAL']).toContain(result);+ });});