@aria-framework/db-worker 0.19.0 → 0.20.0

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.
Files changed (3) hide show
  1. package/README.md +34 -3
  2. package/database.js +88 -10
  3. package/package.json +44 -44
package/README.md CHANGED
@@ -106,11 +106,42 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
106
106
  busy_timeout=5000` and creates the `migrations` tracking table.
107
107
  **`onOpen(db)` runs FIRST, before any pragma or table access** — this is the
108
108
  SQLCipher hook: an encrypted DB needs `pragma key` before anything touches it.
109
- - `runMigrations(migrationsDir)` — applies `*.sql` sorted by filename, each in
110
- a transaction with its tracking-row insert; already-applied files skipped.
111
- A file can opt out — see below.
109
+ - `runMigrations(migrationsDir, { connectionString } = {})` — applies `*.sql` sorted by
110
+ filename, each in a transaction with its tracking-row insert; already-applied files
111
+ skipped. A file can opt out — see below. `connectionString` runs the migrations as a
112
+ different role — see next section.
112
113
  - `getDb()` / `close()`
113
114
 
115
+ ## Migrations as a separate owner role (0.20.0, Postgres)
116
+
117
+ **In Postgres the role that creates a table owns it, and an owner bypasses `ENABLE ROW LEVEL
118
+ SECURITY`.** So an application that runs its own migrations owns every table it migrated, and a
119
+ tenant boundary built on RLS then rests entirely on `FORCE` being set on every table, for ever —
120
+ including the ones tomorrow's migration adds.
121
+
122
+ ```js
123
+ await database.initDriver({ kind: 'postgres', connectionString: process.env.DATABASE_URL });
124
+ await database.runMigrations(dir, { connectionString: process.env.MIGRATION_DATABASE_URL });
125
+ ```
126
+
127
+ With `connectionString`, migrations run on a **separate, short-lived connection** as that role, and
128
+ the application's own driver is never touched. That connection is **destroyed** afterwards, not
129
+ returned to a pool: a pooled privileged connection that a later application query could draw would
130
+ bypass every partner boundary silently — no error, no symptom, wrong rows.
131
+
132
+ The migrations **ledger** is created on that connection too. Created by the app role it would be
133
+ one app-owned table in an otherwise correctly-owned schema, and one is enough.
134
+
135
+ Afterwards the runner asks the *application's* driver who it actually is and **throws** if it holds
136
+ `BYPASSRLS`. Everything above is intent; that check is what makes it a fact.
137
+
138
+ On SQLite there are no roles, so the option is ignored — and says so in the log rather than being
139
+ silently dropped.
140
+
141
+ > Provisioning the roles is the consuming app's job. `aria-starter` ships
142
+ > `scripts/test-pg-provisioning.js`, which asserts the application role owns nothing and holds no
143
+ > `BYPASSRLS`, that every RLS table is also `FORCE`d, and that the backup role can actually read.
144
+
114
145
  ## Migrations that cannot run inside a transaction (0.8.0)
115
146
 
116
147
  Some DDL is illegal inside a transaction. A migration declares that with a
package/database.js CHANGED
@@ -330,10 +330,19 @@ function coveredBy(file, through, files) {
330
330
  *
331
331
  * @returns {Promise<{applied: number}>}
332
332
  */
333
- function runMigrations(migrationsDir) {
333
+ function runMigrations(migrationsDir, opts = {}) {
334
334
  const d = driver();
335
335
  if (!d) throw new Error('runMigrations: call init()/initDriver() first');
336
336
 
337
+ // ANNOUNCED, NOT SILENTLY DROPPED. SQLite has no roles, so a migration connection string is
338
+ // meaningless there — but an argument that is quietly ignored is how a dual-engine app ends up
339
+ // believing its migrations run as a separate role when they never have. Said out loud instead.
340
+ if (opts.connectionString && d.kind !== 'postgres') {
341
+ _logger.warn(`runMigrations: a migration connectionString was supplied but the driver is `
342
+ + `'${d.kind}', which has no roles — it is being IGNORED and migrations run on the ordinary `
343
+ + 'connection. Pass it only on Postgres.');
344
+ }
345
+
337
346
  if (!migrationsDir || !fs.existsSync(migrationsDir)) {
338
347
  _logger.warn('No migrations directory found');
339
348
  return Promise.resolve({ applied: 0 });
@@ -391,7 +400,71 @@ function runMigrations(migrationsDir) {
391
400
 
392
401
  // ── the async path, for engines that have no synchronous driver ───────────────────────────
393
402
  return (async () => {
394
- const applied = new Set((await d.all('SELECT filename FROM migrations')).map((r) => r.filename));
403
+ // ── THE MIGRATION CONNECTION ────────────────────────────────────────────────────────────
404
+ //
405
+ // In Postgres THE ROLE THAT CREATES A TABLE OWNS IT, and an owner bypasses ENABLE ROW LEVEL
406
+ // SECURITY. So an application that runs its own migrations owns every table it migrated, and
407
+ // the whole tenant boundary then rests on FORCE being present on every table for ever —
408
+ // including the ones tomorrow's migration adds. Frozen spec §3: the application connects as a
409
+ // role that owns nothing; the migration role and the backup role are the only BYPASSRLS
410
+ // holders.
411
+ //
412
+ // Given `connectionString`, migrations run on a SEPARATE, SHORT-LIVED connection as that
413
+ // owner/migration role, and the application's own driver is never touched. It is opened here
414
+ // and destroyed in the finally below — NOT returned to a pool, because a pooled privileged
415
+ // connection that a later app query could draw would bypass every partner boundary silently,
416
+ // with no error and no symptom. That is the one outcome worse than the problem being fixed.
417
+ const owner = opts.connectionString
418
+ ? require('./driver/postgres').createPostgresDriver({
419
+ connectionString: opts.connectionString,
420
+ logger: _logger
421
+ })
422
+ : null;
423
+ const md = owner || d;
424
+
425
+ try {
426
+ // The LEDGER on the migration connection too. Created by the app role, `migrations` would be
427
+ // one app-owned table in an otherwise correctly-owned schema — and one is enough.
428
+ if (owner) await ensureMigrationsTable(owner);
429
+ return await runMigrationsOn(md);
430
+ } finally {
431
+ if (owner) {
432
+ // AWAITED, AND ITS FAILURE IS LOUD. A close that quietly failed would leave exactly the
433
+ // privileged pool this design exists to avoid, and the run would still report success.
434
+ await owner.close();
435
+ _logger.info('Migration connection closed (the application keeps its own, unprivileged)');
436
+
437
+ // ── AND THEN PROVE IT, rather than trusting that we did ────────────────────────────────
438
+ //
439
+ // Everything above is intent. This is the only line that turns it into a fact: ask the
440
+ // APPLICATION's driver who it actually is, now that migrations are done. If a privileged
441
+ // connection ever leaked into the pool the app draws from — a close that silently failed,
442
+ // a driver that shared a pool, a future refactor that reused the handle — every partner
443
+ // boundary in the schema would be off, with no error and no symptom. That is a failure
444
+ // you discover from a customer, so it is checked at boot instead.
445
+ //
446
+ // Deliberately AFTER the close and inside the finally: it must run even when a migration
447
+ // threw, because a half-applied run leaves the connection state least understood.
448
+ const [who] = await d.all(
449
+ 'SELECT current_user AS role, '
450
+ + '(SELECT rolbypassrls FROM pg_roles WHERE rolname = current_user) AS bypassrls');
451
+ if (who && who.bypassrls) {
452
+ throw new Error(
453
+ `runMigrations: after closing the migration connection the APPLICATION driver is still `
454
+ + `connected as ${who.role}, which holds BYPASSRLS. Row-level security does not apply `
455
+ + 'to it, so every partner boundary in this schema is inert. The application must '
456
+ + 'connect as a role that owns nothing and has no BYPASSRLS (frozen spec §3); only the '
457
+ + 'migration and backup roles may hold it.');
458
+ }
459
+ }
460
+ }
461
+ })();
462
+
463
+ // HOISTED, and called from the wrapper above. The body is unchanged from the version that ran
464
+ // on the singleton; the only difference is that the driver arrives as an argument, so the same
465
+ // code path serves both the ordinary case and the separate-owner case. Two copies would drift.
466
+ async function runMigrationsOn(md) {
467
+ const applied = new Set((await md.all('SELECT filename FROM migrations')).map((r) => r.filename));
395
468
  let count = 0;
396
469
  for (const file of files) {
397
470
  if (applied.has(file)) continue;
@@ -402,7 +475,7 @@ function runMigrations(migrationsDir) {
402
475
  if (wantsNoTransaction(sql, file)) {
403
476
  _logger.warn(noTxWarning(file));
404
477
  try {
405
- await d.exec(sql);
478
+ await md.exec(sql);
406
479
  } catch (e) {
407
480
  // Rewrite the multi-statement failure into the instruction that fixes it — but ONLY
408
481
  // when the file really does contain more than one statement. Gating matters: VACUUM,
@@ -422,11 +495,11 @@ function runMigrations(migrationsDir) {
422
495
  // A marked file that opened a transaction and did not close it would otherwise return
423
496
  // an "idle in transaction" client to the pool, holding its locks and snapshot for every
424
497
  // later caller that draws it. Cheap to assert, unbounded to leave.
425
- try { await d.exec('ROLLBACK'); } catch (_) { /* no transaction open: the normal case */ }
498
+ try { await md.exec('ROLLBACK'); } catch (_) { /* no transaction open: the normal case */ }
426
499
  }
427
- await d.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
500
+ await md.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
428
501
  } else {
429
- await d.transaction(async (tx) => {
502
+ await md.transaction(async (tx) => {
430
503
  await tx.exec(sql);
431
504
  await tx.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
432
505
  });
@@ -434,7 +507,7 @@ function runMigrations(migrationsDir) {
434
507
  if (through !== null) {
435
508
  for (const covered of coveredBy(file, through, files)) {
436
509
  if (applied.has(covered)) continue;
437
- await d.run('INSERT INTO migrations (filename) VALUES (?)', [covered]);
510
+ await md.run('INSERT INTO migrations (filename) VALUES (?)', [covered]);
438
511
  applied.add(covered);
439
512
  }
440
513
  _logger.info(`Migration ${file} covers everything through ${through} — ledgered, not run`);
@@ -444,7 +517,7 @@ function runMigrations(migrationsDir) {
444
517
  }
445
518
  _logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
446
519
  return { applied: count };
447
- })();
520
+ }
448
521
  }
449
522
 
450
523
  /** Adopt the handle init() just opened — the driver must not open a second connection. */
@@ -498,8 +571,13 @@ function driver() {
498
571
  * `initDriver({ kind: 'postgres', connectionString })` is how a Postgres-native app boots;
499
572
  * `kind: 'sqlite'` is identical to init() but hands back the driver as well.
500
573
  */
501
- async function ensureMigrationsTable() {
502
- const d = driver();
574
+ async function ensureMigrationsTable(given) {
575
+ // TAKES A DRIVER, because the ledger must be created by whichever role runs the migrations. It
576
+ // used to read the singleton unconditionally, so `migrations` was created — and therefore
577
+ // OWNED — by the APPLICATION role even when a separate owner role applied everything else. One
578
+ // table with the wrong owner is enough to reintroduce the whole problem, because an owner
579
+ // bypasses ENABLE ROW LEVEL SECURITY.
580
+ const d = given || driver();
503
581
  const t = d.dialect;
504
582
  // The LEDGER is the one table the framework owns, so it is the one DDL that must be
505
583
  // dialect-aware. Everything else is the app's.
package/package.json CHANGED
@@ -1,44 +1,44 @@
1
- {
2
- "name": "@aria-framework/db-worker",
3
- "version": "0.19.0",
4
- "description": "Aria App Framework — 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
- "license": "UNLICENSED",
6
- "private": false,
7
- "publishConfig": {
8
- "access": "public"
9
- },
10
- "main": "index.js",
11
- "files": [
12
- "client.js",
13
- "database.js",
14
- "dialect.js",
15
- "driver/",
16
- "index.js",
17
- "schemaSnapshot.js",
18
- "settingsStore.js",
19
- "tableOrder.js",
20
- "tenancyMigration.js",
21
- "tenantContext.js",
22
- "worker.js",
23
- "workerRegistry.js"
24
- ],
25
- "peerDependencies": {
26
- "better-sqlite3": ">=9",
27
- "pg": ">=8"
28
- },
29
- "peerDependenciesMeta": {
30
- "better-sqlite3": {
31
- "optional": true
32
- },
33
- "pg": {
34
- "optional": true
35
- }
36
- },
37
- "devDependencies": {
38
- "better-sqlite3": "^12.10.0",
39
- "pg": "^8.23.0"
40
- },
41
- "scripts": {
42
- "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/smoke.js && node test/tier2.js"
43
- }
44
- }
1
+ {
2
+ "name": "@aria-framework/db-worker",
3
+ "version": "0.20.0",
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
+ "license": "UNLICENSED",
6
+ "private": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "main": "index.js",
11
+ "files": [
12
+ "client.js",
13
+ "database.js",
14
+ "dialect.js",
15
+ "driver/",
16
+ "index.js",
17
+ "schemaSnapshot.js",
18
+ "settingsStore.js",
19
+ "tableOrder.js",
20
+ "tenancyMigration.js",
21
+ "tenantContext.js",
22
+ "worker.js",
23
+ "workerRegistry.js"
24
+ ],
25
+ "peerDependencies": {
26
+ "better-sqlite3": ">=9",
27
+ "pg": ">=8"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "better-sqlite3": {
31
+ "optional": true
32
+ },
33
+ "pg": {
34
+ "optional": true
35
+ }
36
+ },
37
+ "devDependencies": {
38
+ "better-sqlite3": "^12.10.0",
39
+ "pg": "^8.23.0"
40
+ },
41
+ "scripts": {
42
+ "test": "node test/driverContract.js && node test/migrations.js && node test/migrations-notx.js && node test/migrationDialect.js && node test/regressions.js && node test/transactions.js && node test/tenantContext.js && node test/tenancyMigration.js && node test/dialectIntrospection.js && node test/tenantRls.pg.js && node test/nestedTransaction.pg.js && node test/migrationRole.pg.js && node test/smoke.js && node test/tier2.js"
43
+ }
44
+ }