Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion apps/ade-cli/src/services/credentials/credentialFileIo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -63,6 +106,7 @@ export function writeFileAtomic(filePath: string, contents: string | Buffer): vo
throw error;
}
ensureMode600(filePath);
syncParentDirectory(path.dirname(filePath));
}

/**
Expand Down
20 changes: 20 additions & 0 deletions apps/desktop/src/main/services/files/fileService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
30 changes: 27 additions & 3 deletions apps/desktop/src/main/services/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ─────────────────────────────────────────────────────

Expand Down Expand Up @@ -851,12 +851,29 @@ 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);
// 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
// briefly readable.
if (exactMode != null) {
try {
nonAsarFs.fchmodSync(fd, exactMode);
} catch {
// Filesystems without POSIX bits keep the open's mode.
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Temp created before mode is applied

Medium Severity

writeFileByDescriptor still opens the sibling temp with 0o666 (umask-filtered, typically 0644) and only then fchmods the preserved mode. A local observer can open that temp in the create-to-chmod window and keep the fd after the mode is narrowed, so a 0600 .env is readable while its bytes land. writeFileAtomic already passes the intended mode into open so the file is never born wider.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2d57067. Configure here.

nonAsarFs.writeFileSync(fd, data, options as fs.WriteFileOptions | BufferEncoding | undefined);
} finally {
nonAsarFs.closeSync(fd);
Expand Down Expand Up @@ -965,7 +982,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);
Expand Down
15 changes: 15 additions & 0 deletions apps/desktop/src/main/services/state/durableFile.test.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -177,6 +178,20 @@ describe("durableFile", () => {
expect(fs.statSync(filePath).mode & 0o777).toBe(0o600);
});

// 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);
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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
Expand Down
8 changes: 4 additions & 4 deletions apps/desktop/src/main/services/state/durableFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion apps/desktop/src/main/services/state/globalState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-<pid>-<hex>`, 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([]);
});
});

Expand Down
35 changes: 6 additions & 29 deletions apps/desktop/src/main/services/state/globalState.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import fs from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import type {
AppWelcomeVideoState,
AutoUpdatePreferences,
Expand All @@ -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;

Expand Down Expand Up @@ -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
Expand All @@ -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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Non-atomic overwrite of desktop settings

When Windows blocks replacement but allows writes, writeGlobalState can overwrite the live settings file in place. replaceViaRename falls back to a direct copy, so an interrupted copy can destroy the previous settings.

Learn more

The desktop keeps preferences, recent projects, and update recovery data in one JSON file. The previous save used only a rename to publish new bytes, so a refused rename left the previous bytes untouched. The shared replacement helper first retries the rename, then tries a staged rename, and finally copies directly to the destination for certain repeated rename errors. The last operation is not atomic and does not flush the copied destination file. readGlobalState treats malformed JSON as empty state.

Example: While the user changes a preference, a Windows reader holds the settings file open with write sharing but without delete sharing. Both renames fail, so the save copies directly onto the settings file. If that copy is interrupted, the next launch can find incomplete JSON instead of the previous settings.

Recommended fix: Give global-state writes a rename-only replacement policy. Keep transient rename retries, but never let this caller fall back to copying over the live file. Verify that a persistent rename refusal leaves the original bytes untouched.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

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 });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Settings replaced after failed disk flush

When the temp file’s disk flush fails, writeGlobalState can still replace the last good settings file. bestEffortFsync suppresses writeback errors, so the rename can publish incomplete settings.

Learn more

Desktop settings, recent projects, and pending update records share one JSON file. Desktop startup reads it as a unit. The previous writer abandoned the temporary file when flushing its contents failed. The shared atomic writer now proceeds to replacement after its flush helper catches the error. If a real writeback error leaves incomplete bytes, readGlobalState falls back to empty state on the next launch.

Example: A recent-project update fits in the filesystem cache, but delayed allocation returns ENOSPC on flush. The temporary file can still be renamed over the valid state, losing previously stored settings along with the attempted update.

Recommended fix: Use a strict regular-file flush for global state and propagate its failure before replacing the destination. Directory flush can remain best effort. Exercise this path with an injected temp-file fsyncSync failure and verify that the old JSON survives.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Saved state can be truncated

writeGlobalState now reaches a fallback that copies directly over the saved file when both rename attempts are refused. On Windows, another program holding the file open can trigger this path. Readers can see incomplete JSON, and a failed copy can destroy the previous state. The old writer left the saved file untouched when rename failed. Keep this caller on a rename-only path, even if that means skipping the update.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/services/state/globalState.ts
Line: 226

Comment:
**Saved state can be truncated**

`writeGlobalState` now reaches a fallback that copies directly over the saved file when both rename attempts are refused. On Windows, another program holding the file open can trigger this path. Readers can see incomplete JSON, and a failed copy can destroy the previous state. The old writer left the saved file untouched when rename failed. Keep this caller on a rename-only path, even if that means skipping the update.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

} catch {
if (fd != null) {
try { fs.closeSync(fd); } catch {}
}
if (tempPath) {
try { fs.unlinkSync(tempPath); } catch {}
}
// Non-fatal; global state is a convenience.
}
}
Expand Down
Loading