@apso/cli 0.55.0 → 0.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/import/data.d.ts +1 -0
- package/dist/commands/import/data.js +8 -3
- package/dist/commands/import/{supabase.d.ts → index.d.ts} +4 -1
- package/dist/commands/import/{supabase.js → index.js} +20 -11
- package/dist/commands/mcp/serve.js +5 -2
- package/dist/commands/schema/validate.js +5 -0
- package/dist/lib/access/cases.js +1 -2
- package/dist/lib/access/rules.json +1 -1
- package/dist/lib/api/services.js +15 -1
- package/dist/lib/base-command.d.ts +6 -0
- package/dist/lib/base-command.js +14 -0
- package/dist/lib/ddl/index.d.ts +12 -7
- package/dist/lib/ddl/index.js +50 -22
- package/dist/lib/generators/go.d.ts +18 -0
- package/dist/lib/generators/go.js +40 -18
- package/dist/lib/generators/python.js +6 -7
- package/dist/lib/generators/typescript.js +76 -14
- package/dist/lib/guards.d.ts +43 -5
- package/dist/lib/guards.js +148 -18
- package/dist/lib/import/copy-data.js +4 -2
- package/dist/lib/import/introspect.js +23 -10
- package/dist/lib/import/pg-to-apsorc.d.ts +5 -1
- package/dist/lib/import/pg-to-apsorc.js +44 -32
- package/dist/lib/import/types.d.ts +9 -4
- package/dist/lib/migrate/sandbox.js +4 -0
- package/dist/lib/templates/entities/entity.eta +2 -2
- package/dist/lib/templates/go/middleware/auth.eta +136 -7
- package/dist/lib/templates/go/services/service.eta +29 -1
- package/dist/lib/templates/guards/permission.guard.eta +15 -0
- package/dist/lib/templates/guards/scope.guard.eta +9 -5
- package/dist/lib/templates/python/auth.eta +100 -2
- package/dist/lib/templates/python/services/service.eta +19 -0
- package/dist/lib/templates/rest/controller-rest.eta +17 -2
- package/dist/lib/templates/rest/dto-rest.eta +20 -8
- package/dist/lib/templates/rest/index-module-rest.eta +5 -1
- package/dist/lib/types/constraints.d.ts +6 -1
- package/dist/lib/types/relationship.d.ts +40 -1
- package/dist/lib/types/relationship.js +34 -1
- package/dist/lib/utils/relationships/parse.js +25 -0
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +23 -14
- package/package.json +1 -1
|
@@ -162,13 +162,15 @@ const PRIMARY_KEYS_SQL = `
|
|
|
162
162
|
ORDER BY cl.relname, ord.n`;
|
|
163
163
|
const FOREIGN_KEYS_SQL = `
|
|
164
164
|
SELECT con.conname, cl.relname AS table_name, att.attname AS column_name,
|
|
165
|
-
clf.relname AS referenced_table,
|
|
166
|
-
|
|
165
|
+
clf.relname AS referenced_table, nsf.nspname AS referenced_schema,
|
|
166
|
+
attf.attname AS referenced_column,
|
|
167
|
+
con.confdeltype, con.confupdtype, con.condeferrable, con.condeferred,
|
|
167
168
|
con.convalidated, ord.n AS key_index
|
|
168
169
|
FROM pg_constraint con
|
|
169
170
|
JOIN pg_class cl ON cl.oid = con.conrelid
|
|
170
171
|
JOIN pg_namespace ns ON ns.oid = cl.relnamespace
|
|
171
172
|
JOIN pg_class clf ON clf.oid = con.confrelid
|
|
173
|
+
JOIN pg_namespace nsf ON nsf.oid = clf.relnamespace
|
|
172
174
|
JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS ord(attnum, n) ON true
|
|
173
175
|
JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = ord.attnum
|
|
174
176
|
JOIN pg_attribute attf ON attf.attrelid = con.confrelid AND attf.attnum = con.confkey[ord.n]
|
|
@@ -254,7 +256,7 @@ const SCHEMAS_SQL = `SELECT schema_name FROM information_schema.schemata`;
|
|
|
254
256
|
* the DB connection) so it can be unit-tested with fixture rows.
|
|
255
257
|
*/
|
|
256
258
|
function buildSchema(schema, raw) {
|
|
257
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o
|
|
259
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
258
260
|
// Enums
|
|
259
261
|
const enumMap = new Map();
|
|
260
262
|
for (const row of raw.enumRows) {
|
|
@@ -320,24 +322,35 @@ function buildSchema(schema, raw) {
|
|
|
320
322
|
table: row.table_name,
|
|
321
323
|
columns: [row.column_name],
|
|
322
324
|
refTable: row.referenced_table,
|
|
325
|
+
...(row.referenced_schema &&
|
|
326
|
+
row.referenced_schema !== schema && {
|
|
327
|
+
refSchema: row.referenced_schema,
|
|
328
|
+
}),
|
|
323
329
|
refColumns: [row.referenced_column],
|
|
324
330
|
confdeltype: row.confdeltype,
|
|
325
|
-
|
|
331
|
+
onUpdate: CONFDELTYPE_TO_ACTION[row.confupdtype],
|
|
332
|
+
...(row.condeferrable === true && {
|
|
333
|
+
deferrable: row.condeferred
|
|
334
|
+
? "INITIALLY DEFERRED"
|
|
335
|
+
: "INITIALLY IMMEDIATE",
|
|
336
|
+
}),
|
|
326
337
|
notValid: row.convalidated === false,
|
|
327
338
|
});
|
|
328
339
|
}
|
|
329
340
|
}
|
|
330
341
|
const fksByTable = new Map();
|
|
331
342
|
for (const fk of fkByConstraint.values()) {
|
|
332
|
-
const list = (
|
|
343
|
+
const list = (_j = fksByTable.get(fk.table)) !== null && _j !== void 0 ? _j : [];
|
|
333
344
|
list.push({
|
|
334
345
|
name: fk.name,
|
|
335
346
|
...(fk.notValid && { notValid: true }),
|
|
336
|
-
...(fk.
|
|
347
|
+
...(fk.onUpdate && fk.onUpdate !== "NO ACTION" && { onUpdate: fk.onUpdate }),
|
|
348
|
+
...(fk.deferrable && { deferrable: fk.deferrable }),
|
|
337
349
|
columns: fk.columns,
|
|
338
350
|
referencedTable: fk.refTable,
|
|
351
|
+
...(fk.refSchema && { referencedSchema: fk.refSchema }),
|
|
339
352
|
referencedColumns: fk.refColumns,
|
|
340
|
-
onDelete: (
|
|
353
|
+
onDelete: (_k = CONFDELTYPE_TO_ACTION[fk.confdeltype]) !== null && _k !== void 0 ? _k : "NO ACTION",
|
|
341
354
|
});
|
|
342
355
|
fksByTable.set(fk.table, list);
|
|
343
356
|
}
|
|
@@ -355,14 +368,14 @@ function buildSchema(schema, raw) {
|
|
|
355
368
|
}
|
|
356
369
|
const uniquesByTable = new Map();
|
|
357
370
|
for (const [name, uc] of uniqueByConstraint.entries()) {
|
|
358
|
-
const list = (
|
|
371
|
+
const list = (_l = uniquesByTable.get(uc.table)) !== null && _l !== void 0 ? _l : [];
|
|
359
372
|
list.push({ name, columns: uc.columns });
|
|
360
373
|
uniquesByTable.set(uc.table, list);
|
|
361
374
|
}
|
|
362
375
|
// Indexes (grouped by index name)
|
|
363
376
|
const indexByName = new Map();
|
|
364
377
|
for (const row of raw.indexRows) {
|
|
365
|
-
const idx = (
|
|
378
|
+
const idx = (_m = indexByName.get(row.index_name)) !== null && _m !== void 0 ? _m : {
|
|
366
379
|
table: row.table_name,
|
|
367
380
|
name: row.index_name,
|
|
368
381
|
columns: [],
|
|
@@ -385,7 +398,7 @@ function buildSchema(schema, raw) {
|
|
|
385
398
|
}
|
|
386
399
|
const indexesByTable = new Map();
|
|
387
400
|
for (const { table, ...idx } of indexByName.values()) {
|
|
388
|
-
indexesByTable.set(table, [...((
|
|
401
|
+
indexesByTable.set(table, [...((_o = indexesByTable.get(table)) !== null && _o !== void 0 ? _o : []), idx]);
|
|
389
402
|
}
|
|
390
403
|
const tables = baseTables.map((name) => {
|
|
391
404
|
var _a, _b, _c, _d, _e, _f;
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* platform derives FK column names in `getRelationshipIdField`
|
|
12
12
|
* (src/lib/utils/relationships/parse.ts) so imported relationships round-trip.
|
|
13
13
|
*/
|
|
14
|
+
import { KeyRules, OnDelete } from "../types/relationship";
|
|
14
15
|
import { Entity } from "../types/entity";
|
|
15
16
|
import { ImportReport, IntrospectedColumn, IntrospectedSchema } from "./types";
|
|
16
17
|
export interface ApsorcImportFieldOutput {
|
|
@@ -71,7 +72,10 @@ export interface ApsorcImportRelationshipOutput {
|
|
|
71
72
|
nullable?: boolean;
|
|
72
73
|
bi_directional?: boolean;
|
|
73
74
|
cascadeDelete?: boolean;
|
|
74
|
-
onDelete?:
|
|
75
|
+
onDelete?: OnDelete;
|
|
76
|
+
onUpdate?: OnDelete;
|
|
77
|
+
deferrable?: KeyRules["deferrable"];
|
|
78
|
+
joinColumnDefault?: string;
|
|
75
79
|
foreignKeyName?: string;
|
|
76
80
|
primary?: boolean;
|
|
77
81
|
validate?: boolean;
|
|
@@ -274,11 +274,12 @@ function isJoinTable(table) {
|
|
|
274
274
|
* report of everything that could not be represented losslessly.
|
|
275
275
|
*/
|
|
276
276
|
function pgToApsorc(schema) {
|
|
277
|
-
var _a, _b, _c, _d, _e;
|
|
277
|
+
var _a, _b, _c, _d, _e, _f;
|
|
278
278
|
const report = emptyReport(schema);
|
|
279
279
|
const enumLabels = new Map(schema.enums.map((e) => [e.name, e.labels]));
|
|
280
280
|
const entities = [];
|
|
281
281
|
const relationships = [];
|
|
282
|
+
const keyByTable = new Map(schema.tables.map((t) => [t.name, t.primaryKey]));
|
|
282
283
|
for (const table of schema.tables) {
|
|
283
284
|
report.tablesImported.push(table.name);
|
|
284
285
|
if (isJoinTable(table)) {
|
|
@@ -291,14 +292,27 @@ function pgToApsorc(schema) {
|
|
|
291
292
|
entity.primaryKeyName = table.primaryKeyName;
|
|
292
293
|
// Columns covered by a single-column FK are materialized by the
|
|
293
294
|
// relationship, so they must not also be emitted as scalar fields.
|
|
295
|
+
// A relationship, like a "foreignKeys" entry, references the primary key
|
|
296
|
+
// of an imported table. Any other single-column key is reported and its
|
|
297
|
+
// column stays a plain field.
|
|
294
298
|
const fkColumns = new Map();
|
|
299
|
+
const singleKeys = [];
|
|
295
300
|
for (const fk of table.foreignKeys) {
|
|
296
|
-
if (fk.columns.length
|
|
297
|
-
fkColumns.set(fk.columns[0], fk);
|
|
298
|
-
}
|
|
299
|
-
else {
|
|
301
|
+
if (fk.columns.length !== 1) {
|
|
300
302
|
report.warnings.compositeFks.push(table.name);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
const targetKey = fk.referencedSchema
|
|
306
|
+
? []
|
|
307
|
+
: keyByTable.get(fk.referencedTable);
|
|
308
|
+
if ((targetKey === null || targetKey === void 0 ? void 0 : targetKey.length) !== 1 || targetKey[0] !== fk.referencedColumns[0]) {
|
|
309
|
+
report.warnings.foreignKeysNotCarried.push(`${table.name}.${fk.name} (${fk.columns[0]} -> ${fk.referencedSchema ? `${fk.referencedSchema}.` : ""}${fk.referencedTable}.${fk.referencedColumns[0]})`);
|
|
310
|
+
continue;
|
|
301
311
|
}
|
|
312
|
+
singleKeys.push(fk);
|
|
313
|
+
// The first key on a column is the relationship's.
|
|
314
|
+
if (!fkColumns.has(fk.columns[0]))
|
|
315
|
+
fkColumns.set(fk.columns[0], fk);
|
|
302
316
|
}
|
|
303
317
|
// --- Primary key handling ---
|
|
304
318
|
const pk = table.primaryKey;
|
|
@@ -325,7 +339,7 @@ function pgToApsorc(schema) {
|
|
|
325
339
|
// key when the column is a foreign key (a table keyed by the row it
|
|
326
340
|
// extends).
|
|
327
341
|
pkAsField = true;
|
|
328
|
-
const keyIsForeignKey =
|
|
342
|
+
const keyIsForeignKey = fkColumns.has(pk[0]);
|
|
329
343
|
if (!keyIsForeignKey)
|
|
330
344
|
report.warnings.nonStandardPks.push(table.name);
|
|
331
345
|
}
|
|
@@ -535,36 +549,18 @@ function pgToApsorc(schema) {
|
|
|
535
549
|
entities.push(entity);
|
|
536
550
|
// --- Foreign keys -> ManyToOne relationships ---
|
|
537
551
|
const keyed = new Set();
|
|
538
|
-
for (const fk of
|
|
539
|
-
if (fk.columns.length !== 1)
|
|
540
|
-
continue; // composite FK handled above
|
|
552
|
+
for (const fk of singleKeys) {
|
|
541
553
|
const sourceColumn = fk.columns[0];
|
|
542
554
|
// A relationship holds one key per column. A second key on the same
|
|
543
555
|
// column (usually an exact duplicate) is kept as a constraint only.
|
|
544
556
|
if (keyed.has(sourceColumn)) {
|
|
545
|
-
const known = ["CASCADE", "SET NULL", "RESTRICT"];
|
|
546
|
-
const onDelete = known.find((rule) => rule === fk.onDelete);
|
|
547
|
-
// An entry references the target's primary key and states ON DELETE
|
|
548
|
-
// only. A key it cannot state exactly is reported, not written.
|
|
549
|
-
const target = schema.tables.find((t) => t.name === fk.referencedTable);
|
|
550
|
-
const targetKey = target === null || target === void 0 ? void 0 : target.primaryKey;
|
|
551
|
-
if ((targetKey === null || targetKey === void 0 ? void 0 : targetKey.length) !== 1 ||
|
|
552
|
-
targetKey[0] !== fk.referencedColumns[0] ||
|
|
553
|
-
(
|
|
554
|
-
// A key that is itself a foreign key belongs to a relationship.
|
|
555
|
-
target === null || target === void 0 ? void 0 : target.foreignKeys.some((k) => k.columns.includes(targetKey[0]))) ||
|
|
556
|
-
fk.onDelete === "SET DEFAULT" ||
|
|
557
|
-
fk.otherActions) {
|
|
558
|
-
report.warnings.foreignKeysNotCarried.push(`${table.name}.${fk.name} (${sourceColumn} -> ${fk.referencedTable})`);
|
|
559
|
-
continue;
|
|
560
|
-
}
|
|
561
557
|
// Postgres names every constraint, so the name is always there.
|
|
562
558
|
((_d = entity.foreignKeys) !== null && _d !== void 0 ? _d : (entity.foreignKeys = [])).push({
|
|
563
559
|
name: (_e = fk.name) !== null && _e !== void 0 ? _e : "",
|
|
564
560
|
column: sourceColumn,
|
|
565
561
|
to: fk.referencedTable,
|
|
566
|
-
...(onDelete && { onDelete }),
|
|
567
|
-
...(fk
|
|
562
|
+
...(fk.onDelete !== "NO ACTION" && { onDelete: fk.onDelete }),
|
|
563
|
+
...keyRules(fk),
|
|
568
564
|
});
|
|
569
565
|
continue;
|
|
570
566
|
}
|
|
@@ -586,15 +582,17 @@ function pgToApsorc(schema) {
|
|
|
586
582
|
rel.foreignKeyName = fk.name;
|
|
587
583
|
if (pkSet.has(sourceColumn))
|
|
588
584
|
rel.primary = true;
|
|
589
|
-
|
|
590
|
-
//
|
|
591
|
-
if (
|
|
592
|
-
|
|
585
|
+
Object.assign(rel, keyRules(fk));
|
|
586
|
+
// The relationship makes the column, so it carries the default too.
|
|
587
|
+
if ((_f = col === null || col === void 0 ? void 0 : col.default) === null || _f === void 0 ? void 0 : _f.trim().toLowerCase().startsWith("nextval("))
|
|
588
|
+
report.warnings.defaultsDropped.push(`${table.name}.${col.name}`);
|
|
589
|
+
else if (col === null || col === void 0 ? void 0 : col.default)
|
|
590
|
+
rel.joinColumnDefault = col.default;
|
|
593
591
|
if (col === null || col === void 0 ? void 0 : col.nullable)
|
|
594
592
|
rel.nullable = true;
|
|
595
593
|
if (fk.onDelete === "CASCADE")
|
|
596
594
|
rel.cascadeDelete = true;
|
|
597
|
-
else if (fk.onDelete
|
|
595
|
+
else if (fk.onDelete !== "NO ACTION")
|
|
598
596
|
rel.onDelete = fk.onDelete;
|
|
599
597
|
relationships.push(rel);
|
|
600
598
|
}
|
|
@@ -612,6 +610,20 @@ function pgToApsorc(schema) {
|
|
|
612
610
|
};
|
|
613
611
|
}
|
|
614
612
|
exports.pgToApsorc = pgToApsorc;
|
|
613
|
+
/**
|
|
614
|
+
* A source key's ON UPDATE rule, DEFERRABLE setting and NOT VALID mark, as
|
|
615
|
+
* .apsorc states them on a relationship or a "foreignKeys" entry.
|
|
616
|
+
* Migrations keep a key NOT VALID. A database built by TypeORM's own schema
|
|
617
|
+
* sync has it validated, which only matters on an empty one.
|
|
618
|
+
*
|
|
619
|
+
* @param {IntrospectedFk} fk - The key as read from the source database.
|
|
620
|
+
* @returns {KeyRules} Only the settings that differ from the defaults.
|
|
621
|
+
*/
|
|
622
|
+
const keyRules = (fk) => ({
|
|
623
|
+
...(fk.onUpdate && { onUpdate: fk.onUpdate }),
|
|
624
|
+
...(fk.deferrable && { deferrable: fk.deferrable }),
|
|
625
|
+
...(fk.notValid && { validate: false }),
|
|
626
|
+
});
|
|
615
627
|
/**
|
|
616
628
|
* Invariant guard: every emitted field type must be a recognized `.apsorc`
|
|
617
629
|
* column type, so code generation never silently falls back to varchar.
|
|
@@ -36,11 +36,15 @@ export interface IntrospectedFk {
|
|
|
36
36
|
notValid?: boolean;
|
|
37
37
|
/** The constraint's name in the source database. */
|
|
38
38
|
name?: string;
|
|
39
|
-
/** The key
|
|
40
|
-
|
|
39
|
+
/** The key's ON UPDATE rule, when it is not NO ACTION. */
|
|
40
|
+
onUpdate?: OnDeleteAction;
|
|
41
|
+
/** Set when the key is DEFERRABLE: when it is checked. */
|
|
42
|
+
deferrable?: "INITIALLY IMMEDIATE" | "INITIALLY DEFERRED";
|
|
41
43
|
/** Local column(s) participating in the FK. */
|
|
42
44
|
columns: string[];
|
|
43
45
|
referencedTable: string;
|
|
46
|
+
/** The referenced table's schema, when it is not the imported one. */
|
|
47
|
+
referencedSchema?: string;
|
|
44
48
|
referencedColumns: string[];
|
|
45
49
|
onDelete: OnDeleteAction;
|
|
46
50
|
}
|
|
@@ -120,8 +124,9 @@ export interface ImportReport {
|
|
|
120
124
|
/** "table.column" arrays whose element type is unknown, imported as text[]. */
|
|
121
125
|
arraysLossy: string[];
|
|
122
126
|
/**
|
|
123
|
-
* "table.constraint (column -> target)" for a
|
|
124
|
-
*
|
|
127
|
+
* "table.constraint (column -> target.column)" for a foreign key that
|
|
128
|
+
* does not reference the primary key of an imported table. The column is
|
|
129
|
+
* kept as a plain field and the key is left out of .apsorc.
|
|
125
130
|
*/
|
|
126
131
|
foreignKeysNotCarried: string[];
|
|
127
132
|
/** "table.constraint" for CHECK constraints marked NOT VALID in the source. */
|
|
@@ -157,6 +157,10 @@ function buildEntityClasses(entities, relationshipMap = {}) {
|
|
|
157
157
|
if ((0, relationship_1.onDeleteOf)(relationship)) {
|
|
158
158
|
relationOptions.onDelete = (0, relationship_1.onDeleteOf)(relationship);
|
|
159
159
|
}
|
|
160
|
+
if (relationship.onUpdate)
|
|
161
|
+
relationOptions.onUpdate = relationship.onUpdate;
|
|
162
|
+
if (relationship.deferrable)
|
|
163
|
+
relationOptions.deferrable = relationship.deferrable;
|
|
160
164
|
if (relationship.type === "ManyToOne") {
|
|
161
165
|
if (relationship.index) {
|
|
162
166
|
typeorm.Index()(EntityClass.prototype, relationship.relationshipName);
|
|
@@ -62,7 +62,7 @@ const { CREATE, UPDATE } = CrudValidationGroups;
|
|
|
62
62
|
@Check(<% if (check.name) { %><%~ JSON.stringify(check.name) %>, <% } %><%~ JSON.stringify(check.expression) %>)
|
|
63
63
|
<% }) %>
|
|
64
64
|
<% it.foreignKeys.forEach((key) => { %>
|
|
65
|
-
@ForeignKey(() => <%= key.target %>, [<%~ JSON.stringify(key.column) %>], [<%~ JSON.stringify(key.targetColumn) %>], {
|
|
65
|
+
@ForeignKey(() => <%= key.target %>, [<%~ JSON.stringify(key.column) %>], [<%~ JSON.stringify(key.targetColumn) %>], { <%~ key.options %> })
|
|
66
66
|
<% }) %>
|
|
67
67
|
<% it.uniques.forEach((unique) => { %>
|
|
68
68
|
@Unique(<% if (unique.name) {%> "<%= unique.name %>", <%} %>[<%~ unique.fields.map((field) => `"${field}"`).join(', ') %>])
|
|
@@ -136,7 +136,7 @@ const columnCode = includeFile(`./entities/entity-col-${field.type}`, { field })
|
|
|
136
136
|
<% if (assoc.index) { %>
|
|
137
137
|
@Index()
|
|
138
138
|
<% } %>
|
|
139
|
-
@ManyToOne(() => <%= assoc.name %><% if (assoc.biDirectional) { %>, <%= assoc.camelCasedName %> => <%= assoc.camelCasedName %>.<%= assoc.inverseSidePropertyName %><% } %><% if (assoc.
|
|
139
|
+
@ManyToOne(() => <%= assoc.name %><% if (assoc.biDirectional) { %>, <%= assoc.camelCasedName %> => <%= assoc.camelCasedName %>.<%= assoc.inverseSidePropertyName %><% } %><% if (assoc.keyRules) { %>, { <%~ assoc.keyRules %> }<% } %>)
|
|
140
140
|
@JoinColumn({ name: '<%= assoc.joinColumnName || assoc.camelCasedId %>'<% if (assoc.foreignKeyName) { %>, foreignKeyConstraintName: '<%= assoc.foreignKeyName %>'<% } %> })
|
|
141
141
|
<%= assoc.relationshipName %>: <%= assoc.name %>;
|
|
142
142
|
|
|
@@ -600,6 +600,25 @@ type relationScope struct {
|
|
|
600
600
|
Table string
|
|
601
601
|
Tenant map[string]string
|
|
602
602
|
Relations map[string]relationHop
|
|
603
|
+
Nested []nestedScope
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// nestedScope is one scopeBy path through a parent (task.workspaceId): the
|
|
607
|
+
// entity's foreign key column, each parent on the way to the tenant (nearest
|
|
608
|
+
// first), and the tenant column on the last parent with the caller value it
|
|
609
|
+
// must equal.
|
|
610
|
+
type nestedScope struct {
|
|
611
|
+
Column string
|
|
612
|
+
Parents []nestedParent
|
|
613
|
+
Tenant string
|
|
614
|
+
Key string
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// nestedParent is a parent's table and its foreign key column to the next
|
|
618
|
+
// parent (empty on the last).
|
|
619
|
+
type nestedParent struct {
|
|
620
|
+
Table string
|
|
621
|
+
Column string
|
|
603
622
|
}
|
|
604
623
|
|
|
605
624
|
type relationHop struct {
|
|
@@ -624,6 +643,20 @@ var relationScopes = map[string]relationScope{
|
|
|
624
643
|
<%~ JSON.stringify(relation) %>: {Entity: <%~ JSON.stringify(hop[0]) %>, SameTenant: <%= hop[1] %>},
|
|
625
644
|
<% }) %>
|
|
626
645
|
},
|
|
646
|
+
Nested: []nestedScope{
|
|
647
|
+
<% for (const n of it.nestedScopes[name] ?? []) { %>
|
|
648
|
+
{
|
|
649
|
+
Column: <%~ JSON.stringify(n.column) %>,
|
|
650
|
+
Tenant: <%~ JSON.stringify(n.tenantColumn) %>,
|
|
651
|
+
Key: <%~ JSON.stringify(n.source) %>,
|
|
652
|
+
Parents: []nestedParent{
|
|
653
|
+
<% n.parents.forEach((p) => { %>
|
|
654
|
+
{Table: <%~ JSON.stringify(p.table) %>, Column: <%~ JSON.stringify(p.column) %>},
|
|
655
|
+
<% }) %>
|
|
656
|
+
},
|
|
657
|
+
},
|
|
658
|
+
<% } %>
|
|
659
|
+
},
|
|
627
660
|
},
|
|
628
661
|
<% }) %>
|
|
629
662
|
}
|
|
@@ -646,22 +679,77 @@ func skipsScope(a *AuthContext, e relationScope) bool {
|
|
|
646
679
|
func tenantWhere(a *AuthContext, e relationScope) (where string, args []interface{}, ok bool) {
|
|
647
680
|
var parts []string
|
|
648
681
|
for column, key := range e.Tenant {
|
|
649
|
-
v := a
|
|
650
|
-
switch key {
|
|
651
|
-
case "userId":
|
|
652
|
-
v = a.UserID
|
|
653
|
-
case "email":
|
|
654
|
-
v = a.Email
|
|
655
|
-
}
|
|
682
|
+
v := callerValue(a, key)
|
|
656
683
|
if v == "" {
|
|
657
684
|
return "", nil, false
|
|
658
685
|
}
|
|
659
686
|
parts = append(parts, `CAST("`+column+`" AS TEXT) = ?`)
|
|
660
687
|
args = append(args, v)
|
|
661
688
|
}
|
|
689
|
+
nested, nestedArgs, ok := nestedWhere(a, e, "")
|
|
690
|
+
if !ok {
|
|
691
|
+
return "", nil, false
|
|
692
|
+
}
|
|
693
|
+
if nested != "" {
|
|
694
|
+
parts = append(parts, nested)
|
|
695
|
+
args = append(args, nestedArgs...)
|
|
696
|
+
}
|
|
662
697
|
return strings.Join(parts, " AND "), args, true
|
|
663
698
|
}
|
|
664
699
|
|
|
700
|
+
// callerValue is the caller's value for a scopeBy key: its user id, its email,
|
|
701
|
+
// or (any other name) its tenant.
|
|
702
|
+
func callerValue(a *AuthContext, key string) string {
|
|
703
|
+
switch key {
|
|
704
|
+
case "userId":
|
|
705
|
+
return a.UserID
|
|
706
|
+
case "email":
|
|
707
|
+
return a.Email
|
|
708
|
+
}
|
|
709
|
+
return a.WorkspaceID
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// parentCond is the condition that keeps the rows of n.Parents[i] to the
|
|
713
|
+
// caller's tenant: the tenant column on the last parent, reached through each
|
|
714
|
+
// parent's foreign key to the next. It takes one argument, the caller's value.
|
|
715
|
+
func parentCond(n nestedScope, i int) string {
|
|
716
|
+
last := n.Parents[len(n.Parents)-1].Table
|
|
717
|
+
cond := `CAST("` + last + `"."` + n.Tenant + `" AS TEXT) = ?`
|
|
718
|
+
for j := len(n.Parents) - 1; j > i; j-- {
|
|
719
|
+
child, parent := n.Parents[j-1], n.Parents[j].Table
|
|
720
|
+
cond = `"` + child.Table + `"."` + child.Column + `" IN (SELECT "` + parent + `"."id" FROM "` + parent + `" WHERE ` + cond + `)`
|
|
721
|
+
}
|
|
722
|
+
return cond
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// nestedWhere is the SQL condition, with its arguments, that keeps rows of e
|
|
726
|
+
// to the caller's tenant through each scopeBy path that runs through a parent
|
|
727
|
+
// (task.workspaceId): the foreign key must name a parent in that tenant.
|
|
728
|
+
// table, when set, qualifies the foreign key column. ok is false when the
|
|
729
|
+
// caller has no value for one of the paths.
|
|
730
|
+
func nestedWhere(a *AuthContext, e relationScope, table string) (where string, args []interface{}, ok bool) {
|
|
731
|
+
var parts []string
|
|
732
|
+
for _, n := range e.Nested {
|
|
733
|
+
v := callerValue(a, n.Key)
|
|
734
|
+
if v == "" {
|
|
735
|
+
return "", nil, false
|
|
736
|
+
}
|
|
737
|
+
column := `"` + n.Column + `"`
|
|
738
|
+
if table != "" {
|
|
739
|
+
column = `"` + table + `".` + column
|
|
740
|
+
}
|
|
741
|
+
parent := n.Parents[0].Table
|
|
742
|
+
parts = append(parts, column+` IN (SELECT "`+parent+`"."id" FROM "`+parent+`" WHERE `+parentCond(n, 0)+`)`)
|
|
743
|
+
args = append(args, v)
|
|
744
|
+
}
|
|
745
|
+
return strings.Join(parts, " AND "), args, true
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// NestedWhere is nestedWhere for a service's own queries on entity.
|
|
749
|
+
func NestedWhere(a *AuthContext, entity, table string) (string, []interface{}, bool) {
|
|
750
|
+
return nestedWhere(a, relationScopes[entity], table)
|
|
751
|
+
}
|
|
752
|
+
|
|
665
753
|
// RelationLoad is one relation to preload: its path as the request names it
|
|
666
754
|
// (author, author.posts) and the conditions its rows must meet, as arguments
|
|
667
755
|
// for gorm's Preload.
|
|
@@ -725,6 +813,47 @@ func RelationLoads(ctx context.Context, root, path string) (loads []RelationLoad
|
|
|
725
813
|
// entity that the caller cannot read. Handlers answer it with 403.
|
|
726
814
|
var ErrReference = errors.New("you do not have access to a row this request references")
|
|
727
815
|
|
|
816
|
+
// CheckParents checks, on a write to entity, each foreign key its scopeBy runs
|
|
817
|
+
// through (task.workspaceId): the parent it names must be in the caller's
|
|
818
|
+
// tenant, or the result is ErrReference. sent maps the foreign key column to
|
|
819
|
+
// the value in the body; a pointer may be given, and nil or zero means not
|
|
820
|
+
// sent. A service caller or a role that skips the entity's scope is not limited.
|
|
821
|
+
func CheckParents(ctx context.Context, db *gorm.DB, entity string, sent map[string]interface{}) error {
|
|
822
|
+
a, _ := FromContext(ctx)
|
|
823
|
+
if a == nil {
|
|
824
|
+
a = &AuthContext{}
|
|
825
|
+
}
|
|
826
|
+
e := relationScopes[entity]
|
|
827
|
+
if a.ServiceID != "" || skipsScope(a, e) {
|
|
828
|
+
return nil
|
|
829
|
+
}
|
|
830
|
+
for _, n := range e.Nested {
|
|
831
|
+
rv := reflect.ValueOf(sent[n.Column])
|
|
832
|
+
for rv.Kind() == reflect.Ptr && !rv.IsNil() {
|
|
833
|
+
rv = rv.Elem()
|
|
834
|
+
}
|
|
835
|
+
if !rv.IsValid() || rv.Kind() == reflect.Ptr || rv.IsZero() {
|
|
836
|
+
continue
|
|
837
|
+
}
|
|
838
|
+
v := callerValue(a, n.Key)
|
|
839
|
+
if v == "" {
|
|
840
|
+
return ErrReference
|
|
841
|
+
}
|
|
842
|
+
parent := n.Parents[0].Table
|
|
843
|
+
var found int64
|
|
844
|
+
if err := db.WithContext(ctx).Table(parent).
|
|
845
|
+
Where(`"`+parent+`"."id" = ?`, rv.Interface()).
|
|
846
|
+
Where(parentCond(n, 0), v).
|
|
847
|
+
Count(&found).Error; err != nil {
|
|
848
|
+
return err
|
|
849
|
+
}
|
|
850
|
+
if found == 0 {
|
|
851
|
+
return ErrReference
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
return nil
|
|
855
|
+
}
|
|
856
|
+
|
|
728
857
|
// CheckReferences is the one place that checks the foreign keys of a write
|
|
729
858
|
// (R8). references maps a tenant-scoped entity to the ids a body names in
|
|
730
859
|
// foreign keys to it; an id may be a pointer, and nil or zero means not sent.
|
|
@@ -79,6 +79,14 @@ func (s *<%= it.entityName %>Service) scoped(ctx context.Context, q *gorm.DB, op
|
|
|
79
79
|
// Compared as text: token claims are strings, the column may be a number or uuid.
|
|
80
80
|
q = q.Where(`CAST("`+table+`"."`+col+`" AS TEXT) = ?`, v)
|
|
81
81
|
}
|
|
82
|
+
<% if (it.scope.nested.length > 0) { %>
|
|
83
|
+
// A path through a parent (task.workspaceId): the parent must be in the caller's tenant.
|
|
84
|
+
nested, nestedArgs, hasTenant := middleware.NestedWhere(a, <%~ JSON.stringify(it.entityName) %>, table)
|
|
85
|
+
if !hasTenant {
|
|
86
|
+
return nil, nil, ErrForbidden
|
|
87
|
+
}
|
|
88
|
+
q = q.Where(nested, nestedArgs...)
|
|
89
|
+
<% } %>
|
|
82
90
|
return q, values, nil
|
|
83
91
|
}
|
|
84
92
|
<% } %>
|
|
@@ -199,7 +207,7 @@ func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%=
|
|
|
199
207
|
<% if (it.scope) { %>
|
|
200
208
|
|
|
201
209
|
// The caller's tenant, never one from the body (.apsorc scopeBy).
|
|
202
|
-
_, scopeVals
|
|
210
|
+
_, <%= it.scope.fields.length > 0 ? 'scopeVals' : '_' %>, scopeErr := s.scoped(ctx, s.db, "create")
|
|
203
211
|
if scopeErr != nil {
|
|
204
212
|
return nil, scopeErr
|
|
205
213
|
}
|
|
@@ -210,6 +218,16 @@ func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%=
|
|
|
210
218
|
}
|
|
211
219
|
}
|
|
212
220
|
<% }) %>
|
|
221
|
+
<% if (it.scope.nested.length > 0) { %>
|
|
222
|
+
// A parent this entity is scoped through must be in the caller's tenant.
|
|
223
|
+
if err := middleware.CheckParents(ctx, s.db, <%~ JSON.stringify(it.entityName) %>, map[string]interface{}{
|
|
224
|
+
<% it.scope.nested.forEach((n) => { %>
|
|
225
|
+
<%~ JSON.stringify(n.column) %>: item.<%= n.goField %>,
|
|
226
|
+
<% }) %>
|
|
227
|
+
}); err != nil {
|
|
228
|
+
return nil, err
|
|
229
|
+
}
|
|
230
|
+
<% } %>
|
|
213
231
|
<% } %>
|
|
214
232
|
<% if (it.references.length) { %>
|
|
215
233
|
|
|
@@ -281,6 +299,16 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
281
299
|
for col := range scopeVals {
|
|
282
300
|
delete(updates, col)
|
|
283
301
|
}
|
|
302
|
+
<% if (it.scope.nested.length > 0) { %>
|
|
303
|
+
// A new parent must be in the caller's tenant.
|
|
304
|
+
if err := middleware.CheckParents(ctx, s.db, <%~ JSON.stringify(it.entityName) %>, map[string]interface{}{
|
|
305
|
+
<% it.scope.nested.forEach((n) => { %>
|
|
306
|
+
<%~ JSON.stringify(n.column) %>: updates[<%~ JSON.stringify(n.column) %>],
|
|
307
|
+
<% }) %>
|
|
308
|
+
}); err != nil {
|
|
309
|
+
return nil, err
|
|
310
|
+
}
|
|
311
|
+
<% } %>
|
|
284
312
|
<% } %>
|
|
285
313
|
<% if (it.references.length) { %>
|
|
286
314
|
if err := middleware.CheckReferences(ctx, s.db, map[string][]interface{}{
|
|
@@ -45,6 +45,21 @@ export const PERMISSION_KEY = 'apsoPermission';
|
|
|
45
45
|
export const Permission = (permission: string, ...roles: string[]) =>
|
|
46
46
|
SetMetadata(PERMISSION_KEY, { permission, roles });
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Adds a role rule to each named handler's OpenAPI description. Goes above
|
|
50
|
+
* @Crud on a controller: @Crud writes its own operation text, and a class
|
|
51
|
+
* decorator listed above it runs after it.
|
|
52
|
+
*/
|
|
53
|
+
export const DescribeRoles = (rules: Record<string, string>): ClassDecorator => (target: any) => {
|
|
54
|
+
for (const [handler, rule] of Object.entries(rules)) {
|
|
55
|
+
const fn = target.prototype[handler];
|
|
56
|
+
if (typeof fn !== 'function') continue;
|
|
57
|
+
const op = Reflect.getMetadata('swagger/apiOperation', fn) ?? {};
|
|
58
|
+
const description = [rule, op.description].filter(Boolean).join('\n\n');
|
|
59
|
+
Reflect.defineMetadata('swagger/apiOperation', { ...op, description }, fn);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
48
63
|
const OPERATIONS: Record<string, Operation> = {
|
|
49
64
|
GET: 'read',
|
|
50
65
|
HEAD: 'read',
|
|
@@ -283,11 +283,15 @@ export class ScopeGuard implements CanActivate {
|
|
|
283
283
|
const relations: string[] = [];
|
|
284
284
|
for (const scope of scopeConfig.scopes) {
|
|
285
285
|
if (!scope.direct && scope.path) {
|
|
286
|
-
//
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
286
|
+
// Every relation on the way to the tenant column:
|
|
287
|
+
// 'task.project.workspaceId' -> 'task', 'task.project'
|
|
288
|
+
const hops = scope.path.split('.').slice(0, -1);
|
|
289
|
+
hops.forEach((_hop, i) => {
|
|
290
|
+
const relationName = hops.slice(0, i + 1).join('.');
|
|
291
|
+
if (!relations.includes(relationName)) {
|
|
292
|
+
relations.push(relationName);
|
|
293
|
+
}
|
|
294
|
+
});
|
|
291
295
|
}
|
|
292
296
|
}
|
|
293
297
|
|