Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(security): compare candidate and prefix in the same canonical form (#3011)

Dragan Spiridonov3030924f22fd
diff --git a/v3/@claude-flow/security/__tests__/path-validator.test.ts b/v3/@claude-flow/security/__tests__/path-validator.test.ts
index 84d4632e02..329872a8e2 100644
--- a/v3/@claude-flow/security/__tests__/path-validator.test.ts
+++ b/v3/@claude-flow/security/__tests__/path-validator.test.ts
@@ -347,4 +347,239 @@ describe('PathValidator', () => {
expect(result.isValid).toBe(true);
});
});
+
+ /**
+ * Regression: a prefix reached through a symlink.
+ *
+ * `validate()` canonicalizes the candidate with `fs.realpath` but the
+ * prefixes were only ever `path.resolve()`d, so the two sides were compared
+ * in different forms and NOTHING under such a prefix could ever match.
+ *
+ * This is not a hypothetical: on macOS `os.tmpdir()` is `/var/folders/...`
+ * and `/var` is a symlink to `/private/var`, so every validator built over a
+ * temp directory rejected its own contents β€” while the same code passed on
+ * Linux, where `/tmp` is a real directory.
+ *
+ * These tests build the symlink explicitly instead of relying on that
+ * platform quirk, so they exercise the property on every platform.
+ */
+ describe('Symlinked prefixes', () => {
+ let root: string;
+ let realDir: string;
+ let linkDir: string;
+ let outsideDir: string;
+ let symlinksSupported: boolean;
+
+ beforeEach(async () => {
+ // Reset per case: a single denied link creation must not silently
+ // suppress every later assertion in the block.
+ symlinksSupported = true;
+ root = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'path-validator-'));
+ realDir = path.join(root, 'real');
+ linkDir = path.join(root, 'link');
+ outsideDir = path.join(root, 'outside');
+ await fsPromises.mkdir(realDir);
+ await fsPromises.mkdir(outsideDir);
+
+ try {
+ // 'junction' is ignored on POSIX and avoids needing Developer Mode or
+ // elevation for directory links on Windows.
+ await fsPromises.symlink(realDir, linkDir, 'junction');
+ } catch {
+ // Unprivileged Windows without Developer Mode cannot create links.
+ symlinksSupported = false;
+ }
+ });
+
+ afterEach(async () => {
+ await fsPromises.rm(root, { recursive: true, force: true });
+ });
+
+ it('accepts an existing file under a symlinked prefix', async (ctx) => {
+ if (!symlinksSupported) ctx.skip();
+ const file = path.join(realDir, 'binary');
+ await fsPromises.writeFile(file, 'contents');
+
+ const linkValidator = new PathValidator({
+ allowedPrefixes: [linkDir],
+ allowHidden: true,
+ });
+
+ const result = await linkValidator.validate(path.join(linkDir, 'binary'));
+
+ expect(result.errors).toEqual([]);
+ expect(result.isValid).toBe(true);
+ expect(result.relativePath).toBe('binary');
+ });
+
+ it('accepts a not-yet-created file under a symlinked prefix', async (ctx) => {
+ if (!symlinksSupported) ctx.skip();
+ const linkValidator = new PathValidator({
+ allowedPrefixes: [linkDir],
+ allowHidden: true,
+ allowNonExistent: true,
+ });
+
+ const result = await linkValidator.validate(path.join(linkDir, 'not-written-yet'));
+
+ expect(result.errors).toEqual([]);
+ expect(result.isValid).toBe(true);
+ });
+
+ it('still rejects a symlink that escapes the prefix', async (ctx) => {
+ if (!symlinksSupported) ctx.skip();
+ const secret = path.join(outsideDir, 'secret');
+ await fsPromises.writeFile(secret, 'contents');
+ await fsPromises.symlink(outsideDir, path.join(realDir, 'escape'), 'junction');
+
+ const linkValidator = new PathValidator({
+ allowedPrefixes: [linkDir],
+ allowHidden: true,
+ });
+
+ const result = await linkValidator.validate(path.join(linkDir, 'escape', 'secret'));
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContain('Path is outside allowed directories');
+ });
+
+ it('rejects a not-yet-created file under an escaping symlink', async (ctx) => {
+ if (!symlinksSupported) ctx.skip();
+ await fsPromises.symlink(outsideDir, path.join(realDir, 'escape'), 'junction');
+
+ const linkValidator = new PathValidator({
+ allowedPrefixes: [linkDir],
+ allowHidden: true,
+ allowNonExistent: true,
+ });
+
+ const result = await linkValidator.validate(path.join(linkDir, 'escape', 'not-written-yet'));
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContain('Path is outside allowed directories');
+ });
+
+ it('keeps validateSync lexical, so a symlinked prefix still matches', (ctx) => {
+ if (!symlinksSupported) ctx.skip();
+ const linkValidator = new PathValidator({
+ allowedPrefixes: [linkDir],
+ allowHidden: true,
+ });
+
+ // validateSync is documented as resolving no symlinks; it must keep
+ // comparing lexical candidate against lexical prefix, or canonicalizing
+ // the prefixes would break it in the mirror image of the async bug.
+ const result = linkValidator.validateSync(path.join(linkDir, 'binary'));
+
+ expect(result.isValid).toBe(true);
+ expect(linkValidator.isWithinAllowed(path.join(linkDir, 'binary'))).toBe(true);
+ });
+
+ it('does not canonicalize when non-existent paths are forbidden', async (ctx) => {
+ if (!symlinksSupported) ctx.skip();
+ // The call already fails; canonicalizing anyway would rewrite the
+ // resolvedPath and matchedPrefix that callers read off the result.
+ const strict = new PathValidator({
+ allowedPrefixes: [linkDir],
+ allowHidden: true,
+ allowNonExistent: false,
+ });
+
+ const result = await strict.validate(path.join(linkDir, 'missing'));
+
+ expect(result.isValid).toBe(false);
+ expect(result.errors).toContain('Path does not exist');
+ expect(result.resolvedPath).toBe(path.join(linkDir, 'missing'));
+ });
+
+ it('pins an allowed prefix to the directory it named at construction', async (ctx) => {
+ if (!symlinksSupported) ctx.skip();
+ // Re-resolving the prefix on every call would let whoever can rewrite
+ // the link redirect the allowlist afterwards. The prefix therefore keeps
+ // denoting what it named when the validator was configured.
+ const pinned = new PathValidator({ allowedPrefixes: [linkDir], allowHidden: true });
+ await fsPromises.writeFile(path.join(realDir, 'file'), 'contents');
+ await fsPromises.writeFile(path.join(outsideDir, 'file'), 'contents');
+
+ await fsPromises.unlink(linkDir);
+ await fsPromises.symlink(outsideDir, linkDir, 'junction');
+
+ expect((await pinned.validate(path.join(realDir, 'file'))).isValid).toBe(true);
+ expect((await pinned.validate(path.join(outsideDir, 'file'))).isValid).toBe(false);
+ });
+
+ it('validates a temp-directory tree the way an installer does', async () => {
+ // The shape that broke `ruflo proxy install` on macOS: a validator built
+ // over a freshly-created temp dir, checking a file extracted into it,
+ // with the default options.
+ const workDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'installer-'));
+ try {
+ const extractDir = path.join(workDir, 'extracted');
+ await fsPromises.mkdir(extractDir);
+ const binary = path.join(extractDir, 'meta-proxy');
+ await fsPromises.writeFile(binary, 'contents');
+
+ const installValidator = new PathValidator({ allowedPrefixes: [extractDir] });
+ const result = await installValidator.validate(binary);
+
+ expect(result.errors).toEqual([]);
+ expect(result.isValid).toBe(true);
+ } finally {
+ await fsPromises.rm(workDir, { recursive: true, force: true });
+ }
+ });
+ });
+
+ /**
+ * A root prefix already ends in a separator, so anchoring the match by
+ * appending another looked for `//` and rejected every descendant. Reachable
+ * as `/` or `C:\` directly, and now also whenever a prefix canonicalizes to
+ * a root.
+ */
+ describe('Root prefixes', () => {
+ const root = path.parse(process.cwd()).root;
+
+ it('accepts descendants of a root prefix', async () => {
+ const rootValidator = new PathValidator({
+ allowedPrefixes: [root],
+ allowHidden: true,
+ blockedNames: [],
+ blockedExtensions: [],
+ });
+
+ const result = await rootValidator.validate(path.join(root, 'etc', 'hosts'));
+
+ expect(result.errors).toEqual([]);
+ expect(result.isValid).toBe(true);
+ expect(result.matchedPrefix).toBe(root);
+ // Not compared to a literal: `/etc` is itself a symlink on macOS, so the
+ // canonical location is platform-dependent. What must hold everywhere is
+ // that the relative path is relative β€” the old `prefix + sep` boundary
+ // would have produced a leading separator had it matched at all.
+ expect(result.relativePath.startsWith(path.sep)).toBe(false);
+ expect(path.join(root, result.relativePath)).toBe(result.resolvedPath);
+ });
+
+ it('accepts descendants of a root prefix synchronously too', () => {
+ const rootValidator = new PathValidator({
+ allowedPrefixes: [root],
+ allowHidden: true,
+ blockedNames: [],
+ blockedExtensions: [],
+ });
+
+ expect(rootValidator.validateSync(path.join(root, 'etc', 'hosts')).isValid).toBe(true);
+ expect(rootValidator.isWithinAllowed(path.join(root, 'etc', 'hosts'))).toBe(true);
+ });
+
+ it('still anchors non-root prefixes at a separator boundary', async () => {
+ const boundaryValidator = new PathValidator({
+ allowedPrefixes: ['/srv/app'],
+ allowHidden: true,
+ });
+
+ expect((await boundaryValidator.validate('/srv/app-secrets/key')).isValid).toBe(false);
+ expect(boundaryValidator.isWithinAllowed('/srv/app-secrets/key')).toBe(false);
+ });
+ });
});
diff --git a/v3/@claude-flow/security/src/path-validator.ts b/v3/@claude-flow/security/src/path-validator.ts
index c21da2e234..6236091ed0 100644
--- a/v3/@claude-flow/security/src/path-validator.ts
+++ b/v3/@claude-flow/security/src/path-validator.ts
@@ -13,6 +13,11 @@
* - Symlink resolution (optional)
* - Traversal pattern detection
*
+ * Canonicalization is symmetric: a candidate is only ever compared against
+ * prefixes held in the same form it was resolved in. Canonicalizing one side
+ * and not the other silently denies everything under a symlinked prefix
+ * (async) or silently accepts an escape through one (sync).
+ *
* @module v3/security/path-validator
*/
@@ -134,6 +139,76 @@ const DEFAULT_BLOCKED_NAMES = [
'.docker',
];
+/**
+ * Canonicalizes a path that may not exist yet, by resolving the longest
+ * ancestor that DOES exist and re-attaching the remaining segments.
+ *
+ * Plain `realpath` throws ENOENT for a path whose leaf is missing, which
+ * would leave the caller comparing a canonical prefix against a merely
+ * lexical candidate β€” the asymmetry this whole helper exists to avoid.
+ * Walking up also means a symlinked PARENT is still resolved, so a
+ * not-yet-created file under a symlinked directory canonicalizes to its
+ * real location instead of its lexical one.
+ *
+ * Falls back to the lexical path if the ancestor walk itself fails (EACCES,
+ * ELOOP, …), preserving the previous behaviour rather than throwing out of
+ * a validation call.
+ */
+async function canonicalize(resolvedPath: string): Promise<string> {
+ try {
+ return await fs.realpath(resolvedPath);
+ } catch (error: any) {
+ if (error?.code !== 'ENOENT') {
+ return resolvedPath;
+ }
+ }
+
+ const parent = path.dirname(resolvedPath);
+ // dirname() of a root ('/' or 'C:\\') is itself β€” stop instead of recursing.
+ if (parent === resolvedPath) {
+ return resolvedPath;
+ }
+
+ return path.join(await canonicalize(parent), path.basename(resolvedPath));
+}
+
+/**
+ * Synchronous twin of {@link canonicalize}, for the constructor and
+ * {@link PathValidator.addPrefix} which cannot await.
+ */
+function canonicalizeSync(resolvedPath: string): string {
+ try {
+ return realpathSync(resolvedPath);
+ } catch (error: any) {
+ if (error?.code !== 'ENOENT') {
+ return resolvedPath;
+ }
+ }
+
+ const parent = path.dirname(resolvedPath);
+ if (parent === resolvedPath) {
+ return resolvedPath;
+ }
+
+ return path.join(canonicalizeSync(parent), path.basename(resolvedPath));
+}
+
+/**
+ * True if `resolvedPath` is the prefix itself or sits underneath it.
+ *
+ * The separator has to be appended to anchor the match at a path boundary, so
+ * `/srv/app-secrets` does not count as inside `/srv/app` β€” but a root prefix
+ * (`/`, `C:\`, a UNC share root) already ends in one, and appending a second
+ * looked for `//`, which rejected every descendant of a root prefix.
+ */
+function isWithinPrefix(resolvedPath: string, prefix: string): boolean {
+ if (resolvedPath === prefix) {
+ return true;
+ }
+ const boundary = prefix.endsWith(path.sep) ? prefix : prefix + path.sep;
+ return resolvedPath.startsWith(boundary);
+}
+
/**
* Path validator that prevents traversal attacks.
*
@@ -154,7 +229,25 @@ const DEFAULT_BLOCKED_NAMES = [
*/
export class PathValidator {
private readonly config: Required<PathValidatorConfig>;
+ /** Lexically resolved prefixes β€” compared against lexically resolved candidates. */
private readonly resolvedPrefixes: string[];
+ /**
+ * Symlink-resolved prefixes β€” compared against symlink-resolved candidates.
+ *
+ * Kept as a SECOND list rather than replacing `resolvedPrefixes`, because
+ * the two comparison sites derive their candidate differently: `validate()`
+ * canonicalizes through the filesystem, `validateSync()`/`isWithinAllowed()`
+ * are documented as lexical-only. Canonicalizing one side without the other
+ * is exactly the bug this fixes, in whichever direction it is done.
+ *
+ * Resolved once, at construction β€” so an allowed prefix denotes the
+ * directory it named when the validator was configured, and retargeting a
+ * symlink afterwards cannot silently redirect the allowlist. Re-resolving on
+ * every call would hand that control to whoever can write the link, and cost
+ * a syscall per validation. Callers needing to follow a moved target should
+ * construct a new validator.
+ */
+ private readonly canonicalPrefixes: string[];
constructor(config: PathValidatorConfig) {
this.config = {
@@ -174,27 +267,23 @@ export class PathValidator {
);
}
- // Pre-resolve all prefixes. #3010 β€” validate() canonicalizes the
- // *candidate* through fs.realpath (when resolveSymlinks is on, the
- // default) but prefixes were only ever path.resolve()d, never
- // realpath'd. On any platform where the prefix itself is reached
- // through a symlink (e.g. macOS os.tmpdir() -> /var/folders/... while
- // /var is itself a symlink to /private/var), the realpath'd candidate
- // can never match the non-realpath'd prefix, and every path under that
- // prefix is rejected as "outside allowed directories" β€” including the
- // prefix's own contents. Mirror validate()'s own ENOENT-tolerant
- // fallback: a prefix that doesn't exist yet (or otherwise can't be
- // realpath'd) still gets a resolved value via path.resolve, matching
- // allowNonExistent's semantics for candidates.
- this.resolvedPrefixes = this.config.allowedPrefixes.map(p => {
- const resolved = path.resolve(p);
- if (!this.config.resolveSymlinks) return resolved;
- try {
- return realpathSync(resolved);
- } catch {
- return resolved;
- }
- });
+ // Pre-resolve all prefixes, lexically and canonically. #3010 β€” validate()
+ // canonicalizes the *candidate* through fs.realpath (when resolveSymlinks
+ // is on, the default) but prefixes were only ever path.resolve()d, never
+ // realpath'd. On any platform where the prefix itself is reached through a
+ // symlink (e.g. macOS os.tmpdir() -> /var/folders/... while /var is itself
+ // a symlink to /private/var), the realpath'd candidate can never match the
+ // non-realpath'd prefix, and every path under that prefix is rejected as
+ // "outside allowed directories" β€” including the prefix's own contents.
+ this.resolvedPrefixes = this.config.allowedPrefixes.map(p =>
+ path.resolve(p)
+ );
+ // Always a distinct array β€” `addPrefix` appends to both, so aliasing the
+ // lexical list would push twice. With resolveSymlinks off no candidate is
+ // ever canonicalized and nothing reads this list, so skip the syscall.
+ this.canonicalPrefixes = this.resolvedPrefixes.map(p =>
+ this.config.resolveSymlinks ? canonicalizeSync(p) : p
+ );
}
/**
@@ -243,6 +332,10 @@ export class PathValidator {
// Resolve the path
let resolvedPath: string;
+ // Which prefix list this candidate may legitimately be compared against:
+ // only a symlink-resolved candidate may be matched against symlink-resolved
+ // prefixes. See `canonicalPrefixes`.
+ let symlinksResolved = false;
try {
resolvedPath = path.resolve(inputPath);
@@ -250,6 +343,7 @@ export class PathValidator {
if (this.config.resolveSymlinks) {
try {
resolvedPath = await fs.realpath(resolvedPath);
+ symlinksResolved = true;
} catch (error: any) {
// Path doesn't exist yet - use resolved path
if (error.code !== 'ENOENT' || !this.config.allowNonExistent) {
@@ -259,6 +353,20 @@ export class PathValidator {
errors.push(`Failed to resolve path: ${error.message}`);
}
}
+ if (error.code === 'ENOENT' && this.config.allowNonExistent) {
+ // The leaf does not exist, but its ancestors may still be
+ // symlinks. Canonicalize what exists so the candidate is in the
+ // same form as `canonicalPrefixes` β€” otherwise every not-yet-
+ // created path under a symlinked prefix (macOS `/var` ->
+ // `/private/var`, `/tmp` -> `/private/tmp`) fails to match.
+ //
+ // Only when non-existent paths are actually allowed: with
+ // `allowNonExistent: false` this call is already a failure, and
+ // canonicalizing anyway would change the `resolvedPath` and
+ // `matchedPrefix` reported to callers for no benefit.
+ resolvedPath = await canonicalize(resolvedPath);
+ symlinksResolved = true;
+ }
}
}
} catch (error: any) {
@@ -276,8 +384,12 @@ export class PathValidator {
let relativePath = '';
let prefixMatched = false;
- for (const prefix of this.resolvedPrefixes) {
- if (resolvedPath === prefix || resolvedPath.startsWith(prefix + path.sep)) {
+ const prefixes = symlinksResolved
+ ? this.canonicalPrefixes
+ : this.resolvedPrefixes;
+
+ for (const prefix of prefixes) {
+ if (isWithinPrefix(resolvedPath, prefix)) {
prefixMatched = true;
matchedPrefix = prefix;
relativePath = resolvedPath.slice(prefix.length);
@@ -408,7 +520,7 @@ export class PathValidator {
let prefixMatched = false;
for (const prefix of this.resolvedPrefixes) {
- if (resolvedPath === prefix || resolvedPath.startsWith(prefix + path.sep)) {
+ if (isWithinPrefix(resolvedPath, prefix)) {
prefixMatched = true;
matchedPrefix = prefix;
relativePath = resolvedPath.slice(prefix.length);
@@ -483,6 +595,9 @@ export class PathValidator {
if (!this.resolvedPrefixes.includes(resolved)) {
this.config.allowedPrefixes.push(prefix);
this.resolvedPrefixes.push(resolved);
+ this.canonicalPrefixes.push(
+ this.config.resolveSymlinks ? canonicalizeSync(resolved) : resolved
+ );
}
}
@@ -500,7 +615,7 @@ export class PathValidator {
try {
const resolved = path.resolve(inputPath);
return this.resolvedPrefixes.some(
- prefix => resolved === prefix || resolved.startsWith(prefix + path.sep)
+ prefix => isWithinPrefix(resolved, prefix)
);
} catch {
return false;