@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
@@ -3,38 +3,47 @@
3
3
  """
4
4
  Authentication for every route on the generated /api router.
5
5
 
6
+ The API key check is built into every Apso service and is not configurable in
7
+ .apsorc. The key source is chosen once, when the service starts, first match
8
+ wins:
9
+ 1. APSO_API_KEY is set: the x-api-key header must match it. The variable holds
10
+ the key itself (not a hash); several keys separated by commas are accepted,
11
+ so a key can be rotated without downtime.
12
+ 2. APSO_SERVICE_TOKEN_JWKS_URL is set: the platform's gateway has checked the
13
+ key and sends a signed token in x-apso-service-token.
14
+ 3. Neither: API keys are off and only signed-in users are accepted. A service
15
+ with no sign-in configured then refuses every request.
16
+
17
+ A caller with a valid key is a service caller (AuthContext.service_id): it may
18
+ call any route and is not tenant-scoped. A request whose key fails is refused,
19
+ whatever else it carries.
6
20
  <% if (it.jwt) { %>
7
- Verifies <%= it.jwt.provider %> JWTs from the Authorization: Bearer header against the
8
- issuer's published keys (JWKS), checks issuer, expiry<% if (it.jwt.audience) { %>, audience<% } %> and algorithm,
9
- and maps the token's claims into an AuthContext on request.state.auth.
10
- AUTH_JWT_ISSUER, AUTH_JWT_AUDIENCE and AUTH_JWKS_URI override the .apsorc values.
11
- <% } else { %>
12
- Reads an API key from the <%= it.apiKey.apiKeyHeader %> header and looks up the <%= it.apiKey.apiKeyEntity %> row
13
- whose <%= it.apiKey.keyField %> is the key's hex SHA-256.
21
+
22
+ A request with no key needs a <%= it.jwt.map((p) => p.provider).join(', ') %> JWT in the Authorization: Bearer header.
23
+ The token's iss claim picks the provider; a token from an issuer that is not
24
+ configured is refused. It is verified against that issuer's published keys
25
+ (JWKS) with issuer, expiry, audience (when one is configured) and algorithm
26
+ checked; its claims, by that provider's claim names, become the AuthContext on
27
+ request.state.auth.
28
+ AUTH_JWT_ISSUER, AUTH_JWT_AUDIENCE, AUTH_JWKS_URI and AUTH_JWT_AUTHORIZED_PARTIES
29
+ override the .apsorc values. With several providers they set the first; the
30
+ second reads the same names ending in _2 (AUTH_JWT_ISSUER_2), and so on.
14
31
  <% } %>
15
32
  """
16
- <% if (it.apiKey) { %>
17
33
  import hashlib
18
- from datetime import date, datetime, timezone
19
- <% } else { %>
34
+ import hmac
35
+ import json
20
36
  import os
21
- <% } %>
37
+ import uuid
22
38
  from dataclasses import dataclass, field
23
- from typing import Any, List, Optional
39
+ from typing import Any, List, NoReturn, Optional
40
+ from urllib.parse import urlsplit
24
41
 
25
- <% if (it.jwt) { %>
26
42
  import jwt
27
- from fastapi import HTTPException, Request, status
43
+ from fastapi import HTTPException, Request, Response, status
28
44
  from jwt import PyJWKClient
45
+ from sqlalchemy import String, cast, func, select
29
46
  from starlette.concurrency import run_in_threadpool
30
- <% } else { %>
31
- from fastapi import Depends, HTTPException, Request, status
32
- from sqlalchemy import select
33
- from sqlalchemy.ext.asyncio import AsyncSession
34
-
35
- from app.database import get_db
36
- from .models.<%= it.apiKey.pyModule %> import <%= it.apiKey.apiKeyEntity %>
37
- <% } %>
38
47
 
39
48
 
40
49
  @dataclass
@@ -47,6 +56,11 @@ class AuthContext:
47
56
  workspace_id: Optional[str] = None
48
57
  organization_id: Optional[str] = None
49
58
  roles: List[str] = field(default_factory=list)
59
+ # The issuer that signed the caller in, and its provider type in .apsorc.
60
+ issuer: Optional[str] = None
61
+ provider: Optional[str] = None
62
+ # Permission strings from the token ("invoice:delete"), read by permissions.py.
63
+ permissions: List[str] = field(default_factory=list)
50
64
  claims: dict = field(default_factory=dict)
