@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.
Files changed (82) 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 +49 -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/deploy/server-push.js +3 -1
  29. package/dist/lib/generators/go.d.ts +13 -1
  30. package/dist/lib/generators/go.js +144 -33
  31. package/dist/lib/generators/python.d.ts +3 -3
  32. package/dist/lib/generators/python.js +48 -24
  33. package/dist/lib/generators/typescript.d.ts +3 -5
  34. package/dist/lib/generators/typescript.js +78 -64
  35. package/dist/lib/guards.d.ts +111 -13
  36. package/dist/lib/guards.js +287 -23
  37. package/dist/lib/templates/go/handlers/handler.eta +8 -8
  38. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  39. package/dist/lib/templates/go/index-module.eta +8 -5
  40. package/dist/lib/templates/go/mcp.eta +307 -0
  41. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  42. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  43. package/dist/lib/templates/go/services/service.eta +37 -16
  44. package/dist/lib/templates/go/utils/query.eta +37 -2
  45. package/dist/lib/templates/guards/guards.module.eta +37 -29
  46. package/dist/lib/templates/guards/index.eta +4 -0
  47. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  48. package/dist/lib/templates/guards/key.guard.eta +280 -0
  49. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  50. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  51. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  52. package/dist/lib/templates/python/auth.eta +354 -95
  53. package/dist/lib/templates/python/index-module.eta +7 -7
  54. package/dist/lib/templates/python/mcp.eta +284 -0
  55. package/dist/lib/templates/python/models/model.eta +6 -5
  56. package/dist/lib/templates/python/permissions.eta +121 -0
  57. package/dist/lib/templates/python/routers/router.eta +39 -1
  58. package/dist/lib/templates/python/schemas/schema.eta +18 -5
  59. package/dist/lib/templates/python/services/service.eta +38 -15
  60. package/dist/lib/templates/python/utils/query.eta +52 -25
  61. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  62. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  63. package/dist/lib/templates/rest/service-rest.eta +3 -44
  64. package/dist/lib/types/auth.d.ts +84 -80
  65. package/dist/lib/types/auth.js +77 -60
  66. package/dist/lib/types/entity.d.ts +17 -9
  67. package/dist/lib/types/entity.js +3 -0
  68. package/dist/lib/types/index.d.ts +2 -2
  69. package/dist/lib/types/index.js +6 -5
  70. package/dist/lib/utils/crud-deps.d.ts +77 -6
  71. package/dist/lib/utils/crud-deps.js +197 -14
  72. package/dist/lib/utils/schema-convert.d.ts +20 -43
  73. package/dist/lib/utils/schema-convert.js +28 -78
  74. package/dist/lib/utils/template.d.ts +11 -0
  75. package/dist/lib/utils/template.js +36 -1
  76. package/dist/lib/verify/index.d.ts +6 -1
  77. package/dist/lib/verify/index.js +30 -13
  78. package/npm-shrinkwrap.json +2 -2
  79. package/oclif.manifest.json +36 -1
  80. package/package.json +1 -1
  81. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  82. package/dist/lib/templates/guards/auth.guard.eta +0 -233
