@apso/cli 0.48.0 → 0.49.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/README.md +28 -1
- package/dist/commands/dev.d.ts +2 -0
- package/dist/commands/dev.js +20 -3
- package/dist/commands/generate.js +49 -13
- package/dist/commands/mcp/serve.js +24 -41
- package/dist/commands/schema/diff.js +3 -4
- package/dist/commands/schema/pull.js +13 -11
- package/dist/commands/schema/push.js +6 -5
- package/dist/commands/schema/validate.d.ts +10 -0
- package/dist/commands/schema/validate.js +54 -0
- package/dist/commands/test/access.d.ts +11 -0
- package/dist/commands/test/access.js +65 -0
- package/dist/lib/access/cases.d.ts +120 -0
- package/dist/lib/access/cases.js +1163 -0
- package/dist/lib/access/index.d.ts +4 -0
- package/dist/lib/access/index.js +7 -0
- package/dist/lib/access/report.d.ts +75 -0
- package/dist/lib/access/report.js +118 -0
- package/dist/lib/access/rules.json +207 -0
- package/dist/lib/access/run.d.ts +38 -0
- package/dist/lib/access/run.js +111 -0
- package/dist/lib/access/tokens.d.ts +46 -0
- package/dist/lib/access/tokens.js +139 -0
- package/dist/lib/api/services.d.ts +10 -7
- package/dist/lib/api/services.js +19 -32
- package/dist/lib/apsorc-parser.d.ts +1 -1
- package/dist/lib/apsorc-parser.js +2 -0
- package/dist/lib/deploy/server-push.js +3 -1
- package/dist/lib/generators/go.d.ts +13 -1
- package/dist/lib/generators/go.js +144 -33
- package/dist/lib/generators/python.d.ts +3 -3
- package/dist/lib/generators/python.js +48 -24
- package/dist/lib/generators/typescript.d.ts +3 -5
- package/dist/lib/generators/typescript.js +78 -64
- package/dist/lib/guards.d.ts +111 -13
- package/dist/lib/guards.js +287 -23
- package/dist/lib/templates/go/handlers/handler.eta +8 -8
- package/dist/lib/templates/go/handlers/scope.eta +3 -2
- package/dist/lib/templates/go/index-module.eta +8 -5
- package/dist/lib/templates/go/mcp.eta +307 -0
- package/dist/lib/templates/go/middleware/auth.eta +587 -166
- package/dist/lib/templates/go/middleware/permission.eta +174 -0
- package/dist/lib/templates/go/services/service.eta +37 -16
- package/dist/lib/templates/go/utils/query.eta +37 -2
- package/dist/lib/templates/guards/guards.module.eta +37 -29
- package/dist/lib/templates/guards/index.eta +4 -0
- package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
- package/dist/lib/templates/guards/key.guard.eta +280 -0
- package/dist/lib/templates/guards/permission.guard.eta +168 -0
- package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
- package/dist/lib/templates/guards/scope.guard.eta +189 -41
- package/dist/lib/templates/python/auth.eta +354 -95
- package/dist/lib/templates/python/index-module.eta +7 -7
- package/dist/lib/templates/python/mcp.eta +284 -0
- package/dist/lib/templates/python/models/model.eta +6 -5
- package/dist/lib/templates/python/permissions.eta +121 -0
- package/dist/lib/templates/python/routers/router.eta +39 -1
- package/dist/lib/templates/python/schemas/schema.eta +18 -5
- package/dist/lib/templates/python/services/service.eta +38 -15
- package/dist/lib/templates/python/utils/query.eta +52 -25
- package/dist/lib/templates/rest/controller-rest.eta +43 -23
- package/dist/lib/templates/rest/index-module-rest.eta +0 -4
- package/dist/lib/templates/rest/service-rest.eta +3 -44
- package/dist/lib/types/auth.d.ts +84 -80
- package/dist/lib/types/auth.js +77 -60
- package/dist/lib/types/entity.d.ts +17 -9
- package/dist/lib/types/entity.js +3 -0
- package/dist/lib/types/index.d.ts +2 -2
- package/dist/lib/types/index.js +6 -5
- package/dist/lib/utils/crud-deps.d.ts +77 -6
- package/dist/lib/utils/crud-deps.js +197 -14
- package/dist/lib/utils/schema-convert.d.ts +20 -43
- package/dist/lib/utils/schema-convert.js +28 -78
- package/dist/lib/utils/template.d.ts +11 -0
- package/dist/lib/utils/template.js +36 -1
- package/dist/lib/verify/index.d.ts +6 -1
- package/dist/lib/verify/index.js +30 -13
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +36 -1
- package/package.json +1 -1
- package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
- package/dist/lib/templates/guards/auth.guard.eta +0 -233
package/dist/lib/guards.js
CHANGED
|
@@ -1,17 +1,32 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.nestedScopeEntities = exports.entityScope = exports.
|
|
3
|
+
exports.scopedReferences = exports.tenantClaimWarnings = exports.nestedScopeEntities = exports.relationScopes = exports.entityScope = exports.getPermissionConfig = exports.hasPermissions = exports.mcpToolNames = exports.authEntityRoutes = exports.hidesRelation = exports.authEntityNames = exports.mcpOperations = exports.hasScopedEntities = exports.getScopedEntities = exports.toRouteName = exports.removedScopeOptionErrors = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
|
+
const types_1 = require("./types");
|
|
5
6
|
const pluralize_1 = tslib_1.__importDefault(require("pluralize"));
|
|
7
|
+
const casing_1 = require("./utils/casing");
|
|
6
8
|
const parse_1 = require("./utils/relationships/parse");
|
|
7
9
|
/**
|
|
8
10
|
* Default scope options when not specified
|
|
9
11
|
*/
|
|
10
12
|
const DEFAULT_SCOPE_OPTIONS = {
|
|
11
|
-
injectOnCreate: true,
|
|
12
|
-
enforceOn: ["find", "get", "create", "update", "delete"],
|
|
13
13
|
bypassRoles: [],
|
|
14
14
|
};
|
|
15
|
+
/** scopeOptions keys that no longer exist, and what `apso generate` says about each. */
|
|
16
|
+
const REMOVED_SCOPE_OPTIONS = {
|
|
17
|
+
injectOnCreate: "The tenant on a create always comes from the caller, never from the request body. A service caller (API key) can set any tenant.",
|
|
18
|
+
enforceOn: "Every read and write of a tenant-scoped entity by a user caller is limited to the caller's tenant, on every operation. A caller that works across tenants is a service caller (API key).",
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* One error per removed scopeOptions key an entity still sets. `apso generate`
|
|
22
|
+
* and `apso schema validate` both refuse it.
|
|
23
|
+
*/
|
|
24
|
+
function removedScopeOptionErrors(entities) {
|
|
25
|
+
return entities.flatMap((entity) => Object.entries(REMOVED_SCOPE_OPTIONS)
|
|
26
|
+
.filter(([key]) => { var _a; return ((_a = entity.scopeOptions) === null || _a === void 0 ? void 0 : _a[key]) !== undefined; })
|
|
27
|
+
.map(([key, why]) => `${entity.name}.scopeOptions.${key} is no longer an option; remove it. ${why}`));
|
|
28
|
+
}
|
|
29
|
+
exports.removedScopeOptionErrors = removedScopeOptionErrors;
|
|
15
30
|
/**
|
|
16
31
|
* Parses scopeBy configuration and returns structured scope fields.
|
|
17
32
|
*/
|
|
@@ -32,6 +47,7 @@ function parseScopeBy(scopeBy) {
|
|
|
32
47
|
function toRouteName(entityName) {
|
|
33
48
|
return (0, pluralize_1.default)(entityName).toLowerCase();
|
|
34
49
|
}
|
|
50
|
+
exports.toRouteName = toRouteName;
|
|
35
51
|
function toRepoName(entityName) {
|
|
36
52
|
const camelCase = entityName.charAt(0).toLowerCase() + entityName.slice(1);
|
|
37
53
|
return `${camelCase}Repository`;
|
|
@@ -71,8 +87,6 @@ function getScopedEntities(entities, relationshipMap) {
|
|
|
71
87
|
scopes: relationshipMap
|
|
72
88
|
? scopes.map((s) => resolveNestedScope(entity.name, s, relationshipMap))
|
|
73
89
|
: scopes,
|
|
74
|
-
injectOnCreate: options.injectOnCreate,
|
|
75
|
-
enforceOn: options.enforceOn,
|
|
76
90
|
bypassRoles: options.bypassRoles,
|
|
77
91
|
};
|
|
78
92
|
});
|
|
@@ -86,24 +100,187 @@ function hasScopedEntities(entities) {
|
|
|
86
100
|
}
|
|
87
101
|
exports.hasScopedEntities = hasScopedEntities;
|
|
88
102
|
/**
|
|
89
|
-
*
|
|
90
|
-
*
|
|
103
|
+
* Operations an entity exposes as MCP tools, from its `mcp` setting.
|
|
104
|
+
* Empty when the entity has not opted in.
|
|
91
105
|
*/
|
|
92
|
-
function
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if (
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
106
|
+
function mcpOperations(entity) {
|
|
107
|
+
if (!entity.mcp)
|
|
108
|
+
return [];
|
|
109
|
+
if (entity.mcp === true)
|
|
110
|
+
return [...types_1.PERMISSION_OPERATIONS];
|
|
111
|
+
const bad = !Array.isArray(entity.mcp) ||
|
|
112
|
+
entity.mcp.find((op) => !types_1.PERMISSION_OPERATIONS.includes(op));
|
|
113
|
+
if (bad)
|
|
114
|
+
throw new Error(`${entity.name}.mcp must be true or a list of ${types_1.PERMISSION_OPERATIONS.join(", ")}`);
|
|
115
|
+
return [...new Set(entity.mcp)];
|
|
116
|
+
}
|
|
117
|
+
exports.mcpOperations = mcpOperations;
|
|
118
|
+
/**
|
|
119
|
+
* Better Auth's tables by entity name (any case) and the fields that mark
|
|
120
|
+
* them, so a domain entity that shares a name (a billing Account) is not
|
|
121
|
+
* taken for one. The OAuth provider's tables have names no domain entity
|
|
122
|
+
* would use, so the name is enough.
|
|
123
|
+
*/
|
|
124
|
+
const BETTER_AUTH_TABLES = {
|
|
125
|
+
session: ["token"],
|
|
126
|
+
account: ["providerId", "accountId"],
|
|
127
|
+
verification: ["identifier", "value"],
|
|
128
|
+
// Organization plugin: who belongs to which tenant, with which role.
|
|
129
|
+
member: ["role"],
|
|
130
|
+
invitation: ["email", "status"],
|
|
131
|
+
// JWT plugin: the signing keys.
|
|
132
|
+
jwks: ["publicKey", "privateKey"],
|
|
133
|
+
oauthclient: [],
|
|
134
|
+
oauthresource: [],
|
|
135
|
+
oauthclientresource: [],
|
|
136
|
+
oauthrefreshtoken: [],
|
|
137
|
+
oauthaccesstoken: [],
|
|
138
|
+
oauthconsent: [],
|
|
139
|
+
oauthclientassertion: [],
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* The entities that store Better Auth's own rows when the better-auth
|
|
143
|
+
* provider is listed: the auth block's session, user and membership
|
|
144
|
+
* (accountUserEntity) entities, and Better Auth's other tables (account,
|
|
145
|
+
* verification, the organization plugin's member and invitation, the JWT
|
|
146
|
+
* plugin's jwks, the OAuth provider's tables). Only a service caller (API
|
|
147
|
+
* key) reaches them: the key guard refuses a signed-in user on their routes,
|
|
148
|
+
* no other entity's controller joins onto them, and they cannot be MCP tools.
|
|
149
|
+
*/
|
|
150
|
+
function authEntityNames(entities, auth) {
|
|
151
|
+
const betterAuth = (0, types_1.authProviders)(auth).find((a) => (0, types_1.isDbSessionAuth)(a));
|
|
152
|
+
if (!betterAuth)
|
|
153
|
+
return [];
|
|
154
|
+
const { sessionEntity, userEntity, accountUserEntity } = {
|
|
155
|
+
...types_1.DB_SESSION_AUTH_DEFAULTS,
|
|
156
|
+
...betterAuth,
|
|
157
|
+
};
|
|
158
|
+
const named = new Set([sessionEntity, userEntity, accountUserEntity]);
|
|
159
|
+
const found = entities.filter((entity) => {
|
|
160
|
+
var _a, _b;
|
|
161
|
+
const fields = new Set(((_a = entity.fields) !== null && _a !== void 0 ? _a : []).map((f) => f.name));
|
|
162
|
+
return (named.has(entity.name) ||
|
|
163
|
+
((_b = BETTER_AUTH_TABLES[entity.name.toLowerCase()]) === null || _b === void 0 ? void 0 : _b.every((f) => fields.has(f))));
|
|
164
|
+
});
|
|
165
|
+
const tool = found.find((entity) => mcpOperations(entity).length > 0);
|
|
166
|
+
if (tool)
|
|
167
|
+
throw new Error(`${tool.name}.mcp: ${tool.name} is an auth entity, which only a service caller (API key) may call, so it cannot be exposed as MCP tools`);
|
|
168
|
+
return found.map((entity) => entity.name);
|
|
169
|
+
}
|
|
170
|
+
exports.authEntityNames = authEntityNames;
|
|
171
|
+
/**
|
|
172
|
+
* True for a relation that a response must not carry: one from another entity
|
|
173
|
+
* onto an auth entity. Auth entities keep the relations between themselves.
|
|
174
|
+
*/
|
|
175
|
+
function hidesRelation(entityName, relatedName, entities, auth) {
|
|
176
|
+
const names = authEntityNames(entities, auth);
|
|
177
|
+
return !names.includes(entityName) && names.includes(relatedName);
|
|
178
|
+
}
|
|
179
|
+
exports.hidesRelation = hidesRelation;
|
|
180
|
+
/** The auth entities' route names (sessions), for the key guard. */
|
|
181
|
+
const authEntityRoutes = (entities, auth) => authEntityNames(entities, auth).map((name) => toRouteName(name));
|
|
182
|
+
exports.authEntityRoutes = authEntityRoutes;
|
|
183
|
+
/**
|
|
184
|
+
* An entity's MCP operations and the names its tools get, the same in every
|
|
185
|
+
* language: list_line_items, get_line_item, create_line_item and so on.
|
|
186
|
+
*/
|
|
187
|
+
function mcpToolNames(entity, auth) {
|
|
188
|
+
const mcp = mcpOperations(entity);
|
|
189
|
+
if (mcp.length > 0 && !auth)
|
|
190
|
+
throw new Error(`${entity.name}.mcp needs an auth block in .apsorc: MCP tools act as the signed-in caller`);
|
|
100
191
|
return {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
192
|
+
mcp,
|
|
193
|
+
mcpName: (0, casing_1.snakeCase)(entity.name),
|
|
194
|
+
mcpPluralName: (0, casing_1.snakeCase)((0, pluralize_1.default)(entity.name)),
|
|
104
195
|
};
|
|
105
196
|
}
|
|
106
|
-
exports.
|
|
197
|
+
exports.mcpToolNames = mcpToolNames;
|
|
198
|
+
function hasPermissions(entities) {
|
|
199
|
+
return entities.some((entity) => entity.permissions);
|
|
200
|
+
}
|
|
201
|
+
exports.hasPermissions = hasPermissions;
|
|
202
|
+
const permissionKey = (entityName) => entityName.charAt(0).toLowerCase() + entityName.slice(1);
|
|
203
|
+
/**
|
|
204
|
+
* The grants entity, checked so it cannot become an escalation path: its
|
|
205
|
+
* writes must be role-guarded, and in a multi-tenant schema it must be
|
|
206
|
+
* tenant-scoped so a grant made in one tenant does not apply in another.
|
|
207
|
+
*/
|
|
208
|
+
function resolveGrants(entities, auth) {
|
|
209
|
+
var _a, _b, _c;
|
|
210
|
+
// One grants entity per service, whichever provider signed the caller in.
|
|
211
|
+
const named = [
|
|
212
|
+
...new Set((0, types_1.authProviders)(auth).map((a) => a.permissionEntity).filter(Boolean)),
|
|
213
|
+
];
|
|
214
|
+
if (named.length > 1)
|
|
215
|
+
throw new Error(`auth providers name different permissionEntity values (${named.join(", ")}); a service has one`);
|
|
216
|
+
const name = (_a = named[0]) !== null && _a !== void 0 ? _a : "RolePermission";
|
|
217
|
+
const entity = entities.find((e) => e.name === name);
|
|
218
|
+
if (!entity) {
|
|
219
|
+
if (named.length > 0)
|
|
220
|
+
throw new Error(`auth.permissionEntity "${name}" is not an entity in .apsorc`);
|
|
221
|
+
return undefined;
|
|
222
|
+
}
|
|
223
|
+
const fields = new Set(((_b = entity.fields) !== null && _b !== void 0 ? _b : []).map((f) => f.name));
|
|
224
|
+
for (const field of ["role", "permission"])
|
|
225
|
+
if (!fields.has(field))
|
|
226
|
+
throw new Error(`Entity ${name} needs a "${field}" text field to grant permissions`);
|
|
227
|
+
const writes = (_c = entity.permissions) !== null && _c !== void 0 ? _c : {};
|
|
228
|
+
if (!writes.create || !writes.update || !writes.delete)
|
|
229
|
+
throw new Error(`${name}.permissions must list roles for create, update and delete; otherwise any signed-in user can grant themselves any permission`);
|
|
230
|
+
const scopes = entity.scopeBy ? [entity.scopeBy].flat() : [];
|
|
231
|
+
const tenantField = scopes.find((s) => !s.includes("."));
|
|
232
|
+
if (!tenantField && entities.some((e) => e !== entity && e.scopeBy))
|
|
233
|
+
throw new Error(`${name} needs a direct scopeBy field: this schema is tenant-scoped, and an unscoped grant would apply in every tenant`);
|
|
234
|
+
return { entity: name, tenantField };
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Validates every entity's permissions and resolves them to permission names
|
|
238
|
+
* ("invoice:delete") by route and by join name, so a role that cannot read
|
|
239
|
+
* Task cannot read it through /projects?join=tasks either. Undefined when no
|
|
240
|
+
* entity has permissions.
|
|
241
|
+
*/
|
|
242
|
+
function getPermissionConfig(entities, relationshipMap, auth) {
|
|
243
|
+
var _a, _b;
|
|
244
|
+
if (!hasPermissions(entities))
|
|
245
|
+
return undefined;
|
|
246
|
+
const byEntity = {};
|
|
247
|
+
for (const entity of entities) {
|
|
248
|
+
if (!entity.permissions)
|
|
249
|
+
continue;
|
|
250
|
+
const rules = {};
|
|
251
|
+
for (const [op, roles] of Object.entries(entity.permissions)) {
|
|
252
|
+
if (!types_1.PERMISSION_OPERATIONS.includes(op))
|
|
253
|
+
throw new Error(`${entity.name}.permissions: unknown operation "${op}"; use ${types_1.PERMISSION_OPERATIONS.join(", ")}`);
|
|
254
|
+
if (!Array.isArray(roles) || roles.some((r) => typeof r !== "string" || !r))
|
|
255
|
+
throw new Error(`${entity.name}.permissions.${op} must be a list of role names`);
|
|
256
|
+
rules[op] = {
|
|
257
|
+
permission: `${permissionKey(entity.name)}:${op}`,
|
|
258
|
+
roles,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
byEntity[entity.name] = rules;
|
|
262
|
+
}
|
|
263
|
+
const routes = {};
|
|
264
|
+
for (const [name, rules] of Object.entries(byEntity))
|
|
265
|
+
routes[toRouteName(name)] = rules;
|
|
266
|
+
const joins = {};
|
|
267
|
+
for (const relations of Object.values(relationshipMap !== null && relationshipMap !== void 0 ? relationshipMap : {})) {
|
|
268
|
+
for (const relation of relations) {
|
|
269
|
+
const read = (_a = byEntity[relation.name]) === null || _a === void 0 ? void 0 : _a.read;
|
|
270
|
+
if (!read)
|
|
271
|
+
continue;
|
|
272
|
+
const name = (0, parse_1.getRelationshipName)(relation);
|
|
273
|
+
for (const key of new Set([name, (0, pluralize_1.default)(name)])) {
|
|
274
|
+
const list = (_b = joins[key]) !== null && _b !== void 0 ? _b : [];
|
|
275
|
+
if (!list.some((rule) => rule.permission === read.permission))
|
|
276
|
+
list.push(read);
|
|
277
|
+
joins[key] = list;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return { routes, joins, grants: resolveGrants(entities, auth) };
|
|
282
|
+
}
|
|
283
|
+
exports.getPermissionConfig = getPermissionConfig;
|
|
107
284
|
/**
|
|
108
285
|
* The direct scopeBy fields of an entity, for services that filter in their
|
|
109
286
|
* own queries (Go, Python). Undefined without auth: with no caller identity
|
|
@@ -122,20 +299,107 @@ function entityScope(entity, hasAuth) {
|
|
|
122
299
|
? s.contextKey
|
|
123
300
|
: "tenant",
|
|
124
301
|
}));
|
|
125
|
-
if (fields.length === 0
|
|
302
|
+
if (fields.length === 0)
|
|
126
303
|
return undefined;
|
|
127
304
|
return {
|
|
128
305
|
fields,
|
|
129
|
-
enforceOn: config.enforceOn,
|
|
130
306
|
bypassRoles: config.bypassRoles,
|
|
131
|
-
injectOnCreate: config.injectOnCreate,
|
|
132
307
|
};
|
|
133
308
|
}
|
|
134
309
|
exports.entityScope = entityScope;
|
|
135
|
-
/**
|
|
310
|
+
/**
|
|
311
|
+
* The relation table for the one rule on loading relations (R7): the tenant
|
|
312
|
+
* filter limits only the entity a request starts from, so a user caller may
|
|
313
|
+
* load a relation onto a tenant-scoped entity only when
|
|
314
|
+
* - the caller holds a role that skips that entity's scope, or
|
|
315
|
+
* - the caller is limited to its tenant on the entity the relation starts
|
|
316
|
+
* from, and the target is scoped by the same keys (Project.tasks).
|
|
317
|
+
* Any other load is refused, for every query syntax and at every depth. The
|
|
318
|
+
* rows of an allowed same-key relation are still limited to the caller's
|
|
319
|
+
* tenant by the target's own scope fields (`scope`), so the rule does not rely
|
|
320
|
+
* on every stored foreign key pointing inside the tenant. A service caller is
|
|
321
|
+
* not limited. Each language walks this table at run time.
|
|
322
|
+
*
|
|
323
|
+
* Undefined without auth or when no entity is scoped.
|
|
324
|
+
*/
|
|
325
|
+
function relationScopes(entities, relationshipMap, hasAuth) {
|
|
326
|
+
var _a;
|
|
327
|
+
if (!hasAuth)
|
|
328
|
+
return undefined;
|
|
329
|
+
const scoped = new Map();
|
|
330
|
+
for (const config of getScopedEntities(entities, relationshipMap)) {
|
|
331
|
+
scoped.set(config.name, {
|
|
332
|
+
keys: new Set(config.scopes.map((s) => s.contextKey)),
|
|
333
|
+
bypassRoles: config.bypassRoles,
|
|
334
|
+
scope: Object.fromEntries(config.scopes.filter((s) => s.direct).map((s) => [s.field, s.contextKey])),
|
|
335
|
+
// Entities this one is scoped through (project.organizationId -> Project).
|
|
336
|
+
parents: config.scopes.filter((s) => !s.direct).map((s) => { var _a; return (_a = s.parentEntity) !== null && _a !== void 0 ? _a : ""; }),
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
if (scoped.size === 0)
|
|
340
|
+
return undefined;
|
|
341
|
+
const table = {};
|
|
342
|
+
for (const entity of entities) {
|
|
343
|
+
const from = scoped.get(entity.name);
|
|
344
|
+
const relations = {};
|
|
345
|
+
for (const relation of (_a = relationshipMap === null || relationshipMap === void 0 ? void 0 : relationshipMap[entity.name]) !== null && _a !== void 0 ? _a : []) {
|
|
346
|
+
const name = (0, parse_1.getRelationshipName)(relation);
|
|
347
|
+
const many = relation.type === "OneToMany" || relation.type === "ManyToMany";
|
|
348
|
+
const to = scoped.get(relation.name);
|
|
349
|
+
// A target scoped through a parent has no tenant column to check on the
|
|
350
|
+
// loaded rows. Its rows are the caller's by definition only when loaded
|
|
351
|
+
// from that parent, through the one relation between the two.
|
|
352
|
+
const fromParent = !to ||
|
|
353
|
+
to.parents.every((parent) => {
|
|
354
|
+
var _a;
|
|
355
|
+
return parent === entity.name &&
|
|
356
|
+
((_a = relationshipMap === null || relationshipMap === void 0 ? void 0 : relationshipMap[entity.name]) !== null && _a !== void 0 ? _a : []).filter((r) => r.name === relation.name).length === 1;
|
|
357
|
+
});
|
|
358
|
+
relations[many ? (0, pluralize_1.default)(name) : name] = [
|
|
359
|
+
relation.name,
|
|
360
|
+
Boolean(from && to && fromParent && [...to.keys].every((key) => from.keys.has(key))),
|
|
361
|
+
];
|
|
362
|
+
}
|
|
363
|
+
table[entity.name] = { bypassRoles: from === null || from === void 0 ? void 0 : from.bypassRoles, scope: from === null || from === void 0 ? void 0 : from.scope, relations };
|
|
364
|
+
}
|
|
365
|
+
return table;
|
|
366
|
+
}
|
|
367
|
+
exports.relationScopes = relationScopes;
|
|
368
|
+
/** Entities whose scopeBy uses a nested path, which Go and Python cannot enforce. */
|
|
136
369
|
function nestedScopeEntities(entities) {
|
|
137
370
|
return getScopedEntities(entities)
|
|
138
371
|
.filter((e) => e.scopes.some((s) => !s.direct))
|
|
139
372
|
.map((e) => e.name);
|
|
140
373
|
}
|
|
141
374
|
exports.nestedScopeEntities = nestedScopeEntities;
|
|
375
|
+
/**
|
|
376
|
+
* One warning per provider that maps no tenant claim while entities are
|
|
377
|
+
* tenant-scoped: its users would get 403 on every one of those entities.
|
|
378
|
+
*/
|
|
379
|
+
function tenantClaimWarnings(entities, auth) {
|
|
380
|
+
const scoped = getScopedEntities(entities)
|
|
381
|
+
.filter((e) => e.scopes.some((s) => s.contextKey !== "userId" && s.contextKey !== "email"))
|
|
382
|
+
.map((e) => e.name);
|
|
383
|
+
if (scoped.length === 0)
|
|
384
|
+
return [];
|
|
385
|
+
const names = scoped.length > 2
|
|
386
|
+
? `${scoped[0]}, ${scoped[1]} and ${scoped.length - 2} more are`
|
|
387
|
+
: `${scoped.join(" and ")} ${scoped.length === 1 ? "is" : "are"}`;
|
|
388
|
+
const listed = Array.isArray(auth) && auth.length > 1;
|
|
389
|
+
return (0, types_1.resolveJwtProviders)(auth)
|
|
390
|
+
.filter((p) => !p.claims.workspaceId && !p.claims.organizationId)
|
|
391
|
+
.map((p) => `auth provider "${p.provider}" (${p.issuer}) has no tenant claim, but ${names} tenant-scoped. Tokens from this provider will get 403 "No tenant in the auth context" on ${scoped.length === 1 ? "that entity" : "those entities"}. Set ${listed ? "claims.organizationId on that provider" : "auth.claims.organizationId"} to the claim that holds the tenant.`);
|
|
392
|
+
}
|
|
393
|
+
exports.tenantClaimWarnings = tenantClaimWarnings;
|
|
394
|
+
/**
|
|
395
|
+
* The foreign keys of an entity that point at a tenant-scoped entity, as
|
|
396
|
+
* field -> that entity, from [field, entity] pairs in the generator's own
|
|
397
|
+
* naming. On a write a user caller may only name rows it could read there
|
|
398
|
+
* (R8). The entity's own scopeBy fields are left out: a write sets those from
|
|
399
|
+
* the caller.
|
|
400
|
+
*/
|
|
401
|
+
function scopedReferences(entity, foreignKeys, scopes) {
|
|
402
|
+
const own = new Set(entity.scopeBy ? [entity.scopeBy].flat() : []);
|
|
403
|
+
return Object.fromEntries(foreignKeys.filter(([field, target]) => { var _a; return !own.has(field) && ((_a = scopes === null || scopes === void 0 ? void 0 : scopes[target]) === null || _a === void 0 ? void 0 : _a.bypassRoles) !== undefined; }));
|
|
404
|
+
}
|
|
405
|
+
exports.scopedReferences = scopedReferences;
|
|
@@ -78,13 +78,13 @@ func (h *<%= it.entityName %>Handler) FindAll(c *gin.Context) {
|
|
|
78
78
|
if opts.Bare {
|
|
79
79
|
rows, err := h.service.FindAllBare(c.Request.Context(), opts)
|
|
80
80
|
if err != nil {
|
|
81
|
-
<% if (it.scope) { %>
|
|
81
|
+
<% if (it.scope || it.references) { %>
|
|
82
82
|
if scopeError(c, err) {
|
|
83
83
|
return
|
|
84
84
|
}
|
|
85
85
|
<% } %>
|
|
86
86
|
if qe, ok := utils.AsQueryError(err); ok {
|
|
87
|
-
c.JSON(
|
|
87
|
+
c.JSON(qe.Status(), gin.H{"error": qe.Error()})
|
|
88
88
|
return
|
|
89
89
|
}
|
|
90
90
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
@@ -96,13 +96,13 @@ func (h *<%= it.entityName %>Handler) FindAll(c *gin.Context) {
|
|
|
96
96
|
|
|
97
97
|
result, err := h.service.FindAll(c.Request.Context(), opts)
|
|
98
98
|
if err != nil {
|
|
99
|
-
<% if (it.scope) { %>
|
|
99
|
+
<% if (it.scope || it.references) { %>
|
|
100
100
|
if scopeError(c, err) {
|
|
101
101
|
return
|
|
102
102
|
}
|
|
103
103
|
<% } %>
|
|
104
104
|
if qe, ok := utils.AsQueryError(err); ok {
|
|
105
|
-
c.JSON(
|
|
105
|
+
c.JSON(qe.Status(), gin.H{"error": qe.Error()})
|
|
106
106
|
return
|
|
107
107
|
}
|
|
108
108
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
@@ -138,7 +138,7 @@ func (h *<%= it.entityName %>Handler) FindOne(c *gin.Context) {
|
|
|
138
138
|
|
|
139
139
|
result, err := h.service.FindOne(c.Request.Context(), id)
|
|
140
140
|
if err != nil {
|
|
141
|
-
<% if (it.scope) { %>
|
|
141
|
+
<% if (it.scope || it.references) { %>
|
|
142
142
|
if scopeError(c, err) {
|
|
143
143
|
return
|
|
144
144
|
}
|
|
@@ -175,7 +175,7 @@ func (h *<%= it.entityName %>Handler) Create(c *gin.Context) {
|
|
|
175
175
|
|
|
176
176
|
result, err := h.service.Create(c.Request.Context(), &input)
|
|
177
177
|
if err != nil {
|
|
178
|
-
<% if (it.scope) { %>
|
|
178
|
+
<% if (it.scope || it.references) { %>
|
|
179
179
|
if scopeError(c, err) {
|
|
180
180
|
return
|
|
181
181
|
}
|
|
@@ -226,7 +226,7 @@ func (h *<%= it.entityName %>Handler) Update(c *gin.Context) {
|
|
|
226
226
|
|
|
227
227
|
result, err := h.service.Update(c.Request.Context(), id, &input)
|
|
228
228
|
if err != nil {
|
|
229
|
-
<% if (it.scope) { %>
|
|
229
|
+
<% if (it.scope || it.references) { %>
|
|
230
230
|
if scopeError(c, err) {
|
|
231
231
|
return
|
|
232
232
|
}
|
|
@@ -263,7 +263,7 @@ func (h *<%= it.entityName %>Handler) Delete(c *gin.Context) {
|
|
|
263
263
|
<% } %>
|
|
264
264
|
|
|
265
265
|
if err := h.service.Delete(c.Request.Context(), id); err != nil {
|
|
266
|
-
<% if (it.scope) { %>
|
|
266
|
+
<% if (it.scope || it.references) { %>
|
|
267
267
|
if scopeError(c, err) {
|
|
268
268
|
return
|
|
269
269
|
}
|
|
@@ -7,15 +7,16 @@ import (
|
|
|
7
7
|
"net/http"
|
|
8
8
|
"strings"
|
|
9
9
|
|
|
10
|
+
"app/autogen/middleware"
|
|
10
11
|
"app/autogen/services"
|
|
11
12
|
"github.com/gin-gonic/gin"
|
|
12
13
|
)
|
|
13
14
|
|
|
14
15
|
// scopeError answers a scoped entity's service error: 403 when the caller has
|
|
15
|
-
// no tenant, 404 when the row is missing or belongs to another tenant.
|
|
16
|
+
// no tenant or the body names a row it cannot read, 404 when the row is missing or belongs to another tenant.
|
|
16
17
|
// It reports whether it wrote a response.
|
|
17
18
|
func scopeError(c *gin.Context, err error) bool {
|
|
18
|
-
if errors.Is(err, services.ErrForbidden) {
|
|
19
|
+
if errors.Is(err, services.ErrForbidden) || errors.Is(err, middleware.ErrReference) {
|
|
19
20
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
|
20
21
|
return true
|
|
21
22
|
}
|
|
@@ -4,8 +4,8 @@ package routes
|
|
|
4
4
|
|
|
5
5
|
import (
|
|
6
6
|
<% if (httpEntities.length > 0) { %> "app/autogen/handlers"
|
|
7
|
-
<% }
|
|
8
|
-
|
|
7
|
+
<% } %> "app/autogen/middleware"
|
|
8
|
+
"app/autogen/models"
|
|
9
9
|
"app/autogen/services"
|
|
10
10
|
"github.com/gin-gonic/gin"
|
|
11
11
|
"gorm.io/gorm"
|
|
@@ -14,11 +14,14 @@ import (
|
|
|
14
14
|
// RegisterAllRoutes registers all entity routes
|
|
15
15
|
func RegisterAllRoutes(r *gin.RouterGroup, db *gorm.DB) {
|
|
16
16
|
models.UseNames(db)
|
|
17
|
-
|
|
18
|
-
// Every route in this group requires authentication (.apsorc auth).
|
|
17
|
+
// Every route in this group needs a valid API key or a signed-in user.
|
|
19
18
|
r.Use(middleware.AuthMiddleware(db))
|
|
20
|
-
|
|
19
|
+
<% if (it.permissions) { %>
|
|
20
|
+
// Role permissions from .apsorc are checked after authentication.
|
|
21
|
+
r.Use(middleware.PermissionMiddleware(db, r.BasePath()))
|
|
21
22
|
<% } %>
|
|
23
|
+
|
|
24
|
+
|
|
22
25
|
<% httpEntities.forEach((entity) => { %>
|
|
23
26
|
// <%= entity.name %> routes
|
|
24
27
|
<%= entity.camelName %>Service := services.New<%= entity.name %>Service(db)
|