Skip to content

Commit 91a34ff

Browse files
authored
fix(studio): claim upload filenames exclusively (#3786)
* fix(studio): claim upload filenames exclusively * fix(studio): write uploads through exclusive descriptors
1 parent a7bf0d2 commit 91a34ff

2 files changed

Lines changed: 94 additions & 8 deletions

File tree

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

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { afterEach, describe, expect, it, type TestContext } from "vitest";
1+
import { afterEach, describe, expect, it, vi, type TestContext } from "vitest";
22
import { Hono } from "hono";
33
import {
44
existsSync,
@@ -17,6 +17,7 @@ import type { StudioApiAdapter } from "../types";
1717

1818
const tempDirs: string[] = [];
1919
afterEach(() => {
20+
vi.restoreAllMocks();
2021
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
2122
});
2223

@@ -201,3 +202,61 @@ describe("file route containment", () => {
201202
);
202203
});
203204
});
205+
206+
describe("upload collision races", () => {
207+
function raceDuringRead(filename: string, collide: () => void) {
208+
const file = new File(["new upload"], filename);
209+
const read = file.arrayBuffer.bind(file);
210+
vi.spyOn(file, "arrayBuffer").mockImplementation(async () => {
211+
collide();
212+
return read();
213+
});
214+
const form = new FormData();
215+
form.append("files", file);
216+
vi.spyOn(Request.prototype, "formData").mockResolvedValue(form);
217+
}
218+
219+
it("preserves an upload that appears while the body is read", async () => {
220+
const { app, project } = fixture();
221+
raceDuringRead("upload.txt", () => writeFileSync(join(project, "upload.txt"), "other upload"));
222+
const response = await upload(app);
223+
expect(response.status).toBe(201);
224+
expect(await response.json()).toMatchObject({ files: ["upload (2).txt"] });
225+
expect(readFileSync(join(project, "upload.txt"), "utf8")).toBe("other upload");
226+
expect(readFileSync(join(project, "upload (2).txt"), "utf8")).toBe("new upload");
227+
});
228+
229+
it.each([".gitignore", "archive.tar.txt"])(
230+
"retries suffix races without changing extension rules: %s",
231+
async (name) => {
232+
const { app, project } = fixture();
233+
const dot = name.indexOf(".", name.startsWith(".") ? 1 : 0);
234+
const base = dot > 0 ? name.slice(0, dot) : name;
235+
const ext = dot > 0 ? name.slice(dot) : "";
236+
writeFileSync(join(project, name), "original");
237+
raceDuringRead(name, () => {
238+
writeFileSync(join(project, `${base} (2)${ext}`), "second");
239+
writeFileSync(join(project, `${base} (3)${ext}`), "third");
240+
});
241+
const response = await upload(app, "", name);
242+
expect(response.status).toBe(201);
243+
expect(await response.json()).toMatchObject({ files: [`${base} (4)${ext}`] });
244+
expect(readFileSync(join(project, `${base} (2)${ext}`), "utf8")).toBe("second");
245+
expect(readFileSync(join(project, `${base} (3)${ext}`), "utf8")).toBe("third");
246+
},
247+
);
248+
249+
it("does not write through a symlink planted during the upload read", async (context) => {
250+
const { app, project, outside } = fixture();
251+
// Establish symlink support before entering the mocked asynchronous read.
252+
const probe = join(project, "probe-link");
253+
linkOrSkip(context, join(outside, "secret.txt"), probe, "file");
254+
rmSync(probe);
255+
raceDuringRead("upload.txt", () =>
256+
symlinkSync(join(outside, "secret.txt"), join(project, "upload.txt")),
257+
);
258+
const response = await upload(app);
259+
expect(await response.json()).toMatchObject({ files: [] });
260+
expect(readFileSync(join(outside, "secret.txt"), "utf8")).toBe("outside secret");
261+
});
262+
});

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

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2204,13 +2204,14 @@ async function processUploadedFiles(
22042204
// Don't overwrite — append (2), (3), etc.
22052205
let finalPath = destPath;
22062206
let finalName = name;
2207+
// Handle dotfiles correctly: .gitignore → ext="", base=".gitignore"
2208+
const dotIdx = name.indexOf(".", name.startsWith(".") ? 1 : 0);
2209+
const ext = dotIdx > 0 ? name.slice(dotIdx) : "";
2210+
const base = dotIdx > 0 ? name.slice(0, dotIdx) : name;
2211+
const MAX_COPY_INDEX = 10000;
2212+
let n = 1;
22072213
if (existsSync(finalPath)) {
2208-
// Handle dotfiles correctly: .gitignore → ext="", base=".gitignore"
2209-
const dotIdx = name.indexOf(".", name.startsWith(".") ? 1 : 0);
2210-
const ext = dotIdx > 0 ? name.slice(dotIdx) : "";
2211-
const base = dotIdx > 0 ? name.slice(0, dotIdx) : name;
2212-
let n = 2;
2213-
const MAX_COPY_INDEX = 10000;
2214+
n = 2;
22142215
while (n < MAX_COPY_INDEX && existsSync(resolve(targetDir, `${base} (${n})${ext}`))) n++;
22152216
if (n >= MAX_COPY_INDEX) {
22162217
skipped.push(name);
@@ -2231,7 +2232,33 @@ async function processUploadedFiles(
22312232
continue;
22322233
}
22332234

2234-
writeFileSync(finalPath, buffer);
2235+
// Reading the upload yields: another request can claim the selected name.
2236+
// Only exclusive creation authorizes a write; retry collisions without
2237+
// following a newly planted link or overwriting another upload.
2238+
let written = false;
2239+
while (n < MAX_COPY_INDEX && isSafePath(projectDir, finalPath)) {
2240+
try {
2241+
const fd = openSync(finalPath, "wx");
2242+
try {
2243+
writeFileSync(fd, buffer);
2244+
} finally {
2245+
closeSync(fd);
2246+
}
2247+
written = true;
2248+
break;
2249+
} catch (error) {
2250+
if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST") {
2251+
throw error;
2252+
}
2253+
n++;
2254+
finalName = `${base} (${n})${ext}`;
2255+
finalPath = resolve(targetDir, finalName);
2256+
}
2257+
}
2258+
if (!written) {
2259+
if (n >= MAX_COPY_INDEX) skipped.push(name);
2260+
continue;
2261+
}
22352262
const relativePath = subDir ? join(subDir, finalName) : finalName;
22362263
uploaded.push(relativePath);
22372264
if (isAudioFile(finalName)) {

0 commit comments

Comments
 (0)