Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(security): pin Convex snapshot import bytes

Rahmanbf35afc0dc97
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 1077b767..74124910 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,15 @@
+## 2026-09-19 — Pin Convex snapshot imports to validated bytes
+
+The security inventory exposed CodeQL alert #139: snapshot metadata was checked by
+pathname, then the same pathname was reopened for hashing and later passed to the
+Convex CLI. Snapshot validation now opens the source once, performs ownership/size/
+ZIP checks and hashing through that descriptor, copies those exact bytes into a private
+0700/0600 staging location, verifies the descriptor did not change during the copy,
+and imports only the staged file. The private copy is removed in a final cleanup path,
+while result metadata continues to identify the caller's original source path. Regression
+coverage changes the source after validation and proves the CLI still receives the
+validated staged bytes.
+
## 2026-09-19 — Keep strict Semgrep coverage complete on the macOS installer
Hosted Semgrep reported zero findings but exited 3 under `--strict` because its Bash parser
diff --git a/lib/infra/convex-cloud-cli-runner.ts b/lib/infra/convex-cloud-cli-runner.ts
index eebdf892..c71d3f26 100644
--- a/lib/infra/convex-cloud-cli-runner.ts
+++ b/lib/infra/convex-cloud-cli-runner.ts
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { spawn } from "node:child_process";
-import { createReadStream, promises as fs } from "node:fs";
+import { constants as fsConstants, promises as fs } from "node:fs";
+import os from "node:os";
import path from "node:path";
import { childEnv } from "@/lib/host/child-env";
import { resolveReadable } from "@/lib/host/paths";
@@ -113,29 +114,95 @@ export async function convexSnapshotContext(snapshotPath: unknown) {
});
if (!snapshot.toLowerCase().endsWith(".zip"))
throw new IntegrationError("convex_snapshot_zip_required");
- const stat = await fs.stat(snapshot).catch(() => null);
- if (!stat?.isFile() || stat.size <= 0 || stat.size > MAX_SNAPSHOT_BYTES)
- throw new IntegrationError("invalid_snapshot_path");
- if (typeof process.getuid === "function" && stat.uid !== process.getuid())
- throw new IntegrationError("invalid_snapshot_path");
- const head = Buffer.alloc(4);
- const handle = await fs.open(snapshot, "r");
+ const handle = await fs
+ .open(snapshot, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
+ .catch(() => {
+ throw new IntegrationError("invalid_snapshot_path");
+ });
+ let stageDir = "";
try {
- await handle.read(head, 0, 4, 0);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_SNAPSHOT_BYTES)
+ throw new IntegrationError("invalid_snapshot_path");
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid())
+ throw new IntegrationError("invalid_snapshot_path");
+
+ const head = Buffer.alloc(4);
+ const first = await handle.read(head, 0, 4, 0);
+ if (
+ first.bytesRead < 4 ||
+ head[0] !== 0x50 ||
+ head[1] !== 0x4b ||
+ ![0x03, 0x05, 0x07].includes(head[2])
+ )
+ throw new IntegrationError("convex_snapshot_zip_required");
+
+ // Import from a private copy produced from the same already-open descriptor that
+ // we validate and hash. This closes the path TOCTOU window: replacing the user
+ // path after validation cannot change the bytes later consumed by the Convex CLI.
+ stageDir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-snapshot-"));
+ await fs.chmod(stageDir, 0o700);
+ const stagedSnapshot = path.join(stageDir, "snapshot.zip");
+ const staged = await fs.open(
+ stagedSnapshot,
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
+ 0o600,
+ );
+ const hash = createHash("sha256");
+ const chunk = Buffer.allocUnsafe(1024 * 1024);
+ let offset = 0;
+ try {
+ while (offset < stat.size) {
+ const requested = Math.min(chunk.length, stat.size - offset);
+ const { bytesRead } = await handle.read(chunk, 0, requested, offset);
+ if (bytesRead <= 0) throw new IntegrationError("invalid_snapshot_path");
+ const view = chunk.subarray(0, bytesRead);
+ hash.update(view);
+ let written = 0;
+ while (written < bytesRead) {
+ const result = await staged.write(
+ view,
+ written,
+ bytesRead - written,
+ offset + written,
+ );
+ if (result.bytesWritten <= 0)
+ throw new IntegrationError("invalid_snapshot_path");
+ written += result.bytesWritten;
+ }
+ offset += bytesRead;
+ }
+ await staged.sync();
+ } finally {
+ await staged.close().catch(() => undefined);
+ }
+
+ const after = await handle.stat();
+ if (
+ after.dev !== stat.dev ||
+ after.ino !== stat.ino ||
+ after.size !== stat.size ||
+ after.mtimeMs !== stat.mtimeMs ||
+ after.ctimeMs !== stat.ctimeMs
+ )
+ throw new IntegrationError("invalid_snapshot_path");
+
+ return {
+ snapshot,
+ stagedSnapshot,
+ size: stat.size,
+ sha256: hash.digest("hex"),
+ cleanup: async () => {
+ await fs.rm(stageDir, { recursive: true, force: true });
+ },
+ };
+ } catch (error) {
+ if (stageDir) await fs.rm(stageDir, { recursive: true, force: true });
+ throw error;
} finally {
await handle.close().catch(() => undefined);
}
- if (
- head[0] !== 0x50 ||
- head[1] !== 0x4b ||
- ![0x03, 0x05, 0x07].includes(head[2])
- )
- throw new IntegrationError("convex_snapshot_zip_required");
-
- const hash = createHash("sha256");
- for await (const chunk of createReadStream(snapshot)) hash.update(chunk);
- return { snapshot, size: stat.size, sha256: hash.digest("hex") };
}
export function convexCliEnv(deployKey: string): Record<string, string> {
diff --git a/lib/infra/convex-cloud-runner.test.ts b/lib/infra/convex-cloud-runner.test.ts
index 2d892c91..5e4c47a8 100644
--- a/lib/infra/convex-cloud-runner.test.ts
+++ b/lib/infra/convex-cloud-runner.test.ts
@@ -3,8 +3,7 @@ import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
const PAT = "pat_synthetic_12345678901234567890";
-const DEPLOY_KEY =
- "prod:happy-otter-123|synthetic_deploy_key_1234567890abcdef";
+const DEPLOY_KEY = "prod:happy-otter-123|synthetic_deploy_key_1234567890abcdef";
let root: string;
let project: string;
let snapshot: string;
@@ -139,8 +138,12 @@ it("imports only with explicit mode and a data-scoped ephemeral key", async () =
return json({ error: "unexpected" }, 500);
},
);
+ let stagedSnapshot = "";
const runCli = vi.fn(async (_exe, args, options) => {
- expect(args).toEqual(["import", snapshot, "--replace-all", "--yes"]);
+ expect(args[0]).toBe("import");
+ stagedSnapshot = String(args[1]);
+ expect(stagedSnapshot).not.toBe(snapshot);
+ expect(args.slice(2)).toEqual(["--replace-all", "--yes"]);
expect(options.env.CONVEX_DEPLOY_KEY).toBe(DEPLOY_KEY);
return { code: 0, stdout: "imported", stderr: "", durationMs: 21 };
});
@@ -158,11 +161,11 @@ it("imports only with explicit mode and a data-scoped ephemeral key", async () =
{ fetchImpl, runCli },
),
);
- expect(result.imported).toBe(true);
- expect(result.mode).toBe("replace-all");
- expect(result.snapshot.bytes).toBe(22);
- expect(result.snapshot.sha256).toMatch(/^[a-f0-9]{64}$/);
- expect(deleted).toBe(true);
+ expect(result).toMatchObject({
+ imported: true, mode: "replace-all", snapshot: { bytes: 22, path: snapshot },
+ });
+ expect(result.snapshot.sha256).toMatch(/^[a-f0-9]{64}$/); expect(deleted).toBe(true);
+ await expect(fs.stat(stagedSnapshot)).rejects.toMatchObject({ code: "ENOENT" });
expect(JSON.stringify(result)).not.toContain(DEPLOY_KEY);
});
it("revokes the ephemeral key when the CLI operation fails", async () => {
diff --git a/lib/infra/convex-cloud-runner.ts b/lib/infra/convex-cloud-runner.ts
index ffd35630..857c2708 100644
--- a/lib/infra/convex-cloud-runner.ts
+++ b/lib/infra/convex-cloud-runner.ts
@@ -71,35 +71,41 @@ export async function importConvexCloudSnapshot(
const fetchImpl = deps.fetchImpl ?? fetch;
const execute = deps.runCli ?? runConvexCli;
- return withConvexEphemeralDeployKey(
- deployment,
- token,
- ["deployment:data:view", "deployment:data:write", "deployment:backups:view", "deployment:backups:import"],
- async (deployKey) => {
- const modeFlag = input.mode === "replace-all" ? "--replace-all" : "--append";
- const result = await execute(
- executable,
- ["import", snap.snapshot, modeFlag, "--yes"],
- {
- cwd: project,
- env: convexCliEnv(deployKey),
- timeoutMs: IMPORT_TIMEOUT_MS,
- },
- );
- if (result.code !== 0) throwConvexCliFailure("import", result, deployKey);
- return {
- deploymentName: deployment,
- projectPath: project,
- imported: true,
- mode: input.mode,
- snapshot: {
- path: snap.snapshot,
- bytes: snap.size,
- sha256: snap.sha256,
- },
- durationMs: result.durationMs,
- };
- },
- fetchImpl,
- );
+ try {
+ return await withConvexEphemeralDeployKey(
+ deployment,
+ token,
+ ["deployment:data:view", "deployment:data:write", "deployment:backups:view", "deployment:backups:import"],
+ async (deployKey) => {
+ const modeFlag =
+ input.mode === "replace-all" ? "--replace-all" : "--append";
+ const result = await execute(
+ executable,
+ ["import", snap.stagedSnapshot, modeFlag, "--yes"],
+ {
+ cwd: project,
+ env: convexCliEnv(deployKey),
+ timeoutMs: IMPORT_TIMEOUT_MS,
+ },
+ );
+ if (result.code !== 0)
+ throwConvexCliFailure("import", result, deployKey);
+ return {
+ deploymentName: deployment,
+ projectPath: project,
+ imported: true,
+ mode: input.mode,
+ snapshot: {
+ path: snap.snapshot,
+ bytes: snap.size,
+ sha256: snap.sha256,
+ },
+ durationMs: result.durationMs,
+ };
+ },
+ fetchImpl,
+ );
+ } finally {
+ await snap.cleanup();
+ }
}
diff --git a/lib/infra/convex-cloud-snapshot-security.test.ts b/lib/infra/convex-cloud-snapshot-security.test.ts
new file mode 100644
index 00000000..c5b5ec06
--- /dev/null
+++ b/lib/infra/convex-cloud-snapshot-security.test.ts
@@ -0,0 +1,45 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+let root = "";
+let snapshot = "";
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-snapshot-test-"));
+ snapshot = path.join(root, "source.zip");
+ process.env.OS_FS_READ_ROOTS = root;
+ await fs.writeFile(
+ snapshot,
+ Buffer.from([
+ 0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ ]),
+ { mode: 0o600 },
+ );
+ vi.resetModules();
+});
+
+afterEach(async () => {
+ delete process.env.OS_FS_READ_ROOTS;
+ await fs.rm(root, { recursive: true, force: true });
+ vi.resetModules();
+});
+
+it("stages the checked snapshot from one open descriptor into a private immutable input", async () => {
+ const original = await fs.readFile(snapshot);
+ const { convexSnapshotContext } = await import("./convex-cloud-cli-runner");
+ const context = await convexSnapshotContext(snapshot);
+ expect(context.stagedSnapshot).not.toBe(snapshot);
+ expect(path.dirname(context.stagedSnapshot)).toMatch(
+ /mso-convex-snapshot-[^/\\]+$/,
+ );
+ expect((await fs.stat(path.dirname(context.stagedSnapshot))).mode & 0o777).toBe(0o700);
+ expect((await fs.stat(context.stagedSnapshot)).mode & 0o777).toBe(0o600);
+ await fs.writeFile(snapshot, "changed after validation", { mode: 0o600 });
+ expect(await fs.readFile(context.stagedSnapshot)).toEqual(original);
+ expect(context.sha256).toMatch(/^[a-f0-9]{64}$/);
+ await context.cleanup();
+ await expect(fs.stat(context.stagedSnapshot)).rejects.toMatchObject({ code: "ENOENT" });
+});