Skip to content

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

fix: require host control for arbitrary Image Gen setup interpreters (#9015)

[._.]/ Adam Eivy045669e5b063
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 711fb0fcb2..4746fbbd31 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -740,8 +740,24 @@ const PYTHON_BASENAMES = IS_WIN
? ['python.exe', 'python3.exe']
: ['python', 'python3'];
+// A UNC share (`\\host\share\…` or its POSIX-typed twin `//host/share/…`)
+// names a binary that lives on a REMOTE machine — launching it hands
+// execution to whoever controls that share. Checked ahead of the basename
+// test below so `\\attacker\share\python.exe` never gets to the point where
+// its basename ("python.exe") would otherwise pass.
+const isUncPath = (p) => /^\\\\/.test(p) || /^\/\//.test(p);
+
+// A path with directory separators that isn't absolute (`./venv/bin/python3`,
+// `subdir/python3`, a bare relative walk) resolves against whatever the
+// server process's cwd happens to be when the route runs — attacker-
+// influenced in ways an absolute path or a bare basename (resolved on PATH
+// by execFile itself) is not. A bare basename has no separator and is exempt.
+const isAbsolutePath = (p) => /^\//.test(p) || /^[a-zA-Z]:[\\/]/.test(p) || /^\\(?!\\)/.test(p);
+
export function isAllowedPython(pythonPath) {
if (typeof pythonPath !== 'string' || !pythonPath) return false;
+ if (isUncPath(pythonPath)) return false;
+ if (/[\\/]/.test(pythonPath) && !isAbsolutePath(pythonPath)) return false;
if (PYTHON_CANDIDATES.includes(pythonPath)) return true;
// Allow any path whose basename looks like a python interpreter — covers
// user-typed venvs (`/path/to/.venv/bin/python3.12`) without opening up
diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.js
index 8043c08e2f..ebf4da9521 100644
--- a/server/lib/pythonSetup.test.js
+++ b/server/lib/pythonSetup.test.js
@@ -186,6 +186,47 @@ describe('HOST_ARCH', () => {
});
});
+describe('isAllowedPython (#9015 — a caller-supplied path must not reach any file merely named python*)', () => {
+ beforeEach(resetState);
+
+ it('accepts a bare basename and a plausible absolute interpreter path', async () => {
+ const { isAllowedPython } = await loadModule();
+ expect(isAllowedPython('python3')).toBe(true);
+ expect(isAllowedPython('python')).toBe(true);
+ expect(isAllowedPython('/usr/bin/python3')).toBe(true);
+ expect(isAllowedPython('/Users/test/.venv/bin/python3.12')).toBe(true);
+ });
+
+ it('rejects a UNC path even though its basename looks like an interpreter', async () => {
+ const { isAllowedPython } = await loadModule();
+ // Windows-style UNC share.
+ expect(isAllowedPython('\\\\host\\share\\python.exe')).toBe(false);
+ // The POSIX-typed twin of a UNC share.
+ expect(isAllowedPython('//host/share/python3')).toBe(false);
+ });
+
+ it('rejects a relative path with directory components', async () => {
+ const { isAllowedPython } = await loadModule();
+ expect(isAllowedPython('./venv/bin/python3')).toBe(false);
+ expect(isAllowedPython('subdir/python3')).toBe(false);
+ expect(isAllowedPython('../../tmp/python3')).toBe(false);
+ });
+
+ it('still rejects a path whose basename is not a python interpreter', async () => {
+ const { isAllowedPython } = await loadModule();
+ expect(isAllowedPython('/usr/bin/bash')).toBe(false);
+ expect(isAllowedPython('')).toBe(false);
+ expect(isAllowedPython(null)).toBe(false);
+ });
+
+ it('accepts a Windows absolute interpreter path and still rejects UNC on win32', async () => {
+ mockState.platform = 'win32';
+ const { isAllowedPython } = await loadModule();
+ expect(isAllowedPython('C:\\Users\\test\\venv\\Scripts\\python.exe')).toBe(true);
+ expect(isAllowedPython('\\\\host\\share\\python.exe')).toBe(false);
+ });
+});
+
describe('probePythonArch', () => {
beforeEach(resetState);
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 8d2e2d47fa..f437e887c5 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -96,7 +96,11 @@ vi.mock('../services/imageGen/index.js', () => ({
// Default to external mode in tests so /generate goes through the dispatcher.
// Local-mode tests below override the settings mock to flip into queue mode.
-vi.mock('../services/settings.js', () => ({
+// Spread the real module (rather than replacing it outright) so `settingsEvents`
+// stays a real EventEmitter — `authGate.js` (reached via imageGenSetup.js's
+// `resolveSetupInterpreter`, #9015) subscribes to it at import time.
+vi.mock('../services/settings.js', async (importOriginal) => ({
+ ...(await importOriginal()),
getSettings: vi.fn(async () => ({ imageGen: { mode: 'external' } })),
}));
@@ -213,6 +217,17 @@ describe('Image Gen Routes', () => {
beforeEach(() => {
app = express();
app.use(express.json());
+ // These requests run over a real loopback socket (`lib/testHelper.js`'s
+ // fetch-based harness), so on a real password-free install they'd carry
+ // host control via `requestHasHostControl` — this stands in for the
+ // `authGate` middleware server/index.js mounts ahead of every route,
+ // without dragging its settings/instance-identity dependencies into this
+ // suite. `imageGenSetup.js`'s `/setup/*` routes need it (#9015) to reach
+ // an interpreter path outside the caller's own allowlisted categories.
+ app.use((req, _res, next) => {
+ req.portosAuthContext = { enabled: false, authenticated: false, method: null };
+ next();
+ });
app.use('/api/image-gen', imageGenRoutes);
app.use(errorMiddleware);
vi.clearAllMocks();
diff --git a/server/routes/imageGenSetup.js b/server/routes/imageGenSetup.js
index 167d4c4a1d..123d29cb54 100644
--- a/server/routes/imageGenSetup.js
+++ b/server/routes/imageGenSetup.js
@@ -13,6 +13,7 @@
import { Router } from 'express';
import { z } from 'zod';
import { join } from 'node:path';
+import { realpathSync } from 'node:fs';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { getSettings, updateSettingsWith } from '../services/settings.js';
@@ -24,11 +25,56 @@ import {
resolveFlux2Python, FLUX2_VENV_DEFAULT, installFlux2Venv, isFlux2InstallSatisfied,
} from '../lib/pythonSetup.js';
import { PATHS } from '../lib/fileUtils.js';
+import { isPathInsideDir } from '../lib/pathSafety.js';
+import { requestHasHostControl, HOST_CONTROL_FORBIDDEN_MESSAGE } from '../services/authGate.js';
import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';
import { getSetupCheck, invalidateSetupCheck, REQUIRED_PIP_NAMES } from '../services/imageGen/setup.js';
const router = Router();
+// AUTHORITY gate for a caller-supplied interpreter path, layered on top of
+// `isAllowedPython`'s FORMAT check (basename looks like a python interpreter,
+// not UNC, not a bare relative walk). A path that merely LOOKS like a python
+// binary can still name an attacker-planted file anywhere on the host's
+// filesystem or a reachable network share — see #9015. A caller without host
+// control may reach only interpreters PortOS itself would have picked:
+// - a bare basename (`python3`, `python`) — execFile resolves that on the
+// server's own PATH, so a remote caller can't smuggle in a foreign binary
+// just by naming a common word.
+// - the interpreter stored in `settings.imageGen.local.pythonPath` — the
+// operator already chose this one (gated on write by #8751).
+// - an interpreter that resolves (after symlinks) inside PortOS's own
+// managed venv directory (`<data>/python/`).
+// Anything else — an arbitrary absolute path, an interpreter the operator
+// never configured — requires `requestHasHostControl(req)`.
+async function resolveSetupInterpreter(req, candidate) {
+ if (!/[\\/]/.test(candidate)) return true;
+
+ const settings = await getSettings();
+ const storedPath = settings?.imageGen?.local?.pythonPath;
+ if (typeof storedPath === 'string' && storedPath && candidate === storedPath) return true;
+
+ try {
+ // Both sides through realpath: a symlinked ancestor of `PATHS.data`
+ // (common for a test's temp data root, and possible for a real install
+ // whose data dir sits on a symlinked volume) would otherwise compare an
+ // unresolved root against a resolved candidate and never match.
+ const realCandidate = realpathSync(candidate);
+ const realVenvRoot = realpathSync(join(PATHS.data, 'python'));
+ if (isPathInsideDir(realVenvRoot, realCandidate)) return true;
+ } catch {
+ // Candidate or the managed venv root doesn't exist (yet) or isn't
+ // reachable — falls through to the host-control check below rather than
+ // being trusted on format alone.
+ }
+
+ return requestHasHostControl(req);
+}
+
+function forbidWithoutHostControl() {
+ throw new ServerError(HOST_CONTROL_FORBIDDEN_MESSAGE, { status: 403, code: 'HOST_CONTROL_FORBIDDEN' });
+}
+
router.get('/python', asyncHandler(async (_req, res) => {
const path = await detectPython();
res.json({ path });
@@ -210,6 +256,7 @@ const sendSetupCheck = async (req, res) => {
code: 'INVALID_PYTHON_PATH',
});
}
+ if (!(await resolveSetupInterpreter(req, pythonPath))) forbidWithoutHostControl();
res.json(await getSetupCheck(pythonPath));
};
@@ -221,8 +268,11 @@ const venvSchema = z.object({
router.post('/create-venv', asyncHandler(async (req, res) => {
const { basePython } = validateRequest(venvSchema, req.body || {});
- if (basePython && !isAllowedPython(basePython)) {
- throw new ServerError('basePython must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });
+ if (basePython) {
+ if (!isAllowedPython(basePython)) {
+ throw new ServerError('basePython must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });
+ }
+ if (!(await resolveSetupInterpreter(req, basePython))) forbidWithoutHostControl();
}
const base = basePython || (await detectPython());
if (!base) {
@@ -260,6 +310,7 @@ router.post('/install', asyncHandler(async (req, res) => {
code: 'INVALID_PYTHON_PATH',
});
}
+ if (!(await resolveSetupInterpreter(req, input.pythonPath))) forbidWithoutHostControl();
const disallowed = input.packages.filter((p) => !REQUIRED_PIP_NAMES.has(p));
if (disallowed.length) {
throw new ServerError(`Packages not in allowlist: ${disallowed.join(', ')}`, {
diff --git a/server/routes/imageGenSetup.test.js b/server/routes/imageGenSetup.test.js
new file mode 100644
index 0000000000..7d04b15efd
--- /dev/null
+++ b/server/routes/imageGenSetup.test.js
@@ -0,0 +1,159 @@
+/**
+ * #9015 — `/api/image-gen/setup/*` must not execute any caller-supplied file
+ * merely because it is NAMED `python*`. Before this fix, `isAllowedPython`
+ * was a basename-only check: `pythonPath=/tmp/x/python3` (or a UNC share on
+ * Windows) passed it and was executed straight away. These tests exercise
+ * `resolveSetupInterpreter`'s AUTHORITY gate through the REAL `authGate`
+ * middleware (mirroring `server/routes/hostControlFamilies.test.js`), so the
+ * loopback-vs-remote distinction is the genuine one `requestHasHostControl`
+ * makes, not a stand-in.
+ */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { request } from '../lib/testHelper.js';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-imagegen-setup-') }));
+afterAll(cleanupTempDataRoots);
+
+// Pinned to a password-free install, same as hostControlFamilies.test.js —
+// the developer's own settings must not change what these cases observe.
+vi.mock('../services/auth.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ isAuthEnabled: vi.fn().mockResolvedValue(false),
+}));
+
+const settingsStore = vi.hoisted(() => ({ current: {} }));
+vi.mock('../services/settings.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getSettings: vi.fn(async () => settingsStore.current),
+ updateSettingsWith: vi.fn(async (mutate) => mutate(settingsStore.current)),
+}));
+
+const setupCheck = vi.hoisted(() => ({
+ getSetupCheck: vi.fn(async (pythonPath) => ({ pythonPath, installed: [], missing: [] })),
+ invalidateSetupCheck: vi.fn(),
+}));
+vi.mock('../services/imageGen/setup.js', () => ({
+ getSetupCheck: setupCheck.getSetupCheck,
+ invalidateSetupCheck: setupCheck.invalidateSetupCheck,
+ REQUIRED_PIP_NAMES: new Set(['mflux']),
+}));
+
+const pySetup = vi.hoisted(() => ({
+ createVenv: vi.fn(async (_base, target) => join(target, 'bin', 'python3')),
+ installPackages: vi.fn(() => ({ promise: Promise.resolve(), kill: vi.fn() })),
+}));
+vi.mock('../lib/pythonSetup.js', async (importOriginal) => ({
+ ...(await importOriginal()), // keep the real isAllowedPython format check
+ detectPython: vi.fn(async () => 'python3'),
+ createVenv: pySetup.createVenv,
+ installPackages: pySetup.installPackages,
+ resolveFlux2Python: vi.fn(() => null),
+ isFlux2InstallSatisfied: vi.fn(async () => true),
+}));
+
+import { authGate } from '../services/authGate.js';
+import imageGenSetupRoutes from './imageGenSetup.js';
+import { PATHS } from '../lib/fileUtils.js';
+
+// Mirrors the order server/index.js mounts them in: authGate observes the
+// real socket address, same as hostControlFamilies.test.js.
+const buildApp = (remoteAddress) => {
+ const app = express();
+ app.use((req, _res, next) => {
+ Object.defineProperty(req.socket, 'remoteAddress', { value: remoteAddress });
+ next();
+ });
+ app.use(authGate);
+ app.use(express.json());
+ app.use('/api/image-gen/setup', imageGenSetupRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+const remote = () => buildApp('192.0.2.10');
+const local = () => buildApp('127.0.0.1');
+
+const expectForbidden = (response) => {
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+};
+
+describe('/api/image-gen/setup/* interpreter admission (#9015)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ settingsStore.current = {};
+ setupCheck.getSetupCheck.mockClear();
+ pySetup.createVenv.mockClear();
+ pySetup.installPackages.mockClear();
+ });
+
+ it('refuses a remote password-free caller naming an arbitrary absolute interpreter, and spawns nothing', async () => {
+ const arbitrary = '/tmp/x/python3';
+
+ expectForbidden(await request(remote()).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(arbitrary)}`));
+ expect(setupCheck.getSetupCheck).not.toHaveBeenCalled();
+
+ expectForbidden(await request(remote()).post('/api/image-gen/setup/create-venv').send({ basePython: arbitrary }));
+ expect(pySetup.createVenv).not.toHaveBeenCalled();
+
+ expectForbidden(await request(remote())
+ .post(`/api/image-gen/setup/install?pythonPath=${encodeURIComponent(arbitrary)}&packages=mflux`));
+ expect(pySetup.installPackages).not.toHaveBeenCalled();
+ });
+
+ it('a UNC path is rejected as an invalid interpreter (400) before authority is even considered', async () => {
+ const unc = '\\\\host\\share\\python.exe';
+ const response = await request(remote()).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(unc)}`);
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('INVALID_PYTHON_PATH');
+ expect(setupCheck.getSetupCheck).not.toHaveBeenCalled();
+ });
+
+ it('a remote caller may still use a bare basename — execFile resolves it on the server PATH', async () => {
+ const response = await request(remote()).get('/api/image-gen/setup/check?pythonPath=python3');
+ expect(response.status).toBe(200);
+ expect(setupCheck.getSetupCheck).toHaveBeenCalledWith('python3');
+ });
+
+ it('a remote caller may still use the interpreter stored in settings.imageGen.local.pythonPath', async () => {
+ const stored = '/opt/example-venv/bin/python3';
+ settingsStore.current = { imageGen: { local: { pythonPath: stored } } };
+ const response = await request(remote()).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(stored)}`);
+ expect(response.status).toBe(200);
+ expect(setupCheck.getSetupCheck).toHaveBeenCalledWith(stored);
+ });
+
+ it('a remote caller may still reach an interpreter inside the PortOS-managed venv directory', async () => {
+ const venvDir = join(PATHS.data, 'python', 'venv', 'bin');
+ mkdirSync(venvDir, { recursive: true });
+ const managedPython = join(venvDir, 'python3');
+ writeFileSync(managedPython, '');
+
+ const response = await request(remote()).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(managedPython)}`);
+ expect(response.status).toBe(200);
+ expect(setupCheck.getSetupCheck).toHaveBeenCalledWith(managedPython);
+ });
+
+ it('a loopback caller on a password-free install may still probe or install into any interpreter path', async () => {
+ const arbitrary = '/tmp/x/python3';
+
+ const check = await request(local()).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(arbitrary)}`);
+ expect(check.status).toBe(200);
+ expect(setupCheck.getSetupCheck).toHaveBeenCalledWith(arbitrary);
+
+ const venv = await request(local()).post('/api/image-gen/setup/create-venv').send({ basePython: arbitrary });
+ expect(venv.status).toBe(200);
+ expect(pySetup.createVenv).toHaveBeenCalledWith(arbitrary, expect.any(String));
+
+ const install = await request(local())
+ .post(`/api/image-gen/setup/install?pythonPath=${encodeURIComponent(arbitrary)}&packages=mflux`);
+ expect(install.status).toBe(200);
+ expect(pySetup.installPackages).toHaveBeenCalled();
+ });
+});