Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
6 changes: 1 addition & 5 deletions packages/core/src/services/worktreeSessionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,7 @@ export async function readWorktreeSession(
return parsed;
}

/**
* Atomically writes the sidecar. Uses `atomicWriteJSON` (write-to-temp +
* rename) so a crash mid-write can never leave a half-written file that
* subsequent reads would reject as malformed.
*/
/** Writes the worktree session sidecar via `atomicWriteJSON`. */
export async function writeWorktreeSession(
filePath: string,
session: WorktreeSession,
Expand Down
156 changes: 156 additions & 0 deletions packages/core/src/utils/atomicFileWrite.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,160 @@ describe('atomicWriteFile', () => {
path.normalize('../otherDir/target.txt'),
);
});

it.skipIf(process.platform === 'win32')(
'should use atomic rename when ownership matches (inode changes)',
async () => {
const filePath = path.join(tmpDir, 'mine.txt');
await fs.writeFile(filePath, 'original');
const inoBefore = (await fs.stat(filePath)).ino;

await atomicWriteFile(filePath, 'updated');

const statAfter = await fs.stat(filePath);
// Atomic rename produces a new inode.
expect(statAfter.ino).not.toBe(inoBefore);
expect(await fs.readFile(filePath, 'utf-8')).toBe('updated');
},
);

it.skipIf(
process.platform === 'win32' || typeof process.geteuid !== 'function',
)(
'should fall back to in-place write when atomic rename would change ownership',
async () => {
// Simulate a file owned by a different user by replacing process.geteuid
// so it reports a uid that doesn't match the file's real uid. The code
// should detect rename would strip ownership and fall back to in-place
// writeFile, which preserves the inode — our signal that fallback ran.
const filePath = path.join(tmpDir, 'shared.txt');
await fs.writeFile(filePath, 'original');
await fs.chmod(filePath, 0o664);

const realStat = await fs.stat(filePath);
const inoBefore = realStat.ino;
const realGeteuid = process.geteuid!;
process.geteuid = () => realStat.uid + 1;

try {
await atomicWriteFile(filePath, 'updated');
} finally {
process.geteuid = realGeteuid;
}

expect(await fs.readFile(filePath, 'utf-8')).toBe('updated');

const statAfter = await fs.stat(filePath);
// In-place write preserves the inode — proves rename was skipped.
expect(statAfter.ino).toBe(inoBefore);
// Permissions preserved.
expect(statAfter.mode & 0o777).toBe(0o664);
// No leftover temp file.
expect(await fs.readdir(tmpDir)).toEqual(['shared.txt']);
},
);

it.skipIf(
process.platform === 'win32' || typeof process.geteuid !== 'function',
)(
'should skip in-place fallback for non-regular files and use atomic replace',
async () => {
// FIFO + ownership mismatch must NOT take the in-place fallback —
// open(O_WRONLY|O_TRUNC) against a FIFO would block forever
// waiting for a reader. The atomic rename path instead replaces
// the FIFO with a regular file, which is the only sane behavior
// for "write to this path" semantics on a special file.
const { execSync } = await import('node:child_process');
const fifoPath = path.join(tmpDir, 'pipe.fifo');
execSync(`mkfifo "${fifoPath}"`);

const realStat = await fs.stat(fifoPath);
expect(realStat.isFIFO()).toBe(true);

const realGeteuid = process.geteuid!;
process.geteuid = () => realStat.uid + 1;

try {
// If the in-place fallback were taken, this would hang
// indefinitely. Vitest's default timeout will catch that.
await atomicWriteFile(fifoPath, 'content');
} finally {
process.geteuid = realGeteuid;
}

// Atomic path replaced the FIFO with a regular file.
const statAfter = await fs.stat(fifoPath);
expect(statAfter.isFile()).toBe(true);
expect(await fs.readFile(fifoPath, 'utf-8')).toBe('content');
},
);

