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): validate trace metadata and use atomic file descriptors

Rahman2972298a74a8
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index f64fa231..ed4922f8 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Fixed**
+- `security` validate trace metadata and use atomic file descriptors
- `security` bound code-scanning filesystem paths and CLI test execution
- `organization` memoize focused groups and retain group search
- `deps` update brace-expansion within supported major lines
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 9b4618ad..08280bd9 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,7 @@
+## 2026-09-30 — Follow-up scan: atomic CLI state and native environment
+
+The exact security release closed all seven reported alerts and exposed two file-check/use findings in previously integrated native-install and A2A-trace code. Native environment creation now uses one exclusive descriptor while preserving existing configuration, and all saved trace reads use a capped O_NOFOLLOW descriptor. Trace persistence accepts only known bounded metadata fields and validated identifiers; malformed API metadata is rejected before writing. The remaining network-to-file finding is intentional private JSON session/workflow metadata persistence, never an executable download; review and scanner state are recorded separately from the two code fixes.
+
## 2026-09-30 — Code-scanning filesystem boundary fixes
Closed the shared bounded-reader gap with lexical and real-parent containment against configured read roots (or the explicit root of an already-authorized internal store/skill scan) while retaining final-component O_NOFOLLOW and pre-allocation size limits. Repository-memory project roots use the host read guard and reject a symlinked memory parent before reads or writes. Project knowledge rejects redirected metadata directories, and linked-worktree lookup checks lexical containment before probing a caller path. The memory-backup CLI fixture now executes a fixed Bash file instead of dynamic shell code. Regression fixtures explicitly authorize their temporary roots and exercise traversal, out-of-root access, symlink parents and preserved valid reads. The current lockfile already contains brace-expansion 1.1.21 and 5.0.12, which cover the three advisory IDs in Scorecard alert 118; scanner closure must be verified against the released SHA. Release-gate count/identity fixtures now use a fixed clock, keeping their assertions independent of a concurrent build while the dedicated deadline/cursor regression still exercises the real production budget.
diff --git a/scripts/a2a-trace-support.mjs b/scripts/a2a-trace-support.mjs
index 399e3c6d..29c71773 100644
--- a/scripts/a2a-trace-support.mjs
+++ b/scripts/a2a-trace-support.mjs
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { promises as fs } from "node:fs";
+import { constants, promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import process from "node:process";
@@ -65,21 +65,38 @@ async function statePath(id) {
return path.join(ROOT, validRunId(id) + ".json");
}
+const STATE_LIMITS = { runId: 80, agent: 48, project: 240, sessionId: 120, sessionLabel: 120, workflowId: 120, status: 24, startedAt: 40, updatedAt: 40, lastFingerprint: 600 };
+function checkState(state) {
+ if (!state || state.version !== 1 || typeof state.runId !== "string" || state.runId !== validRunId(state.runId)) fail("invalid A2A trace state");
+ if (!/^[a-zA-Z0-9_-]{1,120}$/.test(state.sessionId) || !/^[a-zA-Z0-9_-]{1,120}$/.test(state.workflowId)) fail("invalid A2A trace identifiers");
+ if (!["active", "attached", "finished", "failed", "cancelled"].includes(state.status)) fail("invalid A2A trace status");
+ for (const [key, value] of Object.entries(state)) {
+ if (key === "version") continue;
+ if (key === "lastEventMs") { if (!Number.isSafeInteger(value) || value < 0) fail("invalid A2A trace timestamp"); continue; }
+ if (!Object.hasOwn(STATE_LIMITS, key) || (value !== undefined && (typeof value !== "string" || value.length > STATE_LIMITS[key]))) fail("invalid A2A trace field: " + key);
+ }
+ return state;
+}
+
export async function saveState(state) {
+ checkState(state);
const file = await statePath(state.runId);
const temp = file + "." + process.pid + "." + Date.now() + ".tmp";
await fs.writeFile(temp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600, flag: "wx" });
- await fs.chmod(temp, 0o600).catch(() => undefined);
await fs.rename(temp, file);
}
export async function readState(id) {
const file = await statePath(id);
- const stat = await fs.lstat(file).catch(() => null);
- if (!stat || !stat.isFile() || stat.isSymbolicLink()) fail("A2A trace run not found: " + id);
- const state = JSON.parse(await fs.readFile(file, "utf8"));
- if (state && state.version === 1 && state.sessionId && state.workflowId) return state;
- fail("invalid A2A trace state: " + id);
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size > 8192) fail("invalid A2A trace state file");
+ const body = Buffer.alloc(stat.size);
+ const { bytesRead } = await handle.read(body, 0, body.length, 0);
+ if (bytesRead !== body.length) fail("A2A trace state changed during read");
+ return checkState(JSON.parse(body.toString("utf8")));
+ } finally { await handle.close(); }
}
export async function resolveState(options) {
@@ -152,7 +169,7 @@ export async function listRuns() {
for (const entry of entries) {
if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
try {
- const value = JSON.parse(await fs.readFile(path.join(ROOT, entry.name), "utf8"));
+ const value = await readState(entry.name.slice(0, -5));
if (value && value.version === 1) rows.push({
run_id: value.runId, agent: value.agent, project: value.project, status: value.status,
workflow_id: value.workflowId, session_label: value.sessionLabel, updated_at: value.updatedAt
diff --git a/scripts/a2a-trace.test.ts b/scripts/a2a-trace.test.ts
index cc7f1a8d..beb7cb10 100644
--- a/scripts/a2a-trace.test.ts
+++ b/scripts/a2a-trace.test.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
-import { mkdtemp, readFile, rm, stat } from "node:fs/promises";
+import { mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -81,6 +81,20 @@ describe("A2A workflow trace bridge", () => {
expect((await stat(file)).mode & 0o777).toBe(0o600);
});
+ it("rejects malformed remote state and never follows a swapped state-file symlink", async () => {
+ const support = await import("./a2a-trace-support.mjs");
+ const state = JSON.parse(await readFile(path.join(stateDir, "a2a-test.json"), "utf8"));
+ await expect(support.saveState({ ...state, sessionId: { command: "malicious" } })).rejects.toThrow("invalid A2A trace");
+ await expect(support.saveState({ ...state, sessionLabel: "x".repeat(121) })).rejects.toThrow("invalid A2A trace field");
+ await expect(support.saveState({ ...state, executable: "malicious" })).rejects.toThrow("invalid A2A trace field");
+ const target = path.join(stateDir, "outside.json");
+ await writeFile(target, JSON.stringify(state));
+ await symlink(target, path.join(stateDir, "a2a-link.json"));
+ await expect(support.readState("a2a-link")).rejects.toMatchObject({ code: "ELOOP" });
+ await writeFile(path.join(stateDir, "a2a-huge.json"), "x".repeat(8193));
+ await expect(support.readState("a2a-huge")).rejects.toThrow("invalid A2A trace state file");
+ });
+
it("does not expose hidden reasoning as a trace event type", async () => {
await expect(mod.main(["reasoning", "--run", "a2a-test", "--message", "private thoughts"])).rejects.toThrow("unknown A2A trace command");
});
diff --git a/scripts/install-native.mjs b/scripts/install-native.mjs
index a6782db5..7b617f33 100644
--- a/scripts/install-native.mjs
+++ b/scripts/install-native.mjs
@@ -49,12 +49,17 @@ if (fs.existsSync(path.join(root, ".next"))) {
const state = path.join(home, ".mso");
fs.mkdirSync(state, { recursive: true, mode: 0o700 });
if (fs.lstatSync(state).isSymbolicLink()) fail("private state directory cannot be a symlink");
-if (fs.existsSync(envFile) && fs.lstatSync(envFile).isSymbolicLink()) fail("refusing symlinked .env.local");
run("bun", ["install", "--frozen-lockfile"]);
run(process.execPath, ["-e", "require('node-pty')"], { quiet: true });
let generatedPassword = "";
-if (!fs.existsSync(envFile)) {
+let envFd;
+try { envFd = fs.openSync(envFile, "wx", 0o600); }
+catch (error) {
+ if (error.code !== "EEXIST") throw error;
+ if (fs.lstatSync(envFile).isSymbolicLink()) fail("refusing symlinked .env.local");
+}
+if (envFd !== undefined) {
generatedPassword = randomBytes(24).toString("base64url");
const secret = randomBytes(32).toString("hex");
const content = `# Native MSO host. Keep this file private.
@@ -63,7 +68,7 @@ OS_SESSION_SECRET=${secret}
OS_MCP_ENABLED=1
OS_MCP_MAX_SCOPE=read
`;
- fs.writeFileSync(envFile, content, { flag: "wx", mode: 0o600 });
+ try { fs.writeFileSync(envFd, content); } finally { fs.closeSync(envFd); }
if (host === "win32") {
const account = run("whoami", ["/user", "/fo", "csv", "/nh"], { quiet: true });
const sid = account.match(/S-1-\d+(?:-\d+)+/i)?.[0];
diff --git a/scripts/install-native.test.ts b/scripts/install-native.test.ts
new file mode 100644
index 00000000..796e0dae
--- /dev/null
+++ b/scripts/install-native.test.ts
@@ -0,0 +1,36 @@
+import { afterAll, describe, expect, it } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import vm from "node:vm";
+import { randomBytes } from "node:crypto";
+
+const base = fs.mkdtempSync(path.join(os.tmpdir(), "mso-native-env-"));
+const source = fs.readFileSync("scripts/install-native.mjs", "utf8").replace(/^import .*;\n/gm, "").replaceAll("import.meta.url", "'fixture'");
+afterAll(() => { fs.rmSync(base, { recursive: true, force: true }); });
+function install(name: string, seed?: (root: string) => void, fileSystem = fs) {
+ const root = path.join(base, name); fs.mkdirSync(path.join(root, ".git"), { recursive: true }); seed?.(root);
+ vm.runInNewContext(source, { fs: fileSystem, os: { homedir: () => root }, path, randomBytes,
+ fileURLToPath: () => path.join(root, "scripts/install-native.mjs"),
+ process: { platform: "darwin", versions: { node: "22.12.0" }, execPath: "node", env: { CI: "true" }, stdout: { write() {} }, stderr: { write() {} }, exit() { throw new Error("install refused"); } },
+ spawnSync: (_program: string, args: string[]) => ({ status: 0, stdout: args[0] === "remote" ? "https://github.com/rahmanef63/mso.git" : "" }),
+ });
+ return path.join(root, ".env.local");
+}
+describe("native installer atomic private environment creation", () => {
+ it("creates a private file and preserves an existing environment", () => {
+ const file = install("fresh"); expect(fs.statSync(file).mode & 0o777).toBe(0o600);
+ expect(fs.readFileSync(file, "utf8")).toContain("OS_SESSION_SECRET=");
+ const existing = install("existing", root => fs.writeFileSync(path.join(root, ".env.local"), "keep"));
+ expect(fs.readFileSync(existing, "utf8")).toBe("keep");
+ });
+ it("refuses a symlink inserted immediately before exclusive creation", () => {
+ const target = path.join(base, "outside"); fs.writeFileSync(target, "keep");
+ let attempted = false;
+ const guardedFs = { ...fs, openSync(file: fs.PathLike, flags: fs.OpenMode, mode?: fs.Mode | null) {
+ attempted = true; fs.symlinkSync(target, file); return fs.openSync(file, flags, mode);
+ } };
+ expect(() => install("raced", undefined, guardedFs)).toThrow("install refused");
+ expect(attempted).toBe(true); expect(fs.readFileSync(target, "utf8")).toBe("keep");
+ });
+});