@bezoar/core 0.0.4 → 0.0.6
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/index.d.mts +147 -17
- package/.dist/index.mjs +79 -4
- package/README.md +57 -2
- package/package.json +2 -2
package/.dist/index.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { Arguments, Bundle, Database, Definition, Issue, Query, Returns, Row, RowQuery, Schema } from "@bezoar/schema";
|
|
1
|
+
import { Arguments, Bundle, Database, Definition, Issue, Query, Returns, Role, RoleQuery, Row, RowQuery, Schema } from "@bezoar/schema";
|
|
2
2
|
import { Compilable, Kysely } from "kysely";
|
|
3
3
|
/**
|
|
4
4
|
* The members of a service. A query group cannot take one of these names.
|
|
5
5
|
*/
|
|
6
|
-
export declare const RESERVED: readonly ["config", "schema", "query", "first", "execute", "build", "transaction", "migrate", "seed"];
|
|
6
|
+
export declare const RESERVED: readonly ["config", "schema", "query", "first", "execute", "build", "transaction", "migrate", "seed", "roles"];
|
|
7
7
|
/**
|
|
8
8
|
* The query name a report carries for a built query: one that ran through
|
|
9
9
|
* the builder rather than the contract. The name of the builder member of
|
|
@@ -36,6 +36,34 @@ export declare const APPLIED = "SELECT version, checksum FROM bezoar_migrations
|
|
|
36
36
|
* Records one applied migration.
|
|
37
37
|
*/
|
|
38
38
|
export declare const RECORD = "INSERT INTO bezoar_migrations (version, name, checksum) VALUES ($1, $2, $3)";
|
|
39
|
+
/**
|
|
40
|
+
* The key of the advisory lock a roles run holds. Two runs against one
|
|
41
|
+
* database wait for each other, as two migration runs do.
|
|
42
|
+
*/
|
|
43
|
+
export declare const ROLES_LOCK = 6451065;
|
|
44
|
+
/**
|
|
45
|
+
* Whether a role exists in the cluster.
|
|
46
|
+
*/
|
|
47
|
+
export declare const EXISTS = "SELECT 1 FROM pg_roles WHERE rolname = $1";
|
|
48
|
+
/**
|
|
49
|
+
* The schemas of the database other than the system ones: where a grant
|
|
50
|
+
* reaches, and where a roles run revokes before it grants.
|
|
51
|
+
*/
|
|
52
|
+
export declare const SCHEMAS = "SELECT nspname FROM pg_namespace\n WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'\n ORDER BY nspname";
|
|
53
|
+
/**
|
|
54
|
+
* Quotes an identifier for SQL text: a role or a schema name.
|
|
55
|
+
*/
|
|
56
|
+
export declare const quote: (name: string) => string;
|
|
57
|
+
/**
|
|
58
|
+
* Makes a role that cannot log in. A role of bezoar is a group: a login user
|
|
59
|
+
* the deployment makes joins it with `IN ROLE`.
|
|
60
|
+
*/
|
|
61
|
+
export declare const DECLARE: (role: string) => string;
|
|
62
|
+
/**
|
|
63
|
+
* Takes every privilege of a role on the objects of a schema, so that the
|
|
64
|
+
* grant file of the role states the whole of them.
|
|
65
|
+
*/
|
|
66
|
+
export declare const REVOKE: (role: string, schema: string) => string;
|
|
39
67
|
/**
|
|
40
68
|
* Raised at construction when the SQL bundle does not match the contract: a
|
|
41
69
|
* query without SQL, or SQL for a query the contract does not declare.
|
|
@@ -115,6 +143,33 @@ export declare class SeedError extends Error {
|
|
|
115
143
|
readonly seed: string;
|
|
116
144
|
constructor(seed: string, cause: unknown);
|
|
117
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* Raised when a grant fails to apply: the role could not be made, a revoke
|
|
148
|
+
* failed, or its SQL failed. Carries the role and the driver's error as
|
|
149
|
+
* `cause`. The transaction rolls back.
|
|
150
|
+
*/
|
|
151
|
+
export declare class RoleError extends Error {
|
|
152
|
+
readonly role: string;
|
|
153
|
+
constructor(role: string, cause: unknown);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Raised at construction when the service is scoped to a role the contract
|
|
157
|
+
* does not have.
|
|
158
|
+
*/
|
|
159
|
+
export declare class UnknownRoleError extends Error {
|
|
160
|
+
readonly role: string;
|
|
161
|
+
constructor(role: string);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Raised when a service scoped to a role is asked for a query the role may
|
|
165
|
+
* not run. The service of a role offers the queries of the role and no
|
|
166
|
+
* other.
|
|
167
|
+
*/
|
|
168
|
+
export declare class ForbiddenQueryError extends Error {
|
|
169
|
+
readonly query: string;
|
|
170
|
+
readonly role: string;
|
|
171
|
+
constructor(query: string, role: string);
|
|
172
|
+
}
|
|
118
173
|
/**
|
|
119
174
|
* Runs a schema check and rethrows its {@link SchemaError} as the error that
|
|
120
175
|
* `frame` makes from the issues. Any other error propagates untouched.
|
|
@@ -149,16 +204,33 @@ export interface Executor {
|
|
|
149
204
|
exec(sql: string): Promise<void>;
|
|
150
205
|
transaction<T>(run: (executor: Executor) => Promise<T>): Promise<T>;
|
|
151
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* The role a service is scoped to: a role of the contract, or `undefined`
|
|
209
|
+
* for a service over every query.
|
|
210
|
+
*/
|
|
211
|
+
export type Scoping<D extends Definition> = Role<D> | undefined;
|
|
212
|
+
/**
|
|
213
|
+
* The queries a service scoped to `R` offers: the queries of the role, or
|
|
214
|
+
* every query of the contract when there is no role.
|
|
215
|
+
*/
|
|
216
|
+
export type Scope<D extends Definition, R extends Scoping<D>> = [R] extends [Role<D>] ? RoleQuery<D, R> : Query<D>;
|
|
152
217
|
/**
|
|
153
218
|
* The caller-owned state a {@link Bezoar} service reads: the executor it
|
|
154
219
|
* runs on and the SQL of every query. The service reads the executor on each
|
|
155
220
|
* call. A caller can replace it.
|
|
156
221
|
*/
|
|
157
|
-
export type Config<D extends Definition> = {
|
|
222
|
+
export type Config<D extends Definition, R extends Scoping<D> = undefined> = {
|
|
158
223
|
/** The connection the service runs on. */
|
|
159
224
|
executor: Executor;
|
|
160
225
|
/** The SQL of each query, by name, as `@bezoar/kit` built it. */
|
|
161
226
|
queries: Bundle<D>;
|
|
227
|
+
/**
|
|
228
|
+
* The role the service is scoped to. The service offers the queries the
|
|
229
|
+
* kit found the role may run and no other, and the executor is expected
|
|
230
|
+
* to run as the role: a driver takes the role when it connects. Without
|
|
231
|
+
* one, the service offers every query of the contract.
|
|
232
|
+
*/
|
|
233
|
+
role?: R;
|
|
162
234
|
};
|
|
163
235
|
/**
|
|
164
236
|
* What the service reports after a query runs: the name, the SQL, the
|
|
@@ -204,6 +276,16 @@ export interface Seed {
|
|
|
204
276
|
readonly name: string;
|
|
205
277
|
readonly sql: string;
|
|
206
278
|
}
|
|
279
|
+
/**
|
|
280
|
+
* One grant, as `@bezoar/kit` built it: the name of a role, and the SQL
|
|
281
|
+
* that gives the role its privileges. A grant is not tracked: the runner
|
|
282
|
+
* revokes what the role holds and runs the SQL again, so the SQL states the
|
|
283
|
+
* whole of the privileges of the role.
|
|
284
|
+
*/
|
|
285
|
+
export interface Grant {
|
|
286
|
+
readonly role: string;
|
|
287
|
+
readonly sql: string;
|
|
288
|
+
}
|
|
207
289
|
/**
|
|
208
290
|
* The arguments a query is called with: its arguments when it has a required
|
|
209
291
|
* slot, and optional arguments when every slot is nullable or there is none.
|
|
@@ -227,9 +309,10 @@ type Tree<D extends Definition, K extends string, P extends string = ""> = { rea
|
|
|
227
309
|
* The queries of a contract as functions: `db.events.list({ day })`. A dot
|
|
228
310
|
* in a name is a level of the object. The query `events.list` is
|
|
229
311
|
* `db.events.list()`, and its first row is `db.events.list.first()`. The
|
|
230
|
-
* directory of a query file is its group and the file is its name.
|
|
312
|
+
* directory of a query file is its group and the file is its name. `Q` is
|
|
313
|
+
* the queries to offer: every query of the contract, or those of a role.
|
|
231
314
|
*/
|
|
232
|
-
export type Groups<D extends Definition> = Tree<D,
|
|
315
|
+
export type Groups<D extends Definition, Q extends Query<D> = Query<D>> = Tree<D, Q>;
|
|
233
316
|
/**
|
|
234
317
|
* A validator of a row, in the shape of a zod schema: `safeParse` answers
|
|
235
318
|
* with the value as `R` on success and with the issues on failure. Any zod
|
|
@@ -263,15 +346,32 @@ export interface Execute {
|
|
|
263
346
|
<O, R extends O>(query: Compilable<O>, row: Validator<R>): Promise<R | null>;
|
|
264
347
|
};
|
|
265
348
|
}
|
|
349
|
+
/**
|
|
350
|
+
* Applies the grants of a build, and `declare` makes their roles alone.
|
|
351
|
+
*/
|
|
352
|
+
export interface Roles {
|
|
353
|
+
/**
|
|
354
|
+
* Makes the roles the cluster lacks, and applies the grants: for each
|
|
355
|
+
* role, revokes what it holds and runs its SQL, inside one transaction
|
|
356
|
+
* under an advisory lock. Throws `RoleError` when one fails.
|
|
357
|
+
*/
|
|
358
|
+
(grants: readonly Grant[]): Promise<void>;
|
|
359
|
+
/**
|
|
360
|
+
* Makes the roles the cluster lacks and grants nothing. What a migration
|
|
361
|
+
* that names a role needs before it runs.
|
|
362
|
+
*/
|
|
363
|
+
readonly declare: (grants: readonly Grant[]) => Promise<void>;
|
|
364
|
+
}
|
|
266
365
|
/**
|
|
267
366
|
* The members of a service other than its queries. A query group cannot
|
|
268
|
-
* take one of these names.
|
|
367
|
+
* take one of these names. `R` is the role the service is scoped to, or
|
|
368
|
+
* `undefined` for a service over every query.
|
|
269
369
|
*/
|
|
270
|
-
export interface Service<D extends Definition> {
|
|
370
|
+
export interface Service<D extends Definition, R extends Scoping<D> = undefined> {
|
|
271
371
|
/**
|
|
272
|
-
* The caller-owned state: the executor
|
|
372
|
+
* The caller-owned state: the executor, the SQL bundle, and the role.
|
|
273
373
|
*/
|
|
274
|
-
config: Config<D>;
|
|
374
|
+
config: Config<D, R>;
|
|
275
375
|
/**
|
|
276
376
|
* The validation bundle for the contract.
|
|
277
377
|
*/
|
|
@@ -283,13 +383,13 @@ export interface Service<D extends Definition> {
|
|
|
283
383
|
* when the arguments do not fit the slots, `QueryError` when the driver
|
|
284
384
|
* fails, and `InvalidRowError` when a row does not fit the columns.
|
|
285
385
|
*/
|
|
286
|
-
query: <Q extends
|
|
386
|
+
query: <Q extends Scope<D, R>>(query: Q, ...args: Args<D, Q>) => Promise<Returns<D, Q>>;
|
|
287
387
|
/**
|
|
288
388
|
* Runs a query with a column by name and returns its first row, or `null`
|
|
289
389
|
* when it has none. The same call as `first` on the function under its
|
|
290
390
|
* group. Proves the row it returns and no other. Throws as `query` does.
|
|
291
391
|
*/
|
|
292
|
-
first: <Q extends RowQuery<D>>(query: Q, ...args: Args<D, Q>) => Promise<Row<D, Q> | null>;
|
|
392
|
+
first: <Q extends Scope<D, R> & RowQuery<D>>(query: Q, ...args: Args<D, Q>) => Promise<Row<D, Q> | null>;
|
|
293
393
|
/**
|
|
294
394
|
* Runs a built query and returns its rows, proven against a validator
|
|
295
395
|
* when one is given. `execute.first` returns the first row or `null`. See
|
|
@@ -312,7 +412,7 @@ export interface Service<D extends Definition> {
|
|
|
312
412
|
* transaction commits when the function returns and rolls back when it
|
|
313
413
|
* throws.
|
|
314
414
|
*/
|
|
315
|
-
transaction: <T>(run: (tx: Bezoar<D>) => Promise<T>) => Promise<T>;
|
|
415
|
+
transaction: <T>(run: (tx: Bezoar<D, R>) => Promise<T>) => Promise<T>;
|
|
316
416
|
/**
|
|
317
417
|
* Applies the migrations the database lacks, in the order given, inside
|
|
318
418
|
* one transaction under an advisory lock. Returns the versions it applied.
|
|
@@ -325,13 +425,18 @@ export interface Service<D extends Definition> {
|
|
|
325
425
|
* `SeedError` when one fails.
|
|
326
426
|
*/
|
|
327
427
|
seed: (seeds: readonly Seed[]) => Promise<void>;
|
|
428
|
+
/**
|
|
429
|
+
* Applies the grants of a build. See {@link Roles}.
|
|
430
|
+
*/
|
|
431
|
+
roles: Roles;
|
|
328
432
|
}
|
|
329
433
|
/**
|
|
330
434
|
* A runtime database service over a contract. The service has its members
|
|
331
435
|
* and, beside them, a function for every query under its group. It never
|
|
332
|
-
* connects: the caller brings an executor from a driver package.
|
|
436
|
+
* connects: the caller brings an executor from a driver package. A service
|
|
437
|
+
* scoped to a role `R` has a function for the queries of the role alone.
|
|
333
438
|
*/
|
|
334
|
-
export type Bezoar<D extends Definition> = Service<D> & Groups<D
|
|
439
|
+
export type Bezoar<D extends Definition, R extends Scoping<D> = undefined> = Service<D, R> & Groups<D, Scope<D, R>>;
|
|
335
440
|
/**
|
|
336
441
|
* Builds the runtime {@link Bezoar} service over a contract.
|
|
337
442
|
*
|
|
@@ -342,15 +447,40 @@ export type Bezoar<D extends Definition> = Service<D> & Groups<D>;
|
|
|
342
447
|
* has no column. `first` returns the first row instead. The service never
|
|
343
448
|
* connects: the caller brings an executor from a driver
|
|
344
449
|
* package, and a transaction is the same service over the executor of the
|
|
345
|
-
* transaction.
|
|
450
|
+
* transaction. A container with a role makes a service over the queries of
|
|
451
|
+
* the role alone, typed so, over an executor the driver runs as the role.
|
|
346
452
|
*
|
|
347
453
|
* @param definition - The contract: the kit's `contract` export.
|
|
348
|
-
* @param config - The caller-owned container: the executor
|
|
454
|
+
* @param config - The caller-owned container: the executor, the bundle, and
|
|
455
|
+
* the role, if any.
|
|
349
456
|
* @param options - The runtime features: a report after each query.
|
|
350
457
|
* @returns A {@link Bezoar} service bound to the container.
|
|
351
458
|
* @throws InvalidBundleError when the bundle does not match the contract.
|
|
459
|
+
* @throws UnknownRoleError when the contract has no such role.
|
|
352
460
|
* @throws ReservedQueryError when a query group takes a member's name.
|
|
353
461
|
* @throws AmbiguousQueryError when a name is both a query and a group.
|
|
354
462
|
*/
|
|
355
|
-
export declare const makeBezoar: <const D extends Definition>(definition: D, config: Config<D>, options?: Options<D>) => Bezoar<D>;
|
|
463
|
+
export declare const makeBezoar: <const D extends Definition, const R extends Scoping<D> = undefined>(definition: D, config: Config<D, R>, options?: Options<D>) => Bezoar<D, R>;
|
|
464
|
+
/**
|
|
465
|
+
* Makes the roles the cluster lacks, inside one transaction. What a
|
|
466
|
+
* migration needs before it can name a role, in a policy or a grant of its
|
|
467
|
+
* own. Nothing is granted.
|
|
468
|
+
*
|
|
469
|
+
* @param executor - The connection to run on.
|
|
470
|
+
* @param grants - The grants, for the names of their roles.
|
|
471
|
+
*/
|
|
472
|
+
export declare const declareRoles: (executor: Executor, grants: readonly Grant[]) => Promise<void>;
|
|
473
|
+
/**
|
|
474
|
+
* Applies the grants: makes the roles the cluster lacks, and for each role
|
|
475
|
+
* revokes every privilege it holds on the objects of each schema and then
|
|
476
|
+
* runs its SQL. The run is one transaction under an advisory lock, so two
|
|
477
|
+
* runs wait for each other and a run is all or nothing. A grant file states
|
|
478
|
+
* the whole of the privileges of its role: a grant removed from the file is
|
|
479
|
+
* gone after the next run. A membership of a role in another, and a default
|
|
480
|
+
* privilege, are not revoked.
|
|
481
|
+
*
|
|
482
|
+
* @param executor - The connection to run on.
|
|
483
|
+
* @param grants - The grants, in the order to apply them.
|
|
484
|
+
*/
|
|
485
|
+
export declare const roles: (executor: Executor, grants: readonly Grant[]) => Promise<void>;
|
|
356
486
|
export {};
|
package/.dist/index.mjs
CHANGED
|
@@ -10,7 +10,8 @@ const RESERVED = [
|
|
|
10
10
|
"build",
|
|
11
11
|
"transaction",
|
|
12
12
|
"migrate",
|
|
13
|
-
"seed"
|
|
13
|
+
"seed",
|
|
14
|
+
"roles"
|
|
14
15
|
];
|
|
15
16
|
const BUILT = "build";
|
|
16
17
|
const TABLE = "bezoar_migrations";
|
|
@@ -24,6 +25,19 @@ const CREATE = `CREATE TABLE IF NOT EXISTS ${TABLE} (
|
|
|
24
25
|
)`;
|
|
25
26
|
const APPLIED = `SELECT version, checksum FROM ${TABLE} ORDER BY version`;
|
|
26
27
|
const RECORD = `INSERT INTO ${TABLE} (version, name, checksum) VALUES ($1, $2, $3)`;
|
|
28
|
+
const ROLES_LOCK = 6451065;
|
|
29
|
+
const EXISTS = "SELECT 1 FROM pg_roles WHERE rolname = $1";
|
|
30
|
+
const SCHEMAS = `SELECT nspname FROM pg_namespace
|
|
31
|
+
WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'
|
|
32
|
+
ORDER BY nspname`;
|
|
33
|
+
const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
34
|
+
const DECLARE = (role) => `CREATE ROLE ${quote(role)} NOLOGIN`;
|
|
35
|
+
const REVOKE = (role, schema) => [
|
|
36
|
+
`REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA ${quote(schema)} FROM ${quote(role)}`,
|
|
37
|
+
`REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA ${quote(schema)} FROM ${quote(role)}`,
|
|
38
|
+
`REVOKE ALL PRIVILEGES ON ALL ROUTINES IN SCHEMA ${quote(schema)} FROM ${quote(role)}`,
|
|
39
|
+
`REVOKE ALL PRIVILEGES ON SCHEMA ${quote(schema)} FROM ${quote(role)}`
|
|
40
|
+
].join(";\n");
|
|
27
41
|
const summarize = (issues) => issues.map((issue) => issue.path.length ? `${issue.path.map(String).join(".")}: ${issue.message}` : issue.message).join("\n");
|
|
28
42
|
var InvalidBundleError = class extends Error {
|
|
29
43
|
issues;
|
|
@@ -103,6 +117,32 @@ var SeedError = class extends Error {
|
|
|
103
117
|
this.seed = seed;
|
|
104
118
|
}
|
|
105
119
|
};
|
|
120
|
+
var RoleError = class extends Error {
|
|
121
|
+
role;
|
|
122
|
+
constructor(role, cause) {
|
|
123
|
+
super(`@bezoar/core: the grant of ${JSON.stringify(role)} failed`, { cause });
|
|
124
|
+
this.name = "RoleError";
|
|
125
|
+
this.role = role;
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
var UnknownRoleError = class extends Error {
|
|
129
|
+
role;
|
|
130
|
+
constructor(role) {
|
|
131
|
+
super(`@bezoar/core: the contract has no role ${JSON.stringify(role)}`);
|
|
132
|
+
this.name = "UnknownRoleError";
|
|
133
|
+
this.role = role;
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
var ForbiddenQueryError = class extends Error {
|
|
137
|
+
query;
|
|
138
|
+
role;
|
|
139
|
+
constructor(query, role) {
|
|
140
|
+
super(`@bezoar/core: ${JSON.stringify(query)} is not a query of the role ${JSON.stringify(role)}`);
|
|
141
|
+
this.name = "ForbiddenQueryError";
|
|
142
|
+
this.query = query;
|
|
143
|
+
this.role = role;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
106
146
|
const reframe = (frame, run) => {
|
|
107
147
|
try {
|
|
108
148
|
return run();
|
|
@@ -205,6 +245,28 @@ const migrate = (executor, migrations) => executor.transaction(async (tx) => {
|
|
|
205
245
|
}
|
|
206
246
|
return done;
|
|
207
247
|
});
|
|
248
|
+
const ensure = async (tx, grants) => {
|
|
249
|
+
for (const grant of grants) {
|
|
250
|
+
const { rows } = await tx.query(EXISTS, [grant.role]);
|
|
251
|
+
if (rows.length === 0) try {
|
|
252
|
+
await tx.exec(DECLARE(grant.role));
|
|
253
|
+
} catch (cause) {
|
|
254
|
+
throw new RoleError(grant.role, cause);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
const declareRoles = (executor, grants) => executor.transaction((tx) => ensure(tx, grants));
|
|
259
|
+
const roles = (executor, grants) => executor.transaction(async (tx) => {
|
|
260
|
+
await tx.query(ACQUIRE, [ROLES_LOCK]);
|
|
261
|
+
await ensure(tx, grants);
|
|
262
|
+
const schemas = (await tx.query(SCHEMAS, [])).rows.map((row) => String(row.nspname));
|
|
263
|
+
for (const grant of grants) try {
|
|
264
|
+
for (const schema of schemas) await tx.exec(REVOKE(grant.role, schema));
|
|
265
|
+
await tx.exec(grant.sql);
|
|
266
|
+
} catch (cause) {
|
|
267
|
+
throw new RoleError(grant.role, cause);
|
|
268
|
+
}
|
|
269
|
+
});
|
|
208
270
|
const seed = (executor, seeds) => executor.transaction(async (tx) => {
|
|
209
271
|
for (const entry of seeds) try {
|
|
210
272
|
await tx.exec(entry.sql);
|
|
@@ -213,7 +275,18 @@ const seed = (executor, seeds) => executor.transaction(async (tx) => {
|
|
|
213
275
|
}
|
|
214
276
|
});
|
|
215
277
|
const bind = (slots, given) => slots.map((slot) => given[slot.name] ?? null);
|
|
278
|
+
const scopeOf = (definition, role) => {
|
|
279
|
+
if (role === void 0) return keys(definition.queries);
|
|
280
|
+
const queries = definition.roles?.[role];
|
|
281
|
+
if (queries === void 0) throw new UnknownRoleError(role);
|
|
282
|
+
return queries;
|
|
283
|
+
};
|
|
216
284
|
const defineService = (definition, schema, config, options) => {
|
|
285
|
+
const names = scopeOf(definition, config.role);
|
|
286
|
+
const offered = new Set(names);
|
|
287
|
+
const admit = (query) => {
|
|
288
|
+
if (config.role !== void 0 && !offered.has(query)) throw new ForbiddenQueryError(query, config.role);
|
|
289
|
+
};
|
|
217
290
|
const execute = async (query, params) => {
|
|
218
291
|
try {
|
|
219
292
|
return await config.executor.query(config.queries[query], params);
|
|
@@ -223,6 +296,7 @@ const defineService = (definition, schema, config, options) => {
|
|
|
223
296
|
};
|
|
224
297
|
const prove = (query, index, row) => reframe((issues) => new InvalidRowError(query, index, issues), () => schema.assert.row(query, row));
|
|
225
298
|
const perform = async (query, args) => {
|
|
299
|
+
admit(query);
|
|
226
300
|
const statement = definition.queries[query];
|
|
227
301
|
const given = reframe((issues) => new InvalidArgumentsError(query, issues), () => schema.parse.arguments(query, args));
|
|
228
302
|
const started = performance.now();
|
|
@@ -296,9 +370,10 @@ const defineService = (definition, schema, config, options) => {
|
|
|
296
370
|
build: builder,
|
|
297
371
|
transaction,
|
|
298
372
|
migrate: (migrations) => migrate(config.executor, migrations),
|
|
299
|
-
seed: (seeds) => seed(config.executor, seeds)
|
|
373
|
+
seed: (seeds) => seed(config.executor, seeds),
|
|
374
|
+
roles: Object.assign((grants) => roles(config.executor, grants), { declare: (grants) => declareRoles(config.executor, grants) })
|
|
300
375
|
};
|
|
301
|
-
const groups = defineGroups(
|
|
376
|
+
const groups = defineGroups(names, new Set(RESERVED), (query) => {
|
|
302
377
|
const method = (args) => run(query, args);
|
|
303
378
|
return returnsRows(query) ? Object.assign(method, { first: (args) => take(query, args) }) : method;
|
|
304
379
|
});
|
|
@@ -309,4 +384,4 @@ const makeBezoar = (definition, config, options = {}) => {
|
|
|
309
384
|
reframe((issues) => new InvalidBundleError(issues), () => schema.assert.bundle(config.queries));
|
|
310
385
|
return defineService(definition, schema, config, options);
|
|
311
386
|
};
|
|
312
|
-
export { ACQUIRE, APPLIED, AmbiguousQueryError, BUILT, CREATE, InvalidArgumentsError, InvalidBundleError, InvalidRowError, LOCK, MigrationDriftError, MigrationError, QueryError, RECORD, RESERVED, ReservedQueryError, SeedError, TABLE, makeBezoar, reframe };
|
|
387
|
+
export { ACQUIRE, APPLIED, AmbiguousQueryError, BUILT, CREATE, DECLARE, EXISTS, ForbiddenQueryError, InvalidArgumentsError, InvalidBundleError, InvalidRowError, LOCK, MigrationDriftError, MigrationError, QueryError, RECORD, RESERVED, REVOKE, ROLES_LOCK, ReservedQueryError, RoleError, SCHEMAS, SeedError, TABLE, UnknownRoleError, declareRoles, makeBezoar, quote, reframe, roles };
|
package/README.md
CHANGED
|
@@ -154,6 +154,57 @@ The transaction commits when the function returns and rolls back when it
|
|
|
154
154
|
throws. Whether a transaction inside a transaction opens a savepoint is up
|
|
155
155
|
to the driver.
|
|
156
156
|
|
|
157
|
+
## Roles
|
|
158
|
+
|
|
159
|
+
A contract built from a package with roles carries, for each role, the
|
|
160
|
+
queries the kit found it may run. A container with a `role` makes a service
|
|
161
|
+
over those queries alone, typed so: `db.admin.events.update` is not a member
|
|
162
|
+
of the service of `web`, and `db.query("admin.events.update")` is a type
|
|
163
|
+
error, and a `ForbiddenQueryError` by name at runtime. A role the contract
|
|
164
|
+
does not have is an `UnknownRoleError` at construction.
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
const web = makeBezoar(contract, {
|
|
168
|
+
executor: pg(process.env.DATABASE_URL, { role: "web" }),
|
|
169
|
+
queries,
|
|
170
|
+
role: "web",
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The service does not take the role itself: the executor does. Each driver
|
|
175
|
+
package takes a `role` and runs every statement as it. The database then
|
|
176
|
+
enforces what the role may do, under its grants and its policies, for the
|
|
177
|
+
queries of the contract and for the builder alike.
|
|
178
|
+
|
|
179
|
+
`roles` applies the grants of a build. The kit builds the list: each entry
|
|
180
|
+
has a role and its SQL.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
import { roles } from "@bbf/database/roles";
|
|
184
|
+
|
|
185
|
+
await db.roles.declare(roles); // the roles alone, before the migrations
|
|
186
|
+
await db.migrate(migrations);
|
|
187
|
+
await db.roles(roles); // the grants, after the tables exist
|
|
188
|
+
await db.seed(seeds);
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
`roles.declare` makes each role the cluster lacks, as a role that cannot
|
|
192
|
+
log in, and grants nothing. A migration that names a role, in a policy or a
|
|
193
|
+
grant of its own, needs this first. `roles` makes the roles the cluster
|
|
194
|
+
lacks, and then for each role revokes every privilege it holds on the
|
|
195
|
+
tables, sequences, routines, and schemas of the database and runs its SQL,
|
|
196
|
+
inside one transaction under an advisory lock. A grant file states the
|
|
197
|
+
whole of the privileges of its role: a grant removed from the file is gone
|
|
198
|
+
after the next run. A membership of a role in another, and a default
|
|
199
|
+
privilege, are not revoked. A grant that fails is a `RoleError` with its
|
|
200
|
+
role, and the run rolls back.
|
|
201
|
+
|
|
202
|
+
The login users are the deployment's: a role of bezoar is a group, and a
|
|
203
|
+
user joins it with `CREATE ROLE bbf_web LOGIN PASSWORD '…' IN ROLE web`.
|
|
204
|
+
The package says what `web` may do and never who `web` is. A login user
|
|
205
|
+
that is a member of its role alone cannot migrate or grant, so an app over
|
|
206
|
+
one applies neither; the owner does.
|
|
207
|
+
|
|
157
208
|
## Migrations and seeds
|
|
158
209
|
|
|
159
210
|
`migrate` applies the migrations the database lacks. The kit builds the
|
|
@@ -185,8 +236,8 @@ tracked. Write a seed so that it can run again. A seed that fails is a
|
|
|
185
236
|
## Names
|
|
186
237
|
|
|
187
238
|
The members of the service are `config`, `schema`, `query`, `first`,
|
|
188
|
-
`execute`, `build`, `transaction`, `migrate`, and `
|
|
189
|
-
cannot take one of these names,
|
|
239
|
+
`execute`, `build`, `transaction`, `migrate`, `seed`, and `roles`. A query
|
|
240
|
+
group cannot take one of these names,
|
|
190
241
|
and a name cannot be both a query and a group. Either is an error at
|
|
191
242
|
construction: `ReservedQueryError` or `AmbiguousQueryError`. `RESERVED`
|
|
192
243
|
exports the list.
|
|
@@ -198,6 +249,10 @@ exports the list.
|
|
|
198
249
|
- `InvalidRowError`: a row does not fit the columns, or the validator of a
|
|
199
250
|
built query.
|
|
200
251
|
- `QueryError`: the driver failed. `cause` is the driver's error.
|
|
252
|
+
- `UnknownRoleError`: the container names a role the contract lacks.
|
|
253
|
+
- `ForbiddenQueryError`: a service scoped to a role was asked, by name, for
|
|
254
|
+
a query the role may not run.
|
|
255
|
+
- `RoleError`: a grant failed to apply. `cause` is the driver's error.
|
|
201
256
|
- `MigrationDriftError`: the database holds a migration the list does not
|
|
202
257
|
match.
|
|
203
258
|
- `MigrationError`, `SeedError`: a migration or a seed failed. `cause` is
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bezoar/core",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.6",
|
|
4
4
|
"description": "The bezoar runtime service: run queries by name, migrate, seed",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"kysely": "^0.29.7",
|
|
25
25
|
"objectively": "^0.3.0",
|
|
26
|
-
"@bezoar/schema": "0.0.
|
|
26
|
+
"@bezoar/schema": "0.0.6"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"zod": "^4.6.5"
|