fix(studio-server): an edit to a read-only project file is refused and leaves it unchanged (#7731)

* fix(studio-server): an edit to a read-only project file is refused and leaves it unchanged

* test(core): read the refused file without a stat check first
This commit is contained in:
Miguel Ángel
2026-11-14 12:10:48 +00:00
committed by GitHub
parent ff9c3b7619
commit b5e9bc6893
7 changed files with 101 additions and 3 deletions
+20
View File
@@ -165,6 +165,26 @@ describe("replaceFileAtomically", () => {
});
});
describe("replaceFileAtomically on a read-only file", () => {
// Root writes through read-only files, so the refusal is the owner's, as every system answers it.
it.skipIf(process.getuid?.() === 0)("refuses it and leaves it as it was", () => {
const dir = mkdtempSync(join(tmpdir(), "atomic-file-readonly-test-"));
const file = join(dir, "index.html");
writeFileSync(file, "kept");
fs.chmodSync(file, 0o444);
try {
expect(() => replaceFileAtomically(file, "replaced", 0o444)).toThrow(
expect.objectContaining({ code: expect.stringMatching(/^(EACCES|EPERM)$/) }),
);
expect(readFileSync(file, "utf-8")).toBe("kept");
expect(fs.readdirSync(dir)).toEqual(["index.html"]);
} finally {
fs.chmodSync(file, 0o644);
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("createFileAtomically", () => {
const dirs: string[] = [];
+9
View File
@@ -48,12 +48,21 @@ export function replaceFileAtomically(
operations: SiblingFileSystem & Pick<typeof fs, "renameSync"> = fs,
): void {
traceWrite(filePath, content);
refuseReadOnly(filePath);
// Node fs.rename uses libuv uv_fs_rename; win32 calls MoveFileExW with MOVEFILE_REPLACE_EXISTING.
publishSibling(filePath, content, mode, operations, (tempPath) =>
renameWithRetry(tempPath, filePath, { rename: operations.renameSync }),
);
}
export function refuseReadOnly(filePath: string): void {
try {
fs.accessSync(filePath, fs.constants.W_OK);
} catch (error) {
if (errorCode(error) !== "ENOENT") throw error;
}
}
/** Create a file that must not exist yet (EEXIST otherwise); readers never see it empty or partial. */
export function createFileAtomically(
filePath: string,
@@ -180,6 +180,33 @@ describe("applyFileMutations", () => {
}
});
it.skipIf(process.getuid?.() === 0)(
"changes nothing when one of the files is read-only, the others included",
() => {
resetFileWriteReceipts();
const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-readonly-file-"));
const first = join(projectDir, "first.html");
const locked = join(projectDir, "index.html");
try {
writeFileSync(first, "first-before", "utf8");
writeFileSync(locked, "locked-before", "utf8");
chmodSync(locked, 0o444);
expect(() =>
applyFileMutations(projectDir, [
{ sourceFile: "first.html", absPath: first, after: "first-after" },
{ sourceFile: "index.html", absPath: locked, after: "locked-after" },
]),
).toThrow(expect.objectContaining({ code: expect.stringMatching(/^(EACCES|EPERM)$/) }));
expect(readFileSync(first, "utf8")).toBe("first-before");
expect(readFileSync(locked, "utf8")).toBe("locked-before");
} finally {
chmodSync(locked, 0o644);
resetFileWriteReceipts();
rmSync(projectDir, { recursive: true, force: true });
}
},
);
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"reports the write error, not a failed rollback, when a later file was never written",
() => {
@@ -99,6 +99,25 @@ describe("the history store on Windows, while another process briefly holds a fi
expect((await store.read(hash)).toString("utf8")).toBe("<p>before</p>");
});
it.skipIf(process.getuid?.() === 0)("leaves a read-only project file as it is", async () => {
const source = join(root, "source.html");
writeFileSync(source, "<p>before</p>");
const store = await openBlobStore(join(root, "history", "blobs"));
const hash = await store.put(source);
const target = join(root, "index.html");
writeFileSync(target, "<p>after</p>");
fs.chmodSync(target, 0o444);
try {
await expect(store.writeTo(hash, target)).rejects.toMatchObject({
code: expect.stringMatching(/^(EACCES|EPERM)$/),
});
expect(readFileSync(target, "utf8")).toBe("<p>after</p>");
expect(readdirSync(root).sort()).toEqual(["history", "index.html", "source.html"]);
} finally {
fs.chmodSync(target, 0o644);
}
});
it("writes a file back into the project once the hold clears", async () => {
const source = join(root, "source.html");
writeFileSync(source, "<p>before</p>");
@@ -13,7 +13,7 @@ import {
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { pipeline } from "node:stream/promises";
import { atomicTempPath } from "@hyperframes/core/atomic-file";
import { atomicTempPath, refuseReadOnly } from "@hyperframes/core/atomic-file";
import {
isWindowsHold,
renameWithRetry,
@@ -105,6 +105,7 @@ async function cloneOrCopy(
hash: string,
beforeReplace?: () => void,
): Promise<void> {
refuseReadOnly(to);
await mkdir(dirname(to), { recursive: true });
const temp = atomicTempPath(to);
try {
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it } from "vitest";
import { Hono } from "hono";
import { type ChildProcess, spawn, spawnSync } from "node:child_process";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { registerFileRoutes } from "./files";
@@ -36,7 +36,13 @@ function fixture(name: string) {
headers: { "If-Match": '"any"' },
body: "<div>edited</div>",
});
return { file, get, put };
const remove = (id: string) =>
app.request(`http://localhost/projects/demo/file-mutations/remove-elements/${name}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ targets: [{ id }] }),
});
return { file, get, put, remove };
}
const answered = async (response: Response) => ({
@@ -55,6 +61,16 @@ describe.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
expect(await answered(await put())).toEqual({ status: 403, why: "permission" });
});
// fails without the fix: the edit replaced the read-only file (a rename ignores its mode) and answered 200.
it("leaves a read-only file as it is when an element is removed, and answers 403", async () => {
const { file, remove } = fixture("readonly.html");
writeFileSync(file, '<div id="keep">kept</div><p id="gone">tag</p>');
chmodSync(file, 0o444);
cleanups.push(() => chmodSync(file, 0o644));
expect(await answered(await remove("gone"))).toEqual({ status: 403, why: "permission" });
expect(readFileSync(file, "utf8")).toBe('<div id="keep">kept</div><p id="gone">tag</p>');
});
it("does not answer an optional read of it as a blank file", async () => {
const { file, get } = fixture("locked.html");
chmodSync(file, 0o000);
@@ -2807,6 +2807,12 @@ function heldFileAnswer(c: RouteContext, error: unknown) {
}
export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
api.use("/projects/:id/*", async (c, next) => {
await next();
const refusedWrite = c.error ? heldFileAnswer(c, c.error) : null;
if (refusedWrite) c.res = refusedWrite;
});
// ── Read ──
api.get("/projects/:id/files/*", async (c) => {