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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: refuse database admin operations during maintenance (#8816)
[._.]/ Adam Eivya1fca3d82f62
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 66b30184fe..8a1007569e 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -246,7 +246,7 @@ node scripts/database-maintenance.mjs begin native dockernode scripts/database-maintenance.mjs begin docker native```-The command returns the operation ID and direction. Plan for downtime: new pooled database operations and CoS spawn admission are refused immediately, and both managed server and runner refuse normal boot while fenced. Admission is the synchronous fence check: work admitted just before publication may still obtain a connection or spawn afterward. Already-admitted transactions may finish; this boundary alone is **not a drained snapshot boundary**. The offline coordinator must still stop/drain all owned writers and validate live/spawning work before export. A process-local restore callback cannot bypass this persistent fence.+The command returns the operation ID and direction. Plan for downtime: new pooled database operations, database administration mutations/exports, and CoS spawn admission are refused immediately, and both managed server and runner refuse normal boot while fenced. Admission is the synchronous fence check: work admitted just before publication may still obtain a connection or spawn afterward. Already-admitted transactions may finish; this boundary alone is **not a drained snapshot boundary**. The offline coordinator must still stop/drain all owned writers and validate live/spawning work before export. A process-local restore callback cannot bypass this persistent fence.If no transfer has started and saved source configuration is unchanged, cancel using that exact ID:diff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex 59680b0cd1..f3ea120661 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -5,10 +5,17 @@* we can control every shell invocation without touching the real filesystem* or running actual Docker/psql commands.*/-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';+vi.mock('../lib/paths.js', async (importOriginal) => {+ const { makePathsProxy, lazyTempDataRoot } = await import('../lib/mockPathsDataRoot.js');+ return makePathsProxy(await importOriginal(), {+ dataRoot: lazyTempDataRoot('portos-database-admin-'),+ });+});+// resolveBashBinary and the db.sh path are resolved at module load — mock// the dependencies before the route is imported.vi.mock('../lib/bashResolver.js', async (importOriginal) => ({@@ -63,6 +70,11 @@ import { writeFileSync, mkdtempSync, readFileSync, createReadStream } from 'fs';import { tmpdir } from 'os';import { join as pathJoin } from 'path';import databaseRoutes from './database.js';+import { PATHS } from '../lib/paths.js';+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';+import { cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';++afterAll(cleanupTempDataRoots);import { isPg17OnlyDirective, importDumpFile } from '../services/dbAdmin.js';// Helper: make execFile call the callback with controlled output@@ -122,6 +134,39 @@ describe('database migration admission', () => {});});+// Regression: raw shell admin operations bypass the pooled DB write fence.+// Exercise the real durable journal through HTTP, without a live database.+describe('database admin maintenance admission', () => {+ it('refuses every admin operation while fenced and resumes after source-only cancellation', async () => {+ vi.clearAllMocks();+ const journal = createDatabaseMaintenanceJournal(PATHS.data);+ const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example_role' };+ const operation = journal.begin({ source, target: { ...source, mode: 'docker', port: 5561 } });+ try {+ for (const [route, body] of [+ ['switch', { target: 'docker', migrate: true }],+ ['sync', {}], ['start', { backend: 'docker' }],+ ['stop', { backend: 'native' }], ['destroy', { backend: 'docker' }],+ ['setup-native', {}], ['fix', {}],+ ['export', {}], ['export', { backend: 'docker' }],+ ]) {+ const res = await request(makeApp()).post(`/api/database/${route}`).send(body);+ expect(res.status, route).toBe(503);+ expect(res.body.code, route).toBe('DATABASE_MAINTENANCE');+ }+ expect(execFile).not.toHaveBeenCalled();+ expect(spawn).not.toHaveBeenCalled();+ expect(query).not.toHaveBeenCalled();+ expect(checkHealth).not.toHaveBeenCalled();+ } finally {+ journal.cancel(operation.id, source);+ }+ mockExecFile([{ exitCode: 0, stdout: 'started' }]);+ expect((await request(makeApp()).post('/api/database/start').send({ backend: 'docker' })).status).toBe(200);+ expect(execFile).toHaveBeenCalledTimes(1);+ });+});+describe('isPg17OnlyDirective (sed-replacement line filter)', () => {it('matches the pg17-only directives the legacy sed stripped', () => {expect(isPg17OnlyDirective('\\restrict abc123')).toBe(true);@@ -653,6 +698,7 @@ describe('POST /api/database/sync endpoint safety', () => {['switch', { target: 'docker', migrate: false }],['destroy', { backend: 'docker' }],['sync', {}],+ ['export', {}],]) {const res = await request(app).post(`/api/database/${route}`).send(body);expect(res.status).toBe(409);diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.jsindex 250671b508..4f104f7adc 100644--- a/server/services/dbAdmin.js+++ b/server/services/dbAdmin.js@@ -8,6 +8,7 @@ import { stripAnsi } from '../lib/ansiStrip.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';import { resolveBashBinary, toBashPath } from '../lib/bashResolver.js';import { resolvePostgresPort } from '../lib/ports.js';+import { assertDatabaseAdmission } from '../lib/databaseMaintenanceJournal.js';const rootDir = PATHS.root;const dbScript = toBashPath(join(rootDir, 'scripts', 'db.sh'));@@ -21,6 +22,8 @@ const bashBinary = resolveBashBinary();// before they probe or change configuration; always release after failure.let databaseOperationActive = false;async function withDatabaseOperation(operation) {+ // Check synchronously before locking, probing, or launching shell writers.+ assertDatabaseAdmission();if (databaseOperationActive) {throw new ServerError('Another database operation is in progress. Wait for it to finish and retry.', { status: 409 });}@@ -518,7 +521,7 @@ async function syncDatabaseImpl(io) {emit('start', { message: 'Exporting from active database...' });// Explicit backend export bypasses db.sh's saved-mode/container selection.- const { dumpFile } = await exportDatabase(currentMode);+ const { dumpFile } = await exportDatabaseImpl(currentMode);console.log(`🗄️ Sync: exported to ${dumpFile}`);// Step 2: Ensure target is running and configured@@ -657,7 +660,7 @@ async function setupNativeDatabaseImpl(io) {}/** Export a specific database backend, or the active backend when omitted. */-export async function exportDatabase(backend) {+async function exportDatabaseImpl(backend) {const label = `backup-${Date.now()}`;if (backend) {@@ -732,3 +735,5 @@ export const stopDatabase = (backend) => withDatabaseOperation(() => stopDatabasexport const setupNativeDatabase = (io) => withDatabaseOperation(() => setupNativeDatabaseImpl(io));export const fixDatabase = () => withDatabaseOperation(() => fixDatabaseImpl());++export const exportDatabase = (backend) => withDatabaseOperation(() => exportDatabaseImpl(backend));