it.skipIf(
process.platform === 'win32' || typeof process.geteuid !== 'function',
)(
'should write via in-place fallback through a resolved symlink when ownership differs',
async () => {
// atomicWriteFile resolves the symlink via resolveSymlinkChain
// before stat, so the in-place write targets the real file.
// Verifies the symlink itself is preserved.
const realFile = path.join(tmpDir, 'real.txt');
const symlinkAt = path.join(tmpDir, 'attacker-symlink.txt');
await fs.writeFile(realFile, 'real-content');
await fs.symlink(realFile, symlinkAt);

const realGeteuid = process.geteuid!;
const realStat = await fs.stat(realFile);
const inoBefore = realStat.ino;
process.geteuid = () => realStat.uid + 1;

try {
await atomicWriteFile(symlinkAt, 'updated');
} finally {
process.geteuid = realGeteuid;
}

// The real file is updated; the symlink itself is preserved.
expect(await fs.readFile(realFile, 'utf-8')).toBe('updated');
expect((await fs.stat(realFile)).ino).toBe(inoBefore);
expect((await fs.lstat(symlinkAt)).isSymbolicLink()).toBe(true);
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
},
);

it.skipIf(
process.platform === 'win32' ||
typeof process.geteuid !== 'function' ||
// chmod 0o000 against the file's real owner still succeeds via
// POSIX rename in CI/sandbox setups where the user is effectively
// root; only assert real EACCES when we own and can be denied.
process.geteuid() === 0,
)(
'should surface EACCES when in-place fallback hits an unwritable file',
async () => {
// Atomic rename used to silently replace files the calling user
// has no write permission on (rename only needs parent-dir write).
// The in-place fallback respects the file's mode and surfaces
// EACCES — the correct behavior for "you don't own this, you
// shouldn't be replacing it" scenarios.
const filePath = path.join(tmpDir, 'readonly.txt');
await fs.writeFile(filePath, 'original');
await fs.chmod(filePath, 0o444);

const realStat = await fs.stat(filePath);
const realGeteuid = process.geteuid!;
process.geteuid = () => realStat.uid + 1;

try {
await expect(atomicWriteFile(filePath, 'updated')).rejects.toThrow(
/EACCES/,
);
} finally {
process.geteuid = realGeteuid;
// Restore mode so afterEach's rm can clean up.
await fs.chmod(filePath, 0o644);
}

// Original content untouched.
expect(await fs.readFile(filePath, 'utf-8')).toBe('original');
},
);
});
70 changes: 41 additions & 29 deletions packages/core/src/utils/atomicFileWrite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

import * as crypto from 'node:crypto';
import type { Stats } from 'node:fs';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { isNodeError } from './errors.js';
Expand Down Expand Up @@ -94,19 +95,12 @@ async function resolveSymlinkChain(filePath: string): Promise<string> {
}

