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: preserve backup TLS trust with temporary certificate bundles (#9451)

[._.]/ Adam Eivycf8749edbd7c
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 1e4885a944..c4e2fbeca1 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -16,7 +16,7 @@ pool at server startup. Changing `PGHOST`, `PGPORT`, `PGDATABASE`, `PGUSER`, or
`PGPASSWORD` requires restarting PortOS. Inherited libpq overrides (including
`PGHOSTADDR`, service files and `PGOPTIONS`) are removed from these subprocesses.
TLS is captured at startup too: disabled TLS stays disabled, verified TLS uses
-`verify-full` with system trust (requires libpq 17 or newer), and `no-verify` uses `require`. Inline TLS
+`verify-full` with a temporary PEM file containing Node’s active trust roots, and `no-verify` uses `require`. Inline TLS
certificate settings are refused rather than silently weakened. Executable
resolution (`PATH` and `PORTOS_PGDUMP`) is preserved.
diff --git a/server/lib/README.md b/server/lib/README.md
index 59789c20d2..7ae0e15e43 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -625,7 +625,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `db.js` | PostgreSQL connection pool and `withDatabaseMaintenance(fn)` admission/drain gate for atomic restore and reconciliation. |
| `db/` | Boot DDL for the PostgreSQL schema, split per domain (#2832). `db/schema/index.js` re-exports each module's statement array and composes the two ordered lists `ensureSchemaImpl()` runs on every boot (`buildUpgradeDdl()` then `buildCatalogDdl()`). **Statement order is load-bearing** — append inside the domain module and leave the composer order alone. See `db/schema/README.md` for the module catalog. |
| `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. |
-| `pgTools.js` | `buildPgToolEnv(config)` isolates libpq connection/TLS settings from inherited PG variables; `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |
+| `pgTools.js` | `withPgToolEnv(config, run)` stages Node trust roots with guaranteed cleanup; isolates libpq connection/TLS settings from inherited PG variables; `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |
| `ecosystemProcessPorts.js` | Attributes a parsed PM2 ecosystem config's port labels to the app that OWNS them (#7357): `processSurface(name)` (a process name minus one trailing role suffix, so `portos-server`/`portos-ui` share surface `portos` while `portos-autofixer-ui` does not), `attributeProcessPorts(processes, app)` (`api`/`ui`/`devUi` resolved from the app's own surface first, then from a carrier whose name declares no role at all, and left undefined when none — which is what lets the served-by-API `uiPort` derivation take over), and `findCrossProcessPortCollision(processes, edits)` (the pre-write guard: a port another process in the same config already holds). Shared by `services/appPortConfig.js` (write-back) and `services/appListEnrichment.js` (read/derive) so a displayed port and a rewritten port can never disagree about whose it is. |
| `ports.js` | Canonical `PORTS` object (mirroring `ecosystem.config.cjs`, pinned by `ports.test.js`), `DEFAULT_PEER_PORT`, and `resolvePostgresPort(pgMode)`. A pure leaf: `client/src/lib/ports.js` re-exports it, so nothing here may read `process.env` at module scope — the env-derived origins live in `portosUrls.js`. |
| `portosUrls.js` | `PORTOS_UI_URL` / `PORTOS_API_URL` — the origins PortOS interpolates into prompts and links, resolved from `PORTOS_*` / `PORT` at module load. Split out of `ports.js` so that module stays free of module-scope `process.env` reads and can be re-exported to the client. |
diff --git a/server/lib/pgTools.js b/server/lib/pgTools.js
index ca9ba9f942..d1b88eb152 100644
--- a/server/lib/pgTools.js
+++ b/server/lib/pgTools.js
@@ -17,7 +17,8 @@
import { randomUUID } from 'node:crypto';
import { tmpdir } from 'node:os';
-import { readdir } from 'fs/promises';
+import { mkdtemp, readdir, rm, writeFile } from 'fs/promises';
+import { getCACertificates } from 'node:tls';
import { join } from 'path';
import { execFileAsync } from './fileUtils.js';
@@ -141,7 +142,7 @@ export async function resolvePgDumpBinary(serverMajor) {
* Inline certificate material needs a separate managed-file adapter; refuse it
* rather than silently sending a child with weaker authentication.
*/
-export function buildPgToolEnv(config, inherited = process.env) {
+function buildPgToolEnv(config, inherited = process.env, rootCertPath) {
const env = Object.fromEntries(Object.entries(inherited).filter(([key]) => !/^PG/i.test(key)));
const ssl = config.ssl;
if (ssl && typeof ssl === 'object' && Object.keys(ssl).some(key => key !== 'rejectUnauthorized')) {
@@ -149,8 +150,10 @@ export function buildPgToolEnv(config, inherited = process.env) {
}
env.PGPASSWORD = config.password;
env.PGSSLMODE = ssl ? (ssl.rejectUnauthorized === false ? 'require' : 'verify-full') : 'disable';
- // Verified node-postgres TLS uses the system trust store, never ~/.postgresql.
- if (env.PGSSLMODE === 'verify-full') env.PGSSLROOTCERT = 'system';
+ if (env.PGSSLMODE === 'verify-full') {
+ if (!rootCertPath) throw new Error('Verified PostgreSQL TLS requires a managed root certificate file');
+ env.PGSSLROOTCERT = rootCertPath;
+ }
// libpq's require mode verifies a default root.crt when one exists. An
// intentionally absent, unique path preserves node-postgres no-verify TLS.
if (env.PGSSLMODE === 'require') env.PGSSLROOTCERT = join(tmpdir(), `portos-unused-root-${randomUUID()}.crt`);
@@ -162,3 +165,17 @@ export function buildPgToolEnv(config, inherited = process.env) {
env.PGSSLNEGOTIATION = config.sslnegotiation || 'postgres';
return env;
}
+
+/** Run a tool with the Node TLS trust roots in a private, temporary PEM file.
+ * Explicit files work on older supported libpq versions too. Cleanup covers
+ * successful children, spawn failures, timeouts and rejected callbacks.
+ */
+export async function withPgToolEnv(config, run) {
+ if (!config.ssl || config.ssl.rejectUnauthorized === false) return run(buildPgToolEnv(config));
+ const dir = await mkdtemp(join(tmpdir(), 'portos-pg-tls-'));
+ return (async () => {
+ const path = join(dir, 'roots.pem');
+ await writeFile(path, getCACertificates('default').join('\n'), { mode: 0o600 });
+ return run(buildPgToolEnv(config, process.env, path));
+ })().finally(() => rm(dir, { recursive: true, force: true }));
+}
diff --git a/server/lib/pgTools.test.js b/server/lib/pgTools.test.js
index f2ea9dfdde..b49bb869ff 100644
--- a/server/lib/pgTools.test.js
+++ b/server/lib/pgTools.test.js
@@ -27,7 +27,7 @@ vi.mock('./fileUtils.js', async (importOriginal) => {
import { readdir } from 'fs/promises';
import { execFileAsync } from './fileUtils.js';
import {
- buildPgToolEnv,
+ withPgToolEnv,
pickPgDump,
discoverPgDumpCandidates,
resolvePgDump,
@@ -176,19 +176,35 @@ describe('resolvePgDumpBinary', () => {
});
describe('PostgreSQL tool TLS policy', () => {
- it('uses system trust for verified TLS and preserves direct negotiation', () => {
- expect(buildPgToolEnv({ password: 'example', ssl: true, sslnegotiation: 'direct' }, { PATH: '/example/bin', PGSSLROOTCERT: 'poisoned', PGSSLMODE: 'disable' })).toMatchObject({
- PATH: '/example/bin', PGPASSWORD: 'example', PGSSLMODE: 'verify-full', PGSSLROOTCERT: 'system', PGSSLNEGOTIATION: 'direct',
+ it('uses explicit trust roots for verified TLS and preserves direct negotiation', async () => {
+ await withPgToolEnv({ password: 'example', ssl: true, sslnegotiation: 'direct' }, env => {
+ expect(env).toMatchObject({ PGPASSWORD: 'example', PGSSLMODE: 'verify-full', PGSSLNEGOTIATION: 'direct' });
+ expect(env.PGSSLROOTCERT).toMatch(/roots.pem$/);
});
});
- it('requires encrypted no-verify TLS without loading ambient root certificates', () => {
- const env = buildPgToolEnv({ ssl: { rejectUnauthorized: false } }, {});
- expect(env.PGSSLMODE).toBe('require');
- expect(env.PGSSLROOTCERT).toMatch(/portos-unused-root-.*\.crt$/);
+ it('requires encrypted no-verify TLS without loading ambient root certificates', async () => {
+ await withPgToolEnv({ ssl: { rejectUnauthorized: false } }, env => {
+ expect(env.PGSSLMODE).toBe('require');
+ expect(env.PGSSLROOTCERT).toMatch(/portos-unused-root-.*\.crt$/);
+ });
+ });
+
+ it('refuses inline certificates rather than discarding the pool authentication policy', async () => {
+ await expect(withPgToolEnv({ ssl: { ca: 'example-ca' } }, () => {})).rejects.toThrow('inline pool TLS');
});
+});
- it('refuses inline certificates rather than discarding the pool authentication policy', () => {
- expect(() => buildPgToolEnv({ ssl: { ca: 'example-ca' } }, {})).toThrow('inline pool TLS');
+describe('managed PostgreSQL TLS roots', () => {
+ it('removes the private trust file when the child callback rejects', async () => {
+ const { readFile, stat } = await import('node:fs/promises');
+ let path;
+ await expect(withPgToolEnv({ ssl: true }, async env => {
+ path = env.PGSSLROOTCERT;
+ expect(await readFile(path, 'utf8')).toContain('BEGIN CERTIFICATE');
+ expect((await stat(path)).mode & 0o777).toBe(0o600);
+ throw new Error('example spawn failure');
+ })).rejects.toThrow('example spawn failure');
+ await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' });
});
});
diff --git a/server/services/backup.js b/server/services/backup.js
index 0e4c94b302..ed139422e0 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -18,7 +18,7 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createLineReader } from '../lib/streamLines.js';
import { getEvent } from './eventScheduler.js';
import { POOL_CONFIG, checkHealth, ensureSchema, getServerMajorVersion, query, withDatabaseMaintenance } from '../lib/db.js';
-import { buildPgToolEnv, resolvePgDumpBinary } from '../lib/pgTools.js';
+import { withPgToolEnv, resolvePgDumpBinary } from '../lib/pgTools.js';
import { inspectDatabaseDump } from './backupDatabaseDump.js';
import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';
import { getBackendName } from './memoryBackend.js';
@@ -695,7 +695,6 @@ export async function dumpPostgres(outputPath) {
const { host: pgHost, port, database: pgDb, user: pgUser } = POOL_CONFIG;
const pgPort = String(port);
- const pgEnv = buildPgToolEnv(POOL_CONFIG);
// pg_dump must be >= the server's major version or it aborts on a "server
// version mismatch". On machines with multiple Postgres installs (the common
@@ -711,7 +710,7 @@ export async function dumpPostgres(outputPath) {
console.warn(`⚠️ No installed pg_dump satisfies server major ${serverMajor} (using ${pgDumpBin})`);
}
- return new Promise((resolvePromise) => {
+ return withPgToolEnv(POOL_CONFIG, pgEnv => new Promise((resolvePromise) => {
// --clean --if-exists: the dump DROPs each object before recreating it, so it
// replays cleanly into the live, already-initialized PortOS database (the
// common Restore-DB target) instead of erroring "relation already exists" on
@@ -794,7 +793,7 @@ export async function dumpPostgres(outputPath) {
console.warn(`⚠️ pg_dump not available: ${err.message}`);
resolvePromise({ status: 'failed', reason: 'pg_dump_missing', error: err.message });
});
- });
+ }));
}
// Filesystem messages contain private paths; only expose the operation and errno.
@@ -1604,9 +1603,8 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI
const feedPositions = await captureSyncFeedPositions();
const { host: pgHost, port, database: pgDb, user: pgUser } = POOL_CONFIG;
const pgPort = String(port);
- const pgEnv = buildPgToolEnv(POOL_CONFIG);
- const replay = await new Promise((resolveP) => {
+ const replay = await withPgToolEnv(POOL_CONFIG, pgEnv => new Promise((resolveP) => {
// ON_ERROR_STOP=1 aborts on the first failed statement; --single-transaction
// wraps the whole replay in one transaction so that abort ROLLs BACK every
// prior statement. Together they make the restore atomic: it either fully
@@ -1653,7 +1651,7 @@ async function restoreAdmittedDump({ sqlPath, spoolPath, expectedHash, snapshotI
console.warn(`⚠️ psql not available: ${err.message}`);
resolveP({ status: 'failed', reason: 'restore_error', error: err.message });
});
- });
+ }));
if (replay.status !== 'ok') return replay;
// Replay has committed. Reapply this version's upgrades even when readiness
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 27836d22c1..5f84872142 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1353,7 +1353,7 @@ describe('restorePostgres', () => {
await flush();
proc.emit('close', 0);
await flush();
- expect(ensureSchema).toHaveBeenCalledWith({ force: true });
+ await vi.waitFor(() => expect(ensureSchema).toHaveBeenCalledWith({ force: true }));
expect(runDbMigrations).not.toHaveBeenCalled();
expect(settled).toBe(false);
finishSchema();