diff --git a/packages/core/src/atomicFile.test.ts b/packages/core/src/atomicFile.test.ts index 83a55b2386..fcb02829cb 100644 --- a/packages/core/src/atomicFile.test.ts +++ b/packages/core/src/atomicFile.test.ts @@ -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[] = []; diff --git a/packages/core/src/atomicFile.ts b/packages/core/src/atomicFile.ts index 3416d000f8..079d63918e 100644 --- a/packages/core/src/atomicFile.ts +++ b/packages/core/src/atomicFile.ts @@ -48,12 +48,21 @@ export function replaceFileAtomically( operations: SiblingFileSystem & Pick = 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, diff --git a/packages/studio-server/src/helpers/applyFileMutations.test.ts b/packages/studio-server/src/helpers/applyFileMutations.test.ts index 8808bd7209..048efa9005 100644 --- a/packages/studio-server/src/helpers/applyFileMutations.test.ts +++ b/packages/studio-server/src/helpers/applyFileMutations.test.ts @@ -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", () => { diff --git a/packages/studio-server/src/history/blobStore.test.ts b/packages/studio-server/src/history/blobStore.test.ts index 4a900ebaeb..a9f421fca5 100644 --- a/packages/studio-server/src/history/blobStore.test.ts +++ b/packages/studio-server/src/history/blobStore.test.ts @@ -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("

before

"); }); + it.skipIf(process.getuid?.() === 0)("leaves a read-only project file as it is", async () => { + const source = join(root, "source.html"); + writeFileSync(source, "

before

"); + const store = await openBlobStore(join(root, "history", "blobs")); + const hash = await store.put(source); + const target = join(root, "index.html"); + writeFileSync(target, "

after

"); + fs.chmodSync(target, 0o444); + try { + await expect(store.writeTo(hash, target)).rejects.toMatchObject({ + code: expect.stringMatching(/^(EACCES|EPERM)$/), + }); + expect(readFileSync(target, "utf8")).toBe("

after

"); + 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, "

before

"); diff --git a/packages/studio-server/src/history/blobStore.ts b/packages/studio-server/src/history/blobStore.ts index eeb445e0f4..5ad4ef113d 100644 --- a/packages/studio-server/src/history/blobStore.ts +++ b/packages/studio-server/src/history/blobStore.ts @@ -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 { + refuseReadOnly(to); await mkdir(dirname(to), { recursive: true }); const temp = atomicTempPath(to); try { diff --git a/packages/studio-server/src/routes/files.heldFile.test.ts b/packages/studio-server/src/routes/files.heldFile.test.ts index 80e8a773b6..62dc7756a9 100644 --- a/packages/studio-server/src/routes/files.heldFile.test.ts +++ b/packages/studio-server/src/routes/files.heldFile.test.ts @@ -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: "
edited
", }); - 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, '
kept

tag

'); + chmodSync(file, 0o444); + cleanups.push(() => chmodSync(file, 0o644)); + expect(await answered(await remove("gone"))).toEqual({ status: 403, why: "permission" }); + expect(readFileSync(file, "utf8")).toBe('
kept

tag

'); + }); + it("does not answer an optional read of it as a blank file", async () => { const { file, get } = fixture("locked.html"); chmodSync(file, 0o000); diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index ff0e6298aa..c7abf56f49 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -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) => {