@mistriwork/engine 1.0.0-rc.51 → 1.0.0-rc.53

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.
@@ -24,7 +24,27 @@ export declare function postgresDescriptionCounts(): Readonly<{
24
24
  * An adapter on the manager every adapter of `url` with this `shape` shares (sharedPgConnections): its own catalog,
25
25
  * lanes and stores, the pools of its neighbors. Closing it lets its share go; the pools close with the last one.
26
26
  */
27
- export declare function sharedPostgresAdapter(url: string, label: string, shape?: SharedPoolShape): PostgresAdapter;
27
+ export declare function sharedPostgresAdapter(url: string, label: string, shape?: SharedPoolShape, options?: PostgresAdapterOptions): PostgresAdapter;
28
+ /** What an adapter is built with beyond its connection. */
29
+ export interface PostgresAdapterOptions {
30
+ /**
31
+ * The database's own tenant backstop (row security): the role this adapter's connections run as, which every
32
+ * tenant table's one row policy names. With it, a scoped transaction and a read snapshot given a tenant set
33
+ * `mistri.tenant` for the policy to read, the scope catalog accepts exactly that policy (postgresScopeCatalog.ts),
34
+ * and an autocommit scoped read, which no tenant rides with, refuses. A scoped transaction or snapshot asked with no
35
+ * tenant at all refuses too, so a path that forgot its tenant is an error rather than an empty answer; `null` is the
36
+ * deliberate none (a store's or the catalog's own read). Without it, nothing the adapter sends changes.
37
+ *
38
+ * `bypass`: this adapter connects as the tables' owner, which the policy (`TO` the runtime `role`) does not bind —
39
+ * the paths that cross tenants by design. Its catalogs accept the same one policy, and nothing else changes: no
40
+ * tenant is asked for or set, and autocommit scoped reads stay.
41
+ */
42
+ readonly rowSecurity?: {
43
+ readonly role: string;
44
+ readonly force?: boolean;
45
+ readonly bypass?: boolean;
46
+ };
47
+ }
28
48
  export declare class PostgresAdapter implements Adapter {
29
49
  private label;
30
50
  /** Restrict to these schemas. Empty means every non-system schema. */
@@ -38,13 +58,14 @@ export declare class PostgresAdapter implements Adapter {
38
58
  /** The epoch each open write transaction read, by the handle it runs on. */
39
59
  private readonly txEpochs;
40
60
  private epochStore;
61
+ private readonly rowSecurity;
41
62
  /** `work`, forgetting the kept catalog if it dies on a table or column that is gone: what was kept is wrong. */
42
63
  private watched;
43
64
  constructor(connectionString: string, label?: string,
44
65
  /** Restrict to these schemas. Empty means every non-system schema. */
45
66
  schemas?: string[], connections?: PgConnectionManager,
46
67
  /** The reader count the connection's config names; the process defaults fill the rest. */
47
- pool?: PgConnectionOptions);
68
+ pool?: PgConnectionOptions, options?: PostgresAdapterOptions);
48
69
  private verifiedSource;
49
70
  /** The pools' meters, for the operator surface. */
50
71
  poolStats(): readonly PoolRoleStats[];
@@ -312,7 +333,12 @@ export declare class PostgresAdapter implements Adapter {
312
333
  * rollback that was not acknowledged, is unknown, and the client is
313
334
  * discarded rather than reused. Everything else did not commit.
314
335
  */
315
- scopeTransaction<T>(input: RowScope, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>, triggers?: TriggerAcceptance): Promise<T>;
336
+ scopeTransaction<T>(input: RowScope, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>, triggers?: TriggerAcceptance,
337
+ /** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity), where it must be
338
+ * given (`null`: deliberately none); ignored without it. */
339
+ options?: {
340
+ readonly tenant?: string | null;
341
+ }): Promise<T>;
316
342
  /**
317
343
  * Private source-owner boundary, deliberately absent from Adapter: the
318
344
  * PostgreSQL counterpart of `SqliteAdapter.scopeVerifiedTransaction`. The
@@ -327,7 +353,11 @@ export declare class PostgresAdapter implements Adapter {
327
353
  * because its fence is a snapshot check; here the fence is row locks held
328
354
  * to the end of the transaction, so the two checks bound its lifetime.
329
355
  */
330
- scopeVerifiedTransaction<T>(input: RowScope, verify: PostgresTransactionVerifier, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>): Promise<T>;
356
+ scopeVerifiedTransaction<T>(input: RowScope, verify: PostgresTransactionVerifier, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>,
357
+ /** As scopeTransaction's. */
358
+ options?: {
359
+ readonly tenant?: string | null;
360
+ }): Promise<T>;
331
361
  /**
332
362
  * Private source-owner boundary, deliberately absent from Adapter: one
333
363
  * `REPEATABLE READ, READ ONLY` transaction on a leased reader, for trusted
@@ -340,7 +370,11 @@ export declare class PostgresAdapter implements Adapter {
340
370
  * fails surfaces as TransactionOutcomeUnknown; any failure discards the
341
371
  * client rather than returning it to the pool.
342
372
  */
343
- readSnapshot<T>(run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout?: boolean, prologue?: string, ahead?: boolean, whole?: boolean): Promise<T>;
373
+ readSnapshot<T>(run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout?: boolean, prologue?: string, ahead?: boolean, whole?: boolean,
374
+ /** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity), where it must be given
375
+ * (`null`: deliberately none); ignored without it. */
376
+ tenant?: string | null): Promise<T>;
377
+ private tenantSet;
344
378
  /** Private source-shape owner, not an authorization proof or generic Adapter
345
379
  * capability. Only this actual adapter's native snapshot runner is used. */
346
380
  capturePinnedReadSnapshot(dependencies: readonly PostgresReadDependency[], assertCurrent: () => void): Promise<PinnedPostgresReadOwner>;
@@ -29,7 +29,7 @@ import { compileBreakdown, compileBreakdownCount } from '../shared/breakdown.js'
29
29
  import { PgConnectionManager, sharedPgConnections } from './postgresPool.js';
30
30
  import { aheadReport, beforeCommit, behindWrite, generationOf, heldAhead, redoWithoutAhead, sendsAhead, waitsAhead, RolledBackAtCommit, transactionHandle, attestedOn, keepAttestedOn, forgetAttestations, noteCatalogVersion, readsCatalogVersion, suspectsStores, } from './postgresTransactionHandle.js';
31
31
  import { snapshotRead, withoutSnapshotRead } from './snapshotRead.js';
32
- import { SCOPED_SESSION, beginOf, snapshotHandles, verifierPin } from './postgresTransactionOpening.js';
32
+ import { SCOPED_SESSION, beginOf, snapshotHandles, tenantSession, verifierPin, } from './postgresTransactionOpening.js';
33
33
  import { withoutWriteAhead, writeAhead } from './writeAhead.js';
34
34
  import { KeyRows } from './scoped/keyRows.js';
35
35
  import { PLAIN_SCOPE, catalogId, heldLocks, heldRows, lockKey, plainStatement, plainTable, reportWriteAhead, rowLockKey, rowLockStatement, scopedStatement, sendPlainAhead, sendWriteAhead, } from './postgresWriteAhead.js';
@@ -81,8 +81,8 @@ export function postgresDescriptionCounts() {
81
81
  * An adapter on the manager every adapter of `url` with this `shape` shares (sharedPgConnections): its own catalog,
82
82
  * lanes and stores, the pools of its neighbors. Closing it lets its share go; the pools close with the last one.
83
83
  */
84
- export function sharedPostgresAdapter(url, label, shape = {}) {
85
- return new PostgresAdapter(url, label, [], sharedPgConnections(url, shape, keepDatesAsText));
84
+ export function sharedPostgresAdapter(url, label, shape = {}, options = {}) {
85
+ return new PostgresAdapter(url, label, [], sharedPgConnections(url, shape, keepDatesAsText), undefined, options);
86
86
  }
87
87
  /**
88
88
  * Whether a statement sent ahead behind a write's BEGIN (writeAhead.ts) failed, so the transaction must begin again
@@ -120,6 +120,8 @@ export class PostgresAdapter {
120
120
  /* Whether the database holds the epoch store: learned from the first
121
121
  write transaction; absent, every transaction reads the digest as before. */
122
122
  epochStore;
123
+ /* The tenant backstop this adapter runs under (PostgresAdapterOptions.rowSecurity), copied at construction. */
124
+ rowSecurity;
123
125
  /** `work`, forgetting the kept catalog if it dies on a table or column that is gone: what was kept is wrong. */
124
126
  watched(work) {
125
127
  return work.catch((error) => {
@@ -134,9 +136,17 @@ export class PostgresAdapter {
134
136
  /** Restrict to these schemas. Empty means every non-system schema. */
135
137
  schemas = [], connections,
136
138
  /** The reader count the connection's config names; the process defaults fill the rest. */
137
- pool) {
139
+ pool, options = {}) {
138
140
  this.label = label;
139
141
  this.schemas = schemas;
142
+ const security = options.rowSecurity;
143
+ if (security !== undefined &&
144
+ (typeof security.role !== 'string' ||
145
+ !security.role ||
146
+ (security.force !== undefined && typeof security.force !== 'boolean') ||
147
+ (security.bypass !== undefined && typeof security.bypass !== 'boolean')))
148
+ throw new TypeError('A row-security role is a role name.');
149
+ this.rowSecurity = security && Object.freeze({ role: security.role, force: security.force === true, bypass: security.bypass === true });
140
150
  this.connections = connections ?? new PgConnectionManager(connectionString, keepDatesAsText, undefined, pool);
141
151
  this.describes = `${connectionString}\0${schemas.join('\0')}`;
142
152
  this.database = connectionString;
@@ -151,7 +161,8 @@ export class PostgresAdapter {
151
161
  attestedStore: (client, store, read) => this.attestedStore(client, store, read),
152
162
  verifiedSource: () => this.verifiedSource(),
153
163
  journalTransaction: (journal, run, options) => this.journalTransaction(journal, run, options),
154
- readSnapshot: (run) => this.readSnapshot(run, true),
164
+ // A store's tables carry no tenant policy: its snapshot is deliberately no tenant's.
165
+ readSnapshot: (run) => this.readSnapshot(run, true, undefined, false, false, null),
155
166
  hasReplicas: () => this.connections.hasReplicas(),
156
167
  onHealthyReplicas: (work) => this.connections.onHealthyReplicas(work),
157
168
  });
@@ -266,13 +277,13 @@ export class PostgresAdapter {
266
277
  .withWriteClient(async (write) => {
267
278
  await write.query('BEGIN');
268
279
  try {
269
- return await effectCatalogFacts(write, tables);
280
+ return await effectCatalogFacts(write, tables, this.rowSecurity);
270
281
  }
271
282
  finally {
272
283
  await write.query('ROLLBACK');
273
284
  }
274
285
  })
275
- .catch(() => primaryReads(async () => effectCatalogFacts(await this.conn(), tables)));
286
+ .catch(() => primaryReads(async () => effectCatalogFacts(await this.conn(), tables, this.rowSecurity)));
276
287
  }
277
288
  /** The catalog as one handle sees it, read by postgresCatalog.ts: the
278
289
  * reader on connect, or the leased writer inside a scoped transaction,
@@ -485,6 +496,10 @@ export class PostgresAdapter {
485
496
  return this.queryOn(request, await this.conn(), true);
486
497
  }
487
498
  async scopeReads(input) {
499
+ /* Each read here is its own autocommit statement, with no transaction for a tenant to be set in: under the
500
+ backstop it would see nothing, and an empty answer would read as an empty tenant. Loud instead. */
501
+ if (this.rowSecurity && !this.rowSecurity.bypass)
502
+ throw new Refusal('Autocommit scoped reads are unavailable under row security; read in a snapshot.');
488
503
  // Capture before metadata I/O: callers cannot change an in-flight policy.
489
504
  const scope = captureRowScope(input);
490
505
  const schema = await this.schema();
@@ -1120,7 +1135,7 @@ export class PostgresAdapter {
1120
1135
  const verify = options.ordinaryVerify;
1121
1136
  return this.ordinaryJournalTransaction(journal, run, verify && (async () => void (await verify())));
1122
1137
  }
1123
- return this.scopedTransact(options.scope, journal, run, options.verify, options.bound, options.triggers);
1138
+ return this.scopedTransact(options.scope, journal, run, options.verify, options.bound, options.triggers, options.tenant);
1124
1139
  }
1125
1140
  async ordinaryJournalTransaction(journal, run, verify) {
1126
1141
  /* The command host supplies target and receipt lanes through inWriteLanes.
@@ -1229,9 +1244,12 @@ export class PostgresAdapter {
1229
1244
  * rollback that was not acknowledged, is unknown, and the client is
1230
1245
  * discarded rather than reused. Everything else did not commit.
1231
1246
  */
1232
- async scopeTransaction(input, run, triggers) {
1247
+ async scopeTransaction(input, run, triggers,
1248
+ /** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity), where it must be
1249
+ * given (`null`: deliberately none); ignored without it. */
1250
+ options = {}) {
1233
1251
  const scope = captureRowScope(input);
1234
- return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers);
1252
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers, options.tenant, 'scopeTransaction');
1235
1253
  }
1236
1254
  /**
1237
1255
  * Private source-owner boundary, deliberately absent from Adapter: the
@@ -1247,11 +1265,13 @@ export class PostgresAdapter {
1247
1265
  * because its fence is a snapshot check; here the fence is row locks held
1248
1266
  * to the end of the transaction, so the two checks bound its lifetime.
1249
1267
  */
1250
- async scopeVerifiedTransaction(input, verify, run) {
1268
+ async scopeVerifiedTransaction(input, verify, run,
1269
+ /** As scopeTransaction's. */
1270
+ options = {}) {
1251
1271
  const scope = captureRowScope(input);
1252
1272
  if (typeof verify !== 'function' || typeof run !== 'function' || Object.keys(scope).some(isRuntimeRelation))
1253
1273
  throw new Refusal('This verified transaction is unavailable.');
1254
- return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify);
1274
+ return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify, undefined, undefined, options.tenant, 'scopeVerifiedTransaction');
1255
1275
  }
1256
1276
  /**
1257
1277
  * Private source-owner boundary, deliberately absent from Adapter: one
@@ -1268,8 +1288,23 @@ export class PostgresAdapter {
1268
1288
  async readSnapshot(run, observeCheckout = false, prologue, ahead = false,
1269
1289
  /* The prologue is the snapshot's whole question (a membership fence): BEGIN, the prologue and COMMIT in one
1270
1290
  round trip where they were two. `run` is handed its answers and nothing it can ask. */
1271
- whole = false) {
1272
- return readSnapshotOn(this.connections, (db, checkout) => (checkout ? PostgresAdapter.prototype.describe.call(this, db) : this.describeSnapshot(db)), run, observeCheckout, prologue, ahead, whole);
1291
+ whole = false,
1292
+ /** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity), where it must be given
1293
+ * (`null`: deliberately none); ignored without it. */
1294
+ tenant) {
1295
+ return readSnapshotOn(this.connections, (db, checkout) => (checkout ? PostgresAdapter.prototype.describe.call(this, db) : this.describeSnapshot(db)), run, observeCheckout, prologue, ahead, whole, this.tenantSet(tenant, 'readSnapshot'));
1296
+ }
1297
+ /* The tenant's SET in a BEGIN's message (tenantSession), under the backstop alone: without it a tenant passed
1298
+ changes nothing sent, and the owner's adapter (`bypass`) is not bound by the policy. Under it, `null` sets none,
1299
+ and the policy then admits no row; no tenant at all is a caller that forgot it, refused before anything is sent
1300
+ rather than answered with an empty tenant. */
1301
+ tenantSet(tenant, method) {
1302
+ const security = this.rowSecurity;
1303
+ if (!security || security.bypass)
1304
+ return '';
1305
+ if (tenant === undefined)
1306
+ throw new Error(`${method} was asked without a tenant under the row-security backstop; pass the tenant, or null where none is meant.`);
1307
+ return tenant === null ? '' : tenantSession(tenant);
1273
1308
  }
1274
1309
  /** Private source-shape owner, not an authorization proof or generic Adapter
1275
1310
  * capability. Only this actual adapter's native snapshot runner is used. */
@@ -1289,7 +1324,8 @@ export class PostgresAdapter {
1289
1324
  nativeCurrent();
1290
1325
  return createPinnedPostgresReadOwner((run) => {
1291
1326
  nativeCurrent();
1292
- return (PostgresAdapter.prototype.readSnapshot).call(this, run, true);
1327
+ // Its pinned catalog refuses a table under row security: no tenant's rows are read here.
1328
+ return (PostgresAdapter.prototype.readSnapshot).call(this, run, true, undefined, false, false, null);
1293
1329
  }, dependencies, () => {
1294
1330
  nativeCurrent();
1295
1331
  assertCurrent();
@@ -1299,7 +1335,9 @@ export class PostgresAdapter {
1299
1335
  /* Scoped records and, for a command, the durable journal and fresh catalog
1300
1336
  evidence in one transaction. The journal is attested before the catalog
1301
1337
  is read, so an unmigrated layout refuses before any lock is taken. */
1302
- async scopedTransact(scope, journal, run, verify, bound, triggers) {
1338
+ async scopedTransact(scope, journal, run, verify, bound, triggers, tenant, method = 'journalTransaction') {
1339
+ // Said before the transaction is queued: a tenant that cannot be set refuses with nothing begun.
1340
+ const session = SCOPED_SESSION + this.tenantSet(tenant, method);
1303
1341
  /* The proof is loaded where a transaction accepts triggers, not at startup; and awaited in the transaction's turn,
1304
1342
  not before it is queued: a write asked after this one would otherwise take its turn while the module loads. */
1305
1343
  const loading = triggers && !journal?.fixedRecords ? import('./scoped/triggerProof.js') : undefined;
@@ -1338,7 +1376,7 @@ export class PostgresAdapter {
1338
1376
  // The rows whose locks were sent ahead, held from the moment their answers came back (sendWriteAhead), with what each lock said.
1339
1377
  const lockedAhead = new Map();
1340
1378
  let aheads = [];
1341
- const opening = { lock: pinned, pin, digest: true, session: SCOPED_SESSION };
1379
+ const opening = { lock: pinned, pin, digest: true, session };
1342
1380
  let opened = await this.openWrite(write, {
1343
1381
  ...opening,
1344
1382
  sent: () => void (aheads = sendWriteAhead(this, write, scope, peeked, keyRows, journal, verify, hint, lockedAhead)),
@@ -1359,7 +1397,7 @@ export class PostgresAdapter {
1359
1397
  if (journal)
1360
1398
  await this.attestJournal(write, journal);
1361
1399
  const catalog = this.catalogCache.get(opened.epoch, scopeKey) ??
1362
- this.catalogCache.set(opened.epoch, scopeKey, await readPostgresScopeCatalog(write, scope, (db) => this.describeScoped(db)));
1400
+ this.catalogCache.set(opened.epoch, scopeKey, await readPostgresScopeCatalog(write, scope, (db) => this.describeScoped(db), this.rowSecurity));
1363
1401
  // Rows read under another epoch's catalog answer nothing: the statements sent ahead were built from it.
1364
1402
  if (catalog !== peeked) {
1365
1403
  keyRows.forget();
@@ -15,6 +15,15 @@ export declare function withPostgresMaintenanceTransaction<T>(url: string, run:
15
15
  * Returns whether this call created it.
16
16
  */
17
17
  export declare function ensurePostgresRuntimeSchema(client: PgQuery): Promise<boolean>;
18
+ /**
19
+ * Under the tenant row-security backstop, the App connects as `runtime` and its stores belong to `owner`, which
20
+ * migrated them. Declared once the startup attestation has proved the pair (two roles, the runtime neither
21
+ * superuser, BYPASSRLS nor a member of the owner): from then on a store attestation on either role's connection
22
+ * takes the owner's view of ownership and allows the runtime its DML (postgresRuntimeSchemaProblems). A runtime paired with a second, different owner is refused: a store has one owner.
23
+ */
24
+ export declare function declareBackstopRoles(runtime: string, owner: string): void;
25
+ /** Forget every declared pair: a process's tenant pools closing (tenantConnections.forgetTenantPools). */
26
+ export declare function forgetBackstopRoles(): void;
18
27
  /**
19
28
  * What makes a store's part of the runtime schema not this role's alone, as
20
29
  * sentences; empty when it is. The schema: owned by this role (or, for a
@@ -27,7 +36,14 @@ export declare function ensurePostgresRuntimeSchema(client: PgQuery): Promise<bo
27
36
  * the ones named under `prefix`: owned by this role, with no privilege held on
28
37
  * them or their columns by any other. A grant on `public`, a reporting role's
29
38
  * `SELECT ON ALL TABLES IN SCHEMA public`, reaches none of this.
39
+ *
40
+ * `runtime`, under the tenant row-security backstop: the role the App runs
41
+ * as, which is not this one and needs the store too. It alone may hold USAGE
42
+ * on the schema and SELECT, INSERT, UPDATE, DELETE or a sequence's USAGE on
43
+ * the store's relations and columns, never with GRANT OPTION — never CREATE,
44
+ * never ownership, and PUBLIC and every other role are refused as before.
30
45
  */
31
46
  export declare function postgresRuntimeSchemaProblems(client: PgQuery, prefix: string, options?: {
32
47
  delegated?: boolean;
48
+ runtime?: string;
33
49
  }): Promise<string[]>;
@@ -92,11 +92,39 @@ export async function ensurePostgresRuntimeSchema(client) {
92
92
  await client.query(`REVOKE ALL ON SCHEMA ${RUNTIME_SCHEMA} FROM PUBLIC`);
93
93
  return true;
94
94
  }
95
+ /* The tenant backstop's role pairs, runtime to owner (declareBackstopRoles), once a tenant App's startup has
96
+ attested them: none without the backstop, and then every statement below is the one it was. */
97
+ const backstopRoles = new Map();
98
+ /**
99
+ * Under the tenant row-security backstop, the App connects as `runtime` and its stores belong to `owner`, which
100
+ * migrated them. Declared once the startup attestation has proved the pair (two roles, the runtime neither
101
+ * superuser, BYPASSRLS nor a member of the owner): from then on a store attestation on either role's connection
102
+ * takes the owner's view of ownership and allows the runtime its DML (postgresRuntimeSchemaProblems). A runtime paired with a second, different owner is refused: a store has one owner.
103
+ */
104
+ export function declareBackstopRoles(runtime, owner) {
105
+ if (typeof runtime !== 'string' || !runtime || typeof owner !== 'string' || !owner || runtime === owner)
106
+ throw new TypeError('A backstop pairs two role names.');
107
+ const held = backstopRoles.get(runtime);
108
+ if (held !== undefined && held !== owner)
109
+ throw new Refusal(`The role "${runtime}" already runs as the runtime of another owner.`);
110
+ backstopRoles.set(runtime, owner);
111
+ }
112
+ /** Forget every declared pair: a process's tenant pools closing (tenantConnections.forgetTenantPools). */
113
+ export function forgetBackstopRoles() {
114
+ backstopRoles.clear();
115
+ }
116
+ /* The pair the connecting role belongs to, as SQL over two text-array parameters at `at`: a CTE `bk(rt, owner)`
117
+ holding it, or nothing. */
118
+ const backstopPair = (at) => `bk AS (SELECT p.rt, p.owner FROM pg_catalog.unnest($${at}::text[], $${at + 1}::text[]) AS p(rt, owner)
119
+ WHERE CURRENT_USER IN (p.rt, p.owner) LIMIT 1)`;
120
+ const backstopValues = () => [[...backstopRoles.keys()], [...backstopRoles.values()]];
95
121
  /* A role the store may belong to: the connecting role itself, or a role
96
122
  whose privileges it inherits, so a deployment can migrate as one member
97
123
  of an owning group and run as another. A superuser is an implicit member
98
124
  of every role, which would make every owner pass, so for a superuser
99
125
  only itself counts. PUBLIC (grantee 0) is never ours. */
126
+ /* What the runtime role may hold on a store's relation or column: reading and writing its rows, and a sequence's nextval. */
127
+ const DML = `'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'USAGE'`;
100
128
  const ours = (role) => `COALESCE(${role} = me.oid OR (NOT me.rolsuper AND ${role} <> 0 AND pg_catalog.pg_has_role(me.oid, ${role}, 'USAGE')), false)`;
101
129
  /**
102
130
  * What makes a store's part of the runtime schema not this role's alone, as
@@ -110,9 +138,28 @@ const ours = (role) => `COALESCE(${role} = me.oid OR (NOT me.rolsuper AND ${role
110
138
  * the ones named under `prefix`: owned by this role, with no privilege held on
111
139
  * them or their columns by any other. A grant on `public`, a reporting role's
112
140
  * `SELECT ON ALL TABLES IN SCHEMA public`, reaches none of this.
141
+ *
142
+ * `runtime`, under the tenant row-security backstop: the role the App runs
143
+ * as, which is not this one and needs the store too. It alone may hold USAGE
144
+ * on the schema and SELECT, INSERT, UPDATE, DELETE or a sequence's USAGE on
145
+ * the store's relations and columns, never with GRANT OPTION — never CREATE,
146
+ * never ownership, and PUBLIC and every other role are refused as before.
113
147
  */
114
148
  export async function postgresRuntimeSchemaProblems(client, prefix, options = {}) {
115
- const row = (await client.query(`WITH me AS (SELECT r.oid, r.rolsuper FROM pg_catalog.pg_roles r WHERE r.rolname = CURRENT_USER),
149
+ if (options.runtime !== undefined && (typeof options.runtime !== 'string' || !options.runtime))
150
+ throw new TypeError('A runtime role is a role name.');
151
+ /* `rt.oid` is null without a runtime role, so nothing, PUBLIC included, is the runtime's and every grant counts as before. */
152
+ const runtime = (grantee, privilege, kinds) => `COALESCE(${grantee} = rt.oid AND ${privilege} IN (${kinds}), false)`;
153
+ /* Under a declared backstop pair (declareBackstopRoles) the checks take the owner's view, on either role's
154
+ connection, and the runtime is the pair's unless the caller named one. */
155
+ const paired = backstopRoles.size > 0;
156
+ const roles = paired
157
+ ? `${backstopPair(7)},
158
+ me AS (SELECT r.oid, r.rolsuper FROM pg_catalog.pg_roles r WHERE r.rolname = COALESCE((SELECT owner FROM bk), CURRENT_USER)),
159
+ rt AS (SELECT (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname = COALESCE($6::text, (SELECT bk.rt FROM bk))) AS oid),`
160
+ : `me AS (SELECT r.oid, r.rolsuper FROM pg_catalog.pg_roles r WHERE r.rolname = CURRENT_USER),
161
+ rt AS (SELECT (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname = $6::text) AS oid),`;
162
+ const row = (await client.query(`WITH ${roles}
116
163
  ns AS (SELECT n.oid, n.nspowner, n.nspacl FROM pg_catalog.pg_namespace n WHERE n.nspname = $1),
117
164
  acl AS (SELECT a.grantee, a.privilege_type FROM ns, pg_catalog.aclexplode(COALESCE(ns.nspacl, pg_catalog.acldefault('n', ns.nspowner))) a),
118
165
  control AS (SELECT DISTINCT c.relowner AS role FROM ns, pg_catalog.pg_class c
@@ -124,12 +171,15 @@ export async function postgresRuntimeSchemaProblems(client, prefix, options = {}
124
171
  COALESCE((SELECT pg_catalog.has_schema_privilege(ns.oid, 'CREATE') AND pg_catalog.has_schema_privilege(ns.oid, 'USAGE') FROM ns), false) AS granted,
125
172
  EXISTS (SELECT 1 FROM acl, ns, me WHERE acl.privilege_type = 'CREATE' AND acl.grantee <> ns.nspowner AND NOT ${ours('acl.grantee')}
126
173
  AND acl.grantee NOT IN (SELECT role FROM control)) AS "foreignCreate",
127
- EXISTS (SELECT 1 FROM acl, ns, me WHERE acl.grantee <> ns.nspowner AND NOT ${ours('acl.grantee')}
128
- AND acl.grantee NOT IN (SELECT role FROM control)) AS "foreignUsage",
174
+ EXISTS (SELECT 1 FROM acl, ns, me, rt WHERE acl.grantee <> ns.nspowner AND NOT ${ours('acl.grantee')}
175
+ AND acl.grantee NOT IN (SELECT role FROM control)
176
+ AND NOT ${runtime('acl.grantee', 'acl.privilege_type', "'USAGE'")}) AS "foreignUsage",
129
177
  EXISTS (SELECT 1 FROM rel, me WHERE NOT ${ours('rel.relowner')}) AS "foreignOwner",
130
- EXISTS (SELECT 1 FROM rel, me, pg_catalog.aclexplode(rel.relacl) a WHERE NOT ${ours('a.grantee')})
131
- OR EXISTS (SELECT 1 FROM rel, me, pg_catalog.pg_attribute t, pg_catalog.aclexplode(t.attacl) a
132
- WHERE t.attrelid = rel.oid AND NOT ${ours('a.grantee')}) AS "foreignGrant",
178
+ EXISTS (SELECT 1 FROM rel, me, rt, pg_catalog.aclexplode(rel.relacl) a WHERE NOT ${ours('a.grantee')}
179
+ AND NOT (${runtime('a.grantee', 'a.privilege_type', DML)} AND NOT a.is_grantable))
180
+ OR EXISTS (SELECT 1 FROM rel, me, rt, pg_catalog.pg_attribute t, pg_catalog.aclexplode(t.attacl) a
181
+ WHERE t.attrelid = rel.oid AND NOT ${ours('a.grantee')}
182
+ AND NOT (${runtime('a.grantee', 'a.privilege_type', DML)} AND NOT a.is_grantable)) AS "foreignGrant",
133
183
  COALESCE((SELECT (SELECT count(*) FROM pg_catalog.pg_proc WHERE pronamespace = ns.oid AND proname <> ALL ($5::text[]))
134
184
  + (SELECT count(*) FROM pg_catalog.pg_operator WHERE oprnamespace = ns.oid)
135
185
  + (SELECT count(*) FROM pg_catalog.pg_type t WHERE t.typnamespace = ns.oid AND t.typrelid = 0
@@ -153,6 +203,8 @@ export async function postgresRuntimeSchemaProblems(client, prefix, options = {}
153
203
  prefix.length,
154
204
  RUNTIME_CONTROL_PREFIXES.map((each) => `${each.replaceAll('_', '\\_')}%`),
155
205
  RUNTIME_SCHEMA_FUNCTIONS,
206
+ options.runtime ?? null,
207
+ ...(paired ? backstopValues() : []),
156
208
  ])).rows[0];
157
209
  if (!row)
158
210
  return ['its catalog could not be read'];
@@ -43,4 +43,4 @@ export interface PostgresReadSnapshot {
43
43
  * Run `run` in a snapshot on `connections`' reader. `describe` is the adapter's own introspection on the leased
44
44
  * client; `onCheckout` says it is a pinned owner's, whose introspection is the class's and not an instance's.
45
45
  */
46
- export declare function readSnapshotOn<T>(connections: PgConnectionManager, describe: (db: PgQuery, checkout: boolean) => Promise<DatabaseSchema>, run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout: boolean, prologue: string | undefined, ahead: boolean, whole: boolean): Promise<T>;
46
+ export declare function readSnapshotOn<T>(connections: PgConnectionManager, describe: (db: PgQuery, checkout: boolean) => Promise<DatabaseSchema>, run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout: boolean, prologue: string | undefined, ahead: boolean, whole: boolean, session?: string): Promise<T>;
@@ -12,11 +12,12 @@ const BEGIN_SNAPSHOT = 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY';
12
12
  * Run `run` in a snapshot on `connections`' reader. `describe` is the adapter's own introspection on the leased
13
13
  * client; `onCheckout` says it is a pinned owner's, whose introspection is the class's and not an instance's.
14
14
  */
15
- export async function readSnapshotOn(connections, describe, run, observeCheckout, prologue, ahead, whole) {
15
+ export async function readSnapshotOn(connections, describe, run, observeCheckout, prologue, ahead, whole, session = '') {
16
16
  if (typeof run !== 'function' ||
17
17
  (prologue !== undefined && (typeof prologue !== 'string' || !prologue.trim())) ||
18
18
  (ahead && (observeCheckout || prologue === undefined)) ||
19
- (whole && (observeCheckout || ahead || prologue === undefined))) {
19
+ (whole && (observeCheckout || ahead || prologue === undefined)) ||
20
+ typeof session !== 'string') {
20
21
  throw new Refusal('This read snapshot is unavailable.');
21
22
  }
22
23
  /* The answer is final once `run` returns: a read-only transaction's
@@ -27,6 +28,9 @@ export async function readSnapshotOn(connections, describe, run, observeCheckout
27
28
  observed checkout: its owner hands its response off inside the
28
29
  snapshot (postgresReadCatalog.ts), so a COMMIT it never heard
29
30
  acknowledged is an uncertain outcome it must be told of. */
31
+ /* The tenant a row policy reads (postgresTransactionOpening.ts tenantSession), set in every BEGIN this snapshot
32
+ sends: its one answer is the engine's to drop, so an owner counts its own results as it did without one. */
33
+ const set = session ? 1 : 0;
30
34
  let deliver;
31
35
  const answered = new Promise((resolve) => {
32
36
  deliver = resolve;
@@ -50,9 +54,9 @@ export async function readSnapshotOn(connections, describe, run, observeCheckout
50
54
  BEGIN and each of them were one each. The owner waits on the BEGIN's
51
55
  answer before it trusts anything; a BEGIN that failed fails what was
52
56
  sent behind it, and the owner hears the BEGIN's failure first. */
53
- const begun = client.query(prologue === undefined ? BEGIN_SNAPSHOT : `${BEGIN_SNAPSHOT}; ${prologue}${whole ? '; COMMIT' : ''}`).then((opened) => Object.freeze(prologue === undefined
57
+ const begun = client.query(prologue === undefined ? `${BEGIN_SNAPSHOT}${session}` : `${BEGIN_SNAPSHOT}${session}; ${prologue}${whole ? '; COMMIT' : ''}`).then((opened) => Object.freeze(prologue === undefined
54
58
  ? []
55
- : (Array.isArray(opened) ? opened : [opened]).slice(1, whole ? -1 : undefined)));
59
+ : (Array.isArray(opened) ? opened : [opened]).slice(1 + set, whole ? -1 : undefined)));
56
60
  let results;
57
61
  if (ahead)
58
62
  void begun.catch(() => { });
@@ -74,8 +78,8 @@ export async function readSnapshotOn(connections, describe, run, observeCheckout
74
78
  ended = true;
75
79
  if (ahead)
76
80
  await begun;
77
- const closed = (await client.query(`COMMIT; ${BEGIN_SNAPSHOT}; ${next}; COMMIT`));
78
- return Object.freeze((Array.isArray(closed) ? closed : [closed]).slice(2, -1));
81
+ const closed = (await client.query(`COMMIT; ${BEGIN_SNAPSHOT}${session}; ${next}; COMMIT`));
82
+ return Object.freeze((Array.isArray(closed) ? closed : [closed]).slice(2 + set, -1));
79
83
  };
80
84
  try {
81
85
  out = await run(Object.freeze({
@@ -1,8 +1,3 @@
1
- /**
2
- * How a Postgres scoped transaction opens: the verifier a trusted host hands it, the pin that rides in its BEGIN, the
3
- * isolation a snapshot read begins with, and the session text its BEGIN sets. Pure parts of the adapter's opening, kept
4
- * apart from the connection and the writes that use them (postgres.ts).
5
- */
6
1
  import type { DatabaseSchema } from '../shared/schema.js';
7
2
  import type { PgQuery } from './postgresPool.js';
8
3
  import type { PostgresScopeCatalog } from './scoped/postgresScopeCatalog.js';
@@ -37,3 +32,4 @@ export declare function verifierPin(verify: PostgresTransactionVerifier | undefi
37
32
  export declare const snapshotHandles: WeakSet<PgQuery>;
38
33
  export declare const beginOf: (write: PgQuery) => "BEGIN" | "BEGIN ISOLATION LEVEL REPEATABLE READ";
39
34
  export declare const SCOPED_SESSION = "; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3";
35
+ export declare function tenantSession(id: string): string;
@@ -1,3 +1,9 @@
1
+ /**
2
+ * How a Postgres scoped transaction opens: the verifier a trusted host hands it, the pin that rides in its BEGIN, the
3
+ * isolation a snapshot read begins with, and the session text its BEGIN sets. Pure parts of the adapter's opening, kept
4
+ * apart from the connection and the writes that use them (postgres.ts).
5
+ */
6
+ import { Refusal } from './adapter.js';
1
7
  /** A verifier's pin, when it is only LOCK statements with no parameters (it rides in the simple-protocol message).
2
8
  Anything else is not taken: the transaction then runs as it would without one, and its verifier attests in full. */
3
9
  export function verifierPin(verify) {
@@ -14,3 +20,13 @@ export const beginOf = (write) => (snapshotHandles.has(write) ? 'BEGIN ISOLATION
14
20
  field order, which decides how a person's own 01/02/2026 is read, stays the database's. The float and interval
15
21
  text, which no key is (keyTypes.ts), is pinned as well, so a value a trigger's proof compares reads as stored. */
16
22
  export const SCOPED_SESSION = '; SET LOCAL DateStyle = ISO; SET LOCAL IntervalStyle = postgres; SET LOCAL extra_float_digits = 3';
23
+ /* The tenant a row policy reads (`current_setting('mistri.tenant', true)`), said in the BEGIN's own message as the
24
+ session above is: SET LOCAL ends with the transaction, so a pooled connection never carries one tenant's setting
25
+ into another's. SET takes no parameter, so the value is a literal; it is a tenant id (tenantMembership.ts
26
+ parseTenantSelector) and a quote is doubled all the same. NUL cannot be sent at all, and a backslash would be an
27
+ escape under `standard_conforming_strings = off`, so either refuses rather than being said some other way. */
28
+ export function tenantSession(id) {
29
+ if (typeof id !== 'string' || !id || id.includes('\0') || id.includes('\\'))
30
+ throw new Refusal('This tenant cannot be set on the transaction.');
31
+ return `; SET LOCAL mistri.tenant = '${id.replaceAll("'", "''")}'`;
32
+ }
@@ -13,7 +13,25 @@ export interface PostgresScopeCatalog extends ScopeCatalog {
13
13
  /** Each table in `triggered`, what its triggers' proof was read from (postgresTriggers.ts triggerVersion): read
14
14
  * again before COMMIT by a transaction that relied on it (attestPostgresTriggers). */
15
15
  triggerVersions?: ReadonlyMap<string, string>;
16
+ /** Under row security (PostgresAdapterOptions.rowSecurity): each table carrying mistri's tenant policy, and the
17
+ * column that policy compares. Which column a table's policy must be on, and which tables must carry one, is the
18
+ * App's ownership to say (mistri's tenantPostgresCatalog.ts); the engine says only that the shape is exactly this. */
19
+ tenantPolicies?: ReadonlyMap<string, string>;
16
20
  }
21
+ /** Row security as the adapter runs under it: the role a policy names, and whether FORCE ROW LEVEL SECURITY may be on. */
22
+ type RowSecurityShape = Readonly<{
23
+ role: string;
24
+ force: boolean;
25
+ }>;
26
+ /** The only policy a scoped write accepts under row security, by name. */
27
+ export declare const TENANT_POLICY = "mistri_tenant";
28
+ /**
29
+ * What follows the column in the policy's expression as `pg_get_expr` deparses it (PostgreSQL 16.15): a text column
30
+ * reads `(tenant = NULLIF(current_setting('mistri.tenant'::text, true), ''::text))`, a varchar one
31
+ * `((tenant)::text = NULLIF(…))`. Compared as text so that any other expression — `USING (true)`, another setting, an
32
+ * OR — is not mistri's policy, whatever it would filter.
33
+ */
34
+ export declare const TENANT_POLICY_TAIL = " = NULLIF(current_setting('mistri.tenant'::text, true), ''::text))";
17
35
  /**
18
36
  * Before COMMIT, in a transaction that let a write fire a trigger the catalog proved validation-only: the proof's
19
37
  * sources read again. A table's triggers cannot change under its pin, but the function a trigger runs, and the
@@ -48,8 +66,9 @@ export declare function joinedHierarchy(error: unknown): ScopeRefusal | undefine
48
66
  * (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
49
67
  * hierarchy, and the tables a scoped write cannot target for row security, a rule, or the role's privileges.
50
68
  */
51
- export declare function effectCatalogFacts(client: PgQuery, given: readonly string[]): Promise<TriggerKeyFacts>;
69
+ export declare function effectCatalogFacts(client: PgQuery, given: readonly string[], backstop?: RowSecurityShape): Promise<TriggerKeyFacts>;
52
70
  /** Call only on the leased writer inside its transaction, before any read of
53
71
  * user data. The describe callback is the adapter's own introspection so the
54
72
  * evidence has the same shape as the catalog the permissions were bound to. */
55
- export declare function readPostgresScopeCatalog(client: PgQuery, scope: RowScope, describe: (client: PgQuery) => Promise<DatabaseSchema>): Promise<PostgresScopeCatalog>;
73
+ export declare function readPostgresScopeCatalog(client: PgQuery, scope: RowScope, describe: (client: PgQuery) => Promise<DatabaseSchema>, backstop?: RowSecurityShape): Promise<PostgresScopeCatalog>;
74
+ export {};
@@ -32,6 +32,15 @@ import { recordRefusalCause } from '../../shared/refusal.js';
32
32
  import { baseType, CATALOG_OPERATORS, defaultBtreeClass, postgresTreeTriggerNames, postgresTriggerAnalyzer, postgresTriggersByTable, postgresTriggerStatement, postgresTriggerVersions, readPostgresTableCode, } from './postgresTriggers.js';
33
33
  import { keyTypeRefusal, postgresKeyType } from './keyTypes.js';
34
34
  const { EQ, GT, LT, NE, PLUS } = CATALOG_OPERATORS;
35
+ /** The only policy a scoped write accepts under row security, by name. */
36
+ export const TENANT_POLICY = 'mistri_tenant';
37
+ /**
38
+ * What follows the column in the policy's expression as `pg_get_expr` deparses it (PostgreSQL 16.15): a text column
39
+ * reads `(tenant = NULLIF(current_setting('mistri.tenant'::text, true), ''::text))`, a varchar one
40
+ * `((tenant)::text = NULLIF(…))`. Compared as text so that any other expression — `USING (true)`, another setting, an
41
+ * OR — is not mistri's policy, whatever it would filter.
42
+ */
43
+ export const TENANT_POLICY_TAIL = " = NULLIF(current_setting('mistri.tenant'::text, true), ''::text))";
35
44
  const refuse = () => {
36
45
  throw new Refusal('PostgreSQL scoped transactions require a complete catalog and an ordinary table the writer may update.');
37
46
  };
@@ -47,10 +56,36 @@ const saidType = (type, typmod, base, basemod) => `pg_catalog.format_type(${type
47
56
  /** Everything that decides whether a write to a relation means what the
48
57
  * scope assumes: its kind, row security, and the presence of triggers,
49
58
  * rules and policies — and whether this role may update it at all. */
50
- async function facts(client, targets) {
59
+ async function facts(client, targets, backstop) {
51
60
  const result = new Map();
52
61
  if (!targets.length)
53
62
  return result;
63
+ /* Under row security only, so a deployment without it asks the statement it always did. The policy is matched in
64
+ full here — its name, command, permissiveness, its one role, and both expressions as deparsed against a column of
65
+ the table — and anything else is a policy that is not mistri's (tenantShape). */
66
+ const policy = backstop
67
+ ? {
68
+ columns: `,
69
+ c.relforcerowsecurity AS force,
70
+ (SELECT pg_catalog.count(*) FROM pg_catalog.pg_policy p WHERE p.polrelid ${EQ} c.oid)::pg_catalog.int4 AS policy_count,
71
+ tenant.name AS tenant_column`,
72
+ join: `
73
+ LEFT JOIN LATERAL (SELECT a.attname::pg_catalog.text AS name
74
+ FROM pg_catalog.pg_policy p
75
+ JOIN pg_catalog.pg_attribute a ON a.attrelid ${EQ} c.oid AND a.attnum ${GT} 0 AND NOT a.attisdropped
76
+ CROSS JOIN LATERAL (SELECT CASE a.atttypid
77
+ WHEN 25::pg_catalog.oid THEN '(' ${CONCAT} pg_catalog.quote_ident(a.attname::pg_catalog.text) ${CONCAT} $4::pg_catalog.text
78
+ WHEN 1043::pg_catalog.oid THEN '((' ${CONCAT} pg_catalog.quote_ident(a.attname::pg_catalog.text) ${CONCAT} ')::text' ${CONCAT} $4::pg_catalog.text
79
+ END AS said) AS expected
80
+ WHERE p.polrelid ${EQ} c.oid AND p.polname ${EQ} '${TENANT_POLICY}' AND p.polcmd ${EQ} '*' AND p.polpermissive
81
+ AND pg_catalog.cardinality(p.polroles) ${EQ} 1
82
+ AND p.polroles[1] ${EQ} (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname::pg_catalog.text ${EQ} $3::pg_catalog.text)
83
+ AND pg_catalog.pg_get_expr(p.polqual, p.polrelid) ${EQ} expected.said
84
+ AND pg_catalog.pg_get_expr(p.polwithcheck, p.polrelid) ${EQ} expected.said
85
+ LIMIT 1) AS tenant ON true`,
86
+ values: [backstop.role, TENANT_POLICY_TAIL],
87
+ }
88
+ : { columns: '', join: '', values: [] };
54
89
  const rows = await client.query(
55
90
  /* Every function and operator named in pg_catalog (postgresTriggers.ts CAT): with `cardinality` found through the
56
91
  search_path, `public.cardinality(text[])` answered 0 for every table, which read as no triggers at all. */
@@ -62,7 +97,7 @@ async function facts(client, targets) {
62
97
  c.relkind ${EQ} 'p' OR EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhrelid ${EQ} c.oid OR i.inhparent ${EQ} c.oid)
63
98
  AS hierarchy,
64
99
  c.relkind ${EQ} 'r' AND EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhparent ${EQ} c.oid) AS inherited,
65
- unkeyed.name AS unkeyed_column, unkeyed.said AS unkeyed_type
100
+ unkeyed.name AS unkeyed_column, unkeyed.said AS unkeyed_type${policy.columns}
66
101
  FROM ${WANTED}
67
102
  -- A key column whose type is not on the list (keyTypes.ts), its domains unwrapped: no scoped write targets the table.
68
103
  LEFT JOIN LATERAL (SELECT a.attname::pg_catalog.text AS name, ${saidType('a.atttypid', 'a.atttypmod', 'b.type', 'b.typmod')} AS said
@@ -71,7 +106,7 @@ async function facts(client, targets) {
71
106
  WHERE i.indrelid ${EQ} c.oid AND i.indisprimary AND NOT ${postgresKeyType('b.type')}
72
107
  ORDER BY a.attnum LIMIT 1) AS unkeyed ON true
73
108
  -- Its partitions' and inheritance children's too: a write through it reaches their rows and fires theirs.
74
- CROSS JOIN LATERAL (SELECT ${postgresTreeTriggerNames('c.oid')} AS names) AS fired`, [targets.map((target) => target.schema), targets.map((target) => target.name)]);
109
+ CROSS JOIN LATERAL (SELECT ${postgresTreeTriggerNames('c.oid')} AS names) AS fired${policy.join}`, [targets.map((target) => target.schema), targets.map((target) => target.name), ...policy.values]);
75
110
  for (const row of rows.rows) {
76
111
  if (typeof row.schema !== 'string' ||
77
112
  typeof row.name !== 'string' ||
@@ -81,6 +116,10 @@ async function facts(client, targets) {
81
116
  row.trigger_names.some((name) => typeof name !== 'string') ||
82
117
  (row.unkeyed_column !== null && typeof row.unkeyed_column !== 'string') ||
83
118
  (row.unkeyed_type !== null && typeof row.unkeyed_type !== 'string') ||
119
+ (backstop &&
120
+ (typeof row.force !== 'boolean' ||
121
+ !Number.isInteger(row.policy_count) ||
122
+ (row.tenant_column !== null && typeof row.tenant_column !== 'string'))) ||
84
123
  result.has(key(row)))
85
124
  return refuse();
86
125
  result.set(key(row), row);
@@ -88,9 +127,24 @@ async function facts(client, targets) {
88
127
  return result;
89
128
  }
90
129
  const lockable = (fact) => fact !== undefined && ['r', 'p'].includes(fact.kind) && fact.updatable;
91
- const clean = (fact) => !fact.rls && !fact.triggers && !fact.rules && !fact.policies;
130
+ /**
131
+ * Under row security, the one shape of row security a scoped write accepts: enabled, FORCE off unless the deployment
132
+ * allows it, and exactly one policy, mistri's (facts). Anything else — a second policy, a RESTRICTIVE one, `USING
133
+ * (true)`, another role — refuses as it always did, named as a policy that is not mistri's.
134
+ */
135
+ const tenantShape = (fact, backstop) => backstop !== undefined &&
136
+ fact.rls &&
137
+ fact.policies &&
138
+ (!fact.force || backstop.force) &&
139
+ fact.policy_count === 1 &&
140
+ typeof fact.tenant_column === 'string';
141
+ /** Row security a scoped write does not take as given: none at all is clean, and under row security mistri's own is. */
142
+ const secured = (fact, backstop) => (fact.rls || fact.policies) && !tenantShape(fact, backstop);
143
+ const clean = (fact, backstop) => !secured(fact, backstop) && !fact.triggers && !fact.rules;
92
144
  /** Clean but for its triggers: each write is then judged by the triggers it fires (scopedTransaction.ts target). */
93
- const cleanButTriggers = (fact) => fact.triggers && !fact.rls && !fact.rules && !fact.policies;
145
+ const cleanButTriggers = (fact, backstop) => fact.triggers && !secured(fact, backstop) && !fact.rules;
146
+ /** Row security as a refusal names it: under row security, any that is not mistri's tenant policy. */
147
+ const securityNamed = (backstop) => backstop ? "a row policy that is not mistri's tenant policy" : 'row-level security';
94
148
  /** The rows of the triggers of `tables`, read on the writer. */
95
149
  async function triggerRows(client, tables) {
96
150
  const result = await client.query(postgresTriggerStatement(true), [
@@ -389,51 +443,55 @@ async function foreignKeyComparisons(client, schema) {
389
443
  return comparisons;
390
444
  }
391
445
  /** What blocks a scoped write to a table beyond its triggers, as a refusal names it; undefined where nothing does. */
392
- const blockerOf = (fact) => !['r', 'p'].includes(fact.kind)
446
+ const blockerOf = (fact, backstop) => !['r', 'p'].includes(fact.kind)
393
447
  ? 'a kind a scoped write cannot target'
394
448
  : !fact.updatable
395
449
  ? 'no UPDATE privilege for the role that writes'
396
- : fact.rls || fact.rules || fact.policies
397
- ? [fact.rules ? 'a rule' : '', fact.policies || fact.rls ? 'row-level security' : ''].filter(Boolean).join(' and ')
450
+ : fact.rules || secured(fact, backstop)
451
+ ? [fact.rules ? 'a rule' : '', secured(fact, backstop) ? securityNamed(backstop) : ''].filter(Boolean).join(' and ')
398
452
  : undefined;
399
453
  /**
400
454
  * For `mistri check`: what a write's own catalog reads about `ids` to judge a trigger's effects
401
455
  * (readPostgresScopeCatalog), read on `client` outside a write: the keys, the tables in a partition or inheritance
402
456
  * hierarchy, and the tables a scoped write cannot target for row security, a rule, or the role's privileges.
403
457
  */
404
- export async function effectCatalogFacts(client, given) {
458
+ export async function effectCatalogFacts(client, given, backstop) {
405
459
  const ids = [...new Set(given)];
406
- const read = await facts(client, ids.map(located));
460
+ const read = await facts(client, ids.map(located), backstop);
407
461
  const blocked = new Map();
408
462
  const hierarchy = new Set();
409
463
  for (const id of ids) {
410
464
  const fact = read.get(key(located(id)));
411
465
  if (fact?.hierarchy)
412
466
  hierarchy.add(id);
413
- const blocker = fact && blockerOf(fact);
467
+ const blocker = fact && blockerOf(fact, backstop);
414
468
  if (blocker)
415
469
  blocked.set(id, blocker);
416
470
  }
417
471
  return { ...(await effectKeyFacts(client, ids)), hierarchy, blocked };
418
472
  }
419
473
  /** What makes a table unclean, as a refusal names it. */
420
- const unclean = (fact) => [fact.triggers ? triggerNames(fact.trigger_names) : '', fact.rules ? 'a rule' : '', fact.policies || fact.rls ? 'row-level security' : '']
474
+ const unclean = (fact, backstop) => [
475
+ fact.triggers ? triggerNames(fact.trigger_names) : '',
476
+ fact.rules ? 'a rule' : '',
477
+ secured(fact, backstop) ? securityNamed(backstop) : '',
478
+ ]
421
479
  .filter(Boolean)
422
480
  .join(' and ');
423
481
  /** Call only on the leased writer inside its transaction, before any read of
424
482
  * user data. The describe callback is the adapter's own introspection so the
425
483
  * evidence has the same shape as the catalog the permissions were bound to. */
426
- export async function readPostgresScopeCatalog(client, scope, describe) {
484
+ export async function readPostgresScopeCatalog(client, scope, describe, backstop) {
427
485
  try {
428
486
  const wanted = Object.keys(scope).map(located);
429
- const before = await facts(client, wanted);
487
+ const before = await facts(client, wanted, backstop);
430
488
  const pinned = wanted.filter((target) => lockable(before.get(key(target))));
431
489
  const relations = pinned.map((target) => `${POSTGRES_STYLE.quote(target.schema)}.${POSTGRES_STYLE.quote(target.name)}`);
432
490
  if (pinned.length)
433
491
  await client.query(`LOCK TABLE ${relations.join(', ')} IN ROW EXCLUSIVE MODE`);
434
492
  const described = await describe(client);
435
493
  const schema = captureScopeCatalog({ ...described, label: 'PostgreSQL scoped transaction', readAt: new Date().toISOString() });
436
- const after = facts(client, schema.tables.map((table) => ({ schema: table.schema, name: table.name })));
494
+ const after = facts(client, schema.tables.map((table) => ({ schema: table.schema, name: table.name })), backstop);
437
495
  const held = new Set(pinned.map(key));
438
496
  const writable = new Set();
439
497
  const blockedBy = new Map();
@@ -442,6 +500,7 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
442
500
  const inheritanceParents = new Set();
443
501
  const locks = new Set();
444
502
  const withTriggers = [];
503
+ const tenantPolicies = new Map();
445
504
  for (const table of schema.tables) {
446
505
  const fact = (await after).get(key(table));
447
506
  // A relation the catalog listed a moment ago and cannot describe now
@@ -455,6 +514,8 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
455
514
  hierarchy.add(table.id);
456
515
  if (fact.inherited)
457
516
  inheritanceParents.add(table.id);
517
+ if (tenantShape(fact, backstop))
518
+ tenantPolicies.set(table.id, fact.tenant_column);
458
519
  if (!lockable(fact))
459
520
  continue;
460
521
  locks.add(table.id);
@@ -463,12 +524,12 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
463
524
  // Writable means pinned: a table that became clean after the pin
464
525
  // decision could be dirtied again before COMMIT, so it stays read-only.
465
526
  const ordinary = held.has(table.id) && !table.isView && table.columns.some((column) => column.primaryKey);
466
- if (ordinary && clean(fact))
527
+ if (ordinary && clean(fact, backstop))
467
528
  writable.add(table.id);
468
- else if (ordinary && cleanButTriggers(fact))
529
+ else if (ordinary && cleanButTriggers(fact, backstop))
469
530
  withTriggers.push({ id: table.id, schema: table.schema, name: table.name });
470
- else if (!clean(fact))
471
- blockedBy.set(table.id, unclean(fact));
531
+ else if (!clean(fact, backstop))
532
+ blockedBy.set(table.id, unclean(fact, backstop));
472
533
  }
473
534
  /* Read only where a table has triggers: a database without them asks nothing more than it did. */
474
535
  const read = withTriggers.length ? await readTriggers(client, withTriggers) : undefined;
@@ -507,6 +568,7 @@ export async function readPostgresScopeCatalog(client, scope, describe) {
507
568
  ...(hierarchy.size ? { hierarchy } : {}),
508
569
  ...(inheritanceParents.size ? { inheritanceParents } : {}),
509
570
  ...(triggered.size ? { triggered, triggerVersions } : {}),
571
+ ...(tenantPolicies.size ? { tenantPolicies } : {}),
510
572
  lockable: locks,
511
573
  pinned: relations,
512
574
  };
@@ -75,6 +75,9 @@ export interface JournalTransactionOptions<V> {
75
75
  readonly ordinaryVerify?: () => unknown;
76
76
  /** A scoped transaction's triggers the App accepts, by physical table (scoped/triggerProof.ts). */
77
77
  readonly triggers?: TriggerAcceptance;
78
+ /** A scoped transaction's tenant, for the row policy under PostgreSQL's backstop (PostgresAdapterOptions.rowSecurity),
79
+ * where it must be given (`null`: deliberately none); SQLite has none. */
80
+ readonly tenant?: string | null;
78
81
  }
79
82
  /** The callback: the records, the journal, and a scoped transaction's catalog evidence (absent in an ordinary one). */
80
83
  export type JournalRun<J, T> = (records: WriteTransaction, journal: J, catalog?: DatabaseSchema) => Promise<T>;
@@ -103,6 +103,8 @@ export async function readStartupConfig(opts, registry, given) {
103
103
  ...(c.replicas ? { replicas: c.replicas } : {}),
104
104
  // A direct URL for LISTEN behind a pooler, checked by loadConfig.
105
105
  ...(c.listen ? { listen: c.listen } : {}),
106
+ // The row-level security backstop and its owner's URL, checked by loadConfig.
107
+ ...(c.backstop ? { backstop: c.backstop, ...(c.owner ? { owner: c.owner } : {}) } : {}),
106
108
  // An API's base URL, description and auth, checked by loadConfig.
107
109
  http: c.http,
108
110
  // Where its migrations are (tablewalk migrate), checked by loadConfig.
@@ -88,6 +88,14 @@ export interface ConnectionConfig {
88
88
  * listening session (packages/mistri/src/adapters/events/postgresCommandEventWake.ts).
89
89
  */
90
90
  listen?: string;
91
+ /**
92
+ * `"rls"`: the database's row-level security stands behind the tenant scope (docs/postgresql.md). `url` and
93
+ * `replicas` then name the runtime role, which owns no table and reads under the pinned policy; `owner` names
94
+ * the role that owns the tables. A tenant App only; checked by backstopOf.
95
+ */
96
+ backstop?: 'rls';
97
+ /** The owner role's URL under `backstop`, resolved as `url` is: what crosses tenants by design runs on it. */
98
+ owner?: string;
91
99
  /**
92
100
  * Present for an API read through its description (`"kind": "http"` in the
93
101
  * config file); `url` is then the API's base URL. It holds no secret:
@@ -299,6 +307,10 @@ interface ConfigFile {
299
307
  replicas?: unknown;
300
308
  /** A direct URL for LISTEN behind a pooler, checked by listenOf. */
301
309
  listen?: unknown;
310
+ /** `"rls"` with `owner`, checked by backstopOf. */
311
+ backstop?: unknown;
312
+ /** The owner role's URL under `backstop`, checked by backstopOf. */
313
+ owner?: unknown;
302
314
  /** `"http"` for an API, `"cache"`, `"webhook"`, … for a service (serviceConnections.ts); absent for a database. */
303
315
  kind?: 'http' | ServiceKind;
304
316
  /** A description file relative to this one, or the description itself. */
@@ -319,12 +331,14 @@ interface ConfigFile {
319
331
  export interface LoadedConfig {
320
332
  path: string;
321
333
  /** As written — a SQLite path located against the file (`writtenUrl` keeps the spelling) — plus an HTTP connection's fields checked and its description resolved against the file, and a checked pool. */
322
- connections: Array<Omit<ConfigFile['connections'][number], 'pool' | 'replicas' | 'listen'> & {
334
+ connections: Array<Omit<ConfigFile['connections'][number], 'pool' | 'replicas' | 'listen' | 'backstop' | 'owner'> & {
323
335
  writtenUrl?: string;
324
336
  http?: HttpConnectionConfig;
325
337
  pool?: PoolSize;
326
338
  replicas?: string[];
327
339
  listen?: string;
340
+ backstop?: 'rls';
341
+ owner?: string;
328
342
  }>;
329
343
  /** The services the file names beside its databases, checked; never databases, never listed as connections. */
330
344
  services: ServiceConfig[];
@@ -31,7 +31,7 @@ import { httpConnectionOf, openHttp } from './httpConnection.js';
31
31
  import { checkServices, isServiceKind, isUrlless, keptUnread, parseConfigSections, serviceConnectionOf, serviceEntry, } from './configSections.js';
32
32
  import { CACHE_SECTIONS, openCache } from './cacheService.js';
33
33
  import { MemoryCacheStore, scopedCache } from '../adapters/cache/cacheStore.js';
34
- import { listenOf, poolOf, replicaEngine, replicasOf } from './poolConfig.js';
34
+ import { backstopOf, listenOf, poolOf, replicaEngine, replicasOf } from './poolConfig.js';
35
35
  import { slug } from '../shared/slug.js';
36
36
  import { sqliteTargetFrom } from './configPaths.js';
37
37
  import { product } from './product.js';
@@ -826,7 +826,8 @@ export async function loadConfig(explicit, sections) {
826
826
  const pool = poolOf(c, http !== undefined, path);
827
827
  const replicas = replicasOf(c, http !== undefined, path);
828
828
  const listen = listenOf(c, http !== undefined, path);
829
- const { pool: _written, replicas: _listed, listen: _direct, ...entry } = c;
829
+ const backstop = backstopOf(c, http !== undefined, path);
830
+ const { pool: _written, replicas: _listed, listen: _direct, backstop: _wall, owner: _owner, ...entry } = c;
830
831
  const located = http ? c.url : sqliteTargetFrom(c.url, dirname(resolve(path)));
831
832
  return [
832
833
  {
@@ -836,6 +837,7 @@ export async function loadConfig(explicit, sections) {
836
837
  ...(pool ? { pool } : {}),
837
838
  ...(replicas ? { replicas } : {}),
838
839
  ...(listen ? { listen } : {}),
840
+ ...(backstop ?? {}),
839
841
  },
840
842
  ];
841
843
  });
@@ -30,5 +30,17 @@ export declare function replicasOf(entry: Record<string, unknown>, http: boolean
30
30
  * anything but PostgreSQL rather than ignored: a wake that is not happening is a 30-second wait nobody chose.
31
31
  */
32
32
  export declare function listenOf(entry: Record<string, unknown>, http: boolean, path: string): string | undefined;
33
+ /**
34
+ * A connection's `"backstop": "rls"` and its `"owner"`: the database's row-level security as a second wall behind
35
+ * the tenant scope (docs/postgresql.md). `url` and `replicas` then name the runtime role, which owns nothing and
36
+ * reads under the pinned policy; `owner` names the role that owns the tables and serves what crosses tenants by
37
+ * design. Both or neither: a backstop with no owner has nobody to resolve a public address or run the jobs that
38
+ * read every tenant, and an owner with no backstop is a second pool doing what `url` does. Refused for HTTP and
39
+ * SQLite, which have no roles to separate.
40
+ */
41
+ export declare function backstopOf(entry: Record<string, unknown>, http: boolean, path: string): {
42
+ owner: string;
43
+ backstop: 'rls';
44
+ } | undefined;
33
45
  /** Which engine a URL names, for a replica's agreement with its primary; undefined for anything else. */
34
46
  export declare function replicaEngine(url: string): 'PostgreSQL' | undefined;
@@ -106,6 +106,40 @@ export function listenOf(entry, http, path) {
106
106
  throw new Error(`${where} is not a PostgreSQL connection, so it has nothing to listen on. Remove "listen".`);
107
107
  return listen;
108
108
  }
109
+ /**
110
+ * A connection's `"backstop": "rls"` and its `"owner"`: the database's row-level security as a second wall behind
111
+ * the tenant scope (docs/postgresql.md). `url` and `replicas` then name the runtime role, which owns nothing and
112
+ * reads under the pinned policy; `owner` names the role that owns the tables and serves what crosses tenants by
113
+ * design. Both or neither: a backstop with no owner has nobody to resolve a public address or run the jobs that
114
+ * read every tenant, and an owner with no backstop is a second pool doing what `url` does. Refused for HTTP and
115
+ * SQLite, which have no roles to separate.
116
+ */
117
+ export function backstopOf(entry, http, path) {
118
+ const { owner, backstop } = entry;
119
+ if (owner === undefined && backstop === undefined)
120
+ return undefined;
121
+ const where = `${path}: connection "${String(entry.name)}"`;
122
+ if (http)
123
+ throw new Error(`${where} is an HTTP connection; "backstop" and "owner" separate database roles. Remove them.`);
124
+ if (backstop === undefined) {
125
+ throw new Error(`${where} has "owner" without "backstop". The owner's URL is only used under "backstop": "rls"; add it, or remove "owner".`);
126
+ }
127
+ if (backstop !== 'rls')
128
+ throw new Error(`${where} has "backstop": ${JSON.stringify(backstop)}. The one backstop is "rls".`);
129
+ if (owner === undefined) {
130
+ throw new Error(`${where} has "backstop": "rls" without "owner". Add "owner": the URL of the role that owns the tables, such as "\${OWNER_URL}".`);
131
+ }
132
+ if (typeof owner !== 'string' || !owner.trim()) {
133
+ throw new Error(`${where} has "owner": ${JSON.stringify(owner)}. It must be a PostgreSQL URL, such as "postgres://owner@db:5432/app".`);
134
+ }
135
+ const written = owner.trim();
136
+ if (!written.includes('$') && replicaEngine(written) !== 'PostgreSQL')
137
+ throw new Error(`${where} has an "owner" that is not a PostgreSQL URL; the backstop is PostgreSQL's row-level security.`);
138
+ const url = String(entry.url);
139
+ if (!url.includes('$') && replicaEngine(url) !== 'PostgreSQL')
140
+ throw new Error(`${where} is not a PostgreSQL connection; SQLite has no roles or row-level security. Remove "backstop" and "owner".`);
141
+ return { owner: written, backstop: 'rls' };
142
+ }
109
143
  /** Which engine a URL names, for a replica's agreement with its primary; undefined for anything else. */
110
144
  export function replicaEngine(url) {
111
145
  if (/^postgres(ql)?:\/\//i.test(url))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mistriwork/engine",
3
- "version": "1.0.0-rc.51",
3
+ "version": "1.0.0-rc.53",
4
4
  "description": "The engine both products stand on: the adapters (SQLite, Postgres), the catalog, the query language, keyset pages, the HTTP kit and the shared rules. No React.",
5
5
  "homepage": "https://mistriwork.dev",
6
6
  "bugs": {