From 2d57067fdeba15bdd11693c51bc8f5a09f0721f0 Mon Sep 17 00:00:00 2001 From: Arul Sharma Date: Mon, 23 Nov 2026 02:03:05 -0500 Subject: [PATCH 1/2] fix(storage): atomic saves keep file modes and sync the credential bytes Four writers had drifted from ADE's own atomic-save helper: - writeGlobalState hand-rolled a temp+rename that replaced an existing ade-state.json's permission bits with the umask default. - The credential store's atomic writer renamed a 0600 temp without syncing it, so a crash right after the rename could leave an empty credential file and sign the machine out. - writeFileAtomic skipped the post-open chmod when the caller passed an explicit mode, so a narrowing umask could still strip bits. - secureWriteAtomicWithinRoot, used by every Files-tab and lane-diff save, replaced the target inode with a temp at the umask default: editing a 0755 script dropped its executable bit and a 0600 .env became readable. Use the shared writer for global state, fsync the credential temp and its directory, always apply the mode to the open descriptor, and carry the target's existing bits onto the user-file temp before any bytes land. The new mode tests are POSIX-only and skipped on this Windows host. Co-Authored-By: Claude Code --- .../services/credentials/credentialFileIo.ts | 46 ++++++++++++++++++- .../main/services/files/fileService.test.ts | 20 ++++++++ .../desktop/src/main/services/shared/utils.ts | 22 ++++++++- .../main/services/state/durableFile.test.ts | 13 ++++++ .../src/main/services/state/durableFile.ts | 8 ++-- .../src/main/services/state/globalState.ts | 35 +++----------- 6 files changed, 108 insertions(+), 36 deletions(-) diff --git a/apps/ade-cli/src/services/credentials/credentialFileIo.ts b/apps/ade-cli/src/services/credentials/credentialFileIo.ts index 2eda6b3d73..8c69a3687a 100644 --- a/apps/ade-cli/src/services/credentials/credentialFileIo.ts +++ b/apps/ade-cli/src/services/credentials/credentialFileIo.ts @@ -51,10 +51,53 @@ export function ensureDirMode700(dirPath: string): void { } } +/** + * A crash right after the rename used to leave a zero-length credential file: + * the bytes were never synced before the name moved. The refresh token in it + * is spent the moment it was written, so that loss signs the machine out. + */ +function syncFileData(fd: number): void { + try { + fs.fsyncSync(fd); + } catch { + // Some filesystems do not support fsync; the rename still stands. + } +} + +/** Persist the rename itself. Windows has no directory handle to flush. */ +function syncParentDirectory(dirPath: string): void { + if (process.platform === "win32") return; + let fd: number | null = null; + try { + fd = fs.openSync(dirPath, "r"); + fs.fsyncSync(fd); + } catch { + // Directory fsync is unavailable on some filesystems. + } finally { + if (fd !== null) { + try { fs.closeSync(fd); } catch { /* best effort */ } + } + } +} + export function writeFileAtomic(filePath: string, contents: string | Buffer): void { ensureDirMode700(path.dirname(filePath)); const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`; - fs.writeFileSync(tmpPath, contents, { mode: 0o600 }); + const fd = fs.openSync(tmpPath, "w", 0o600); + try { + fs.writeFileSync(fd, contents); + syncFileData(fd); + } catch (error) { + try { fs.closeSync(fd); } catch { /* preserve the write error */ } + try { fs.rmSync(tmpPath, { force: true }); } catch { /* preserve the write error */ } + throw error; + } + try { + fs.closeSync(fd); + } catch (error) { + try { fs.rmSync(tmpPath, { force: true }); } catch { /* preserve the close error */ } + throw error; + } ensureMode600(tmpPath); try { renameRetryingOnWindows(tmpPath, filePath); @@ -63,6 +106,7 @@ export function writeFileAtomic(filePath: string, contents: string | Buffer): vo throw error; } ensureMode600(filePath); + syncParentDirectory(path.dirname(filePath)); } /** diff --git a/apps/desktop/src/main/services/files/fileService.test.ts b/apps/desktop/src/main/services/files/fileService.test.ts index aa3c43e84a..f3da331550 100644 --- a/apps/desktop/src/main/services/files/fileService.test.ts +++ b/apps/desktop/src/main/services/files/fileService.test.ts @@ -911,6 +911,26 @@ describe("fileService", () => { service.writeWorkspaceText({ workspaceId: "workspace-1", path: "docs/notes.md", text: "# new\n" }); expect(fs.readFileSync(path.join(rootPath, "docs", "notes.md"), "utf8")).toBe("# new\n"); + // A replace is a new inode: an edited script keeps its executable bit + // and a .env keeps its owner-only bits. A new file keeps the default. + if (process.platform !== "win32") { + const script = path.join(rootPath, "docs", "script.sh"); + fs.writeFileSync(script, "#!/bin/sh\n", "utf8"); + fs.chmodSync(script, 0o755); + service.writeWorkspaceText({ workspaceId: "workspace-1", path: "docs/script.sh", text: "#!/bin/sh\necho hi\n" }); + expect(fs.statSync(script).mode & 0o777).toBe(0o755); + + const secret = path.join(rootPath, "docs", ".env"); + fs.writeFileSync(secret, "A=1\n", "utf8"); + fs.chmodSync(secret, 0o600); + service.writeWorkspaceText({ workspaceId: "workspace-1", path: "docs/.env", text: "A=2\n" }); + expect(fs.statSync(secret).mode & 0o777).toBe(0o600); + + const fresh = path.join(rootPath, "docs", "fresh.md"); + service.writeWorkspaceText({ workspaceId: "workspace-1", path: "docs/fresh.md", text: "new\n" }); + expect(fs.statSync(fresh).mode & 0o777).toBe(0o666 & ~process.umask()); + } + // Chunked upload: each chunk lands at the byte it names, the receipt // hashes the whole file, and a chunk at the wrong byte (a retry sent // twice) is refused instead of corrupting it. diff --git a/apps/desktop/src/main/services/shared/utils.ts b/apps/desktop/src/main/services/shared/utils.ts index 3c4663e178..388aafcaf2 100644 --- a/apps/desktop/src/main/services/shared/utils.ts +++ b/apps/desktop/src/main/services/shared/utils.ts @@ -13,7 +13,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto"; import { isWindowsCmdCommandNotFound, resolveCliSpawnInvocation, terminateProcessTree } from "./processExecution"; import { AdeExpectedError, markExpected } from "../../../shared/expectedError"; import { containsSecretToken, redactSecretTokens } from "../../../shared/secretTokenShapes"; -import { writeFileAtomic } from "../state/durableFile"; +import { existingFileMode, writeFileAtomic } from "../state/durableFile"; // ── Type guards ───────────────────────────────────────────────────── @@ -851,12 +851,23 @@ function writeFileByDescriptor( filePath: string, data: string | NodeJS.ArrayBufferView, options?: fs.WriteFileOptions | BufferEncoding, + exactMode?: number, ): void { const mode = typeof options === "object" && options != null && typeof options.mode === "number" ? options.mode : 0o666; const fd = openWriteNoFollow(filePath, nonAsarFs.constants.O_WRONLY | nonAsarFs.constants.O_CREAT | nonAsarFs.constants.O_TRUNC, mode); try { + // The open's mode passes through the umask; a kept mode must come out + // exactly as it was, and before any bytes land so a secret file is never + // briefly readable. + if (exactMode != null) { + try { + nonAsarFs.fchmodSync(fd, exactMode); + } catch { + // Filesystems without POSIX bits keep the open's mode. + } + } nonAsarFs.writeFileSync(fd, data, options as fs.WriteFileOptions | BufferEncoding | undefined); } finally { nonAsarFs.closeSync(fd); @@ -965,7 +976,14 @@ export function secureWriteAtomicWithinRoot(root: string, candidate: string, tex initialTarget.parentPath, `.${path.basename(initialTarget.targetPath) || "tmp"}.${randomUUID()}.tmp`, ); - writeFileByDescriptor(tmpPath, text, typeof text === "string" ? "utf8" : undefined); + // A rename replaces the target inode, so an edited 0755 script or 0600 .env + // would otherwise take the umask's default bits. A new file keeps today's. + writeFileByDescriptor( + tmpPath, + text, + typeof text === "string" ? "utf8" : undefined, + existingFileMode(initialTarget.targetPath), + ); try { const { targetPath } = prepareMutationTargetWithinRoot(root, candidate); nonAsarFs.renameSync(tmpPath, targetPath); diff --git a/apps/desktop/src/main/services/state/durableFile.test.ts b/apps/desktop/src/main/services/state/durableFile.test.ts index aca3b4d10d..794e44776d 100644 --- a/apps/desktop/src/main/services/state/durableFile.test.ts +++ b/apps/desktop/src/main/services/state/durableFile.test.ts @@ -177,6 +177,19 @@ describe("durableFile", () => { expect(fs.statSync(filePath).mode & 0o777).toBe(0o600); }); + it.skipIf(process.platform === "win32")("keeps a requested mode even when the umask would narrow it", () => { + // The open's mode passes through the umask: a 0o400 umask turns an open + // 0o600 into a write-only file, so the descriptor needs the chmod too. + const previous = process.umask(0o400); + try { + writeFileAtomic(filePath, "secret", { mode: 0o600 }); + } finally { + process.umask(previous); + } + expect(fs.statSync(filePath).mode & 0o777).toBe(0o600); + expect(tempLeftovers()).toEqual([]); + }); + it("never removes the destination before the replacement is in place", () => { // The pre-unlink some writers use as "the Windows fix" opens a window in // which the file simply does not exist, and a concurrent reader that diff --git a/apps/desktop/src/main/services/state/durableFile.ts b/apps/desktop/src/main/services/state/durableFile.ts index 23e47b72a0..1d0bf7f72f 100644 --- a/apps/desktop/src/main/services/state/durableFile.ts +++ b/apps/desktop/src/main/services/state/durableFile.ts @@ -212,10 +212,10 @@ export function writeFileAtomic( fd = mode != null ? fs.openSync(tempPath, "wx", mode) : fs.openSync(tempPath, "wx"); - // The open's mode passes through the umask; a kept mode must come out - // exactly as it was. A filesystem without POSIX bits keeps its default - // rather than losing the write. - if (opts.mode == null && mode != null) { + // The open's mode passes through the umask; a requested or kept mode must + // come out exactly as it was. A filesystem without POSIX bits keeps its + // default rather than losing the write. + if (mode != null) { try { fs.fchmodSync(fd, mode); } catch { diff --git a/apps/desktop/src/main/services/state/globalState.ts b/apps/desktop/src/main/services/state/globalState.ts index fb71aa8336..b027fd160e 100644 --- a/apps/desktop/src/main/services/state/globalState.ts +++ b/apps/desktop/src/main/services/state/globalState.ts @@ -1,6 +1,5 @@ import fs from "node:fs"; import path from "node:path"; -import { randomUUID } from "node:crypto"; import type { AppWelcomeVideoState, AutoUpdatePreferences, @@ -21,6 +20,7 @@ import { projectRefStateKey } from "../../../shared/projectIdentity"; import type { SavedWindowRepositoryTabs } from "../../../shared/windowRepositoryTabs"; import { sanitizePortableGitRemote } from "../../../shared/crossMachineHandoff"; import type { MainWindowState } from "./mainWindowState"; +import { writeFileAtomic } from "./durableFile"; export type RecentProjectRemote = RecentProjectRemoteRef; @@ -210,8 +210,6 @@ export function readGlobalStateForUpdate(filePath: string): GlobalState { } export function writeGlobalState(filePath: string, state: GlobalState): void { - let tempPath: string | null = null; - let fd: number | null = null; try { const serialized = `${JSON.stringify(state, null, 2)}\n`; // The file already holds this state (the window restores the tabs it @@ -221,33 +219,12 @@ export function writeGlobalState(filePath: string, state: GlobalState): void { } catch { // Missing or unreadable: write it. } - const dir = path.dirname(filePath); - fs.mkdirSync(dir, { recursive: true }); - tempPath = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`); - fd = fs.openSync(tempPath, "w"); - fs.writeFileSync(fd, serialized, "utf8"); - fs.fsyncSync(fd); - fs.closeSync(fd); - fd = null; - fs.renameSync(tempPath, filePath); - tempPath = null; - try { - const dirFd = fs.openSync(dir, "r"); - try { - fs.fsyncSync(dirFd); - } finally { - fs.closeSync(dirFd); - } - } catch { - // Directory fsync is best effort across filesystems/platforms. - } + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + // One atomic writer for the whole app: it keeps the replaced file's + // permission bits (this hand-rolled save widened a 0o600 state file under + // the process umask) and syncs the temp file and its directory. + writeFileAtomic(filePath, serialized, { fsync: true }); } catch { - if (fd != null) { - try { fs.closeSync(fd); } catch {} - } - if (tempPath) { - try { fs.unlinkSync(tempPath); } catch {} - } // Non-fatal; global state is a convenience. } } From 03eacec8f20686ce729d9863703aaf549801120b Mon Sep 17 00:00:00 2001 From: Arul Sharma Date: Mon, 23 Nov 2026 02:57:43 -0500 Subject: [PATCH 2/2] fix(storage): keep the temp private at create, and harden the tests Review follow-ups: - writeFileByDescriptor passes the kept mode to open as well, so a 0600 user-file temp is never briefly readable between create and fchmod. - The umask test skips in Vitest worker threads, where process.umask()'s setter throws (ERR_WORKER_UNSUPPORTED_OPERATION) on Linux CI. - globalState's leftover-temp assertion follows the shared writer's `.tmp--` shape instead of a `.tmp` suffix. Co-Authored-By: Claude Code --- apps/desktop/src/main/services/shared/utils.ts | 8 +++++++- apps/desktop/src/main/services/state/durableFile.test.ts | 4 +++- apps/desktop/src/main/services/state/globalState.test.ts | 4 +++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src/main/services/shared/utils.ts b/apps/desktop/src/main/services/shared/utils.ts index 388aafcaf2..75bf24b036 100644 --- a/apps/desktop/src/main/services/shared/utils.ts +++ b/apps/desktop/src/main/services/shared/utils.ts @@ -856,7 +856,13 @@ function writeFileByDescriptor( const mode = typeof options === "object" && options != null && typeof options.mode === "number" ? options.mode : 0o666; - const fd = openWriteNoFollow(filePath, nonAsarFs.constants.O_WRONLY | nonAsarFs.constants.O_CREAT | nonAsarFs.constants.O_TRUNC, mode); + // The kept mode goes to the open too: an empty temp must never be readable + // by others, not even between create and the fchmod below. + const fd = openWriteNoFollow( + filePath, + nonAsarFs.constants.O_WRONLY | nonAsarFs.constants.O_CREAT | nonAsarFs.constants.O_TRUNC, + exactMode ?? mode, + ); try { // The open's mode passes through the umask; a kept mode must come out // exactly as it was, and before any bytes land so a secret file is never diff --git a/apps/desktop/src/main/services/state/durableFile.test.ts b/apps/desktop/src/main/services/state/durableFile.test.ts index 794e44776d..bacf35f684 100644 --- a/apps/desktop/src/main/services/state/durableFile.test.ts +++ b/apps/desktop/src/main/services/state/durableFile.test.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { isMainThread } from "node:worker_threads"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { injectFsFault } from "../../../test/faultInjection"; import { @@ -177,7 +178,8 @@ describe("durableFile", () => { expect(fs.statSync(filePath).mode & 0o777).toBe(0o600); }); - it.skipIf(process.platform === "win32")("keeps a requested mode even when the umask would narrow it", () => { + // The umask setter throws in a Vitest worker thread (ERR_WORKER_UNSUPPORTED_OPERATION). + it.skipIf(process.platform === "win32" || !isMainThread)("keeps a requested mode even when the umask would narrow it", () => { // The open's mode passes through the umask: a 0o400 umask turns an open // 0o600 into a write-only file, so the descriptor needs the chmod too. const previous = process.umask(0o400); diff --git a/apps/desktop/src/main/services/state/globalState.test.ts b/apps/desktop/src/main/services/state/globalState.test.ts index bc74213494..c0172ae2e9 100644 --- a/apps/desktop/src/main/services/state/globalState.test.ts +++ b/apps/desktop/src/main/services/state/globalState.test.ts @@ -293,7 +293,9 @@ describe("writeGlobalState", () => { writeGlobalState(filePath, state); expect(readGlobalState(filePath)).toEqual(state); - expect(fs.readdirSync(dir).filter((entry) => entry.endsWith(".tmp"))).toEqual([]); + // The shared writer's temp shape is `.name.tmp--`, so assert the + // directory holds only the state file instead of matching a suffix. + expect(fs.readdirSync(dir).filter((entry) => entry !== path.basename(filePath))).toEqual([]); }); });