@apso/cli 0.48.0 → 0.49.1
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
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
<%~ includeFile('../header.eta') %>
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
Injectable,
|
|
5
|
+
CallHandler,
|
|
6
|
+
ExecutionContext,
|
|
7
|
+
ForbiddenException,
|
|
8
|
+
NestInterceptor,
|
|
9
|
+
SetMetadata,
|
|
10
|
+
} from '@nestjs/common';
|
|
11
|
+
import { Reflector } from '@nestjs/core';
|
|
12
|
+
import { PARSED_CRUD_REQUEST_KEY } from '@apso/crud';
|
|
13
|
+
<% if (it.permissions) { %>
|
|
14
|
+
import { PermissionGuard } from './permission.guard';
|
|
15
|
+
<% } %>
|
|
16
|
+
|
|
17
|
+
/** Names the entity a controller serves, for RelationAccess. */
|
|
18
|
+
export const RELATION_ROOT = 'apsoRelationRoot';
|
|
19
|
+
export const RelationRoot = (entity: string) => SetMetadata(RELATION_ROOT, entity);
|
|
20
|
+
|
|
21
|
+
interface RelationScope {
|
|
22
|
+
/** Set when the entity's reads are tenant-scoped: the roles that skip its scope. */
|
|
23
|
+
bypassRoles?: string[];
|
|
24
|
+
/** Set with bypassRoles: the entity's scopeBy fields and the caller value each must equal. */
|
|
25
|
+
scope?: Record<string, string>;
|
|
26
|
+
/** Relation name -> [the entity it loads, whether a caller limited to its tenant here stays in it there]. */
|
|
27
|
+
relations: Record<string, [string, boolean]>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Every entity's relations, from .apsorc relationships and scopeBy. */
|
|
31
|
+
export const RELATION_SCOPES: Record<string, RelationScope> = <%~ JSON.stringify(it.relationScopes ?? {}, null, 2) %>;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The first relation in `path` that would load rows outside the caller's
|
|
35
|
+
* tenant, if any. The tenant filter limits only the entity a request starts
|
|
36
|
+
* from, so a relation onto a tenant-scoped entity is loaded only when the
|
|
37
|
+
* caller holds a role that skips that entity's scope, or is limited to its
|
|
38
|
+
* tenant on the entity the relation starts from and the target is scoped by
|
|
39
|
+
* the same keys.
|
|
40
|
+
*
|
|
41
|
+
* When the path is allowed, `tenant` holds the scopeBy fields of the entity
|
|
42
|
+
* the path ends on, if the caller is limited to its tenant there. The rows the
|
|
43
|
+
* relation loads must match them, so a row that points at another tenant's
|
|
44
|
+
* row does not carry it into a response.
|
|
45
|
+
*/
|
|
46
|
+
export function relationOutsideTenant(
|
|
47
|
+
root: string,
|
|
48
|
+
path: string,
|
|
49
|
+
roles: string[],
|
|
50
|
+
): { refused?: string; tenant?: Record<string, string> } {
|
|
51
|
+
const skips = (entity?: RelationScope) => Boolean(entity?.bypassRoles?.some((role) => roles.includes(role)));
|
|
52
|
+
let from = RELATION_SCOPES[root];
|
|
53
|
+
let tenant: Record<string, string> | undefined;
|
|
54
|
+
for (const name of path.split('.')) {
|
|
55
|
+
const hop = from?.relations[name];
|
|
56
|
+
if (!hop) return {};
|
|
57
|
+
const [entity, sameTenant] = hop;
|
|
58
|
+
const to = RELATION_SCOPES[entity];
|
|
59
|
+
const inTenant = sameTenant && from.bypassRoles !== undefined && !skips(from);
|
|
60
|
+
if (to?.bypassRoles !== undefined && !skips(to) && !inTenant) return { refused: name };
|
|
61
|
+
// Allowed as a same-tenant hop: its rows are held to that tenant.
|
|
62
|
+
tenant = inTenant && to?.bypassRoles !== undefined && !skips(to) ? to.scope : undefined;
|
|
63
|
+
from = to;
|
|
64
|
+
}
|
|
65
|
+
return { tenant };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* RelationAccess - the one place that decides which relations a request may
|
|
70
|
+
* load. It is on every generated controller, listed above @Crud so it runs
|
|
71
|
+
* after the CRUD request is parsed, and reads the relation paths from the
|
|
72
|
+
* parsed request. A select embed (?select=*,tasks(*)) arrives there as a
|
|
73
|
+
* relation path, at every depth. A filter or sort on a related
|
|
74
|
+
* entity's field needs the relation loaded, so it meets the same check.
|
|
75
|
+
*
|
|
76
|
+
* A user caller is refused a relation that would load another tenant's rows<% if (it.permissions) { %>
|
|
77
|
+
|
|
78
|
+
* or an entity its role cannot read<% } %>. A service caller (valid API key) is
|
|
79
|
+
* not limited. A request with no parsed CRUD request is refused.
|
|
80
|
+
*/
|
|
81
|
+
@Injectable()
|
|
82
|
+
export class RelationAccess implements NestInterceptor {
|
|
83
|
+
constructor(
|
|
84
|
+
private reflector: Reflector,
|
|
85
|
+
<% if (it.permissions) { %>
|
|
86
|
+
private permissions: PermissionGuard,
|
|
87
|
+
<% } %>
|
|
88
|
+
) {}
|
|
89
|
+
|
|
90
|
+
async intercept(context: ExecutionContext, next: CallHandler) {
|
|
91
|
+
const request = context.switchToHttp().getRequest();
|
|
92
|
+
const parsed = request[PARSED_CRUD_REQUEST_KEY]?.parsed;
|
|
93
|
+
const root = this.reflector.get<string>(RELATION_ROOT, context.getClass());
|
|
94
|
+
if (!parsed || !root) {
|
|
95
|
+
throw new Error('RelationAccess needs @RelationRoot and must be listed above @Crud');
|
|
96
|
+
}
|
|
97
|
+
if (request.auth?.serviceId) {
|
|
98
|
+
return next.handle();
|
|
99
|
+
}
|
|
100
|
+
const joins: { field: string; on?: { field: string; operator: string; value: unknown }[] }[] = parsed.join ?? [];
|
|
101
|
+
const paths: string[] = joins.map((join) => join.field);
|
|
102
|
+
const roles: string[] = request.auth?.roles ?? [];
|
|
103
|
+
for (const join of joins) {
|
|
104
|
+
const { refused, tenant } = relationOutsideTenant(root, join.field, roles);
|
|
105
|
+
if (refused) {
|
|
106
|
+
request.apso = { ...request.apso, denied: 'relation outside the tenant scope' };
|
|
107
|
+
throw new ForbiddenException(`The relation "${refused}" cannot be loaded from ${root}: its rows are tenant-scoped`);
|
|
108
|
+
}
|
|
109
|
+
// The join itself carries the tenant condition, so it also holds for a
|
|
110
|
+
// filter or sort on the related entity's fields.
|
|
111
|
+
for (const [field, key] of Object.entries(tenant ?? {})) {
|
|
112
|
+
const value = request[key] ?? request.user?.[key] ?? request.auth?.[key] ?? request.auth?.workspaceId;
|
|
113
|
+
if (value == null || value === '') {
|
|
114
|
+
throw new ForbiddenException('No tenant in the auth context');
|
|
115
|
+
}
|
|
116
|
+
join.on = [...(join.on ?? []), { field, operator: '$eq', value }];
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
<% if (it.permissions) { %>
|
|
120
|
+
await this.permissions.checkRelations(request, paths);
|
|
121
|
+
<% } %>
|
|
122
|
+
return next.handle();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
<%~ includeFile('../header.eta') %>
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
|
+
BadRequestException,
|
|
5
|
+
ConflictException,
|
|
4
6
|
Injectable,
|
|
5
7
|
CanActivate,
|
|
6
8
|
ExecutionContext,
|
|
@@ -8,7 +10,7 @@ import {
|
|
|
8
10
|
} from '@nestjs/common';
|
|
9
11
|
import { Reflector } from '@nestjs/core';
|
|
10
12
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
11
|
-
import {
|
|
13
|
+
import { DataSource, Repository } from 'typeorm';
|
|
12
14
|
|
|
13
15
|
<% /* Import all entities that have scoped relationships (from sibling autogen folders) */ %>
|
|
14
16
|
<% it.scopedEntities.forEach((entity) => { %>
|
|
@@ -56,10 +58,6 @@ export const Public = () =>
|
|
|
56
58
|
export interface ScopeConfig {
|
|
57
59
|
/** The scope fields or paths (e.g., 'workspaceId' or 'task.workspaceId') */
|
|
58
60
|
scopes: ScopeField[];
|
|
59
|
-
/** Whether to inject scope on create */
|
|
60
|
-
injectOnCreate: boolean;
|
|
61
|
-
/** Which operations to enforce scope on */
|
|
62
|
-
enforceOn: string[];
|
|
63
61
|
/** Roles that can bypass scope enforcement */
|
|
64
62
|
bypassRoles: string[];
|
|
65
63
|
}
|
|
@@ -105,13 +103,24 @@ export const ENTITY_SCOPES: Record<string, ScopeConfig> = {
|
|
|
105
103
|
}<%= scopeIndex < entity.scopes.length - 1 ? ',' : '' %>
|
|
106
104
|
<% }) %>
|
|
107
105
|
],
|
|
108
|
-
injectOnCreate: <%= entity.injectOnCreate %>,
|
|
109
|
-
enforceOn: [<%~ entity.enforceOn.map(op => `'${op}'`).join(', ') %>],
|
|
110
106
|
bypassRoles: [<%~ entity.bypassRoles.map(role => `'${role}'`).join(', ') %>],
|
|
111
107
|
}<%= index < it.scopedEntities.length - 1 ? ',' : '' %>
|
|
112
108
|
<% }) %>
|
|
113
109
|
};
|
|
114
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Every entity by its route, so a write body can be checked against the
|
|
113
|
+
* entity's relations whether or not the entity itself is scoped.
|
|
114
|
+
*/
|
|
115
|
+
export const ROUTE_ENTITIES: Record<string, string> = {
|
|
116
|
+
<% it.routeEntities.forEach((entity) => { %>
|
|
117
|
+
'<%= entity.route %>': '<%= entity.name %>',
|
|
118
|
+
<% }) %>
|
|
119
|
+
};
|
|
120
|
+
const ENTITY_ROUTES: Record<string, string> = Object.fromEntries(
|
|
121
|
+
Object.entries(ROUTE_ENTITIES).map(([route, name]) => [name, route]),
|
|
122
|
+
);
|
|
123
|
+
|
|
115
124
|
@Injectable()
|
|
116
125
|
export class ScopeGuard implements CanActivate {
|
|
117
126
|
constructor(
|
|
@@ -120,12 +129,24 @@ export class ScopeGuard implements CanActivate {
|
|
|
120
129
|
@InjectRepository(<%= entity.name %>)
|
|
121
130
|
private <%= entity.repoName %>: Repository<<%= entity.name %>>,
|
|
122
131
|
<% }) %>
|
|
123
|
-
<% if (it.hasNestedFk) { %>
|
|
124
132
|
private dataSource: DataSource,
|
|
125
|
-
<% } %>
|
|
126
133
|
) {}
|
|
127
134
|
|
|
128
135
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
136
|
+
try {
|
|
137
|
+
return await this.check(context);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error instanceof ForbiddenException) {
|
|
140
|
+
// The reason, for the log.
|
|
141
|
+
const request = context.switchToHttp().getRequest();
|
|
142
|
+
const denied = /tenant/.test(error.message) ? 'no tenant' : 'outside the tenant scope';
|
|
143
|
+
request.apso = { ...request.apso, denied };
|
|
144
|
+
}
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private async check(context: ExecutionContext): Promise<boolean> {
|
|
129
150
|
// Check if route should skip scope check
|
|
130
151
|
const skipCheck = this.reflector.getAllAndOverride<boolean>(
|
|
131
152
|
SKIP_SCOPE_CHECK,
|
|
@@ -148,6 +169,11 @@ export class ScopeGuard implements CanActivate {
|
|
|
148
169
|
|
|
149
170
|
const request = context.switchToHttp().getRequest();
|
|
150
171
|
|
|
172
|
+
// A service caller (valid API key) is not tenant-scoped.
|
|
173
|
+
if (request.auth?.serviceId) {
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
|
|
151
177
|
// Get the resource path from the request
|
|
152
178
|
const path = request.route?.path || request.path;
|
|
153
179
|
const method = request.method;
|
|
@@ -162,8 +188,12 @@ export class ScopeGuard implements CanActivate {
|
|
|
162
188
|
|
|
163
189
|
// Check if this is a scoped entity
|
|
164
190
|
const scopeConfig = ENTITY_SCOPES[entityType];
|
|
191
|
+
const writes = method === 'POST' || method === 'PUT' || method === 'PATCH';
|
|
165
192
|
if (!scopeConfig) {
|
|
166
|
-
// Not a scoped entity
|
|
193
|
+
// Not a scoped entity; its body still must not reach a scoped row.
|
|
194
|
+
if (writes) {
|
|
195
|
+
await this.checkBody(request, entityType);
|
|
196
|
+
}
|
|
167
197
|
return true;
|
|
168
198
|
}
|
|
169
199
|
|
|
@@ -173,13 +203,14 @@ export class ScopeGuard implements CanActivate {
|
|
|
173
203
|
return true;
|
|
174
204
|
}
|
|
175
205
|
|
|
206
|
+
// A body must not reach another entity's rows or write over an existing row.
|
|
207
|
+
if (writes) {
|
|
208
|
+
await this.checkBody(request, entityType, scopeConfig);
|
|
209
|
+
}
|
|
210
|
+
|
|
176
211
|
// Map HTTP method to operation
|
|
177
212
|
const operation = this.mapMethodToOperation(method, request.params?.id);
|
|
178
213
|
|
|
179
|
-
// Check if this operation should be enforced
|
|
180
|
-
if (!scopeConfig.enforceOn.includes(operation)) {
|
|
181
|
-
return true;
|
|
182
|
-
}
|
|
183
214
|
<% if (it.hasNestedFk) { %>
|
|
184
215
|
|
|
185
216
|
// Nested paths (task.workspaceId): load the caller's parent ids for the
|
|
@@ -200,8 +231,8 @@ export class ScopeGuard implements CanActivate {
|
|
|
200
231
|
}
|
|
201
232
|
}
|
|
202
233
|
|
|
203
|
-
//
|
|
204
|
-
if (operation === 'create'
|
|
234
|
+
// On create the scope values come from the caller, never from the body.
|
|
235
|
+
if (operation === 'create') {
|
|
205
236
|
this.injectScopeValues(request, scopeConfig);
|
|
206
237
|
}
|
|
207
238
|
<% if (it.hasAuth) { %>
|
|
@@ -212,7 +243,7 @@ export class ScopeGuard implements CanActivate {
|
|
|
212
243
|
}
|
|
213
244
|
<% } %>
|
|
214
245
|
|
|
215
|
-
// For GET (list) requests,
|
|
246
|
+
// For GET (list) requests, require the caller's tenant
|
|
216
247
|
if (operation === 'find') {
|
|
217
248
|
this.addScopeFilter(request, scopeConfig);
|
|
218
249
|
}
|
|
@@ -302,10 +333,6 @@ export class ScopeGuard implements CanActivate {
|
|
|
302
333
|
}
|
|
303
334
|
|
|
304
335
|
private injectScopeValues(request: any, scopeConfig: ScopeConfig): void {
|
|
305
|
-
if (!request.body || typeof request.body !== 'object') {
|
|
306
|
-
return;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
336
|
for (const scope of scopeConfig.scopes) {
|
|
310
337
|
if (scope.direct) {
|
|
311
338
|
const scopeValue = this.getScopeValue(request, scope.contextKey);
|
|
@@ -314,37 +341,159 @@ export class ScopeGuard implements CanActivate {
|
|
|
314
341
|
throw new ForbiddenException('No tenant in the auth context');
|
|
315
342
|
}
|
|
316
343
|
// Always the caller's tenant, never one from the body.
|
|
317
|
-
request.body
|
|
344
|
+
for (const item of this.bodyItems(request.body)) {
|
|
345
|
+
item[scope.field] = scopeValue;
|
|
346
|
+
}
|
|
318
347
|
<% } else { %>
|
|
319
|
-
|
|
320
|
-
|
|
348
|
+
for (const item of this.bodyItems(request.body)) {
|
|
349
|
+
if (scopeValue && !item[scope.field]) {
|
|
350
|
+
item[scope.field] = scopeValue;
|
|
351
|
+
}
|
|
321
352
|
}
|
|
322
353
|
<% } %>
|
|
323
354
|
}
|
|
324
355
|
}
|
|
325
356
|
}
|
|
326
357
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
358
|
+
/** The rows a write body carries: the body itself and each row of a bulk create. */
|
|
359
|
+
private bodyItems(body: any): any[] {
|
|
360
|
+
const plain = (v: any) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
361
|
+
if (!plain(body)) {
|
|
362
|
+
return [];
|
|
330
363
|
}
|
|
364
|
+
return [body, ...(Array.isArray(body.bulk) ? body.bulk.filter(plain) : [])];
|
|
365
|
+
}
|
|
331
366
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
367
|
+
/**
|
|
368
|
+
* Relations and ids in a write body. TypeORM saves a relation object in
|
|
369
|
+
* place of the foreign key column, saves the rows listed under a to-many
|
|
370
|
+
* relation, and updates the row a body names by id. So before the
|
|
371
|
+
* checks below run:
|
|
372
|
+
* - the body's own id is dropped: the database assigns it on create, and
|
|
373
|
+
* on update the row is the one the route names. A key the client chooses
|
|
374
|
+
* is kept on create, and refused when a row already has it
|
|
375
|
+
* - a to-one relation becomes its foreign key, which is then checked like
|
|
376
|
+
* any other column
|
|
377
|
+
* - a foreign key to a tenant-scoped entity, sent as a column or as a
|
|
378
|
+
* relation, must name a row the caller could read (null is allowed)
|
|
379
|
+
* - rows of a scoped entity listed under a relation must be the caller's
|
|
380
|
+
* own, and only their ids are kept
|
|
381
|
+
* A referenced row is looked up once per request, however many rows of a
|
|
382
|
+
* bulk create name it.
|
|
383
|
+
*/
|
|
384
|
+
private async checkBody(
|
|
385
|
+
request: any,
|
|
386
|
+
entityType: string,
|
|
387
|
+
scopeConfig?: ScopeConfig,
|
|
388
|
+
): Promise<void> {
|
|
389
|
+
if (Array.isArray(request.body)) {
|
|
390
|
+
throw new BadRequestException('The body must be an object');
|
|
391
|
+
}
|
|
392
|
+
const name = ROUTE_ENTITIES[entityType];
|
|
393
|
+
if (!name) {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const metadata = this.dataSource.getMetadata(name);
|
|
397
|
+
const scopeFields = (scopeConfig?.scopes ?? []).map((s) => s.fkField ?? s.field);
|
|
398
|
+
const denied = () => new ForbiddenException('You do not have access to this resource');
|
|
399
|
+
const roles: string[] = request.auth?.roles ?? request.user?.roles ?? request.roles ?? [];
|
|
400
|
+
// An entity whose rows the caller reads only inside its tenant.
|
|
401
|
+
const limited = (scope?: ScopeConfig): scope is ScopeConfig =>
|
|
402
|
+
Boolean(scope) && !scope!.bypassRoles.some((role) => roles.includes(role));
|
|
403
|
+
const lookups = new Map<string, Promise<boolean>>();
|
|
404
|
+
const readable = (route: string, id: unknown, scope: ScopeConfig): Promise<boolean> => {
|
|
405
|
+
const key = `${route}:${id}`;
|
|
406
|
+
if (!lookups.has(key)) lookups.set(key, this.verifyResourceAccess(route, String(id), request, scope));
|
|
407
|
+
return lookups.get(key)!;
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
for (const item of this.bodyItems(request.body)) {
|
|
411
|
+
if (scopeConfig) {
|
|
412
|
+
const chosen: Record<string, any> = {};
|
|
413
|
+
for (const column of metadata.primaryColumns) {
|
|
414
|
+
const sent = item[column.propertyName];
|
|
415
|
+
if (column.isGenerated || request.method !== 'POST') {
|
|
416
|
+
delete item[column.propertyName];
|
|
417
|
+
} else if (sent != null) {
|
|
418
|
+
chosen[column.propertyName] = sent;
|
|
419
|
+
}
|
|
338
420
|
}
|
|
339
|
-
|
|
340
|
-
if (
|
|
341
|
-
|
|
342
|
-
|
|
421
|
+
// A key the client chooses: a create must not write over the row that has it.
|
|
422
|
+
if (Object.keys(chosen).length > 0) {
|
|
423
|
+
if (Object.values(chosen).some((v) => typeof v === 'object')) throw denied();
|
|
424
|
+
if (await this.dataSource.getRepository(name).findOne({ where: chosen })) {
|
|
425
|
+
throw new ConflictException('A row with this key already exists');
|
|
426
|
+
}
|
|
343
427
|
}
|
|
344
428
|
}
|
|
429
|
+
for (const relation of metadata.relations) {
|
|
430
|
+
const key = relation.propertyName;
|
|
431
|
+
const value = item[key];
|
|
432
|
+
const target = relation.inverseEntityMetadata;
|
|
433
|
+
const targetRoute = ENTITY_ROUTES[target.name];
|
|
434
|
+
const targetScope = ENTITY_SCOPES[targetRoute];
|
|
435
|
+
const isObject = value !== null && typeof value === 'object';
|
|
436
|
+
|
|
437
|
+
const [join] = relation.joinColumns;
|
|
438
|
+
if ((relation.isManyToOne || relation.isOneToOneOwner) && relation.joinColumns.length === 1) {
|
|
439
|
+
if (!targetScope && !scopeFields.includes(join.propertyName)) continue;
|
|
440
|
+
const referenced = join.referencedColumn!.propertyName;
|
|
441
|
+
let id: any;
|
|
442
|
+
if (Object.prototype.hasOwnProperty.call(item, key)) {
|
|
443
|
+
id = isObject ? (Array.isArray(value) ? undefined : value[referenced]) : value;
|
|
444
|
+
if (id !== null && typeof id === 'object') throw denied();
|
|
445
|
+
if (join.isVirtual) {
|
|
446
|
+
// No column property to move the id to: keep the id alone.
|
|
447
|
+
item[key] = id == null ? null : { [referenced]: id };
|
|
448
|
+
} else {
|
|
449
|
+
delete item[key];
|
|
450
|
+
if (id !== undefined) item[join.propertyName] = id;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
// The foreign key as it will be saved. The entity's own scope fields
|
|
454
|
+
// are set from the caller or checked as its parent, further on.
|
|
455
|
+
if (!join.isVirtual) id = item[join.propertyName];
|
|
456
|
+
if (id == null || scopeFields.includes(join.propertyName) || !limited(targetScope)) continue;
|
|
457
|
+
if (typeof id === 'object' || !(await readable(targetRoute, id, targetScope))) throw denied();
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// A to-many (or inverse one-to-one) relation: saving it writes the listed rows.
|
|
462
|
+
if (!Object.prototype.hasOwnProperty.call(item, key)) continue;
|
|
463
|
+
if (!targetScope) continue;
|
|
464
|
+
// A shared row cannot take over or let go of scoped rows.
|
|
465
|
+
if (!scopeConfig) throw denied();
|
|
466
|
+
const primary = target.primaryColumns[0].propertyName;
|
|
467
|
+
const kept: any[] = [];
|
|
468
|
+
for (const row of Array.isArray(value) ? value : value == null ? [] : [value]) {
|
|
469
|
+
const id = row !== null && typeof row === 'object' ? row[primary] : row;
|
|
470
|
+
if (id == null || typeof id === 'object') throw denied();
|
|
471
|
+
if (!(await readable(targetRoute, id, targetScope))) throw denied();
|
|
472
|
+
kept.push({ [primary]: id });
|
|
473
|
+
}
|
|
474
|
+
item[key] = Array.isArray(value) ? kept : kept[0] ?? null;
|
|
475
|
+
}
|
|
345
476
|
}
|
|
346
477
|
}
|
|
347
478
|
|
|
479
|
+
/**
|
|
480
|
+
* A list request needs the caller's tenant. The filter itself is the
|
|
481
|
+
* controller's @CrudAuth, which applies to every query dialect; nothing is
|
|
482
|
+
* added to the query string here.
|
|
483
|
+
*/
|
|
484
|
+
private addScopeFilter(request: any, scopeConfig: ScopeConfig): void {
|
|
485
|
+
<% if (it.hasAuth) { %>
|
|
486
|
+
for (const scope of scopeConfig.scopes) {
|
|
487
|
+
if (scope.direct && !this.getScopeValue(request, scope.contextKey)) {
|
|
488
|
+
throw new ForbiddenException('No tenant in the auth context');
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
<% } else { %>
|
|
492
|
+
void request;
|
|
493
|
+
void scopeConfig;
|
|
494
|
+
<% } %>
|
|
495
|
+
}
|
|
496
|
+
|
|
348
497
|
private getScopeValue(request: any, contextKey: string): string | undefined {
|
|
349
498
|
// Try multiple locations for the scope value
|
|
350
499
|
return (
|
|
@@ -389,10 +538,9 @@ export class ScopeGuard implements CanActivate {
|
|
|
389
538
|
request.apsoScope = { ...request.apsoScope, [scope.fkField]: ids };
|
|
390
539
|
|
|
391
540
|
if (operation === 'create' || operation === 'update') {
|
|
392
|
-
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
const fk = item?.[scope.fkField] ?? item?.[scope.field]?.[pk];
|
|
541
|
+
// checkBody has already turned a relation object into this foreign key.
|
|
542
|
+
for (const item of this.bodyItems(request.body)) {
|
|
543
|
+
const fk = item[scope.fkField];
|
|
396
544
|
if (fk != null && !ids.some((id: any) => String(id) === String(fk))) {
|
|
397
545
|
throw new ForbiddenException('You do not have access to this resource');
|
|
398
546
|
}
|