diff --git a/packages/code/src/checkpoint-catalog.test.ts b/packages/code/src/checkpoint-catalog.test.ts new file mode 100644 index 00000000..3209664d --- /dev/null +++ b/packages/code/src/checkpoint-catalog.test.ts @@ -0,0 +1,284 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { constants } from 'node:fs'; +import { + chmod, + link, + mkdir, + mkdtemp, + open, + readdir, + rename, + rm, + stat, + symlink, + truncate, + unlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import type { TestContext } from 'node:test'; + +import { CheckpointCatalog } from './checkpoint-catalog.js'; + +const skip = process.platform !== 'linux'; +const flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; +const old = Buffer.from('old'); +const next = Buffer.from('new'); +const ceiling = 1024 * 1024; + +async function fixture(t: TestContext) { + const dir = await mkdtemp(join(tmpdir(), 'checkpoint-catalog-')); + const path = join(dir, 'catalog-dir'); + await mkdir(path, { mode: 0o700 }); + const root = await open(path, flags); + t.after(async () => { + await root.close(); + await rm(dir, { recursive: true, force: true }); + }); + return { dir, path, root, file: join(path, 'catalog') }; +} + +test( + 'initialization is explicit, replacement changes inode, and reopened bytes are isolated', + { skip }, + async t => { + const { root, file, path } = await fixture(t); + await assert.rejects(CheckpointCatalog.open(root), { code: 'ENOENT' }); + const store = await CheckpointCatalog.initialize(root, old); + await assert.rejects( + CheckpointCatalog.initialize(root, next), + /already exists/ + ); + const prior = await stat(file); + assert.equal(prior.mode & 0o7777, 0o600); + assert.equal(prior.nlink, 1); + assert.deepEqual(await store.read(), old); + const input = Buffer.from(next); + const replacement = store.replace(input); + input.fill(0); + await assert.rejects(store.read(), /unavailable/); + await replacement; + assert.notEqual((await stat(file)).ino, prior.ino); + const reopened = await CheckpointCatalog.open(root); + (await reopened.read()).fill(0); + assert.deepEqual(await reopened.read(), next); + assert.deepEqual(await readdir(path), ['catalog']); + } +); + +test( + 'bounds the complete on-disk record to 1 MiB, and rejects invalid input without writing', + { skip }, + async t => { + const { root, file } = await fixture(t); + await assert.rejects( + CheckpointCatalog.initialize(root, Buffer.alloc(0)), + /payload size/ + ); + const store = await CheckpointCatalog.initialize(root, old); + const header = (await stat(file)).size - old.length; + const payload = Buffer.alloc(ceiling - header, 42); + await assert.rejects( + store.replace(Buffer.alloc(payload.length + 1)), + /payload size/ + ); + assert.deepEqual(await store.read(), old); + await store.replace(payload); + assert.equal((await stat(file)).size, ceiling); + assert.deepEqual(await store.read(), payload); + await truncate(file, ceiling + 1); + await assert.rejects( + CheckpointCatalog.open(root), + /Invalid checkpoint catalog file/ + ); + } +); + +test( + 'rejects missing and corrupt replacements and never repairs them implicitly', + { skip }, + async t => { + const { root, file } = await fixture(t); + const store = await CheckpointCatalog.initialize(root, old); + const handle = await open(file, 'r+'); + try { + await handle.write( + Buffer.from('x'), + 0, + 1, + (await handle.stat()).size - 1 + ); + } finally { + await handle.close(); + } + await assert.rejects(CheckpointCatalog.open(root), /checksum/); + await assert.rejects(store.replace(next), /checksum/); + await assert.rejects(store.read(), /unavailable/); + await assert.rejects( + CheckpointCatalog.initialize(root, next), + /already exists/ + ); + await truncate(file, 0); + await assert.rejects( + CheckpointCatalog.open(root), + /Invalid checkpoint catalog file/ + ); + await unlink(file); + const reopened = await CheckpointCatalog.initialize(root, old); + await unlink(file); + await assert.rejects(reopened.replace(next), { code: 'ENOENT' }); + await assert.rejects(CheckpointCatalog.open(root), { code: 'ENOENT' }); + } +); + +test( + 'rejects non-private and non-regular catalog entries and validates the pinned directory', + { skip }, + async t => { + const { root, path, file, dir } = await fixture(t); + const saved = join(dir, 'saved'); + await rename(path, saved); + await mkdir(path, { mode: 0o700 }); + await CheckpointCatalog.initialize(root, old); + assert.deepEqual(await readdir(path), []); + assert.deepEqual(await readdir(saved), ['catalog']); + const pinned = join(saved, 'catalog'); + await chmod(saved, 0o750); + await assert.rejects( + CheckpointCatalog.open(root), + /Invalid checkpoint catalog directory/ + ); + await chmod(saved, 0o700); + await chmod(pinned, 0o640); + await assert.rejects( + CheckpointCatalog.open(root), + /Invalid checkpoint catalog file/ + ); + await chmod(pinned, 0o600); + await link(pinned, file); + await assert.rejects( + CheckpointCatalog.open(root), + /Invalid checkpoint catalog file/ + ); + await unlink(file); + await unlink(pinned); + await symlink(file, pinned); + await assert.rejects(CheckpointCatalog.open(root), { code: 'ELOOP' }); + await assert.rejects( + CheckpointCatalog.initialize(root, next), + /already exists/ + ); + await unlink(pinned); + execFileSync('mkfifo', ['-m', '600', pinned]); + await assert.rejects( + CheckpointCatalog.open(root), + /Invalid checkpoint catalog file/ + ); + } +); + +test( + 'directory sync failure quarantines the instance until a validated reopen syncs again', + { skip }, + async t => { + const { root } = await fixture(t); + const store = await CheckpointCatalog.initialize(root, old); + const sync = t.mock.method(root, 'sync', async () => { + throw new Error('injected sync failure'); + }); + await assert.rejects(store.replace(next), /injected sync failure/); + await assert.rejects(store.read(), /unavailable/); + await assert.rejects(store.replace(old), /unavailable/); + await assert.rejects( + CheckpointCatalog.open(root), + /injected sync failure/ + ); + assert.equal(sync.mock.callCount(), 2); + sync.mock.restore(); + const reopened = await CheckpointCatalog.open(root); + assert.deepEqual(await reopened.read(), next); + await reopened.replace(old); + assert.deepEqual(await reopened.read(), old); + } +); + +test( + 'an existing temp is never followed or removed, including before initialization', + { skip }, + async t => { + const { root, dir, path } = await fixture(t); + const other = join(dir, 'other'); + await writeFile(other, 'other', { mode: 0o600 }); + const temp = join(path, '.catalog.tmp'); + await symlink(other, temp); + await assert.rejects(CheckpointCatalog.initialize(root, old), { + code: 'EEXIST', + }); + await assert.rejects(CheckpointCatalog.open(root), { code: 'ENOENT' }); + assert.deepEqual(await readdir(path), ['.catalog.tmp']); + assert.equal((await stat(other)).size, 5); + } +); + +for (const phase of ['file-synced', 'renamed', 'committed']) { + test( + `reopen after SIGKILL with replacement ${phase}`, + { skip }, + async t => { + const { root, path } = await fixture(t); + await CheckpointCatalog.initialize(root, old); + const result = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { open } from 'node:fs/promises'; + import { CheckpointCatalog } from ${JSON.stringify( + new URL('./checkpoint-catalog.js', import.meta.url).href + )}; + const root = await open(process.argv[1], ${flags}); + const store = await CheckpointCatalog.open(root); + const kill = () => process.kill(process.pid, 'SIGKILL'); + if (process.argv[2] === 'file-synced') { + const handle = await open(process.argv[1], ${flags}); + const proto = Object.getPrototypeOf(handle); + const sync = proto.sync; + await handle.close(); + proto.sync = async function () { await sync.call(this); kill(); }; + } else if (process.argv[2] === 'renamed') { + root.sync = async () => { kill(); }; + } + await store.replace(Buffer.from('new')); + kill(); + `, + path, + phase, + ], + { encoding: 'utf8', timeout: 10000 } + ); + assert.equal(result.signal, 'SIGKILL', result.stderr); + const reopened = await CheckpointCatalog.open(root); + if (phase === 'file-synced') { + assert.deepEqual(await reopened.read(), old); + assert.deepEqual((await readdir(path)).sort(), [ + '.catalog.tmp', + 'catalog', + ]); + await assert.rejects(reopened.replace(next), { + code: 'EEXIST', + }); + assert.deepEqual((await readdir(path)).sort(), [ + '.catalog.tmp', + 'catalog', + ]); + } else { + assert.deepEqual(await reopened.read(), next); + assert.deepEqual(await readdir(path), ['catalog']); + } + } + ); +} diff --git a/packages/code/src/checkpoint-catalog.ts b/packages/code/src/checkpoint-catalog.ts new file mode 100644 index 00000000..72ac44c5 --- /dev/null +++ b/packages/code/src/checkpoint-catalog.ts @@ -0,0 +1,182 @@ +import { createHash } from 'node:crypto'; +import { constants } from 'node:fs'; +import { lstat, open, rename } from 'node:fs/promises'; +import type { FileHandle } from 'node:fs/promises'; + +const ceiling = 1024 * 1024; +const magic = Buffer.from('librechat/checkpoint-catalog/v1\0'); +const header = magic.length + 32; +const catalog = 'catalog'; +const temporary = '.catalog.tmp'; + +function checksum(payload: Buffer): Buffer { + return createHash('sha256').update(magic).update(payload).digest(); +} + +function encode(payload: Buffer): Buffer { + if (!payload.length || payload.length > ceiling - header) { + throw new Error('Invalid checkpoint catalog payload size'); + } + const bytes = Buffer.alloc(header + payload.length); + magic.copy(bytes); + payload.copy(bytes, header); + checksum(bytes.subarray(header)).copy(bytes, magic.length); + return bytes; +} + +async function read(path: string): Promise { + const uid = process.geteuid?.(); + const file = await open( + path, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK + ); + try { + const info = await file.stat(); + const { size, mode, uid: owner, nlink } = info; + if ( + !info.isFile() || + owner !== uid || + (mode & 0o7777) !== 0o600 || + nlink !== 1 || + size <= header || + size > ceiling + ) { + throw new Error('Invalid checkpoint catalog file'); + } + const bytes = Buffer.alloc(size); + let offset = 0; + while (offset < size) { + const { bytesRead } = await file.read( + bytes, + offset, + size - offset, + offset + ); + if (!bytesRead) throw new Error('Truncated checkpoint catalog'); + offset += bytesRead; + } + const payload = bytes.subarray(header); + if ( + (await file.stat()).size !== size || + !bytes.subarray(0, magic.length).equals(magic) || + !bytes.subarray(magic.length, header).equals(checksum(payload)) + ) { + throw new Error('Invalid checkpoint catalog checksum or version'); + } + return payload; + } finally { + await file.close(); + } +} + +async function assertAbsent(path: string): Promise { + try { + await lstat(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; + throw error; + } + throw new Error('Checkpoint catalog already exists'); +} + +/** + * Internal opaque storage, not retention policy. The caller validates payload + * semantics and supplies a borrowed, syncable Linux directory handle on a + * supported durable local filesystem and trusted procfs. It must hold an + * exclusive lease for the entire use of this instance, keep the directory + * private from all tools, and allow no other catalog instance or writer to + * access it concurrently. Never retain this object past that lease. + * + * A leftover temp is not a catalog. It blocks writes without blocking reads + * of a valid catalog. Only separate recovery may assess or remove it. + */ +export class CheckpointCatalog { + private busy = false; + private failed = false; + + private constructor(private readonly root: FileHandle) {} + + /** For a known new catalog only, never a fallback when reopening fails. */ + static async initialize( + root: FileHandle, + payload: Buffer + ): Promise { + const store = new CheckpointCatalog(root); + await store.publish(encode(payload), true); + return store; + } + + /** Revalidate the published file and confirm the directory entry is durable. */ + static async open(root: FileHandle): Promise { + const store = new CheckpointCatalog(root); + await store.read(); + await root.sync(); + return store; + } + + read(): Promise { + return this.run(directory => read(`${directory}/${catalog}`)); + } + + async replace(payload: Buffer): Promise { + await this.publish(encode(payload), false); + } + + private publish(bytes: Buffer, initialize: boolean): Promise { + return this.run(async directory => { + const path = `${directory}/${catalog}`; + const temp = `${directory}/${temporary}`; + if (initialize) await assertAbsent(path); + else await read(path); + + // The fixed exclusive name bounds abandoned staging to one file. + const file = await open( + temp, + constants.O_WRONLY | + constants.O_CREAT | + constants.O_EXCL | + constants.O_NOFOLLOW, + 0o600 + ); + try { + await file.chmod(0o600); + await file.writeFile(bytes); + await file.sync(); + } finally { + await file.close(); + } + // The lease holds across the destination check and publish. No + // writes to the old or newly published inode, nor rollback on error. + await rename(temp, path); + await this.root.sync(); + }); + } + + private async run( + operation: (directory: string) => Promise + ): Promise { + if (this.failed || this.busy) + throw new Error('Checkpoint catalog unavailable'); + this.busy = true; + try { + const uid = process.geteuid?.(); + if (process.platform !== 'linux' || uid === undefined) { + throw new Error('Checkpoint catalog requires Linux'); + } + const info = await this.root.stat(); + if ( + !info.isDirectory() || + info.uid !== uid || + (info.mode & 0o7777) !== 0o700 + ) { + throw new Error('Invalid checkpoint catalog directory'); + } + return await operation(`/proc/self/fd/${this.root.fd}`); + } catch (error) { + this.failed = true; + throw error; + } finally { + this.busy = false; + } + } +}