51
65
 
52
66
 
@@ -60,20 +74,48 @@ def _unauthorized(detail: str) -> HTTPException:
60
74
  <% if (it.jwt) { %>
61
75
 
62
76
 
63
- ISSUER = os.getenv("AUTH_JWT_ISSUER") or <%~ JSON.stringify(it.jwt.issuer) %>
64
- AUDIENCE = os.getenv("AUTH_JWT_AUDIENCE") or <%~ JSON.stringify(it.jwt.audience || '') %>
65
- JWKS_URI = os.getenv("AUTH_JWKS_URI") or <%~ JSON.stringify(it.jwt.jwksUri) %>
66
- ALGORITHMS = <%~ JSON.stringify(it.jwt.algorithms) %>
67
- # Origins allowed in the azp claim; empty allows any.
68
- AUTHORIZED_PARTIES = [
69
- p.strip()
70
- for p in (os.getenv("AUTH_JWT_AUTHORIZED_PARTIES") or <%~ JSON.stringify(it.jwt.authorizedParties.join(',')) %>).split(",")
71
- if p.strip()
72
- ]
73
- CLAIMS = <%~ JSON.stringify(it.jwt.claims) %>
77
+ _CONFIGURED = <%~ JSON.stringify(it.jwt) %>
78
+
79
+ <% if (it.mcp) { %>
80
+ # The public URL of the MCP endpoint (see mcp.py). An MCP client asks the
81
+ # identity provider for a token for this URL, so it is an accepted audience
82
+ # next to a provider's own. No configured audience means none is checked.
83
+ MCP_RESOURCE = os.getenv("MCP_RESOURCE_URL") or ""
84
+ <% } else { %>
85
+ MCP_RESOURCE = ""
86
+ <% } %>
87
+
74
88
 
75
- # Fetches and caches the issuer's keys on first use.
76
- _jwks = PyJWKClient(JWKS_URI, cache_keys=True)
89
+ def _provider(i: int, p: dict) -> dict:
90
+ """One trusted issuer: its own keys, audience and claim names."""
91
+ # The first provider reads AUTH_JWT_ISSUER, the second AUTH_JWT_ISSUER_2, and so on.
92
+ s = "" if i == 0 else f"_{i + 1}"
93
+ parties = os.getenv(f"AUTH_JWT_AUTHORIZED_PARTIES{s}") or ",".join(p["authorizedParties"])
94
+ issuer = os.getenv(f"AUTH_JWT_ISSUER{s}") or p["issuer"]
95
+ # Better Auth: the OAuth provider signs with the base URL, the JWT plugin
96
+ # with its origin as iss and aud. Both are this provider, with the same keys.
97
+ origin = "{0.scheme}://{0.netloc}".format(urlsplit(issuer)) if p["provider"] == "better-auth" else ""
98
+ return {
99
+ "provider": p["provider"],
100
+ "issuer": issuer,
101
+ "issuers": {issuer, origin} if origin else {issuer},
102
+ "audience": os.getenv(f"AUTH_JWT_AUDIENCE{s}") or p.get("audience") or origin,
103
+ # Fetches and caches the issuer's keys on first use.
104
+ "jwks": PyJWKClient(os.getenv(f"AUTH_JWKS_URI{s}") or p["jwksUri"], cache_keys=True),
105
+ "algorithms": p["algorithms"],
106
+ # Origins allowed in the azp claim; empty allows any.
107
+ "authorized_parties": [x.strip() for x in parties.split(",") if x.strip()],
108
+ "claims": p["claims"],
109
+ }
110
+
111
+
112
+ _PROVIDERS = [_provider(i, p) for i, p in enumerate(_CONFIGURED)]
113
+ PROVIDERS = {issuer: p for p in _PROVIDERS for issuer in p["issuers"]}
114
+ if len(PROVIDERS) != sum(len(p["issuers"]) for p in _PROVIDERS):
115
+ # The token's iss picks the provider, so two providers cannot share one.
116
+ raise RuntimeError(
117
+ "[apso] Two auth providers have the same issuer. Check AUTH_JWT_ISSUER and its numbered variants."
118
+ )
77
119
 
78
120
 
79
121
  def _claim(payload: dict, path: Optional[str]) -> Any:
@@ -104,14 +146,31 @@ def _roles(value: Any) -> List[str]:
104
146
  return [value] if isinstance(value, str) and value else []
105
147
 
106
148
 
107
- async def require_auth(request: Request) -> AuthContext:
108
- """FastAPI dependency: verify the bearer token and attach the AuthContext."""
149
+ async def _require_user(request: Request) -> AuthContext:
150
+ """Verify the bearer token and return the signed-in user's AuthContext."""
109
151
  header = request.headers.get("authorization", "")
110
152
  if not header.startswith("Bearer "):
111
153
  raise _unauthorized("No bearer token provided")
112
154
  token = header[len("Bearer "):]
155
+ # The token's own issuer picks the provider, before anything is verified;
156
+ # then only that provider's keys and settings are used.
157
+ try:
158
+ iss = jwt.decode(token, options={"verify_signature": False}).get("iss")
159
+ except jwt.PyJWTError:
160
+ raise _unauthorized("Invalid token")
161
+ p = PROVIDERS.get(iss) if isinstance(iss, str) else None
162
+ if p is None:
163
+ raise _unauthorized("Invalid token")
164
+ AUDIENCE, CLAIMS, cognito = p["audience"], p["claims"], p["provider"] == "cognito"
165
+ audiences = [a for a in (AUDIENCE, MCP_RESOURCE) if a] if AUDIENCE else []
166
+ <% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
167
+ # Better Auth signs both kinds of token with one key: only an OAuth access
168
+ # token (header type at+jwt) may be one issued for the MCP URL.
169
+ if p["provider"] == "better-auth" and jwt.get_unverified_header(token).get("typ") != "at+jwt":
170
+ audiences = [AUDIENCE]
171
+ <% } %>
113
172
  try:
