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

fix: refuse unreadable database restore manifests (#7164)

[._.]/ Adam Eivy901abcd0efdb
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index 20b6d84f6f..28e831c236 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -204,9 +204,12 @@ export function BackupTab() {
return;
}
if (preview.status !== 'ok') {
- toast.error(preview.reason === 'manifest_mismatch'
+ const message = preview.reason === 'manifest_mismatch'
? 'Snapshot dump failed integrity verification'
- : `DB restore unavailable: ${preview.reason || 'unknown'}`);
+ : preview.reason === 'manifest_unreadable'
+ ? 'Snapshot verification metadata could not be read. Choose another snapshot or repair the backup media before retrying.'
+ : `DB restore unavailable: ${preview.reason || 'unknown'}`;
+ toast.error(message);
return;
}
setRestorePreview(preview);
diff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsx
index a758e14a5c..ee9d45ca6a 100644
--- a/client/src/components/settings/BackupTab.test.jsx
+++ b/client/src/components/settings/BackupTab.test.jsx
@@ -209,6 +209,22 @@ describe('BackupTab', () => {
expect(toast.error).toHaveBeenCalledWith('Snapshot dump failed integrity verification');
expect(screen.queryByText(/Restore database\?/i)).toBeNull();
});
+
+ it('explains an unreadable integrity manifest and does not open confirmation', async () => {
+ withSnapshot();
+ restoreDatabase.mockResolvedValue({ status: 'failed', reason: 'manifest_unreadable' });
+ await renderTab();
+
+ await act(async () => {
+ fireEvent.click(await screen.findByRole('button', { name: /Restore DB/i }));
+ });
+
+ expect(restoreDatabase).toHaveBeenCalledTimes(1);
+ expect(toast.error).toHaveBeenCalledWith(
+ 'Snapshot verification metadata could not be read. Choose another snapshot or repair the backup media before retrying.'
+ );
+ expect(screen.queryByText(/Restore database\?/i)).toBeNull();
+ });
});
describe('Run Now gating (saved state)', () => {
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 9601b95c6a..52f85d169c 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -78,6 +78,7 @@ Replays the snapshot's `portos-db.sql` into the live database via `psql -v ON_ER
| `{ status: 'ok', dryRun, sizeBytes, tableCount }` | Dry-run report, or a successful real restore |
| `{ status: 'skipped', reason: 'no_dump' }` | No `portos-db.sql` in the snapshot (or 0 bytes) |
| `{ status: 'skipped', reason: 'not_configured' }` | Real restore requested but Postgres is unreachable — refuses to half-restore |
+| `{ status: 'failed', reason: 'manifest_unreadable' }` | An existing `manifest.json` is corrupt or unreadable — choose another snapshot or repair the backup media before retrying |
| `{ status: 'failed', reason: 'manifest_mismatch' }` | Snapshot's `portos-db.sql` hash disagrees with `manifest.json` — dump considered untrustworthy |
| `{ status: 'failed', reason: 'restore_error', error }` | `psql` replay failed (stderr captured) |
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 909b52671f..8bcd3127a1 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -304,6 +304,7 @@ describe('backup routes', () => {
// can surface the reason — collapsing them into a 500 envelope would hide
// which check refused the restore.
it.each([
+ ['manifest_unreadable', { status: 'failed', reason: 'manifest_unreadable' }],
['manifest_mismatch', { status: 'failed', reason: 'manifest_mismatch' }],
['restore_error', { status: 'failed', reason: 'restore_error', error: 'psql: exited 1' }],
['no_dump', { status: 'skipped', reason: 'no_dump' }],
diff --git a/server/services/backup.js b/server/services/backup.js
index 2274551c71..a9af7f9089 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -12,7 +12,7 @@ import { access, lstat, readdir, readFile, stat, unlink, writeFile } from 'fs/pr
import { PassThrough } from 'node:stream';
import { hostname } from 'os';
import { join, resolve, relative, isAbsolute } from 'path';
-import { PATHS, ensureDir, readJSONFile, atomicWrite, sha256File } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, readJSONFile, readJSONFileStrict, atomicWrite, sha256File } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createLineReader } from '../lib/streamLines.js';
import { getEvent } from './eventScheduler.js';
@@ -944,7 +944,7 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
* { status: 'ok', dryRun, sizeBytes, tableCount } (dry-run or applied)
* { status: 'skipped', reason: 'no_dump' } (no sql file in snapshot)
* { status: 'skipped', reason: 'not_configured' } (real restore, PG unreachable)
- * { status: 'failed', reason: 'restore_error'|'timeout', error }
+ * { status: 'failed', reason: 'manifest_unreadable'|'manifest_mismatch'|'restore_error'|'timeout', error? }
* @param {string} destPath - Backup destination root
* @param {string} snapshotId
* @param {{dryRun?: boolean}} [options]
@@ -966,12 +966,18 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true } =
// '../portos-db.sql' (it lives ALONGSIDE the snapshot data/ dir, not inside
// it). Backward-compat: snapshots taken before manifests existed — or missing
// the dump key — have nothing to verify against, so we SKIP verification and
- // proceed rather than hard-failing. Only a manifest that IS present AND
- // carries a mismatching hash refuses the restore.
+ // proceed rather than hard-failing. An existing manifest refuses the restore
+ // when it cannot be read or when its recorded dump hash does not match.
const manifestPath = join(snapshotDir, 'manifest.json');
- // Read-only verification metadata; preserve the legacy no-manifest behavior
- // below. This path never writes the manifest back.
- const manifest = await readJSONFile(manifestPath, null);
+ // Read-only verification metadata. A confirmed ENOENT remains the legacy
+ // no-manifest case, while corrupt bytes and every other read failure mean the
+ // dump cannot be trusted. This path never writes the manifest back.
+ const manifestRead = await readJSONFileStrict(manifestPath, null);
+ if (!manifestRead.ok) {
+ console.error(`❌ restore: integrity manifest unreadable for snapshot ${snapshotId}`);
+ return { status: 'failed', reason: 'manifest_unreadable' };
+ }
+ const manifest = manifestRead.value;
const expectedHash = manifest?.files?.['../portos-db.sql'];
if (expectedHash) {
const actualHash = await sha256File(sqlPath);
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 995179b6c9..4931e71b3e 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -735,6 +735,14 @@ describe('dumpPostgres status classification', () => {
describe('restorePostgres', () => {
let restorePostgres;
+ const mockLegacyDumpRead = (sql = 'CREATE TABLE a (...);\n') => {
+ vi.spyOn(fs, 'readFile').mockImplementation(async (path) => {
+ if (String(path).endsWith('manifest.json')) {
+ throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ }
+ return sql;
+ });
+ };
beforeEach(async () => {
vi.clearAllMocks();
// clearAllMocks does not undo stubEnv — a PGPASSWORD stub from a failed
@@ -771,7 +779,7 @@ describe('restorePostgres', () => {
it('dry-run reports size/tableCount without spawning psql', async () => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
expect(result.status).toBe('ok');
expect(result.dryRun).toBe(true);
@@ -782,7 +790,7 @@ describe('restorePostgres', () => {
it('refuses a real restore when PG is not connected', async () => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
checkHealth.mockResolvedValue({ connected: false, hasSchema: false });
const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false });
expect(result).toEqual({ status: 'skipped', reason: 'not_configured' });
@@ -798,7 +806,7 @@ describe('restorePostgres', () => {
it('drains verbose psql output so progress cannot stall on pipe backpressure', async () => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
let child;
spawn.mockImplementationOnce((_bin, _args, options) => {
@@ -826,7 +834,7 @@ describe('restorePostgres', () => {
it('real restore returns failed/restore_error on non-zero psql exit', async () => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
const proc = fakeProc();
spawn.mockReturnValue(proc);
@@ -899,37 +907,24 @@ describe('restorePostgres', () => {
expect(result.tableCount).toBe(1);
});
- // A manifest.json that is PRESENT but unparseable reads the same as absent:
- // readJSONFile returns its `null` default, so there is no expected hash to
- // compare against and verification is skipped rather than hard-failing.
- // Pinning that here so a future "throw on corrupt manifest" change is a
- // deliberate decision instead of a silent behavior swap.
- it('skips verification (does not throw) when manifest.json is malformed JSON', async () => {
- vi.spyOn(fs, 'stat').mockResolvedValue({ size: DUMP_SQL.length, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockImplementation(async (p) => (
- String(p).endsWith('manifest.json') ? '{ "files": { ' : DUMP_SQL
- ));
- const result = await restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true });
- expect(result).toEqual({ status: 'ok', dryRun: true, sizeBytes: DUMP_SQL.length, tableCount: 1 });
- });
-
- // A malformed manifest must not become a free pass for a real restore either:
- // the replay still happens (verification skipped), so assert it reaches psql
- // rather than silently returning skipped.
- it('still runs a real restore when manifest.json is malformed JSON', async () => {
+ it.each([
+ ['malformed JSON', '{ "files": { '],
+ ['a non-ENOENT read failure', Object.assign(new Error('media I/O failure'), { code: 'EIO' })],
+ ])('refuses dry-run and real restore when manifest.json has %s', async (_case, manifestResult) => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: DUMP_SQL.length, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockImplementation(async (p) => (
- String(p).endsWith('manifest.json') ? 'not json at all' : DUMP_SQL
- ));
+ vi.spyOn(fs, 'readFile').mockImplementation(async (p) => {
+ if (!String(p).endsWith('manifest.json')) return DUMP_SQL;
+ if (manifestResult instanceof Error) throw manifestResult;
+ return manifestResult;
+ });
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
- const proc = fakeProc();
- spawn.mockReturnValue(proc);
- const p = restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false });
- await flush();
- proc.emit('close', 0);
- const result = await p;
- expect(result.status).toBe('ok');
- expect(spawn).toHaveBeenCalledTimes(1);
+
+ await expect(restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: true }))
+ .resolves.toEqual({ status: 'failed', reason: 'manifest_unreadable' });
+ await expect(restorePostgres('/dest', '2026-06-05T00-00-00', { dryRun: false }))
+ .resolves.toEqual({ status: 'failed', reason: 'manifest_unreadable' });
+ expect(checkHealth).not.toHaveBeenCalled();
+ expect(spawn).not.toHaveBeenCalled();
});
// psql missing from the host (ENOENT) surfaces as a spawn 'error' event, not a
@@ -937,7 +932,7 @@ describe('restorePostgres', () => {
// restore UI would hang forever — assert it resolves as a structured failure.
it('resolves failed/restore_error when the psql spawn emits an error event', async () => {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
const proc = fakeProc();
spawn.mockReturnValue(proc);
@@ -955,7 +950,7 @@ describe('restorePostgres', () => {
vi.useFakeTimers();
try {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
const proc = fakeProc();
spawn.mockReturnValue(proc);
@@ -980,7 +975,7 @@ describe('restorePostgres', () => {
vi.useFakeTimers();
try {
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
const proc = fakeProc();
spawn.mockReturnValue(proc);
@@ -1006,7 +1001,7 @@ describe('restorePostgres', () => {
it('passes --single-transaction and ON_ERROR_STOP=1 with the default PGPASSWORD', async () => {
vi.stubEnv('PGPASSWORD', '');
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
const proc = fakeProc();
spawn.mockReturnValue(proc);
@@ -1026,7 +1021,7 @@ describe('restorePostgres', () => {
it('prefers an explicit PGPASSWORD over the portos default', async () => {
vi.stubEnv('PGPASSWORD', 'from-env');
vi.spyOn(fs, 'stat').mockResolvedValue({ size: 4096, isFile: () => true });
- vi.spyOn(fs, 'readFile').mockResolvedValue('CREATE TABLE a (...);\n');
+ mockLegacyDumpRead();
checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
const proc = fakeProc();
spawn.mockReturnValue(proc);