@mistriwork/engine 1.0.0-rc.50 → 1.0.0-rc.52
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/dist/adapters/postgres.d.ts +29 -4
- package/dist/adapters/postgres.js +38 -14
- package/dist/adapters/postgresMaintenance.d.ts +7 -0
- package/dist/adapters/postgresMaintenance.js +22 -5
- package/dist/adapters/postgresReadSnapshot.d.ts +1 -1
- package/dist/adapters/postgresReadSnapshot.js +10 -6
- package/dist/adapters/postgresTransactionOpening.d.ts +1 -5
- package/dist/adapters/postgresTransactionOpening.js +16 -0
- package/dist/adapters/scoped/postgresScopeCatalog.d.ts +21 -2
- package/dist/adapters/scoped/postgresScopeCatalog.js +81 -19
- package/dist/adapters/scoped/scopedTransaction.d.ts +50 -0
- package/dist/adapters/scoped/scopedTransaction.js +154 -10
- package/dist/adapters/storeHost.d.ts +2 -0
- package/package.json +1 -1
|
@@ -25,6 +25,19 @@ export declare function postgresDescriptionCounts(): Readonly<{
|
|
|
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
27
|
export declare function sharedPostgresAdapter(url: string, label: string, shape?: SharedPoolShape): 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. Without it, nothing the adapter sends changes.
|
|
35
|
+
*/
|
|
36
|
+
readonly rowSecurity?: {
|
|
37
|
+
readonly role: string;
|
|
38
|
+
readonly force?: boolean;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
28
41
|
export declare class PostgresAdapter implements Adapter {
|
|
29
42
|
private label;
|
|
30
43
|
/** Restrict to these schemas. Empty means every non-system schema. */
|
|
@@ -38,13 +51,14 @@ export declare class PostgresAdapter implements Adapter {
|
|
|
38
51
|
/** The epoch each open write transaction read, by the handle it runs on. */
|
|
39
52
|
private readonly txEpochs;
|
|
40
53
|
private epochStore;
|
|
54
|
+
private readonly rowSecurity;
|
|
41
55
|
/** `work`, forgetting the kept catalog if it dies on a table or column that is gone: what was kept is wrong. */
|
|
42
56
|
private watched;
|
|
43
57
|
constructor(connectionString: string, label?: string,
|
|
44
58
|
/** Restrict to these schemas. Empty means every non-system schema. */
|
|
45
59
|
schemas?: string[], connections?: PgConnectionManager,
|
|
46
60
|
/** The reader count the connection's config names; the process defaults fill the rest. */
|
|
47
|
-
pool?: PgConnectionOptions);
|
|
61
|
+
pool?: PgConnectionOptions, options?: PostgresAdapterOptions);
|
|
48
62
|
private verifiedSource;
|
|
49
63
|
/** The pools' meters, for the operator surface. */
|
|
50
64
|
poolStats(): readonly PoolRoleStats[];
|
|
@@ -312,7 +326,11 @@ export declare class PostgresAdapter implements Adapter {
|
|
|
312
326
|
* rollback that was not acknowledged, is unknown, and the client is
|
|
313
327
|
* discarded rather than reused. Everything else did not commit.
|
|
314
328
|
*/
|
|
315
|
-
scopeTransaction<T>(input: RowScope, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>, triggers?: TriggerAcceptance
|
|
329
|
+
scopeTransaction<T>(input: RowScope, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>, triggers?: TriggerAcceptance,
|
|
330
|
+
/** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
|
|
331
|
+
options?: {
|
|
332
|
+
readonly tenant?: string;
|
|
333
|
+
}): Promise<T>;
|
|
316
334
|
/**
|
|
317
335
|
* Private source-owner boundary, deliberately absent from Adapter: the
|
|
318
336
|
* PostgreSQL counterpart of `SqliteAdapter.scopeVerifiedTransaction`. The
|
|
@@ -327,7 +345,11 @@ export declare class PostgresAdapter implements Adapter {
|
|
|
327
345
|
* because its fence is a snapshot check; here the fence is row locks held
|
|
328
346
|
* to the end of the transaction, so the two checks bound its lifetime.
|
|
329
347
|
*/
|
|
330
|
-
scopeVerifiedTransaction<T>(input: RowScope, verify: PostgresTransactionVerifier, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T
|
|
348
|
+
scopeVerifiedTransaction<T>(input: RowScope, verify: PostgresTransactionVerifier, run: (tx: WriteTransaction, catalog: DatabaseSchema) => Promise<T>,
|
|
349
|
+
/** As scopeTransaction's. */
|
|
350
|
+
options?: {
|
|
351
|
+
readonly tenant?: string;
|
|
352
|
+
}): Promise<T>;
|
|
331
353
|
/**
|
|
332
354
|
* Private source-owner boundary, deliberately absent from Adapter: one
|
|
333
355
|
* `REPEATABLE READ, READ ONLY` transaction on a leased reader, for trusted
|
|
@@ -340,7 +362,10 @@ export declare class PostgresAdapter implements Adapter {
|
|
|
340
362
|
* fails surfaces as TransactionOutcomeUnknown; any failure discards the
|
|
341
363
|
* client rather than returning it to the pool.
|
|
342
364
|
*/
|
|
343
|
-
readSnapshot<T>(run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout?: boolean, prologue?: string, ahead?: boolean, whole?: boolean
|
|
365
|
+
readSnapshot<T>(run: (snapshot: PostgresReadSnapshot) => Promise<T>, observeCheckout?: boolean, prologue?: string, ahead?: boolean, whole?: boolean,
|
|
366
|
+
/** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
|
|
367
|
+
tenant?: string): Promise<T>;
|
|
368
|
+
private tenantSet;
|
|
344
369
|
/** Private source-shape owner, not an authorization proof or generic Adapter
|
|
345
370
|
* capability. Only this actual adapter's native snapshot runner is used. */
|
|
346
371
|
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';
|
|
@@ -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,14 @@ 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' || !security.role || (security.force !== undefined && typeof security.force !== 'boolean')))
|
|
145
|
+
throw new TypeError('A row-security role is a role name.');
|
|
146
|
+
this.rowSecurity = security && Object.freeze({ role: security.role, force: security.force === true });
|
|
140
147
|
this.connections = connections ?? new PgConnectionManager(connectionString, keepDatesAsText, undefined, pool);
|
|
141
148
|
this.describes = `${connectionString}\0${schemas.join('\0')}`;
|
|
142
149
|
this.database = connectionString;
|
|
@@ -266,13 +273,13 @@ export class PostgresAdapter {
|
|
|
266
273
|
.withWriteClient(async (write) => {
|
|
267
274
|
await write.query('BEGIN');
|
|
268
275
|
try {
|
|
269
|
-
return await effectCatalogFacts(write, tables);
|
|
276
|
+
return await effectCatalogFacts(write, tables, this.rowSecurity);
|
|
270
277
|
}
|
|
271
278
|
finally {
|
|
272
279
|
await write.query('ROLLBACK');
|
|
273
280
|
}
|
|
274
281
|
})
|
|
275
|
-
.catch(() => primaryReads(async () => effectCatalogFacts(await this.conn(), tables)));
|
|
282
|
+
.catch(() => primaryReads(async () => effectCatalogFacts(await this.conn(), tables, this.rowSecurity)));
|
|
276
283
|
}
|
|
277
284
|
/** The catalog as one handle sees it, read by postgresCatalog.ts: the
|
|
278
285
|
* reader on connect, or the leased writer inside a scoped transaction,
|
|
@@ -485,6 +492,10 @@ export class PostgresAdapter {
|
|
|
485
492
|
return this.queryOn(request, await this.conn(), true);
|
|
486
493
|
}
|
|
487
494
|
async scopeReads(input) {
|
|
495
|
+
/* Each read here is its own autocommit statement, with no transaction for a tenant to be set in: under the
|
|
496
|
+
backstop it would see nothing, and an empty answer would read as an empty tenant. Loud instead. */
|
|
497
|
+
if (this.rowSecurity)
|
|
498
|
+
throw new Refusal('Autocommit scoped reads are unavailable under row security; read in a snapshot.');
|
|
488
499
|
// Capture before metadata I/O: callers cannot change an in-flight policy.
|
|
489
500
|
const scope = captureRowScope(input);
|
|
490
501
|
const schema = await this.schema();
|
|
@@ -1120,7 +1131,7 @@ export class PostgresAdapter {
|
|
|
1120
1131
|
const verify = options.ordinaryVerify;
|
|
1121
1132
|
return this.ordinaryJournalTransaction(journal, run, verify && (async () => void (await verify())));
|
|
1122
1133
|
}
|
|
1123
|
-
return this.scopedTransact(options.scope, journal, run, options.verify, options.bound, options.triggers);
|
|
1134
|
+
return this.scopedTransact(options.scope, journal, run, options.verify, options.bound, options.triggers, options.tenant);
|
|
1124
1135
|
}
|
|
1125
1136
|
async ordinaryJournalTransaction(journal, run, verify) {
|
|
1126
1137
|
/* The command host supplies target and receipt lanes through inWriteLanes.
|
|
@@ -1229,9 +1240,11 @@ export class PostgresAdapter {
|
|
|
1229
1240
|
* rollback that was not acknowledged, is unknown, and the client is
|
|
1230
1241
|
* discarded rather than reused. Everything else did not commit.
|
|
1231
1242
|
*/
|
|
1232
|
-
async scopeTransaction(input, run, triggers
|
|
1243
|
+
async scopeTransaction(input, run, triggers,
|
|
1244
|
+
/** `tenant`: what the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
|
|
1245
|
+
options = {}) {
|
|
1233
1246
|
const scope = captureRowScope(input);
|
|
1234
|
-
return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers);
|
|
1247
|
+
return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), undefined, undefined, triggers, options.tenant);
|
|
1235
1248
|
}
|
|
1236
1249
|
/**
|
|
1237
1250
|
* Private source-owner boundary, deliberately absent from Adapter: the
|
|
@@ -1247,11 +1260,13 @@ export class PostgresAdapter {
|
|
|
1247
1260
|
* because its fence is a snapshot check; here the fence is row locks held
|
|
1248
1261
|
* to the end of the transaction, so the two checks bound its lifetime.
|
|
1249
1262
|
*/
|
|
1250
|
-
async scopeVerifiedTransaction(input, verify, run
|
|
1263
|
+
async scopeVerifiedTransaction(input, verify, run,
|
|
1264
|
+
/** As scopeTransaction's. */
|
|
1265
|
+
options = {}) {
|
|
1251
1266
|
const scope = captureRowScope(input);
|
|
1252
1267
|
if (typeof verify !== 'function' || typeof run !== 'function' || Object.keys(scope).some(isRuntimeRelation))
|
|
1253
1268
|
throw new Refusal('This verified transaction is unavailable.');
|
|
1254
|
-
return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify);
|
|
1269
|
+
return this.scopedTransact(scope, undefined, (tx, _journal, catalog) => run(tx, catalog), verify, undefined, undefined, options.tenant);
|
|
1255
1270
|
}
|
|
1256
1271
|
/**
|
|
1257
1272
|
* Private source-owner boundary, deliberately absent from Adapter: one
|
|
@@ -1268,8 +1283,15 @@ export class PostgresAdapter {
|
|
|
1268
1283
|
async readSnapshot(run, observeCheckout = false, prologue, ahead = false,
|
|
1269
1284
|
/* The prologue is the snapshot's whole question (a membership fence): BEGIN, the prologue and COMMIT in one
|
|
1270
1285
|
round trip where they were two. `run` is handed its answers and nothing it can ask. */
|
|
1271
|
-
whole = false
|
|
1272
|
-
|
|
1286
|
+
whole = false,
|
|
1287
|
+
/** What the row policy reads, under the backstop (PostgresAdapterOptions.rowSecurity); ignored without it. */
|
|
1288
|
+
tenant) {
|
|
1289
|
+
return readSnapshotOn(this.connections, (db, checkout) => (checkout ? PostgresAdapter.prototype.describe.call(this, db) : this.describeSnapshot(db)), run, observeCheckout, prologue, ahead, whole, this.tenantSet(tenant));
|
|
1290
|
+
}
|
|
1291
|
+
/* The tenant's SET in a BEGIN's message (tenantSession), under the backstop alone: without it a tenant passed
|
|
1292
|
+
changes nothing sent. Under it, a transaction given none sets none, and the policy then admits no row. */
|
|
1293
|
+
tenantSet(tenant) {
|
|
1294
|
+
return this.rowSecurity && tenant !== undefined ? tenantSession(tenant) : '';
|
|
1273
1295
|
}
|
|
1274
1296
|
/** Private source-shape owner, not an authorization proof or generic Adapter
|
|
1275
1297
|
* capability. Only this actual adapter's native snapshot runner is used. */
|
|
@@ -1299,7 +1321,9 @@ export class PostgresAdapter {
|
|
|
1299
1321
|
/* Scoped records and, for a command, the durable journal and fresh catalog
|
|
1300
1322
|
evidence in one transaction. The journal is attested before the catalog
|
|
1301
1323
|
is read, so an unmigrated layout refuses before any lock is taken. */
|
|
1302
|
-
async scopedTransact(scope, journal, run, verify, bound, triggers) {
|
|
1324
|
+
async scopedTransact(scope, journal, run, verify, bound, triggers, tenant) {
|
|
1325
|
+
// Said before the transaction is queued: a tenant that cannot be set refuses with nothing begun.
|
|
1326
|
+
const session = SCOPED_SESSION + this.tenantSet(tenant);
|
|
1303
1327
|
/* The proof is loaded where a transaction accepts triggers, not at startup; and awaited in the transaction's turn,
|
|
1304
1328
|
not before it is queued: a write asked after this one would otherwise take its turn while the module loads. */
|
|
1305
1329
|
const loading = triggers && !journal?.fixedRecords ? import('./scoped/triggerProof.js') : undefined;
|
|
@@ -1338,7 +1362,7 @@ export class PostgresAdapter {
|
|
|
1338
1362
|
// The rows whose locks were sent ahead, held from the moment their answers came back (sendWriteAhead), with what each lock said.
|
|
1339
1363
|
const lockedAhead = new Map();
|
|
1340
1364
|
let aheads = [];
|
|
1341
|
-
const opening = { lock: pinned, pin, digest: true, session
|
|
1365
|
+
const opening = { lock: pinned, pin, digest: true, session };
|
|
1342
1366
|
let opened = await this.openWrite(write, {
|
|
1343
1367
|
...opening,
|
|
1344
1368
|
sent: () => void (aheads = sendWriteAhead(this, write, scope, peeked, keyRows, journal, verify, hint, lockedAhead)),
|
|
@@ -1359,7 +1383,7 @@ export class PostgresAdapter {
|
|
|
1359
1383
|
if (journal)
|
|
1360
1384
|
await this.attestJournal(write, journal);
|
|
1361
1385
|
const catalog = this.catalogCache.get(opened.epoch, scopeKey) ??
|
|
1362
|
-
this.catalogCache.set(opened.epoch, scopeKey, await readPostgresScopeCatalog(write, scope, (db) => this.describeScoped(db)));
|
|
1386
|
+
this.catalogCache.set(opened.epoch, scopeKey, await readPostgresScopeCatalog(write, scope, (db) => this.describeScoped(db), this.rowSecurity));
|
|
1363
1387
|
// Rows read under another epoch's catalog answer nothing: the statements sent ahead were built from it.
|
|
1364
1388
|
if (catalog !== peeked) {
|
|
1365
1389
|
keyRows.forget();
|
|
@@ -27,7 +27,14 @@ export declare function ensurePostgresRuntimeSchema(client: PgQuery): Promise<bo
|
|
|
27
27
|
* the ones named under `prefix`: owned by this role, with no privilege held on
|
|
28
28
|
* them or their columns by any other. A grant on `public`, a reporting role's
|
|
29
29
|
* `SELECT ON ALL TABLES IN SCHEMA public`, reaches none of this.
|
|
30
|
+
*
|
|
31
|
+
* `runtime`, under the tenant row-security backstop: the role the App runs
|
|
32
|
+
* as, which is not this one and needs the store too. It alone may hold USAGE
|
|
33
|
+
* on the schema and SELECT, INSERT, UPDATE, DELETE or a sequence's USAGE on
|
|
34
|
+
* the store's relations and columns, never with GRANT OPTION — never CREATE,
|
|
35
|
+
* never ownership, and PUBLIC and every other role are refused as before.
|
|
30
36
|
*/
|
|
31
37
|
export declare function postgresRuntimeSchemaProblems(client: PgQuery, prefix: string, options?: {
|
|
32
38
|
delegated?: boolean;
|
|
39
|
+
runtime?: string;
|
|
33
40
|
}): Promise<string[]>;
|
|
@@ -97,6 +97,8 @@ export async function ensurePostgresRuntimeSchema(client) {
|
|
|
97
97
|
of an owning group and run as another. A superuser is an implicit member
|
|
98
98
|
of every role, which would make every owner pass, so for a superuser
|
|
99
99
|
only itself counts. PUBLIC (grantee 0) is never ours. */
|
|
100
|
+
/* What the runtime role may hold on a store's relation or column: reading and writing its rows, and a sequence's nextval. */
|
|
101
|
+
const DML = `'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'USAGE'`;
|
|
100
102
|
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
103
|
/**
|
|
102
104
|
* What makes a store's part of the runtime schema not this role's alone, as
|
|
@@ -110,9 +112,20 @@ const ours = (role) => `COALESCE(${role} = me.oid OR (NOT me.rolsuper AND ${role
|
|
|
110
112
|
* the ones named under `prefix`: owned by this role, with no privilege held on
|
|
111
113
|
* them or their columns by any other. A grant on `public`, a reporting role's
|
|
112
114
|
* `SELECT ON ALL TABLES IN SCHEMA public`, reaches none of this.
|
|
115
|
+
*
|
|
116
|
+
* `runtime`, under the tenant row-security backstop: the role the App runs
|
|
117
|
+
* as, which is not this one and needs the store too. It alone may hold USAGE
|
|
118
|
+
* on the schema and SELECT, INSERT, UPDATE, DELETE or a sequence's USAGE on
|
|
119
|
+
* the store's relations and columns, never with GRANT OPTION — never CREATE,
|
|
120
|
+
* never ownership, and PUBLIC and every other role are refused as before.
|
|
113
121
|
*/
|
|
114
122
|
export async function postgresRuntimeSchemaProblems(client, prefix, options = {}) {
|
|
123
|
+
if (options.runtime !== undefined && (typeof options.runtime !== 'string' || !options.runtime))
|
|
124
|
+
throw new TypeError('A runtime role is a role name.');
|
|
125
|
+
/* `rt.oid` is null without a runtime role, so nothing, PUBLIC included, is the runtime's and every grant counts as before. */
|
|
126
|
+
const runtime = (grantee, privilege, kinds) => `COALESCE(${grantee} = rt.oid AND ${privilege} IN (${kinds}), false)`;
|
|
115
127
|
const row = (await client.query(`WITH me AS (SELECT r.oid, r.rolsuper FROM pg_catalog.pg_roles r WHERE r.rolname = CURRENT_USER),
|
|
128
|
+
rt AS (SELECT (SELECT r.oid FROM pg_catalog.pg_roles r WHERE r.rolname = $6::text) AS oid),
|
|
116
129
|
ns AS (SELECT n.oid, n.nspowner, n.nspacl FROM pg_catalog.pg_namespace n WHERE n.nspname = $1),
|
|
117
130
|
acl AS (SELECT a.grantee, a.privilege_type FROM ns, pg_catalog.aclexplode(COALESCE(ns.nspacl, pg_catalog.acldefault('n', ns.nspowner))) a),
|
|
118
131
|
control AS (SELECT DISTINCT c.relowner AS role FROM ns, pg_catalog.pg_class c
|
|
@@ -124,12 +137,15 @@ export async function postgresRuntimeSchemaProblems(client, prefix, options = {}
|
|
|
124
137
|
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
138
|
EXISTS (SELECT 1 FROM acl, ns, me WHERE acl.privilege_type = 'CREATE' AND acl.grantee <> ns.nspowner AND NOT ${ours('acl.grantee')}
|
|
126
139
|
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)
|
|
140
|
+
EXISTS (SELECT 1 FROM acl, ns, me, rt WHERE acl.grantee <> ns.nspowner AND NOT ${ours('acl.grantee')}
|
|
141
|
+
AND acl.grantee NOT IN (SELECT role FROM control)
|
|
142
|
+
AND NOT ${runtime('acl.grantee', 'acl.privilege_type', "'USAGE'")}) AS "foreignUsage",
|
|
129
143
|
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
|
-
|
|
132
|
-
|
|
144
|
+
EXISTS (SELECT 1 FROM rel, me, rt, pg_catalog.aclexplode(rel.relacl) a WHERE NOT ${ours('a.grantee')}
|
|
145
|
+
AND NOT (${runtime('a.grantee', 'a.privilege_type', DML)} AND NOT a.is_grantable))
|
|
146
|
+
OR EXISTS (SELECT 1 FROM rel, me, rt, pg_catalog.pg_attribute t, pg_catalog.aclexplode(t.attacl) a
|
|
147
|
+
WHERE t.attrelid = rel.oid AND NOT ${ours('a.grantee')}
|
|
148
|
+
AND NOT (${runtime('a.grantee', 'a.privilege_type', DML)} AND NOT a.is_grantable)) AS "foreignGrant",
|
|
133
149
|
COALESCE((SELECT (SELECT count(*) FROM pg_catalog.pg_proc WHERE pronamespace = ns.oid AND proname <> ALL ($5::text[]))
|
|
134
150
|
+ (SELECT count(*) FROM pg_catalog.pg_operator WHERE oprnamespace = ns.oid)
|
|
135
151
|
+ (SELECT count(*) FROM pg_catalog.pg_type t WHERE t.typnamespace = ns.oid AND t.typrelid = 0
|
|
@@ -153,6 +169,7 @@ export async function postgresRuntimeSchemaProblems(client, prefix, options = {}
|
|
|
153
169
|
prefix.length,
|
|
154
170
|
RUNTIME_CONTROL_PREFIXES.map((each) => `${each.replaceAll('_', '\\_')}%`),
|
|
155
171
|
RUNTIME_SCHEMA_FUNCTIONS,
|
|
172
|
+
options.runtime ?? null,
|
|
156
173
|
])).rows[0];
|
|
157
174
|
if (!row)
|
|
158
175
|
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
|
|
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
|
-
|
|
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
|
|
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.
|
|
397
|
-
? [fact.rules ? 'a rule' : '', fact
|
|
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) => [
|
|
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
|
};
|
|
@@ -63,6 +63,31 @@ export declare const isForeignKeyViolation: (error: unknown) => boolean;
|
|
|
63
63
|
* refusal; what the operator reads names the constraint and nothing of the row.
|
|
64
64
|
*/
|
|
65
65
|
export declare const foreignKeyRefusal: (error: unknown) => ScopeRefusal;
|
|
66
|
+
/** The columns of `table` whose unique rule refused a write, or undefined where the error names another table, an
|
|
67
|
+
* expression, an exclusion, or nothing it can read. */
|
|
68
|
+
export declare function uniqueColumns(error: unknown, table: Pick<TableMeta, 'name' | 'schema'>): string[] | undefined;
|
|
69
|
+
/**
|
|
70
|
+
* Whether a unique refusal on `columns` names a row the principal reads: some group of its rule fixes every one of
|
|
71
|
+
* those columns' values (`=` and nothing else), and the row written holds exactly those values. Any row the unique rule
|
|
72
|
+
* compared equal to it then holds them too, and is inside the same group, so long as the index compares those columns
|
|
73
|
+
* no more loosely than the scope does. That is what the engine cannot read off the error, so only a comparison that is
|
|
74
|
+
* attested counts:
|
|
75
|
+
* - on SQLite (`sqlite`), a column the scope compares by its bytes (`binary`): a tenant's owner column, which every
|
|
76
|
+
* unique index of a tenant table must compare BINARY (the tenant write source's assertUniqueKeys). Any other
|
|
77
|
+
* condition is compared under the column's collation, where `UNIQUE (email COLLATE NOCASE)` finds 'X' equal to an
|
|
78
|
+
* 'x' the scope tells apart, so the refusal stays generic;
|
|
79
|
+
* - on PostgreSQL, a condition under the column's own collation: an index compares by it unless it names another, and
|
|
80
|
+
* a tenant's owner column must be deterministic in every unique index (tenantPostgresCatalog.ts).
|
|
81
|
+
* A tenant's own table answers so, by the owner column its unique indexes include: the conflicting row is the tenant's
|
|
82
|
+
* own. A rule that reads the whole table answers so whatever the index compares.
|
|
83
|
+
*/
|
|
84
|
+
export declare function uniqueConflictSeen(rule: RowScope[string], columns: readonly string[], row: Readonly<Record<string, unknown>>, sqlite: boolean): boolean;
|
|
85
|
+
/**
|
|
86
|
+
* A unique rule's refusal of a scoped write, where the row it conflicts with may be one the principal cannot read:
|
|
87
|
+
* said as the scope's own refusal, so neither the column nor the fact that the value is taken outside its rows is
|
|
88
|
+
* named. The operator reads the table and the columns, never the value.
|
|
89
|
+
*/
|
|
90
|
+
export declare const uniqueRefusal: (table: Pick<TableMeta, 'id'>, columns: readonly string[] | undefined) => ScopeRefusal;
|
|
66
91
|
/** A table's triggers as a refusal names them: `the trigger "audit_order"`, `the triggers "a", "b"`. */
|
|
67
92
|
export declare const triggerNames: (names: readonly string[]) => string;
|
|
68
93
|
export { blocksEveryWrite, sayBlocked, sayRuns, sayTriggers, type ScopeTrigger } from './scopeTriggers.js';
|
|
@@ -158,6 +183,31 @@ export declare function sameTables(scope: Readonly<Record<string, unknown>>, bou
|
|
|
158
183
|
* words stay value-free, the reason recorded beneath them for the owner. */
|
|
159
184
|
export declare class ScopeRefusal extends Refusal {
|
|
160
185
|
}
|
|
186
|
+
/** The sentence a delete hears when every row still referencing it is one its principal cannot read. */
|
|
187
|
+
export declare const IN_USE = "This record is in use and can't be deleted.";
|
|
188
|
+
/**
|
|
189
|
+
* A delete refused because rows still reference the row, said as the record's state rather than as the scope: the
|
|
190
|
+
* person can act on it. Its words name only what the principal reads — the referencing table and how many of its
|
|
191
|
+
* rows point here, counted under the principal's own rows — and, where every remaining reference is one the scope
|
|
192
|
+
* hides (another tenant's row on a shared parent, a row the policy keeps from them), name nothing: {@link IN_USE}.
|
|
193
|
+
* That the delete is refused at all is the one thing such a row still says, and it cannot be otherwise: deleting it
|
|
194
|
+
* would reach that row. The total across every row is recorded for the operator only.
|
|
195
|
+
*/
|
|
196
|
+
export declare class ReferencedRefusal extends ScopeRefusal {
|
|
197
|
+
/** What the principal reads of the references: the table and its count, or nothing when it reads none. */
|
|
198
|
+
readonly seen?: {
|
|
199
|
+
readonly table: string;
|
|
200
|
+
readonly count: number;
|
|
201
|
+
} | undefined;
|
|
202
|
+
constructor(
|
|
203
|
+
/** What the principal reads of the references: the table and its count, or nothing when it reads none. */
|
|
204
|
+
seen?: {
|
|
205
|
+
readonly table: string;
|
|
206
|
+
readonly count: number;
|
|
207
|
+
} | undefined);
|
|
208
|
+
}
|
|
209
|
+
/** The ReferencedRefusal a failure was rebuilt over, however many value-free wrappers lie between. */
|
|
210
|
+
export declare function referencedBeneath(error: unknown): ReferencedRefusal | undefined;
|
|
161
211
|
/**
|
|
162
212
|
* The principal's scope and the reads it compiles to, for a transaction that
|
|
163
213
|
* may create a parent and then its children. A scope is resolved before the
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Refusal } from '../adapter.js';
|
|
2
2
|
import { buildWhere } from '../../shared/filter.js';
|
|
3
|
-
import { authorFault, recordRefusalCause } from '../../shared/refusal.js';
|
|
3
|
+
import { authorFault, recordRefusalCause, refusalCause, sayRefusal } from '../../shared/refusal.js';
|
|
4
4
|
import { coerceForColumn, columnKind } from '../../shared/schema.js';
|
|
5
5
|
import { blockingTriggers, firedBy, sayRuns, sayTriggers, sayWrite } from './scopeTriggers.js';
|
|
6
6
|
import { detachStoredText, overlaid, storedText, storedTextOf } from './storedText.js';
|
|
@@ -21,6 +21,74 @@ export const foreignKeyRefusal = (error) => {
|
|
|
21
21
|
const constraint = error?.constraint;
|
|
22
22
|
return recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), `The database's foreign key${typeof constraint === 'string' ? ` ${JSON.stringify(constraint)}` : ''} refused the write: a row it points at is not in the principal's rows, or does not exist.`);
|
|
23
23
|
};
|
|
24
|
+
/** Whether a failure is a unique rule refusing a write: SQLite's PRIMARY KEY and UNIQUE, PostgreSQL's 23505 and 23P01. */
|
|
25
|
+
const isUniqueViolation = (error) => {
|
|
26
|
+
const { code, errcode } = (error ?? {});
|
|
27
|
+
return errcode === 1555 || errcode === 2067 || code === '23505' || code === '23P01';
|
|
28
|
+
};
|
|
29
|
+
/* A column as each engine names it in a unique refusal, and nothing else: the names only, never the values
|
|
30
|
+
(engine/src/server/constraints.ts reads the same, for a form's field, where the adapters cannot import it). */
|
|
31
|
+
const COLUMN_NAME = /^[A-Za-z_][\w$]{0,127}$/;
|
|
32
|
+
/** The columns of `table` whose unique rule refused a write, or undefined where the error names another table, an
|
|
33
|
+
* expression, an exclusion, or nothing it can read. */
|
|
34
|
+
export function uniqueColumns(error, table) {
|
|
35
|
+
const e = (error ?? {});
|
|
36
|
+
let names;
|
|
37
|
+
if (e.code === '23505') {
|
|
38
|
+
// A trigger or a cascade can break another table's rule: only the table written is judged.
|
|
39
|
+
if (e.table !== table.name || (typeof e.schema === 'string' && table.schema && e.schema !== table.schema))
|
|
40
|
+
return undefined;
|
|
41
|
+
const head = typeof e.detail === 'string' ? /^Key \(([^()]*)\)=\(/.exec(e.detail) : null;
|
|
42
|
+
names = head?.[1].split(',').map((name) => name.trim());
|
|
43
|
+
}
|
|
44
|
+
else if (typeof e.message === 'string') {
|
|
45
|
+
const said = /^UNIQUE constraint failed: (.+)$/.exec(e.message);
|
|
46
|
+
names = said?.[1].split(',').map((part) => {
|
|
47
|
+
const at = part.trim();
|
|
48
|
+
return at.startsWith(`${table.name}.`) ? at.slice(table.name.length + 1) : '';
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return names?.length && names.every((name) => COLUMN_NAME.test(name)) ? [...new Set(names)] : undefined;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Whether a unique refusal on `columns` names a row the principal reads: some group of its rule fixes every one of
|
|
55
|
+
* those columns' values (`=` and nothing else), and the row written holds exactly those values. Any row the unique rule
|
|
56
|
+
* compared equal to it then holds them too, and is inside the same group, so long as the index compares those columns
|
|
57
|
+
* no more loosely than the scope does. That is what the engine cannot read off the error, so only a comparison that is
|
|
58
|
+
* attested counts:
|
|
59
|
+
* - on SQLite (`sqlite`), a column the scope compares by its bytes (`binary`): a tenant's owner column, which every
|
|
60
|
+
* unique index of a tenant table must compare BINARY (the tenant write source's assertUniqueKeys). Any other
|
|
61
|
+
* condition is compared under the column's collation, where `UNIQUE (email COLLATE NOCASE)` finds 'X' equal to an
|
|
62
|
+
* 'x' the scope tells apart, so the refusal stays generic;
|
|
63
|
+
* - on PostgreSQL, a condition under the column's own collation: an index compares by it unless it names another, and
|
|
64
|
+
* a tenant's owner column must be deterministic in every unique index (tenantPostgresCatalog.ts).
|
|
65
|
+
* A tenant's own table answers so, by the owner column its unique indexes include: the conflicting row is the tenant's
|
|
66
|
+
* own. A rule that reads the whole table answers so whatever the index compares.
|
|
67
|
+
*/
|
|
68
|
+
export function uniqueConflictSeen(rule, columns, row, sqlite) {
|
|
69
|
+
if (rule === true)
|
|
70
|
+
return true;
|
|
71
|
+
if (rule === false)
|
|
72
|
+
return false;
|
|
73
|
+
return rule.groups.some((group) => group.length > 0 &&
|
|
74
|
+
group.every((condition) => !isViaCondition(condition) &&
|
|
75
|
+
condition.op === '=' &&
|
|
76
|
+
condition.other === undefined &&
|
|
77
|
+
condition.collation === undefined &&
|
|
78
|
+
condition.equality === undefined &&
|
|
79
|
+
(!sqlite || rule.binary?.includes(condition.column) === true) &&
|
|
80
|
+
columns.includes(condition.column) &&
|
|
81
|
+
condition.value !== undefined &&
|
|
82
|
+
!Array.isArray(condition.value) &&
|
|
83
|
+
Object.hasOwn(row, condition.column) &&
|
|
84
|
+
row[condition.column] === condition.value));
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A unique rule's refusal of a scoped write, where the row it conflicts with may be one the principal cannot read:
|
|
88
|
+
* said as the scope's own refusal, so neither the column nor the fact that the value is taken outside its rows is
|
|
89
|
+
* named. The operator reads the table and the columns, never the value.
|
|
90
|
+
*/
|
|
91
|
+
export const uniqueRefusal = (table, columns) => recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), `A unique rule on "${table.id}"${columns ? ` (${columns.map((column) => JSON.stringify(column)).join(', ')})` : ''} refused the write, and the row it conflicts with may be outside the principal's rows.`);
|
|
24
92
|
/** A table's triggers as a refusal names them: `the trigger "audit_order"`, `the triggers "a", "b"`. */
|
|
25
93
|
export const triggerNames = (names) => `the trigger${names.length === 1 ? '' : 's'} ${names.map((name) => JSON.stringify(name)).join(', ')}`;
|
|
26
94
|
/* The trigger vocabulary, for `mistri check` (commandTriggerChecks.ts), which says the same refusal ahead of time. */
|
|
@@ -114,6 +182,39 @@ export class ScopeRefusal extends Refusal {
|
|
|
114
182
|
const refuse = (reason) => {
|
|
115
183
|
throw recordRefusalCause(new ScopeRefusal('This operation is not available in the current row scope.'), reason);
|
|
116
184
|
};
|
|
185
|
+
/** The sentence a delete hears when every row still referencing it is one its principal cannot read. */
|
|
186
|
+
export const IN_USE = "This record is in use and can't be deleted.";
|
|
187
|
+
/**
|
|
188
|
+
* A delete refused because rows still reference the row, said as the record's state rather than as the scope: the
|
|
189
|
+
* person can act on it. Its words name only what the principal reads — the referencing table and how many of its
|
|
190
|
+
* rows point here, counted under the principal's own rows — and, where every remaining reference is one the scope
|
|
191
|
+
* hides (another tenant's row on a shared parent, a row the policy keeps from them), name nothing: {@link IN_USE}.
|
|
192
|
+
* That the delete is refused at all is the one thing such a row still says, and it cannot be otherwise: deleting it
|
|
193
|
+
* would reach that row. The total across every row is recorded for the operator only.
|
|
194
|
+
*/
|
|
195
|
+
export class ReferencedRefusal extends ScopeRefusal {
|
|
196
|
+
seen;
|
|
197
|
+
constructor(
|
|
198
|
+
/** What the principal reads of the references: the table and its count, or nothing when it reads none. */
|
|
199
|
+
seen) {
|
|
200
|
+
super(seen
|
|
201
|
+
? `${seen.count === 1 ? 'A record' : `${seen.count} records`} in "${seen.table}" still ${seen.count === 1 ? 'points' : 'point'} at this one. Change or remove ${seen.count === 1 ? 'it' : 'them'} first, then try again.`
|
|
202
|
+
: IN_USE);
|
|
203
|
+
this.seen = seen;
|
|
204
|
+
this.name = 'ReferencedRefusal';
|
|
205
|
+
sayRefusal(this, this.message);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/** The ReferencedRefusal a failure was rebuilt over, however many value-free wrappers lie between. */
|
|
209
|
+
export function referencedBeneath(error) {
|
|
210
|
+
let at = error;
|
|
211
|
+
for (let depth = 0; at !== null && typeof at === 'object' && depth < 16; depth++) {
|
|
212
|
+
if (at instanceof ReferencedRefusal)
|
|
213
|
+
return at;
|
|
214
|
+
at = refusalCause(at) ?? (at instanceof Error ? at.cause : undefined);
|
|
215
|
+
}
|
|
216
|
+
return undefined;
|
|
217
|
+
}
|
|
117
218
|
const isViaCondition = (condition) => typeof condition.via?.resource === 'string';
|
|
118
219
|
const keyText = (key) => Object.entries(key)
|
|
119
220
|
.map(([column, value]) => `${column} ${JSON.stringify(value)}`)
|
|
@@ -199,6 +300,28 @@ referencesOf) {
|
|
|
199
300
|
reads = own.reads(scope, false);
|
|
200
301
|
guards = own.reads(scope, true);
|
|
201
302
|
};
|
|
303
|
+
/* A row still referenced, said in what the principal reads of it. The total above counts every row on the writer, as
|
|
304
|
+
the cascade would reach them; how many of those the principal reads is counted again under its own rows, by each
|
|
305
|
+
referencing column as the child compares — where the foreign key matches more than that (a parent collation the
|
|
306
|
+
child lacks), fewer are named, never more, and none named is the sentence that names nothing. */
|
|
307
|
+
const referencedRefusal = async (table, key, referenced) => {
|
|
308
|
+
const cause = `A scoped command may not delete the "${table.id}" row ${keyText(key)}: ${referenced
|
|
309
|
+
.map(({ fk, total }) => `"${fk.from.table}" still references it (${total} ${total === 1 ? 'row' : 'rows'} in all)`)
|
|
310
|
+
.join(', ')}.`;
|
|
311
|
+
for (const { fk, values } of referenced) {
|
|
312
|
+
const seen = await reads
|
|
313
|
+
.count(fk.from.table, { groups: [fk.from.columns.map((column, index) => ({ column, op: '=', value: values[index] }))] })
|
|
314
|
+
.catch((error) => {
|
|
315
|
+
// A table the principal does not read at all reads none of the references: refused as the one that names nothing.
|
|
316
|
+
if (error instanceof Refusal)
|
|
317
|
+
return 0;
|
|
318
|
+
throw error;
|
|
319
|
+
});
|
|
320
|
+
if (seen > 0)
|
|
321
|
+
return recordRefusalCause(new ReferencedRefusal({ table: fk.from.table, count: seen }), cause);
|
|
322
|
+
}
|
|
323
|
+
return recordRefusalCause(new ReferencedRefusal(), cause);
|
|
324
|
+
};
|
|
202
325
|
const target = (id, write) => {
|
|
203
326
|
const table = catalog.schema.tables.find((table) => table.id === id);
|
|
204
327
|
if (!table)
|
|
@@ -527,11 +650,23 @@ referencesOf) {
|
|
|
527
650
|
/* The statements themselves. A foreign key that refuses one answers as a hidden parent does (foreignKeyRefusal):
|
|
528
651
|
the checks before a write compare what it names, and this is everything they cannot see — a default's part of a
|
|
529
652
|
reference, a value a trigger writes, a deferred check. */
|
|
530
|
-
|
|
531
|
-
|
|
653
|
+
/* A unique rule that refuses one names its column, and on PostgreSQL the value, of a row that may be outside the
|
|
654
|
+
principal's rows: that the value is taken there is what the scope keeps. It is let through only where the
|
|
655
|
+
conflicting row is one the principal reads (uniqueConflictSeen); otherwise it is the scope's own refusal. */
|
|
656
|
+
const statement = (sent, table, row) => sent.catch((error) => {
|
|
657
|
+
if (isForeignKeyViolation(error))
|
|
658
|
+
throw foreignKeyRefusal(error);
|
|
659
|
+
if (isUniqueViolation(error) && table) {
|
|
660
|
+
const columns = uniqueColumns(error, table);
|
|
661
|
+
// With a scope present, a table it does not name has no rows the principal reads (shared/rowScope.ts).
|
|
662
|
+
const rule = scope === undefined ? true : Object.hasOwn(scope, table.id) ? scope[table.id] : false;
|
|
663
|
+
if (!columns || !uniqueConflictSeen(rule, columns, row ?? {}, typeof error.errcode === 'number'))
|
|
664
|
+
throw uniqueRefusal(table, columns);
|
|
665
|
+
}
|
|
666
|
+
throw error;
|
|
532
667
|
});
|
|
533
|
-
const insertRow = (request) => statement(records.insert(request));
|
|
534
|
-
const updateRow = (request) => statement(records.update(request));
|
|
668
|
+
const insertRow = (table, request) => statement(records.insert(request), table, request.values ?? {});
|
|
669
|
+
const updateRow = (table, request, row) => statement(records.update(request), table, row);
|
|
535
670
|
const afterward = async (afterwards, images) => {
|
|
536
671
|
for (const next of afterwards ?? [])
|
|
537
672
|
await next(images);
|
|
@@ -551,7 +686,7 @@ referencesOf) {
|
|
|
551
686
|
const given = unproven(parentChecks(table, request.values ?? {}, undefined, true));
|
|
552
687
|
if (!locks?.together)
|
|
553
688
|
await verify(given);
|
|
554
|
-
const result = locks?.together ? await parentsFirst(given, () => insertRow(request)) : await insertRow(request);
|
|
689
|
+
const result = locks?.together ? await parentsFirst(given, () => insertRow(table, request)) : await insertRow(table, request);
|
|
555
690
|
const filter = keyFilter(table, result.key);
|
|
556
691
|
/* The new row locked and read back, and where the writer sends together
|
|
557
692
|
its references checked in the same flight, from the row the INSERT
|
|
@@ -588,7 +723,8 @@ referencesOf) {
|
|
|
588
723
|
const set = new Set(Object.keys(request.values ?? {}));
|
|
589
724
|
const afterwards = proof && (await proof.before(table, { kind: 'update', set: [...set] }, proof.images.update(table, before, request.values)));
|
|
590
725
|
// What the update sets is given; every other column of a reference it sets in part is as stored, bound as its text.
|
|
591
|
-
const
|
|
726
|
+
const written = overlaid(before, request.values);
|
|
727
|
+
const given = unproven(parentChecks(table, written, set, true));
|
|
592
728
|
if (!locks?.together)
|
|
593
729
|
await verify(given);
|
|
594
730
|
/* The row read again after the write, sent the moment the write is: it
|
|
@@ -605,7 +741,9 @@ referencesOf) {
|
|
|
605
741
|
let result;
|
|
606
742
|
try {
|
|
607
743
|
// The references it sets leave ahead of it, in its flight (parentsFirst).
|
|
608
|
-
result = locks?.together
|
|
744
|
+
result = locks?.together
|
|
745
|
+
? await parentsFirst(given, () => updateRow(table, request, written))
|
|
746
|
+
: await updateRow(table, request, written);
|
|
609
747
|
}
|
|
610
748
|
finally {
|
|
611
749
|
withdraw?.();
|
|
@@ -637,6 +775,7 @@ referencesOf) {
|
|
|
637
775
|
are counted: across every row of each table, on the writer itself,
|
|
638
776
|
since the principal sees every row the bound holds there and a row
|
|
639
777
|
outside the bound pointing in is the one a cascade must never reach. */
|
|
778
|
+
const referenced = [];
|
|
640
779
|
for (const fk of children) {
|
|
641
780
|
const values = fk.to.columns.map((column) => row[column]);
|
|
642
781
|
if (values.some((value) => value === null))
|
|
@@ -644,9 +783,14 @@ referencesOf) {
|
|
|
644
783
|
if (!values.every(comparable))
|
|
645
784
|
return refuse(`"${table.id}".${fk.to.columns.join('+')} holds a value that is not a text or a number.`);
|
|
646
785
|
const key = { groups: [Object.entries(request.key).map(([column, value]) => ({ column, op: '=', value }))] };
|
|
647
|
-
|
|
648
|
-
|
|
786
|
+
const total = await counted?.(fk, key);
|
|
787
|
+
if (total === undefined)
|
|
788
|
+
return refuse(`A scoped command may not delete the "${table.id}" row ${keyText(request.key)}: its references were not counted.`);
|
|
789
|
+
if (total !== 0)
|
|
790
|
+
referenced.push({ fk, values, total });
|
|
649
791
|
}
|
|
792
|
+
if (referenced.length)
|
|
793
|
+
throw await referencedRefusal(table, request.key, referenced);
|
|
650
794
|
const afterwards = proof && (await proof.before(table, { kind: 'delete' }, proof.images.delete(row)));
|
|
651
795
|
const result = await statement(records.remove(request));
|
|
652
796
|
if (result.affected !== 1)
|
|
@@ -75,6 +75,8 @@ 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); SQLite has none. */
|
|
79
|
+
readonly tenant?: string;
|
|
78
80
|
}
|
|
79
81
|
/** The callback: the records, the journal, and a scoped transaction's catalog evidence (absent in an ordinary one). */
|
|
80
82
|
export type JournalRun<J, T> = (records: WriteTransaction, journal: J, catalog?: DatabaseSchema) => Promise<T>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mistriwork/engine",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.52",
|
|
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": {
|