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 bounded MCP store reads to one descriptor

Abdurrahman Fakhrulb2f4f607000b
diff --git a/app/api/models/test/route.test.ts b/app/api/models/test/route.test.ts
index 3a39497c..6b90119f 100644
--- a/app/api/models/test/route.test.ts
+++ b/app/api/models/test/route.test.ts
@@ -25,6 +25,29 @@ vi.mock("@/lib/models", () => ({ resolveModel: vi.fn() }));
vi.mock("@/lib/host/ssrf", () => ({ safeProviderFetch: vi.fn() }));
describe("/api/models/test OpenAI Codex OAuth", () => {
+ it("requires Owner before reading configuration or sending an inference request", async () => {
+ const { requireSession } = await import("@/lib/auth/require-session");
+ vi.mocked(requireSession).mockResolvedValueOnce(false);
+ const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
+ const { POST } = await import("./route");
+ expect((await POST()).status).toBe(401);
+ expect(requireSession).toHaveBeenCalledWith("owner");
+ expect(resolveModelRef).not.toHaveBeenCalled(); expect(fetch).not.toHaveBeenCalled();
+ });
+ it("sends only the selected model and static ping through the custom-provider guard", async () => {
+ resolveModelRef.mockResolvedValue("fixture/model");
+ const { selectedCustomConn } = await import("@/lib/config/store");
+ vi.mocked(selectedCustomConn).mockResolvedValueOnce({ baseUrl: "https://fixture.invalid/v1" });
+ const { resolveModel } = await import("@/lib/models");
+ vi.mocked(resolveModel).mockResolvedValue({ protocol: "openai", baseUrl: "https://fixture.invalid/v1", apiKey: "synthetic", provider: "fixture", model: "model", privateFileData: "must stay local" } as never);
+ const { safeProviderFetch } = await import("@/lib/host/ssrf");
+ vi.mocked(safeProviderFetch).mockResolvedValueOnce(new Response());
+ const { POST } = await import("./route");
+ expect((await (await POST()).json()).ok).toBe(true);
+ const [url, request] = vi.mocked(safeProviderFetch).mock.calls.at(-1)!;
+ expect(url).toBe("https://fixture.invalid/v1/chat/completions");
+ expect(JSON.parse(request!.body as string)).toEqual({ model: "model", max_tokens: 1, messages: [{ role: "user", content: "ping" }] });
+ });
it("bounds custom-provider error bodies and applies a deadline before fetching", async () => {
resolveModelRef.mockResolvedValue("fixture/model");
const { resolveModel } = await import("@/lib/models");
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 4e59730a..2b00f216 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Fixed**
+- `security` pin bounded MCP store reads to one descriptor
- `oauth` keep registered consent within narrow viewports
- `security` enforce live delegated grants and bound provider and OAuth state
- `security` close remaining repository scan trust boundaries
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index ffef58e6..c8d5874a 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,9 @@
+## 2026-10-09: Pin the bounded MCP store read and review the inference-test alert
+
+Post-release CodeQL found a check/reopen race in the new store byte limit. The reader now opens once with no-follow/nonblocking flags, checks and reads that descriptor into a size-bounded buffer, rejects growth/content changes and closes it on every path. Real-file regressions replace the pathname after open and grow the file after the size check. Atomic replacement still permits reading the original consistent snapshot.
+
+CodeQL alert #159 traces the selected model name from config.json into the Owner-only inference test's `model` field. That transmission is intentional: the request has a static ping, one-token budget, registry-selected built-in endpoint or the existing custom-provider SSRF guard, and no arbitrary file payload. It repeats the previously reviewed alert #22. Regression tests prove the Owner boundary and exact custom-provider request body. Only this specific false positive is reviewed; scanners, rules, inventory enforcement and real findings remain enabled.
+
## 2026-10-09: Close the eight findings from the independent security rescan
The completed rescan of `dac56bdf` found six Medium and two Low issues, with no High findings. Named MCP integrations now reuse the private endpoint-bound transport and recursive credential redaction rather than embedding bearer headers in an unbound server. OAuth consent accepts only server-generated registered client identities and their exact callbacks, preventing manual/pruned client IDs from aliasing another principal. The obsolete manual Client ID guidance is removed; clients must register and reconnect for new consent. The browser proof also exposed the consent grid's minimum-content width overflowing a 390px viewport; its card now permits shrinking, retaining readable content and the desktop/mobile reflow assertion.
diff --git a/lib/mcp/store-security.test.ts b/lib/mcp/store-security.test.ts
index 1d758ce0..496b83e4 100644
--- a/lib/mcp/store-security.test.ts
+++ b/lib/mcp/store-security.test.ts
@@ -18,6 +18,38 @@ afterEach(() => vi.restoreAllMocks());
describe("durable MCP credential isolation", () => {
+ it("reads the size-checked descriptor when the store pathname is replaced", async () => {
+ const state = await import("./store-state");
+ await state.commitMcpStore({ clients: { original: { name: "fixture", redirectUris: [], createdAt: Date.now() } }, codes: {}, tokens: {}, refreshTokens: {}, spentRefreshTokens: {} });
+ const open = fs.open.bind(fs);
+ vi.spyOn(fs, "open").mockImplementation(async (...args: Parameters<typeof fs.open>) => {
+ const handle = await open(...args);
+ if (args[0] === process.env.OS_MCP_STORE) {
+ await fs.rename(process.env.OS_MCP_STORE!, path.join(DIR, "previous.json"));
+ await fs.writeFile(process.env.OS_MCP_STORE!, "x".repeat(4 * 1024 * 1024 + 1), { mode: 0o600 });
+ }
+ return handle;
+ });
+ expect(Object.keys((await state.readMcpStore()).clients)).toEqual(["original"]);
+ });
+ it("rejects growth after the descriptor size check without reading an unbounded body", async () => {
+ const state = await import("./store-state");
+ await state.commitMcpStore(await state.readMcpStore());
+ const open = fs.open.bind(fs);
+ vi.spyOn(fs, "open").mockImplementation(async (...args: Parameters<typeof fs.open>) => {
+ const handle = await open(...args);
+ if (args[0] === process.env.OS_MCP_STORE) {
+ const stat = handle.stat.bind(handle);
+ vi.spyOn(handle, "stat").mockImplementationOnce(async () => {
+ const before = await stat();
+ await fs.appendFile(process.env.OS_MCP_STORE!, "x".repeat(4 * 1024 * 1024));
+ return before;
+ });
+ }
+ return handle;
+ });
+ await expect(state.readMcpStore()).rejects.toThrow(/changed while reading/);
+ });
it("bounds many rotations, prunes expired access, preserves absolute expiry and rate limits the authenticated family", async () => {
const clock = vi.spyOn(Date, "now").mockReturnValue(1_800_000_000_000);
await store.storeOAuthGrant({ accessToken: "a0", refreshToken: "r0", clientId: "bounded", label: "fixture", scope: "exec", resource: "https://fixture.invalid/mcp", grantId: "bounded" });
diff --git a/lib/mcp/store-state.ts b/lib/mcp/store-state.ts
index 6c9490ba..2ed302ca 100644
--- a/lib/mcp/store-state.ts
+++ b/lib/mcp/store-state.ts
@@ -1,6 +1,6 @@
import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
-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 type { McpStore } from "./store-types";
@@ -12,13 +12,25 @@ const empty = (): McpStore => ({ clients: {}, codes: {}, tokens: {}, refreshToke
export async function readMcpStore(): Promise<McpStore> {
let raw: string;
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
try {
- if ((await fs.stat(STORE_PATH)).size > MAX_STORE_BYTES) throw new Error("MCP credential store size limit reached");
- raw = await fs.readFile(STORE_PATH, "utf8");
+ handle = await fs.open(STORE_PATH, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ const before = await handle.stat();
+ if (!before.isFile() || before.size > MAX_STORE_BYTES) throw new Error("MCP credential store size limit reached");
+ const bytes = Buffer.alloc(before.size + 1);
+ let used = 0;
+ while (used < bytes.length) {
+ const { bytesRead } = await handle.read(bytes, used, bytes.length - used, used);
+ if (!bytesRead) break;
+ used += bytesRead;
+ }
+ const after = await handle.stat();
+ if (used !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs) throw new Error("MCP credential store changed while reading");
+ raw = bytes.subarray(0, used).toString("utf8");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return empty();
throw error;
- }
+ } finally { await handle?.close(); }
const parsed = JSON.parse(raw) as Partial<McpStore>;
return {
clients: parsed.clients ?? {},