Skip to content

Commit cc19b8c

Browse files
DeryFerdmiguel-heygenorphan4183
authored
fix(server): contain static file requests within their served roots (#4217)
* fix(server): contain static file requests within their served roots Static asset handlers joined the raw request path onto their root directory without checking where it landed. Hono decodes percent escapes while routing, so an encoded backslash (%5c) arrives as a real separator on Windows and dot segments arrive already collapsed — "/assets/..%5c..%5csecret" and "/%2e%2e%2fsecret" could read files above the studio bundle root (embedded Studio server) and above compiledDir/projectDir (engine render file server). Browsers never request those shapes, but anything that can reach the bound port can: raw local clients, LAN peers when the preview binds 0.0.0.0, and a shared-machine process hitting the render server. Both handlers now resolve the request path first and refuse anything that collapses outside its root, using the same lexical containment the preview asset route already applies — bundle/project assets behind symlinked directories keep being served, only dot-segment escapes are rejected. Route-level pathSafety tests pin the behavior in both packages, including the Windows backslash shape and the symlinked-asset cases from the descriptor-pinning regressions. Validated: new containment suites fail on the prior handlers (200 + marker file content served from outside the root) and pass with the guards; cli server (140), engine services (1024+, matching the main baseline incl. pre-existing browserManager failures), typecheck, oxlint, oxfmt and the full workspace build all clean. * fix: close fallow audit findings, prove containment cross-platform Fallow audit (health/complexity): createFileServer's request handler exceeded the CRAP-score threshold once the new containment checks were added. Extracted resolveContainedPaths, a small pure function that resolves and validates both roots, cutting the handler's own branching back down. Fallow audit (duplication): the new pathSafety test files copied their temp-root/studioDir setup and teardown from the existing staticAssets test wholesale. Extracted the shared parts into studioServerTestFixture.ts (makeStudioServerRoot, writeStudioIndexHtml, cleanupStudioServerRoot); only the per-file vi.mock("node:path", ...) call stays duplicated, since Vitest requires it declared statically in each test file and it cannot be moved behind a shared function -- that one block keeps a narrow, targeted ignore comment instead of a file-wide one. Security claim: isWithinProjectRoot's %5c-decoded-backslash escape is real, but only on Windows -- POSIX never treats a literal backslash as a separator, and Hono leaves %2f undecoded in c.req.path, so none of the new tests' encoded-traversal payloads produce an actual escape on Linux (verified empirically: they pass identically with the fix reverted). isWithinProjectRoot now takes an optional path-module override (defaulting to the host's native node:path, so every existing caller is unchanged) so its win32 and posix branches can be unit tested directly from one OS, the same pattern already used by producer/fileServer.ts's isPathInside. New tests cover a backslash traversal, a mixed backslash/forward-slash traversal, and a drive-letter path escaping the root under path.win32, plus the existing posix case -- confirmed each one fails when the check is removed. The HTTP-level tests stay as-is: real regression coverage for them comes from the windows-latest CI job, which runs both new pathSafety suites unfiltered. --------- Co-authored-by: Miguel Ángel <[email protected]> Co-authored-by: orphan4183 <[email protected]>
1 parent dd97478 commit cc19b8c

8 files changed

Lines changed: 292 additions & 22 deletions

File tree

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
import * as fs from "node:fs";
3+
import * as path from "node:path";
4+
import { createStudioServer } from "./studioServer.js";
5+
import {
6+
cleanupStudioServerRoot,
7+
makeStudioServerRoot,
8+
writeStudioIndexHtml,
9+
} from "./studioServerTestFixture.js";
10+
11+
/**
12+
* The static SPA handlers resolve the raw request path against the bundle
13+
* directory. Hono decodes percent escapes when routing, so an encoded
14+
* separator or dot segment in the request must never walk out of the bundle
15+
* root — browsers would not send those shapes, but anything that can reach
16+
* the bound port can. These tests pin containment at the handler.
17+
*/
18+
19+
const hooks = vi.hoisted(() => ({ studioDir: "" }));
20+
21+
// The bundle directory is resolved from __dirname at server construction, so
22+
// point that one `resolve(<...>/server, "studio")` call at a temp tree.
23+
// fallow-ignore-next-line code-duplication
24+
vi.mock("node:path", async (importOriginal) => {
25+
const actual = await importOriginal<typeof path>();
26+
return {
27+
...actual,
28+
resolve: (...parts: string[]) =>
29+
hooks.studioDir && parts.length === 2 && parts[0]?.endsWith("server") && parts[1] === "studio"
30+
? hooks.studioDir
31+
: actual.resolve(...parts),
32+
};
33+
});
34+
35+
let root: string;
36+
let server: Awaited<ReturnType<typeof createStudioServer>>;
37+
38+
beforeEach(async () => {
39+
const fixture = makeStudioServerRoot("hf-studio-containment-");
40+
root = fixture.root;
41+
hooks.studioDir = fixture.studioDir;
42+
fs.writeFileSync(path.join(root, "studio-marker.txt"), "STUDIO-MARKER");
43+
writeStudioIndexHtml(hooks.studioDir);
44+
server = await createStudioServer({ projectDir: fixture.projectDir });
45+
});
46+
47+
afterEach(() => {
48+
cleanupStudioServerRoot(server, root, () => (hooks.studioDir = ""));
49+
});
50+
51+
describe("static file path containment", () => {
52+
// A percent-encoded backslash decodes to a real separator on Windows, so
53+
// two encoded hops walk from the bundle root to the temp root above it.
54+
it.each(["/assets/..%5c..%5cstudio-marker.txt", "/icons/..%5c..%5cstudio-marker.txt"])(
55+
"rejects encoded traversal %s",
56+
async (requestPath) => {
57+
const response = await server.app.request(requestPath);
58+
expect(response.status).toBe(404);
59+
expect(await response.text()).not.toContain("STUDIO-MARKER");
60+
},
61+
);
62+
63+
it("still serves the SPA shell and bundle assets", async () => {
64+
const shell = await server.app.request("/");
65+
expect(shell.status).toBe(200);
66+
expect(await shell.text()).toContain("Studio");
67+
68+
fs.writeFileSync(path.join(hooks.studioDir, "assets", "app.js"), "export {};");
69+
const asset = await server.app.request("/assets/app.js");
70+
expect(asset.status).toBe(200);
71+
expect(await asset.text()).toContain("export {};");
72+
});
73+
});

‎packages/cli/src/server/studioServer.staticAssets.test.ts‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
22
import * as fs from "node:fs";
33
import * as path from "node:path";
4-
import { tmpdir } from "node:os";
54
import { createStudioServer, type StudioServer } from "./studioServer.js";
5+
import {
6+
cleanupStudioServerRoot,
7+
makeStudioServerRoot,
8+
writeStudioIndexHtml,
9+
} from "./studioServerTestFixture.js";
610

711
/**
812
* Cache policy for the studio bundle, decided by ROUTE. Vite emits only
@@ -15,6 +19,7 @@ const hooks = vi.hoisted(() => ({ studioDir: "" }));
1519

1620
// The bundle directory is resolved from __dirname at server construction, so
1721
// point that one `resolve(<...>/server, "studio")` call at a temp tree.
22+
// fallow-ignore-next-line code-duplication
1823
vi.mock("node:path", async (importOriginal) => {
1924
const actual = await importOriginal<typeof path>();
2025
return {
@@ -38,26 +43,19 @@ let root: string;
3843
let server: StudioServer;
3944

4045
beforeEach(() => {
41-
root = fs.mkdtempSync(path.join(tmpdir(), "hf-studio-assets-"));
42-
hooks.studioDir = path.join(root, "studio");
43-
const projectDir = path.join(root, "project");
44-
fs.mkdirSync(projectDir);
45-
fs.mkdirSync(path.join(hooks.studioDir, "assets"), { recursive: true });
46+
const fixture = makeStudioServerRoot("hf-studio-assets-");
47+
root = fixture.root;
48+
hooks.studioDir = fixture.studioDir;
4649
fs.mkdirSync(path.join(hooks.studioDir, "icons"), { recursive: true });
4750
fs.writeFileSync(path.join(hooks.studioDir, "assets", HASHED_BUNDLE), BUNDLE_BYTES);
4851
fs.writeFileSync(path.join(hooks.studioDir, "icons", PUBLIC_ICON), "<svg/>");
4952
fs.writeFileSync(path.join(hooks.studioDir, "favicon.svg"), "<svg/>");
50-
fs.writeFileSync(
51-
path.join(hooks.studioDir, "index.html"),
52-
"<html><head></head><body>Studio</body></html>",
53-
);
54-
server = createStudioServer({ projectDir });
53+
writeStudioIndexHtml(hooks.studioDir);
54+
server = createStudioServer({ projectDir: fixture.projectDir });
5555
});
5656

5757
afterEach(() => {
58-
server.watcher.close();
59-
fs.rmSync(root, { recursive: true, force: true });
60-
hooks.studioDir = "";
58+
cleanupStudioServerRoot(server, root, () => (hooks.studioDir = ""));
6159
});
6260

6361
describe("studio bundle cache policy", () => {

‎packages/cli/src/server/studioServer.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { resolveAutoProxy } from "../utils/projectConfig.js";
4949
import { getElementScreenshotClip } from "@hyperframes/studio-server/screenshot-clip";
5050
import type { ScreenshotClip } from "@hyperframes/studio-server/screenshot-clip";
5151
import type { RenderJob } from "@hyperframes/producer";
52+
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
5253
import { seekCompositionTimeline } from "../capture/captureCompositionFrame.js";
5354
import {
5455
assertWebGpuAdapterAvailable,
@@ -893,6 +894,12 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
893894
// Studio SPA static files
894895
const serveStudioStaticFile = (cacheControl: string) => (c: Context) => {
895896
const filePath = resolve(studioDir, c.req.path.slice(1));
897+
// Percent escapes can decode into separators and dot segments before this
898+
// resolve, so a hostile request can name files above the bundle
899+
// directory. Containment stays lexical on purpose: bundle assets may sit
900+
// behind symlinked directories (same tradeoff as the preview asset
901+
// route), but dot segments must never collapse outside the bundle root.
902+
if (!isWithinProjectRoot(studioDir, filePath)) return c.text("not found", 404);
896903
const content = readBundleFile(filePath);
897904
if (content === null) return c.text("not found", 404);
898905
return new Response(content, {
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import * as fs from "node:fs";
2+
import * as path from "node:path";
3+
import { tmpdir } from "node:os";
4+
5+
/**
6+
* Temp root plus empty `studio/assets` and `project` dirs, shared by every
7+
* studioServer static-file test; each caller writes its own fixture files
8+
* into the returned `studioDir` before constructing the server.
9+
*/
10+
export function makeStudioServerRoot(prefix: string): {
11+
root: string;
12+
studioDir: string;
13+
projectDir: string;
14+
} {
15+
const root = fs.mkdtempSync(path.join(tmpdir(), prefix));
16+
const studioDir = path.join(root, "studio");
17+
const projectDir = path.join(root, "project");
18+
fs.mkdirSync(projectDir);
19+
fs.mkdirSync(path.join(studioDir, "assets"), { recursive: true });
20+
return { root, studioDir, projectDir };
21+
}
22+
23+
/** The one SPA shell every studioServer static-file test needs, unchanged. */
24+
export function writeStudioIndexHtml(studioDir: string): void {
25+
fs.writeFileSync(
26+
path.join(studioDir, "index.html"),
27+
"<html><head></head><body>Studio</body></html>",
28+
);
29+
}
30+
31+
/** Pairs with makeStudioServerRoot; `onDone` resets caller-local state (e.g. the `hooks.studioDir` mock target). */
32+
export function cleanupStudioServerRoot(
33+
server: { watcher: { close(): void } },
34+
root: string,
35+
onDone?: () => void,
36+
): void {
37+
server.watcher.close();
38+
fs.rmSync(root, { recursive: true, force: true });
39+
onDone?.();
40+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
2+
import * as fs from "node:fs";
3+
import * as path from "node:path";
4+
import { tmpdir } from "node:os";
5+
import { createFileServer, type FileServerHandle } from "./fileServer.js";
6+
7+
/**
8+
* The server derives each request path from the URL and joins it onto
9+
* compiledDir/projectDir. Hono decodes percent escapes when routing, so an
10+
* encoded separator or dot segment in the request must never walk out of the
11+
* served roots — Chrome never requests those shapes, but anything that can
12+
* reach the port (LAN bind, other local processes) can. On Windows an encoded
13+
* backslash (%5c) decodes to a real separator, so `..%5c..%5c` escapes even
14+
* though `..%2f` is normalized away by join(). These tests pin containment
15+
* at the handler.
16+
*/
17+
describe("fileServer path containment", () => {
18+
let root: string;
19+
let projectDir: string;
20+
let outsideFile: string;
21+
let server: FileServerHandle;
22+
23+
beforeEach(async () => {
24+
root = fs.mkdtempSync(path.join(tmpdir(), "hf-fileserver-containment-"));
25+
projectDir = path.join(root, "project");
26+
fs.mkdirSync(projectDir);
27+
fs.writeFileSync(path.join(projectDir, "index.html"), "<html></html>");
28+
outsideFile = path.join(root, "outside-secret.txt");
29+
fs.writeFileSync(outsideFile, "OUTSIDE");
30+
server = await createFileServer({
31+
headScripts: [],
32+
bodyScripts: [],
33+
projectDir,
34+
});
35+
});
36+
37+
afterEach(async () => {
38+
await server.close();
39+
fs.rmSync(root, { recursive: true, force: true });
40+
});
41+
42+
const escapeAttempts = [
43+
// Encoded separators: %2f collapses with a leading dot-segment only via a
44+
// nested hop, %5c is a live separator on Windows.
45+
"/..%2foutside-secret.txt",
46+
"/%2e%2e%2foutside-secret.txt",
47+
"/nested%2f..%2f..%2foutside-secret.txt",
48+
"/..%5coutside-secret.txt",
49+
"/..%5c..%5coutside-secret.txt",
50+
];
51+
52+
it.each(escapeAttempts)("rejects encoded traversal %s", async (requestPath) => {
53+
const response = await fetch(`${server.url}${requestPath}`);
54+
expect(response.status).toBe(404);
55+
expect(await response.text()).not.toContain("OUTSIDE");
56+
});
57+
58+
it("still serves files inside the project", async () => {
59+
const response = await fetch(`${server.url}/index.html`);
60+
expect(response.status).toBe(200);
61+
expect(await response.text()).toContain("<html>");
62+
});
63+
});

‎packages/engine/src/services/fileServer.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { serve } from "@hono/node-server";
1111
import { readFileSync, openSync, fstatSync, closeSync, statSync, constants } from "node:fs";
1212
import { join, extname } from "node:path";
1313
import { injectScriptsIntoHtml } from "@hyperframes/core/compiler";
14+
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
1415

1516
const MIME_TYPES: Record<string, string> = {
1617
".html": "text/html; charset=utf-8",
@@ -84,6 +85,24 @@ function readRegularFile(filePath: string): Buffer<ArrayBuffer> | null {
8485
}
8586
}
8687

88+
/**
89+
* Resolves the request path against both roots and rejects the pair the
90+
* moment either escapes -- lexically, so a symlinked asset directory still
91+
* resolves (see the containment note at the call site).
92+
*/
93+
function resolveContainedPaths(
94+
projectDir: string,
95+
compiledDir: string | undefined,
96+
relativePath: string,
97+
): { projectPath: string; compiledPath: string | null } | null {
98+
const projectPath = join(projectDir, relativePath);
99+
if (!isWithinProjectRoot(projectDir, projectPath)) return null;
100+
if (!compiledDir) return { projectPath, compiledPath: null };
101+
const compiledPath = join(compiledDir, relativePath);
102+
if (!isWithinProjectRoot(compiledDir, compiledPath)) return null;
103+
return { projectPath, compiledPath };
104+
}
105+
87106
export function createFileServer(options: FileServerOptions): Promise<FileServerHandle> {
88107
const { projectDir, compiledDir, port = 0, stripEmbeddedRuntime = true } = options;
89108

@@ -98,10 +117,14 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer
98117

99118
// Remove leading slash
100119
const relativePath = requestPath.replace(/^\//, "");
101-
const compiledPath = compiledDir ? join(compiledDir, relativePath) : null;
120+
// Percent escapes can decode into separators and dot segments before the
121+
// join, so a hostile request can name files above either root -- see
122+
// resolveContainedPaths for why the check stays lexical, not realpath.
123+
const resolved = resolveContainedPaths(projectDir, compiledDir, relativePath);
124+
if (!resolved) return c.text("Not found", 404);
102125
const content =
103-
(compiledPath ? readRegularFile(compiledPath) : null) ??
104-
readRegularFile(join(projectDir, relativePath));
126+
(resolved.compiledPath ? readRegularFile(resolved.compiledPath) : null) ??
127+
readRegularFile(resolved.projectPath);
105128
if (content === null) return c.text("Not found", 404);
106129

107130
const ext = extname(relativePath).toLowerCase();

‎packages/parsers/src/assetResolution.test.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { afterAll, beforeAll, describe, expect, it } from "vitest";
22
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
4-
import { join } from "node:path";
4+
import { join, posix, win32 } from "node:path";
55
import {
66
collectSubCompositionSrcs,
77
isUnresolvedAssetPlaceholder,
8+
isWithinProjectRoot,
89
maskNonScannableRanges,
910
resolveProjectRelativeSrc,
1011
} from "./assetResolution.js";
@@ -219,3 +220,48 @@ describe("resolveProjectRelativeSrc — the one src resolver for lint and render
219220
}
220221
});
221222
});
223+
224+
// A CI runner is one OS. Injecting path.win32/path.posix exercises both
225+
// platforms' separator and drive-letter rules from here, so a regression in
226+
// either fails this suite regardless of which OS actually runs it.
227+
describe("isWithinProjectRoot", () => {
228+
it("rejects a backslash traversal under path.win32", () => {
229+
const root = "C:\\project";
230+
const candidate = win32.join(root, "..\\secret.txt");
231+
expect(isWithinProjectRoot(root, candidate, win32)).toBe(false);
232+
});
233+
234+
it("rejects a mixed backslash/forward-slash traversal under path.win32", () => {
235+
const root = "C:\\project";
236+
const candidate = win32.join(root, "..\\../secret.txt");
237+
expect(isWithinProjectRoot(root, candidate, win32)).toBe(false);
238+
});
239+
240+
it("rejects a drive-letter path outside the root under path.win32", () => {
241+
const root = "C:\\project";
242+
const candidate = "D:\\secret.txt";
243+
expect(isWithinProjectRoot(root, candidate, win32)).toBe(false);
244+
});
245+
246+
it("allows a nested asset under path.win32", () => {
247+
const root = "C:\\project";
248+
const candidate = win32.join(root, "assets\\a.png");
249+
expect(isWithinProjectRoot(root, candidate, win32)).toBe(true);
250+
});
251+
252+
it("rejects a forward-slash traversal under path.posix", () => {
253+
const root = "/project";
254+
const candidate = posix.join(root, "../secret.txt");
255+
expect(isWithinProjectRoot(root, candidate, posix)).toBe(false);
256+
});
257+
258+
it("allows a nested asset under path.posix", () => {
259+
const root = "/project";
260+
const candidate = posix.join(root, "assets/a.png");
261+
expect(isWithinProjectRoot(root, candidate, posix)).toBe(true);
262+
});
263+
264+
it("allows the root itself", () => {
265+
expect(isWithinProjectRoot("/project", "/project", posix)).toBe(true);
266+
});
267+
});

0 commit comments

Comments
 (0)