114
- signing_key = await run_in_threadpool(_jwks.get_signing_key_from_jwt, token)
173
+ signing_key = await run_in_threadpool(p["jwks"].get_signing_key_from_jwt, token)
115
174
  except jwt.PyJWKClientConnectionError:
116
175
  raise HTTPException(
117
176
  status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
@@ -123,27 +182,29 @@ async def require_auth(request: Request) -> AuthContext:
123
182
  payload = jwt.decode(
124
183
  token,
125
184
  signing_key.key,
126
- algorithms=ALGORITHMS,
127
- issuer=ISSUER,
128
- <% if (it.jwt.provider !== 'cognito') { %>
129
- audience=AUDIENCE or None,
130
- options={"require": ["exp", "iss"], "verify_aud": bool(AUDIENCE)},
131
- <% } else { %>
132
- options={"require": ["exp", "iss"], "verify_aud": False},
133
- <% } %>
185
+ algorithms=p["algorithms"],
186
+ issuer=iss,
187
+ # Cognito's audience is checked below.
188
+ audience=None if cognito else audiences or None,
189
+ options={"require": ["exp", "iss"], "verify_aud": bool(AUDIENCE) and not cognito},
134
190
  )
135
191
  except jwt.PyJWTError:
136
192
  raise _unauthorized("Invalid token")
137
- <% if (it.jwt.provider === 'cognito') { %>
193
+ <% if (it.jwt.some((p) => p.provider === 'cognito')) { %>
138
194
  # Cognito ID tokens carry aud; access tokens carry client_id instead.
139
- if AUDIENCE:
195
+ if cognito and AUDIENCE:
140
196
  aud = payload.get("aud", payload.get("client_id"))
141
- if not (AUDIENCE in aud if isinstance(aud, list) else aud == AUDIENCE):
197
+ if not set(aud if isinstance(aud, list) else [aud]) & set(audiences):
142
198
  raise _unauthorized("Invalid token")
143
199
  <% } %>
144
200
 
145
201
  azp = payload.get("azp")
146
- if AUTHORIZED_PARTIES and azp is not None and azp not in AUTHORIZED_PARTIES:
202
+ <% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
203
+ # Better Auth's OAuth access tokens (header type at+jwt) name their client in azp.
204
+ if p["provider"] == "better-auth" and jwt.get_unverified_header(token).get("typ") == "at+jwt" and not isinstance(azp, str):
205
+ raise _unauthorized("Invalid token")
206
+ <% } %>
207
+ if p["authorized_parties"] and azp is not None and azp not in p["authorized_parties"]:
147
208
  raise _unauthorized("Invalid token")
148
209
 
149
210
  user_id = _str(_claim(payload, CLAIMS.get("userId")))
@@ -158,60 +219,258 @@ async def require_auth(request: Request) -> AuthContext:
158
219
  workspace_id=tenant,
159
220
  organization_id=tenant,
160
221
  roles=_roles(_claim(payload, CLAIMS.get("roles"))),
222
+ issuer=iss,
223
+ provider=p["provider"],
224
+ permissions=_roles(_claim(payload, CLAIMS.get("permissions"))),
161
225
  claims=payload,
162
226
  )
