@apso/cli 0.56.0 → 0.57.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.
@@ -108,18 +108,46 @@ export interface DirectScopeField {
108
108
  /** userId and email map to the caller's own; anything else is the tenant. */
109
109
  source: "userId" | "email" | "tenant";
110
110
  }
111
+ /**
112
+ * One scopeBy path through parents (task.project.organizationId), resolved to
113
+ * the foreign keys it follows, for services that filter in SQL (Go, Python).
114
+ */
115
+ export interface NestedScopeData {
116
+ /** The entity's foreign key to the first parent, as .apsorc names it (taskId). */
117
+ field: string;
118
+ /**
119
+ * Each parent on the way to the tenant, nearest first: the entity, and its
120
+ * foreign key to the next parent (none on the last).
121
+ */
122
+ parents: {
123
+ entity: string;
124
+ field?: string;
125
+ }[];
126
+ /** The field on the last parent that holds the tenant. */
127
+ tenantField: string;
128
+ /** userId and email map to the caller's own; anything else is the tenant. */
129
+ source: "userId" | "email" | "tenant";
130
+ }
111
131
  /** What Go and Python services need to scope one entity. */
112
132
  export interface EntityScopeData {
113
133
  fields: DirectScopeField[];
134
+ /** Paths through a parent; empty unless the relationship map was given. */
135
+ nested: NestedScopeData[];
114
136
  bypassRoles: string[];
115
137
  }
138
+ /**
139
+ * The scopeBy paths of an entity that run through parents, each resolved hop
140
+ * by hop. Every step before the last must be a many-to-one relationship: its
141
+ * foreign key is what the SQL filter follows.
142
+ */
143
+ export declare function nestedScopes(entity: Entity, relationshipMap: RelationshipMap): NestedScopeData[];
116
144
  /**
117
145
  * The direct scopeBy fields of an entity, for services that filter in their
118
146
  * own queries (Go, Python). Undefined without auth: with no caller identity
119
- * there is no tenant to scope by. Nested paths (task.workspaceId) are not
120
- * included; see hasNestedScopes.
147
+ * there is no tenant to scope by. Paths through a parent (task.workspaceId)
148
+ * are resolved only when the relationship map is given.
121
149
  */
122
- export declare function entityScope(entity: Entity, hasAuth: boolean): EntityScopeData | undefined;
150
+ export declare function entityScope(entity: Entity, hasAuth: boolean, relationshipMap?: RelationshipMap): EntityScopeData | undefined;
123
151
  /** One entity in the relation table every generated service checks. */
