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

address review (codex): sanitize screenshots at the /api/runs boundary, keep trusted absolute paths working

[._.]/ Adam Eivydc08ad1c8cac
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 08bfff7d0e..e76201df9c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -9,7 +9,7 @@
- **Backup restore/delete path validation hardened** — `subdirFilter` on `POST /api/backup/restore` was an unconstrained string interpolated into an rsync `--include=${subdirFilter}/***` arg, so `*` could override the filter chain (restoring everything over live data) and `../foo` could traverse out of the snapshot subdir; it now validates against a relative path pattern that rejects wildcard, `..`, and absolute-path segments, with a mirrored defense-in-depth guard in `restoreSnapshot` for non-route callers. `deleteBackup` previously validated `filename.replace(/[.]/g,'')` (so the real dotted filename was never checked, leaving only the `startsWith(backupDir)` guard) — it now validates the raw filename directly and explicitly rejects `..`. (#1822)
- **Settings API no longer leaks third-party API tokens** — `GET` and `PUT /api/settings` redacted only the top-level `secrets` key, so `imageGen.hfToken` (HuggingFace) and `civitai.apiKey` were returned in full on both initial load and after any save. Both responses now run through a single sanitizer that strips those tokens (sibling config preserved), matching how the Settings UI already reads only token *presence* from the dedicated `/image-gen/setup/hf-token-status` and `/loras/auth/civitai` status routes. On-disk values are untouched. (#1821)
- **Vision-test endpoint no longer reads arbitrary files** — `POST /api/providers/:id/test-vision` took `imagePath` straight from the request body, so a `../` traversal or absolute path could have any readable file base64-encoded and forwarded to the configured external vision provider. The image loader now allowlists `imagePath` to a real image basename under `data/screenshots` (via the canonical `resolveScreenshot` path resolver), rejecting traversal and absolute-path escapes before any file is read or forwarded. (#1820)
-- **`POST /api/runs` vision screenshots no longer read arbitrary files** — the same unsanitized-`imagePath` gap as #1820 lived in the vendored aiToolkit runner: `screenshots[]` was validated only as `z.array(z.string())` and passed straight to `loadImageAsBase64`, which did `imagePath.startsWith('/') ? imagePath : join(screenshotsDir, imagePath)` — so `{ "screenshots": ["../../../../etc/passwd"] }` (or an absolute path) could have any readable file base64-encoded and forwarded to the configured external vision provider. Because the toolkit is self-contained (no imports out to PortOS modules), the loader now applies a basename + image-extension allowlist + `resolve().startsWith(screenshotsDir)` containment guard inline — mirroring `resolveScreenshot`'s semantics — and rejects anything outside the screenshots root before any file is read. Rejected paths are logged and skipped (matching the existing missing-image handling), so a bad entry never crashes the out-of-request runner. (#1870)
+- **`POST /api/runs` vision screenshots no longer read arbitrary files** — the same unsanitized-`imagePath` gap as #1820 lived in the vendored aiToolkit runner: `screenshots[]` was validated only as `z.array(z.string())` and passed straight to `loadImageAsBase64`, which did `imagePath.startsWith('/') ? imagePath : join(screenshotsDir, imagePath)` — so `{ "screenshots": ["../../../../etc/passwd"] }` (or an absolute path) could have any readable file base64-encoded and forwarded to the configured external vision provider. The untrusted `POST /api/runs` boundary now sanitizes `screenshots[]` via a new `sanitizeScreenshotRefs` helper that `basename`s each entry (collapsing both `../` traversal and absolute-path escapes, including the legitimate absolute paths the Runner UI uploads under `data/screenshots`) and enforces an image-extension allow-list, returning a 400 for any non-image / traversal reference before the run is created. The shared `loadImageAsBase64` loader additionally `basename`s relative refs as defense-in-depth, while still passing trusted in-process absolute paths (e.g. Universe Builder gallery images under `data/images`, already validated by `resolveImageSources`) through unchanged. Kept self-contained — no imports out of the toolkit. (#1870)
## Added
diff --git a/server/lib/aiToolkit/routes/runs.js b/server/lib/aiToolkit/routes/runs.js
index 326ef5e675..9398815918 100644
--- a/server/lib/aiToolkit/routes/runs.js
+++ b/server/lib/aiToolkit/routes/runs.js
@@ -1,5 +1,5 @@
import { Router } from 'express';
-import { runSchema, validate } from '../validation.js';
+import { runSchema, validate, sanitizeScreenshotRefs } from '../validation.js';
import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';
export function createRunsRoutes(runnerService, options = {}) {
@@ -38,6 +38,20 @@ export function createRunsRoutes(runnerService, options = {}) {
throw new ServerError('prompt is required', { status: 400 });
}
+ // `screenshots[]` is untrusted user input that the vision loader
+ // base64-encodes and forwards to the external provider — constrain it to
+ // safe screenshots-dir basenames here so a `../` traversal or absolute path
+ // can't exfiltrate an arbitrary file (issue #1870). A non-image / traversal
+ // entry is rejected loudly rather than silently dropped.
+ const { safe: safeScreenshots, rejected } = sanitizeScreenshotRefs(screenshots);
+ if (rejected.length > 0) {
+ throw new ServerError('Invalid screenshot path', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: `Disallowed screenshot reference(s): ${rejected.join(', ')}` },
+ });
+ }
+
const runData = await runnerService.createRun({
providerId,
model,
@@ -45,7 +59,7 @@ export function createRunsRoutes(runnerService, options = {}) {
workspacePath,
workspaceName,
timeout,
- screenshots
+ screenshots: safeScreenshots
});
const { runId, provider, metadata, timeout: effectiveTimeout } = runData;
@@ -91,7 +105,7 @@ export function createRunsRoutes(runnerService, options = {}) {
model: runModel,
prompt,
workspacePath,
- screenshots,
+ screenshots: safeScreenshots,
onData: (data) => {
io?.emit(`run:${runId}:data`, data);
},
diff --git a/server/lib/aiToolkit/routes/runs.test.js b/server/lib/aiToolkit/routes/runs.test.js
index 97339d99d8..d76d0caf11 100644
--- a/server/lib/aiToolkit/routes/runs.test.js
+++ b/server/lib/aiToolkit/routes/runs.test.js
@@ -163,4 +163,37 @@ describe('POST /api/runs — fallback-model execution', () => {
expect(res.status).toBe(400);
expect(runnerService.createRun).not.toHaveBeenCalled();
});
+
+ describe('screenshot path sanitization (#1870)', () => {
+ it('rejects a traversal screenshot path with 400 before reaching the runner', async () => {
+ const { app, runnerService } = makeApp(runData({ providerType: 'api', defaultModel: 'd' }));
+ const res = await request(app)
+ .post('/api/runs')
+ .send({ providerId: 'p1', prompt: 'hi', screenshots: ['../../../../etc/passwd'] });
+ expect(res.status).toBe(400);
+ expect(runnerService.createRun).not.toHaveBeenCalled();
+ expect(runnerService.executeApiRun).not.toHaveBeenCalled();
+ });
+
+ it('rejects an absolute non-image path with 400', async () => {
+ const { app, runnerService } = makeApp(runData({ providerType: 'api', defaultModel: 'd' }));
+ const res = await request(app)
+ .post('/api/runs')
+ .send({ providerId: 'p1', prompt: 'hi', screenshots: ['/etc/passwd'] });
+ expect(res.status).toBe(400);
+ expect(runnerService.createRun).not.toHaveBeenCalled();
+ });
+
+ it('rebases a legit absolute screenshots path to its basename and forwards it to the runner', async () => {
+ const { app, runnerService } = makeApp(runData({ providerType: 'api', defaultModel: 'd' }));
+ const res = await request(app)
+ .post('/api/runs')
+ .send({ providerId: 'p1', prompt: 'hi', screenshots: ['/home/u/portos/data/screenshots/grab.png'] });
+ expect(res.status).toBe(202);
+ // Both createRun and executeApiRun receive the sanitized basename, never
+ // the caller-supplied absolute path.
+ expect(runnerService.createRun.mock.calls[0][0].screenshots).toEqual(['grab.png']);
+ expect(runnerService.executeApiRun.mock.calls[0][0].screenshots).toEqual(['grab.png']);
+ });
+ });
});
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index de51053089..f40ffcc0be 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -1,7 +1,7 @@
import { mkdir, readFile, readdir, rm } from 'fs/promises';
import { atomicWrite } from './internal/atomicWrite.js';
import { existsSync } from 'fs';
-import { join, extname, basename, resolve, sep } from 'path';
+import { join, extname, basename, isAbsolute } from 'path';
import { spawn } from 'child_process';
import { randomUUID } from 'crypto';
import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';
@@ -66,40 +66,22 @@ export function createRunnerService(config = {}) {
return mimeTypes[ext] || 'image/png';
}
- // Allow-list of image extensions a screenshot may carry. Mirrors getMimeType's
- // keys — a path with any other extension (or none) is rejected before we read
- // it off disk.
- const ALLOWED_SCREENSHOT_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']);
-
- // Resolve a caller-supplied screenshot reference to an absolute path that is
- // provably contained in screenshotsDir, or return null. `screenshots[]` on
- // POST /api/runs is unauthenticated user input, so without this guard a value
- // like `../../../../etc/passwd` (or an absolute path) would have any readable
- // file base64-encoded and forwarded to the configured external vision
- // provider — an arbitrary-file-read exfiltration. Mirrors the basename +
- // extension-allow-list + `resolve().startsWith(root)` containment semantics of
- // PortOS's resolveScreenshot (server/lib/fileUtils.js), reimplemented here
- // because the aiToolkit is self-contained and must not import out to PortOS.
- function resolveScreenshotPath(imagePath) {
- if (typeof imagePath !== 'string' || !imagePath) return null;
- // basename strips every directory component, so `../`-traversal and
- // absolute paths collapse to a bare filename before we touch disk.
- const safe = basename(imagePath);
- if (!safe || safe === '.' || safe === '..') return null;
- if (!ALLOWED_SCREENSHOT_EXTENSIONS.has(extname(safe).toLowerCase())) return null;
- const fullPath = resolve(join(screenshotsDir, safe));
- // Defense-in-depth: even after basename, confirm the resolved path stays
- // under the screenshots root before reading it.
- const rootPrefix = resolve(screenshotsDir) + sep;
- if (!fullPath.startsWith(rootPrefix)) return null;
- return fullPath;
- }
-
async function loadImageAsBase64(imagePath) {
- const fullPath = resolveScreenshotPath(imagePath);
- if (!fullPath) {
- throw new Error(`Invalid or disallowed screenshot path: ${imagePath}`);
+ if (typeof imagePath !== 'string' || !imagePath) {
+ throw new Error(`Invalid screenshot path: ${imagePath}`);
}
+ // Relative references are anchored under screenshotsDir with `basename`
+ // applied, so a `../`-traversal collapses to a bare filename and can't
+ // escape the screenshots dir. Absolute paths come only from trusted
+ // in-process callers (e.g. PortOS's Universe Builder, whose
+ // `resolveImageSources` has already validated them against an approved
+ // image root) and pass through unchanged. The untrusted POST /api/runs
+ // surface is additionally sanitized at the route boundary
+ // (sanitizeScreenshotRefs in routes/runs.js) so an attacker-supplied
+ // absolute path never reaches this loader. See issue #1870 / #1820.
+ const fullPath = isAbsolute(imagePath)
+ ? imagePath
+ : join(screenshotsDir, basename(imagePath));
if (!existsSync(fullPath)) {
throw new Error(`Image not found: ${fullPath}`);
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 3215c2c17a..736a4217f3 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, afterEach, vi } from 'vitest';
import { mkdtemp, rm, readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
+import { join, basename } from 'path';
import { tmpdir } from 'os';
import { createRunnerService } from './runner.js';
@@ -126,16 +126,16 @@ describe('AI Toolkit runner service', () => {
expect('num_ctx' in JSON.parse(fetch.mock.calls[0][1].body)).toBe(false);
});
- it('rejects traversal / absolute screenshot paths and only forwards in-dir images to the vision API', async () => {
+ it('anchors relative screenshot refs under screenshotsDir so `../` traversal cannot escape it', async () => {
const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
const screenshotsDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-shots-'));
const secretsDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-secret-'));
tempDirs.push(dataDir, screenshotsDir, secretsDir);
- // A legitimate in-dir screenshot, plus a file outside the screenshots root
- // a traversal/absolute path would try to exfiltrate.
+ // A legitimate in-dir screenshot, plus a secret sitting one level up that a
+ // relative `../`-traversal would try to read off disk.
await writeFile(join(screenshotsDir, 'valid.png'), 'PNGDATA');
- await writeFile(join(secretsDir, 'passwd'), 'root:x:0:0');
+ await writeFile(join(secretsDir, 'secret.png'), 'TOPSECRET');
const fetch = stubStreamingFetch();
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -154,12 +154,10 @@ describe('AI Toolkit runner service', () => {
model: null,
prompt: 'describe these',
workspacePath: process.cwd(),
- screenshots: [
- 'valid.png',
- '../../../../etc/passwd',
- join(secretsDir, 'passwd'), // absolute path outside the screenshots root
- 'notes.txt' // disallowed extension, even though basename is in-dir
- ],
+ // The loader applies basename() to relative refs, so this `../`-traversal
+ // collapses to `secret.png` under screenshotsDir (absent there) instead of
+ // reading the real sibling file it points at.
+ screenshots: ['valid.png', `../${basename(secretsDir)}/secret.png`],
onData: undefined,
onComplete: () => done()
});
@@ -168,12 +166,13 @@ describe('AI Toolkit runner service', () => {
expect(fetch).toHaveBeenCalledTimes(1);
const sentContent = JSON.parse(fetch.mock.calls[0][1].body).messages[0].content;
const imageParts = sentContent.filter((p) => p.type === 'image_url');
- // Only the valid in-dir screenshot is forwarded; the traversal, absolute,
- // and disallowed-extension entries are skipped.
+ // Only the valid in-dir screenshot is forwarded; the traversal entry
+ // collapses to a basename that isn't present in screenshotsDir and is
+ // skipped.
expect(imageParts).toHaveLength(1);
expect(imageParts[0].image_url.url.startsWith('data:image/png;base64,')).toBe(true);
// The secret file's contents are never base64-encoded into the payload.
- const secretB64 = Buffer.from('root:x:0:0').toString('base64');
+ const secretB64 = Buffer.from('TOPSECRET').toString('base64');
expect(JSON.stringify(sentContent)).not.toContain(secretB64);
errSpy.mockRestore();
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index f3cfb9a1bd..d447598e99 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -1,4 +1,48 @@
import { z } from 'zod';
+import { basename, extname } from 'path';
+
+// Image extensions a vision screenshot may carry. Mirrors the runner's
+// getMimeType keys — anything else (or a no-extension path like `passwd`) is
+// rejected.
+const ALLOWED_SCREENSHOT_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']);
+
+/**
+ * Sanitize the untrusted `screenshots[]` array from POST /api/runs into safe,
+ * screenshots-dir-relative basenames. `screenshots[]` is unauthenticated user
+ * input passed to the vision loader, which base64-encodes each image and
+ * forwards it to the configured external provider — so without this an entry
+ * like `../../../../etc/passwd` or an absolute `/etc/passwd` would exfiltrate an
+ * arbitrary readable file (issue #1870, the sibling of the #1820 vision-test
+ * fix). `basename` collapses every directory component (neutralizing `../`
+ * traversal AND absolute-path escapes, including the legitimate absolute paths
+ * the RunnerPage uploads under data/screenshots) and the extension allow-list
+ * rejects non-image references before any file is read. Lives here (not the
+ * shared loadImageAsBase64) so trusted in-process callers that pass validated
+ * absolute paths from other image roots — e.g. Universe Builder gallery images
+ * under data/images — keep working; only the HTTP boundary is constrained.
+ *
+ * @param {unknown} screenshots
+ * @returns {{ safe: string[], rejected: string[] }}
+ */
+export function sanitizeScreenshotRefs(screenshots) {
+ const safe = [];
+ const rejected = [];
+ if (!Array.isArray(screenshots)) return { safe, rejected };
+ for (const entry of screenshots) {
+ if (typeof entry !== 'string' || !entry) {
+ rejected.push(String(entry));
+ continue;
+ }
+ const name = basename(entry);
+ if (!name || name === '.' || name === '..' ||
+ !ALLOWED_SCREENSHOT_EXTENSIONS.has(extname(name).toLowerCase())) {
+ rejected.push(entry);
+ continue;
+ }
+ safe.push(name);
+ }
+ return { safe, rejected };
+}
export const providerSchema = z.object({
// Sample providers post a stable id (e.g. 'codex') so the server can adopt
diff --git a/server/lib/aiToolkit/validation.test.js b/server/lib/aiToolkit/validation.test.js
new file mode 100644
index 0000000000..c9c8a259bd
--- /dev/null
+++ b/server/lib/aiToolkit/validation.test.js
@@ -0,0 +1,65 @@
+import { describe, it, expect } from 'vitest';
+import { sanitizeScreenshotRefs } from './validation.js';
+
+describe('sanitizeScreenshotRefs — POST /api/runs screenshot hardening (#1870)', () => {
+ it('keeps an in-dir image basename unchanged', () => {
+ expect(sanitizeScreenshotRefs(['shot.png'])).toEqual({ safe: ['shot.png'], rejected: [] });
+ });
+
+ it('neutralizes the legit absolute path the RunnerPage uploads under data/screenshots to its basename', () => {
+ // /api/screenshots returns an absolute `path`; the RunnerPage forwards it
+ // verbatim — basename rebases it to a screenshots-dir-relative ref.
+ expect(sanitizeScreenshotRefs(['/home/user/portos/data/screenshots/grab.png']))
+ .toEqual({ safe: ['grab.png'], rejected: [] });
+ });
+
+ it('rejects `../` traversal that escapes to a non-image file', () => {
+ const { safe, rejected } = sanitizeScreenshotRefs(['../../../../etc/passwd']);
+ expect(safe).toEqual([]);
+ expect(rejected).toEqual(['../../../../etc/passwd']);
+ });
+
+ it('rejects an absolute path to a non-image file outside the screenshots dir', () => {
+ const { safe, rejected } = sanitizeScreenshotRefs(['/etc/passwd']);
+ expect(safe).toEqual([]);
+ expect(rejected).toEqual(['/etc/passwd']);
+ });
+
+ it('collapses a traversal path that happens to end in an image extension to a harmless in-dir basename', () => {
+ // basename neutralizes the escape; the result is a screenshots-dir ref that
+ // simply won't exist (the loader then skips it) — never an arbitrary read.
+ expect(sanitizeScreenshotRefs(['../../secret/evil.png'])).toEqual({ safe: ['evil.png'], rejected: [] });
+ });
+
+ it('rejects disallowed extensions and dotfiles with no extension', () => {
+ expect(sanitizeScreenshotRefs(['notes.txt', '.env']))
+ .toEqual({ safe: [], rejected: ['notes.txt', '.env'] });
+ });
+
+ it('is case-insensitive on the extension allow-list', () => {
+ expect(sanitizeScreenshotRefs(['Shot.PNG', 'pic.JPEG']))
+ .toEqual({ safe: ['Shot.PNG', 'pic.JPEG'], rejected: [] });
+ });
+
+ it('partitions a mixed list into safe + rejected', () => {
+ const { safe, rejected } = sanitizeScreenshotRefs([
+ 'a.png',
+ '../../../../etc/passwd',
+ 'b.webp',
+ 'readme.md',
+ ]);
+ expect(safe).toEqual(['a.png', 'b.webp']);
+ expect(rejected).toEqual(['../../../../etc/passwd', 'readme.md']);
+ });
+
+ it('treats non-string and empty entries as rejected', () => {
+ const { safe, rejected } = sanitizeScreenshotRefs(['ok.png', '', 42, null]);
+ expect(safe).toEqual(['ok.png']);
+ expect(rejected).toEqual(['', '42', 'null']);
+ });
+
+ it('returns empty partitions for a non-array input', () => {
+ expect(sanitizeScreenshotRefs(undefined)).toEqual({ safe: [], rejected: [] });
+ expect(sanitizeScreenshotRefs('x.png')).toEqual({ safe: [], rejected: [] });
+ });
+});