From b9cb88150a0f44a273e962ea06e029f8c24d0b51 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Fri, 4 Dec 2026 21:56:57 -0500 Subject: [PATCH 1/2] feat(worker): Reserve private checkpoint directories --- .../code/src/checkpoint-directory.test.ts | 338 ++++++++++++++++++ packages/code/src/checkpoint-directory.ts | 234 ++++++++++++ packages/code/src/process-lock.ts | 20 +- 3 files changed, 585 insertions(+), 7 deletions(-) create mode 100644 packages/code/src/checkpoint-directory.test.ts create mode 100644 packages/code/src/checkpoint-directory.ts diff --git a/packages/code/src/checkpoint-directory.test.ts b/packages/code/src/checkpoint-directory.test.ts new file mode 100644 index 00000000..4b8588a5 --- /dev/null +++ b/packages/code/src/checkpoint-directory.test.ts @@ -0,0 +1,338 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { + chmod, + mkdir, + mkdtemp, + readdir, + rename, + rm, + stat, + symlink, + writeFile, +} from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import type { TestContext } from 'node:test'; + +import { withCheckpointDirectory } from './checkpoint-directory.js'; +import { ProcessLockBusyError } from './process-lock.js'; + +const linux = process.platform === 'linux'; +const options = { skip: !linux, timeout: 10_000 }; +const base = process.env.CHECKPOINT_TEST_ROOT ?? homedir(); +const unsupported = process.env.CHECKPOINT_TEST_UNSUPPORTED_ROOT; +const admit = async () => () => {}; +const unexpected = async (): Promise => + assert.fail('Unexpected callback'); + +async function fixture(t: TestContext, root = base): Promise { + const path = await mkdtemp(join(root, '.checkpoint-reservation-')); + t.after(() => rm(path, { recursive: true, force: true })); + return path; +} + +async function assertReusable(path: string): Promise { + assert.equal( + await withCheckpointDirectory(path, admit, async fd => { + const pinned = await stat(fd, { bigint: true }); + const current = await stat(path, { bigint: true }); + assert.equal(pinned.dev, current.dev); + assert.equal(pinned.ino, current.ino); + return 'reserved'; + }), + 'reserved' + ); +} + +test( + 'checkpoint reservation refuses unsupported platforms', + { skip: linux }, + async () => { + await assert.rejects( + withCheckpointDirectory('/unused', unexpected, unexpected), + /requires Linux/ + ); + } +); + +test( + 'checkpoint reservation bounds canonical absolute path input', + options, + async () => { + for (const path of [ + '', + '/', + 'relative', + '/a//b', + '/a/', + '/./a', + '/a/../b', + '/a\0b', + '/\ud800', + '/' + 'a'.repeat(4096), + '/' + 'é'.repeat(2048), + '/' + 'é'.repeat(128), + '/' + Array(65).fill('a').join('/'), + ]) { + await assert.rejects( + withCheckpointDirectory(path, unexpected, unexpected), + /Invalid checkpoint directory path/ + ); + } + } +); + +test( + 'checkpoint reservation rejects untrusted entries without creating or changing them', + options, + async t => { + const root = await fixture(t); + const store = join(root, 'store'); + await assert.rejects( + withCheckpointDirectory(store, unexpected, unexpected), + { code: 'ENOENT' } + ); + await writeFile(store, 'fixture', { mode: 0o700 }); + await assert.rejects( + withCheckpointDirectory(store, unexpected, unexpected), + { code: 'ENOTDIR' } + ); + await rm(store); + await mkdir(store, { mode: 0o700 }); + const alias = join(root, 'alias'); + await symlink(store, alias); + await assert.rejects( + withCheckpointDirectory(alias, unexpected, unexpected), + { code: 'ENOTDIR' } + ); + const ancestor = join(root, 'parent'); + await symlink(root, ancestor); + await assert.rejects( + withCheckpointDirectory( + join(ancestor, 'store'), + unexpected, + unexpected + ), + { code: 'ENOTDIR' } + ); + for (const mode of [0o750, 0o2700]) { + await chmod(store, mode); + await assert.rejects( + withCheckpointDirectory(store, unexpected, unexpected), + /mode 0700/ + ); + assert.equal((await stat(store)).mode & 0o7777, mode); + } + await chmod(store, 0o700); + for (const mode of [0o720, 0o1777]) { + await chmod(root, mode); + await assert.rejects( + withCheckpointDirectory(store, unexpected, unexpected), + /Untrusted checkpoint directory ancestor/ + ); + } + await chmod(root, 0o700); + await assertReusable(store); + assert.deepEqual(await readdir(store), []); + } +); + +test( + 'checkpoint reservation rejects a non-local-ext4/XFS fixture before the verifier', + { + ...options, + skip: !linux || !unsupported, + }, + async t => { + const path = await fixture(t, unsupported); + await assert.rejects( + withCheckpointDirectory(path, unexpected, unexpected), + /requires a local ext4 or XFS filesystem/ + ); + } +); + +test( + 'checkpoint reservation unwinds verifier, operation and release failures', + options, + async t => { + const path = await fixture(t); + const failure = new Error('synthetic failure'); + await assert.rejects( + withCheckpointDirectory( + path, + async () => { + await assert.rejects( + withCheckpointDirectory(path, unexpected, unexpected), + ProcessLockBusyError + ); + throw failure; + }, + unexpected + ), + error => error === failure + ); + await assertReusable(path); + + let borrowed: string | undefined; + let released = false; + await assert.rejects( + withCheckpointDirectory( + path, + async directory => { + const current = await stat(path, { bigint: true }); + assert.equal(directory.path, path); + assert.equal(directory.dev, current.dev); + assert.equal(directory.ino, current.ino); + assert.match(directory.mountId, /^\d+$/); + return async () => { + await assert.rejects( + withCheckpointDirectory( + path, + unexpected, + unexpected + ), + ProcessLockBusyError + ); + released = true; + }; + }, + async fd => { + borrowed = fd; + throw failure; + } + ), + error => error === failure + ); + assert.ok(released); + assert.ok(borrowed); + await assert.rejects(stat(borrowed), { code: 'ENOENT' }); + await assertReusable(path); + + await assert.rejects( + withCheckpointDirectory( + path, + async () => () => { + throw failure; + }, + async () => {} + ), + error => error === failure + ); + await assertReusable(path); + } +); + +test( + 'checkpoint reservation revalidates the pinned directory after isolation and releases pins on mismatch', + options, + async t => { + const root = await fixture(t); + const path = join(root, 'store'); + const moved = join(root, 'moved'); + await mkdir(path, { mode: 0o700 }); + let released = false; + await assert.rejects( + withCheckpointDirectory( + path, + async () => { + await rename(path, moved); + await mkdir(path, { mode: 0o700 }); + return () => { + released = true; + }; + }, + unexpected + ), + /changed during reservation/ + ); + assert.ok(released); + await assertReusable(moved); + await assertReusable(path); + + released = false; + await assert.rejects( + withCheckpointDirectory( + path, + async () => { + await chmod(path, 0o750); + return () => { + released = true; + }; + }, + unexpected + ), + /mode 0700/ + ); + assert.ok(released); + await chmod(path, 0o700); + await assertReusable(path); + + released = false; + await assert.rejects( + withCheckpointDirectory( + path, + async () => { + await chmod(root, 0o720); + return () => { + released = true; + }; + }, + unexpected + ), + /Untrusted checkpoint directory ancestor/ + ); + assert.ok(released); + await chmod(root, 0o700); + await assertReusable(path); + } +); + +test( + 'checkpoint reservation contends across processes during the async operation and recovers after process exit', + options, + async t => { + const path = await fixture(t); + const url = new URL('./checkpoint-directory.js', import.meta.url).href; + const child = spawn( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { setTimeout as delay } from 'node:timers/promises'; + import { withCheckpointDirectory } from ${JSON.stringify(url)}; + await withCheckpointDirectory(process.argv[1], async () => () => {}, async () => { + process.send('reserved'); + await delay(30_000); + }); + `, + path, + ], + { stdio: ['ignore', 'ignore', 'inherit', 'ipc'] } + ); + const closed = once(child, 'close'); + t.after(async () => { + child.kill('SIGKILL'); + await closed; + }); + const [ready] = await Promise.race([ + once(child, 'message', { signal: t.signal }), + closed.then(([code, signal]) => + assert.fail(`Owner exited before reserving: ${code}/${signal}`) + ), + ]); + assert.equal(ready, 'reserved'); + await assert.rejects( + withCheckpointDirectory(path, unexpected, unexpected), + ProcessLockBusyError + ); + child.kill('SIGKILL'); + assert.deepEqual(await closed, [null, 'SIGKILL']); + await assertReusable(path); + assert.deepEqual(await readdir(path), []); + } +); diff --git a/packages/code/src/checkpoint-directory.ts b/packages/code/src/checkpoint-directory.ts new file mode 100644 index 00000000..f4748057 --- /dev/null +++ b/packages/code/src/checkpoint-directory.ts @@ -0,0 +1,234 @@ +import { constants } from 'node:fs'; +import { open, readlink, statfs } from 'node:fs/promises'; +import type { BigIntStats } from 'node:fs'; +import type { FileHandle } from 'node:fs/promises'; + +import { readLinuxMountInfo } from './identity-mount.js'; +import { ProcessLockBusyError, tryLockDescriptor } from './process-lock.js'; + +const MAX_PATH_BYTES = 4095; +const MAX_COMPONENTS = 64; +const DIRECTORY = + constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; +const PROC_SUPER_MAGIC = 0x9fa0n; +const EXT4_SUPER_MAGIC = 0xef53n; +const XFS_SUPER_MAGIC = 0x58465342n; + +interface CheckpointDirectory { + readonly path: string; + readonly dev: bigint; + readonly ino: bigint; + readonly mountId: string; +} + +/** + * Must complete isolation admission against all grants and keep them pinned + * through the operation. A rejection must roll back any partial pins; on + * success the reservation calls the returned release function even if its + * subsequent revalidation or operation fails. + */ +type VerifyIsolation = ( + directory: CheckpointDirectory +) => Promise<() => void | Promise>; + +function components(path: string): string[] { + if ( + typeof path !== 'string' || + path.length > MAX_PATH_BYTES || + Buffer.byteLength(path) > MAX_PATH_BYTES || + !path.startsWith('/') || + Buffer.from(path).toString('utf8') !== path || + path.includes('\0') + ) { + throw new Error('Invalid checkpoint directory path'); + } + const parts = path.slice(1).split('/'); + if ( + parts.length > MAX_COMPONENTS || + parts.some( + part => + !part || + part === '.' || + part === '..' || + Buffer.byteLength(part) > 255 + ) + ) { + throw new Error('Invalid checkpoint directory path'); + } + return parts; +} + +function descriptor(handle: FileHandle): string { + return `/proc/self/fd/${handle.fd}`; +} + +function assertOwned(status: BigIntStats, uid: bigint): void { + if ( + !status.isDirectory() || + status.uid !== uid || + (status.mode & 0o7777n) !== 0o700n + ) { + throw new Error( + 'Checkpoint directory must be owned by the worker with mode 0700' + ); + } +} + +async function openDirectory( + parts: readonly string[], + uid: bigint +): Promise { + let handle = await open('/', DIRECTORY); + try { + for (const part of parts) { + const status = await handle.stat({ bigint: true }); + if ( + (status.uid !== 0n && status.uid !== uid) || + (status.mode & 0o022n) !== 0n + ) { + throw new Error('Untrusted checkpoint directory ancestor'); + } + const parent = handle; + handle = await open(`${descriptor(parent)}/${part}`, DIRECTORY); + await parent.close(); + } + return handle; + } catch (error) { + await handle.close(); + throw error; + } +} + +async function mountId(handle: FileHandle): Promise { + const info = await open(`/proc/self/fdinfo/${handle.fd}`, 'r'); + try { + const limit = 4096; + const buffer = Buffer.alloc(limit); + let length = 0; + while (length < limit) { + const { bytesRead } = await info.read( + buffer, + length, + limit - length, + null + ); + if (bytesRead === 0) break; + length += bytesRead; + } + const ids = [ + ...buffer + .toString('ascii', 0, length) + .matchAll(/^mnt_id:\s*([0-9]+)$/gm), + ]; + if (length === limit || ids.length !== 1) { + throw new Error('Cannot identify checkpoint directory mount'); + } + return ids[0][1]; + } finally { + await info.close(); + } +} + +async function assertFilesystem(handle: FileHandle, id: string): Promise { + const { type } = await statfs(descriptor(handle), { bigint: true }); + if (type !== EXT4_SUPER_MAGIC && type !== XFS_SUPER_MAGIC) { + throw new Error( + 'Checkpoint directory requires a local ext4 or XFS filesystem' + ); + } + // The magic is shared by ext2/3/4; use the pinned descriptor's mount ID, + // not the path or device alone, to corroborate the mounted driver. + const matches = (await readLinuxMountInfo()) + .split('\n') + .filter(line => line.startsWith(`${id} `)); + const filesystem = type === EXT4_SUPER_MAGIC ? 'ext4' : 'xfs'; + if ( + matches.length !== 1 || + matches[0].split(' - ')[1]?.split(' ')[0] !== filesystem + ) { + throw new Error( + 'Checkpoint directory requires a local ext4 or XFS filesystem' + ); + } +} + +async function revalidate( + handle: FileHandle, + directory: CheckpointDirectory, + parts: readonly string[], + uid: bigint +): Promise { + const current = await openDirectory(parts, uid); + try { + const status = await current.stat({ bigint: true }); + assertOwned(status, uid); + assertOwned(await handle.stat({ bigint: true }), uid); + if ( + status.dev !== directory.dev || + status.ino !== directory.ino || + (await mountId(current)) !== directory.mountId || + !( + await readlink(descriptor(current), { encoding: 'buffer' }) + ).equals(Buffer.from(directory.path)) + ) { + throw new Error('Checkpoint directory changed during reservation'); + } + } finally { + await current.close(); + } +} + +/** + * Reserves an existing directory against cooperating processes only. Assumes + * trusted Linux procfs and mount administration. Ownership, inode checks and + * flock are not isolation from the worker UID, privileged actors or aliases; + * the mandatory verifier supplies admission and pins the grant set. + * The operation gets a borrowed descriptor path, valid only until it settles; + * use it only in this process, and do not expose it to untrusted code, retain it, + * or duplicate its descriptor. + */ +export async function withCheckpointDirectory( + path: string, + verifyIsolation: VerifyIsolation, + operation: (descriptorPath: string) => Promise +): Promise { + if (process.platform !== 'linux' || process.geteuid === undefined) { + throw new Error('Checkpoint directory reservation requires Linux'); + } + const parts = components(path); + if ( + (await statfs('/proc/self/fd', { bigint: true })).type !== + PROC_SUPER_MAGIC + ) { + throw new Error('Checkpoint directory reservation requires procfs'); + } + const uid = BigInt(process.geteuid()); + const handle = await openDirectory(parts, uid); + try { + const status = await handle.stat({ bigint: true }); + assertOwned(status, uid); + const { dev, ino } = status; + const id = await mountId(handle); + const directory = Object.freeze({ path, dev, ino, mountId: id }); + await assertFilesystem(handle, id); + if (!(await tryLockDescriptor(handle.fd))) { + throw new ProcessLockBusyError( + 'Checkpoint directory reservation is active' + ); + } + await revalidate(handle, directory, parts, uid); + const release = await verifyIsolation(directory); + if (typeof release !== 'function') + throw new Error( + 'Checkpoint isolation verifier did not return a release function' + ); + try { + await revalidate(handle, directory, parts, uid); + return await operation(descriptor(handle)); + } finally { + await release(); + } + } finally { + await handle.close(); + } +} diff --git a/packages/code/src/process-lock.ts b/packages/code/src/process-lock.ts index 6e456d50..0694c491 100644 --- a/packages/code/src/process-lock.ts +++ b/packages/code/src/process-lock.ts @@ -23,6 +23,18 @@ async function lockBinding() { return await binding; } +function tryLock(native: Awaited>, fd: number): boolean { + if (native.flock(fd, LOCK_EX | LOCK_NB) === 0) return true; + const errno = native.errno(); + if (errno === native.eagain) return false; + throw new Error(`Conversation worktree lock failed with errno ${errno}`); +} + +/** The caller owns the descriptor and releases the lock by closing it. */ +export async function tryLockDescriptor(fd: number): Promise { + return tryLock(await lockBinding(), fd); +} + /** Process-lifetime advisory lock; the kernel releases it on crash or restart. */ export async function withProcessLock( path: string, @@ -43,13 +55,7 @@ export async function withProcessLock( try { for (;;) { signal?.throwIfAborted(); - if (native.flock(handle.fd, LOCK_EX | LOCK_NB) === 0) break; - const errno = native.errno(); - if (errno !== native.eagain) { - throw new Error( - `Conversation worktree lock failed with errno ${errno}` - ); - } + if (tryLock(native, handle.fd)) break; if (!wait) throw new ProcessLockBusyError('Process lock is active'); await delay(50, undefined, { signal }); } From 66cb969773dbaea98608f2bb0d4e24e28badd8c8 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Fri, 4 Dec 2026 22:01:26 -0500 Subject: [PATCH 2/2] test(worker): Gate reservation success fixtures on filesystem support --- .../code/src/checkpoint-directory.test.ts | 56 ++++++++++++++++--- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/packages/code/src/checkpoint-directory.test.ts b/packages/code/src/checkpoint-directory.test.ts index 4b8588a5..a5a8f1a5 100644 --- a/packages/code/src/checkpoint-directory.test.ts +++ b/packages/code/src/checkpoint-directory.test.ts @@ -22,7 +22,8 @@ import { ProcessLockBusyError } from './process-lock.js'; const linux = process.platform === 'linux'; const options = { skip: !linux, timeout: 10_000 }; -const base = process.env.CHECKPOINT_TEST_ROOT ?? homedir(); +const configuredRoot = process.env.CHECKPOINT_TEST_ROOT; +const base = configuredRoot ?? homedir(); const unsupported = process.env.CHECKPOINT_TEST_UNSUPPORTED_ROOT; const admit = async () => () => {}; const unexpected = async (): Promise => @@ -34,6 +35,27 @@ async function fixture(t: TestContext, root = base): Promise { return path; } +const unsupportedFilesystem = + /^Checkpoint directory requires a local ext4 or XFS filesystem$/; + +async function supportedFixture(t: TestContext): Promise { + const path = await fixture(t); + try { + await assertReusable(path); + return path; + } catch (error) { + if ( + configuredRoot || + !(error instanceof Error) || + !unsupportedFilesystem.test(error.message) + ) + throw error; + t.skip( + 'Default fixture filesystem does not support checkpoint reservations' + ); + } +} + async function assertReusable(path: string): Promise { assert.equal( await withCheckpointDirectory(path, admit, async fd => { @@ -135,7 +157,6 @@ test( ); } await chmod(root, 0o700); - await assertReusable(store); assert.deepEqual(await readdir(store), []); } ); @@ -144,13 +165,27 @@ test( 'checkpoint reservation rejects a non-local-ext4/XFS fixture before the verifier', { ...options, - skip: !linux || !unsupported, + skip: !linux, }, async t => { const path = await fixture(t, unsupported); - await assert.rejects( - withCheckpointDirectory(path, unexpected, unexpected), - /requires a local ext4 or XFS filesystem/ + let admitted = false; + try { + await withCheckpointDirectory(path, admit, async () => { + admitted = true; + }); + } catch (error) { + assert.match( + String(error instanceof Error ? error.message : error), + unsupportedFilesystem + ); + return; + } + assert.equal(admitted, true); + if (unsupported) + assert.fail('Configured unsupported fixture was admitted'); + t.skip( + 'Default fixture is supported; set CHECKPOINT_TEST_UNSUPPORTED_ROOT to test rejection' ); } ); @@ -159,7 +194,8 @@ test( 'checkpoint reservation unwinds verifier, operation and release failures', options, async t => { - const path = await fixture(t); + const path = await supportedFixture(t); + if (!path) return; const failure = new Error('synthetic failure'); await assert.rejects( withCheckpointDirectory( @@ -230,7 +266,8 @@ test( 'checkpoint reservation revalidates the pinned directory after isolation and releases pins on mismatch', options, async t => { - const root = await fixture(t); + const root = await supportedFixture(t); + if (!root) return; const path = join(root, 'store'); const moved = join(root, 'moved'); await mkdir(path, { mode: 0o700 }); @@ -295,7 +332,8 @@ test( 'checkpoint reservation contends across processes during the async operation and recovers after process exit', options, async t => { - const path = await fixture(t); + const path = await supportedFixture(t); + if (!path) return; const url = new URL('./checkpoint-directory.js', import.meta.url).href; const child = spawn( process.execPath,