@apso/cli 0.47.6 → 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.
Files changed (141) hide show
  1. package/README.md +28 -1
  2. package/dist/commands/dev.d.ts +2 -0
  3. package/dist/commands/dev.js +20 -3
  4. package/dist/commands/generate.js +55 -13
  5. package/dist/commands/mcp/serve.js +24 -41
  6. package/dist/commands/schema/diff.js +3 -4
  7. package/dist/commands/schema/pull.js +13 -11
  8. package/dist/commands/schema/push.js +6 -5
  9. package/dist/commands/schema/validate.d.ts +10 -0
  10. package/dist/commands/schema/validate.js +54 -0
  11. package/dist/commands/test/access.d.ts +11 -0
  12. package/dist/commands/test/access.js +65 -0
  13. package/dist/lib/access/cases.d.ts +120 -0
  14. package/dist/lib/access/cases.js +1163 -0
  15. package/dist/lib/access/index.d.ts +4 -0
  16. package/dist/lib/access/index.js +7 -0
  17. package/dist/lib/access/report.d.ts +75 -0
  18. package/dist/lib/access/report.js +118 -0
  19. package/dist/lib/access/rules.json +207 -0
  20. package/dist/lib/access/run.d.ts +38 -0
  21. package/dist/lib/access/run.js +111 -0
  22. package/dist/lib/access/tokens.d.ts +46 -0
  23. package/dist/lib/access/tokens.js +139 -0
  24. package/dist/lib/api/services.d.ts +10 -7
  25. package/dist/lib/api/services.js +19 -32
  26. package/dist/lib/apsorc-parser.d.ts +1 -1
  27. package/dist/lib/apsorc-parser.js +2 -0
  28. package/dist/lib/ddl/change.js +2 -0
  29. package/dist/lib/ddl/index.d.ts +11 -1
  30. package/dist/lib/ddl/index.js +30 -16
  31. package/dist/lib/ddl/sync.d.ts +25 -0
  32. package/dist/lib/ddl/sync.js +78 -0
  33. package/dist/lib/deploy/server-push.js +3 -1
  34. package/dist/lib/generators/go.d.ts +25 -7
  35. package/dist/lib/generators/go.js +365 -128
  36. package/dist/lib/generators/python.d.ts +9 -3
  37. package/dist/lib/generators/python.js +282 -47
  38. package/dist/lib/generators/typescript.d.ts +3 -5
  39. package/dist/lib/generators/typescript.js +78 -64
  40. package/dist/lib/guards.d.ts +111 -13
  41. package/dist/lib/guards.js +287 -23
  42. package/dist/lib/templates/entities/entity-col-array.eta +1 -1
  43. package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
  44. package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
  45. package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
  46. package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
  47. package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
  48. package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
  49. package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
  50. package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
  51. package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
  52. package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
  53. package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
  54. package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
  55. package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
  56. package/dist/lib/templates/go/dto/dto.eta +17 -18
  57. package/dist/lib/templates/go/handlers/handler.eta +10 -8
  58. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  59. package/dist/lib/templates/go/index-module.eta +10 -5
  60. package/dist/lib/templates/go/mcp.eta +307 -0
  61. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  62. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  63. package/dist/lib/templates/go/models/model.eta +22 -19
  64. package/dist/lib/templates/go/models/schema.eta +72 -0
  65. package/dist/lib/templates/go/services/service.eta +84 -35
  66. package/dist/lib/templates/go/utils/query.eta +68 -7
  67. package/dist/lib/templates/guards/guards.module.eta +37 -29
  68. package/dist/lib/templates/guards/index.eta +4 -0
  69. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  70. package/dist/lib/templates/guards/key.guard.eta +280 -0
  71. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  72. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  73. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  74. package/dist/lib/templates/python/auth.eta +354 -95
  75. package/dist/lib/templates/python/index-module.eta +7 -7
  76. package/dist/lib/templates/python/mcp.eta +284 -0
  77. package/dist/lib/templates/python/models/init.eta +24 -0
  78. package/dist/lib/templates/python/models/model.eta +30 -61
  79. package/dist/lib/templates/python/permissions.eta +121 -0
  80. package/dist/lib/templates/python/routers/router.eta +39 -1
  81. package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
  82. package/dist/lib/templates/python/schemas/schema.eta +27 -14
  83. package/dist/lib/templates/python/services/service.eta +38 -15
  84. package/dist/lib/templates/python/utils/query.eta +52 -25
  85. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  86. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  87. package/dist/lib/templates/rest/service-rest.eta +3 -44
  88. package/dist/lib/types/auth.d.ts +84 -80
  89. package/dist/lib/types/auth.js +77 -60
  90. package/dist/lib/types/entity.d.ts +17 -9
  91. package/dist/lib/types/entity.js +3 -0
  92. package/dist/lib/types/index.d.ts +2 -2
  93. package/dist/lib/types/index.js +6 -5
  94. package/dist/lib/utils/crud-deps.d.ts +77 -6
  95. package/dist/lib/utils/crud-deps.js +197 -14
  96. package/dist/lib/utils/field.d.ts +12 -0
  97. package/dist/lib/utils/field.js +18 -2
  98. package/dist/lib/utils/schema-convert.d.ts +20 -43
  99. package/dist/lib/utils/schema-convert.js +28 -78
  100. package/dist/lib/utils/template.d.ts +11 -0
  101. package/dist/lib/utils/template.js +36 -1
  102. package/dist/lib/verify/index.d.ts +6 -1
  103. package/dist/lib/verify/index.js +30 -13
  104. package/npm-shrinkwrap.json +2 -2
  105. package/oclif.manifest.json +36 -1
  106. package/package.json +1 -1
  107. package/dist/lib/templates/go/models/model-col-array.eta +0 -1
  108. package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
  109. package/dist/lib/templates/go/models/model-col-date.eta +0 -1
  110. package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
  111. package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
  112. package/dist/lib/templates/go/models/model-col-float.eta +0 -1
  113. package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
  114. package/dist/lib/templates/go/models/model-col-json.eta +0 -1
  115. package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
  116. package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
  117. package/dist/lib/templates/go/models/model-col-string.eta +0 -1
  118. package/dist/lib/templates/go/models/model-col-text.eta +0 -1
  119. package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
  120. package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
  121. package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
  122. package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
  123. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  124. package/dist/lib/templates/guards/auth.guard.eta +0 -233
  125. package/dist/lib/templates/python/models/model-col-array.eta +0 -4
  126. package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
  127. package/dist/lib/templates/python/models/model-col-date.eta +0 -4
  128. package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
  129. package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
  130. package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
  131. package/dist/lib/templates/python/models/model-col-float.eta +0 -6
  132. package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
  133. package/dist/lib/templates/python/models/model-col-json.eta +0 -4
  134. package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
  135. package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
  136. package/dist/lib/templates/python/models/model-col-string.eta +0 -6
  137. package/dist/lib/templates/python/models/model-col-text.eta +0 -6
  138. package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
  139. package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
  140. package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
  141. package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
