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([issue-1333]): broaden test-DB write guard to catch CTE/COPY/MERGE/multi-statement writes
[._.]/ Adam Eivy347d5fa5de5c
diff --git a/server/lib/db.guards.test.js b/server/lib/db.guards.test.jsindex 81bc8c94f9..724403fb59 100644--- a/server/lib/db.guards.test.js+++ b/server/lib/db.guards.test.js@@ -13,11 +13,15 @@* that left NODE_ENV unset is still gated.* - checkHealth() — reports "disconnected" under the test runner on a real* DB so every db-backed suite skips via its existing branch.- * - query() — hard backstop: throws on ANY row write (INSERT/UPDATE/- * DELETE/TRUNCATE) under the test runner on a non-test DB- * even if a suite reaches it without gating on checkHealth- * first. (DELETE-only guarding let test INSERTs leak- * fixtures into the real `portos` DB on 2026-06-14.)+ * - query() — hard backstop: throws on ANY row write — INSERT/UPDATE/+ * DELETE/TRUNCATE/MERGE, COPY … FROM imports, data-+ * modifying CTEs, and a write hidden in a multi-statement+ * batch — under the test runner on a non-test DB even if a+ * suite reaches it without gating on checkHealth first.+ * (DELETE-only guarding let test INSERTs leak fixtures+ * into the real `portos` DB on 2026-06-14; the `^`-anchored+ * single-verb match then let CTE/COPY/MERGE/multi-statement+ * writes slip past — #1333.)* - withTransaction() — the SAME backstop on the raw pg client it hands the* callback. client.query() bypasses query() entirely, so* every store mutation that writes inside a transaction@@ -247,6 +251,112 @@ describe('assertWriteAllowed (shared query + transaction-client backstop)', () =});});+// #1333: the original `^`-anchored single-verb match only saw the FIRST keyword,+// so four less-obvious write forms slipped past the backstop. No current store+// uses them (latent, not exploitable), but the guard is billed as the last line+// of defense, so it must catch them — without false-positiving the read forms+// they shadow (`COPY … TO` exports, `SELECT … FOR UPDATE` row locks).+describe('assertWriteAllowed broadened write forms (#1333)', () => {+ const armProd = () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ };++ it('throws on a data-modifying CTE whose write is the leading statement', () => {+ armProd();+ expect(() =>+ assertWriteAllowed(+ 'WITH doomed AS (SELECT id FROM universes LIMIT 1) ' ++ 'DELETE FROM universes WHERE id IN (SELECT id FROM doomed)',+ ),+ ).toThrow(/Refusing to mutate/i);+ });++ it('throws on a CTE whose write hides inside the WITH body', () => {+ armProd();+ expect(() =>+ assertWriteAllowed(+ "WITH ins AS (INSERT INTO authors (id) VALUES ('x') RETURNING id) SELECT * FROM ins",+ ),+ ).toThrow(/Refusing to mutate/i);+ expect(() =>+ assertWriteAllowed(+ "WITH u AS (UPDATE pipeline_series SET name = 'x' RETURNING id) SELECT * FROM u",+ ),+ ).toThrow(/Refusing to mutate/i);+ });++ it('throws on MERGE INTO', () => {+ armProd();+ expect(() =>+ assertWriteAllowed(+ 'MERGE INTO authors a USING src s ON a.id = s.id ' ++ 'WHEN MATCHED THEN UPDATE SET data = s.data',+ ),+ ).toThrow(/Refusing to mutate/i);+ });++ it('throws on COPY … FROM imports (table and column-list forms)', () => {+ armProd();+ expect(() => assertWriteAllowed("COPY authors FROM '/tmp/authors.csv' CSV")).toThrow(+ /Refusing to mutate/i,+ );+ expect(() => assertWriteAllowed('COPY authors (id, data) FROM STDIN')).toThrow(+ /Refusing to mutate/i,+ );+ });++ it('allows COPY … TO exports (a read), including the subquery form', () => {+ armProd();+ // COPY <table> TO and COPY (query) TO are exports — the inner FROM of the+ // subquery must NOT read as a write.+ expect(() => assertWriteAllowed('COPY authors TO STDOUT')).not.toThrow();+ expect(() =>+ assertWriteAllowed('COPY (SELECT * FROM authors) TO STDOUT'),+ ).not.toThrow();+ });++ it('throws on a write hidden after a read in a multi-statement batch', () => {+ armProd();+ expect(() => assertWriteAllowed('SELECT 1; DELETE FROM universes')).toThrow(+ /Refusing to mutate/i,+ );+ });++ it('does not false-positive on a multi-statement read batch', () => {+ armProd();+ expect(() => assertWriteAllowed('SELECT 1; SELECT 2 FROM authors')).not.toThrow();+ });++ it('does not false-positive on a write verb that only appears in a comment', () => {+ armProd();+ expect(() =>+ assertWriteAllowed('-- DELETE FROM old_universes (historical note)\nSELECT 1'),+ ).not.toThrow();+ expect(() =>+ assertWriteAllowed('/* TODO: TRUNCATE legacy */ SELECT count(*) FROM authors'),+ ).not.toThrow();+ });++ it('does not false-positive on SELECT … FOR UPDATE / FOR NO KEY UPDATE row locks', () => {+ armProd();+ expect(() =>+ assertWriteAllowed('SELECT data FROM authors WHERE id = $1 FOR UPDATE'),+ ).not.toThrow();+ expect(() =>+ assertWriteAllowed('SELECT data FROM authors WHERE id = $1 FOR NO KEY UPDATE'),+ ).not.toThrow();+ });++ it('allows the broadened write forms against a designated test DB', () => {+ setEnv('PGDATABASE', 'portos_test');+ setEnv('TEST_DB_OK', undefined);+ expect(() => assertWriteAllowed('MERGE INTO authors a USING src s ON a.id = s.id')).not.toThrow();+ expect(() => assertWriteAllowed("COPY authors FROM '/tmp/x.csv'")).not.toThrow();+ expect(() => assertWriteAllowed('SELECT 1; DELETE FROM authors')).not.toThrow();+ });+});+// Drift guard: a DB-backed suite skips on a non-test DB (correct), so if a new// one is left out of vitest.config.db.js it would simply NEVER run — silently// losing coverage with a green board. This asserts every real DB-backed suitediff --git a/server/lib/db.js b/server/lib/db.jsindex aa8a33c668..52a80b2ecb 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -82,16 +82,55 @@ export function isTestRunner() {// series/issues/story-builder fixtures leaked into the real `portos` DB and// federated to peers. INSERT/UPDATE are now blocked too. Schema DDL// (CREATE/ALTER/DROP) is still allowed: it is idempotent, carries no row-data,-// and ensureSchema() needs it to stand up portos_test. Skips leading-// line/block comments + whitespace before the verb.-const ROW_WRITE_SQL =- /^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/|\s)*(INSERT\s+INTO|UPDATE\s|DELETE\s+FROM|TRUNCATE)\b/i;+// and ensureSchema() needs it to stand up portos_test.+//+// The first cut was `^`-anchored on a single leading verb, which let four+// less-obvious write forms slip past the "absolute backstop": data-modifying+// CTEs (`WITH … DELETE …`), `COPY … FROM` imports, `MERGE INTO`, and a write+// hiding after a leading read in a multi-statement batch (`SELECT 1; DELETE …`).+// No current store issues those forms, so this was latent rather than+// exploitable — but the guard is billed as the last line of defense, so it now+// matches a write verb ANYWHERE, after stripping comments so a keyword named in+// a comment can't trip it (and a write after a comment can't slip past).+//+// Comments are stripped first (not just a leading block) so `-- DELETE FROM x`+// in a header doesn't false-positive a harmless SELECT, and a write hidden after+// a non-leading comment is still caught. A `--`/`/*` inside a string literal is a+// theoretical edge this test-only backstop accepts.+function stripSqlComments(text) {+ return text.replace(/--[^\n]*/g, ' ').replace(/\/\*[\s\S]*?\*\//g, ' ');+}++const ROW_WRITE_PATTERNS = [+ /\bINSERT\s+INTO\b/i,+ /\bDELETE\s+FROM\b/i,+ /\bMERGE\s+INTO\b/i,+ /\bTRUNCATE\b/i,+ // UPDATE … SET — the SET clause is what makes it a write, and distinguishes it+ // from a `SELECT … FOR UPDATE` / `FOR NO KEY UPDATE` row-lock read. `[^;]+?`+ // keeps the match inside one statement so `… FOR UPDATE; SET search_path …`+ // (a read followed by a session command) doesn't read as an UPDATE write.+ /\bUPDATE\b\s+[^;]+?\bSET\b/i,+ // COPY <table> FROM — an import writes rows. `COPY (query) TO` / `COPY <table>+ // TO` is an export (read): the `(?!\()` rejects the subquery-export form whose+ // inner FROM would otherwise match, and requiring FROM before the next `;`+ // leaves `COPY <table> TO …` (no FROM) alone.+ /\bCOPY\s+(?!\()[^;]*?\bFROM\b/i,+];++// True when the SQL performs a row write in any of the recognized forms.+function isRowWriteSql(text) {+ const sql = stripSqlComments(text);+ return ROW_WRITE_PATTERNS.some((re) => re.test(sql));+}/*** Hard backstop: under the test runner, refuse to MUTATE a non-test database.- * Throws (fail loudly) on any row write (INSERT/UPDATE/DELETE/TRUNCATE) instead- * of silently writing — or stranding — real data. Reads (SELECT) and schema DDL- * are left alone so health/version probes and ensureSchema() still work.+ * Throws (fail loudly) on any row write — INSERT/UPDATE/DELETE/TRUNCATE/MERGE,+ * COPY … FROM imports, data-modifying CTEs, and a write hidden in a multi-+ * statement batch — instead of silently writing (or stranding) real data. Reads+ * (SELECT, including COPY … TO exports) and schema DDL are left alone so+ * health/version probes and ensureSchema() still work.** Shared by BOTH the pool `query()` wrapper and the per-transaction client in* `withTransaction()`. The transaction path is critical: nearly every store@@ -108,7 +147,7 @@ export function assertWriteAllowed(text) {isTestRunner() &&!isTestDatabase() &&typeof text === 'string' &&- ROW_WRITE_SQL.test(text)+ isRowWriteSql(text)) {throw new Error(`🛑 Refusing to mutate non-test database '${process.env.PGDATABASE || 'portos'}' under the test runner. ` +