163
- request.state.auth = ctx
164
227
  return ctx
165
- <% } else { %>
228
+ <% } %>
229
+
230
+
231
+ NO_SOURCE = (
232
+ "This service has no API key source and no sign-in configured, so it refuses every request. "
233
+ 'Set APSO_API_KEY in its environment; "apso dev" creates a development key in .env.'
234
+ )
235
+ NO_CREDENTIAL = "No credential on the request. Send the API key in the x-api-key header."
236
+ WRONG_KEY = "The key in the x-api-key header does not match APSO_API_KEY."
237
+ NO_SERVICE_TOKEN = (
238
+ "This service takes API keys through the platform gateway, and the request has no valid "
239
+ "x-apso-service-token. Call the service at its gateway URL with a key issued for it."
240
+ )
241
+ 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."
242
+ HAS_SIGN_IN = <%= it.jwt ? 'True' : 'False' %>
243
+
244
+ # The detailed 401 is for a developer's machine only: "apso dev" sets
245
+ # APSO_LOCAL, and Lambda ignores it.
246
+ LOCAL = os.getenv("APSO_LOCAL") == "1" and not os.getenv("AWS_LAMBDA_FUNCTION_NAME")
247
+
248
+ # The key source, chosen once at start-up.
249
+ _KEYS = [
250
+ hashlib.sha256(k.strip().encode()).digest()
251
+ for k in os.getenv("APSO_API_KEY", "").split(",")
252
+ if k.strip()
253
+ ]
254
+ _SERVICE_JWKS_URL = "" if _KEYS else os.getenv("APSO_SERVICE_TOKEN_JWKS_URL", "")
255
+ _SERVICE_JWKS = PyJWKClient(_SERVICE_JWKS_URL, cache_keys=True) if _SERVICE_JWKS_URL else None
256
+ _SERVICE_ISSUER = os.getenv("APSO_SERVICE_TOKEN_ISSUER", "")
257
+ _SERVICE_ID = os.getenv("APSO_SERVICE_ID", "")
258
+
259
+ if _KEYS:
260
+ print(f"[apso] API keys: checked against APSO_API_KEY ({len(_KEYS)} set)", flush=True)
261
+ elif _SERVICE_JWKS:
262
+ print("[apso] API keys: checked by the platform gateway (APSO_SERVICE_TOKEN_JWKS_URL)", flush=True)
263
+ if not (_SERVICE_ISSUER and _SERVICE_ID):
264
+ print(
265
+ "[apso] WARNING: APSO_SERVICE_TOKEN_ISSUER and APSO_SERVICE_ID must both be set; "
266
+ "until then every API key is refused.",
267
+ flush=True,
268
+ )
269
+ else:
270
+ print("[apso] API keys: off (neither APSO_API_KEY nor APSO_SERVICE_TOKEN_JWKS_URL is set)", flush=True)
271
+ if not HAS_SIGN_IN:
272
+ print(f"[apso] WARNING: {NO_SOURCE}", flush=True)
166
273
 
167
274
 