@@ -0,0 +1,280 @@
1
+ /**
2
+ * ApiKeyGuard - the API key check built into every Apso service
3
+ *
4
+ * Auto-generated by Apso CLI. Not configurable in .apsorc.
5
+ *
6
+ * The key source is chosen once, when the service starts, first match wins:
7
+ * 1. APSO_API_KEY is set: the x-api-key header must match it. The variable
8
+ * holds the key itself (not a hash); several keys separated by commas are
9
+ * accepted, so a key can be rotated without downtime.
10
+ * 2. APSO_SERVICE_TOKEN_JWKS_URL is set: the platform's gateway has checked
11
+ * the key and sends a signed token in x-apso-service-token.
12
+ * 3. Neither: API keys are off and only signed-in users are accepted. A
13
+ * service with no sign-in configured then refuses every request.
14
+ *
15
+ * A caller with a valid key is a service caller (request.auth.serviceId): it
16
+ * may call any route, is not tenant-scoped and skips role permission checks.
17
+ * A request whose key fails is refused, whatever else it carries.
18
+ *
19
+ * For logging, the guards record who is calling on request.apso.caller and
20
+ * why a request was refused on request.apso.denied.
21
+ *
22
+ * DO NOT EDIT - Changes will be overwritten on next scaffold
23
+ */
24
+ import {
25
+ Injectable,
26
+ CanActivate,
27
+ ExecutionContext,
28
+ <% if (it.authRoutes.length > 0) { %>
29
+ ForbiddenException,
30
+ <% } %>
31
+ UnauthorizedException,
32
+ } from '@nestjs/common';
33
+ import { Reflector } from '@nestjs/core';
34
+ import { createHash, randomUUID, timingSafeEqual } from 'crypto';
35
+ import { createRemoteJWKSet, jwtVerify } from 'jose';
36
+ <% if (it.hasAuth) { %>
37
+ import { AuthGuard, IS_PUBLIC_KEY<% if (it.mcpAuth) { %>, MCP_SIGN_IN<% } %> } from './auth.guard';
38
+ <% } else if (it.scopedEntities.length > 0) { %>
39
+ import { IS_PUBLIC_KEY } from './scope.guard';
40
+ <% } else { %>
41
+
42
+ export const IS_PUBLIC_KEY = 'isPublic';
43
+
44
+ /**
45
+ * Decorator to mark a route as public (skips the key check)
46
+ * Usage: @Public()
47
+ */
48
+ export const Public =
49
+ () => (target: any, key?: string, descriptor?: PropertyDescriptor) => {
50
+ Reflect.defineMetadata(IS_PUBLIC_KEY, true, descriptor?.value || target);
51
+ };
52
+ <% } %>
53
+
54
+ /** What request.auth holds for a caller that presented a valid API key. */
55
+ export interface ServiceCaller {
56
+ /** The key's id: from the platform, or the first 8 hex digits of its SHA-256. */
57
+ serviceId: string;
58
+ roles: string[];
59
+ permissions: string[];
60
+ }
61
+
62
+ const NO_SOURCE =
63
+ 'This service has no API key source and no sign-in configured, so it refuses every request. Set APSO_API_KEY in its environment; "apso dev" creates a development key in .env.';
64
+ const NO_CREDENTIAL = 'No credential on the request. Send the API key in the x-api-key header.';
65
+ const WRONG_KEY = 'The key in the x-api-key header does not match APSO_API_KEY.';
66
+ const NO_SERVICE_TOKEN =
67
+ 'This service takes API keys through the platform gateway, and the request has no valid x-apso-service-token. Call the service at its gateway URL with a key issued for it.';
68
+ const KEYS_OFF = 'An x-api-key header was sent, but API keys are off on this service. Set APSO_API_KEY to turn them on.';
69
+
70
+ const sha256 = (value: string) => createHash('sha256').update(value).digest();
71
+ <% if (it.authRoutes.length > 0) { %>
72
+
73
+ /**
74
+ * The auth entities hold session tokens, password hashes, reset tokens and
75
+ * each user's tenant and role, so only a service caller reaches their routes;
76
+ * a signed-in user gets a 403. No other entity's controller joins onto them.
77
+ */
78
+ const AUTH_ENTITY_ROUTES = new Set([<%~ it.authRoutes.map((r) => `'${r}'`).join(', ') %>]);
79
+ <% } %>
80
+
81
+ @Injectable()
82
+ export class ApiKeyGuard implements CanActivate {
83
+ private readonly keys: Buffer[];
84
+ private readonly jwks?: ReturnType<typeof createRemoteJWKSet>;
85
+ private readonly issuer = process.env.APSO_SERVICE_TOKEN_ISSUER;
86
+ private readonly serviceId = process.env.APSO_SERVICE_ID;
87
+ // The detailed 401 is for a developer's machine only: "apso dev" sets
88
+ // APSO_LOCAL, and Lambda ignores it.
89
+ private readonly local = process.env.APSO_LOCAL === '1' && !process.env.AWS_LAMBDA_FUNCTION_NAME;
90
+
91
+ constructor(
92
+ private reflector: Reflector,
93
+ <% if (it.hasAuth) { %>
94
+ private authGuard: AuthGuard,
95
+ <% } %>
96
+ ) {
97
+ this.keys = (process.env.APSO_API_KEY || '')
98
+ .split(',')
99
+ .map((key) => key.trim())
100
+ .filter(Boolean)
101
+ .map(sha256);
102
+ const jwksUrl = process.env.APSO_SERVICE_TOKEN_JWKS_URL;
103
+ if (this.keys.length > 0) {
104
+ console.log(`[apso] API keys: checked against APSO_API_KEY (${this.keys.length} set)`);
105
+ } else if (jwksUrl) {
106
+ this.jwks = createRemoteJWKSet(new URL(jwksUrl));
107
+ console.log('[apso] API keys: checked by the platform gateway (APSO_SERVICE_TOKEN_JWKS_URL)');
108
+ if (!this.issuer || !this.serviceId) {
109
+ console.warn('[apso] WARNING: APSO_SERVICE_TOKEN_ISSUER and APSO_SERVICE_ID must both be set; until then every API key is refused.');
110
+ }
111
+ } else {
112
+ console.log('[apso] API keys: off (neither APSO_API_KEY nor APSO_SERVICE_TOKEN_JWKS_URL is set)');
113
+ <% if (!it.hasAuth) { %>
114
+ console.warn(`[apso] WARNING: ${NO_SOURCE}`);
115
+ <% } %>
116
+ }
117
+ }
118
+
119
+ async canActivate(context: ExecutionContext): Promise<boolean> {
120
+ const http = context.switchToHttp();
121
+ const request = http.getRequest();
122
+ http.getResponse().setHeader('x-request-id', this.requestId(request));
123
+
124
+ const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
125
+ context.getHandler(),
126
+ context.getClass(),
127
+ ]);
128
+ // The template's health check stays public for load balancer probes.
129
+ if (isPublic || (request.method === 'GET' && /^\/health\/?$/.test(request.path))) {
130
+ return true;
131
+ }
132
+
133
+ if (await this.serviceCaller(request)) {
134
+ return true;
135
+ }
136
+ <% if (it.hasAuth) { %>
137
+ // No key on the request: the caller has to be a signed-in user.
138
+ try {
139
+ await this.authGuard.canActivate(context);
140
+ } catch (error) {
141
+ if (error instanceof UnauthorizedException) {
142
+ this.refuse(
143
+ request,
144
+ `${error.message}. Send a signed-in user's token, or an API key in the x-api-key header.`,
145
+ error.message.toLowerCase(),
146
+ );
147
+ }
148
+ throw error;
149
+ }
150
+ <% if (it.authRoutes.length > 0) { %>
151
+ const route = String(request.route?.path || request.path).match(/^\/([^\/]+)/)?.[1];
152
+ if (route && AUTH_ENTITY_ROUTES.has(route.toLowerCase())) {
153
+ // The log line names the signed-in user that was refused.
154
+ this.userCaller(request);
155
+ request.apso = { ...request.apso, denied: 'auth entity, service callers only' };
156
+ throw new ForbiddenException('This route is for service callers only');
157
+ }
158
+ <% } %>
159
+ return this.userCaller(request);
160
+ <% } else { %>
161
+ if (this.keys.length > 0 || this.jwks) {
162
+ this.refuse(request, NO_CREDENTIAL, 'no credential');
163
+ }
164
+ this.refuse(request, NO_SOURCE, 'no key source');
165
+ <% } %>
166
+ }
167
+ <% if (it.mcpAuth) { %>
168
+
169
+ /** The same check for a request outside the guard chain (the /mcp endpoint). */
170
+ async authenticate(request: any): Promise<unknown> {
171
+ this.requestId(request);
172
+ if (await this.serviceCaller(request)) {
173
+ return request.auth;
174
+ }
175
+ const auth = await this.authGuard.authenticate(request);
176
+ this.userCaller(request);
177
+ return auth;
178
+ }
179
+ <% } %>
180
+ <% if (it.hasAuth) { %>
181
+
182
+ /** Record the signed-in user AuthGuard attached as the request's caller. */
183
+ private userCaller(request: any): true {
184
+ const auth = request.auth ?? {};
185
+ const clientId = auth.claims?.azp ?? auth.claims?.client_id;
186
+ request.apso = {
187
+ ...request.apso,
188
+ caller: { type: 'user', userId: auth.userId, tenantId: auth.workspaceId, ...(clientId ? { clientId } : {}) },
189
+ };
190
+ return true;
191
+ }
192
+ <% } %>
193
+
194
+ /**
195
+ * True when the request carries a valid key, false when it presents none.
196
+ * A key that fails the chosen source is refused here; no other source and
197
+ * no user token is tried.
198
+ */
199
+ private async serviceCaller(request: any): Promise<boolean> {
200
+ const key = request.headers['x-api-key'];
201
+ let serviceId: string | undefined;
202
+ if (this.keys.length > 0) {
203
+ if (!key) return false;
204
+ const digest = sha256(String(key));
205
+ // Every key is compared, in constant time.
206
+ const [match] = this.keys.filter((candidate) => timingSafeEqual(candidate, digest));
207
+ if (!match) this.refuse(request, WRONG_KEY, 'api key not recognised');
208
+ serviceId = match.toString('hex').slice(0, 8);
209
+ } else if (this.jwks) {
210
+ const token = request.headers['x-apso-service-token'];
211
+ if (!key && !token) return false;
212
+ serviceId = token ? await this.verifyServiceToken(String(token)) : undefined;
213
+ if (!serviceId) this.refuse(request, NO_SERVICE_TOKEN, 'no valid service token');
214
+ } else {
215
+ if (!key) return false;
216
+ this.refuse(request, KEYS_OFF, 'api keys are off');
217
+ }
218
+ const caller: ServiceCaller = { serviceId: serviceId as string, roles: [], permissions: [] };
219
+ request.auth = caller;
220
+ // The key's id, never the key.
221
+ request.apso = { ...request.apso, caller: { type: 'service', keyId: caller.serviceId } };
222
+ return true;
223
+ }
224
+
225
+ /** The key id from the gateway's token (sub "apikey:<id>"), when the token is valid for this service. */
226
+ private async verifyServiceToken(token: string): Promise<string | undefined> {
227
+ if (!this.jwks || !this.issuer || !this.serviceId) return undefined;
228
+ try {
229
+ const { payload } = await jwtVerify(token, this.jwks, {
230
+ issuer: this.issuer,
231
+ audience: this.serviceId,
232
+ algorithms: ['ES256'],
233
+ requiredClaims: ['exp', 'sub'],
234
+ });
235
+ const id = /^apikey:(.+)$/.exec(payload.sub as string)?.[1];
236
+ return id;
237
+ } catch {
238
+ return undefined;
239
+ }
240
+ }
241
+
242
+ /**
243
+ * The request id: the logging library's (request.apso.requestId) when it is
244
+ * installed, else the caller's x-request-id, else a new one.
245
+ */
246
+ private requestId(request: any): string {
247
+ const sent = request.apso?.requestId ?? request.headers['x-request-id'];
248
+ const id = typeof sent === 'string' && sent ? sent : randomUUID();
249
+ request.headers['x-request-id'] = id;
250
+ return id;
251
+ }
252
+
253
+ /** 401. The reason goes to the log, and to the caller only on a developer's machine. */
254
+ private refuse(request: any, reason: string, denied: string): never {
255
+ const requestId = request.headers['x-request-id'];
256
+ request.apso = { ...request.apso, denied };
257
+ console.warn(`[apso] 401 ${request.method} ${String(request.url).split('?')[0]} request=${requestId}: ${reason}`);
258
+ throw new UnauthorizedException({
259
+ statusCode: 401,
260
+ message: this.local ? reason : 'Unauthorized',
261
+ requestId,
262
+ });
263
+ }
264
+ }
265
+ <% if (it.mcpAuth) { %>
266
+
267
+ /**
268
+ * Sign-in settings @apso/mcp reads (its MCP_AUTH token). An MCP client that
269
+ * calls /mcp without a valid token or key is pointed at the identity
270
+ * provider, and every MCP request meets the same check as the REST API.
271
+ */
272
+ export const McpAuthProvider = {
273
+ provide: 'APSO_MCP_AUTH',
274
+ inject: [ApiKeyGuard],
275
+ useFactory: (guard: ApiKeyGuard) => ({
276
+ ...MCP_SIGN_IN,
277
+ verify: (request: any) => guard.authenticate(request),
278
+ }),
279
+ };
280
+ <% } %>
@@ -0,0 +1,168 @@
1
+ <%~ includeFile('../header.eta') %>
2
+
3
+ import {
4
+ Injectable,
5
+ CanActivate,
6
+ ExecutionContext,
7
+ ForbiddenException,
8
+ SetMetadata,
9
+ } from '@nestjs/common';
10
+ import { Reflector } from '@nestjs/core';
11
+ <% if (it.permissions.grants) { %>
12
+ import { DataSource, In, IsNull } from 'typeorm';
13
+ <% } %>
14
+ import { IS_PUBLIC_KEY } from './auth.guard';
15
+
16
+ type Operation = 'read' | 'create' | 'update' | 'delete';
17
+
18
+ /** A guarded operation: its permission name and the roles that have it by default. */
19
+ interface Rule {
20
+ permission: string;
21
+ roles: string[];
22
+ }
23
+
24
+ /**
25
+ * Guarded operations by route, from .apsorc permissions. An operation that is
26
+ * not listed is open to any authenticated caller.
27
+ */
28
+ export const ENTITY_PERMISSIONS: Record<string, Partial<Record<Operation, Rule>>> = <%~ JSON.stringify(it.permissions.routes, null, 2) %>;
29
+
30
+ /**
31
+ * Read rules a loaded relation must satisfy, by relation name, so a caller who
32
+ * cannot read an entity cannot read it through another entity's route either.
33
+ */
34
+ const JOIN_PERMISSIONS: Record<string, Rule[]> = <%~ JSON.stringify(it.permissions.joins, null, 2) %>;
35
+
36
+ export const PERMISSION_KEY = 'apsoPermission';
37
+
38
+ /**
39
+ * Names the permission a hand-written route needs and the roles that have it
40
+ * by default: @Permission('invoice:approve', 'admin') on
41
+ * POST /invoices/:id/approve. On a controller class it covers every route in
42
+ * it. Without it a route is checked as its entity's read, create, update or
43
+ * delete, by path and HTTP method.
44
+ */
45
+ export const Permission = (permission: string, ...roles: string[]) =>
46
+ SetMetadata(PERMISSION_KEY, { permission, roles });
47
+
48
+ const OPERATIONS: Record<string, Operation> = {
49
+ GET: 'read',
50
+ HEAD: 'read',
51
+ POST: 'create',
52
+ PUT: 'update',
53
+ PATCH: 'update',
54
+ DELETE: 'delete',
55
+ };
56
+
57
+ /**
58
+ * PermissionGuard - runs after ApiKeyGuard. A user may perform a guarded
59
+ * operation when any of these holds:
60
+ * - one of its roles is in the .apsorc default list
61
+ * - its token carries the permission (e.g. Auth0 RBAC "permissions")
62
+ <% if (it.permissions.grants) { %>
63
+ * - a <%= it.permissions.grants.entity %> row grants the permission to one of its roles<% if (it.permissions.grants.tenantField) { %>
64
+ * in its tenant (or in every tenant, when <%= it.permissions.grants.tenantField %> is null)<% } %>
65
+
66
+ <% } %>
67
+ * Grants only add access; they never take away a default.
68
+ * Every interface that calls this API (REST, SDK, MCP) goes through it.
69
+ */
70
+ @Injectable()
71
+ export class PermissionGuard implements CanActivate {
72
+ constructor(
73
+ private reflector: Reflector,
74
+ <% if (it.permissions.grants) { %>
75
+ private dataSource: DataSource,
76
+ <% } %>
77
+ ) {}
78
+
79
+ async canActivate(context: ExecutionContext): Promise<boolean> {
80
+ const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
81
+ context.getHandler(),
82
+ context.getClass(),
83
+ ]);
84
+ if (isPublic) {
85
+ return true;
86
+ }
87
+
88
+ const request = context.switchToHttp().getRequest();
89
+ // A service caller (valid API key) is not limited by role.
90
+ if (request.auth?.serviceId) {
91
+ return true;
92
+ }
93
+ const path: string = request.route?.path || request.path;
94
+ const entity = path.match(/^\/([^\/]+)/)?.[1]?.toLowerCase();
95
+ const operation = OPERATIONS[request.method];
96
+ const rule =
97
+ this.reflector.getAllAndOverride<Rule>(PERMISSION_KEY, [
98
+ context.getHandler(),
99
+ context.getClass(),
100
+ ]) ?? (entity && operation ? ENTITY_PERMISSIONS[entity]?.[operation] : undefined);
101
+ if (rule && !(await this.allowed(request, rule))) {
102
+ this.deny(request, rule.permission);
103
+ }
104
+
105
+ return true;
106
+ }
107
+
108
+ /**
109
+ * The read rules of every relation a request loads. Called by RelationAccess
110
+ * (relations.interceptor.ts) with the parsed request's relation paths
111
+ * (projects.tasks), whatever query syntax named them.
112
+ */
113
+ async checkRelations(request: any, paths: string[]): Promise<void> {
114
+ for (const path of paths) {
115
+ for (const relation of path.split('.')) {
116
+ for (const joined of JOIN_PERMISSIONS[relation] ?? []) {
117
+ if (!(await this.allowed(request, joined))) {
118
+ this.deny(request, joined.permission);
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }
124
+
125
+ /** 403, with the reason on request.apso.denied for the log. */
126
+ private deny(request: any, permission: string): never {
127
+ request.apso = { ...request.apso, denied: `missing permission ${permission}` };
128
+ throw new ForbiddenException(`Missing permission ${permission}`);
129
+ }
130
+
131
+ private async allowed(request: any, rule: Rule): Promise<boolean> {
132
+ const roles: string[] = request.auth?.roles ?? [];
133
+ if (rule.roles.some((role) => roles.includes(role))) {
134
+ return true;
135
+ }
136
+ return (await this.granted(request)).has(rule.permission);
137
+ }
138
+
139
+ /** The caller's permissions from its token and grants, loaded once per request. */
140
+ private async granted(request: any): Promise<Set<string>> {
141
+ if (request.apsoPermissions) {
142
+ return request.apsoPermissions;
143
+ }
144
+ const granted = new Set<string>(request.auth?.permissions ?? []);
145
+ <% if (it.permissions.grants) { %>
146
+ const roles: string[] = request.auth?.roles ?? [];
147
+ if (roles.length > 0) {
148
+ <% if (it.permissions.grants.tenantField) { %>
149
+ const tenant = request.auth?.workspaceId;
150
+ const where: any[] = [{ role: In(roles), <%= it.permissions.grants.tenantField %>: IsNull() }];
151
+ if (tenant != null) {
152
+ where.push({ role: In(roles), <%= it.permissions.grants.tenantField %>: tenant });
153
+ }
154
+ <% } else { %>
155
+ const where: any = { role: In(roles) };
156
+ <% } %>
157
+ // ponytail: one query per guarded request; cache per role and tenant
158
+ // with a short TTL if this shows up in latency.
159
+ const rows = await this.dataSource
160
+ .getRepository('<%= it.permissions.grants.entity %>')
161
+ .find({ select: { permission: true } as any, where });
162
+ rows.forEach((row: any) => granted.add(row.permission));
163
+ }
164
+ <% } %>
165
+ request.apsoPermissions = granted;
166
+ return granted;
167
+ }
168
+ }
@@ -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
+ }