@@ -1,16 +1,34 @@
1
1
  /**
2
- * AuthGuard - verifies <%= it.jwt.provider %> JWTs against the issuer's JWKS
2
+ * AuthGuard - verifies <%= it.jwt.map((p) => p.provider).join(', ') %> JWTs against the issuer's JWKS
3
3
  *
4
4
  * Auto-generated by Apso CLI from .apsorc auth configuration
5
5
  *
6
6
  * This guard:
7
7
  * - Reads the token from the Authorization: Bearer header
8
- * - Verifies its signature with the issuer's published keys, plus issuer,
9
- * expiry<% if (it.jwt.audience) { %>, audience<% } %> and algorithm
10
- * - Maps the token's claims into a normalized AuthContext on request.auth
8
+ * - Picks the provider whose issuer is the token's iss claim. A token from an
9
+ * issuer that is not configured is refused, and no other provider is tried
10
+ * - Verifies its signature with that issuer's published keys, plus issuer,
11
+ * expiry, audience (when one is configured) and algorithm
12
+ * - Maps the token's claims, by that provider's claim names, into a
13
+ * normalized AuthContext on request.auth
14
+ <% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
11
15
  *
12
- * AUTH_JWT_ISSUER, AUTH_JWT_AUDIENCE and AUTH_JWKS_URI override the .apsorc
13
- * values at runtime (for example a staging and a production tenant).
16
+ * Better Auth issues two kinds of token, signed with the same keys:
17
+ * - The JWT plugin's token, which the app's own front end sends. Its iss and
18
+ * aud are Better Auth's baseURL option, normally the origin of the URL in
19
+ * .apsorc, so that origin is accepted as an issuer and is the default
20
+ * audience (AUTH_JWT_AUDIENCE or auth.jwt.audience changes it).
21
+ * - An OAuth access token (header type at+jwt) issued to an MCP client. Its
22
+ * iss is the URL in .apsorc and its aud is the resource it was issued for:
23
+ * MCP_RESOURCE_URL, or the audience above. It must name its client in azp.
24
+ * A session cookie or session token is not a JWT and is refused.
25
+ <% } %>
26
+ *
27
+ * AUTH_JWT_ISSUER, AUTH_JWT_AUDIENCE, AUTH_JWKS_URI and
28
+ * AUTH_JWT_AUTHORIZED_PARTIES override the .apsorc values at runtime (for
29
+ * example a staging and a production tenant). With several providers they
30
+ * set the first; the second reads the same names ending in _2
31
+ * (AUTH_JWT_ISSUER_2), and so on.
14
32
  *
15
33
  * DO NOT EDIT - Changes will be overwritten on next scaffold
16
34
  */
@@ -21,7 +39,7 @@ import {
21
39
  UnauthorizedException,
22
40
  } from '@nestjs/common';
23
41
  import { Reflector } from '@nestjs/core';
24
- import { createRemoteJWKSet, jwtVerify, JWTPayload } from 'jose';
42
+ import { createRemoteJWKSet, decodeJwt,<% if (it.jwt.some((p) => p.provider === 'better-auth')) { %> decodeProtectedHeader,<% } %> jwtVerify, JWTPayload } from 'jose';
25
43
 
26
44
  export const IS_PUBLIC_KEY = 'isPublic';
27
45
 
@@ -44,18 +62,51 @@ export interface AuthContext {
44
62
  workspaceId?: string;
45
63
  organizationId?: string;
46
64
  roles: string[];
65
+ /** Permission strings from the token ("invoice:delete"), read by PermissionGuard. */
66
+ permissions: string[];
67
+ /** The issuer that signed the caller in, and its provider type in .apsorc. */
68
+ issuer: string;
69
+ provider: string;
47
70
  claims: JWTPayload;
48
71
  }
49
72
 
