@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
@@ -4,49 +4,62 @@ package middleware
4
4
 
5
5
  // AuthMiddleware authenticates every route registered on the /api group.
6
6
  // Routes registered outside that group (such as /health) stay public.
7
- <% if (it.jwt) { %>
8
7
  //
9
- // It verifies <%= it.jwt.provider %> JWTs from the Authorization: Bearer header against the
10
- // issuer's published keys (JWKS), checks issuer, expiry<% if (it.jwt.audience) { %>, audience<% } %> and algorithm,
11
- // and maps the token's claims into an AuthContext.
12
- // AUTH_JWT_ISSUER, AUTH_JWT_AUDIENCE and AUTH_JWKS_URI override the .apsorc values.
13
- <% } else { %>
8
+ // The API key check is built into every Apso service and is not configurable
9
+ // in .apsorc. The key source is chosen once, when the service starts, first
10
+ // match wins:
11
+ // 1. APSO_API_KEY is set: the x-api-key header must match it. The variable
12
+ // holds the key itself (not a hash); several keys separated by commas are
13
+ // accepted, so a key can be rotated without downtime.
14
+ // 2. APSO_SERVICE_TOKEN_JWKS_URL is set: the platform's gateway has checked
15
+ // the key and sends a signed token in x-apso-service-token.
16
+ // 3. Neither: API keys are off and only signed-in users are accepted. A
17
+ // service with no sign-in configured then refuses every request.
18
+ //
19
+ // A caller with a valid key is a service caller (AuthContext.ServiceID): it may
20
+ // call any route and is not tenant-scoped. A request whose key fails is
21
+ // refused, whatever else it carries.
22
+ <% if (it.jwt) { %>
14
23
  //
15
- // It reads an API key from the <%= it.apiKey.apiKeyHeader %> header and looks up the
16
- // <%= it.apiKey.apiKeyEntity %> row whose <%= it.apiKey.keyField %> is the key's hex SHA-256.
24
+ // A request with no key needs a <%= it.jwt.map((p) => p.provider).join(', ') %> JWT in the Authorization: Bearer header.
25
+ // The token's iss claim picks the provider; a token from an issuer that is not
26
+ // configured is refused. It is verified against that issuer's published keys
27
+ // (JWKS) with issuer, expiry, audience (when one is configured) and algorithm
28
+ // checked; its claims, by that provider's claim names, become the AuthContext.
29
+ // AUTH_JWT_ISSUER, AUTH_JWT_AUDIENCE, AUTH_JWKS_URI and
30
+ // AUTH_JWT_AUTHORIZED_PARTIES override the .apsorc values. With several
31
+ // providers they set the first; the second reads the same names ending in _2
32
+ // (AUTH_JWT_ISSUER_2), and so on.
17
33
  <% } %>
18
34
 
19
35
  import (
20
36
  "context"
21
- <% if (it.jwt) { %>
22
- "encoding/json"
23
- <% } else { %>
37
+ "crypto/rand"
24
38
  "crypto/sha256"
39
+ "crypto/subtle"
25
40
  "encoding/hex"
26
- "fmt"
41
+ <% if (it.jwt) { %>
42
+ "encoding/json"
27
43
  <% } %>
44
+ "errors"
45
+ "fmt"
46
+ "log"
28
47
  "net/http"
29
- <% if (it.jwt) { %>
48
+ <% if (it.jwt && it.jwt.some((p) => p.provider === 'better-auth')) { %>
49
+ "net/url"
50
+ <% } %>
30
51
  "os"
52
+ "reflect"
53
+ <% if (it.jwt) { %>
31
54
  "strconv"
55
+ <% } %>
32
56
  "strings"
33
57
  "sync"
34
- <% } else if (it.apiKey.hasExpiresAt) { %>
35
- "time"
36
- <% } %>
37
58
 
38
- <% if (it.jwt) { %>
39
59
  "github.com/MicahParks/keyfunc/v3"
40
- <% } %>
41
60
  "github.com/gin-gonic/gin"
42
- <% if (it.jwt) { %>
43
61
  "github.com/golang-jwt/jwt/v5"
44
- <% } %>
45
62
  "gorm.io/gorm"
46
- <% if (it.apiKey) { %>
47
-
48
- "app/autogen/models"
49
- <% } %>
50
63
  )
51
64
 
52
65
  // AuthContext is the normalized identity of the caller.
@@ -57,6 +70,11 @@ type AuthContext struct {
57
70
  WorkspaceID string `json:"workspaceId,omitempty"`
58
71
  OrganizationID string `json:"organizationId,omitempty"`
59
72
  Roles []string `json:"roles"`
73
+ // The issuer that signed the caller in, and its provider type in .apsorc.
74
+ Issuer string `json:"issuer,omitempty"`
75
+ Provider string `json:"provider,omitempty"`
76
+ // Permission strings from the token ("invoice:delete"), read by PermissionMiddleware.
77
+ Permissions []string `json:"permissions,omitempty"`
60
78
  Claims map[string]interface{} `json:"claims,omitempty"`
61
79
  }
62
80
 
@@ -88,10 +106,31 @@ func GetAuthContext(c *gin.Context) (*AuthContext, bool) {
88
106
  return a, ok
89
107
  }
90
108
 
91
- func unauthorized(c *gin.Context, msg string) {
92
- c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": msg})
109
+ const (
110
+ noSource = `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.`
111
+ noCredential = "No credential on the request. Send the API key in the x-api-key header."
112
+ wrongKey = "The key in the x-api-key header does not match APSO_API_KEY."
113
+ noServiceToken = "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."
114
+ keysOff = "An x-api-key header was sent, but API keys are off on this service. Set APSO_API_KEY to turn them on."
115
+ hasSignIn = <%= it.jwt ? 'true' : 'false' %>
116
+
117
+ requestIDHeader = "x-request-id"
118
+ )
119
+
120
+ // The detailed 401 is for a developer's machine only: "apso dev" sets
121
+ // APSO_LOCAL, and Lambda ignores it.
122
+ var local = os.Getenv("APSO_LOCAL") == "1" && os.Getenv("AWS_LAMBDA_FUNCTION_NAME") == ""
123
+
124
+ // refuse answers 401. The reason goes to the log, and to the caller only on a
125
+ // developer's machine.
126
+ func refuse(c *gin.Context, reason string) {
127
+ id := c.Request.Header.Get(requestIDHeader)
128
+ log.Printf("[apso] 401 %s %s request=%s: %s", c.Request.Method, c.Request.URL.Path, id, reason)
129
+ if !local {
130
+ reason = "Unauthorized"
131
+ }
132
+ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": reason, "requestId": id})
93
133
  }
94
- <% if (it.jwt) { %>
95
134
 
96
135
  func splitList(s string) []string {
97
136
  out := []string{}
@@ -103,6 +142,182 @@ func splitList(s string) []string {
103
142
  return out
104
143
  }
105
144
 
145
+ // lazyJWKS fetches a JWKS on first use, retrying on later requests if the
146
+ // issuer was unreachable. keyfunc refreshes the set in the background.
147
+ type lazyJWKS struct {
148
+ url string
149
+ mu sync.Mutex
150
+ k keyfunc.Keyfunc
151
+ }
152
+
153
+ func (j *lazyJWKS) get() (keyfunc.Keyfunc, error) {
154
+ j.mu.Lock()
155
+ defer j.mu.Unlock()
156
+ if j.k != nil {
157
+ return j.k, nil
158
+ }
159
+ k, err := keyfunc.NewDefaultCtx(context.Background(), []string{j.url})
160
+ if err != nil {
161
+ return nil, err
162
+ }
163
+ j.k = k
164
+ return k, nil
165
+ }
166
+
167
+ // keySource is where API keys are checked, chosen once at start-up.
168
+ type keySource struct {
169
+ keys [][sha256.Size]byte
170
+ jwks *lazyJWKS
171
+ issuer string
172
+ serviceID string
173
+ }
174
+
175
+ func chooseKeySource() *keySource {
176
+ s := &keySource{
177
+ issuer: os.Getenv("APSO_SERVICE_TOKEN_ISSUER"),
178
+ serviceID: os.Getenv("APSO_SERVICE_ID"),
179
+ }
180
+ for _, k := range splitList(os.Getenv("APSO_API_KEY")) {
181
+ s.keys = append(s.keys, sha256.Sum256([]byte(k)))
182
+ }
183
+ switch url := os.Getenv("APSO_SERVICE_TOKEN_JWKS_URL"); {
184
+ case len(s.keys) > 0:
185
+ log.Printf("[apso] API keys: checked against APSO_API_KEY (%d set)", len(s.keys))
186
+ case url != "":
187
+ s.jwks = &lazyJWKS{url: url}
188
+ log.Print("[apso] API keys: checked by the platform gateway (APSO_SERVICE_TOKEN_JWKS_URL)")
189
+ if s.issuer == "" || s.serviceID == "" {
190
+ log.Print("[apso] WARNING: APSO_SERVICE_TOKEN_ISSUER and APSO_SERVICE_ID must both be set; until then every API key is refused.")
191
+ }
192
+ default:
193
+ log.Print("[apso] API keys: off (neither APSO_API_KEY nor APSO_SERVICE_TOKEN_JWKS_URL is set)")
194
+ if !hasSignIn {
195
+ log.Print("[apso] WARNING: " + noSource)
196
+ }
197
+ }
198
+ return s
199
+ }
200
+
201
+ // keyID returns the key id from the gateway's token (sub "apikey:<id>"), or ""
202
+ // when the token is not valid for this service.
203
+ func (s *keySource) keyID(token string) string {
204
+ if token == "" || s.issuer == "" || s.serviceID == "" {
205
+ return ""
206
+ }
207
+ k, err := s.jwks.get()
208
+ if err != nil {
209
+ return ""
210
+ }
211
+ claims := jwt.RegisteredClaims{}
212
+ parsed, err := jwt.ParseWithClaims(token, &claims, k.Keyfunc,
213
+ jwt.WithIssuer(s.issuer),
214
+ jwt.WithAudience(s.serviceID),
215
+ jwt.WithValidMethods([]string{"ES256"}),
216
+ jwt.WithExpirationRequired(),
217
+ )
218
+ if err != nil || !parsed.Valid {
219
+ return ""
220
+ }
221
+ id, _ := strings.CutPrefix(claims.Subject, "apikey:")
222
+ if id == claims.Subject {
223
+ return ""
224
+ }
225
+ return id
226
+ }
227
+
228
+ // serviceCaller returns the service caller when the request carries a valid
229
+ // key, and refused=true after answering 401 for a key that fails the chosen
230
+ // source; no other source and no user token is tried. Both are zero when the
231
+ // request presents no key.
232
+ func (s *keySource) serviceCaller(c *gin.Context) (caller *AuthContext, refused bool) {
233
+ key := c.GetHeader("x-api-key")
234
+ id := ""
235
+ switch {
236
+ case len(s.keys) > 0:
237
+ if key == "" {
238
+ return nil, false
239
+ }
240
+ sum := sha256.Sum256([]byte(key))
241
+ // Every key is compared, in constant time.
242
+ for _, k := range s.keys {
243
+ if subtle.ConstantTimeCompare(k[:], sum[:]) == 1 && id == "" {
244
+ id = hex.EncodeToString(k[:4])
245
+ }
246
+ }
247
+ if id == "" {
248
+ refuse(c, wrongKey)
249
+ return nil, true
250
+ }
251
+ case s.jwks != nil:
252
+ token := c.GetHeader("x-apso-service-token")
253
+ if key == "" && token == "" {
254
+ return nil, false
255
+ }
256
+ if id = s.keyID(token); id == "" {
257
+ refuse(c, noServiceToken)
258
+ return nil, true
259
+ }
260
+ default:
261
+ if key == "" {
262
+ return nil, false
263
+ }
264
+ refuse(c, keysOff)
265
+ return nil, true
266
+ }
267
+ return &AuthContext{ServiceID: id, Roles: []string{}}, false
268
+ }
269
+
270
+ // The key source is chosen once, however many routes use AuthMiddleware.
271
+ var chosenKeySource = sync.OnceValue(chooseKeySource)
272
+
273
+ // AuthMiddleware accepts a valid API key<% if (it.jwt) { %>, else a signed-in user<% } %>. The database is unused.
274
+ func AuthMiddleware(_ *gorm.DB) gin.HandlerFunc {
275
+ source := chosenKeySource()
276
+ return func(c *gin.Context) {
277
+ // The caller's x-request-id is kept, or one is created; the response echoes it.
278
+ id := c.GetHeader(requestIDHeader)
279
+ if id == "" {
280
+ b := make([]byte, 16)
281
+ _, _ = rand.Read(b)
282
+ id = hex.EncodeToString(b)
283
+ c.Request.Header.Set(requestIDHeader, id)
284
+ }
285
+ c.Header(requestIDHeader, id)
286
+
287
+ caller, refused := source.serviceCaller(c)
288
+ if refused {
289
+ return
290
+ }
291
+ if caller != nil {
292
+ setAuth(c, caller)
293
+ c.Next()
294
+ return
295
+ }
296
+ <% if (it.jwt && it.authRoutes.length > 0) { %>
297
+ // Auth entities are for service callers only. A user still signs in
298
+ // first, so a request with no valid credential gets its 401.
299
+ if parts := strings.Split(c.Request.URL.Path, "/"); len(parts) > 2 && authEntityRoutes[strings.ToLower(parts[2])] {
300
+ userAuth(c, true)
301
+ return
302
+ }
303
+ <% } %>
304
+ <% if (it.jwt) { %>
305
+ userAuth(c, false)
306
+ <% } else { %>
307
+ if len(source.keys) > 0 || source.jwks != nil {
308
+ refuse(c, noCredential)
309
+ } else {
310
+ refuse(c, noSource)
311
+ }
312
+ <% } %>
313
+ }
314
+ }
315
+ <% if (it.jwt) { %>
316
+
317
+ func unauthorized(c *gin.Context, msg string) {
318
+ refuse(c, msg+". Send a signed-in user's token, or an API key in the x-api-key header.")
319
+ }
320
+
106
321
  func env(name, fallback string) string {
107
322
  if v := os.Getenv(name); v != "" {
108
323
  return v
@@ -110,32 +325,78 @@ func env(name, fallback string) string {
110
325
  return fallback
111
326
  }
112
327
 
113
- var (
114
- issuer = env("AUTH_JWT_ISSUER", <%~ JSON.stringify(it.jwt.issuer) %>)
115
- audience = env("AUTH_JWT_AUDIENCE", <%~ JSON.stringify(it.jwt.audience || '') %>)
116
- jwksURI = env("AUTH_JWKS_URI", <%~ JSON.stringify(it.jwt.jwksUri) %>)
117
- algorithms = []string{<%~ it.jwt.algorithms.map((a) => JSON.stringify(a)).join(', ') %>}
118
- // Origins allowed in the azp claim; empty allows any.
119
- authorizedParties = splitList(env("AUTH_JWT_AUTHORIZED_PARTIES", <%~ JSON.stringify(it.jwt.authorizedParties.join(',')) %>))
328
+ // provider is one trusted issuer: its own keys, audience and claim names.
329
+ type provider struct {
330
+ name string
331
+ issuer string
332
+ audience string
333
+ algorithms []string
334
+ authorizedParties []string // origins allowed in the azp claim; empty allows any
335
+ jwks *lazyJWKS
336
+ userID string
337
+ workspace string
338
+ organization string
339
+ email string
340
+ roles string
341
+ permissions string
342
+ }
120
343
 
121
- jwksMu sync.Mutex
122
- jwks keyfunc.Keyfunc
344
+ // mcpResource is the public URL of the MCP endpoint, when the service serves
345
+ // MCP tools. An MCP client asks the identity provider for a token for this URL,
346
+ // so it is an accepted audience next to a provider's own.
347
+ <% if (it.mcp) { %>
348
+ var mcpResource = os.Getenv("MCP_RESOURCE_URL")
349
+ <% } else { %>
350
+ const mcpResource = ""
351
+ <% } %>
352
+
353
+ // providers by issuer. The first provider reads AUTH_JWT_ISSUER, the second
354
+ // AUTH_JWT_ISSUER_2, and so on.
355
+ var providers = byIssuer(
356
+ <% it.jwt.forEach((p, i) => { const s = i === 0 ? '' : `_${i + 1}` %>
357
+ &provider{
358
+ name: <%~ JSON.stringify(p.provider) %>,
359
+ issuer: env("AUTH_JWT_ISSUER<%= s %>", <%~ JSON.stringify(p.issuer) %>),
360
+ audience: env("AUTH_JWT_AUDIENCE<%= s %>", <%~ JSON.stringify(p.audience || '') %>),
361
+ algorithms: []string{<%~ p.algorithms.map((a) => JSON.stringify(a)).join(', ') %>},
362
+ authorizedParties: splitList(env("AUTH_JWT_AUTHORIZED_PARTIES<%= s %>", <%~ JSON.stringify(p.authorizedParties.join(',')) %>)),
363
+ jwks: &lazyJWKS{url: env("AUTH_JWKS_URI<%= s %>", <%~ JSON.stringify(p.jwksUri) %>)},
364
+ userID: <%~ JSON.stringify(p.claims.userId) %>,
365
+ workspace: <%~ JSON.stringify(p.claims.workspaceId || '') %>,
366
+ organization: <%~ JSON.stringify(p.claims.organizationId || '') %>,
367
+ email: <%~ JSON.stringify(p.claims.email || '') %>,
368
+ roles: <%~ JSON.stringify(p.claims.roles || '') %>,
369
+ permissions: <%~ JSON.stringify(p.claims.permissions || '') %>,
370
+ },
371
+ <% }) %>
123
372
  )
124
373
 
125
- // keys fetches the issuer's JWKS on first use, retrying on later requests if
126
- // the issuer was unreachable. keyfunc refreshes the set in the background.
127
- func keys() (keyfunc.Keyfunc, error) {
128
- jwksMu.Lock()
129
- defer jwksMu.Unlock()
130
- if jwks != nil {
131
- return jwks, nil
132
- }
133
- k, err := keyfunc.NewDefaultCtx(context.Background(), []string{jwksURI})
134
- if err != nil {
135
- return nil, err
374
+ func byIssuer(list ...*provider) map[string]*provider {
375
+ m := map[string]*provider{}
376
+ for _, p := range list {
377
+ issuers := []string{p.issuer}
378
+ <% if (it.jwt && it.jwt.some((p) => p.provider === 'better-auth')) { %>
379
+ // Better Auth: the OAuth provider signs with the base URL, the JWT plugin
380
+ // with its origin as iss and aud. Both are this provider, with the same keys.
381
+ if u, err := url.Parse(p.issuer); p.name == "better-auth" && err == nil {
382
+ origin := u.Scheme + "://" + u.Host
383
+ if origin != p.issuer {
384
+ issuers = append(issuers, origin)
385
+ }
386
+ if p.audience == "" {
387
+ p.audience = origin
388
+ }
389
+ }
390
+ <% } %>
391
+ for _, issuer := range issuers {
392
+ if _, taken := m[issuer]; taken {
393
+ // The token's iss picks the provider, so two providers cannot share one.
394
+ log.Fatalf("[apso] Two auth providers have the issuer %q. Check AUTH_JWT_ISSUER and its numbered variants.", issuer)
395
+ }
396
+ m[issuer] = p
397
+ }
136
398
  }
137
- jwks = k
138
- return k, nil
399
+ return m
139
400
  }
140
401
 
141
402
  // claim reads a claim by exact name (Auth0 namespaced URLs contain dots),
@@ -196,76 +457,116 @@ func roles(v interface{}) []string {
196
457
  return out
197
458
  }
198
459
 
199
- // AuthMiddleware verifies the caller's JWT. The database is unused for JWT auth.
200
- func AuthMiddleware(_ *gorm.DB) gin.HandlerFunc {
201
- return func(c *gin.Context) {
202
- header := c.GetHeader("Authorization")
203
- if !strings.HasPrefix(header, "Bearer ") {
204
- unauthorized(c, "No bearer token provided")
205
- return
206
- }
207
- k, err := keys()
208
- if err != nil {
209
- c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "Token signing keys unavailable"})
210
- return
211
- }
212
- opts := []jwt.ParserOption{
213
- jwt.WithIssuer(issuer),
214
- jwt.WithValidMethods(algorithms),
215
- jwt.WithExpirationRequired(),
216
- }
217
- <% if (it.jwt.provider !== 'cognito') { %>
218
- if audience != "" {
219
- opts = append(opts, jwt.WithAudience(audience))
220
- }
460
+ <% if (it.authRoutes.length > 0) { %>
461
+ var authEntityRoutes = map[string]bool{<%~ it.authRoutes.map((r) => JSON.stringify(r) + ': true').join(', ') %>}
462
+
221
463
  <% } %>
222
- mc := jwt.MapClaims{}
223
- token, err := jwt.ParseWithClaims(strings.TrimPrefix(header, "Bearer "), mc, k.Keyfunc, opts...)
224
- if err != nil || !token.Valid {
464
+ // userAuth verifies the caller's JWT and attaches the signed-in user. With
465
+ // serviceOnly, a caller who signs in is refused with a 403.
466
+ func userAuth(c *gin.Context, serviceOnly bool) {
467
+ header := c.GetHeader("Authorization")
468
+ if !strings.HasPrefix(header, "Bearer ") {
469
+ unauthorized(c, "No bearer token provided")
470
+ return
471
+ }
472
+ raw := strings.TrimPrefix(header, "Bearer ")
473
+ // The token's own issuer picks the provider, before anything is verified;
474
+ // then only that provider's keys and settings are used.
475
+ unverified := jwt.MapClaims{}
476
+ if _, _, err := jwt.NewParser().ParseUnverified(raw, unverified); err != nil {
477
+ unauthorized(c, "Invalid token")
478
+ return
479
+ }
480
+ iss, _ := unverified["iss"].(string)
481
+ p, ok := providers[iss]
482
+ if !ok {
483
+ unauthorized(c, "Invalid token")
484
+ return
485
+ }
486
+ k, err := p.jwks.get()
487
+ if err != nil {
488
+ c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "Token signing keys unavailable"})
489
+ return
490
+ }
491
+ opts := []jwt.ParserOption{
492
+ jwt.WithIssuer(iss),
493
+ jwt.WithValidMethods(p.algorithms),
494
+ jwt.WithExpirationRequired(),
495
+ }
496
+ cognito := p.name == "cognito"
497
+ if p.audience != "" && !cognito && mcpResource == "" {
498
+ opts = append(opts, jwt.WithAudience(p.audience))
499
+ }
500
+ mc := jwt.MapClaims{}
501
+ token, err := jwt.ParseWithClaims(raw, mc, k.Keyfunc, opts...)
502
+ if err != nil || !token.Valid {
503
+ unauthorized(c, "Invalid token")
504
+ return
505
+ }
506
+ claims := map[string]interface{}(mc)
507
+ if p.audience != "" && !cognito && mcpResource != "" {
508
+ aud, _ := mc.GetAudience()
509
+ // Better Auth signs both kinds of token with one key: only an OAuth access
510
+ // token (header type at+jwt) may be one issued for the MCP URL.
511
+ forMcp := contains(aud, mcpResource) && (p.name != "better-auth" || token.Header["typ"] == "at+jwt")
512
+ if !contains(aud, p.audience) && !forMcp {
225
513
  unauthorized(c, "Invalid token")
226
514
  return
227
515
  }
228
- claims := map[string]interface{}(mc)
229
- <% if (it.jwt.provider === 'cognito') { %>
230
- // Cognito ID tokens carry aud; access tokens carry client_id instead.
231
- if audience != "" {
232
- aud := claims["aud"]
233
- if aud == nil {
234
- aud = claims["client_id"]
235
- }
236
- if !containsAudience(aud, audience) {
237
- unauthorized(c, "Invalid token")
238
- return
239
- }
516
+ }
517
+ <% if (it.jwt.some((p) => p.provider === 'cognito')) { %>
518
+ // Cognito ID tokens carry aud; access tokens carry client_id instead.
519
+ if cognito && p.audience != "" {
520
+ aud := claims["aud"]
521
+ if aud == nil {
522
+ aud = claims["client_id"]
240
523
  }
241
- <% } %>
242
-
243
- if azp, ok := claims["azp"].(string); ok && len(authorizedParties) > 0 && !contains(authorizedParties, azp) {
524
+ if !containsAudience(aud, p.audience) && (mcpResource == "" || !containsAudience(aud, mcpResource)) {
244
525
  unauthorized(c, "Invalid token")
245
526
  return
246
527
  }
528
+ }
529
+ <% } %>
247
530
 
248
- userID := str(claim(claims, <%~ JSON.stringify(it.jwt.claims.userId) %>))
249
- if userID == "" {
250
- unauthorized(c, "Token has no user id")
251
- return
252
- }
253
- tenant := str(claim(claims, <%~ JSON.stringify(it.jwt.claims.workspaceId || '') %>))
254
- if tenant == "" {
255
- tenant = str(claim(claims, <%~ JSON.stringify(it.jwt.claims.organizationId || '') %>))
256
- }
257
- setAuth(c, &AuthContext{
258
- UserID: userID,
259
- Email: str(claim(claims, <%~ JSON.stringify(it.jwt.claims.email || '') %>)),
260
- WorkspaceID: tenant,
261
- OrganizationID: tenant,
262
- Roles: roles(claim(claims, <%~ JSON.stringify(it.jwt.claims.roles || '') %>)),
263
- Claims: claims,
264
- })
265
- c.Next()
531
+ <% if (it.jwt.some((p) => p.provider === 'better-auth')) { %>
532
+ // Better Auth's OAuth access tokens (header type at+jwt) name their client in azp.
533
+ if _, named := claims["azp"].(string); p.name == "better-auth" && token.Header["typ"] == "at+jwt" && !named {
534
+ unauthorized(c, "Invalid token")
535
+ return
536
+ }
537
+ <% } %>
538
+ if azp, ok := claims["azp"].(string); ok && len(p.authorizedParties) > 0 && !contains(p.authorizedParties, azp) {
539
+ unauthorized(c, "Invalid token")
540
+ return
266
541
  }
542
+
543
+ userID := str(claim(claims, p.userID))
544
+ if userID == "" {
545
+ unauthorized(c, "Token has no user id")
546
+ return
547
+ }
548
+ tenant := str(claim(claims, p.workspace))
549
+ if tenant == "" {
550
+ tenant = str(claim(claims, p.organization))
551
+ }
552
+ if serviceOnly {
553
+ c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "This route is for service callers only"})
554
+ return
555
+ }
556
+ setAuth(c, &AuthContext{
557
+ UserID: userID,
558
+ Email: str(claim(claims, p.email)),
559
+ WorkspaceID: tenant,
560
+ OrganizationID: tenant,
561
+ Roles: roles(claim(claims, p.roles)),
562
+ Issuer: iss,
563
+ Provider: p.name,
564
+ Permissions: roles(claim(claims, p.permissions)),
565
+ Claims: claims,
566
+ })
567
+ c.Next()
267
568
  }
268
- <% if (it.jwt.provider === 'cognito') { %>
569
+ <% if (it.jwt.some((p) => p.provider === 'cognito')) { %>
269
570
 
270
571
  func containsAudience(aud interface{}, want string) bool {
271
572
  switch t := aud.(type) {
@@ -281,76 +582,196 @@ func containsAudience(aud interface{}, want string) bool {
281
582
  return false
282
583
  }
283
584
  <% } %>
284
- <% } else { %>
585
+ <% } %>
285
586
 
286
- <% if (it.apiKey.hasExpiresAt) { %>
287
- // before reports whether an expiresAt value read from the database is still
288
- // in the future. A value it cannot read counts as expired.
289
- func before(v interface{}, now time.Time) bool {
290
- switch t := v.(type) {
291
- case time.Time:
292
- return now.Before(t)
293
- case *time.Time:
294
- return t == nil || now.Before(*t)
295
- case string:
296
- for _, layout := range []string{time.RFC3339Nano, "2006-01-02 15:04:05", "2006-01-02"} {
297
- if p, err := time.Parse(layout, t); err == nil {
298
- return now.Before(p)
587
+ // relationScope is one entity in the relation table: whether its reads are
588
+ // tenant-scoped, the roles that skip that scope, its table and scopeBy columns
589
+ // (each with the caller value it must equal: "userId", "email", or any other
590
+ // name for the tenant), and each relation a request can load (the entity it
591
+ // loads, and whether a caller limited to its tenant here stays in it there).
592
+ type relationScope struct {
593
+ Scoped bool
594
+ BypassRoles []string
595
+ Table string
596
+ Tenant map[string]string
597
+ Relations map[string]relationHop
598
+ }
599
+
600
+ type relationHop struct {
601
+ Entity string
602
+ SameTenant bool
603
+ }
604
+
605
+ // relationScopes holds every entity's relations, from .apsorc relationships and scopeBy.
606
+ var relationScopes = map[string]relationScope{
607
+ <% Object.entries(it.relationScopes).forEach(([name, scope]) => { %>
608
+ <%~ JSON.stringify(name) %>: {
609
+ Scoped: <%= scope.bypassRoles !== undefined %>,
610
+ BypassRoles: []string{<%~ (scope.bypassRoles ?? []).map((r) => JSON.stringify(r)).join(', ') %>},
611
+ Table: <%~ JSON.stringify(it.tables[name] ?? '') %>,
612
+ Tenant: map[string]string{
613
+ <% Object.entries(scope.scope ?? {}).forEach(([column, key]) => { %>
614
+ <%~ JSON.stringify(column) %>: <%~ JSON.stringify(key) %>,
615
+ <% }) %>
616
+ },
617
+ Relations: map[string]relationHop{
618
+ <% Object.entries(scope.relations).forEach(([relation, hop]) => { %>
619
+ <%~ JSON.stringify(relation) %>: {Entity: <%~ JSON.stringify(hop[0]) %>, SameTenant: <%= hop[1] %>},
620
+ <% }) %>
621
+ },
622
+ },
623
+ <% }) %>
624
+ }
625
+
626
+ // skipsScope reports whether the caller holds a role that skips e's tenant scope.
627
+ func skipsScope(a *AuthContext, e relationScope) bool {
628
+ for _, r := range a.Roles {
629
+ for _, b := range e.BypassRoles {
630
+ if r == b {
631
+ return true
299
632
  }
300
633
  }
301
- case []byte:
302
- return before(string(t), now)
303
634
  }
304
635
  return false
305
636
  }
306
637
 
307
- <% } %>
308
- // AuthMiddleware authenticates the caller's API key against <%= it.apiKey.apiKeyEntity %>.
309
- func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
310
- return func(c *gin.Context) {
311
- key := c.GetHeader(<%~ JSON.stringify(it.apiKey.apiKeyHeader) %>)
312
- if key == "" {
313
- unauthorized(c, "No API key provided")
314
- return
638
+ // tenantWhere is the SQL condition, with its arguments, that keeps rows of e
639
+ // to the caller's tenant (compared as text: token claims are strings). ok is
640
+ // false when the caller has no value for one of e's scopeBy columns.
641
+ func tenantWhere(a *AuthContext, e relationScope) (where string, args []interface{}, ok bool) {
642
+ var parts []string
643
+ for column, key := range e.Tenant {
644
+ v := a.WorkspaceID
645
+ switch key {
646
+ case "userId":
647
+ v = a.UserID
648
+ case "email":
649
+ v = a.Email
315
650
  }
316
- sum := sha256.Sum256([]byte(key))
317
- row := map[string]interface{}{}
318
- err := db.Model(&models.<%= it.apiKey.goModel %>{}).
319
- Where(<%~ JSON.stringify('"' + it.apiKey.keyColumn + '" = ?') %>, hex.EncodeToString(sum[:])).
320
- Take(&row).Error
321
- if err != nil {
322
- unauthorized(c, "Invalid API key")
323
- return
651
+ if v == "" {
652
+ return "", nil, false
324
653
  }
325
- <% if (it.apiKey.hasStatus) { %>
326
- if fmt.Sprint(row["status"]) != "active" {
327
- unauthorized(c, "API key is not active")
328
- return
654
+ parts = append(parts, `CAST("`+column+`" AS TEXT) = ?`)
655
+ args = append(args, v)
656
+ }
657
+ return strings.Join(parts, " AND "), args, true
658
+ }
659
+
660
+ // RelationLoad is one relation to preload: its path as the request names it
661
+ // (author, author.posts) and the conditions its rows must meet, as arguments
662
+ // for gorm's Preload.
663
+ type RelationLoad struct {
664
+ Path string
665
+ Conds []interface{}
666
+ }
667
+
668
+ // RelationLoads is the one place that decides which relations a request may
669
+ // load. For a path (author.posts) it returns each step to preload, or the
670
+ // first relation that would load rows outside the caller's tenant. The tenant
671
+ // filter limits only the entity a request starts from, so a relation onto a
672
+ // tenant-scoped entity is loaded only when the caller holds a role that skips
673
+ // that entity's scope, or is limited to its tenant on the entity the relation
674
+ // starts from and the target is scoped by the same keys. The rows of such a
675
+ // relation are still limited to the caller's tenant by the target's own
676
+ // scopeBy columns, so a row that points at another tenant's row does not carry
677
+ // it into a response. A service caller (valid API key) is not limited.
678
+ func RelationLoads(ctx context.Context, root, path string) (loads []RelationLoad, refused string) {
679
+ a, _ := FromContext(ctx)
680
+ if a == nil {
681
+ a = &AuthContext{}
682
+ }
683
+ skips := func(e relationScope) bool { return skipsScope(a, e) }
684
+ // Outside the table (or for a service caller) a relation loads as it is.
685
+ known := len(relationScopes) > 0 && a.ServiceID == ""
686
+ from := relationScopes[root]
687
+ parts := strings.Split(path, ".")
688
+ for i, name := range parts {
689
+ load := RelationLoad{Path: strings.Join(parts[:i+1], ".")}
690
+ // Requests may name a relation as the field (Posts) or as .apsorc does (posts).
691
+ if name != "" {
692
+ name = strings.ToLower(name[:1]) + name[1:]
329
693
  }
330
- <% } %>
331
- <% if (it.apiKey.hasExpiresAt) { %>
332
- if v := row[<%~ JSON.stringify(it.apiKey.expiresColumn) %>]; v != nil && !before(v, time.Now()) {
333
- unauthorized(c, "API key has expired")
334
- return
694
+ hop, ok := from.Relations[name]
695
+ known = known && ok
696
+ if known {
697
+ to := relationScopes[hop.Entity]
698
+ inTenant := hop.SameTenant && from.Scoped && !skips(from)
699
+ if to.Scoped && !skips(to) && !inTenant {
700
+ return nil, name
701
+ }
702
+ // The hop was allowed as a same-tenant one: hold its rows to that tenant.
703
+ if inTenant && to.Scoped && !skips(to) {
704
+ where, args, ok := tenantWhere(a, to)
705
+ if !ok {
706
+ return nil, name
707
+ }
708
+ if where != "" {
709
+ load.Conds = append([]interface{}{where}, args...)
710
+ }
711
+ }
712
+ from = to
335
713
  }
336
- <% } %>
337
- tenant := ""
338
- if v := row[<%~ JSON.stringify(it.apiKey.workspaceColumn) %>]; v != nil {
339
- tenant = fmt.Sprint(v)
714
+ loads = append(loads, load)
715
+ }
716
+ return loads, ""
717
+ }
718
+
719
+ // ErrReference means a write names, in a foreign key, a row of a tenant-scoped
720
+ // entity that the caller cannot read. Handlers answer it with 403.
721
+ var ErrReference = errors.New("you do not have access to a row this request references")
722
+
723
+ // CheckReferences is the one place that checks the foreign keys of a write
724
+ // (R8). references maps a tenant-scoped entity to the ids a body names in
725
+ // foreign keys to it; an id may be a pointer, and nil or zero means not sent.
726
+ // Every id must be a row the caller could read, or the result is ErrReference.
727
+ // A service caller or a role that skips the target's scope is not limited.
728
+ // One query per referenced entity.
729
+ func CheckReferences(ctx context.Context, db *gorm.DB, references map[string][]interface{}) error {
730
+ a, _ := FromContext(ctx)
731
+ if a == nil {
732
+ a = &AuthContext{}
733
+ }
734
+ if a.ServiceID != "" {
735
+ return nil
736
+ }
737
+ for entity, sent := range references {
738
+ to := relationScopes[entity]
739
+ if !to.Scoped || skipsScope(a, to) {
740
+ continue
340
741
  }
341
- roles := []string{}
342
- <% if (it.apiKey.roleField) { %>
343
- if v := row[<%~ JSON.stringify(it.apiKey.roleColumn) %>]; v != nil {
344
- roles = append(roles, fmt.Sprint(v))
742
+ seen := map[string]bool{}
743
+ var ids []interface{}
744
+ for _, v := range sent {
745
+ rv := reflect.ValueOf(v)
746
+ for rv.Kind() == reflect.Ptr && !rv.IsNil() {
747
+ rv = rv.Elem()
748
+ }
749
+ if !rv.IsValid() || rv.Kind() == reflect.Ptr || rv.IsZero() {
750
+ continue
751
+ }
752
+ if key := fmt.Sprint(rv.Interface()); !seen[key] {
753
+ seen[key] = true
754
+ ids = append(ids, rv.Interface())
755
+ }
756
+ }
757
+ if len(ids) == 0 {
758
+ continue
759
+ }
760
+ where, args, ok := tenantWhere(a, to)
761
+ if !ok {
762
+ return ErrReference
763
+ }
764
+ q := db.WithContext(ctx).Table(to.Table).Where(`"id" IN ?`, ids)
765
+ if where != "" {
766
+ q = q.Where(where, args...)
767
+ }
768
+ var found int64
769
+ if err := q.Count(&found).Error; err != nil {
770
+ return err
771
+ }
772
+ if found != int64(len(ids)) {
773
+ return ErrReference
345
774
  }
346
- <% } %>
347
- setAuth(c, &AuthContext{
348
- ServiceID: fmt.Sprint(row["id"]),
349
- WorkspaceID: tenant,
350
- OrganizationID: tenant,
351
- Roles: roles,
352
- })
353
- c.Next()
354
775
  }
776
+ return nil
355
777
  }
356
- <% } %>