Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
close the symlink bypass in the data-root guard, and fix root containment
[._.]/ Adam Eivye3567abab7f3
diff --git a/server/lib/pathContainment.js b/server/lib/pathContainment.jsindex c3bdc1fdc5..7acaec5dcf 100644--- a/server/lib/pathContainment.js+++ b/server/lib/pathContainment.js@@ -41,7 +41,10 @@ export function isPathAtOrInsideDir(dir, candidatePath) {const fold = (p) => (CASE_INSENSITIVE_FS ? p.toLowerCase() : p);const root = fold(resolvePath(dir));const target = fold(resolvePath(candidatePath));- return target === root || target.startsWith(root + PATH_SEP);+ // A filesystem or drive root ALREADY ends in the separator ('/', 'C:\\'), so+ // appending one would anchor on '//' and report nothing as inside it.+ const prefix = root.endsWith(PATH_SEP) ? root : root + PATH_SEP;+ return target === root || target.startsWith(prefix);}/**diff --git a/server/lib/testDataIsolation.guards.test.js b/server/lib/testDataIsolation.guards.test.jsindex 04126f02ef..4450e9b61d 100644--- a/server/lib/testDataIsolation.guards.test.js+++ b/server/lib/testDataIsolation.guards.test.js@@ -81,7 +81,13 @@ const SELF = relative(REPO_ROOT, fileURLToPath(import.meta.url)).split(sep).join// premise is the live install: it enumerates the user's own screenshots to// feed a real vision model, and skips itself when the directory is absent.// A future false positive belongs here too — with a sentence saying why it's safe.+// - testDataIsolation.test.js is the RUNTIME guard's own contract test. It has+// to name the real root — proving the guard refuses a write there is the+// whole point — and it can never write into it: every assertion about a real+// path asserts that the call REJECTS, and the one case that writes bytes+// targets a temp root. (#6176)const ALLOWED = new Set([+ 'server/lib/testDataIsolation.test.js','server/services/creativeDirectorPrompts.test.js','server/services/visionTest.integration.test.js',]);diff --git a/server/lib/testDataIsolation.js b/server/lib/testDataIsolation.jsindex cf586d5876..8458d71671 100644--- a/server/lib/testDataIsolation.js+++ b/server/lib/testDataIsolation.js@@ -56,8 +56,8 @@* `aiToolkit/AGENTS.md`).*/-import { existsSync } from 'fs';-import { basename, dirname, join, resolve } from 'path';+import { existsSync, lstatSync, readlinkSync } from 'fs';+import { basename, dirname, isAbsolute, join, resolve } from 'path';import { resolveCodeRootForModule, resolveInstallRoot } from './dataRoot.js';import { canonicalizePath, isPathAtOrInsideDir } from './pathContainment.js';import { isTestRunner } from './runtimeEnv.js';@@ -90,16 +90,59 @@ function canonicalDir(dir) {return resolved;}+/** The link's target if `path` is a symlink, else null. Never throws. */+function readLinkTarget(path) {+ try {+ if (!lstatSync(path).isSymbolicLink()) return null;+ return readlinkSync(path);+ } catch {+ return null;+ }+}++// Bound on how many symlink hops to follow. Deep chains do not occur in a test+// fixture; the cap just keeps a cyclic link from spinning.+const MAX_LINK_HOPS = 8;++/**+ * Where a follow-the-link write would actually land, or null when `abs` is not+ * a symlink. Resolved through `canonicalizePath` rather than `realpathSync` so+ * a DANGLING link still reports its target — a fixture link pointing at a file+ * the real tree has not created yet is exactly the case that would otherwise+ * slip through, because `realpathSync` throws ENOENT on it.+ */+function followLinks(abs) {+ let current = abs;+ for (let hop = 0; hop < MAX_LINK_HOPS; hop += 1) {+ const link = readLinkTarget(current);+ if (!link) return hop === 0 ? null : current;+ current = canonicalizePath(isAbsolute(link) ? link : join(dirname(current), link));+ }+ return current;+}+/**- * Canonicalize a write target: resolve symlinked ANCESTORS, but never follow a- * symlinked final component. That matches what the write actually does —- * `atomicWrite` replaces a symlink with a regular file rather than following it- * (see its header), so the bytes land at the link's own location.+ * A write target has TWO possible landing sites, and the guard must refuse if+ * either is in the real tree, because the primitives disagree about symlinks:+ *+ * - `atomicWrite` REPLACES a symlinked destination with a regular file rather+ * than following it (see its header), so the bytes land at the link's own+ * location — ancestors resolved, final component not.+ * - `writeFile` / `appendFile` / `copyFile` FOLLOW a symlinked destination, so+ * the bytes land wherever the link points.+ *+ * Checking only the first spelling would let a fixture symlink inside a temp+ * root point at `data/provider-quotas.json` and write straight through — the+ * exact #6171 leak this guard exists to stop.*/-const canonicalTarget = (target) => {+const canonicalTargets = (target) => {const abs = resolve(target);const parent = dirname(abs);- return parent === abs ? abs : join(canonicalDir(parent), basename(abs));+ const viaAncestors = parent === abs ? abs : join(canonicalDir(parent), basename(abs));+ // Only does work when the destination IS a symlink; an ordinary first write+ // costs one lstat and nothing more.+ const followed = followLinks(abs);+ return followed && followed !== viaAncestors ? [viaAncestors, followed] : [viaAncestors];};/**@@ -109,14 +152,16 @@ const canonicalTarget = (target) => {* case-folding on case-insensitive filesystems — a hand-rolled `relative()`* test would read `…/Data/x.json` on macOS as outside the root it is in fact* inside. Relative paths and `..` climbs are resolved first, so neither can- * walk in sideways.+ * walk in sideways, and a symlinked destination is judged at BOTH the locations+ * a write could land on (see `canonicalTargets`).** @param {string} target - path to test* @returns {boolean}*/export function isInsideRealDataRoot(target) {if (typeof target !== 'string' || target === '') return false;- return isPathAtOrInsideDir(realDataRoot(), canonicalTarget(target));+ const root = realDataRoot();+ return canonicalTargets(target).some((candidate) => isPathAtOrInsideDir(root, candidate));}/**diff --git a/server/lib/testDataIsolation.test.js b/server/lib/testDataIsolation.test.jsindex 3c9b47127e..bd8b3e30e4 100644--- a/server/lib/testDataIsolation.test.js+++ b/server/lib/testDataIsolation.test.js@@ -15,12 +15,13 @@*/import { describe, it, expect, vi, afterEach, afterAll } from 'vitest';-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';+import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'fs';import { tmpdir } from 'os';-import { join } from 'path';+import { isAbsolute, join, relative, sep } from 'path';import { appendFileGuarded, atomicWrite, copyFileGuarded, ensureDir, writeFileGuarded } from './fileCore.js';import { appendJSONLine } from './jsonIo.js';import { assertNotNewRealDataDir, assertNotRealDataWrite, isInsideRealDataRoot } from './testDataIsolation.js';+import { isPathAtOrInsideDir } from './pathContainment.js';import { isTestRunner } from './runtimeEnv.js';import { PATHS } from './paths.js';@@ -64,7 +65,27 @@ describe('isInsideRealDataRoot', () => {});it('catches a `..` climb back into the real tree', () => {- expect(isInsideRealDataRoot(join(REAL_DATA, 'brain', '..', '..', 'data', 'sneaky.json'))).toBe(true);+ // Concatenated, NOT join()'d: `path.join` normalizes its arguments, so a+ // join()-built path arrives already collapsed and the case would pass even+ // if the function dropped its own `resolve()`.+ expect(isInsideRealDataRoot(`${REAL_DATA}/brain/../../data/sneaky.json`)).toBe(true);+ });++ it('catches a relative path that resolves into the real tree', () => {+ const rel = relative(process.cwd(), join(REAL_DATA, 'relative.json'));+ expect(isAbsolute(rel)).toBe(false);+ expect(isInsideRealDataRoot(rel)).toBe(true);+ });++ it('follows a symlinked destination — the write lands where the link points', () => {+ // writeFile/appendFile/copyFile follow a symlinked final component, so a+ // fixture link inside a temp root can reach live data even though the link+ // itself sits outside. atomicWrite replaces the link instead, which is why+ // BOTH landing sites are checked.+ const link = join(tempRoot, 'looks-safe.json');+ symlinkSync(join(REAL_DATA, 'provider-quotas.json'), link);+ expect(isInsideRealDataRoot(link)).toBe(true);+ rmSync(link, { force: true });});it('is not fooled by a non-string or empty target', () => {@@ -73,6 +94,19 @@ describe('isInsideRealDataRoot', () => {});});+describe('isPathAtOrInsideDir (the containment primitive behind it)', () => {+ it('treats a filesystem root as containing its children', () => {+ // `root + sep` is '//' for '/', so a naive anchor matched nothing at all —+ // harmless for today's `<install>/data` root, wrong for the next caller.+ expect(isPathAtOrInsideDir(sep, join(sep, 'etc'))).toBe(true);+ expect(isPathAtOrInsideDir(sep, sep)).toBe(true);+ });++ it('still rejects a sibling that merely shares the prefix', () => {+ expect(isPathAtOrInsideDir('/data/uploads', '/data/uploads-evil/x')).toBe(false);+ });+});+describe('assertNotRealDataWrite', () => {it('is inert outside the test runner, so production writes are unaffected', () => {vi.stubEnv('NODE_ENV', 'production');diff --git a/server/services/runner.js b/server/services/runner.jsindex 760cb01be7..d253afbd8a 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -3,9 +3,9 @@* Re-exports toolkit runner service functions with local overrides*/import { spawn } from '../lib/childProcess.js';-import { writeFile, readFile } from 'fs/promises';+import { readFile } from 'fs/promises';import { join } from 'path';-import { atomicWrite, ensureDir, tryReadFile, PATHS } from '../lib/fileUtils.js';+import { atomicWrite, ensureDir, tryReadFile, writeFileGuarded, PATHS } from '../lib/fileUtils.js';import { resolveSpawnCwd } from '../lib/spawnCwd.js';import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';@@ -110,7 +110,7 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erroconst outputPath = join(runDir, 'output.txt');const metadataPath = join(runDir, 'metadata.json');- await writeFile(outputPath, output).catch(() => {});+ await writeFileGuarded(outputPath, output).catch(() => {});const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => '{}');let metadata = {};@@ -521,7 +521,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, scawait cleanupVisionFiles().catch((error) => console.error(`❌ Failed to clean CLI vision files: ${error.message}`));if (spawnError) console.error(`❌ Run ${runId} spawn error: ${spawnError.message}`);- await writeFile(outputPath, output);+ await writeFileGuarded(outputPath, output);metadata.endTime = new Date().toISOString();metadata.duration = Date.now() - startTime;