50
- const ISSUER = process.env.AUTH_JWT_ISSUER || <%~ JSON.stringify(it.jwt.issuer) %>;
51
- const AUDIENCE = process.env.AUTH_JWT_AUDIENCE || <%~ JSON.stringify(it.jwt.audience || '') %>;
52
- const JWKS_URI = process.env.AUTH_JWKS_URI || <%~ JSON.stringify(it.jwt.jwksUri) %>;
53
- const ALGORITHMS = <%~ JSON.stringify(it.jwt.algorithms) %>;
54
- const AUTHORIZED_PARTIES = (process.env.AUTH_JWT_AUTHORIZED_PARTIES || <%~ JSON.stringify(it.jwt.authorizedParties.join(',')) %>)
55
- .split(',')
56
- .map((s) => s.trim())
57
- .filter(Boolean);
58
- const CLAIMS = <%~ JSON.stringify(it.jwt.claims) %> as Record<string, string | undefined>;
73
+ <% if (it.mcpAuth) { %>
74
+ // Public URL of the MCP endpoint (https://api.example.com/mcp). MCP clients ask
75
+ // the identity provider for a token for this URL, so it is an accepted audience.
76
+ const MCP_RESOURCE = process.env.MCP_RESOURCE_URL || '';
77
+ <% } else { %>
78
+ const MCP_RESOURCE = '';
79
+ <% } %>
80
+
81
+ /** One trusted issuer: its own keys, audience and claim names. */
82
+ const PROVIDERS = (<%~ JSON.stringify(it.jwt) %> as any[]).map((p, i) => {
83
+ // The first provider reads AUTH_JWT_ISSUER, the second AUTH_JWT_ISSUER_2, and so on.
84
+ const env = (name: string) => process.env[i === 0 ? name : `${name}_${i + 1}`];
85
+ const issuer = env('AUTH_JWT_ISSUER') || (p.issuer as string);
86
+ // Better Auth's JWT plugin signs with the origin of its URL as iss and aud.
87
+ const origin = p.provider === 'better-auth' ? new URL(issuer).origin : '';
88
+ const audience = env('AUTH_JWT_AUDIENCE') || p.audience || origin;
89
+ return {
90
+ provider: p.provider as string,
91
+ issuer,
92
+ issuers: origin ? [...new Set([issuer, origin])] : [issuer],
93
+ audience,
94
+ // No configured audience means none is checked (Clerk and Cognito tokens carry no aud).
95
+ audiences: audience ? [audience, MCP_RESOURCE].filter(Boolean) : [],
96
+ jwks: createRemoteJWKSet(new URL(env('AUTH_JWKS_URI') || p.jwksUri)),
97
+ algorithms: p.algorithms as string[],
98
+ authorizedParties: (env('AUTH_JWT_AUTHORIZED_PARTIES') || p.authorizedParties.join(','))
99
+ .split(',')
100
+ .map((s: string) => s.trim())
101
+ .filter(Boolean) as string[],
102
+ claims: p.claims as Record<string, string | undefined>,
103
+ };
104
+ });
105
+ const BY_ISSUER = new Map(PROVIDERS.flatMap((p) => p.issuers.map((issuer) => [issuer, p] as const)));
106
+ if (BY_ISSUER.size !== PROVIDERS.reduce((n, p) => n + p.issuers.length, 0)) {
107
+ // The token's iss picks the provider, so two providers cannot share one.
108
+ throw new Error('[apso] Two auth providers have the same issuer. Check AUTH_JWT_ISSUER and its numbered variants.');
109
+ }
59
110
 
60
111
  /** A claim by exact name (Auth0 namespaced URLs contain dots), else by dotted path. */
