Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Workspace backup: check login storage under followed links, and handle root links

AdityaUmalee4be59b5d6b2
diff --git a/server/workspace-backup-policy.ts b/server/workspace-backup-policy.ts
index c7ee0cfab7..81cefbad01 100644
--- a/server/workspace-backup-policy.ts
+++ b/server/workspace-backup-policy.ts
@@ -1,4 +1,4 @@
-import { lstatSync, readlinkSync, type Stats } from "node:fs";
+import { lstatSync, readdirSync, readlinkSync, realpathSync, type Stats } from "node:fs";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { parseStoredConfig } from "./config.ts";
import { inSecretFolder } from "./secret-folder.ts";
@@ -132,3 +132,17 @@ export function dataRelativePath(root: string, followed: readonly FollowedTopLev
export function carriedTwice(followed: readonly FollowedTopLevelLink[], target: string): boolean {
return followed.some((link) => pathUnder(target, link.target) !== undefined);
}
+
+/** The top-level items of the data folder `root` (its real path) that link to a place outside it, as the backup follows
+ * them. A dangling link, or one to a folder holding `root`, is left out here; the backup itself refuses both. */
+export function topLevelLinksOut(root: string): FollowedTopLevelLink[] {
+ const links: FollowedTopLevelLink[] = [];
+ for (const name of readdirSync(root)) {
+ const source = join(root, name);
+ if (!lstatSync(source).isSymbolicLink()) continue;
+ let target: string;
+ try { target = realpathSync(source); } catch { continue; }
+ if (pathUnder(root, target) === undefined && pathUnder(target, root) === undefined) links.push({ name, target });
+ }
+ return links;
+}
diff --git a/server/workspace-backup.test.ts b/server/workspace-backup.test.ts
index ddb0cd0f32..c119d6a398 100644
--- a/server/workspace-backup.test.ts
+++ b/server/workspace-backup.test.ts
@@ -1,7 +1,7 @@
import { createCipheriv, createHash, randomBytes, scryptSync } from "node:crypto";
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { basename, join } from "node:path";
+import { basename, join, parse } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { createServer as createNetServer } from "node:net";
import { gzipSync } from "node:zlib";
@@ -702,6 +702,27 @@ describe("encrypted full workspace backups", () => {
await expect(createWorkspaceBackup(root, { password: PASSWORD })).rejects.toMatchObject({ errorKey: "serverError.backup.recursiveLink" });
});
+ it("refuses provider authentication storage reached through a top-level link, and still follows unrelated linked folders", async () => {
+ const root = directory();
+ const drive = directory();
+ mkdirSync(join(drive, "events"));
+ writeFileSync(join(drive, "events", "auth.json"), "linked-secret");
+ symlinkSync(join(drive, "events"), join(root, "events"), process.platform === "win32" ? "junction" : "dir");
+ const config = (home: string) => ({ instances: { custom: { driver: "claudeAgent", environment: { CODEX_HOME: home } } } });
+ json(join(root, "config.json"), config(join(drive, "events")));
+ await expect(createWorkspaceBackup(root, { password: PASSWORD })).rejects.toThrow(/Provider authentication storage/);
+ expect(existsSync(join(root, ".backups"))).toBe(false);
+ json(join(root, "config.json"), config(join(drive, "codex-home")));
+ const exported = await createWorkspaceBackup(root, { password: PASSWORD });
+ expect(exported.summary.warnings.some((warning) => warning.endsWith(": events."))).toBe(true);
+ });
+
+ it("refuses a top-level link to the filesystem root as a loop", async () => {
+ const root = directory();
+ symlinkSync(parse(root).root, join(root, "up"), process.platform === "win32" ? "junction" : "dir");
+ await expect(createWorkspaceBackup(root, { password: PASSWORD })).rejects.toMatchObject({ errorKey: "serverError.backup.recursiveLink" });
+ }, 20_000);
+
it("saves links inside one workspace as copies of what they point to, and refuses loops and links to other workspaces", async () => {
const root = directory();
const project = join(root, "workspaces", "ws", "project");
diff --git a/server/workspace-backup.ts b/server/workspace-backup.ts
index 62a124fff4..5f84f81a01 100644
--- a/server/workspace-backup.ts
+++ b/server/workspace-backup.ts
@@ -5,7 +5,7 @@ import {
fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync,
readSync, realpathSync, renameSync, rmSync, writeFileSync, writeSync,
} from "node:fs";
-import { isAbsolute, join, parse, posix, relative, resolve, sep, win32 } from "node:path";
+import { join, parse, posix, resolve, win32 } from "node:path";
import { homedir } from "node:os";
import { DatabaseSync } from "node:sqlite";
import { pipeline } from "node:stream/promises";
@@ -15,7 +15,7 @@ import { userErrorFields, userErrorThrown } from "./user-errors.ts";
import { WORKSPACE_BACKUP_CLIENT_KEYS } from "../shared/workspace-backup-client.ts";
import { INSTRUCTION_FILE, restorePaths, validRelative } from "./workspace-backup-paths.ts";
import { cjkSearchText } from "./cjk-search.ts";
-import { browserProfileFolder, bytecodeCache, carriedTwice, dataEngineSpillPath, dataRelativePath, examplePaths, ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, installedDependencyFolder, managedTaskSkillLink, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig, type FollowedTopLevelLink } from "./workspace-backup-policy.ts";
+import { browserProfileFolder, bytecodeCache, carriedTwice, dataEngineSpillPath, dataRelativePath, examplePaths, ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, installedDependencyFolder, managedTaskSkillLink, pathUnder, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig, topLevelLinksOut, type FollowedTopLevelLink } from "./workspace-backup-policy.ts";
import { omittedAsTeamPrivate, routinesWithoutTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts";
import { flushLaterSaves } from "./save-batch.ts";
import { DATA_TABLES, foldLegacySidecars, LEGACY_SIDECARS, LIVE_DATABASE_SIDECARS, SNAPSHOT_DATABASES, snapshotDatabases, tooLargeError } from "./workspace-backup-databases.ts";
@@ -172,7 +172,7 @@ function writeJson(path: string, value: unknown): void {
function privateMetadata(manifest: Manifest): WorkspaceBackupPrivateMetadata {
return { summary: manifest.summary, clientState: manifest.clientState };
}
-function assertLocalAuthOutsideSnapshot(dataDir: string): void {
+function assertLocalAuthOutsideSnapshot(dataDir: string, followed: readonly FollowedTopLevelLink[] = []): void {
const configPath = join(dataDir, "config.json");
const config = existsSync(configPath) ? privateJson(configPath) : {};
const instances = record(config) && record(config.instances) ? config.instances : {};
@@ -183,8 +183,8 @@ function assertLocalAuthOutsideSnapshot(dataDir: string): void {
const expanded = text.startsWith("~/") || text.startsWith("~\\") ? join(home, text.slice(2)) : text;
const resolved = resolve(expanded);
const exists = entryExists(resolved);
- const path = relative(exists ? realpathSync(dataDir) : resolve(dataDir), exists ? realpathSync(resolved) : resolved).replaceAll("\\", "/");
- if (path === ".." || path.startsWith("../") || isAbsolute(path)) return;
+ const path = dataRelativePath(exists ? realpathSync(dataDir) : resolve(dataDir), followed, exists ? realpathSync(resolved) : resolved)?.replaceAll("\\", "/");
+ if (path === undefined) return;
if (path && (excluded(path.split("/")[0]) || excludedWorkspaceAuthPath(path))) return;
throw new Error(`Provider authentication storage (${field}) is inside backed-up workspace files. Move that login storage into the excluded providers folder or outside this workspace before backing up or restoring.`);
};
@@ -316,7 +316,7 @@ export async function createWorkspaceBackup(dataDir: string, options: CreateWork
export async function createWorkspaceBackupSnapshot(dataDir: string, options: CreateWorkspaceBackupOptions, jobId?: string): Promise<CreatedWorkspaceBackup> {
if (Object.hasOwn(options, "credentials")) throw new Error("Workspace backups do not transfer credentials.");
- assertLocalAuthOutsideSnapshot(dataDir);
+ assertLocalAuthOutsideSnapshot(dataDir, topLevelLinksOut(realpathSync(dataDir)));
const salt = randomBytes(16);
const key = await passwordKey(options.password, salt);
const job = newJob(dataDir, jobId);
@@ -391,7 +391,7 @@ export async function createWorkspaceBackupSnapshot(dataDir: string, options: Cr
throw new Error(`Cannot back up user-created symbolic link; replace it with regular files first: ${path}`);
}
}
- if (chain.some((folder) => folder === target || folder.startsWith(`${target}${sep}`))) {
+ if (chain.some((folder) => pathUnder(target, folder) !== undefined)) {
throw userErrorThrown("serverError.backup.recursiveLink", { path });
}
if (followed && carriedTwice(moved, target)) throw new Error(`Cannot back up user-created symbolic link; replace it with regular files first: ${path}`);