feat(mosaic): durable pre-update snapshot + verify net + restore CLI (#791 PR2)
Some checks failed
ci/woodpecker/pr/ci Pipeline failed

Third, independent recovery layer for keep-mode upgrades (Part of #791). PR1's
manifest keeps the sync out of operator paths and the ephemeral /tmp snapshot
rolls back a mid-write crash; this adds the case neither covers — a "successful"
upgrade that a manifest/logic bug silently let touch an operator file.

- install.sh make_durable_snapshot(): before any mutation, copy the operator-owned
  surface that exists to $XDG_STATE_HOME/mosaic/backups/pre-update-<UTC-ts>/
  (0700 dirs / 0600 files, umask 077 scoped + restored). Fail-open; retention
  MOSAIC_BACKUP_RETENTION (default 5).
- install.sh verify_operator_surface(): post-sync, restore any operator file the
  upgrade diverged/removed and warn loudly (a divergence = manifest bug). Honors
  intentional migration removals; refuses to restore through a symlink (CWE-59);
  guards mkdir under set -e.
- mosaic restore (TS): --list (default dry-run), --from <ts> confirmation-gated
  restore. Strict timestamp selector (CWE-22), O_NOFOLLOW 0600 writes (CWE-59),
  containment + managed-dir checks via secure-file.ts. Counts/paths only — never
  emits file contents (secrev).
- Gates: typecheck/lint/format ✓; mosaic vitest 1252; restore.spec 30;
  bash gates durable-snapshot 41 / manifest-guard 193 / rollback 28 / migration 21.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Hermes Agent
2026-07-16 19:04:14 -05:00
parent 32a0ffba13
commit 8bee1b65ea
8 changed files with 1403 additions and 4 deletions

View File

@@ -17,6 +17,7 @@ import { registerConfigCommand } from './commands/config.js';
import { registerFleetCommand } from './commands/fleet.js';
import { registerMissionCommand } from './commands/mission.js';
import { registerUninstallCommand } from './commands/uninstall.js';
import { registerRestoreCommand } from './commands/restore.js';
// prdy is registered via launch.ts
import { registerLaunchCommands } from './commands/launch.js';
import { registerAuthCommand } from './commands/auth.js';
@@ -406,6 +407,10 @@ registerStorageCommand(program);
registerUninstallCommand(program);
// ─── restore ─────────────────────────────────────────────────────────────────
registerRestoreCommand(program);
// ─── telemetry ───────────────────────────────────────────────────────────────
registerTelemetryCommand(program);

View File

@@ -0,0 +1,466 @@
/**
* Tests for `mosaic restore` (#791 PR2 Task 12).
*
* The durable pre-update snapshot (install.sh: make_durable_snapshot) writes the
* operator-owned surface to $XDG_STATE_HOME/mosaic/backups/pre-update-<ts>/ with
* 0700 dirs / 0600 files. `mosaic restore` is the recovery counterpart:
* • --list (default) enumerate snapshots by timestamp — dry-run, never mutates.
* • --from <ts> restore that snapshot over MOSAIC_HOME, confirmation-gated.
* It reports counts and relative paths ONLY — a snapshot may contain secrets
* (credentials.json), so no file content is ever printed (secrev invariant).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
mkdtempSync,
rmSync,
mkdirSync,
writeFileSync,
readFileSync,
statSync,
lstatSync,
symlinkSync,
} from 'node:fs';
import { join } from 'node:path';
import { tmpdir, homedir } from 'node:os';
import { Command } from 'commander';
import {
resolveBackupRoot,
listSnapshots,
resolveSnapshotDir,
planRestore,
applyRestore,
runRestore,
registerRestoreCommand,
} from './restore.js';
const SECRET = 'SUPER-SECRET-TOKEN-do-not-log-restore';
function seedSnapshot(root: string, ts: string, files: Record<string, string>): string {
const dir = join(root, `pre-update-${ts}`);
for (const [rel, content] of Object.entries(files)) {
const abs = join(dir, rel);
mkdirSync(join(abs, '..'), { recursive: true });
writeFileSync(abs, content);
}
return dir;
}
describe('mosaic restore (#791 PR2)', () => {
let tmp: string;
let backups: string;
beforeEach(() => {
tmp = mkdtempSync(join(tmpdir(), 'mosaic-restore-'));
backups = join(tmp, 'state', 'mosaic', 'backups');
mkdirSync(backups, { recursive: true });
vi.clearAllMocks();
});
afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
describe('resolveBackupRoot', () => {
it('honors XDG_STATE_HOME', () => {
expect(resolveBackupRoot({ XDG_STATE_HOME: '/x/state' })).toBe('/x/state/mosaic/backups');
});
it('falls back to ~/.local/state', () => {
expect(resolveBackupRoot({})).toBe(join(homedir(), '.local', 'state', 'mosaic', 'backups'));
});
});
describe('listSnapshots', () => {
it('returns [] when the backup root does not exist', () => {
expect(listSnapshots(join(tmp, 'nope'))).toEqual([]);
});
it('lists pre-update snapshots newest-first with file counts, ignoring other dirs', () => {
seedSnapshot(backups, '20240101T000000Z', { 'SOUL.md': 'a' });
seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'b', 'agents/x.conf': 'c' });
mkdirSync(join(backups, 'unrelated-dir'), { recursive: true });
const snaps = listSnapshots(backups);
expect(snaps.map((s) => s.timestamp)).toEqual(['20260101T000000Z', '20240101T000000Z']);
expect(snaps[0]!.fileCount).toBe(2);
expect(snaps[1]!.fileCount).toBe(1);
});
});
describe('resolveSnapshotDir', () => {
it('resolves by bare timestamp and by full pre-update-<ts> name', () => {
const dir = seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'a' });
expect(resolveSnapshotDir(backups, '20260101T000000Z')).toBe(dir);
expect(resolveSnapshotDir(backups, 'pre-update-20260101T000000Z')).toBe(dir);
});
it('returns undefined for an unknown timestamp', () => {
expect(resolveSnapshotDir(backups, '19990101T000000Z')).toBeUndefined();
});
});
describe('planRestore', () => {
it('walks nested dirs and returns every relative file path', () => {
const dir = seedSnapshot(backups, '20260101T000000Z', {
'SOUL.md': 'a',
'agents/x.conf': 'b',
'tools/_lib/credentials.json': 'c',
});
expect(planRestore(dir).sort()).toEqual(
['SOUL.md', 'agents/x.conf', 'tools/_lib/credentials.json'].sort(),
);
});
});
describe('applyRestore', () => {
it('restores byte-exact content, creates parent dirs, and sets 0600', () => {
const dir = seedSnapshot(backups, '20260101T000000Z', {
'SOUL.md': 'original-soul',
'tools/_lib/credentials.json': `TOKEN=${SECRET}\n`,
});
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
// A diverged operator file that restore must overwrite.
writeFileSync(join(home, 'SOUL.md'), 'CORRUPTED');
const n = applyRestore(dir, home, planRestore(dir));
expect(n).toBe(2);
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('original-soul');
expect(readFileSync(join(home, 'tools/_lib/credentials.json'), 'utf8')).toBe(
`TOKEN=${SECRET}\n`,
);
expect(statSync(join(home, 'SOUL.md')).mode & 0o777).toBe(0o600);
expect(statSync(join(home, 'tools/_lib/credentials.json')).mode & 0o777).toBe(0o600);
});
});
describe('runRestore', () => {
it('--list prints timestamps and counts, mutating nothing', async () => {
seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'a', 'agents/x.conf': 'b' });
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const code = await runRestore({
list: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
});
expect(code).toBe(0);
const out = log.mock.calls.flat().join('\n');
expect(out).toContain('20260101T000000Z');
expect(out).toMatch(/2\b/); // the file count is surfaced
log.mockRestore();
});
it('--from restores the snapshot over MOSAIC_HOME byte-exact (yes bypasses prompt)', async () => {
seedSnapshot(backups, '20260101T000000Z', {
'SOUL.md': 'restored-soul',
'tools/_lib/credentials.json': `TOKEN=${SECRET}\n`,
});
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
writeFileSync(join(home, 'SOUL.md'), 'STALE');
const code = await runRestore({
from: '20260101T000000Z',
yes: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
});
expect(code).toBe(0);
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('restored-soul');
expect(readFileSync(join(home, 'tools/_lib/credentials.json'), 'utf8')).toBe(
`TOKEN=${SECRET}\n`,
);
});
it('--from with an unknown timestamp fails without mutating', async () => {
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
writeFileSync(join(home, 'SOUL.md'), 'KEEP');
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
const code = await runRestore({
from: '19990101T000000Z',
yes: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
});
expect(code).toBe(1);
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('KEEP');
err.mockRestore();
});
it('--dry-run with --from reports the plan but mutates nothing', async () => {
seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'snap' });
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
writeFileSync(join(home, 'SOUL.md'), 'UNCHANGED');
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const code = await runRestore({
from: '20260101T000000Z',
dryRun: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
});
expect(code).toBe(0);
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('UNCHANGED');
log.mockRestore();
});
it('--from prompts and applies the restore when the operator confirms', async () => {
seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'confirmed-soul' });
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
writeFileSync(join(home, 'SOUL.md'), 'STALE');
vi.spyOn(console, 'log').mockImplementation(() => {});
const confirm = vi.fn().mockResolvedValue(true);
const code = await runRestore({
from: '20260101T000000Z',
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
confirm,
});
expect(code).toBe(0);
expect(confirm).toHaveBeenCalledOnce();
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('confirmed-soul');
});
it('--from aborts without mutating when the operator declines', async () => {
seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'snap' });
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
writeFileSync(join(home, 'SOUL.md'), 'KEEP');
vi.spyOn(console, 'log').mockImplementation(() => {});
const confirm = vi.fn().mockResolvedValue(false);
const code = await runRestore({
from: '20260101T000000Z',
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
confirm,
});
expect(code).toBe(0);
expect(confirm).toHaveBeenCalledOnce();
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('KEEP');
});
it('MOSAIC_ASSUME_YES=1 bypasses the confirmation prompt', async () => {
seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'env-yes' });
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
writeFileSync(join(home, 'SOUL.md'), 'STALE');
vi.spyOn(console, 'log').mockImplementation(() => {});
const confirm = vi.fn().mockResolvedValue(false);
const code = await runRestore({
from: '20260101T000000Z',
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state'), MOSAIC_ASSUME_YES: '1' },
confirm,
});
expect(code).toBe(0);
expect(confirm).not.toHaveBeenCalled();
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('env-yes');
});
it('--list reports gracefully when no snapshots exist', async () => {
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const code = await runRestore({
list: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'empty-state') },
});
expect(code).toBe(0);
expect(log.mock.calls.flat().join('\n')).toMatch(/No pre-update snapshots/);
});
it('never prints a secret value found inside a backed-up file', async () => {
seedSnapshot(backups, '20260101T000000Z', {
'tools/_lib/credentials.json': `TOKEN=${SECRET}\n`,
});
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
await runRestore({
list: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
});
await runRestore({
from: '20260101T000000Z',
yes: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
});
const all = [...log.mock.calls, ...err.mock.calls].flat().join('\n');
expect(all).not.toContain(SECRET);
log.mockRestore();
err.mockRestore();
});
});
// Regression coverage for the codex code+security review of PR2 (#791):
// CWE-22 traversal via --from, and CWE-59 symlink write-through in applyRestore.
describe('security hardening', () => {
it.each([
'../../etc',
'pre-update-/../../tmp/poison',
'pre-update-../evil',
'20260101T000000Z/../../../tmp',
'not-a-timestamp',
'2026-01-01',
])('resolveSnapshotDir rejects traversal / malformed selector %j', (bad) => {
// Even if a matching directory exists on disk, a non-timestamp selector
// must not resolve — the only accepted shape is <8>T<6>Z[-n].
expect(resolveSnapshotDir(backups, bad)).toBeUndefined();
});
it('runRestore --from a traversal selector fails closed without copying', async () => {
// Plant a real dir one level ABOVE the backup root. The naive resolver
// `join(root, from)` with `from='../poison'` would reach it (backups is
// .../mosaic/backups, so `../poison` == .../mosaic/poison) and import it.
const outside = join(tmp, 'state', 'mosaic', 'poison');
mkdirSync(outside, { recursive: true });
writeFileSync(join(outside, 'x'), 'attacker');
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
const code = await runRestore({
from: '../poison',
yes: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
});
expect(code).toBe(1);
expect(statSync(home).isDirectory()).toBe(true);
// Nothing from `outside` was imported.
expect(() => statSync(join(home, 'x'))).toThrow();
err.mockRestore();
});
it('applyRestore refuses to write a secret through a symlinked leaf (CWE-59)', () => {
const dir = seedSnapshot(backups, '20260101T000000Z', {
'tools/_lib/credentials.json': `TOKEN=${SECRET}\n`,
});
const home = join(tmp, 'home');
mkdirSync(join(home, 'tools', '_lib'), { recursive: true });
// Attacker points the operator credentials file at a file they can read.
const exfil = join(tmp, 'exfil-target');
writeFileSync(exfil, 'original-attacker-content');
symlinkSync(exfil, join(home, 'tools', '_lib', 'credentials.json'));
expect(() => applyRestore(dir, home, planRestore(dir))).toThrow();
// The secret was NOT written through the link into the attacker's file.
expect(readFileSync(exfil, 'utf8')).toBe('original-attacker-content');
});
it('applyRestore refuses to write through a symlinked ancestor (CWE-59)', () => {
const dir = seedSnapshot(backups, '20260101T000000Z', {
'tools/_lib/credentials.json': `TOKEN=${SECRET}\n`,
});
const home = join(tmp, 'home');
mkdirSync(join(home, 'tools'), { recursive: true });
// Attacker replaces the `tools/_lib` ancestor with a symlink out of the root.
const exfilDir = join(tmp, 'exfil-dir');
mkdirSync(exfilDir, { recursive: true });
symlinkSync(exfilDir, join(home, 'tools', '_lib'));
expect(() => applyRestore(dir, home, planRestore(dir))).toThrow();
// Nothing was written into the attacker-controlled directory.
expect(() => statSync(join(exfilDir, 'credentials.json'))).toThrow();
});
it('runRestore surfaces a symlink violation as exit 1 without leaking the secret', async () => {
seedSnapshot(backups, '20260101T000000Z', {
'tools/_lib/credentials.json': `TOKEN=${SECRET}\n`,
});
const home = join(tmp, 'home');
mkdirSync(join(home, 'tools', '_lib'), { recursive: true });
const exfil = join(tmp, 'exfil-target');
writeFileSync(exfil, 'attacker');
symlinkSync(exfil, join(home, 'tools', '_lib', 'credentials.json'));
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const err = vi.spyOn(console, 'error').mockImplementation(() => {});
const code = await runRestore({
from: '20260101T000000Z',
yes: true,
mosaicHome: home,
env: { XDG_STATE_HOME: join(tmp, 'state') },
});
expect(code).toBe(1);
expect(readFileSync(exfil, 'utf8')).toBe('attacker');
const all = [...log.mock.calls, ...err.mock.calls].flat().join('\n');
expect(all).not.toContain(SECRET);
log.mockRestore();
err.mockRestore();
});
it('applyRestore replaces a diverged regular file in place with 0600 (not a symlink)', () => {
const dir = seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'restored' });
const home = join(tmp, 'home');
mkdirSync(home, { recursive: true });
writeFileSync(join(home, 'SOUL.md'), 'stale');
const n = applyRestore(dir, home, planRestore(dir));
expect(n).toBe(1);
expect(lstatSync(join(home, 'SOUL.md')).isSymbolicLink()).toBe(false);
expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('restored');
expect(statSync(join(home, 'SOUL.md')).mode & 0o777).toBe(0o600);
});
});
describe('registerRestoreCommand', () => {
it('registers `restore` with the expected flags', () => {
const program = new Command();
program.exitOverride();
registerRestoreCommand(program);
const cmd = program.commands.find((c) => c.name() === 'restore');
expect(cmd).toBeDefined();
const longs = cmd!.options.map((o) => o.long);
expect(longs).toEqual(
expect.arrayContaining(['--list', '--from', '--dry-run', '--yes', '--mosaic-home']),
);
});
it('runs the list action end-to-end via the parsed command', async () => {
seedSnapshot(backups, '20260101T000000Z', { 'SOUL.md': 'a' });
const prevXdg = process.env['XDG_STATE_HOME'];
process.env['XDG_STATE_HOME'] = join(tmp, 'state');
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
try {
const program = new Command();
program.exitOverride();
registerRestoreCommand(program);
await program.parseAsync(['restore', '--list', '--mosaic-home', join(tmp, 'home')], {
from: 'user',
});
expect(log.mock.calls.flat().join('\n')).toContain('20260101T000000Z');
} finally {
log.mockRestore();
if (prevXdg === undefined) delete process.env['XDG_STATE_HOME'];
else process.env['XDG_STATE_HOME'] = prevXdg;
}
});
});
});

View File

@@ -0,0 +1,313 @@
/**
* restore.ts — top-level `mosaic restore` command (#791 PR2 Task 12)
*
* Recovery counterpart to the durable pre-update snapshot taken by install.sh
* (make_durable_snapshot). Before a keep-mode upgrade mutates anything, the
* installer copies the operator-owned surface to
* $XDG_STATE_HOME/mosaic/backups/pre-update-<UTC-ts>/ (0700 dirs / 0600 files)
* This command lets the operator inspect and roll back to those snapshots:
*
* mosaic restore # == --list: enumerate snapshots (dry-run)
* mosaic restore --list
* mosaic restore --from <ts> # restore that snapshot over MOSAIC_HOME
* mosaic restore --from <ts> --dry-run
*
* SECREV INVARIANT: a snapshot may contain secrets (e.g. tools/_lib/credentials.json).
* This command reports counts and RELATIVE PATHS only — it never reads a backed-up
* file into any logged string. Restored files are written back 0600 (owner-only),
* matching the snapshot's own private posture. The path convention here mirrors
* install.sh `backup_root()`; keep the two in sync (no shared code across the boundary).
*/
import {
existsSync,
readdirSync,
statSync,
lstatSync,
readFileSync,
openSync,
writeSync,
fchmodSync,
closeSync,
constants,
} from 'node:fs';
import { createInterface } from 'node:readline';
import { homedir } from 'node:os';
import { join, dirname, relative } from 'node:path';
import type { Command } from 'commander';
import { DEFAULT_MOSAIC_HOME } from '../constants.js';
import { assertCanonicalContainment, ensureManagedDirectory } from '../fleet/secure-file.js';
// ─── types ───────────────────────────────────────────────────────────────────
export interface SnapshotInfo {
/** The UTC stamp after the `pre-update-` prefix, e.g. "20260716T232225Z". */
readonly timestamp: string;
/** Absolute path to the snapshot directory. */
readonly dir: string;
/** Number of files captured in the snapshot. */
readonly fileCount: number;
}
export interface RestoreOptions {
list?: boolean;
from?: string;
dryRun?: boolean;
yes?: boolean;
mosaicHome: string;
/** Environment source (injectable for tests); defaults to process.env. */
env?: NodeJS.ProcessEnv;
/**
* Confirmation gate (injectable for tests); defaults to an interactive
* readline prompt. Returns true to proceed with the overwrite.
*/
confirm?: (question: string) => Promise<boolean>;
}
const SNAPSHOT_PREFIX = 'pre-update-';
/**
* The exact shape install.sh `make_durable_snapshot()` stamps: `<8>T<6>Z` UTC,
* with an optional `-<n>` same-second collision suffix. `--from` is matched
* against this — nothing containing a path separator or `..` can pass, so a
* selector can never escape the backup root (CWE-22).
*/
const SNAPSHOT_TS_RE = /^\d{8}T\d{6}Z(?:-\d+)?$/;
// ─── pure helpers ─────────────────────────────────────────────────────────────
/** Resolve the durable-snapshot root, mirroring install.sh `backup_root()`. */
export function resolveBackupRoot(env: NodeJS.ProcessEnv = process.env): string {
const stateHome = env['XDG_STATE_HOME'] || join(homedir(), '.local', 'state');
return join(stateHome, 'mosaic', 'backups');
}
/** Recursively collect every file under `dir` as a path relative to `dir`. */
export function planRestore(dir: string): string[] {
const out: string[] = [];
const walk = (cur: string): void => {
for (const entry of readdirSync(cur, { withFileTypes: true })) {
const abs = join(cur, entry.name);
if (entry.isDirectory()) {
walk(abs);
} else if (entry.isFile()) {
out.push(relative(dir, abs));
}
}
};
if (existsSync(dir)) walk(dir);
return out;
}
/** Enumerate snapshots newest-first (the `pre-update-<ts>` names sort chronologically). */
export function listSnapshots(root: string): SnapshotInfo[] {
if (!existsSync(root)) return [];
let entries: string[];
try {
entries = readdirSync(root);
} catch {
return [];
}
return entries
.filter((name) => name.startsWith(SNAPSHOT_PREFIX))
.map((name) => join(root, name))
.filter((dir) => {
try {
return statSync(dir).isDirectory();
} catch {
return false;
}
})
.sort()
.reverse()
.map((dir) => ({
timestamp: dir.split('/').at(-1)!.slice(SNAPSHOT_PREFIX.length),
dir,
fileCount: planRestore(dir).length,
}));
}
/**
* Resolve a snapshot dir from a `--from` selector. Accepts ONLY a strict
* generated identifier — a bare `<ts>` or the full `pre-update-<ts>` name — and
* builds exactly `join(root, 'pre-update-' + ts)`. A selector containing `/`,
* `..`, or anything but the timestamp shape is rejected (returns undefined), so
* `--from` can never traverse outside the backup root (CWE-22). The resolved dir
* must be a real, non-symlink directory (lstat, not stat), so a symlinked
* snapshot entry can't redirect the restore either.
*/
export function resolveSnapshotDir(root: string, from: string): string | undefined {
const ts = from.startsWith(SNAPSHOT_PREFIX) ? from.slice(SNAPSHOT_PREFIX.length) : from;
if (!SNAPSHOT_TS_RE.test(ts)) return undefined;
const dir = join(root, `${SNAPSHOT_PREFIX}${ts}`);
try {
if (lstatSync(dir).isDirectory()) return dir;
} catch {
/* absent or inaccessible */
}
return undefined;
}
/**
* Copy each `relPaths` entry from the snapshot back into `mosaicHome`, forcing
* 0600 on the restored file (owner-only — the operator surface may hold secrets).
* Returns the number of files restored. Never reads a file's content into a
* logged string.
*
* SYMLINK-SAFE (CWE-59): a snapshot may hold secrets, so we must never let a
* tampered destination redirect the write. Every destination path is contained
* within `mosaicHome` (assertCanonicalContainment) and every ancestor is proven
* to be a real, non-symlink directory (ensureManagedDirectory) before we write.
* The leaf itself is opened O_NOFOLLOW, so if it was swapped for a symlink the
* open fails closed (ELOOP) rather than writing the secret through the link.
*/
export function applyRestore(
snapDir: string,
mosaicHome: string,
relPaths: readonly string[],
): number {
let restored = 0;
for (const rel of relPaths) {
const src = join(snapDir, rel);
const dst = join(mosaicHome, rel);
// Fail closed if the target path escapes the managed root or any ancestor is
// a symlink; create missing ancestors as private (0700) real directories.
assertCanonicalContainment(mosaicHome, dst);
ensureManagedDirectory(mosaicHome, dirname(dst));
// O_NOFOLLOW: refuse to follow a symlink at the leaf (secret exfil guard).
// O_CREAT|O_TRUNC: create a fresh 0600 file, or overwrite a diverged real one.
const fd = openSync(
dst,
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
0o600,
);
try {
fchmodSync(fd, 0o600); // enforce 0600 even when the file pre-existed
writeSync(fd, readFileSync(src));
} finally {
closeSync(fd);
}
restored += 1;
}
return restored;
}
// ─── orchestration ────────────────────────────────────────────────────────────
async function promptConfirm(question: string): Promise<boolean> {
const rl = createInterface({ input: process.stdin, output: process.stdout });
try {
return await new Promise<boolean>((resolve) => {
rl.question(`${question} [y/N] `, (ans) => resolve(ans.trim().toLowerCase() === 'y'));
});
} finally {
rl.close();
}
}
/**
* Run `mosaic restore`. Returns a process exit code (0 ok, 1 error) rather than
* calling process.exit, so it stays unit-testable.
*/
export async function runRestore(opts: RestoreOptions): Promise<number> {
const env = opts.env ?? process.env;
const root = resolveBackupRoot(env);
// Default action (and explicit --list): enumerate, never mutate.
if (opts.list || !opts.from) {
const snaps = listSnapshots(root);
if (snaps.length === 0) {
console.log(`No pre-update snapshots found under ${root}.`);
return 0;
}
console.log(`Pre-update snapshots under ${root} (newest first):\n`);
for (const s of snaps) {
console.log(` ${s.timestamp}${s.fileCount} file(s)`);
}
console.log(`\nRestore one with: mosaic restore --from <timestamp>`);
return 0;
}
// --from <ts>: restore over the operator surface.
const snapDir = resolveSnapshotDir(root, opts.from);
if (!snapDir) {
console.error(`No snapshot matching '${opts.from}' under ${root}.`);
console.error(`Run 'mosaic restore --list' to see available timestamps.`);
return 1;
}
const relPaths = planRestore(snapDir);
const ts = snapDir.split('/').at(-1)!.slice(SNAPSHOT_PREFIX.length);
if (opts.dryRun) {
console.log(
`[dry-run] Would restore ${relPaths.length} file(s) from snapshot ${ts} into ${opts.mosaicHome}:`,
);
for (const rel of relPaths) console.log(` ${rel}`);
console.log('[dry-run] No changes made.');
return 0;
}
const assumeYes = opts.yes || env['MOSAIC_ASSUME_YES'] === '1';
if (!assumeYes) {
console.log(
`About to restore ${relPaths.length} operator file(s) from snapshot ${ts} into ${opts.mosaicHome}.`,
);
console.log('This OVERWRITES those files with their pre-update contents.');
const ok = await (opts.confirm ?? promptConfirm)('Proceed?');
if (!ok) {
console.log('Restore cancelled. No changes made.');
return 0;
}
}
let n: number;
try {
n = applyRestore(snapDir, opts.mosaicHome, relPaths);
} catch (err) {
// A containment/symlink violation is a fail-closed security stop, not a
// routine error — surface it without leaking file contents and abort.
console.error(
`Restore aborted: a destination path under ${opts.mosaicHome} is unsafe to write ` +
`(symlink or escapes the managed root). No files were restored. (${(err as Error).message})`,
);
return 1;
}
console.log(`Restored ${n} operator file(s) from snapshot ${ts} into ${opts.mosaicHome}.`);
return 0;
}
// ─── commander registration ───────────────────────────────────────────────────
export function registerRestoreCommand(program: Command): void {
program
.command('restore')
.description('List or restore durable pre-update snapshots of your operator config (#791)')
.option('--list', 'List available snapshots by timestamp (default action)')
.option('--from <timestamp>', 'Restore the snapshot with this timestamp over MOSAIC_HOME')
.option('--dry-run', 'With --from: show what would be restored without changing anything')
.option('--yes, -y', 'Skip the confirmation prompt (also: MOSAIC_ASSUME_YES=1)')
.option(
'--mosaic-home <path>',
'Override MOSAIC_HOME directory',
process.env['MOSAIC_HOME'] ?? DEFAULT_MOSAIC_HOME,
)
.action(
async (opts: {
list?: boolean;
from?: string;
dryRun?: boolean;
yes?: boolean;
mosaicHome: string;
}) => {
const code = await runRestore({
list: opts.list,
from: opts.from,
dryRun: opts.dryRun,
yes: opts.yes,
mosaicHome: opts.mosaicHome,
});
if (code !== 0) process.exit(code);
},
);
}