Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(review): harden artifact snapshot identity

Chrisa90aae5f7bef
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 23e042e472..65548a4111 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -6783,7 +6783,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
Promise.all([
reconcileInterruptedReviews(),
sessionTurnLeaseTracker.reconcileStaleLeases(),
- cleanupOrphanedReviewArtifactSnapshots(),
+ cleanupOrphanedReviewArtifactSnapshots({ currentOwner: reviewRunOwner }),
]),
)
.then(() => undefined)
@@ -6896,6 +6896,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const prepared = await prepareStableReviewArtifactSnapshots({
workingDir: sourceWorkingDir,
grant: explicitArtifactGrant,
+ owner: reviewRunOwner,
prepare: (snapshotGrant) =>
loadReviewEvidence({
sourceSessionId: source.id,
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
index ac1376eb5c..e72693ca82 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactFingerprint.test.ts
@@ -1,4 +1,4 @@
-import { promises as fs } from 'node:fs';
+import { constants, promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -8,6 +8,7 @@ import {
fingerprintReviewArtifacts,
prepareWithStableReviewArtifacts,
ReviewArtifactChangedDuringPreparationError,
+ ReviewArtifactFingerprintChangedError,
ReviewArtifactFingerprintLimitError,
} from '../reviewArtifactFingerprint.js';
@@ -38,15 +39,37 @@ describe('review artifact fingerprint', () => {
expect(after).not.toBe(before);
});
+ it('hashes the unchanged-metadata middle of large files instead of sampling their ends', async () => {
+ const dir = await makeTempDir();
+ const file = path.join(dir, 'large.bin');
+ const fixedTime = new Date('2024-01-01T00:00:00.000Z');
+ await fs.writeFile(file, Buffer.alloc(9 * 1024 * 1024, 0x61));
+ await fs.utimes(file, fixedTime, fixedTime);
+ const beforeStat = await fs.stat(file);
+ const before = await fingerprintReviewArtifacts([file]);
+
+ const handle = await fs.open(file, 'r+');
+ try {
+ await handle.write(Buffer.from('changed!'), 0, 8, 4 * 1024 * 1024);
+ } finally {
+ await handle.close();
+ }
+ await fs.utimes(file, fixedTime, fixedTime);
+ const afterStat = await fs.stat(file);
+ const after = await fingerprintReviewArtifacts([file]);
+
+ expect(afterStat.size).toBe(beforeStat.size);
+ expect(afterStat.mtimeMs).toBe(beforeStat.mtimeMs);
+ expect(after).not.toBe(before);
+ });
+
it('uses locale-independent ordering for directory entries', async () => {
const dir = await makeTempDir();
await fs.writeFile(path.join(dir, 'z.txt'), 'z');
await fs.writeFile(path.join(dir, 'ä.txt'), 'a');
- const localeCompare = vi
- .spyOn(String.prototype, 'localeCompare')
- .mockImplementation(() => {
- throw new Error('locale-dependent ordering must not be used');
- });
+ const localeCompare = vi.spyOn(String.prototype, 'localeCompare').mockImplementation(() => {
+ throw new Error('locale-dependent ordering must not be used');
+ });
try {
await expect(fingerprintReviewArtifacts([dir])).resolves.toMatch(/^[a-f0-9]{64}$/);
@@ -89,6 +112,77 @@ describe('review artifact fingerprint', () => {
).rejects.toBeInstanceOf(ReviewArtifactFingerprintLimitError);
});
+ it('fails closed instead of using metadata when the complete-content budget is exhausted', async () => {
+ const dir = await makeTempDir();
+ const file = path.join(dir, 'draft.txt');
+ await fs.writeFile(file, '12345');
+
+ await expect(fingerprintReviewArtifacts([file], { maxContentBytes: 4 })).rejects.toBeInstanceOf(
+ ReviewArtifactFingerprintLimitError,
+ );
+ });
+
+ it('rejects an atomic replacement between lstat and open', async () => {
+ const dir = await makeTempDir();
+ const file = path.join(dir, 'approved.txt');
+ const replacement = path.join(dir, 'replacement.txt');
+ await fs.writeFile(file, 'approved bytes');
+ await fs.writeFile(replacement, 'different bytes');
+ const artifactPath = await fs.realpath(file);
+ let replaced = false;
+
+ await expect(
+ fingerprintReviewArtifacts([artifactPath], {
+ openFile: async (filePath, flags) => {
+ if (filePath === artifactPath && !replaced) {
+ replaced = true;
+ await fs.rm(file);
+ await fs.rename(replacement, file);
+ }
+ return fs.open(filePath, flags);
+ },
+ }),
+ ).rejects.toBeInstanceOf(ReviewArtifactFingerprintChangedError);
+ });
+
+ it('opens files with O_NOFOLLOW when the host supports it', async () => {
+ if (typeof constants.O_NOFOLLOW !== 'number' || constants.O_NOFOLLOW === 0) return;
+ const dir = await makeTempDir();
+ const file = path.join(dir, 'approved.txt');
+ const sensitive = path.join(dir, 'private-key');
+ await fs.writeFile(file, 'approved bytes');
+ await fs.writeFile(sensitive, 'sensitive bytes');
+ const artifactPath = await fs.realpath(file);
+ let capturedFlags = 0;
+
+ await expect(
+ fingerprintReviewArtifacts([artifactPath], {
+ openFile: async (filePath, flags) => {
+ capturedFlags = flags;
+ await fs.rm(file);
+ await fs.symlink(sensitive, file);
+ return fs.open(filePath, flags);
+ },
+ }),
+ ).rejects.toBeInstanceOf(ReviewArtifactFingerprintChangedError);
+ expect(capturedFlags & constants.O_NOFOLLOW).toBe(constants.O_NOFOLLOW);
+ });
+
+ it('does not follow a symlink that already replaced an artifact root', async () => {
+ if (process.platform === 'win32') return;
+ const dir = await makeTempDir();
+ const link = path.join(dir, 'approved.txt');
+ const sensitive = path.join(dir, 'private-key');
+ await fs.writeFile(sensitive, 'sensitive bytes');
+ await fs.symlink(sensitive, link);
+ const openFile = vi.fn((filePath: string, flags: number) => fs.open(filePath, flags));
+
+ await expect(fingerprintReviewArtifacts([link], { openFile })).resolves.toMatch(
+ /^[a-f0-9]{64}$/,
+ );
+ expect(openFile).not.toHaveBeenCalled();
+ });
+
it('rejects a same-size replacement between extraction and the first baseline', async () => {
const dir = await makeTempDir();
const file = path.join(dir, 'draft.txt');
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts
index f1abec7fef..3b7a9c00dd 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactSnapshot.test.ts
@@ -4,6 +4,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
+import type { ReviewRunOwner } from '../../../shared/reviewRun.js';
import {
reviewArtifactPathIdentity,
ReviewArtifactAuthorizationError,
@@ -19,6 +20,23 @@ import {
import { ReviewArtifactChangedDuringPreparationError } from '../reviewArtifactFingerprint.js';
const tempDirs: string[] = [];
+const TEST_OWNER: ReviewRunOwner = {
+ instanceId: 'snapshot-test-owner',
+ processId: process.pid,
+ liveness: { version: 1, port: 65_534, token: 'snapshot-test-owner-token' },
+};
+
+async function writeSnapshotOwner(
+ snapshotRoot: string,
+ owner: ReviewRunOwner,
+ createdAt = Date.now(),
+): Promise<string> {
+ const ownerPath = `${snapshotRoot}.owner.json`;
+ await fs.writeFile(ownerPath, JSON.stringify({ version: 1, createdAt, owner }), {
+ mode: 0o600,
+ });
+ return ownerPath;
+}
async function tempDir(): Promise<string> {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-review-snapshot-test-'));
@@ -67,12 +85,17 @@ describe('materializeReviewArtifactSnapshots', () => {
const materialized = await materializeReviewArtifactSnapshots({
workingDir,
grant: await grantFor([artifactPath]),
+ owner: TEST_OWNER,
});
const snapshotPath = materialized.grant.snapshotPaths?.get(artifactPath);
if (!snapshotPath) throw new Error('expected snapshot path');
await fs.writeFile(sourcePath, 'replacement version');
expect(await fs.readFile(snapshotPath, 'utf8')).toBe('authorized version');
+ const snapshotRoot = path.dirname(snapshotPath);
+ const ownerPath = `${snapshotRoot}.owner.json`;
+ await expect(fs.readdir(snapshotRoot)).resolves.not.toContain(path.basename(ownerPath));
+ await expect(fs.readFile(ownerPath, 'utf8')).resolves.toContain(TEST_OWNER.instanceId);
if (process.platform !== 'win32') {
expect((await fs.stat(path.dirname(snapshotPath))).mode & 0o777).toBe(0o700);
expect((await fs.stat(snapshotPath)).mode & 0o777).toBe(0o600);
@@ -80,6 +103,7 @@ describe('materializeReviewArtifactSnapshots', () => {
await materialized.cleanup();
await expect(fs.stat(snapshotPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.stat(ownerPath)).rejects.toMatchObject({ code: 'ENOENT' });
await materialized.cleanup();
});
@@ -100,6 +124,7 @@ describe('materializeReviewArtifactSnapshots', () => {
materializeReviewArtifactSnapshots({
workingDir,
grant,
+ owner: TEST_OWNER,
}),
).rejects.toBeInstanceOf(ReviewArtifactAuthorizationError);
});
@@ -118,9 +143,9 @@ describe('materializeReviewArtifactSnapshots', () => {
await fs.rm(sourcePath);
await fs.link(sensitivePath, sourcePath);
- await expect(materializeReviewArtifactSnapshots({ workingDir, grant })).rejects.toBeInstanceOf(
- ReviewArtifactAuthorizationError,
- );
+ await expect(
+ materializeReviewArtifactSnapshots({ workingDir, grant, owner: TEST_OWNER }),
+ ).rejects.toBeInstanceOf(ReviewArtifactAuthorizationError);
});
it('rejects an atomic replacement after the original path was authorized', async () => {
@@ -135,9 +160,37 @@ describe('materializeReviewArtifactSnapshots', () => {
await fs.rename(replacementPath, sourcePath);
- await expect(materializeReviewArtifactSnapshots({ workingDir, grant })).rejects.toBeInstanceOf(
- ReviewArtifactAuthorizationError,
- );
+ await expect(
+ materializeReviewArtifactSnapshots({ workingDir, grant, owner: TEST_OWNER }),
+ ).rejects.toBeInstanceOf(ReviewArtifactAuthorizationError);
+ });
+
+ it('rejects an atomic replacement between lstat and open', async () => {
+ const workingDir = await tempDir();
+ const externalDir = await tempDir();
+ const sourcePath = path.join(externalDir, 'approved.txt');
+ const replacementPath = path.join(externalDir, 'replacement.txt');
+ await fs.writeFile(sourcePath, 'approved bytes');
+ await fs.writeFile(replacementPath, 'different bytes');
+ const artifactPath = await fs.realpath(sourcePath);
+ const grant = await grantFor([artifactPath]);
+ let replaced = false;
+
+ await expect(
+ materializeReviewArtifactSnapshots({
+ workingDir,
+ grant,
+ owner: TEST_OWNER,
+ openFile: async (filePath, flags) => {
+ if (filePath === artifactPath && !replaced) {
+ replaced = true;
+ await fs.rm(sourcePath);
+ await fs.rename(replacementPath, sourcePath);
+ }
+ return fs.open(filePath, flags);
+ },
+ }),
+ ).rejects.toBeInstanceOf(ReviewArtifactAuthorizationError);
});
it('does not grant an unsnapshotted external directory to a reviewer', async () => {
@@ -148,6 +201,7 @@ describe('materializeReviewArtifactSnapshots', () => {
materializeReviewArtifactSnapshots({
workingDir,
grant: await grantFor([externalDir]),
+ owner: TEST_OWNER,
}),
).rejects.toThrow('one file at a time');
});
@@ -163,6 +217,7 @@ describe('materializeReviewArtifactSnapshots', () => {
prepareStableReviewArtifactSnapshots({
workingDir,
grant: await grantFor([artifactPath]),
+ owner: TEST_OWNER,
prepare: async (snapshotGrant) => {
const snapshotPath = snapshotGrant.snapshotPaths?.get(artifactPath);
if (!snapshotPath) throw new Error('expected snapshot path');
@@ -178,15 +233,16 @@ describe('materializeReviewArtifactSnapshots', () => {
const scanRoot = await tempDir();
const deadRoot = path.join(scanRoot, 'cindy-review-artifacts-v1-424242-Ab12Cd');
const lookalikeRoot = path.join(scanRoot, 'cindy-review-artifacts-424242-Ab12Cd');
- const liveRoot = path.join(scanRoot, `cindy-review-artifacts-v1-${process.pid}-Ef34Gh`);
+ const liveRoot = path.join(scanRoot, 'cindy-review-artifacts-v1-313131-Ef34Gh');
await fs.mkdir(deadRoot);
await fs.mkdir(lookalikeRoot);
await fs.mkdir(liveRoot);
await fs.writeFile(path.join(deadRoot, 'artifact.txt'), 'stale');
await cleanupOrphanedReviewArtifactSnapshots({
+ currentOwner: TEST_OWNER,
tempRoot: scanRoot,
- isProcessAlive: (pid) => pid === process.pid,
+ processIsAlive: (pid) => pid === 313131,
});
await expect(fs.lstat(deadRoot)).rejects.toMatchObject({ code: 'ENOENT' });
@@ -204,14 +260,79 @@ describe('materializeReviewArtifactSnapshots', () => {
await fs.symlink(targetRoot, linkPath);
await cleanupOrphanedReviewArtifactSnapshots({
+ currentOwner: TEST_OWNER,
tempRoot: scanRoot,
- isProcessAlive: () => false,
+ processIsAlive: () => false,
});
await expect(fs.lstat(linkPath)).resolves.toMatchObject({ mode: expect.any(Number) });
await expect(fs.readFile(targetFile, 'utf8')).resolves.toBe('keep');
});
+ it('reaps a crashed v2 snapshot even when its PID belongs to another live process', async () => {
+ const scanRoot = await tempDir();
+ const staleRoot = path.join(scanRoot, 'cindy-review-artifacts-v2-424242-Kl78Mn');
+ const staleOwner: ReviewRunOwner = {
+ instanceId: 'crashed-owner',
+ processId: 424242,
+ liveness: { version: 1, port: 12_345, token: 'crashed-owner-token' },
+ };
+ await fs.mkdir(staleRoot);
+ const ownerPath = await writeSnapshotOwner(staleRoot, staleOwner);
+ await fs.writeFile(path.join(staleRoot, 'artifact.txt'), 'sensitive snapshot');
+
+ await cleanupOrphanedReviewArtifactSnapshots({
+ currentOwner: TEST_OWNER,
+ tempRoot: scanRoot,
+ processIsAlive: () => true,
+ ownerLivenessProbe: (owner) =>
+ owner.instanceId === staleOwner.instanceId ? 'ended' : 'unknown',
+ });
+
+ await expect(fs.lstat(staleRoot)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fs.lstat(ownerPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('preserves a v2 snapshot owned by the exact live Main instance', async () => {
+ const scanRoot = await tempDir();
+ const liveRoot = path.join(scanRoot, 'cindy-review-artifacts-v2-424242-Op90Qr');
+ const liveOwner: ReviewRunOwner = {
+ instanceId: 'live-owner',
+ processId: 424242,
+ liveness: { version: 1, port: 23_456, token: 'live-owner-token-1' },
+ };
+ await fs.mkdir(liveRoot);
+ const ownerPath = await writeSnapshotOwner(liveRoot, liveOwner);
+
+ await cleanupOrphanedReviewArtifactSnapshots({
+ currentOwner: TEST_OWNER,
+ tempRoot: scanRoot,
+ processIsAlive: () => true,
+ ownerLivenessProbe: () => 'alive',
+ });
+
+ await expect(fs.lstat(liveRoot)).resolves.toBeDefined();
+ await expect(fs.lstat(ownerPath)).resolves.toBeDefined();
+ });
+
+ it('bounds cleanup of an unverifiable legacy snapshot whose PID stays alive', async () => {
+ const scanRoot = await tempDir();
+ const staleRoot = path.join(scanRoot, 'cindy-review-artifacts-v1-424242-St12Uv');
+ const now = Date.now() + 10_000;
+ await fs.mkdir(staleRoot);
+ await fs.utimes(staleRoot, new Date(1_000), new Date(1_000));
+
+ await cleanupOrphanedReviewArtifactSnapshots({
+ currentOwner: TEST_OWNER,
+ tempRoot: scanRoot,
+ processIsAlive: () => true,
+ now: () => now,
+ maxUnverifiableAgeMs: 1_000,
+ });
+
+ await expect(fs.lstat(staleRoot)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
it('removes active snapshots during normal process cleanup', async () => {
const workingDir = await tempDir();
const externalDir = await tempDir();
@@ -221,6 +342,7 @@ describe('materializeReviewArtifactSnapshots', () => {
const materialized = await materializeReviewArtifactSnapshots({
workingDir,
grant: await grantFor([artifactPath]),
+ owner: TEST_OWNER,
});
const snapshotPath = materialized.grant.snapshotPaths?.get(artifactPath);
if (!snapshotPath) throw new Error('expected snapshot path');
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
index a3dff919fd..e3661cba79 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactFingerprint.ts
@@ -1,28 +1,75 @@
import { createHash } from 'node:crypto';
-import { promises as fs, type Stats } from 'node:fs';
+import { constants, promises as fs, type Stats } from 'node:fs';
import path from 'node:path';
import { isReviewSensitiveCredentialPath } from '@cindy/maker-core';
+import { reviewArtifactPathIdentityMatches } from './reviewArtifactAuthorization.js';
+
const MAX_DIRECTORY_ENTRIES = 10_000;
-const MAX_FULL_FILE_BYTES = 8 * 1024 * 1024;
-const LARGE_FILE_SAMPLE_BYTES = 1024 * 1024;
const READ_CHUNK_BYTES = 128 * 1024;
const MAX_TOTAL_CONTENT_BYTES = 128 * 1024 * 1024;
+const NOFOLLOW_FLAG = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0;
+
+export type ReviewArtifactFileOpener = (
+ filePath: string,
+ flags: number,
+) => ReturnType<typeof fs.open>;
interface FingerprintState {
hash: ReturnType<typeof createHash>;
entries: number;
maxDirectoryEntries: number;
contentBytesRemaining: number;
+ openFile: ReviewArtifactFileOpener;
}
export interface ReviewArtifactFingerprintOptions {
/** Test seam; production uses the bounded fail-closed default. */
maxDirectoryEntries?: number;
+ /** Test seam; production hashes at most the bounded total before failing closed. */
+ maxContentBytes?: number;
+ /** Test seam for deterministic lstat/open replacement coverage. */
+ openFile?: ReviewArtifactFileOpener;
}
export class ReviewArtifactFingerprintLimitError extends Error {}
+export class ReviewArtifactFingerprintChangedError extends Error {}
+
+async function assertCanonicalReviewArtifactPath(absolutePath: string): Promise<void> {
+ const canonicalPath = await fs.realpath(absolutePath).catch(() => null);
+ if (!canonicalPath || path.resolve(canonicalPath) !== path.resolve(absolutePath)) {
+ throw new ReviewArtifactFingerprintChangedError(
+ 'A review artifact path changed while its content fingerprint was being prepared',
+ );
+ }
+}
+
+async function resolveFingerprintRoot(rawPath: string): Promise<string> {
+ const normalizedPath = path.normalize(rawPath);
+ const before = await fs.lstat(normalizedPath).catch(() => null);
+ if (!before || before.isSymbolicLink()) return normalizedPath;
+
+ const canonicalPath = await fs.realpath(normalizedPath).catch(() => null);
+ if (!canonicalPath) return normalizedPath;
+ const [afterRawPath, afterCanonicalPath] = await Promise.all([
+ fs.lstat(normalizedPath).catch(() => null),
+ fs.lstat(canonicalPath).catch(() => null),
+ ]);
+ if (
+ !afterRawPath ||
+ afterRawPath.isSymbolicLink() ||
+ !afterCanonicalPath ||
+ afterCanonicalPath.isSymbolicLink() ||
+ !reviewArtifactPathIdentityMatches(before, afterRawPath) ||
+ !reviewArtifactPathIdentityMatches(before, afterCanonicalPath)
+ ) {
+ throw new ReviewArtifactFingerprintChangedError(
+ 'A review artifact root changed while its content fingerprint was being prepared',
+ );
+ }
+ return canonicalPath;
+}
function addRecord(state: FingerprintState, ...parts: Array<string | number>): void {
state.hash.update(parts.join('\0')).update('\n');
@@ -63,37 +110,52 @@ async function addFile(
stat: Stats,
state: FingerprintState,
): Promise<void> {
- addRecord(state, 'file', relativePath, stat.size, stat.mtimeMs, stat.ctimeMs, stat.mode);
+ if (
+ !Number.isSafeInteger(stat.size) ||
+ stat.size < 0 ||
+ stat.size > state.contentBytesRemaining
+ ) {
+ throw new ReviewArtifactFingerprintLimitError(
+ 'Review artifacts exceed the complete-content fingerprint byte limit',
+ );
+ }
+
+ // Content, path, size and mode define the reusable result. Mutable file
+ // timestamps are checked for TOCTOU below, but are intentionally omitted
+ // from the digest so the regression exercises the complete content hash.
+ addRecord(state, 'file', relativePath, stat.size, stat.mode);
let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
try {
- handle = await fs.open(absolutePath, 'r');
- if (state.contentBytesRemaining <= 0) {
- addRecord(state, 'metadata-only', relativePath);
- } else if (stat.size <= MAX_FULL_FILE_BYTES && stat.size <= state.contentBytesRemaining) {
- const bytesRead = await hashRange(handle, state, 0, stat.size);
- state.contentBytesRemaining -= bytesRead;
- } else {
- const totalSample = Math.min(
- LARGE_FILE_SAMPLE_BYTES * 2,
- stat.size,
- state.contentBytesRemaining,
+ handle = await state.openFile(absolutePath, constants.O_RDONLY | NOFOLLOW_FLAG);
+ const opened = await handle.stat();
+ if (!opened.isFile() || !reviewArtifactPathIdentityMatches(stat, opened)) {
+ throw new ReviewArtifactFingerprintChangedError(
+ 'A review artifact changed while its content fingerprint was being prepared',
+ );
+ }
+
+ const bytesRead = await hashRange(handle, state, 0, opened.size);
+ const afterHandle = await handle.stat();
+ const afterPath = await fs.lstat(absolutePath).catch(() => null);
+ if (
+ bytesRead !== opened.size ||
+ !reviewArtifactPathIdentityMatches(opened, afterHandle) ||
+ !afterPath ||
+ afterPath.isSymbolicLink() ||
+ !reviewArtifactPathIdentityMatches(opened, afterPath)
+ ) {
+ throw new ReviewArtifactFingerprintChangedError(
+ 'A review artifact changed while its content fingerprint was being prepared',
);
- const firstSample = Math.ceil(totalSample / 2);
- const lastSample = totalSample - firstSample;
- let bytesRead = await hashRange(handle, state, 0, firstSample);
- if (lastSample > 0) {
- bytesRead += await hashRange(
- handle,
- state,
- Math.max(firstSample, stat.size - lastSample),
- lastSample,
- );
- }
- state.contentBytesRemaining -= bytesRead;
- addRecord(state, 'sampled', relativePath, bytesRead);
}
+ state.contentBytesRemaining -= bytesRead;
+ addRecord(state, 'file-end', relativePath, bytesRead);
} catch (error) {
- addRecord(state, 'read-error', relativePath, error instanceof Error ? error.name : 'unknown');
+ if (error instanceof ReviewArtifactFingerprintChangedError) throw error;
+ throw new ReviewArtifactFingerprintChangedError(
+ 'A review artifact could not be safely opened for content fingerprinting',
+ { cause: error },
+ );
} finally {
await handle?.close().catch(() => undefined);
}
@@ -135,6 +197,11 @@ async function walk(
addRecord(state, 'symlink', relativePath, target, stat.mtimeMs, stat.ctimeMs);
return;
}
+ if (stat.isFile() || stat.isDirectory()) {
+ // Reject an intermediate directory that became a symlink after its parent
+ // was enumerated; O_NOFOLLOW only protects the final path component.
+ await assertCanonicalReviewArtifactPath(absolutePath);
+ }
if (stat.isFile()) {
await addFile(absolutePath, relativePath, stat, state);
return;
@@ -167,8 +234,9 @@ async function walk(
/**
* Build a local-only identity for explicit review artifacts. The manifest is
- * deliberately bounded, ignores credential paths, and hashes file contents
- * (or both ends of very large files) so same-size edits are still detected.
+ * deliberately bounded, ignores credential paths, and hashes every readable
+ * file byte. Exceeding the byte budget fails closed instead of degrading to a
+ * sampled or metadata-only identity that could reuse a stale Review result.
*/
export async function fingerprintReviewArtifacts(
paths: readonly string[],
@@ -178,16 +246,21 @@ export async function fingerprintReviewArtifacts(
if (!Number.isSafeInteger(maxDirectoryEntries) || maxDirectoryEntries <= 0) {
throw new TypeError('maxDirectoryEntries must be a positive safe integer');
}
+ const maxContentBytes = options.maxContentBytes ?? MAX_TOTAL_CONTENT_BYTES;
+ if (!Number.isSafeInteger(maxContentBytes) || maxContentBytes < 0) {
+ throw new TypeError('maxContentBytes must be a non-negative safe integer');
+ }
const state: FingerprintState = {
hash: createHash('sha256'),
entries: 0,
maxDirectoryEntries,
- contentBytesRemaining: MAX_TOTAL_CONTENT_BYTES,
+ contentBytesRemaining: maxContentBytes,
+ openFile: options.openFile ?? ((filePath, flags) => fs.open(filePath, flags)),
};
const canonicalRoots = new Set<string>();
for (const rawPath of paths) {
if (!path.isAbsolute(rawPath) || isSensitive(rawPath)) continue;
- const canonical = await fs.realpath(rawPath).catch(() => path.normalize(rawPath));
+ const canonical = await resolveFingerprintRoot(rawPath);
if (!isSensitive(canonical)) canonicalRoots.add(canonical);
}
for (const root of [...canonicalRoots].sort()) {
diff --git a/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts b/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
index b1391ca142..497cec0255 100644
--- a/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
+++ b/apps/desktop/src/main/reviewer/reviewArtifactSnapshot.ts
@@ -10,15 +10,27 @@ import {
type ReviewArtifactPathIdentity,
type ReviewExplicitArtifactGrant,
} from './reviewArtifactAuthorization.js';
-import { prepareWithStableReviewArtifacts } from './reviewArtifactFingerprint.js';
+import {
+ prepareWithStableReviewArtifacts,
+ type ReviewArtifactFileOpener,
+} from './reviewArtifactFingerprint.js';
+import {
+ reviewRunOwnerStatus,
+ type ReviewOwnerLivenessProbe,
+ type ReviewProcessAliveProbe,
+} from './reviewRunRecovery.js';
+import { readReviewRunOwner, type ReviewRunOwner } from '../../shared/reviewRun.js';
const MAX_SNAPSHOT_FILE_BYTES = 64 * 1024 * 1024;
const MAX_SNAPSHOT_TOTAL_BYTES = 128 * 1024 * 1024;
const COPY_BUFFER_BYTES = 1024 * 1024;
const NOFOLLOW_FLAG = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0;
-const SNAPSHOT_ROOT_PREFIX = 'cindy-review-artifacts-v1-';
-const SNAPSHOT_ROOT_NAME = /^cindy-review-artifacts-v1-(\d+)-[A-Za-z0-9]{6}$/;
-const ACTIVE_SNAPSHOT_ROOTS = new Set<string>();
+const SNAPSHOT_ROOT_PREFIX = 'cindy-review-artifacts-v2-';
+const SNAPSHOT_ROOT_NAME = /^cindy-review-artifacts-v(1|2)-(\d+)-[A-Za-z0-9]{6}$/;
+const SNAPSHOT_OWNER_SUFFIX = '.owner.json';
+const SNAPSHOT_OWNER_MAX_BYTES = 4 * 1024;
+const DEFAULT_UNVERIFIABLE_SNAPSHOT_MAX_AGE_MS = 24 * 60 * 60 * 1_000;
+const ACTIVE_SNAPSHOT_ROOTS = new Map<string, string>();
export interface MaterializedReviewArtifacts {
grant: ReviewExplicitArtifactGrant;
@@ -52,48 +64,184 @@ function defaultProcessIsAlive(pid: number): boolean {
}
}
+interface ReviewArtifactSnapshotOwnerRecord {
+ version: 1;
+ createdAt: number;
+ owner: ReviewRunOwner;
+}
+
+function snapshotOwnerPath(snapshotRoot: string): string {
+ return `${snapshotRoot}${SNAPSHOT_OWNER_SUFFIX}`;
+}
+
+function readSnapshotOwnerRecord(value: unknown): ReviewArtifactSnapshotOwnerRecord | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ const owner = readReviewRunOwner(record.owner);
+ if (
+ record.version !== 1 ||
+ typeof record.createdAt !== 'number' ||
+ !Number.isFinite(record.createdAt) ||
+ record.createdAt <= 0 ||
+ !owner
+ ) {
+ return null;
+ }
+ return { version: 1, createdAt: record.createdAt, owner };
+}
+
+async function loadSnapshotOwnerRecord(
+ snapshotRoot: string,
+ expectedProcessId: number,
+ currentUid: number | null,
+): Promise<ReviewArtifactSnapshotOwnerRecord | null> {
+ const ownerPath = snapshotOwnerPath(snapshotRoot);
+ const before = await fs.lstat(ownerPath).catch(() => null);
+ if (
+ !before ||
+ before.isSymbolicLink() ||
+ !before.isFile() ||
+ before.size > SNAPSHOT_OWNER_MAX_BYTES ||
+ (currentUid !== null && before.uid !== currentUid)
+ ) {
+ return null;
+ }
+
+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
+ try {
+ handle = await fs.open(ownerPath, constants.O_RDONLY | NOFOLLOW_FLAG);
+ const opened = await handle.stat();
+ if (!reviewArtifactSnapshotStatMatches(before, opened)) return null;
+ const raw = await handle.readFile({ encoding: 'utf8' });
+ const afterHandle = await handle.stat();
+ const afterPath = await fs.lstat(ownerPath).catch(() => null);
+ if (
+ !reviewArtifactSnapshotStatMatches(opened, afterHandle) ||
+ !afterPath ||
+ afterPath.isSymbolicLink() ||
+ !reviewArtifactSnapshotStatMatches(opened, afterPath)
+ ) {
+ return null;
+ }
+ const record = readSnapshotOwnerRecord(JSON.parse(raw) as unknown);
+ return record?.owner.processId === expectedProcessId ? record : null;
+ } catch {
+ return null;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+}
+
+function snapshotIsExpired(
+ stat: Stats,
+ createdAt: number | undefined,
+ now: number,
+ maxAgeMs: number,
+): boolean {
+ const lastKnownActiveAt = createdAt ?? Math.max(stat.birthtimeMs, stat.ctimeMs, stat.mtimeMs);
+ return now - lastKnownActiveAt >= maxAgeMs;
+}
+
/**
* Reclaims snapshot roots left by a terminated Cindy process. The versioned,
* PID-scoped name and ownership checks deliberately avoid broad temp cleanup.
*/
-export async function cleanupOrphanedReviewArtifactSnapshots(
- options: {
- tempRoot?: string;
- isProcessAlive?: (pid: number) => boolean;
- } = {},
-): Promise<void> {
+export async function cleanupOrphanedReviewArtifactSnapshots(options: {
+ currentOwner: ReviewRunOwner;
+ tempRoot?: string;
+ processIsAlive?: ReviewProcessAliveProbe;
+ ownerLivenessProbe?: ReviewOwnerLivenessProbe;
+ now?: () => number;
+ maxUnverifiableAgeMs?: number;
+}): Promise<void> {
const tempRoot = options.tempRoot ?? os.tmpdir();
const entries = await fs.readdir(tempRoot, { withFileTypes: true }).catch((error) => {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
throw error;
});
const currentUid = typeof process.getuid === 'function' ? process.getuid() : null;
- const isProcessAlive = options.isProcessAlive ?? defaultProcessIsAlive;
+ const processIsAlive = options.processIsAlive ?? defaultProcessIsAlive;
+ const now = options.now?.() ?? Date.now();
+ const maxUnverifiableAgeMs =
+ options.maxUnverifiableAgeMs ?? DEFAULT_UNVERIFIABLE_SNAPSHOT_MAX_AGE_MS;
+ if (!Number.isFinite(maxUnverifiableAgeMs) || maxUnverifiableAgeMs < 0) {
+ throw new TypeError('maxUnverifiableAgeMs must be a non-negative finite number');
+ }
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const match = SNAPSHOT_ROOT_NAME.exec(entry.name);
if (!match) continue;
- const ownerPid = Number(match[1]);
- if (!Number.isSafeInteger(ownerPid) || ownerPid <= 0 || ownerPid === process.pid) continue;
- if (isProcessAlive(ownerPid)) continue;
+ const snapshotVersion = Number(match[1]);
+ const ownerPid = Number(match[2]);
+ if (!Number.isSafeInteger(ownerPid) || ownerPid <= 0) continue;
const candidate = path.join(tempRoot, entry.name);
const stat = await fs.lstat(candidate).catch(() => null);
if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) continue;
if (currentUid !== null && stat.uid !== currentUid) continue;
+
+ const ownerRecord =
+ snapshotVersion === 2 ? await loadSnapshotOwnerRecord(candidate, ownerPid, currentUid) : null;
+ const owner =
+ ownerRecord?.owner ??
+ ({
+ instanceId: `legacy-snapshot:${entry.name}`,
+ processId: ownerPid,
+ } satisfies ReviewRunOwner);
+ const status = await reviewRunOwnerStatus(
+ owner,
+ options.currentOwner,
+ processIsAlive,
+ options.ownerLivenessProbe,
+ );
+ if (status === 'alive') continue;
+ if (
+ status === 'unknown' &&
+ !snapshotIsExpired(stat, ownerRecord?.createdAt, now, maxUnverifiableAgeMs)
+ ) {
+ continue;
+ }
+
await fs.rm(candidate, { recursive: true, force: true });
+ await fs.rm(snapshotOwnerPath(candidate), { force: true });
}
+
+ // A crash between root removal and sidecar removal must not leave the exact
+ // liveness challenge behind indefinitely in the shared temp directory.
+ for (const entry of entries) {
+ if (!entry.isFile() || !entry.name.endsWith(SNAPSHOT_OWNER_SUFFIX)) continue;
+ const rootName = entry.name.slice(0, -SNAPSHOT_OWNER_SUFFIX.length);
+ if (!SNAPSHOT_ROOT_NAME.test(rootName)) continue;
+ const ownerPath = path.join(tempRoot, entry.name);
+ const rootPath = path.join(tempRoot, rootName);
+ if (await fs.lstat(rootPath).catch(() => null)) continue;
+ const ownerStat = await fs.lstat(ownerPath).catch(() => null);
+ if (
+ !ownerStat ||
+ ownerStat.isSymbolicLink() ||
+ !ownerStat.isFile() ||
+ (currentUid !== null && ownerStat.uid !== currentUid)
+ ) {
+ continue;
+ }
+ await fs.rm(ownerPath, { force: true });
+ }
+}
+
+async function removeSnapshotRoot(snapshotRoot: string, ownerPath: string): Promise<void> {
+ await fs.rm(snapshotRoot, { recursive: true, force: true });
+ await fs.rm(ownerPath, { force: true });
+ ACTIVE_SNAPSHOT_ROOTS.delete(snapshotRoot);
}
/** Remove every private snapshot still owned by this Main process on clean exit. */
export async function cleanupActiveReviewArtifactSnapshots(): Promise<void> {
const failures: unknown[] = [];
await Promise.all(
- [...ACTIVE_SNAPSHOT_ROOTS].map(async (snapshotRoot) => {
+ [...ACTIVE_SNAPSHOT_ROOTS].map(async ([snapshotRoot, ownerPath]) => {
try {
- await fs.rm(snapshotRoot, { recursive: true, force: true });
- ACTIVE_SNAPSHOT_ROOTS.delete(snapshotRoot);
+ await removeSnapshotRoot(snapshotRoot, ownerPath);
} catch (error) {
failures.push(error);
}
@@ -113,8 +261,14 @@ async function copyOpenFile(
sourcePath: string,
destinationPath: string,
expectedIdentity: ReviewArtifactPathIdentity,
+ openFile: ReviewArtifactFileOpener,
): Promise<number> {
- const source = await fs.open(sourcePath, constants.O_RDONLY | NOFOLLOW_FLAG);
+ const source = await openFile(sourcePath, constants.O_RDONLY | NOFOLLOW_FLAG).catch((error) => {
+ throw new ReviewArtifactAuthorizationError(
+ 'A review artifact changed after permission was granted',
+ { cause: error },
+ );
+ });
let destination: Awaited<ReturnType<typeof fs.open>> | null = null;
try {
const canonicalPath = await fs.realpath(sourcePath);
@@ -157,7 +311,14 @@ async function copyOpenFile(
sourceOffset += bytesRead;
}
const after = await source.stat();
- if (sourceOffset !== before.size || !reviewArtifactSnapshotStatMatches(before, after)) {
+ const afterPath = await fs.lstat(sourcePath).catch(() => null);
+ if (
+ sourceOffset !== before.size ||
+ !reviewArtifactSnapshotStatMatches(before, after) ||
+ !afterPath ||
+ afterPath.isSymbolicLink() ||
+ !reviewArtifactPathIdentityMatches(expectedIdentity, afterPath)
+ ) {
throw new ReviewArtifactAuthorizationError(
'A review artifact changed while its private snapshot was being prepared',
);
@@ -179,11 +340,22 @@ async function copyOpenFile(
export async function materializeReviewArtifactSnapshots(input: {
workingDir: string;
grant: ReviewExplicitArtifactGrant;
+ owner: ReviewRunOwner;
+ /** Test seam for deterministic lstat/open replacement coverage. */
+ openFile?: ReviewArtifactFileOpener;
}): Promise<MaterializedReviewArtifacts> {
+ if (
+ !readReviewRunOwner(input.owner) ||
+ input.owner.processId !== process.pid ||
+ !input.owner.liveness
+ ) {
+ throw new Error('Review artifact snapshot owner is not ready');
+ }
const canonicalWorkingDir = await fs.realpath(input.workingDir).catch(() => null);
const snapshotPaths = new Map<string, string>();
const liveDirectoryPaths: string[] = [];
let snapshotRoot: string | null = null;
+ let ownerPath: string | null = null;
let cleaned = false;
let cleanupPromise: Promise<void> | null = null;
let totalBytes = 0;
@@ -196,8 +368,7 @@ export async function materializeReviewArtifactSnapshots(input: {
}
if (!cleanupPromise) {
cleanupPromise = (async () => {
- await fs.rm(snapshotRoot!, { recursive: true, force: true });
- ACTIVE_SNAPSHOT_ROOTS.delete(snapshotRoot!);
+ await removeSnapshotRoot(snapshotRoot!, ownerPath!);
cleaned = true;
})();
}
@@ -241,17 +412,41 @@ export async function materializeReviewArtifactSnapshots(input: {
if (!snapshotRoot) {
snapshotRoot = await fs.mkdtemp(
- path.join(os.tmpdir(), `${SNAPSHOT_ROOT_PREFIX}${process.pid}-`),
+ path.join(os.tmpdir(), `${SNAPSHOT_ROOT_PREFIX}${input.owner.processId}-`),
);
- ACTIVE_SNAPSHOT_ROOTS.add(snapshotRoot);
- await fs.chmod(snapshotRoot, 0o700);
+ ownerPath = snapshotOwnerPath(snapshotRoot);
+ try {
+ await fs.chmod(snapshotRoot, 0o700);
+ const ownerRecord: ReviewArtifactSnapshotOwnerRecord = {
+ version: 1,
+ createdAt: Date.now(),
+ owner: input.owner,
+ };
+ await fs.writeFile(ownerPath, JSON.stringify(ownerRecord), {
+ encoding: 'utf8',
+ flag: constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW_FLAG,
+ mode: 0o600,
+ });
+ ACTIVE_SNAPSHOT_ROOTS.set(snapshotRoot, ownerPath);
+ } catch (error) {
+ await fs.rm(snapshotRoot, { recursive: true, force: true });
+ await fs.rm(ownerPath, { force: true });
+ snapshotRoot = null;
+ ownerPath = null;
+ throw error;
+ }
}
const key = createHash('sha256').update(sourcePath, 'utf8').digest('hex').slice(0, 16);
const destinationPath = path.join(
snapshotRoot,
`${String(index + 1).padStart(2, '0')}-${key}${safeSnapshotExtension(sourcePath)}`,
);
- totalBytes += await copyOpenFile(sourcePath, destinationPath, expectedIdentity);
+ totalBytes += await copyOpenFile(
+ sourcePath,
+ destinationPath,
+ expectedIdentity,
+ input.openFile ?? ((filePath, flags) => fs.open(filePath, flags)),
+ );
if (totalBytes > MAX_SNAPSHOT_TOTAL_BYTES) {
throw new ReviewArtifactAuthorizationError(
'Review artifacts exceed the 128 MB local snapshot limit',
@@ -282,6 +477,7 @@ export async function materializeReviewArtifactSnapshots(input: {
export async function prepareStableReviewArtifactSnapshots<T>(input: {
workingDir: string;
grant: ReviewExplicitArtifactGrant;
+ owner: ReviewRunOwner;
prepare: (snapshotGrant: ReviewExplicitArtifactGrant) => Promise<T>;
}): Promise<PreparedStableReviewArtifacts<T>> {
const holder: { materialized?: MaterializedReviewArtifacts } = {};
@@ -290,6 +486,7 @@ export async function prepareStableReviewArtifactSnapshots<T>(input: {
holder.materialized = await materializeReviewArtifactSnapshots({
workingDir: input.workingDir,
grant: input.grant,
+ owner: input.owner,
});
return input.prepare(holder.materialized.grant);
});
diff --git a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts b/apps/desktop/src/main/reviewer/reviewRunRecovery.ts
index fc0e2542fc..c71beb172d 100644
--- a/apps/desktop/src/main/reviewer/reviewRunRecovery.ts
+++ b/apps/desktop/src/main/reviewer/reviewRunRecovery.ts
@@ -8,6 +8,7 @@ export type ReviewProcessAliveProbe = (processId: number) => boolean;
export type ReviewOwnerLivenessProbe = (
owner: ReviewRunOwner,
) => ReviewOwnerLivenessProbeResult | Promise<ReviewOwnerLivenessProbeResult>;
+export type ReviewRunOwnerStatus = 'alive' | 'ended' | 'unknown';
export function isReviewProcessAlive(processId: number): boolean {
try {
@@ -18,27 +19,40 @@ export function isReviewProcessAlive(processId: number): boolean {
}
}
-export async function hasReviewOwnerProcessEnded(
+/**
+ * Classify the exact Main-process incarnation behind a persisted Review owner.
+ * Legacy PID-only owners remain unknown while that PID exists because it may
+ * already belong to an unrelated process.
+ */
+export async function reviewRunOwnerStatus(
owner: ReviewRunOwner,
currentOwner: ReviewRunOwner,
processIsAlive: ReviewProcessAliveProbe = isReviewProcessAlive,
ownerLivenessProbe: ReviewOwnerLivenessProbe = (candidate) =>
candidate.liveness ? probeReviewOwnerLiveness(candidate.liveness) : 'unknown',
-): Promise<boolean> {
- if (owner.instanceId === currentOwner.instanceId) return false;
+): Promise<ReviewRunOwnerStatus> {
+ if (owner.instanceId === currentOwner.instanceId) return 'alive';
// This process now owns the same PID, so the differently identified previous
// owner has definitely terminated even if the OS immediately reused the PID.
- if (owner.processId === currentOwner.processId) return true;
+ if (owner.processId === currentOwner.processId) return 'ended';
if (owner.liveness) {
- const result = await ownerLivenessProbe(owner);
- if (result === 'alive') return false;
- if (result === 'ended') return true;
- // A timeout or other ambiguous local transport failure must not let two
- // Desktop instances own the same Review source concurrently.
- return false;
+ return ownerLivenessProbe(owner);
}
// Compatibility for leases/cards written before exact instance probes existed.
- return !processIsAlive(owner.processId);
+ return processIsAlive(owner.processId) ? 'unknown' : 'ended';
+}
+
+export async function hasReviewOwnerProcessEnded(
+ owner: ReviewRunOwner,
+ currentOwner: ReviewRunOwner,
+ processIsAlive: ReviewProcessAliveProbe = isReviewProcessAlive,
+ ownerLivenessProbe: ReviewOwnerLivenessProbe = (candidate) =>
+ candidate.liveness ? probeReviewOwnerLiveness(candidate.liveness) : 'unknown',
+): Promise<boolean> {
+ return (
+ (await reviewRunOwnerStatus(owner, currentOwner, processIsAlive, ownerLivenessProbe)) ===
+ 'ended'
+ );
}
/**