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: require operator authority for backup administration

Adam Eivy219f0687bb93
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index cebd701b2f..5354bcfcd2 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -5,6 +5,14 @@ PortOS backs up two things together, into a single timestamped snapshot:
1. **Filesystem data** — an rsync mirror of `./data/` (with SHA-256 manifest).
2. **PostgreSQL** — a `pg_dump` logical dump (`portos-db.sql`) written alongside the snapshot.
+Backup configuration, manual runs, snapshot downloads/deletion, and restore/recovery
+require operator authority: a verified human or delegated agent session when auth is
+on, or a genuine local connection when auth is off. A reachable LAN/tailnet caller
+or scoped federation credential cannot export the raw archive or alter recovery
+policy. This includes HEAD requests for downloads. Status and snapshot inventory
+remain readable under the normal API policy. Scheduled backups continue under the
+operator-configured policy without additional confirmation.
+
### Consistency while assets are changing
The backup service closes a shared cross-process publication boundary before copying
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 2f4f7677b9..ba731a740c 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -12,7 +12,8 @@
* A route belongs here when it runs a process, git, npm, gh or a CoS agent on
* the host, or when it sets what one will run (a repo path, a start command, a
* task prompt, a shell job), or accesses live camera/microphone streams.
- * Ordinary read-only GETs stay open. Mutating routes in the
+ * Ordinary read-only GETs stay open; raw backup archives require operator
+ * authority because they export private records and credentials. Mutating routes in the
* same families that are deliberately left OUT:
* - apps: delete/archive/unarchive, scope-adherence — they
* change only PortOS's own records or read files; nothing runs.
@@ -422,8 +423,14 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
'POST /api/notes/vaults',
'PUT /api/notes/vaults/:id',
- // Restores replace records and machine-local execution policy; previews
- // require the same operator authority as execution (#8772).
+ // Backups contain private records and credentials, not a bounded read-only
+ // projection. Creating/exporting/deleting them and resuming a restore need
+ // the same operator authority as restore previews/execution (#8772).
+ // Status and snapshot inventory stay open; backup policy is body-gated below.
+ 'POST /api/backup/run',
+ 'GET /api/backup/snapshots/:snapshotId/download',
+ 'DELETE /api/backup/snapshots/:snapshotId',
+ 'POST /api/backup/restore-db/recover',
'POST /api/backup/restore',
'POST /api/backup/restore-db',
@@ -862,10 +869,14 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
* `PUT /api/settings` slices that set what runs or the guardrails around it:
* harness enablement and wrapper CLIs, the Code Animation worker tools, the
* code-review chain, the untrusted content screen in front of agent work,
- * scheduled self-update, and scheduled series autopilots. The store is polymorphic, so its other slices stay open.
+ * scheduled self-update, scheduled series autopilots, and backup destination/
+ * recovery policy. The store is polymorphic, so its other slices stay open.
*/
export const HOST_CONTROL_SETTINGS_SLICES = Object.freeze([
'autoUpdate',
+ // Destination, schedule, exclusions and retention control private copies
+ // and recovery durability, including writes consumed later by the scheduler.
+ 'backup',
'codeAnimationExecution',
'codeReview',
'credentialBootstraps',
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 718218c2af..6236afb1ac 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -599,7 +599,7 @@ describe('backup restore operator authority (#8772)', () => {
beforeEach(() => {
vi.clearAllMocks();
isAuthEnabled.mockResolvedValue(false);
- verifyRequestSession.mockImplementation(async (req) => req.headers.authorization === 'Bearer example-operator');
+ verifyRequestSession.mockImplementation(async (req) => ['Bearer example-operator', 'Bearer example-agent'].includes(req.headers.authorization));
verifyPassword.mockResolvedValue(false);
loadData.mockResolvedValue({ peers: [peer] });
getSettings.mockResolvedValue({ backup: { destPath: '/example-backups' } });
@@ -607,6 +607,47 @@ describe('backup restore operator authority (#8772)', () => {
backup.restorePostgres.mockResolvedValue({ success: true });
});
+ // Regression: the raw archive, its creation/deletion and deferred recovery
+ // must not be reachable merely because a network peer can reach PortOS.
+ describe.each([
+ ['get', '/snapshots/snap-1/download', 'openSnapshotStream'],
+ ['head', '/snapshots/snap-1/download', 'openSnapshotStream'],
+ ['post', '/run', 'runBackup'],
+ ['delete', '/snapshots/snap-1', 'deleteSnapshot'],
+ ['post', '/restore-db/recover', 'resumeDatabaseRestore'],
+ ])('%s %s operator authority', (method, path, service) => {
+ const sink = () => service === 'resumeDatabaseRestore' ? resumeDatabaseRestore : backup[service];
+ const body = method === 'post' ? { id: '00000000-0000-4000-8000-000000000001' } : undefined;
+
+ it('refuses remote and scoped-peer callers before backup effects', async () => {
+ for (const enabled of [false, true]) {
+ isAuthEnabled.mockResolvedValue(enabled);
+ const pending = request(buildGuardedApp('192.0.2.10'))[method]('/api/backup' + path)
+ .set(PEER_AUTH_HEADER, derivePeerAuthToken(peer.syncSecret, peer.instanceId))
+ .set(PEER_INSTANCE_HEADER, peer.instanceId);
+ const res = await (body ? pending.send(body) : pending);
+ expect(res.status).toBe(403);
+ expect(sink()).not.toHaveBeenCalled();
+ }
+ });
+
+ it('preserves local, human-session and delegated-agent operations', async () => {
+ for (const token of [null, 'example-operator', 'example-agent']) {
+ isAuthEnabled.mockResolvedValue(token !== null);
+ if (service === 'openSnapshotStream') {
+ const stream = new PassThrough();
+ stream.end('synthetic snapshot');
+ sink().mockResolvedValueOnce(stream);
+ } else sink().mockResolvedValueOnce({ success: true });
+ const pending = request(buildGuardedApp(token ? '192.0.2.10' : '127.0.0.1'))[method]('/api/backup' + path);
+ if (token) pending.set('Authorization', `Bearer ${token}`);
+ const res = await (body ? pending.send(body) : pending);
+ expect(res.status).toBe(200);
+ expect(sink()).toHaveBeenCalledTimes(token === null ? 1 : token === 'example-operator' ? 2 : 3);
+ }
+ });
+ });
+
describe.each([
['restore', 'restoreSnapshot'],
['restore-db', 'restorePostgres'],
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index ca9cee2b47..5f5a011c3a 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -128,6 +128,7 @@ vi.mock('../services/itermBridge.js', () => ({
}));
import settingsRoutes from './settings.js';
+import { hostControlBodyGate } from '../services/authGate.js';
import codeReviewRoutes from './codeReview.js';
import { reconcileBeeperIngestion } from '../services/beeperArming.js';
import { reconcileItermBridge } from '../services/itermBridge.js';
@@ -1620,3 +1621,41 @@ describe('Settings routes — atomic partial saves (#11045)', () => {
expect(persisted().localLlm).toEqual({ mtplx: { idleMinutes: 5 } });
});
});
+
+// Regression: generic settings writes must not let a remote caller repoint,
+// disable or prune the backups that hold the install's private records.
+describe('backup settings operator authority', () => {
+ beforeEach(() => { store = { backup: { destPath: '/example-backups', enabled: true } }; vi.clearAllMocks(); });
+ const guardedApp = (authority) => {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ Object.defineProperty(req.socket, 'remoteAddress', { value: authority === 'local' ? '127.0.0.1' : '192.0.2.10', configurable: true });
+ // authGate supplies this verified context for both human and agent sessions.
+ req.portosAuthContext = authority === 'session'
+ ? { enabled: true, authenticated: true, method: 'session' }
+ : { enabled: false, authenticated: false, method: null };
+ next();
+ });
+ app.use(hostControlBodyGate);
+ app.use('/api/settings', settingsRoutes);
+ return app;
+ };
+
+ it.each([{ destPath: '/example-other-backups' }, { enabled: false }, { retentionCount: 1 }, null])(
+ 'refuses unauthorized backup policy changes before persistence: %j', async (backup) => {
+ const previous = structuredClone(store);
+ const res = await request(guardedApp('remote')).put('/api/settings').send({ backup });
+ expect(res.status).toBe(403);
+ expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+ expect(updateSettingsWith).not.toHaveBeenCalled();
+ expect(store).toEqual(previous);
+ },
+ );
+
+ it.each(['local', 'session'])('preserves authorized backup configuration: %s', async (authority) => {
+ const res = await request(guardedApp(authority)).put('/api/settings').send({ backup: { destPath: '/example-other-backups' } });
+ expect(res.status).toBe(200);
+ expect(store.backup.destPath).toBe('/example-other-backups');
+ });
+});