/**
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
* Atomically write arbitrary content (string or Buffer) to a file.
* Atomically write content to a file (write-to-temp + rename).
*
* 1. Resolve symlinks (including broken ones) so the temp file lives
* next to the real target.
* 2. Write to a temporary file with fsync (`flush: true` by default).
* 3. Preserve the original file's permissions (or apply `options.mode`).
* 4. Atomic rename (POSIX) with retry (Windows).
* 5. On EXDEV (cross-device rename), fall back to direct write.
* **Note:** the EXDEV fallback is non-atomic — a crash mid-write
* can leave a partially-written file. EXDEV only occurs when the
* resolved target path is on a different filesystem than its parent
* directory, which is rare in practice.
* 6. Always clean up the temp file on failure.
* Falls back to in-place write when the existing file's uid differs
* from the process's euid — POSIX rename would reset ownership.
* Also falls back on EXDEV (cross-device). Both fallbacks lose crash
* atomicity but preserve the existing inode's uid.
*
* The parent directory of `filePath` must already exist.
*/
Expand All @@ -122,19 +116,20 @@ export async function atomicWriteFile(

const targetPath = await resolveSymlinkChain(filePath);

const tmpPath = `${targetPath}.${crypto.randomBytes(6).toString('hex')}.tmp`;

// Stat the target to preserve existing permissions (mask out file-type bits).
let existingMode: number | undefined;
// Stat the target to preserve existing permissions and detect
// ownership-changing renames (see the ownership-preservation note in
// the function doc).
let existingStat: Stats | undefined;
try {
const stat = await fs.stat(targetPath);
existingMode = stat.mode & 0o7777;
existingStat = await fs.stat(targetPath);
} catch (err) {
if (!isNodeError(err) || err.code !== 'ENOENT') {
throw err;
}
}

const existingMode =
existingStat !== undefined ? existingStat.mode & 0o7777 : undefined;
const desiredMode = existingMode ?? options?.mode;

const writeOptions: {
Expand All @@ -156,6 +151,33 @@ export async function atomicWriteFile(
}
};

// Detect when atomic rename would silently change ownership. POSIX
// rename creates a new inode owned by the process's euid:egid; if the
// existing file has a different uid, fall back to in-place write which
// preserves the inode and therefore uid. Only uid is compared — gid
// is intentionally skipped because macOS inherits the parent
// directory's GID for new files, making egid !== file.gid a
// false positive on the most common dev platform.
const ownershipWouldChange = (): boolean => {
if (existingStat === undefined) return false;
if (process.platform === 'win32') return false;
const euid = process.geteuid?.();
if (euid === undefined) return false;
return existingStat.uid !== euid;
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
};

if (
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
existingStat !== undefined &&
existingStat.isFile() &&
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
ownershipWouldChange()
) {
await fs.writeFile(targetPath, data, writeOptions);
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
await tryChmod(targetPath);
return;
}

const tmpPath = `${targetPath}.${crypto.randomBytes(6).toString('hex')}.tmp`;
Comment thread
doudouOUC marked this conversation as resolved.
Resolved

try {
await fs.writeFile(tmpPath, data, writeOptions);
await tryChmod(tmpPath);
Expand All @@ -179,17 +201,7 @@ export async function atomicWriteFile(
}
}

/**
* Atomically write a JSON value to a file.
*
* Delegates to {@link atomicWriteFile} for the actual atomic
* write-to-temp + rename flow.
*
* Note: if `filePath` is a symlink, the write resolves the chain
* and updates the real target file — the symlink itself is preserved.
*
* The parent directory of `filePath` must already exist.
*/
/** Atomically write a JSON value to a file. Delegates to {@link atomicWriteFile}. */
export async function atomicWriteJSON(
filePath: string,
data: unknown,
Expand Down
21 changes: 8 additions & 13 deletions packages/core/src/utils/runtimeStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@
* keeps running while no longer serving the recorded session
* (e.g. a hypothetical future mode-switch). Not currently invoked.
*
* The file is written atomically (tmp-file + rename) and contains a
* small, stable schema. External consumers should treat unknown fields
* as forward-compatible additions.
* The file is written via `atomicWriteJSON` (write-to-temp + rename,
* with in-place fallback when ownership differs).
* The schema is small and stable; external consumers should treat
* unknown fields as forward-compatible additions.
*/

import * as fs from 'node:fs/promises';
Expand Down Expand Up @@ -78,17 +79,11 @@ export interface WriteRuntimeStatusFields {
}

/**
* Atomically write the runtime status file at `filePath`.
* Write the runtime status file at `filePath`.
*
* Writes via tmp-file + rename so an external observer never sees a
* partially written file: it sees either the previous contents or the
* fully committed new contents.
*
* The parent directory of `filePath` is created on demand. Exceptions
* from the underlying I/O propagate to the caller; this function does
* not log or swallow them. Callers that want best-effort semantics
* should wrap the call in a try/catch. On failure no leftover `.tmp`
* file is kept on disk.
* The parent directory is created on demand. Exceptions propagate to
* the caller; callers that want best-effort semantics should wrap in
* a try/catch.
*/
export async function writeRuntimeStatus(
filePath: string,
Expand Down
Loading