168
- def _expired(value: Any) -> bool:
169
- if value is None:
170
- return False
171
- if isinstance(value, datetime):
172
- if value.tzinfo is None:
173
- value = value.replace(tzinfo=timezone.utc)
174
- return value <= datetime.now(timezone.utc)
175
- if isinstance(value, date):
176
- return value <= date.today()
177
- return False
178
-
179
-
180
- async def require_auth(request: Request, db: AsyncSession = Depends(get_db)) -> AuthContext:
181
- """FastAPI dependency: authenticate the API key and attach the AuthContext."""
182
- key = request.headers.get(<%~ JSON.stringify(it.apiKey.apiKeyHeader) %>)
183
- if not key:
184
- raise _unauthorized("No API key provided")
185
- digest = hashlib.sha256(key.encode()).hexdigest()
186
- result = await db.execute(
187
- select(<%= it.apiKey.apiKeyEntity %>).where(<%= it.apiKey.apiKeyEntity %>.<%= it.apiKey.keyField %> == digest)
275
+ def _refuse(request: Request, reason: str) -> NoReturn:
276
+ """401. The reason goes to the log, and to the caller only on a developer's machine."""
277
+ request_id = request.state.request_id
278
+ print(f"[apso] 401 {request.method} {request.url.path} request={request_id}: {reason}", flush=True)
279
+ raise HTTPException(
280
+ status_code=status.HTTP_401_UNAUTHORIZED,
281
+ detail={"message": reason if LOCAL else "Unauthorized", "requestId": request_id},
282
+ headers={"x-request-id": request_id},
188
283
  )
189
- record = result.scalar_one_or_none()
190
- if record is None:
191
- raise _unauthorized("Invalid API key")
192
- <% if (it.apiKey.hasStatus) { %>
193
- if getattr(record.status, "value", record.status) != "active":
194
- raise _unauthorized("API key is not active")
284
+
285
+
286
+ def _service_token_key_id(token: str) -> Optional[str]:
287
+ """The key id from the gateway's token (sub "apikey:<id>"), when the token is valid for this service."""
288
+ if not (_SERVICE_JWKS and _SERVICE_ISSUER and _SERVICE_ID):
289
+ return None
290
+ try:
291
+ signing_key = _SERVICE_JWKS.get_signing_key_from_jwt(token)
292
+ payload = jwt.decode(
293
+ token,
294
+ signing_key.key,
295
+ algorithms=["ES256"],
296
+ issuer=_SERVICE_ISSUER,
297
+ audience=_SERVICE_ID,
298
+ options={"require": ["exp", "iss", "aud", "sub"]},
299
+ )
300
+ except jwt.PyJWTError:
301
+ return None
302
+ sub = payload["sub"]
303
+ return sub[len("apikey:"):] or None if isinstance(sub, str) and sub.startswith("apikey:") else None
304
+
305
+
306
+ async def _service_caller(request: Request) -> Optional[AuthContext]:
307
+ """
308
+ The service caller when the request carries a valid key, None when it
309
+ presents none. A key that fails the chosen source is refused here; no
310
+ other source and no user token is tried.
311
+ """
312
+ key = request.headers.get("x-api-key")
313
+ if _KEYS:
314
+ if not key:
315
+ return None
316
+ digest = hashlib.sha256(key.encode()).digest()
317
+ # Every key is compared, in constant time.
318
+ matches = [k for k in _KEYS if hmac.compare_digest(k, digest)]
319
+ if not matches:
320
+ _refuse(request, WRONG_KEY)
321
+ key_id = matches[0].hex()[:8]
322
+ elif _SERVICE_JWKS:
323
+ token = request.headers.get("x-apso-service-token")
324
+ if not key and not token:
325
+ return None
326
+ key_id = await run_in_threadpool(_service_token_key_id, token) if token else None
327
+ if not key_id:
328
+ _refuse(request, NO_SERVICE_TOKEN)
329
+ else:
330
+ if not key:
331
+ return None
332
+ _refuse(request, KEYS_OFF)
333
+ return AuthContext(service_id=key_id)
334
+
335
+
336
+ <% if (it.jwt && it.authRoutes.length > 0) { %>
337
+ AUTH_ENTITY_ROUTES = {<%~ it.authRoutes.map((r) => JSON.stringify(r)).join(', ') %>}
338
+
339
+
195
340
  <% } %>
196
- <% if (it.apiKey.hasExpiresAt) { %>
197
- if _expired(record.expiresAt):
198
- raise _unauthorized("API key has expired")
341
+ async def require_auth(request: Request, response: Response) -> AuthContext:
342
+ """FastAPI dependency: accept a valid API key<% if (it.jwt) { %>, else a signed-in user<% } %>; attach the AuthContext."""
343
+ request_id = request.headers.get("x-request-id") or str(uuid.uuid4())
344
+ request.state.request_id = request_id
345
+ response.headers["x-request-id"] = request_id
346
+ ctx = await _service_caller(request)
347
+ if ctx is None:
348
+ <% if (it.jwt) { %>
349
+ try:
350
+ ctx = await _require_user(request)
351
+ except HTTPException as e:
352
+ if e.status_code != status.HTTP_401_UNAUTHORIZED:
353
+ raise
354
+ _refuse(request, f"{e.detail}. Send a signed-in user's token, or an API key in the x-api-key header.")
355
+ <% if (it.authRoutes.length > 0) { %>
356
+ # Auth entities are for service callers only.
357
+ if request.url.path.split("/")[2:3] and request.url.path.split("/")[2].lower() in AUTH_ENTITY_ROUTES:
358
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="This route is for service callers only")
199
359
  <% } %>
200
-
201
- tenant = getattr(record, <%~ JSON.stringify(it.apiKey.workspaceField) %>, None)
202
- tenant = str(tenant) if tenant is not None else None
203
- <% if (it.apiKey.roleField) { %>
204
- role = getattr(record, <%~ JSON.stringify(it.apiKey.roleField) %>, None)
205
- roles = [str(getattr(role, "value", role))] if role is not None else []
206
360
  <% } else { %>
207
- roles: List[str] = []
361
+ _refuse(request, NO_CREDENTIAL if _KEYS or _SERVICE_JWKS else NO_SOURCE)
208
362
  <% } %>
209
- ctx = AuthContext(
210
- service_id=str(record.id),
211
- workspace_id=tenant,
212
- organization_id=tenant,
213
- roles=roles,
214
- )
215
363
  request.state.auth = ctx
216
364
  return ctx
217
- <% } %>
365
+
366
+
367
+ # Every entity's relations, from .apsorc relationships and scopeBy:
368
+ # entity -> {"bypassRoles": the roles that skip its tenant scope (None when it
369
+ # is not scoped), "relations": {name: [the entity it loads, whether a caller
370
+ # limited to its tenant here stays in it there]}}.
371
+ RELATION_SCOPES: dict = json.loads(<%~ JSON.stringify(JSON.stringify(it.relationScopes)) %>)
372
+
373
+
374
+ def relation_refused(auth: Optional[AuthContext], root: str, path: str) -> Optional[str]:
375
+ """
376
+ The one place that decides which relations a request may load: the first
377
+ relation in `path` that would load rows outside the caller's tenant, if
378
+ any. The tenant filter limits only the entity a request starts from, so a
379
+ relation onto a tenant-scoped entity is loaded only when the caller holds a
380
+ role that skips that entity's scope, or is limited to its tenant on the
381
+ entity the relation starts from and the target is scoped by the same keys.
382
+ A service caller (valid API key) is not limited.
383
+ """
384
+ if not RELATION_SCOPES or (auth is not None and auth.service_id):
385
+ return None
386
+ roles = set(auth.roles) if auth is not None else set()
387
+
388
+ def skips(entity: Optional[dict]) -> bool:
389
+ return bool(entity and roles & set(entity.get("bypassRoles") or []))
390
+
391
+ start = RELATION_SCOPES.get(root)
392
+ for name in path.split("."):
393
+ hop = (start or {}).get("relations", {}).get(name)
394
+ if not hop:
395
+ return None
396
+ to = RELATION_SCOPES.get(hop[0]) or {}
397
+ in_tenant = hop[1] and start.get("bypassRoles") is not None and not skips(start)
398
+ if to.get("bypassRoles") is not None and not skips(to) and not in_tenant:
399
+ return name
400
+ start = to
401
+ return None
402
+
403
+
404
+ def tenant_values(auth: Optional[AuthContext], entity: str) -> Optional[dict]:
405
+ """
406
+ The caller's value for each scopeBy field of `entity`, or None when the
407
+ caller is not limited to a tenant there: the entity's reads are not
408
+ tenant-scoped, or the caller is a service caller or holds a role that
409
+ skips its scope.
410
+ """
411
+ scoped = RELATION_SCOPES.get(entity) or {}
412
+ if scoped.get("bypassRoles") is None or (auth is not None and auth.service_id):
413
+ return None
414
+ if auth is not None and set(auth.roles) & set(scoped["bypassRoles"]):
415
+ return None
416
+ by_key = {"userId": "user_id", "email": "email"}
417
+ return {
418
+ field: getattr(auth, by_key.get(key, "workspace_id"), None)
419
+ for field, key in (scoped.get("scope") or {}).items()
420
+ }
421
+
422
+
423
+ def _tenant_conditions(model: Any, values: dict) -> list:
424
+ """SQL conditions that keep rows of `model` to the caller's tenant (compared as text)."""
425
+ if any(v in (None, "") for v in values.values()):
426
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No tenant in the auth context")
427
+ return [cast(getattr(model, field), String) == str(value) for field, value in values.items()]
428
+
429
+
430
+ def relation_conditions(auth: Optional[AuthContext], root: str, name: str, target: Any) -> list:
431
+ """
432
+ The conditions the rows loaded through relation `name` of `root` must
433
+ meet. A relation the rule above allows because both ends are scoped by the
434
+ same keys still loads only rows of the caller's tenant, so a row that
435
+ points at another tenant's row does not carry it into a response.
436
+ """
437
+ hop = ((RELATION_SCOPES.get(root) or {}).get("relations") or {}).get(name)
438
+ # Only a hop the rule allows as a same-tenant one; any other is refused or not limited.
439
+ values = tenant_values(auth, hop[0]) if hop and hop[1] else None
440
+ return _tenant_conditions(target, values) if values else []
441
+
442
+
443
+ async def check_references(auth: Optional[AuthContext], db: Any, references: dict) -> None:
444
+ """
445
+ The one place that checks the foreign keys of a write (R8). `references`
446
+ maps a tenant-scoped entity to the ids a body names in foreign keys to it.
447
+ Every id must be a row the caller could read; otherwise 403. A key set to
448
+ null is not checked, and a service caller or a role that skips the
449
+ target's scope is not limited. One query per referenced entity.
450
+ """
451
+ from . import models
452
+
453
+ for entity, sent in references.items():
454
+ ids = {i for i in sent if i is not None}
455
+ values = tenant_values(auth, entity)
456
+ if not ids or values is None:
457
+ continue
458
+ model = getattr(models, entity)
459
+ found = await db.execute(
460
+ select(func.count()).select_from(model).where(model.id.in_(ids), *_tenant_conditions(model, values))
461
+ )
462
+ if found.scalar() != len(ids):
463
+ raise HTTPException(
464
+ status_code=status.HTTP_403_FORBIDDEN,
465
+ detail="You do not have access to a row this request references",
466
+ )
467
+
468
+
469
+ def check_relation(auth: Optional[AuthContext], root: str, path: str) -> None:
470
+ """403 when relation_refused names a relation in `path`."""
471
+ refused = relation_refused(auth, root, path)
472
+ if refused:
473
+ raise HTTPException(
474
+ status_code=status.HTTP_403_FORBIDDEN,
475
+ detail=f'The relation "{refused}" cannot be loaded from {root}: its rows are tenant-scoped',
476
+ )
@@ -1,11 +1,10 @@
1
1
  <%~ includeFile('./header.eta', it) %>
2
2
 
3
- <% if (it.hasAuth) { %>
4
3
  from fastapi import APIRouter, Depends
5
4
 
6
5
  from .auth import require_auth
7
- <% } else { %>
8
- from fastapi import APIRouter
6
+ <% if (it.permissions) { %>
7
+ from .permissions import require_permission
9
8
  <% } %>
10
9
 
11
10
  <% it.entities.forEach((entity) => { %>
@@ -13,11 +12,12 @@ from .routers.<%= entity.name.toLowerCase() %> import router as <%= entity.name.
13
12
  <% }) %>
14
13
 
15
14
  # Create main router for autogenerated endpoints
16
- <% if (it.hasAuth) { %>
17
- # Every route on this router requires authentication (.apsorc auth).
18
- autogen_router = APIRouter(prefix="/api", dependencies=[Depends(require_auth)])
15
+ # Every route on this router needs a valid API key or a signed-in user (see auth.py).
16
+ <% if (it.permissions) { %>
17
+ # Role permissions from .apsorc are checked after authentication (see permissions.py).
18
+ autogen_router = APIRouter(prefix="/api", dependencies=[Depends(require_auth), Depends(require_permission)])
19
19
  <% } else { %>
20
- autogen_router = APIRouter(prefix="/api")
20
+ autogen_router = APIRouter(prefix="/api", dependencies=[Depends(require_auth)])
21
21
  <% } %>
22
22
 
23
23
  # Include all entity routers