@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.
- package/README.md +28 -1
- package/dist/commands/dev.d.ts +2 -0
- package/dist/commands/dev.js +20 -3
- package/dist/commands/generate.js +49 -13
- package/dist/commands/mcp/serve.js +24 -41
- package/dist/commands/schema/diff.js +3 -4
- package/dist/commands/schema/pull.js +13 -11
- package/dist/commands/schema/push.js +6 -5
- package/dist/commands/schema/validate.d.ts +10 -0
- package/dist/commands/schema/validate.js +54 -0
- package/dist/commands/test/access.d.ts +11 -0
- package/dist/commands/test/access.js +65 -0
- package/dist/lib/access/cases.d.ts +120 -0
- package/dist/lib/access/cases.js +1163 -0
- package/dist/lib/access/index.d.ts +4 -0
- package/dist/lib/access/index.js +7 -0
- package/dist/lib/access/report.d.ts +75 -0
- package/dist/lib/access/report.js +118 -0
- package/dist/lib/access/rules.json +207 -0
- package/dist/lib/access/run.d.ts +38 -0
- package/dist/lib/access/run.js +111 -0
- package/dist/lib/access/tokens.d.ts +46 -0
- package/dist/lib/access/tokens.js +139 -0
- package/dist/lib/api/services.d.ts +10 -7
- package/dist/lib/api/services.js +19 -32
- package/dist/lib/apsorc-parser.d.ts +1 -1
- package/dist/lib/apsorc-parser.js +2 -0
- package/dist/lib/deploy/server-push.js +3 -1
- package/dist/lib/generators/go.d.ts +13 -1
- package/dist/lib/generators/go.js +144 -33
- package/dist/lib/generators/python.d.ts +3 -3
- package/dist/lib/generators/python.js +48 -24
- package/dist/lib/generators/typescript.d.ts +3 -5
- package/dist/lib/generators/typescript.js +78 -64
- package/dist/lib/guards.d.ts +111 -13
- package/dist/lib/guards.js +287 -23
- package/dist/lib/templates/go/handlers/handler.eta +8 -8
- package/dist/lib/templates/go/handlers/scope.eta +3 -2
- package/dist/lib/templates/go/index-module.eta +8 -5
- package/dist/lib/templates/go/mcp.eta +307 -0
- package/dist/lib/templates/go/middleware/auth.eta +587 -166
- package/dist/lib/templates/go/middleware/permission.eta +174 -0
- package/dist/lib/templates/go/services/service.eta +37 -16
- package/dist/lib/templates/go/utils/query.eta +37 -2
- package/dist/lib/templates/guards/guards.module.eta +37 -29
- package/dist/lib/templates/guards/index.eta +4 -0
- package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
- package/dist/lib/templates/guards/key.guard.eta +280 -0
- package/dist/lib/templates/guards/permission.guard.eta +168 -0
- package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
- package/dist/lib/templates/guards/scope.guard.eta +189 -41
- package/dist/lib/templates/python/auth.eta +354 -95
- package/dist/lib/templates/python/index-module.eta +7 -7
- package/dist/lib/templates/python/mcp.eta +284 -0
- package/dist/lib/templates/python/models/model.eta +6 -5
- package/dist/lib/templates/python/permissions.eta +121 -0
- package/dist/lib/templates/python/routers/router.eta +39 -1
- package/dist/lib/templates/python/schemas/schema.eta +18 -5
- package/dist/lib/templates/python/services/service.eta +38 -15
- package/dist/lib/templates/python/utils/query.eta +52 -25
- package/dist/lib/templates/rest/controller-rest.eta +43 -23
- package/dist/lib/templates/rest/index-module-rest.eta +0 -4
- package/dist/lib/templates/rest/service-rest.eta +3 -44
- package/dist/lib/types/auth.d.ts +84 -80
- package/dist/lib/types/auth.js +77 -60
- package/dist/lib/types/entity.d.ts +17 -9
- package/dist/lib/types/entity.js +3 -0
- package/dist/lib/types/index.d.ts +2 -2
- package/dist/lib/types/index.js +6 -5
- package/dist/lib/utils/crud-deps.d.ts +77 -6
- package/dist/lib/utils/crud-deps.js +197 -14
- package/dist/lib/utils/schema-convert.d.ts +20 -43
- package/dist/lib/utils/schema-convert.js +28 -78
- package/dist/lib/utils/template.d.ts +11 -0
- package/dist/lib/utils/template.js +36 -1
- package/dist/lib/verify/index.d.ts +6 -1
- package/dist/lib/verify/index.js +30 -13
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +36 -1
- package/package.json +1 -1
- package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
- package/dist/lib/templates/guards/auth.guard.eta +0 -233
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
<%~ includeFile('../header.eta', it) %>
|
|
2
|
+
|
|
3
|
+
package middleware
|
|
4
|
+
|
|
5
|
+
// PermissionMiddleware checks the role permissions from .apsorc on every route
|
|
6
|
+
// of the /api group, after AuthMiddleware.
|
|
7
|
+
//
|
|
8
|
+
// A signed-in user may perform a guarded operation when any of these holds:
|
|
9
|
+
// - one of its roles is in the .apsorc default list
|
|
10
|
+
// - its token carries the permission (for example Auth0 RBAC "permissions")
|
|
11
|
+
<% if (it.grants) { %>
|
|
12
|
+
// - a <%= it.grants.entity %> row grants the permission to one of its roles<% if (it.grants.tenantField) { %> in its
|
|
13
|
+
// tenant (or in every tenant, when <%= it.grants.tenantField %> is null)<% } %>
|
|
14
|
+
|
|
15
|
+
<% } %>
|
|
16
|
+
//
|
|
17
|
+
// Grants only add access; they never take away a default. An operation that
|
|
18
|
+
// is not listed is open to any authenticated caller. A service caller (valid
|
|
19
|
+
// API key) is not limited by role. Every interface that calls this API (REST,
|
|
20
|
+
// SDK, MCP) goes through this check.
|
|
21
|
+
|
|
22
|
+
import (
|
|
23
|
+
"net/http"
|
|
24
|
+
"regexp"
|
|
25
|
+
"strings"
|
|
26
|
+
|
|
27
|
+
"github.com/gin-gonic/gin"
|
|
28
|
+
"gorm.io/gorm"
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
// permissionRule is a guarded operation: its permission name and the roles
|
|
32
|
+
// that have it by default.
|
|
33
|
+
type permissionRule struct {
|
|
34
|
+
permission string
|
|
35
|
+
roles []string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// entityPermissions holds the guarded operations by route.
|
|
39
|
+
var entityPermissions = map[string]map[string]permissionRule{
|
|
40
|
+
<% it.routes.forEach((route) => { %>
|
|
41
|
+
<%~ JSON.stringify(route.path) %>: {
|
|
42
|
+
<% route.rules.forEach((r) => { %>
|
|
43
|
+
<%~ JSON.stringify(r.op) %>: {<%~ JSON.stringify(r.permission) %>, []string{<%~ r.roles.map((x) => JSON.stringify(x)).join(', ') %>}},
|
|
44
|
+
<% }) %>
|
|
45
|
+
},
|
|
46
|
+
<% }) %>
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// joinPermissions holds the read rules a join must satisfy, by relation name,
|
|
50
|
+
// so a caller who cannot read an entity cannot read it through a join either.
|
|
51
|
+
var joinPermissions = map[string][]permissionRule{
|
|
52
|
+
<% it.joins.forEach((join) => { %>
|
|
53
|
+
<%~ JSON.stringify(join.name) %>: {
|
|
54
|
+
<% join.rules.forEach((r) => { %>
|
|
55
|
+
{<%~ JSON.stringify(r.permission) %>, []string{<%~ r.roles.map((x) => JSON.stringify(x)).join(', ') %>}},
|
|
56
|
+
<% }) %>
|
|
57
|
+
},
|
|
58
|
+
<% }) %>
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
var permissionOperations = map[string]string{
|
|
62
|
+
http.MethodGet: "read",
|
|
63
|
+
http.MethodHead: "read",
|
|
64
|
+
http.MethodPost: "create",
|
|
65
|
+
http.MethodPut: "update",
|
|
66
|
+
http.MethodPatch: "update",
|
|
67
|
+
http.MethodDelete: "delete",
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// A relation embedded in a PostgREST select: rel(...), alias:rel!inner(...).
|
|
71
|
+
var embedPattern = regexp.MustCompile(`([A-Za-z_]\w*)(?:![A-Za-z]+)?\(`)
|
|
72
|
+
|
|
73
|
+
// joinedRelations lists every relation the query asks to load, under either
|
|
74
|
+
// query dialect. ?join=Invoices loads the same relation as ?join=invoices, so
|
|
75
|
+
// the first letter is lowered to the .apsorc name.
|
|
76
|
+
func joinedRelations(c *gin.Context) []string {
|
|
77
|
+
q := c.Request.URL.Query()
|
|
78
|
+
raw := []string{}
|
|
79
|
+
for _, j := range q["join"] {
|
|
80
|
+
raw = append(raw, strings.Split(strings.SplitN(j, "||", 2)[0], ".")...)
|
|
81
|
+
}
|
|
82
|
+
for _, s := range q["select"] {
|
|
83
|
+
for _, m := range embedPattern.FindAllStringSubmatch(s, -1) {
|
|
84
|
+
raw = append(raw, m[1])
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
names := []string{}
|
|
88
|
+
for _, n := range raw {
|
|
89
|
+
if n = strings.TrimSpace(n); n != "" {
|
|
90
|
+
names = append(names, strings.ToLower(n[:1])+n[1:])
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return names
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// grantedPermissions returns the caller's permissions from its token<% if (it.grants) { %> and
|
|
97
|
+
// its roles' <%= it.grants.entity %> rows. A failed query grants nothing<% } %>.
|
|
98
|
+
func grantedPermissions(db *gorm.DB, a *AuthContext) map[string]bool {
|
|
99
|
+
granted := map[string]bool{}
|
|
100
|
+
for _, p := range a.Permissions {
|
|
101
|
+
granted[p] = true
|
|
102
|
+
}
|
|
103
|
+
<% if (it.grants) { %>
|
|
104
|
+
if len(a.Roles) > 0 {
|
|
105
|
+
// ponytail: one query per guarded request; cache per role and tenant
|
|
106
|
+
// with a short TTL if this shows up in latency.
|
|
107
|
+
q := db.Table(<%~ JSON.stringify(it.grants.table) %>).Where(`"role" IN ?`, a.Roles)
|
|
108
|
+
<% if (it.grants.tenantField) { %>
|
|
109
|
+
if a.WorkspaceID == "" {
|
|
110
|
+
q = q.Where(`"<%= it.grants.tenantField %>" IS NULL`)
|
|
111
|
+
} else {
|
|
112
|
+
q = q.Where(`("<%= it.grants.tenantField %>" IS NULL OR CAST("<%= it.grants.tenantField %>" AS text) = ?)`, a.WorkspaceID)
|
|
113
|
+
}
|
|
114
|
+
<% } %>
|
|
115
|
+
var rows []string
|
|
116
|
+
if err := q.Pluck("permission", &rows).Error; err == nil {
|
|
117
|
+
for _, p := range rows {
|
|
118
|
+
granted[p] = true
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
<% } %>
|
|
123
|
+
return granted
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// PermissionMiddleware answers 403 unless the caller may perform the
|
|
127
|
+
// operation. basePath is the path of the group the routes are registered on.
|
|
128
|
+
func PermissionMiddleware(db *gorm.DB, basePath string) gin.HandlerFunc {
|
|
129
|
+
return func(c *gin.Context) {
|
|
130
|
+
a, ok := GetAuthContext(c)
|
|
131
|
+
if !ok {
|
|
132
|
+
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Forbidden"})
|
|
133
|
+
return
|
|
134
|
+
}
|
|
135
|
+
if a.ServiceID != "" {
|
|
136
|
+
c.Next()
|
|
137
|
+
return
|
|
138
|
+
}
|
|
139
|
+
// Loaded once per request, and only when a default role does not decide.
|
|
140
|
+
var granted map[string]bool
|
|
141
|
+
allowed := func(r permissionRule) bool {
|
|
142
|
+
for _, have := range a.Roles {
|
|
143
|
+
for _, want := range r.roles {
|
|
144
|
+
if have == want {
|
|
145
|
+
return true
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if granted == nil {
|
|
150
|
+
granted = grantedPermissions(db, a)
|
|
151
|
+
}
|
|
152
|
+
return granted[r.permission]
|
|
153
|
+
}
|
|
154
|
+
deny := func(r permissionRule) {
|
|
155
|
+
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "Missing permission " + r.permission})
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
rest := strings.TrimPrefix(strings.TrimPrefix(c.FullPath(), basePath), "/")
|
|
159
|
+
entity := strings.SplitN(rest, "/", 2)[0]
|
|
160
|
+
if r, ok := entityPermissions[entity][permissionOperations[c.Request.Method]]; ok && !allowed(r) {
|
|
161
|
+
deny(r)
|
|
162
|
+
return
|
|
163
|
+
}
|
|
164
|
+
for _, relation := range joinedRelations(c) {
|
|
165
|
+
for _, r := range joinPermissions[relation] {
|
|
166
|
+
if !allowed(r) {
|
|
167
|
+
deny(r)
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
c.Next()
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -10,7 +10,7 @@ import (
|
|
|
10
10
|
"errors"
|
|
11
11
|
|
|
12
12
|
"app/autogen/dto"
|
|
13
|
-
<% if (it.scope) { %>
|
|
13
|
+
<% if (it.scope || it.references.length) { %>
|
|
14
14
|
"app/autogen/middleware"
|
|
15
15
|
<% } %>
|
|
16
16
|
"app/autogen/models"
|
|
@@ -48,19 +48,19 @@ func New<%= it.entityName %>Service(db *gorm.DB) *<%= it.entityName %>Service {
|
|
|
48
48
|
}
|
|
49
49
|
<% if (it.scope) { %>
|
|
50
50
|
|
|
51
|
-
// scoped limits q to the caller's tenant
|
|
52
|
-
//
|
|
53
|
-
//
|
|
51
|
+
// scoped limits q to the caller's tenant per .apsorc scopeBy, on every
|
|
52
|
+
// operation (op names it), and returns the scope column values. Both are
|
|
53
|
+
// unchanged for a service caller or a bypass role.
|
|
54
54
|
func (s *<%= it.entityName %>Service) scoped(ctx context.Context, q *gorm.DB, op string) (*gorm.DB, map[string]string, error) {
|
|
55
|
-
|
|
56
|
-
case <%~ it.scope.enforceOn.map((o) => JSON.stringify(o)).join(', ') %>:
|
|
57
|
-
default:
|
|
58
|
-
return q, nil, nil
|
|
59
|
-
}
|
|
55
|
+
_ = op
|
|
60
56
|
a, ok := middleware.FromContext(ctx)
|
|
61
57
|
if !ok {
|
|
62
58
|
return nil, nil, ErrForbidden
|
|
63
59
|
}
|
|
60
|
+
// A service caller (valid API key) is not tenant-scoped.
|
|
61
|
+
if a.ServiceID != "" {
|
|
62
|
+
return q, nil, nil
|
|
63
|
+
}
|
|
64
64
|
<% if (it.scope.bypassRoles.length > 0) { %>
|
|
65
65
|
if hasAnyRole(a.Roles, <%~ it.scope.bypassRoles.map((r) => JSON.stringify(r)).join(', ') %>) {
|
|
66
66
|
return q, nil, nil
|
|
@@ -89,7 +89,7 @@ func (s *<%= it.entityName %>Service) FindAll(ctx context.Context, opts utils.Qu
|
|
|
89
89
|
var items []models.<%= it.entityName %>
|
|
90
90
|
|
|
91
91
|
query := s.db.WithContext(ctx).Model(&models.<%= it.entityName %>{})
|
|
92
|
-
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
92
|
+
<% it.associations.filter(a => a.eager && !a.hidden).forEach((assoc) => { %>
|
|
93
93
|
query = query.Preload("<%= assoc.fieldName %>")
|
|
94
94
|
<% }) %>
|
|
95
95
|
<% if (it.scope) { %>
|
|
@@ -130,7 +130,7 @@ func (s *<%= it.entityName %>Service) FindAllBare(ctx context.Context, opts util
|
|
|
130
130
|
var items []models.<%= it.entityName %>
|
|
131
131
|
|
|
132
132
|
query := s.db.WithContext(ctx).Model(&models.<%= it.entityName %>{})
|
|
133
|
-
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
133
|
+
<% it.associations.filter(a => a.eager && !a.hidden).forEach((assoc) => { %>
|
|
134
134
|
query = query.Preload("<%= assoc.fieldName %>")
|
|
135
135
|
<% }) %>
|
|
136
136
|
<% if (it.scope) { %>
|
|
@@ -161,7 +161,7 @@ func (s *<%= it.entityName %>Service) FindOne(ctx context.Context, id string) (*
|
|
|
161
161
|
var item models.<%= it.entityName %>
|
|
162
162
|
|
|
163
163
|
query := s.db.WithContext(ctx)
|
|
164
|
-
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
164
|
+
<% it.associations.filter(a => a.eager && !a.hidden).forEach((assoc) => { %>
|
|
165
165
|
query = query.Preload("<%= assoc.fieldName %>")
|
|
166
166
|
<% }) %>
|
|
167
167
|
<% if (it.scope) { %>
|
|
@@ -196,7 +196,7 @@ func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%=
|
|
|
196
196
|
<%= assoc.fkField %>: input.<%= assoc.fkField %>,
|
|
197
197
|
<% }) %>
|
|
198
198
|
}
|
|
199
|
-
<% if (it.scope
|
|
199
|
+
<% if (it.scope) { %>
|
|
200
200
|
|
|
201
201
|
// The caller's tenant, never one from the body (.apsorc scopeBy).
|
|
202
202
|
_, scopeVals, scopeErr := s.scoped(ctx, s.db, "create")
|
|
@@ -210,6 +210,17 @@ func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%=
|
|
|
210
210
|
}
|
|
211
211
|
}
|
|
212
212
|
<% }) %>
|
|
213
|
+
<% } %>
|
|
214
|
+
<% if (it.references.length) { %>
|
|
215
|
+
|
|
216
|
+
// Foreign keys to tenant-scoped entities must name rows the caller can read.
|
|
217
|
+
if err := middleware.CheckReferences(ctx, s.db, map[string][]interface{}{
|
|
218
|
+
<% it.references.forEach((r) => { %>
|
|
219
|
+
<%~ JSON.stringify(r.target) %>: {item.<%= r.goField %>},
|
|
220
|
+
<% }) %>
|
|
221
|
+
}); err != nil {
|
|
222
|
+
return nil, err
|
|
223
|
+
}
|
|
213
224
|
<% } %>
|
|
214
225
|
|
|
215
226
|
if err := s.db.WithContext(ctx).Create(&item).Error; err != nil {
|
|
@@ -271,6 +282,15 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
271
282
|
delete(updates, col)
|
|
272
283
|
}
|
|
273
284
|
<% } %>
|
|
285
|
+
<% if (it.references.length) { %>
|
|
286
|
+
if err := middleware.CheckReferences(ctx, s.db, map[string][]interface{}{
|
|
287
|
+
<% it.references.forEach((r) => { %>
|
|
288
|
+
<%~ JSON.stringify(r.target) %>: {updates[<%~ JSON.stringify(r.column) %>]},
|
|
289
|
+
<% }) %>
|
|
290
|
+
}); err != nil {
|
|
291
|
+
return nil, err
|
|
292
|
+
}
|
|
293
|
+
<% } %>
|
|
274
294
|
|
|
275
295
|
if len(updates) > 0 {
|
|
276
296
|
if err := s.db.WithContext(ctx).Model(&item).Updates(updates).Error; err != nil {
|
|
@@ -280,7 +300,7 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
280
300
|
|
|
281
301
|
// Reload with associations
|
|
282
302
|
query := s.db.WithContext(ctx)
|
|
283
|
-
<% it.associations.filter(a => a.eager).forEach((assoc) => { %>
|
|
303
|
+
<% it.associations.filter(a => a.eager && !a.hidden).forEach((assoc) => { %>
|
|
284
304
|
query = query.Preload("<%= assoc.fieldName %>")
|
|
285
305
|
<% }) %>
|
|
286
306
|
<% if (it.primaryKeyType === 'uuid') { %>
|
|
@@ -335,8 +355,9 @@ func (s *<%= it.entityName %>Service) toResponse(item *models.<%= it.entityName
|
|
|
335
355
|
<%= assoc.fkField %>: item.<%= assoc.fkField %>,
|
|
336
356
|
<% }) %>
|
|
337
357
|
}
|
|
338
|
-
// Relations loaded by ?join= or eager loading.
|
|
339
|
-
|
|
358
|
+
// Relations loaded by ?join= or eager loading. A relation onto an auth
|
|
359
|
+
// entity is left out: those rows are for service callers only.
|
|
360
|
+
<% it.associations.filter(a => !a.hidden).forEach((assoc) => { %>
|
|
340
361
|
<% if (assoc.type === 'ManyToOne' || assoc.type === 'OneToOne') { %>
|
|
341
362
|
if item.<%= assoc.fieldName %> != nil {
|
|
342
363
|
related := (&<%= assoc.name %>Service{}).toResponse(item.<%= assoc.fieldName %>)
|
|
@@ -7,10 +7,12 @@ import (
|
|
|
7
7
|
"fmt"
|
|
8
8
|
"math"
|
|
9
9
|
"net/url"
|
|
10
|
+
"reflect"
|
|
10
11
|
"regexp"
|
|
11
12
|
"strconv"
|
|
12
13
|
"strings"
|
|
13
14
|
|
|
15
|
+
"app/autogen/middleware"
|
|
14
16
|
"gorm.io/gorm"
|
|
15
17
|
)
|
|
16
18
|
|
|
@@ -23,10 +25,23 @@ const (
|
|
|
23
25
|
// ErrQuery is a client-facing (HTTP 400) query error. The generated handler
|
|
24
26
|
// maps any *QueryError to a 400 response so a malformed dialect request never
|
|
25
27
|
// surfaces as a 500 (apso #60).
|
|
26
|
-
type QueryError struct{
|
|
28
|
+
type QueryError struct {
|
|
29
|
+
Msg string
|
|
30
|
+
// Forbidden makes the handler answer 403: the query is well formed, and
|
|
31
|
+
// the caller may not run it.
|
|
32
|
+
Forbidden bool
|
|
33
|
+
}
|
|
27
34
|
|
|
28
35
|
func (e *QueryError) Error() string { return e.Msg }
|
|
29
36
|
|
|
37
|
+
// Status is the HTTP status the handler answers with.
|
|
38
|
+
func (e *QueryError) Status() int {
|
|
39
|
+
if e.Forbidden {
|
|
40
|
+
return 403
|
|
41
|
+
}
|
|
42
|
+
return 400
|
|
43
|
+
}
|
|
44
|
+
|
|
30
45
|
func queryErr(format string, a ...interface{}) *QueryError {
|
|
31
46
|
return &QueryError{Msg: fmt.Sprintf(format, a...)}
|
|
32
47
|
}
|
|
@@ -744,7 +759,15 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
744
759
|
|
|
745
760
|
// Joins (Preloads)
|
|
746
761
|
for _, j := range opts.Joins {
|
|
747
|
-
|
|
762
|
+
// Every relation a request loads (join or select embed) is checked for the caller.
|
|
763
|
+
loads, refused := middleware.RelationLoads(query.Statement.Context, modelName(query), j.Relation)
|
|
764
|
+
if refused != "" {
|
|
765
|
+
return query, 0, 1, &QueryError{Forbidden: true, Msg: fmt.Sprintf("The relation %q cannot be loaded from %s: its rows are tenant-scoped", refused, modelName(query))}
|
|
766
|
+
}
|
|
767
|
+
// Each step of the path, so a tenant-scoped step loads the caller's rows only.
|
|
768
|
+
for _, load := range loads {
|
|
769
|
+
query = query.Preload(preloadName(load.Path), load.Conds...)
|
|
770
|
+
}
|
|
748
771
|
}
|
|
749
772
|
|
|
750
773
|
// Pagination
|
|
@@ -768,6 +791,18 @@ func ApplyQueryE(db *gorm.DB, opts QueryOptions, allowedFields map[string]bool)
|
|
|
768
791
|
return query, total, pageCount, nil
|
|
769
792
|
}
|
|
770
793
|
|
|
794
|
+
// modelName is the entity a query starts from (the struct passed to Model).
|
|
795
|
+
func modelName(query *gorm.DB) string {
|
|
796
|
+
t := reflect.TypeOf(query.Statement.Model)
|
|
797
|
+
for t != nil && (t.Kind() == reflect.Ptr || t.Kind() == reflect.Slice) {
|
|
798
|
+
t = t.Elem()
|
|
799
|
+
}
|
|
800
|
+
if t == nil {
|
|
801
|
+
return ""
|
|
802
|
+
}
|
|
803
|
+
return t.Name()
|
|
804
|
+
}
|
|
805
|
+
|
|
771
806
|
// quoteColumn quotes an allowlisted column name: the columns keep their
|
|
772
807
|
// .apsorc names, so seenAt must not fold to seenat.
|
|
773
808
|
func quoteColumn(c string) string {
|
|
@@ -7,9 +7,13 @@ import { APP_GUARD } from '@nestjs/core';
|
|
|
7
7
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
8
8
|
import { ScopeGuard } from './scope.guard';
|
|
9
9
|
<% } %>
|
|
10
|
+
import { ApiKeyGuard<% if (it.mcpAuth) { %>, McpAuthProvider<% } %> } from './key.guard';
|
|
10
11
|
<% if (it.hasAuth) { %>
|
|
11
12
|
import { AuthGuard } from './auth.guard';
|
|
12
13
|
<% } %>
|
|
14
|
+
<% if (it.permissions) { %>
|
|
15
|
+
import { PermissionGuard } from './permission.guard';
|
|
16
|
+
<% } %>
|
|
13
17
|
|
|
14
18
|
<% /* Import all entities for ScopeGuard (from sibling autogen folders) */ %>
|
|
15
19
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
@@ -19,33 +23,24 @@ import { <%= entity.name %> } from '../<%= entity.name %>/<%= entity.name %>.ent
|
|
|
19
23
|
<% }) %>
|
|
20
24
|
<% } %>
|
|
21
25
|
|
|
22
|
-
<% /* Import entities for AuthGuard (from sibling autogen folders) */ %>
|
|
23
|
-
<% if (it.authEntities.length > 0) { %>
|
|
24
|
-
// Entities for AuthGuard
|
|
25
|
-
<% it.authEntities.forEach((entity) => { %>
|
|
26
|
-
import { <%= entity %> } from '../<%= entity %>/<%= entity %>.entity';
|
|
27
|
-
<% }) %>
|
|
28
|
-
<% } %>
|
|
29
|
-
|
|
30
26
|
/**
|
|
31
|
-
* GuardsModule
|
|
27
|
+
* GuardsModule turns on the service's global guards. Every request is refused
|
|
28
|
+
* unless a guard lets it through; a route opts out with @Public().
|
|
32
29
|
*
|
|
33
30
|
* Auto-generated from .apsorc configuration.
|
|
34
31
|
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* and tenant-scoped unless a route opts out with @Public().
|
|
40
|
-
* 3. Services with no auth model generate no guards and rely on the API Gateway
|
|
41
|
-
* API key at the edge.
|
|
42
|
-
*
|
|
32
|
+
* ApiKeyGuard (in every service):
|
|
33
|
+
* - Checks the x-api-key header against the key source chosen at start-up
|
|
34
|
+
* (APSO_API_KEY, else the platform gateway's service token, else off)
|
|
35
|
+
* - A caller with a valid key is a service caller: any route, no tenant scope
|
|
43
36
|
<% if (it.hasAuth) { %>
|
|
44
|
-
* AuthGuard
|
|
45
|
-
* -
|
|
46
|
-
|
|
47
|
-
*
|
|
37
|
+
* - A request with no key goes to AuthGuard (<%= it.authProvider %>), which
|
|
38
|
+
* attaches the signed-in user's AuthContext to request.auth
|
|
39
|
+
<% } else { %>
|
|
40
|
+
* - No sign-in is configured (.apsorc has no auth block), so a request with no
|
|
41
|
+
* valid key is refused
|
|
48
42
|
<% } %>
|
|
43
|
+
*
|
|
49
44
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
50
45
|
* ScopeGuard:
|
|
51
46
|
* - Enforces data isolation based on scopeBy config
|
|
@@ -67,7 +62,6 @@ import { <%= entity %> } from '../<%= entity %>/<%= entity %>.entity';
|
|
|
67
62
|
<% /* Collect all unique entities */ %>
|
|
68
63
|
<% const allEntities = new Set(); %>
|
|
69
64
|
<% if (it.scopedEntities) { it.scopedEntities.forEach(e => allEntities.add(e.name)); } %>
|
|
70
|
-
<% it.authEntities.forEach(e => allEntities.add(e)); %>
|
|
71
65
|
<% const entityArray = Array.from(allEntities); %>
|
|
72
66
|
<% entityArray.forEach((entity, index) => { %>
|
|
73
67
|
<%= entity %><%= index < entityArray.length - 1 ? ',' : '' %>
|
|
@@ -75,21 +69,31 @@ import { <%= entity %> } from '../<%= entity %>/<%= entity %>.entity';
|
|
|
75
69
|
]),
|
|
76
70
|
],
|
|
77
71
|
providers: [
|
|
72
|
+
ApiKeyGuard,
|
|
78
73
|
<% if (it.hasAuth) { %>
|
|
79
74
|
AuthGuard,
|
|
80
75
|
<% } %>
|
|
76
|
+
<% if (it.mcpAuth) { %>
|
|
77
|
+
McpAuthProvider,
|
|
78
|
+
<% } %>
|
|
79
|
+
<% if (it.permissions) { %>
|
|
80
|
+
PermissionGuard,
|
|
81
|
+
<% } %>
|
|
81
82
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
82
83
|
ScopeGuard,
|
|
83
84
|
<% } %>
|
|
84
|
-
// Global guards
|
|
85
|
-
//
|
|
86
|
-
// config generate no guards at all and are protected at the edge by the
|
|
87
|
-
// API Gateway API key — so this does not conflict with that setup. Use the
|
|
88
|
-
// @Public() decorator to opt an individual route out of authentication.
|
|
89
|
-
<% if (it.hasAuth) { %>
|
|
85
|
+
// Global guards, in the order they run. ApiKeyGuard checks an API key and
|
|
86
|
+
// hands a request without one to AuthGuard when sign-in is configured.
|
|
90
87
|
{
|
|
91
88
|
provide: APP_GUARD,
|
|
92
|
-
|
|
89
|
+
useExisting: ApiKeyGuard,
|
|
90
|
+
},
|
|
91
|
+
<% if (it.permissions) { %>
|
|
92
|
+
// Global guards run in this order: roles are checked after the caller is
|
|
93
|
+
// known and before the scope guard loads any rows.
|
|
94
|
+
{
|
|
95
|
+
provide: APP_GUARD,
|
|
96
|
+
useClass: PermissionGuard,
|
|
93
97
|
},
|
|
94
98
|
<% } %>
|
|
95
99
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
@@ -100,9 +104,13 @@ import { <%= entity %> } from '../<%= entity %>/<%= entity %>.entity';
|
|
|
100
104
|
<% } %>
|
|
101
105
|
],
|
|
102
106
|
exports: [
|
|
107
|
+
ApiKeyGuard,
|
|
103
108
|
<% if (it.hasAuth) { %>
|
|
104
109
|
AuthGuard,
|
|
105
110
|
<% } %>
|
|
111
|
+
<% if (it.permissions) { %>
|
|
112
|
+
PermissionGuard,
|
|
113
|
+
<% } %>
|
|
106
114
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
107
115
|
ScopeGuard,
|
|
108
116
|
<% } %>
|
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
<%~ includeFile('../header.eta') %>
|
|
2
2
|
|
|
3
|
+
export * from './key.guard';
|
|
3
4
|
<% if (it.hasAuth) { %>
|
|
4
5
|
export * from './auth.guard';
|
|
5
6
|
<% } %>
|
|
7
|
+
<% if (it.permissions) { %>
|
|
8
|
+
export { PermissionGuard, ENTITY_PERMISSIONS, Permission } from './permission.guard';
|
|
9
|
+
<% } %>
|
|
6
10
|
<% if (it.scopedEntities && it.scopedEntities.length > 0) { %>
|
|
7
11
|
<% if (it.hasAuth) { %>
|
|
8
12
|
// When auth is configured, only export scope-specific items from scope.guard
|