124
152
  export interface RelationScope {
125
153
  /** Set when the entity's reads are tenant-scoped: the roles that skip its scope. */
@@ -154,8 +182,6 @@ export interface RelationScope {
154
182
  * Undefined without auth or when no entity is scoped.
155
183
  */
156
184
  export declare function relationScopes(entities: Entity[], relationshipMap: RelationshipMap | undefined, hasAuth: boolean): Record<string, RelationScope> | undefined;
157
- /** Entities whose scopeBy uses a nested path, which Go and Python cannot enforce. */
158
- export declare function nestedScopeEntities(entities: Entity[]): string[];
159
185
  /**
160
186
  * One warning per provider that maps no tenant claim while entities are
161
187
  * tenant-scoped: its users would get 403 on every one of those entities.
@@ -169,3 +195,15 @@ export declare function tenantClaimWarnings(entities: Entity[], auth?: AuthConfi
169
195
  * the caller.
170
196
  */
171
197
  export declare function scopedReferences(entity: Entity, foreignKeys: [field: string, target: string][], scopes: Record<string, RelationScope> | undefined): Record<string, string>;
198
+ /**
199
+ * One operation's role rule as a sentence, for its OpenAPI description:
200
+ * "Requires role: manager (from the token's `o.rol` claim). Other callers get 403."
201
+ */
202
+ export declare function roleRuleText(rule: PermissionRule, auth?: AuthConfig): string;
203
+ /** Each guarded operation of an entity and its rule, from .apsorc permissions. */
204
+ export declare function entityRoleRules(entity: Entity): Partial<Record<PermissionOperation, PermissionRule>>;
205
+ /**
206
+ * The OpenAPI info.description: who signs callers in, how records are scoped
207
+ * and which operations need which role, in plain words.
208
+ */
209
+ export declare function accessSummary(entities: Entity[], auth?: AuthConfig): string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.scopedReferences = exports.tenantClaimWarnings = exports.nestedScopeEntities = exports.relationScopes = exports.entityScope = exports.getPermissionConfig = exports.hasPermissions = exports.mcpToolNames = exports.authEntityRoutes = exports.hidesRelation = exports.authEntityNames = exports.mcpOperations = exports.hasScopedEntities = exports.getScopedEntities = exports.toRouteName = exports.removedScopeOptionErrors = void 0;
3
+ exports.accessSummary = exports.entityRoleRules = exports.roleRuleText = exports.scopedReferences = exports.tenantClaimWarnings = exports.relationScopes = exports.entityScope = exports.nestedScopes = exports.getPermissionConfig = exports.hasPermissions = exports.mcpToolNames = exports.authEntityRoutes = exports.hidesRelation = exports.authEntityNames = exports.mcpOperations = exports.hasScopedEntities = exports.getScopedEntities = exports.toRouteName = exports.removedScopeOptionErrors = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const types_1 = require("./types");
6
6
  const pluralize_1 = tslib_1.__importDefault(require("pluralize"));
@@ -280,28 +280,58 @@ function getPermissionConfig(entities, relationshipMap, auth) {
280
280
  return { routes, joins, grants: resolveGrants(entities, auth) };
281
281
  }
282
282
  exports.getPermissionConfig = getPermissionConfig;
283
+ const scopeSource = (contextKey) => contextKey === "userId" || contextKey === "email" ? contextKey : "tenant";
284
+ /**
285
+ * The scopeBy paths of an entity that run through parents, each resolved hop
286
+ * by hop. Every step before the last must be a many-to-one relationship: its
287
+ * foreign key is what the SQL filter follows.
288
+ */
289
+ function nestedScopes(entity, relationshipMap) {
290
+ if (!entity.scopeBy)
291
+ return [];
292
+ return parseScopeBy(entity.scopeBy)
293
+ .filter((s) => !s.direct && s.path)
294
+ .map((s) => {
295
+ const steps = s.path.split(".");
296
+ const tenantField = steps.pop();
297
+ let from = entity.name;
298
+ const hops = steps.map((step) => {
299
+ var _a;
300
+ const relation = ((_a = relationshipMap[from]) !== null && _a !== void 0 ? _a : []).find((r) => r.type === "ManyToOne" && (0, parse_1.getRelationshipName)(r) === step);
301
+ if (!relation)
302
+ throw new Error(`${entity.name}.scopeBy "${s.path}": "${step}" must be a many-to-one relationship of ${from}`);
303
+ const hop = { entity: relation.name, field: (0, parse_1.getRelationshipIdField)(relation) };
304
+ from = relation.name;
305
+ return hop;
306
+ });
307
+ return {
308
+ field: hops[0].field,
309
+ parents: hops.map((h, i) => { var _a; return ({ entity: h.entity, field: (_a = hops[i + 1]) === null || _a === void 0 ? void 0 : _a.field }); }),
310
+ tenantField,
311
+ source: scopeSource(tenantField),
312
+ };
313
+ });
314
+ }
315
+ exports.nestedScopes = nestedScopes;
283
316
  /**
284
317
  * The direct scopeBy fields of an entity, for services that filter in their
285
318
  * own queries (Go, Python). Undefined without auth: with no caller identity
286
- * there is no tenant to scope by. Nested paths (task.workspaceId) are not
287
- * included; see hasNestedScopes.
319
+ * there is no tenant to scope by. Paths through a parent (task.workspaceId)
320
+ * are resolved only when the relationship map is given.
288
321
  */
289
- function entityScope(entity, hasAuth) {
322
+ function entityScope(entity, hasAuth, relationshipMap) {
290
323
  if (!hasAuth || !entity.scopeBy)
291
324
  return undefined;
292
325
  const [config] = getScopedEntities([entity]);
293
326
  const fields = config.scopes
294
327
  .filter((s) => s.direct)
295
- .map((s) => ({
296
- field: s.field,
297
- source: s.contextKey === "userId" || s.contextKey === "email"
298
- ? s.contextKey
299
- : "tenant",
300
- }));
301
- if (fields.length === 0)
328
+ .map((s) => ({ field: s.field, source: scopeSource(s.contextKey) }));
329
+ const nested = relationshipMap ? nestedScopes(entity, relationshipMap) : [];
330
+ if (fields.length === 0 && nested.length === 0)
302
331
  return undefined;
303
332
  return {
304
333
  fields,
334
+ nested,
305
335
  bypassRoles: config.bypassRoles,
306
336
  };
307
337
  }
@@ -364,13 +394,6 @@ function relationScopes(entities, relationshipMap, hasAuth) {
364
394
  return table;
365
395
  }
366
396
  exports.relationScopes = relationScopes;
367
- /** Entities whose scopeBy uses a nested path, which Go and Python cannot enforce. */
368
- function nestedScopeEntities(entities) {
369
- return getScopedEntities(entities)
370
- .filter((e) => e.scopes.some((s) => !s.direct))
371
- .map((e) => e.name);
372
- }
373
- exports.nestedScopeEntities = nestedScopeEntities;
374
397
  /**
375
398
  * One warning per provider that maps no tenant claim while entities are
376
399
  * tenant-scoped: its users would get 403 on every one of those entities.
@@ -402,3 +425,110 @@ function scopedReferences(entity, foreignKeys, scopes) {
402
425
  return Object.fromEntries(foreignKeys.filter(([field, target]) => { var _a; return !own.has(field) && ((_a = scopes === null || scopes === void 0 ? void 0 : scopes[target]) === null || _a === void 0 ? void 0 : _a.bypassRoles) !== undefined; }));
403
426
  }
404
427
  exports.scopedReferences = scopedReferences;
428
+ /*
429
+ * Access text for the OpenAPI contract (/_docs-json). An app builder reading
430
+ * the contract should leave these rules to the API instead of copying them
431
+ * into the browser: matching users to roles by email, sending the tenant on a
432
+ * write, hiding a delete button as the only check.
433
+ */
434
+ const PROVIDER_NAMES = {
435
+ "better-auth": "Better Auth",
436
+ auth0: "Auth0",
437
+ clerk: "Clerk",
438
+ cognito: "Amazon Cognito",
439
+ jwt: "a JWT issuer",
440
+ };
441
+ const KEY_ONLY_DESCRIPTION = "Every request needs the service API key in the `x-api-key` header; without it the API answers 401. " +
442
+ "The key is for server-side callers only. Never put it in a browser app: a browser app calls its own backend, which calls this API.";
443
+ /** "the token's `o.rol` claim", naming each provider's claim when they differ. */
444
+ function claimText(providers, pick) {
445
+ const names = [...new Set(providers.map((p) => pick(p)).filter((n) => Boolean(n)))];
446
+ if (names.length === 0)
447
+ return undefined;
448
+ return `the token's ${names.map((n) => `\`${n}\``).join(" or ")} claim`;
449
+ }
450
+ const tenantClaim = (p) => { var _a; return (_a = p.claims.workspaceId) !== null && _a !== void 0 ? _a : p.claims.organizationId; };
451
+ const joinWords = (words, last = "and") => words.length <= 1 ? words.join("") : `${words.slice(0, -1).join(", ")} ${last} ${words[words.length - 1]}`;
452
+ /**
453
+ * One operation's role rule as a sentence, for its OpenAPI description:
454
+ * "Requires role: manager (from the token's `o.rol` claim). Other callers get 403."
455
+ */
456
+ function roleRuleText(rule, auth) {
457
+ const providers = (0, types_1.resolveJwtProviders)(auth);
458
+ const roles = claimText(providers, (p) => p.claims.roles);
459
+ const perms = claimText(providers, (p) => p.claims.permissions);
460
+ return (`Requires role: ${joinWords(rule.roles, "or")}${roles ? ` (from ${roles})` : " (from the token)"}` +
461
+ `${perms ? `, or \`${rule.permission}\` in ${perms}` : ""}. Other signed-in users get 403. ` +
462
+ "The API checks this; a client app must not re-implement it.");
463
+ }
464
+ exports.roleRuleText = roleRuleText;
465
+ /** Each guarded operation of an entity and its rule, from .apsorc permissions. */
466
+ function entityRoleRules(entity) {
467
+ var _a;
468
+ return Object.fromEntries(Object.entries((_a = entity.permissions) !== null && _a !== void 0 ? _a : {}).map(([op, roles]) => [
469
+ op,
470
+ { permission: `${permissionKey(entity.name)}:${op}`, roles: roles !== null && roles !== void 0 ? roles : [] },
471
+ ]));
472
+ }
473
+ exports.entityRoleRules = entityRoleRules;
474
+ /**
475
+ * The OpenAPI info.description: who signs callers in, how records are scoped
476
+ * and which operations need which role, in plain words.
477
+ */
478
+ function accessSummary(entities, auth) {
479
+ var _a, _b, _c, _d, _e, _f;
480
+ const providers = (0, types_1.resolveJwtProviders)(auth);
481
+ if (providers.length === 0)
482
+ return KEY_ONLY_DESCRIPTION;
483
+ const lines = [
484
+ "**Access rules.** This API enforces every rule below on every request. A client app must not re-implement them: " +
485
+ "do not look users up to decide their role, do not send the tenant field, and do not treat a hidden button as the check.",
486
+ "",
487
+ `- **Sign-in:** ${joinWords([...new Set(providers.map((p) => (p.provider === "jwt" ? `a JWT issuer (${p.issuer})` : PROVIDER_NAMES[p.provider])))], "or")}. Send the signed-in user's token as \`Authorization: Bearer <token>\`. Without a valid token the API answers 401.`,
488
+ ];
489
+ const tenant = (_a = claimText(providers, tenantClaim)) !== null && _a !== void 0 ? _a : "the token's tenant claim";
490
+ const user = (_b = claimText(providers, (p) => p.claims.userId)) !== null && _b !== void 0 ? _b : "the token's `sub` claim";
491
+ // Entities by scope sentence, so a schema scoped by one field reads as one line.
492
+ const byScope = new Map();
493
+ for (const { name, scopes, bypassRoles } of getScopedEntities(entities)) {
494
+ const parts = scopes.map((s) => s.direct
495
+ ? `\`${s.field}\` is taken from ${s.contextKey === "userId" ? user : s.contextKey === "email" ? "the token's email claim" : tenant}`
496
+ : `rows are limited through \`${s.path}\` to the caller's tenant (${tenant})`);
497
+ const bypass = bypassRoles.length > 0 ? ` Callers with role ${joinWords(bypassRoles, "or")} see every tenant.` : "";
498
+ const key = `${parts.join("; ")}.${bypass}`;
499
+ const group = (_c = byScope.get(key)) !== null && _c !== void 0 ? _c : { names: [], fields: scopes.filter((s) => s.direct).map((s) => `\`${s.field}\``) };
500
+ group.names.push(name);
501
+ byScope.set(key, group);
502
+ }
503
+ for (const [scope, { names, fields }] of byScope) {
504
+ const it = fields.length > 1 ? "them" : "it";
505
+ lines.push(`- **Scoped records:** ${joinWords(names)}: ${scope} Reads and lists return only the caller's records` +
506
+ (fields.length > 0
507
+ ? `, and creates and updates set ${joinWords(fields)} from the token. The client must not send ${it} or filter by ${it}.`
508
+ : "."));
509
+ }
510
+ const guarded = entities.filter((e) => e.permissions && Object.keys(e.permissions).length > 0);
511
+ if (guarded.length > 0) {
512
+ const roles = (_d = claimText(providers, (p) => p.claims.roles)) !== null && _d !== void 0 ? _d : "the token";
513
+ const perms = claimText(providers, (p) => p.claims.permissions);
514
+ lines.push(`- **Roles** come from ${roles}${perms ? ` (a permission such as \`${permissionKey(guarded[0].name)}:delete\` in ${perms} also passes)` : ""}. ` +
515
+ "A caller without the role gets 403. Operations not listed are open to any signed-in user:");
516
+ for (const entity of guarded) {
517
+ // Operations that need the same roles share a clause.
518
+ const byRoles = new Map();
519
+ for (const op of types_1.PERMISSION_OPERATIONS) {
520
+ const roles = (_e = entity.permissions) === null || _e === void 0 ? void 0 : _e[op];
521
+ if (!roles)
522
+ continue;
523
+ const key = joinWords(roles, "or");
524
+ byRoles.set(key, [...((_f = byRoles.get(key)) !== null && _f !== void 0 ? _f : []), op]);
525
+ }
526
+ const clauses = [...byRoles].map(([roles, ops]) => `${joinWords(ops)} need${ops.length === 1 ? "s" : ""} ${roles}`);
527
+ lines.push(` - ${entity.name}: ${clauses.join("; ")}.`);
528
+ }
529
+ lines.push("- To show only the actions a user may take, read the role from the same token, and still handle 403.");
530
+ }
531
+ lines.push("- **API key:** server-side callers may send the service key in `x-api-key` instead of a token. It is not limited to one tenant or role. Never put it in a browser app.");
532
+ return lines.join("\n");
533
+ }
534
+ exports.accessSummary = accessSummary;
@@ -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.WorkspaceID
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, scopeErr := s.scoped(ctx, s.db, "create")
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
- // Extract relation name from path (e.g., 'task.workspaceId' -> 'task')
287
- const relationName = scope.path.split('.')[0];
288
- if (!relations.includes(relationName)) {
289
- relations.push(relationName);
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