61
112
  function claim(payload: JWTPayload, path?: string): unknown {
@@ -74,8 +125,6 @@ function roles(v: unknown): string[] {
74
125
 
75
126
  @Injectable()
76
127
  export class AuthGuard implements CanActivate {
77
- private readonly jwks = createRemoteJWKSet(new URL(JWKS_URI));
78
-
79
128
  constructor(private reflector: Reflector) {}
80
129
 
81
130
  async canActivate(context: ExecutionContext): Promise<boolean> {
@@ -93,36 +142,61 @@ export class AuthGuard implements CanActivate {
93
142
  return true;
94
143
  }
95
144
 
96
- const request = context.switchToHttp().getRequest();
145
+ await this.authenticate(context.switchToHttp().getRequest());
146
+ return true;
147
+ }
148
+
149
+ /**
150
+ * Verify the request's bearer token and attach the caller to the request.
151
+ * Throws UnauthorizedException when the token is missing or not accepted.
152
+ */
153
+ async authenticate(request: any): Promise<AuthContext> {
97
154
  const header: string | undefined = request.headers.authorization;
98
155
  if (!header || !header.startsWith('Bearer ')) {
99
156
  throw new UnauthorizedException('No bearer token provided');
100
157
  }
101
158
 
159
+ const token = header.substring(7);
102
160
  let payload: JWTPayload;
161
+ let provider: (typeof PROVIDERS)[number] | undefined;
103
162
  try {
104
- ({ payload } = await jwtVerify(header.substring(7), this.jwks, {
105
- issuer: ISSUER,
106
- algorithms: ALGORITHMS,
107
- <% if (it.jwt.provider !== 'cognito') { %>
108
- audience: AUDIENCE || undefined,
163
+ // The token's own issuer picks the provider, before anything is
164
+ // verified; then only that provider's keys and settings are used.
165
+ const iss = decodeJwt(token).iss as string;
166
+ provider = BY_ISSUER.get(iss);
167
+ if (!provider) throw new Error('issuer not configured');
168
+ let audiences = provider.audiences;
169
+ <% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
170
+ // Better Auth: only an OAuth access token may be one issued for the MCP URL.
171
+ const accessToken = provider.provider === 'better-auth' && decodeProtectedHeader(token).typ === 'at+jwt';
172
+ if (provider.provider === 'better-auth' && !accessToken) audiences = [provider.audience];
109
173
  <% } %>
174
+ ({ payload } = await jwtVerify(token, provider.jwks, {
175
+ issuer: iss,
176
+ algorithms: provider.algorithms,
177
+ // Cognito's audience is checked below.
178
+ audience: provider.provider !== 'cognito' && audiences.length > 0 ? audiences : undefined,
110
179
  }));
180
+ <% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
181
+ if (accessToken && typeof (payload as any).azp !== 'string') throw new Error('access token without azp');
182
+ <% } %>
111
183
  } catch {
112
184
  throw new UnauthorizedException('Invalid token');
113
185
  }
114
- <% if (it.jwt.provider === 'cognito') { %>
186
+ const { authorizedParties, claims: CLAIMS } = provider;
187
+ <% if (it.jwt.some((p) => p.provider === 'cognito')) { %>
115
188
  // Cognito ID tokens carry aud; access tokens carry client_id instead.
116
- if (AUDIENCE) {
189
+ if (provider.provider === 'cognito' && provider.audiences.length > 0) {
117
190
  const aud = payload.aud ?? (payload as any).client_id;
118
- if (!(Array.isArray(aud) ? aud.includes(AUDIENCE) : aud === AUDIENCE)) {
191
+ const given: unknown[] = Array.isArray(aud) ? aud : [aud];
192
+ if (!given.some((value) => provider.audiences.includes(value as string))) {
119
193
  throw new UnauthorizedException('Invalid token');
120
194
  }
121
195
  }
122
196
  <% } %>
123
197
 
124
198
  const azp = (payload as any).azp;
125
- if (AUTHORIZED_PARTIES.length > 0 && azp !== undefined && !AUTHORIZED_PARTIES.includes(azp)) {
199
+ if (authorizedParties.length > 0 && azp !== undefined && !authorizedParties.includes(azp)) {
126
200
  throw new UnauthorizedException('Invalid token');
127
201
  }
128
202
 
@@ -139,6 +213,9 @@ export class AuthGuard implements CanActivate {
139
213
  workspaceId: tenant,
140
214
  organizationId: tenant,
141
215
  roles: roles(claim(payload, CLAIMS.roles)),
216
+ permissions: roles(claim(payload, CLAIMS.permissions)),
217
+ issuer: payload.iss as string,
218
+ provider: provider.provider,
142
219
  claims: payload,
143
220
  };
144
221
 
@@ -147,9 +224,17 @@ export class AuthGuard implements CanActivate {
147
224
  // Read by ScopeGuard's scope lookup.
148
225
  request.workspaceId = tenant;
149
226
  request.organizationId = tenant;
150
- return true;
227
+ return auth;
151
228
  }
152
229
  }
230
+ <% if (it.mcpAuth) { %>
231
+
232
+ /** Where MCP clients sign in. ApiKeyGuard adds the credential check for @apso/mcp. */
233
+ export const MCP_SIGN_IN = {
234
+ authorizationServers: PROVIDERS.map((p) => p.issuer),
235
+ resource: MCP_RESOURCE || undefined,
236
+ };
237
+ <% } %>
153
238
 
154
239
  /**
155
240
  * Helper function to get AuthContext from request
@@ -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
+ }