@apso/cli 0.56.0 → 0.57.1
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/dist/commands/import/data.d.ts +1 -0
- package/dist/commands/import/data.js +8 -3
- package/dist/commands/import/{supabase.d.ts → index.d.ts} +4 -1
- package/dist/commands/import/{supabase.js → index.js} +19 -10
- package/dist/commands/schema/validate.js +5 -0
- package/dist/lib/access/cases.js +1 -2
- package/dist/lib/access/rules.json +1 -1
- package/dist/lib/api/services.js +15 -1
- package/dist/lib/base-command.d.ts +6 -0
- package/dist/lib/base-command.js +14 -0
- package/dist/lib/generators/go.d.ts +18 -0
- package/dist/lib/generators/go.js +40 -18
- package/dist/lib/generators/python.js +6 -7
- package/dist/lib/generators/typescript.js +48 -9
- package/dist/lib/guards.d.ts +43 -5
- package/dist/lib/guards.js +148 -18
- package/dist/lib/import/copy-data.d.ts +23 -5
- package/dist/lib/import/copy-data.js +45 -7
- package/dist/lib/import/index.d.ts +1 -1
- package/dist/lib/import/index.js +2 -1
- package/dist/lib/import/pg-data.d.ts +1 -1
- package/dist/lib/import/pg-data.js +10 -5
- package/dist/lib/templates/go/middleware/auth.eta +136 -7
- package/dist/lib/templates/go/services/service.eta +29 -1
- package/dist/lib/templates/guards/permission.guard.eta +15 -0
- package/dist/lib/templates/guards/scope.guard.eta +9 -5
- package/dist/lib/templates/python/auth.eta +100 -2
- package/dist/lib/templates/python/services/service.eta +19 -0
- package/dist/lib/templates/rest/controller-rest.eta +17 -2
- package/dist/lib/templates/rest/dto-rest.eta +20 -8
- package/dist/lib/templates/rest/index-module-rest.eta +5 -1
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +23 -14
- package/package.json +1 -1
|
@@ -600,6 +600,25 @@ type relationScope struct {
|
|
|
600
600
|
Table string
|
|
601
601
|
Tenant map[string]string
|
|
602
602
|
Relations map[string]relationHop
|
|
603
|
+
Nested []nestedScope
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// nestedScope is one scopeBy path through a parent (task.workspaceId): the
|
|
607
|
+
// entity's foreign key column, each parent on the way to the tenant (nearest
|
|
608
|
+
// first), and the tenant column on the last parent with the caller value it
|
|
609
|
+
// must equal.
|
|
610
|
+
type nestedScope struct {
|
|
611
|
+
Column string
|
|
612
|
+
Parents []nestedParent
|
|
613
|
+
Tenant string
|
|
614
|
+
Key string
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// nestedParent is a parent's table and its foreign key column to the next
|
|
618
|
+
// parent (empty on the last).
|
|
619
|
+
type nestedParent struct {
|
|
620
|
+
Table string
|
|
621
|
+
Column string
|
|
603
622
|
}
|
|
604
623
|
|
|
605
624
|
type relationHop struct {
|
|
@@ -624,6 +643,20 @@ var relationScopes = map[string]relationScope{
|
|
|
624
643
|
<%~ JSON.stringify(relation) %>: {Entity: <%~ JSON.stringify(hop[0]) %>, SameTenant: <%= hop[1] %>},
|
|
625
644
|
<% }) %>
|
|
626
645
|
},
|
|
646
|
+
Nested: []nestedScope{
|
|
647
|
+
<% for (const n of it.nestedScopes[name] ?? []) { %>
|
|
648
|
+
{
|
|
649
|
+
Column: <%~ JSON.stringify(n.column) %>,
|
|
650
|
+
Tenant: <%~ JSON.stringify(n.tenantColumn) %>,
|
|
651
|
+
Key: <%~ JSON.stringify(n.source) %>,
|
|
652
|
+
Parents: []nestedParent{
|
|
653
|
+
<% n.parents.forEach((p) => { %>
|
|
654
|
+
{Table: <%~ JSON.stringify(p.table) %>, Column: <%~ JSON.stringify(p.column) %>},
|
|
655
|
+
<% }) %>
|
|
656
|
+
},
|
|
657
|
+
},
|
|
658
|
+
<% } %>
|
|
659
|
+
},
|
|
627
660
|
},
|
|
628
661
|
<% }) %>
|
|
629
662
|
}
|
|
@@ -646,22 +679,77 @@ func skipsScope(a *AuthContext, e relationScope) bool {
|
|
|
646
679
|
func tenantWhere(a *AuthContext, e relationScope) (where string, args []interface{}, ok bool) {
|
|
647
680
|
var parts []string
|
|
648
681
|
for column, key := range e.Tenant {
|
|
649
|
-
v := a
|
|
650
|
-
switch key {
|
|
651
|
-
case "userId":
|
|
652
|
-
v = a.UserID
|
|
653
|
-
case "email":
|
|
654
|
-
v = a.Email
|
|
655
|
-
}
|
|
682
|
+
v := callerValue(a, key)
|
|
656
683
|
if v == "" {
|
|
657
684
|
return "", nil, false
|
|
658
685
|
}
|
|
659
686
|
parts = append(parts, `CAST("`+column+`" AS TEXT) = ?`)
|
|
660
687
|
args = append(args, v)
|
|
661
688
|
}
|
|
689
|
+
nested, nestedArgs, ok := nestedWhere(a, e, "")
|
|
690
|
+
if !ok {
|
|
691
|
+
return "", nil, false
|
|
692
|
+
}
|
|
693
|
+
if nested != "" {
|
|
694
|
+
parts = append(parts, nested)
|
|
695
|
+
args = append(args, nestedArgs...)
|
|
696
|
+
}
|
|
662
697
|
return strings.Join(parts, " AND "), args, true
|
|
663
698
|
}
|
|
664
699
|
|
|
700
|
+
// callerValue is the caller's value for a scopeBy key: its user id, its email,
|
|
701
|
+
// or (any other name) its tenant.
|
|
702
|
+
func callerValue(a *AuthContext, key string) string {
|
|
703
|
+
switch key {
|
|
704
|
+
case "userId":
|
|
705
|
+
return a.UserID
|
|
706
|
+
case "email":
|
|
707
|
+
return a.Email
|
|
708
|
+
}
|
|
709
|
+
return a.WorkspaceID
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// parentCond is the condition that keeps the rows of n.Parents[i] to the
|
|
713
|
+
// caller's tenant: the tenant column on the last parent, reached through each
|
|
714
|
+
// parent's foreign key to the next. It takes one argument, the caller's value.
|
|
715
|
+
func parentCond(n nestedScope, i int) string {
|
|
716
|
+
last := n.Parents[len(n.Parents)-1].Table
|
|
717
|
+
cond := `CAST("` + last + `"."` + n.Tenant + `" AS TEXT) = ?`
|
|
718
|
+
for j := len(n.Parents) - 1; j > i; j-- {
|
|
719
|
+
child, parent := n.Parents[j-1], n.Parents[j].Table
|
|
720
|
+
cond = `"` + child.Table + `"."` + child.Column + `" IN (SELECT "` + parent + `"."id" FROM "` + parent + `" WHERE ` + cond + `)`
|
|
721
|
+
}
|
|
722
|
+
return cond
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// nestedWhere is the SQL condition, with its arguments, that keeps rows of e
|
|
726
|
+
// to the caller's tenant through each scopeBy path that runs through a parent
|
|
727
|
+
// (task.workspaceId): the foreign key must name a parent in that tenant.
|
|
728
|
+
// table, when set, qualifies the foreign key column. ok is false when the
|
|
729
|
+
// caller has no value for one of the paths.
|
|
730
|
+
func nestedWhere(a *AuthContext, e relationScope, table string) (where string, args []interface{}, ok bool) {
|
|
731
|
+
var parts []string
|
|
732
|
+
for _, n := range e.Nested {
|
|
733
|
+
v := callerValue(a, n.Key)
|
|
734
|
+
if v == "" {
|
|
735
|
+
return "", nil, false
|
|
736
|
+
}
|
|
737
|
+
column := `"` + n.Column + `"`
|
|
738
|
+
if table != "" {
|
|
739
|
+
column = `"` + table + `".` + column
|
|
740
|
+
}
|
|
741
|
+
parent := n.Parents[0].Table
|
|
742
|
+
parts = append(parts, column+` IN (SELECT "`+parent+`"."id" FROM "`+parent+`" WHERE `+parentCond(n, 0)+`)`)
|
|
743
|
+
args = append(args, v)
|
|
744
|
+
}
|
|
745
|
+
return strings.Join(parts, " AND "), args, true
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// NestedWhere is nestedWhere for a service's own queries on entity.
|
|
749
|
+
func NestedWhere(a *AuthContext, entity, table string) (string, []interface{}, bool) {
|
|
750
|
+
return nestedWhere(a, relationScopes[entity], table)
|
|
751
|
+
}
|
|
752
|
+
|
|
665
753
|
// RelationLoad is one relation to preload: its path as the request names it
|
|
666
754
|
// (author, author.posts) and the conditions its rows must meet, as arguments
|
|
667
755
|
// for gorm's Preload.
|
|
@@ -725,6 +813,47 @@ func RelationLoads(ctx context.Context, root, path string) (loads []RelationLoad
|
|
|
725
813
|
// entity that the caller cannot read. Handlers answer it with 403.
|
|
726
814
|
var ErrReference = errors.New("you do not have access to a row this request references")
|
|
727
815
|
|
|
816
|
+
// CheckParents checks, on a write to entity, each foreign key its scopeBy runs
|
|
817
|
+
// through (task.workspaceId): the parent it names must be in the caller's
|
|
818
|
+
// tenant, or the result is ErrReference. sent maps the foreign key column to
|
|
819
|
+
// the value in the body; a pointer may be given, and nil or zero means not
|
|
820
|
+
// sent. A service caller or a role that skips the entity's scope is not limited.
|
|
821
|
+
func CheckParents(ctx context.Context, db *gorm.DB, entity string, sent map[string]interface{}) error {
|
|
822
|
+
a, _ := FromContext(ctx)
|
|
823
|
+
if a == nil {
|
|
824
|
+
a = &AuthContext{}
|
|
825
|
+
}
|
|
826
|
+
e := relationScopes[entity]
|
|
827
|
+
if a.ServiceID != "" || skipsScope(a, e) {
|
|
828
|
+
return nil
|
|
829
|
+
}
|
|
830
|
+
for _, n := range e.Nested {
|
|
831
|
+
rv := reflect.ValueOf(sent[n.Column])
|
|
832
|
+
for rv.Kind() == reflect.Ptr && !rv.IsNil() {
|
|
833
|
+
rv = rv.Elem()
|
|
834
|
+
}
|
|
835
|
+
if !rv.IsValid() || rv.Kind() == reflect.Ptr || rv.IsZero() {
|
|
836
|
+
continue
|
|
837
|
+
}
|
|
838
|
+
v := callerValue(a, n.Key)
|
|
839
|
+
if v == "" {
|
|
840
|
+
return ErrReference
|
|
841
|
+
}
|
|
842
|
+
parent := n.Parents[0].Table
|
|
843
|
+
var found int64
|
|
844
|
+
if err := db.WithContext(ctx).Table(parent).
|
|
845
|
+
Where(`"`+parent+`"."id" = ?`, rv.Interface()).
|
|
846
|
+
Where(parentCond(n, 0), v).
|
|
847
|
+
Count(&found).Error; err != nil {
|
|
848
|
+
return err
|
|
849
|
+
}
|
|
850
|
+
if found == 0 {
|
|
851
|
+
return ErrReference
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
return nil
|
|
855
|
+
}
|
|
856
|
+
|
|
728
857
|
// CheckReferences is the one place that checks the foreign keys of a write
|
|
729
858
|
// (R8). references maps a tenant-scoped entity to the ids a body names in
|
|
730
859
|
// foreign keys to it; an id may be a pointer, and nil or zero means not sent.
|
|
@@ -79,6 +79,14 @@ func (s *<%= it.entityName %>Service) scoped(ctx context.Context, q *gorm.DB, op
|
|
|
79
79
|
// Compared as text: token claims are strings, the column may be a number or uuid.
|
|
80
80
|
q = q.Where(`CAST("`+table+`"."`+col+`" AS TEXT) = ?`, v)
|
|
81
81
|
}
|
|
82
|
+
<% if (it.scope.nested.length > 0) { %>
|
|
83
|
+
// A path through a parent (task.workspaceId): the parent must be in the caller's tenant.
|
|
84
|
+
nested, nestedArgs, hasTenant := middleware.NestedWhere(a, <%~ JSON.stringify(it.entityName) %>, table)
|
|
85
|
+
if !hasTenant {
|
|
86
|
+
return nil, nil, ErrForbidden
|
|
87
|
+
}
|
|
88
|
+
q = q.Where(nested, nestedArgs...)
|
|
89
|
+
<% } %>
|
|
82
90
|
return q, values, nil
|
|
83
91
|
}
|
|
84
92
|
<% } %>
|
|
@@ -199,7 +207,7 @@ func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%=
|
|
|
199
207
|
<% if (it.scope) { %>
|
|
200
208
|
|
|
201
209
|
// The caller's tenant, never one from the body (.apsorc scopeBy).
|
|
202
|
-
_, scopeVals
|
|
210
|
+
_, <%= it.scope.fields.length > 0 ? 'scopeVals' : '_' %>, scopeErr := s.scoped(ctx, s.db, "create")
|
|
203
211
|
if scopeErr != nil {
|
|
204
212
|
return nil, scopeErr
|
|
205
213
|
}
|
|
@@ -210,6 +218,16 @@ func (s *<%= it.entityName %>Service) Create(ctx context.Context, input *dto.<%=
|
|
|
210
218
|
}
|
|
211
219
|
}
|
|
212
220
|
<% }) %>
|
|
221
|
+
<% if (it.scope.nested.length > 0) { %>
|
|
222
|
+
// A parent this entity is scoped through must be in the caller's tenant.
|
|
223
|
+
if err := middleware.CheckParents(ctx, s.db, <%~ JSON.stringify(it.entityName) %>, map[string]interface{}{
|
|
224
|
+
<% it.scope.nested.forEach((n) => { %>
|
|
225
|
+
<%~ JSON.stringify(n.column) %>: item.<%= n.goField %>,
|
|
226
|
+
<% }) %>
|
|
227
|
+
}); err != nil {
|
|
228
|
+
return nil, err
|
|
229
|
+
}
|
|
230
|
+
<% } %>
|
|
213
231
|
<% } %>
|
|
214
232
|
<% if (it.references.length) { %>
|
|
215
233
|
|
|
@@ -281,6 +299,16 @@ func (s *<%= it.entityName %>Service) Update(ctx context.Context, id string, inp
|
|
|
281
299
|
for col := range scopeVals {
|
|
282
300
|
delete(updates, col)
|
|
283
301
|
}
|
|
302
|
+
<% if (it.scope.nested.length > 0) { %>
|
|
303
|
+
// A new parent must be in the caller's tenant.
|
|
304
|
+
if err := middleware.CheckParents(ctx, s.db, <%~ JSON.stringify(it.entityName) %>, map[string]interface{}{
|
|
305
|
+
<% it.scope.nested.forEach((n) => { %>
|
|
306
|
+
<%~ JSON.stringify(n.column) %>: updates[<%~ JSON.stringify(n.column) %>],
|
|
307
|
+
<% }) %>
|
|
308
|
+
}); err != nil {
|
|
309
|
+
return nil, err
|
|
310
|
+
}
|
|
311
|
+
<% } %>
|
|
284
312
|
<% } %>
|
|
285
313
|
<% if (it.references.length) { %>
|
|
286
314
|
if err := middleware.CheckReferences(ctx, s.db, map[string][]interface{}{
|
|
@@ -45,6 +45,21 @@ export const PERMISSION_KEY = 'apsoPermission';
|
|
|
45
45
|
export const Permission = (permission: string, ...roles: string[]) =>
|
|
46
46
|
SetMetadata(PERMISSION_KEY, { permission, roles });
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Adds a role rule to each named handler's OpenAPI description. Goes above
|
|
50
|
+
* @Crud on a controller: @Crud writes its own operation text, and a class
|
|
51
|
+
* decorator listed above it runs after it.
|
|
52
|
+
*/
|
|
53
|
+
export const DescribeRoles = (rules: Record<string, string>): ClassDecorator => (target: any) => {
|
|
54
|
+
for (const [handler, rule] of Object.entries(rules)) {
|
|
55
|
+
const fn = target.prototype[handler];
|
|
56
|
+
if (typeof fn !== 'function') continue;
|
|
57
|
+
const op = Reflect.getMetadata('swagger/apiOperation', fn) ?? {};
|
|
58
|
+
const description = [rule, op.description].filter(Boolean).join('\n\n');
|
|
59
|
+
Reflect.defineMetadata('swagger/apiOperation', { ...op, description }, fn);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
48
63
|
const OPERATIONS: Record<string, Operation> = {
|
|
49
64
|
GET: 'read',
|
|
50
65
|
HEAD: 'read',
|
|
@@ -283,11 +283,15 @@ export class ScopeGuard implements CanActivate {
|
|
|
283
283
|
const relations: string[] = [];
|
|
284
284
|
for (const scope of scopeConfig.scopes) {
|
|
285
285
|
if (!scope.direct && scope.path) {
|
|
286
|
-
//
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
286
|
+
// Every relation on the way to the tenant column:
|
|
287
|
+
// 'task.project.workspaceId' -> 'task', 'task.project'
|
|
288
|
+
const hops = scope.path.split('.').slice(0, -1);
|
|
289
|
+
hops.forEach((_hop, i) => {
|
|
290
|
+
const relationName = hops.slice(0, i + 1).join('.');
|
|
291
|
+
if (!relations.includes(relationName)) {
|
|
292
|
+
relations.push(relationName);
|
|
293
|
+
}
|
|
294
|
+
});
|
|
291
295
|
}
|
|
292
296
|
}
|
|
293
297
|
|
|
@@ -43,6 +43,7 @@ import jwt
|
|
|
43
43
|
from fastapi import HTTPException, Request, Response, status
|
|
44
44
|
from jwt import PyJWKClient
|
|
45
45
|
from sqlalchemy import String, cast, func, select
|
|
46
|
+
from sqlalchemy.orm import aliased
|
|
46
47
|
from starlette.concurrency import run_in_threadpool
|
|
47
48
|
|
|
48
49
|
|
|
@@ -409,6 +410,98 @@ def relation_refused(auth: Optional[AuthContext], root: str, path: str) -> Optio
|
|
|
409
410
|
return None
|
|
410
411
|
|
|
411
412
|
|
|
413
|
+
# entity -> its scopeBy paths through a parent (task.workspaceId), each as
|
|
414
|
+
# {"field": the entity's foreign key to the first parent, "parents": [{"entity",
|
|
415
|
+
# "field": its foreign key to the next parent, absent on the last}],
|
|
416
|
+
# "tenantField": the tenant column on the last parent, "source": "userId",
|
|
417
|
+
# "email" or "tenant"}.
|
|
418
|
+
NESTED_SCOPES: dict = json.loads(<%~ JSON.stringify(JSON.stringify(it.nestedScopes)) %>)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _caller_value(auth: Optional[AuthContext], source: str) -> Any:
|
|
422
|
+
"""The caller's value for a scopeBy key: its user id, its email, or its tenant."""
|
|
423
|
+
by_key = {"userId": "user_id", "email": "email"}
|
|
424
|
+
return getattr(auth, by_key.get(source, "workspace_id"), None)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _skips_scope(auth: Optional[AuthContext], entity: str) -> bool:
|
|
428
|
+
"""A service caller, or a role that skips `entity`'s tenant scope."""
|
|
429
|
+
if auth is None:
|
|
430
|
+
return False
|
|
431
|
+
bypass = (RELATION_SCOPES.get(entity) or {}).get("bypassRoles") or []
|
|
432
|
+
return bool(auth.service_id) or bool(set(auth.roles) & set(bypass))
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _parents_in_tenant(nested: dict, index: int, value: Any) -> Any:
|
|
436
|
+
"""
|
|
437
|
+
The ids of the parent at `index` of a scopeBy path that are in the caller's
|
|
438
|
+
tenant: the tenant column on the last parent, reached through each parent's
|
|
439
|
+
foreign key to the next. Each parent is aliased, so a path through the same
|
|
440
|
+
table twice does not correlate with the query around it.
|
|
441
|
+
"""
|
|
442
|
+
from . import models
|
|
443
|
+
|
|
444
|
+
parents = nested["parents"]
|
|
445
|
+
parent = aliased(getattr(models, parents[index]["entity"]))
|
|
446
|
+
if index == len(parents) - 1:
|
|
447
|
+
condition = cast(getattr(parent, nested["tenantField"]), String) == str(value)
|
|
448
|
+
else:
|
|
449
|
+
condition = getattr(parent, parents[index]["field"]).in_(_parents_in_tenant(nested, index + 1, value))
|
|
450
|
+
return select(parent.id).where(condition)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def nested_conditions(auth: Optional[AuthContext], entity: str, model: Any) -> list:
|
|
454
|
+
"""
|
|
455
|
+
SQL conditions that keep rows of `entity` (as `model`) to the caller's
|
|
456
|
+
tenant through each scopeBy path that runs through a parent
|
|
457
|
+
(task.workspaceId): the foreign key must name a parent in that tenant.
|
|
458
|
+
Empty for a service caller or a role that skips the entity's scope; 403
|
|
459
|
+
when the caller has no value for a path.
|
|
460
|
+
"""
|
|
461
|
+
nested = NESTED_SCOPES.get(entity) or []
|
|
462
|
+
if not nested or _skips_scope(auth, entity):
|
|
463
|
+
return []
|
|
464
|
+
conditions = []
|
|
465
|
+
for n in nested:
|
|
466
|
+
value = _caller_value(auth, n["source"])
|
|
467
|
+
if value in (None, ""):
|
|
468
|
+
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No tenant in the auth context")
|
|
469
|
+
conditions.append(getattr(model, n["field"]).in_(_parents_in_tenant(n, 0, value)))
|
|
470
|
+
return conditions
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
async def check_parents(auth: Optional[AuthContext], db: Any, entity: str, rows: List[dict]) -> None:
|
|
474
|
+
"""
|
|
475
|
+
On a write to `entity`, each foreign key its scopeBy runs through
|
|
476
|
+
(task.workspaceId) must name a parent in the caller's tenant; otherwise
|
|
477
|
+
403. A key that is absent or null is not checked, and a service caller or a
|
|
478
|
+
role that skips the entity's scope is not limited.
|
|
479
|
+
"""
|
|
480
|
+
from . import models
|
|
481
|
+
|
|
482
|
+
nested = NESTED_SCOPES.get(entity) or []
|
|
483
|
+
if not nested or _skips_scope(auth, entity):
|
|
484
|
+
return
|
|
485
|
+
for n in nested:
|
|
486
|
+
ids = {row.get(n["field"]) for row in rows} - {None}
|
|
487
|
+
if not ids:
|
|
488
|
+
continue
|
|
489
|
+
value = _caller_value(auth, n["source"])
|
|
490
|
+
parent = getattr(models, n["parents"][0]["entity"])
|
|
491
|
+
found = None
|
|
492
|
+
if value not in (None, ""):
|
|
493
|
+
found = await db.execute(
|
|
494
|
+
select(func.count())
|
|
495
|
+
.select_from(parent)
|
|
496
|
+
.where(parent.id.in_(ids), parent.id.in_(_parents_in_tenant(n, 0, value)))
|
|
497
|
+
)
|
|
498
|
+
if found is None or found.scalar() != len(ids):
|
|
499
|
+
raise HTTPException(
|
|
500
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
501
|
+
detail="You do not have access to a row this request references",
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
|
|
412
505
|
def tenant_values(auth: Optional[AuthContext], entity: str) -> Optional[dict]:
|
|
413
506
|
"""
|
|
414
507
|
The caller's value for each scopeBy field of `entity`, or None when the
|
|
@@ -445,7 +538,10 @@ def relation_conditions(auth: Optional[AuthContext], root: str, name: str, targe
|
|
|
445
538
|
hop = ((RELATION_SCOPES.get(root) or {}).get("relations") or {}).get(name)
|
|
446
539
|
# Only a hop the rule allows as a same-tenant one; any other is refused or not limited.
|
|
447
540
|
values = tenant_values(auth, hop[0]) if hop and hop[1] else None
|
|
448
|
-
|
|
541
|
+
if values is None:
|
|
542
|
+
return []
|
|
543
|
+
# A target scoped through a parent has no tenant column of its own.
|
|
544
|
+
return _tenant_conditions(target, values) + nested_conditions(auth, hop[0], target)
|
|
449
545
|
|
|
450
546
|
|
|
451
547
|
async def check_references(auth: Optional[AuthContext], db: Any, references: dict) -> None:
|
|
@@ -465,7 +561,9 @@ async def check_references(auth: Optional[AuthContext], db: Any, references: dic
|
|
|
465
561
|
continue
|
|
466
562
|
model = getattr(models, entity)
|
|
467
563
|
found = await db.execute(
|
|
468
|
-
select(func.count())
|
|
564
|
+
select(func.count())
|
|
565
|
+
.select_from(model)
|
|
566
|
+
.where(model.id.in_(ids), *_tenant_conditions(model, values), *nested_conditions(auth, entity, model))
|
|
469
567
|
)
|
|
470
568
|
if found.scalar() != len(ids):
|
|
471
569
|
raise HTTPException(
|
|
@@ -11,6 +11,9 @@ from sqlalchemy import String, cast
|
|
|
11
11
|
<% if (it.references.length) { %>
|
|
12
12
|
from ..auth import check_references
|
|
13
13
|
<% } %>
|
|
14
|
+
<% if (it.scope && it.scope.nested.length) { %>
|
|
15
|
+
from ..auth import check_parents, nested_conditions
|
|
16
|
+
<% } %>
|
|
14
17
|
from ..models.<%= it.entityName.toLowerCase() %> import <%= it.entityName %>
|
|
15
18
|
from ..schemas.<%= it.entityName.toLowerCase() %> import <%= it.entityName %>Create, <%= it.entityName %>Update
|
|
16
19
|
from ..utils.query import QueryBuilder, QueryOptions, PaginatedResult
|
|
@@ -57,6 +60,10 @@ class <%= it.entityName %>Service:
|
|
|
57
60
|
cast(getattr(<%= it.entityName %>, field), String) == str(value)
|
|
58
61
|
for field, value in self._scope_values(op).items()
|
|
59
62
|
]
|
|
63
|
+
<% if (it.scope.nested.length) { %>
|
|
64
|
+
# A path through a parent (task.workspaceId): the parent must be in the caller's tenant.
|
|
65
|
+
scope += nested_conditions(self.auth, <%~ JSON.stringify(it.entityName) %>, <%= it.entityName %>)
|
|
66
|
+
<% } %>
|
|
60
67
|
return QueryBuilder(<%= it.entityName %>, self.db, auth=self.auth, scope=scope)
|
|
61
68
|
|
|
62
69
|
def _with_tenant(self, payload: dict) -> dict:
|
|
@@ -115,6 +122,9 @@ class <%= it.entityName %>Service:
|
|
|
115
122
|
payload = data.model_dump(exclude_unset=True)
|
|
116
123
|
<% if (it.scope) { %>
|
|
117
124
|
payload = self._with_tenant(payload)
|
|
125
|
+
<% if (it.scope.nested.length) { %>
|
|
126
|
+
await check_parents(self.auth, self.db, <%~ JSON.stringify(it.entityName) %>, [payload])
|
|
127
|
+
<% } %>
|
|
118
128
|
<% } %>
|
|
119
129
|
<% if (it.references.length) { %>
|
|
120
130
|
await self._check_references([payload])
|
|
@@ -132,6 +142,9 @@ class <%= it.entityName %>Service:
|
|
|
132
142
|
payloads = [item.model_dump(exclude_unset=True) for item in data]
|
|
133
143
|
<% if (it.scope) { %>
|
|
134
144
|
payloads = [self._with_tenant(payload) for payload in payloads]
|
|
145
|
+
<% if (it.scope.nested.length) { %>
|
|
146
|
+
await check_parents(self.auth, self.db, <%~ JSON.stringify(it.entityName) %>, payloads)
|
|
147
|
+
<% } %>
|
|
135
148
|
<% } %>
|
|
136
149
|
<% if (it.references.length) { %>
|
|
137
150
|
await self._check_references(payloads)
|
|
@@ -160,6 +173,9 @@ class <%= it.entityName %>Service:
|
|
|
160
173
|
# A scoped row cannot move to another tenant.
|
|
161
174
|
for field in self._scope_values("update"):
|
|
162
175
|
update_data.pop(field, None)
|
|
176
|
+
<% if (it.scope.nested.length) { %>
|
|
177
|
+
await check_parents(self.auth, self.db, <%~ JSON.stringify(it.entityName) %>, [update_data])
|
|
178
|
+
<% } %>
|
|
163
179
|
<% } %>
|
|
164
180
|
<% if (it.references.length) { %>
|
|
165
181
|
await self._check_references([update_data])
|
|
@@ -187,6 +203,9 @@ class <%= it.entityName %>Service:
|
|
|
187
203
|
<% if (it.scope) { %>
|
|
188
204
|
for field in self._scope_values("update"):
|
|
189
205
|
replace_data.pop(field, None)
|
|
206
|
+
<% if (it.scope.nested.length) { %>
|
|
207
|
+
await check_parents(self.auth, self.db, <%~ JSON.stringify(it.entityName) %>, [replace_data])
|
|
208
|
+
<% } %>
|
|
190
209
|
<% } %>
|
|
191
210
|
<% if (it.references.length) { %>
|
|
192
211
|
await self._check_references([replace_data])
|
|
@@ -2,11 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
import { Controller, Body<% if (it.relationAccess) { %>, UseInterceptors<% } %> } from "@nestjs/common";
|
|
4
4
|
import { Crud, <% if (it.crudAuth.length || it.crudAuthNested.length) { %>CrudAuth, <% } %>CrudController, Override, ParsedRequest, CrudRequest, ParsedBody, CreateManyDto } from '@apso/crud';
|
|
5
|
-
import { ApiTags, ApiResponse, ApiOperation, ApiBody } from '@nestjs/swagger';
|
|
5
|
+
import { ApiTags, ApiResponse, ApiOperation, ApiBody, ApiExtraModels, ApiUnauthorizedResponse<% if (it.hasAuth) { %>, ApiForbiddenResponse<% } %> } from '@nestjs/swagger';
|
|
6
6
|
<% if (it.mcp.length) { %>
|
|
7
7
|
import { McpTool } from '@apso/mcp';
|
|
8
8
|
<% } %>
|
|
9
|
-
|
|
9
|
+
// The row schema is named after the entity (<%= it.entityName %>), the name the responses reference.
|
|
10
|
+
import {<%= it.entityName %>Create, <%= it.entityName %>Update, <%= it.entityName %> as <%= it.entityName %>Row} from './dtos/<%= it.entityName%>.dto'
|
|
10
11
|
// The entity, not the response DTO: the documented filter parameters (one per
|
|
11
12
|
// column, which is also what an MCP list tool accepts) come from its columns.
|
|
12
13
|
import { <%= it.entityName %> } from './<%= it.entityName %>.entity';
|
|
@@ -14,6 +15,9 @@ import {<%= it.svcName %>} from './<%= it.entityName %>.service';
|
|
|
14
15
|
<% if (it.relationAccess) { %>
|
|
15
16
|
import { RelationAccess, RelationRoot } from '../guards/relations.interceptor';
|
|
16
17
|
<% } %>
|
|
18
|
+
<% if (Object.keys(it.roleDocs).length) { %>
|
|
19
|
+
import { DescribeRoles } from '../guards/permission.guard';
|
|
20
|
+
<% } %>
|
|
17
21
|
|
|
18
22
|
<%
|
|
19
23
|
// Postgres computes a generated column, so a value sent for one is dropped
|
|
@@ -45,6 +49,10 @@ const skipScope = (req: any) => {
|
|
|
45
49
|
return roles.some((r) => BYPASS_ROLES.includes(r));
|
|
46
50
|
};
|
|
47
51
|
<% } %>
|
|
52
|
+
<% if (Object.keys(it.roleDocs).length) { %>
|
|
53
|
+
// Above @Crud, which writes its own operation text: adds each role rule to it.
|
|
54
|
+
@DescribeRoles(<%~ JSON.stringify(it.roleDocs, null, 4) %>)
|
|
55
|
+
<% } %>
|
|
48
56
|
<% if (it.relationAccess) { %>
|
|
49
57
|
// Above @Crud, so it runs after @Crud's interceptor has parsed the request.
|
|
50
58
|
@UseInterceptors(RelationAccess)
|
|
@@ -123,6 +131,13 @@ const skipScope = (req: any) => {
|
|
|
123
131
|
<% } %>
|
|
124
132
|
|
|
125
133
|
@Controller('<%= it.pluralEntityName %>')
|
|
134
|
+
@ApiExtraModels(<%= it.entityName %>Row)
|
|
135
|
+
<% if (it.hasAuth) { %>
|
|
136
|
+
@ApiUnauthorizedResponse({ description: 'No valid sign-in token (Authorization: Bearer) or API key (x-api-key).' })
|
|
137
|
+
@ApiForbiddenResponse({ description: "The token's role does not allow this operation, or the record is outside the caller's tenant." })
|
|
138
|
+
<% } else { %>
|
|
139
|
+
@ApiUnauthorizedResponse({ description: 'No valid API key (x-api-key).' })
|
|
140
|
+
<% } %>
|
|
126
141
|
@ApiTags('<%= it.pluralEntityName %>')
|
|
127
142
|
export class <%= it.ctrlName %> implements CrudController<<%= it.entityName %>>{
|
|
128
143
|
constructor(public service: <%= it.svcName %>) {}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
<%~ includeFile('./header.eta') %>
|
|
2
2
|
|
|
3
|
-
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
|
3
|
+
import { ApiHideProperty, ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
|
4
4
|
import {
|
|
5
5
|
IsString,
|
|
6
6
|
IsNumber,
|
|
@@ -19,6 +19,10 @@ import { Type } from 'class-transformer';
|
|
|
19
19
|
<% if (it.importEnums) { %>
|
|
20
20
|
import * as enums from '../../enums';
|
|
21
21
|
<% } %>
|
|
22
|
+
<% /* Enum values go in the OpenAPI document, as one named schema per enum. */ %>
|
|
23
|
+
<% const apiOpts = (f) => f.dataType.includes("Enum") ? `{ enum: enums.${f.dataType}, enumName: '${f.dataType}' }` : ''; %>
|
|
24
|
+
<% /* Postgres numeric reads back as a string ("12.50"), so the row schema says so. */ %>
|
|
25
|
+
<% const rowOpts = (f) => (f.type === 'numeric' || f.type === 'decimal') ? `{ type: String, format: 'decimal', description: 'A decimal, sent as a string ("12.50") to keep its precision.' }` : apiOpts(f); %>
|
|
22
26
|
|
|
23
27
|
export class <%= it.entityName %>Create {
|
|
24
28
|
<% if (it.addDefaultPKProperty && (it.primaryKeyType === 'uuid' || it.primaryKeyType === 'text')) { %>
|
|
@@ -29,11 +33,15 @@ export class <%= it.entityName %>Create {
|
|
|
29
33
|
|
|
30
34
|
<% } -%>
|
|
31
35
|
<% it.columns.filter((field) => !field.generated).forEach((field) => { -%>
|
|
32
|
-
<% if (
|
|
33
|
-
|
|
36
|
+
<% if (field.serverSet) { -%>
|
|
37
|
+
// Set by the server from the caller's tenant (scopeBy).
|
|
38
|
+
@ApiHideProperty()
|
|
39
|
+
@IsOptional()
|
|
40
|
+
<% } else if (!field.required) { -%>
|
|
41
|
+
@ApiPropertyOptional(<%~ apiOpts(field) %>)
|
|
34
42
|
@IsOptional()
|
|
35
43
|
<% } else { -%>
|
|
36
|
-
@ApiProperty()
|
|
44
|
+
@ApiProperty(<%~ apiOpts(field) %>)
|
|
37
45
|
@IsNotEmpty()
|
|
38
46
|
<% } -%>
|
|
39
47
|
<% if (field.dataType.includes("Enum")) { -%>
|
|
@@ -99,7 +107,11 @@ export class <%= it.entityName %>Create {
|
|
|
99
107
|
|
|
100
108
|
export class <%= it.entityName %>Update {
|
|
101
109
|
<% it.columns.filter((field) => !field.generated).forEach((field) => { -%>
|
|
102
|
-
|
|
110
|
+
<% if (field.serverSet) { -%>
|
|
111
|
+
@ApiHideProperty()
|
|
112
|
+
<% } else { -%>
|
|
113
|
+
@ApiPropertyOptional(<%~ apiOpts(field) %>)
|
|
114
|
+
<% } -%>
|
|
103
115
|
@IsOptional()
|
|
104
116
|
<% if (field.dataType.includes("Enum")) { -%>
|
|
105
117
|
@IsEnum(enums.<%= field.dataType %>)
|
|
@@ -169,12 +181,12 @@ export class <%= it.entityName %> {
|
|
|
169
181
|
|
|
170
182
|
<% } -%>
|
|
171
183
|
<% it.columns.forEach((field) => { -%>
|
|
172
|
-
<% if (
|
|
173
|
-
@ApiPropertyOptional()
|
|
184
|
+
<% if (field.nullable) { -%>
|
|
185
|
+
@ApiPropertyOptional(<%~ rowOpts(field) %>)
|
|
174
186
|
<%= field.name %>?: <% if (field.dataType.includes("Enum")) { %>enums.<%= field.dataType %><% } else if (field.type === 'json' || field.type === 'json-plain') { %>Record<string, any><% } else if (field.type === 'timestamp' || field.type === 'timestamptz') { %>Date<% } else { %><%= field.dataType %><% } %>;
|
|
175
187
|
|
|
176
188
|
<% } else { -%>
|
|
177
|
-
@ApiProperty()
|
|
189
|
+
@ApiProperty(<%~ rowOpts(field) %>)
|
|
178
190
|
<%= field.name %>: <% if (field.dataType.includes("Enum")) { %>enums.<%= field.dataType %><% } else if (field.type === 'json' || field.type === 'json-plain') { %>Record<string, any><% } else if (field.type === 'timestamp' || field.type === 'timestamptz') { %>Date<% } else { %><%= field.dataType %><% } %>;
|
|
179
191
|
|
|
180
192
|
<% } -%>
|
|
@@ -20,4 +20,8 @@ GuardsModule,
|
|
|
20
20
|
<% if (it.schemaExtras) { %>
|
|
21
21
|
SchemaExtrasModule,
|
|
22
22
|
<% } %>
|
|
23
|
-
]
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
// The OpenAPI info.description: who signs callers in, how records are scoped
|
|
26
|
+
// and which operations need which role (from .apsorc).
|
|
27
|
+
export const apiDescription = <%~ JSON.stringify(it.apiDescription) %>;
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@apso/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.57.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@apso/cli",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.57.1",
|
|
10
10
|
"license": "Apache-2.0",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@apso/schema-tools": "^0.2.3",
|