@aria-framework/db-worker 0.20.3 → 0.20.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/database.js CHANGED
@@ -422,11 +422,15 @@ function runMigrations(migrationsDir, opts = {}) {
422
422
  : null;
423
423
  const md = owner || d;
424
424
 
425
+ let migrationError = null;
425
426
  try {
426
427
  // The LEDGER on the migration connection too. Created by the app role, `migrations` would be
427
428
  // one app-owned table in an otherwise correctly-owned schema — and one is enough.
428
429
  if (owner) await ensureMigrationsTable(owner);
429
430
  return await runMigrationsOn(md);
431
+ } catch (e) {
432
+ migrationError = e; // remembered so the finally does not overwrite it
433
+ throw e;
430
434
  } finally {
431
435
  if (owner) {
432
436
  // AWAITED, AND ITS FAILURE IS LOUD. A close that quietly failed would leave exactly the
@@ -445,6 +449,18 @@ function runMigrations(migrationsDir, opts = {}) {
445
449
  //
446
450
  // Deliberately AFTER the close and inside the finally: it must run even when a migration
447
451
  // threw, because a half-applied run leaves the connection state least understood.
452
+ // ── AND IT MUST NOT REPLACE THE REASON WE GOT HERE ────────────────────────────────────
453
+ //
454
+ // This runs in a `finally`, so it also runs when a MIGRATION FAILED. Throwing from here
455
+ // would discard that failure — the operator would see a connection error instead of the
456
+ // SQL that broke, at the one moment a half-applied chain makes the real cause matter most.
457
+ // So the proof is skipped when we are already unwinding an error, and any failure of the
458
+ // proof ITSELF is reported rather than thrown when there is a prior error to preserve.
459
+ if (migrationError) {
460
+ _logger.warn('Skipping the BYPASSRLS proof: a migration already failed, and its error is '
461
+ + 'the one worth keeping. Re-run once that is fixed.');
462
+ return;
463
+ }
448
464
  const [who] = await d.all(
449
465
  'SELECT current_user AS role, '
450
466
  + '(SELECT rolbypassrls FROM pg_roles WHERE rolname = current_user) AS bypassrls');
@@ -571,7 +587,7 @@ function driver() {
571
587
  * `initDriver({ kind: 'postgres', connectionString })` is how a Postgres-native app boots;
572
588
  * `kind: 'sqlite'` is identical to init() but hands back the driver as well.
573
589
  */
574
- async function ensureMigrationsTable(given) {
590
+ async function ensureMigrationsTable(given, opts = {}) {
575
591
  // TAKES A DRIVER, because the ledger must be created by whichever role runs the migrations. It
576
592
  // used to read the singleton unconditionally, so `migrations` was created — and therefore
577
593
  // OWNED — by the APPLICATION role even when a separate owner role applied everything else. One
@@ -611,6 +627,25 @@ async function ensureMigrationsTable(given) {
611
627
  // almost always that migrations have simply never been run against this database as the role
612
628
  // that is allowed to.
613
629
  if (d.kind === 'postgres' && /permission denied for schema/i.test(e.message || '')) {
630
+ // ── OPTIONAL AT init(), REQUIRED AT runMigrations() ────────────────────────────────────
631
+ //
632
+ // 0.20.1 fixed the case where the ledger ALREADY EXISTS and left the fresh-install case
633
+ // unbootable: an empty database plus an application role that correctly holds no CREATE
634
+ // means initDriver could not create the ledger and threw. Its own message said to run the
635
+ // migrations first — and runMigrations begins `const d = driver(); if (!d) throw`, so it
636
+ // cannot run until initDriver has succeeded. A chicken-and-egg that made every NEW,
637
+ // correctly provisioned Postgres database impossible to start, which is precisely the
638
+ // database every new app begins with.
639
+ //
640
+ // So initDriver ASKS and moves on. runMigrations creates the ledger on the migration
641
+ // connection, where the role may. A caller that never migrates and then queries the ledger
642
+ // still fails, loudly, naming the missing relation.
643
+ if (opts.optional) {
644
+ _logger.warn('db-worker: the migrations ledger does not exist yet and this role may not '
645
+ + 'create it — which is correct for an application role. runMigrations() will create it '
646
+ + 'on the migration connection. Continuing.');
647
+ return;
648
+ }
614
649
  throw new Error(
615
650
  'db-worker: the migrations ledger does not exist and this role may not create it — '
616
651
  + `${e.message}. This is the expected shape when the application connects as a role that `
@@ -637,7 +672,9 @@ async function initDriver(opts = {}) {
637
672
  } else {
638
673
  throw new Error(`initDriver: unknown kind '${kind}'`);
639
674
  }
640
- await ensureMigrationsTable();
675
+ // optional: a fresh database plus a non-owner app role is a legitimate state — see the note
676
+ // inside ensureMigrationsTable. runMigrations creates it as the role that may.
677
+ await ensureMigrationsTable(null, { optional: true });
641
678
  _logger = opts.logger || _logger;
642
679
  _logger.info(`Database opened (${kind})`);
643
680
  return _driver;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.20.3",
3
+ "version": "0.20.5",
4
4
  "description": "Aria App Framework \u2014 db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -64,6 +64,23 @@ function generateTenancyMigration(opts = {}) {
64
64
  // a schema that seeds a row is a row every future app inherits without choosing it.
65
65
  const seedHouse = opts.seedHousePartner !== false;
66
66
 
67
+ // THE ONE INPUT THAT IS THE BOUNDARY ITSELF, and it was the one not validated. An empty or
68
+ // missing POLICY_EXPRESSION generated `USING ()` for every table — a syntactically invalid
69
+ // migration, written to disk, reported as a success, failing only when it ran. manifest/dbPath/
70
+ // Database are all refused when absent; this deserves it more than any of them.
71
+ const policyExpr = String((manifest && manifest.POLICY_EXPRESSION) || '').trim();
72
+ if (!policyExpr) {
73
+ throw new Error('generateTenancyMigration: the manifest has no POLICY_EXPRESSION. That '
74
+ + 'expression IS the tenant boundary — generating `USING ()` would emit an invalid migration '
75
+ + 'that only fails when it runs, after the schema half has already applied.');
76
+ }
77
+
78
+ // Quoted for SQL, not interpolated raw. A name carrying an apostrophe — "O'Brien Holdings" —
79
+ // produced a syntax error inside a generated file nobody hand-reviews, and a name taken from
80
+ // configuration or a tenant record made this an injection seam into a migration that later runs
81
+ // as the OWNER role.
82
+ const sqlLiteral = (v) => `'${String(v).replace(/'/g, "''")}'`;
83
+
67
84
  const db = new Database(dbPath, { readonly: true });
68
85
  try {
69
86
  const scoped = manifest.scoped();
@@ -110,7 +127,7 @@ function generateTenancyMigration(opts = {}) {
110
127
  '-- a second partner is created. SEEDED HERE because this migration is a RETROFIT onto a',
111
128
  '-- database that already has rows: they are backfilled to partner 1, which therefore has',
112
129
  '-- to exist by the time the backfill runs.',
113
- `INSERT INTO partners (id, name, is_house) VALUES (1, '${houseName}', 1);`,
130
+ `INSERT INTO partners (id, name, is_house) VALUES (1, ${sqlLiteral(houseName)}, 1);`,
114
131
  ''
115
132
  ] : [
116
133
  '-- THE HOUSE PARTNER IS NOT SEEDED HERE. On a fresh installation there are no rows to',
@@ -216,8 +233,13 @@ function generateTenancyMigration(opts = {}) {
216
233
  // and RESTRICT/NO ACTION write nothing.
217
234
  const del = !fk.onDelete || fk.onDelete === 'NO ACTION'
218
235
  ? ''
219
- : (fk.onDelete === 'SET NULL'
220
- ? ` ON DELETE SET NULL (${fk.from})`
236
+ // SET DEFAULT IS THE SAME DEFECT. It fell through to the bare branch, so a composite
237
+ // key set BOTH columns to their defaults — and partner_id's default is
238
+ // current_setting('app.partner_id'), so a delete with no scope nulls a NOT NULL column
239
+ // and a delete under a DIFFERENT scope silently REPARENTS the child row to another
240
+ // tenant. Postgres 15+ takes a column list here too.
241
+ : (fk.onDelete === 'SET NULL' || fk.onDelete === 'SET DEFAULT'
242
+ ? ` ON DELETE ${fk.onDelete} (${fk.from})`
221
243
  : ` ON DELETE ${fk.onDelete}`);
222
244
  out.push(
223
245
  `ALTER TABLE ${table} ADD CONSTRAINT fk_${table}_${fk.from}_partner`
@@ -244,7 +266,7 @@ function generateTenancyMigration(opts = {}) {
244
266
  for (const w of widen) {
245
267
  const cols = ['partner_id', ...w.columns].join(', ');
246
268
  if (w.index) {
247
- out.push(`DROP INDEX ${w.index};`);
269
+ out.push(`DROP INDEX IF EXISTS ${w.index};`);
248
270
  out.push(`CREATE UNIQUE INDEX ${w.index} ON ${w.table} (${cols})`
249
271
  + (w.where ? ` WHERE ${w.where}` : '') + ';');
250
272
  } else {
@@ -328,12 +350,30 @@ function generateTenancyMigration(opts = {}) {
328
350
 
329
351
  const expr = String(manifest.POLICY_EXPRESSION || '').trim();
330
352
  const body = [];
331
- for (const { table } of ordered) {
353
+ for (const { table, nullable } of ordered) {
332
354
  body.push(`ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;`);
333
355
  body.push(`ALTER TABLE ${table} FORCE ROW LEVEL SECURITY;`);
334
356
  body.push(`CREATE POLICY tenant_isolation ON ${table} FOR ALL`);
335
- body.push(` USING (${expr})`);
336
- body.push(` WITH CHECK (${expr});`);
357
+ if (nullable) {
358
+ // ── A NULLABLE partner_id MEANS "INSTALLATION-WIDE DEFAULT", AND THE TWO HALVES DIFFER ──
359
+ //
360
+ // The manifest classifies a table nullable precisely so a row with NO partner can act as
361
+ // the default for every tenant. The policy used the same expression for both halves, and
362
+ // `partner_id = current_setting(...)` is NULL for such a row — not true — so the default
363
+ // was INVISIBLE to every partner-scoped read and unwritable by any of them. The whole
364
+ // point of the classification was inoperative on Postgres, and worked on SQLite, where
365
+ // there is no policy to get wrong. Measured: a partner-scoped session saw 0 of 1 such rows
366
+ // and its insert was refused by the policy.
367
+ //
368
+ // READING a default is every tenant's business; CREATING one is not. So USING admits the
369
+ // NULL row and WITH CHECK does not — and platform scope still writes them, because the
370
+ // expression's platform arm is `true` and covers the NULL case on its own.
371
+ body.push(` USING (partner_id IS NULL OR (${expr}))`);
372
+ body.push(` WITH CHECK (${expr});`);
373
+ } else {
374
+ body.push(` USING (${expr})`);
375
+ body.push(` WITH CHECK (${expr});`);
376
+ }
337
377
  body.push('');
338
378
  }
339
379
  const rlsFile = [