Skip to content

Commit 723cd0d

Browse files
authored
fix(studio-server): block dangling symlink upload escapes (#3661)
* fix(studio-server): block dangling symlink upload escapes * fix(studio-server): contain rename reference updates
1 parent 7b77246 commit 723cd0d

3 files changed

Lines changed: 226 additions & 1 deletion

File tree

‎packages/core/src/safePath.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
import { resolve, sep, join, dirname, basename } from "node:path";
2-
import { realpathSync } from "node:fs";
2+
import { lstatSync, realpathSync } from "node:fs";
3+
4+
// realpath also fails for dangling/cyclic symlinks. Existing entries must not
5+
// become missing segments: writes could follow them outside the project.
6+
function isMissingPath(path: string): boolean {
7+
try {
8+
lstatSync(path);
9+
return false;
10+
} catch (error) {
11+
return Boolean(
12+
error &&
13+
typeof error === "object" &&
14+
"code" in error &&
15+
(error.code === "ENOENT" || error.code === "ENOTDIR"),
16+
);
17+
}
18+
}
319

420
/**
521
* Reject paths that escape the `base` directory — including via symlinks.
@@ -41,6 +57,7 @@ export function isSafePath(base: string, resolved: string): boolean {
4157
try {
4258
ancestorReal = realpathSync(probe);
4359
} catch {
60+
if (!isMissingPath(probe)) return false;
4461
const parent = dirname(probe);
4562
if (parent === probe) return false; // walked past the filesystem root
4663
trailing.push(basename(probe));
Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
import { afterEach, describe, expect, it, type TestContext } from "vitest";
2+
import { Hono } from "hono";
3+
import {
4+
existsSync,
5+
mkdirSync,
6+
mkdtempSync,
7+
readFileSync,
8+
rmSync,
9+
symlinkSync,
10+
writeFileSync,
11+
} from "node:fs";
12+
import { tmpdir } from "node:os";
13+
import { join, relative } from "node:path";
14+
import { registerFileRoutes } from "./files";
15+
import { fileContentVersion } from "../helpers/fileVersion";
16+
import type { StudioApiAdapter } from "../types";
17+
18+
const tempDirs: string[] = [];
19+
afterEach(() => {
20+
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
21+
});
22+
23+
function fixture() {
24+
const root = mkdtempSync(join(tmpdir(), "hf-file-containment-"));
25+
tempDirs.push(root);
26+
const project = join(root, "project");
27+
const outside = join(root, "outside");
28+
mkdirSync(project);
29+
mkdirSync(outside);
30+
writeFileSync(join(project, "inside.txt"), "inside");
31+
writeFileSync(join(outside, "secret.txt"), "outside secret");
32+
const adapter: StudioApiAdapter = {
33+
listProjects: () => [],
34+
resolveProject: async (id) => ({ id, dir: project }),
35+
bundle: async () => null,
36+
lint: async () => ({ findings: [] }),
37+
runtimeUrl: "/api/runtime.js",
38+
rendersDir: () => join(root, "renders"),
39+
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "out.mp4" }),
40+
};
41+
const app = new Hono();
42+
registerFileRoutes(app, adapter);
43+
return { app, project, outside };
44+
}
45+
46+
function linkOrSkip(context: TestContext, target: string, link: string, type: "file" | "dir") {
47+
try {
48+
symlinkSync(target, link, type);
49+
} catch (error) {
50+
if (
51+
process.platform === "win32" &&
52+
error &&
53+
typeof error === "object" &&
54+
"code" in error &&
55+
["EPERM", "EACCES", "ENOSYS"].includes(String(error.code))
56+
) {
57+
context.skip("Windows runner does not permit creating symbolic links");
58+
}
59+
throw error;
60+
}
61+
}
62+
63+
const fileUrl = (path: string) =>
64+
`http://localhost/projects/demo/files/${encodeURIComponent(path)}`;
65+
function upload(app: Hono, dir = "", filename = "upload.txt") {
66+
const form = new FormData();
67+
form.append("files", new File(["upload bytes"], filename));
68+
return app.request(`http://localhost/projects/demo/upload?dir=${encodeURIComponent(dir)}`, {
69+
method: "POST",
70+
body: form,
71+
});
72+
}
73+
74+
describe("file route containment", () => {
75+
it.each(["GET", "PUT", "POST", "DELETE"])(
76+
"rejects encoded traversal through %s without changing outside bytes",
77+
async (method) => {
78+
const { app, project, outside } = fixture();
79+
const target = join(outside, "secret.txt");
80+
const response = await app.request(fileUrl(relative(project, target)), {
81+
method,
82+
headers: { "If-Match": fileContentVersion("outside secret") },
83+
...(method === "PUT" || method === "POST" ? { body: "overwrite" } : {}),
84+
});
85+
expect(response.status).toBe(403);
86+
expect(await response.text()).not.toContain("outside secret");
87+
expect(readFileSync(target, "utf8")).toBe("outside secret");
88+
},
89+
);
90+
91+
it("rejects NUL bytes in read, rename, and duplicate inputs", async () => {
92+
const { app, project } = fixture();
93+
expect((await app.request(fileUrl("inside.txt\0"))).status).toBe(403);
94+
const rename = await app.request(fileUrl("inside.txt"), {
95+
method: "PATCH",
96+
headers: { "Content-Type": "application/json" },
97+
body: JSON.stringify({ newPath: "bad\0.txt" }),
98+
});
99+
const duplicate = await app.request("http://localhost/projects/demo/duplicate-file", {
100+
method: "POST",
101+
headers: { "Content-Type": "application/json" },
102+
body: JSON.stringify({ path: "inside.txt\0" }),
103+
});
104+
expect(rename.status).toBe(400);
105+
expect(duplicate.status).toBe(400);
106+
expect(readFileSync(join(project, "inside.txt"), "utf8")).toBe("inside");
107+
});
108+
109+
it("rejects escaping rename destinations and duplicate sources", async () => {
110+
const { app, project, outside } = fixture();
111+
const rename = await app.request(fileUrl("inside.txt"), {
112+
method: "PATCH",
113+
headers: { "Content-Type": "application/json" },
114+
body: JSON.stringify({ newPath: relative(project, join(outside, "moved.txt")) }),
115+
});
116+
const duplicate = await app.request("http://localhost/projects/demo/duplicate-file", {
117+
method: "POST",
118+
headers: { "Content-Type": "application/json" },
119+
body: JSON.stringify({ path: relative(project, join(outside, "secret.txt")) }),
120+
});
121+
expect(rename.status).toBe(403);
122+
expect(duplicate.status).toBe(404);
123+
expect(existsSync(join(outside, "moved.txt"))).toBe(false);
124+
expect(readFileSync(join(project, "inside.txt"), "utf8")).toBe("inside");
125+
expect(readFileSync(join(outside, "secret.txt"), "utf8")).toBe("outside secret");
126+
});
127+
128+
it("blocks reads and uploads through a symlink to an outside directory", async (context) => {
129+
const { app, project, outside } = fixture();
130+
linkOrSkip(context, outside, join(project, "alias"), "dir");
131+
const read = await app.request(fileUrl("alias/secret.txt"));
132+
expect(read.status).toBe(403);
133+
expect(await read.text()).not.toContain("outside secret");
134+
expect((await upload(app, "alias/new")).status).toBe(403);
135+
expect(existsSync(join(outside, "new"))).toBe(false);
136+
});
137+
138+
it("updates internal rename references without following an external file symlink", async (context) => {
139+
const { app, project, outside } = fixture();
140+
const external = join(outside, "victim.html");
141+
const internal = join(project, "index.html");
142+
writeFileSync(external, "reference: inside.txt");
143+
writeFileSync(internal, "reference: inside.txt");
144+
linkOrSkip(context, external, join(project, "external.html"), "file");
145+
146+
const response = await app.request(fileUrl("inside.txt"), {
147+
method: "PATCH",
148+
headers: { "Content-Type": "application/json" },
149+
body: JSON.stringify({ newPath: "moved.txt" }),
150+
});
151+
152+
expect(response.status).toBe(200);
153+
expect(readFileSync(external, "utf8")).toBe("reference: inside.txt");
154+
expect(readFileSync(internal, "utf8")).toBe("reference: moved.txt");
155+
expect(readFileSync(join(project, "moved.txt"), "utf8")).toBe("inside");
156+
expect(existsSync(join(project, "inside.txt"))).toBe(false);
157+
expect((await response.json()).updatedReferences).toBe(1);
158+
});
159+
160+
it("blocks upload directory traversal and skips unsafe filenames", async () => {
161+
const { app, project, outside } = fixture();
162+
expect((await upload(app, relative(project, outside))).status).toBe(403);
163+
const unsafe = await upload(app, "", "..unsafe.txt");
164+
expect(unsafe.status).toBe(201);
165+
expect((await unsafe.json()).files).toEqual([]);
166+
expect(existsSync(join(outside, "upload.txt"))).toBe(false);
167+
expect(existsSync(join(project, "..unsafe.txt"))).toBe(false);
168+
});
169+
170+
it.each([false, true])(
171+
"does not follow a dangling upload symlink (renamed: %s)",
172+
async (collision, context) => {
173+
const { app, project, outside } = fixture();
174+
const external = join(outside, "new.txt");
175+
if (collision) writeFileSync(join(project, "upload.txt"), "existing upload");
176+
const filename = collision ? "upload (2).txt" : "upload.txt";
177+
linkOrSkip(context, external, join(project, filename), "file");
178+
const response = await upload(app);
179+
expect(response.status).toBe(201);
180+
expect((await response.json()).files).toEqual([]);
181+
expect(existsSync(external)).toBe(false);
182+
},
183+
);
184+
185+
it("allows nested file creation, uploads, and internal directory symlinks", async (context) => {
186+
const { app, project } = fixture();
187+
const created = await app.request(fileUrl("nested/inside.txt"), {
188+
method: "PUT",
189+
headers: { "If-None-Match": "*" },
190+
body: "nested bytes",
191+
});
192+
expect(created.status).toBe(200);
193+
expect((await (await app.request(fileUrl("nested/inside.txt"))).json()).content).toBe(
194+
"nested bytes",
195+
);
196+
expect((await upload(app, "nested")).status).toBe(201);
197+
expect(readFileSync(join(project, "nested/upload.txt"), "utf8")).toBe("upload bytes");
198+
linkOrSkip(context, join(project, "nested"), join(project, "alias"), "dir");
199+
expect((await (await app.request(fileUrl("alias/inside.txt"))).json()).content).toBe(
200+
"nested bytes",
201+
);
202+
});
203+
});

‎packages/studio-server/src/routes/files.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,7 @@ function updateReferences(projectDir: string, oldPath: string, newPath: string):
584584

585585
let updatedCount = 0;
586586
for (const file of textFiles) {
587+
if (!isSafePath(projectDir, file)) continue;
587588
const content = readFileSync(file, "utf-8");
588589

589590
// Only replace full relative paths — never bare filenames, which can
@@ -2219,6 +2220,10 @@ async function processUploadedFiles(
22192220
finalPath = resolve(targetDir, finalName);
22202221
}
22212222

2223+
// The collision suffix chooses a different path; validate that destination
2224+
// too, including dangling symlinks that existsSync treats as absent.
2225+
if (!isSafePath(projectDir, finalPath)) continue;
2226+
22222227
const buffer = Buffer.from(await value.arrayBuffer());
22232228
const validation = validateUploadedMediaBuffer(finalName, buffer);
22242229
if (!validation.ok) {

0 commit comments

Comments
 (0)