Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): reject unmanifested snapshot files

[._.]/ Adam Eivy51e27a9dfa35
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 69f3360179..bf935342d9 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -67,7 +67,7 @@ A backup run that fails after creating its snapshot directory records a durable
### Files — `restoreSnapshot()`
-Before rsync can read or overwrite live data, PortOS strictly reads `manifest.json`, validates every manifest path and SHA-256 value, and hashes every recorded regular file in the selected restore scope. A missing, unreadable, or mismatching selected file refuses both preview and execution before rsync starts. Selective restore verifies only its literal selected subtree and ignores the separately handled `../portos-db.sql` entry. The same preflight runs again for execution, so changing snapshot bytes after a successful preview cannot bypass verification. Readable symlinks retain the hash behavior used when the manifest was created; dangling symlinks remain outside the regular-file manifest and retain rsync's archive compatibility.
+Before rsync can read or overwrite live data, PortOS strictly reads `manifest.json`, validates every manifest path and SHA-256 value, and hashes every recorded regular file in the selected restore scope. A missing, unreadable, mismatching, or unrecorded selected file refuses both preview and execution before rsync starts. Selective restore verifies only its literal selected subtree and ignores the separately handled `../portos-db.sql` entry. The same preflight runs again for execution, so changing or adding snapshot bytes after a successful preview cannot bypass verification. Readable symlinks retain the hash behavior used when the manifest was created; dangling symlinks remain outside the regular-file manifest and retain rsync's archive compatibility.
Snapshots from PortOS versions that predate `manifest.json` remain restorable as an explicit compatibility case. Restore responses report `verification.status` as `verified` (with `checkedFiles`) or `unverified` with reason `manifest_absent`; the confirmation panel warns when a legacy restore cannot be verified. An existing manifest that is malformed or unreadable fails closed and is never treated as legacy absence.
diff --git a/server/services/backup.js b/server/services/backup.js
index a98d6a2d9f..5a32cbe399 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -914,6 +914,7 @@ function manifestDataEntries(manifest, srcDir, subdirFilter) {
if (manifest.fileCount !== entries.length) return null;
const selected = [];
+ const dataPaths = new Set();
for (const [entry, expectedHash] of entries) {
if (typeof expectedHash !== 'string' || !SHA256_PATTERN.test(expectedHash)) return null;
if (entry === '../portos-db.sql') continue;
@@ -931,13 +932,15 @@ function manifestDataEntries(manifest, srcDir, subdirFilter) {
const filePath = resolve(srcDir, ...segments);
const rel = relative(resolve(srcDir), filePath);
if (!rel || rel.startsWith('..') || isAbsolute(rel)) return null;
+ if (dataPaths.has(normalized)) return null;
+ dataPaths.add(normalized);
if (!subdirFilter || normalized === subdirFilter || normalized.startsWith(`${subdirFilter}/`)) {
selected.push({ filePath, expectedHash });
}
}
- return selected;
+ return { selected, dataPaths };
}
const snapshotFileIntegrityError = (snapshotId) => new ServerError(
@@ -945,6 +948,43 @@ const snapshotFileIntegrityError = (snapshotId) => new ServerError(
{ status: 409, code: 'BACKUP_FILE_INTEGRITY_FAILED' },
);
+async function snapshotManifestFilePaths(srcDir, subdirFilter) {
+ const scopePath = subdirFilter
+ ? resolve(srcDir, ...subdirFilter.split('/'))
+ : srcDir;
+ const scopeInfo = await lstat(scopePath).catch(err => {
+ if (err?.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (!scopeInfo) return [];
+
+ const candidates = scopeInfo.isDirectory()
+ ? (await readdir(scopePath, { recursive: true })).map(entry => join(scopePath, entry))
+ : [scopePath];
+ const paths = [];
+
+ for (const filePath of candidates) {
+ const info = await stat(filePath).catch(async err => {
+ // Match generateManifest(): dangling links are intentionally outside the
+ // manifest, while readable links to regular files are hashed and tracked.
+ if (err?.code === 'ENOENT') {
+ const entryInfo = await lstat(filePath);
+ if (entryInfo.isSymbolicLink()) return null;
+ }
+ throw err;
+ });
+ if (!info?.isFile()) continue;
+
+ const normalized = relative(srcDir, filePath).replaceAll('\\', '/');
+ if (!normalized || normalized.startsWith('../') || isAbsolute(normalized)) {
+ throw new Error('Snapshot entry escaped the data directory');
+ }
+ paths.push(normalized);
+ }
+
+ return paths;
+}
+
async function verifySnapshotFiles(snapshotDir, srcDir, snapshotId, subdirFilter) {
// A unique fallback distinguishes a genuinely absent legacy manifest from an
// existing file whose parsed value is JSON null.
@@ -963,13 +1003,23 @@ async function verifySnapshotFiles(snapshotDir, srcDir, snapshotId, subdirFilter
return { status: 'unverified', reason: 'manifest_absent', checkedFiles: 0 };
}
- const selected = manifestDataEntries(manifestRead.value, srcDir, subdirFilter);
- if (!selected) {
+ const manifestEntries = manifestDataEntries(manifestRead.value, srcDir, subdirFilter);
+ if (!manifestEntries) {
throw new ServerError(`Snapshot integrity manifest is invalid: ${snapshotId}`, {
status: 409,
code: 'BACKUP_MANIFEST_INVALID',
});
}
+ const { selected, dataPaths } = manifestEntries;
+
+ // Hash agreement is insufficient if rsync can also copy files the manifest
+ // never recorded. Rebuild the same regular-file inventory in the selected
+ // scope and reject additions before rsync reads or overwrites anything.
+ const snapshotPaths = await snapshotManifestFilePaths(srcDir, subdirFilter)
+ .catch(() => null);
+ if (!snapshotPaths || snapshotPaths.some(entry => !dataPaths.has(entry))) {
+ throw snapshotFileIntegrityError(snapshotId);
+ }
for (const { filePath, expectedHash } of selected) {
const info = await lstat(filePath).catch(() => null);
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 10019e3cc3..a73e4e146a 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1201,6 +1201,26 @@ describe('restoreSnapshot manifest verification', () => {
expect(await realFs.readFile(livePath, 'utf8')).toBe('healthy live data');
});
+ it('refuses a file added after preview when it is absent from the manifest', async () => {
+ const relativePath = 'restore-integrity/example.json';
+ const originalHash = await writeSnapshotFile(relativePath, 'trusted backup');
+ await writeManifest({ [relativePath]: originalHash });
+ const livePath = joinPath(PATHS.data, relativePath);
+ await realFs.mkdir(joinPath(livePath, '..'), { recursive: true });
+ await realFs.writeFile(livePath, 'healthy live data');
+
+ await expect(finishRestore({ dryRun: true })).resolves.toMatchObject({
+ verification: { status: 'verified', checkedFiles: 1 },
+ });
+
+ await writeSnapshotFile('restore-integrity/unrecorded.json', 'added after backup');
+ spawn.mockReset();
+ await expect(restoreSnapshot(tmpRoot, 'snap-1', { dryRun: false }))
+ .rejects.toMatchObject({ code: 'BACKUP_FILE_INTEGRITY_FAILED' });
+ expect(spawn).not.toHaveBeenCalled();
+ expect(await realFs.readFile(livePath, 'utf8')).toBe('healthy live data');
+ });
+
it.each([
['missing', async (path) => realFs.unlink(path)],
['unreadable', async (path) => {
@@ -1235,6 +1255,16 @@ describe('restoreSnapshot manifest verification', () => {
});
});
+ it('ignores an unrecorded file outside a literal selective scope', async () => {
+ const brainHash = await writeSnapshotFile('brain/example.json', 'brain');
+ await writeSnapshotFile('media/unrecorded.json', 'outside selection');
+ await writeManifest({ 'brain/example.json': brainHash });
+
+ await expect(finishRestore({ dryRun: true, subdirFilter: 'brain' })).resolves.toMatchObject({
+ verification: { status: 'verified', checkedFiles: 1 },
+ });
+ });
+
it.each([
['malformed JSON', '{"files":'],
['a null root', 'null'],