@apso/cli 0.47.6 → 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 (141) 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 +55 -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/ddl/change.js +2 -0
  29. package/dist/lib/ddl/index.d.ts +11 -1
  30. package/dist/lib/ddl/index.js +30 -16
  31. package/dist/lib/ddl/sync.d.ts +25 -0
  32. package/dist/lib/ddl/sync.js +78 -0
  33. package/dist/lib/deploy/server-push.js +3 -1
  34. package/dist/lib/generators/go.d.ts +25 -7
  35. package/dist/lib/generators/go.js +365 -128
  36. package/dist/lib/generators/python.d.ts +9 -3
  37. package/dist/lib/generators/python.js +282 -47
  38. package/dist/lib/generators/typescript.d.ts +3 -5
  39. package/dist/lib/generators/typescript.js +78 -64
  40. package/dist/lib/guards.d.ts +111 -13
  41. package/dist/lib/guards.js +287 -23
  42. package/dist/lib/templates/entities/entity-col-array.eta +1 -1
  43. package/dist/lib/templates/go/dto/dto-col-array.eta +2 -2
  44. package/dist/lib/templates/go/dto/dto-col-date.eta +1 -1
  45. package/dist/lib/templates/go/dto/dto-col-decimal.eta +1 -1
  46. package/dist/lib/templates/go/dto/dto-col-enum.eta +1 -1
  47. package/dist/lib/templates/go/dto/dto-col-float.eta +1 -1
  48. package/dist/lib/templates/go/dto/dto-col-integer.eta +3 -3
  49. package/dist/lib/templates/go/dto/dto-col-numeric.eta +1 -1
  50. package/dist/lib/templates/go/dto/dto-col-string.eta +1 -1
  51. package/dist/lib/templates/go/dto/dto-col-text.eta +1 -1
  52. package/dist/lib/templates/go/dto/dto-col-timestamp.eta +1 -1
  53. package/dist/lib/templates/go/dto/dto-col-timestamptz.eta +1 -1
  54. package/dist/lib/templates/go/dto/dto-col-uuid.eta +1 -1
  55. package/dist/lib/templates/go/dto/dto-col-varchar.eta +1 -1
  56. package/dist/lib/templates/go/dto/dto.eta +17 -18
  57. package/dist/lib/templates/go/handlers/handler.eta +10 -8
  58. package/dist/lib/templates/go/handlers/scope.eta +3 -2
  59. package/dist/lib/templates/go/index-module.eta +10 -5
  60. package/dist/lib/templates/go/mcp.eta +307 -0
  61. package/dist/lib/templates/go/middleware/auth.eta +587 -166
  62. package/dist/lib/templates/go/middleware/permission.eta +174 -0
  63. package/dist/lib/templates/go/models/model.eta +22 -19
  64. package/dist/lib/templates/go/models/schema.eta +72 -0
  65. package/dist/lib/templates/go/services/service.eta +84 -35
  66. package/dist/lib/templates/go/utils/query.eta +68 -7
  67. package/dist/lib/templates/guards/guards.module.eta +37 -29
  68. package/dist/lib/templates/guards/index.eta +4 -0
  69. package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
  70. package/dist/lib/templates/guards/key.guard.eta +280 -0
  71. package/dist/lib/templates/guards/permission.guard.eta +168 -0
  72. package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
  73. package/dist/lib/templates/guards/scope.guard.eta +189 -41
  74. package/dist/lib/templates/python/auth.eta +354 -95
  75. package/dist/lib/templates/python/index-module.eta +7 -7
  76. package/dist/lib/templates/python/mcp.eta +284 -0
  77. package/dist/lib/templates/python/models/init.eta +24 -0
  78. package/dist/lib/templates/python/models/model.eta +30 -61
  79. package/dist/lib/templates/python/permissions.eta +121 -0
  80. package/dist/lib/templates/python/routers/router.eta +39 -1
  81. package/dist/lib/templates/python/schemas/schema-col-array.eta +1 -1
  82. package/dist/lib/templates/python/schemas/schema.eta +27 -14
  83. package/dist/lib/templates/python/services/service.eta +38 -15
  84. package/dist/lib/templates/python/utils/query.eta +52 -25
  85. package/dist/lib/templates/rest/controller-rest.eta +43 -23
  86. package/dist/lib/templates/rest/index-module-rest.eta +0 -4
  87. package/dist/lib/templates/rest/service-rest.eta +3 -44
  88. package/dist/lib/types/auth.d.ts +84 -80
  89. package/dist/lib/types/auth.js +77 -60
  90. package/dist/lib/types/entity.d.ts +17 -9
  91. package/dist/lib/types/entity.js +3 -0
  92. package/dist/lib/types/index.d.ts +2 -2
  93. package/dist/lib/types/index.js +6 -5
  94. package/dist/lib/utils/crud-deps.d.ts +77 -6
  95. package/dist/lib/utils/crud-deps.js +197 -14
  96. package/dist/lib/utils/field.d.ts +12 -0
  97. package/dist/lib/utils/field.js +18 -2
  98. package/dist/lib/utils/schema-convert.d.ts +20 -43
  99. package/dist/lib/utils/schema-convert.js +28 -78
  100. package/dist/lib/utils/template.d.ts +11 -0
  101. package/dist/lib/utils/template.js +36 -1
  102. package/dist/lib/verify/index.d.ts +6 -1
  103. package/dist/lib/verify/index.js +30 -13
  104. package/npm-shrinkwrap.json +2 -2
  105. package/oclif.manifest.json +36 -1
  106. package/package.json +1 -1
  107. package/dist/lib/templates/go/models/model-col-array.eta +0 -1
  108. package/dist/lib/templates/go/models/model-col-boolean.eta +0 -1
  109. package/dist/lib/templates/go/models/model-col-date.eta +0 -1
  110. package/dist/lib/templates/go/models/model-col-decimal.eta +0 -1
  111. package/dist/lib/templates/go/models/model-col-enum.eta +0 -2
  112. package/dist/lib/templates/go/models/model-col-float.eta +0 -1
  113. package/dist/lib/templates/go/models/model-col-integer.eta +0 -1
  114. package/dist/lib/templates/go/models/model-col-json.eta +0 -1
  115. package/dist/lib/templates/go/models/model-col-jsonb.eta +0 -1
  116. package/dist/lib/templates/go/models/model-col-numeric.eta +0 -1
  117. package/dist/lib/templates/go/models/model-col-string.eta +0 -1
  118. package/dist/lib/templates/go/models/model-col-text.eta +0 -1
  119. package/dist/lib/templates/go/models/model-col-timestamp.eta +0 -1
  120. package/dist/lib/templates/go/models/model-col-timestamptz.eta +0 -1
  121. package/dist/lib/templates/go/models/model-col-uuid.eta +0 -1
  122. package/dist/lib/templates/go/models/model-col-varchar.eta +0 -1
  123. package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
  124. package/dist/lib/templates/guards/auth.guard.eta +0 -233
  125. package/dist/lib/templates/python/models/model-col-array.eta +0 -4
  126. package/dist/lib/templates/python/models/model-col-boolean.eta +0 -6
  127. package/dist/lib/templates/python/models/model-col-date.eta +0 -4
  128. package/dist/lib/templates/python/models/model-col-datetime.eta +0 -5
  129. package/dist/lib/templates/python/models/model-col-decimal.eta +0 -4
  130. package/dist/lib/templates/python/models/model-col-enum.eta +0 -16
  131. package/dist/lib/templates/python/models/model-col-float.eta +0 -6
  132. package/dist/lib/templates/python/models/model-col-integer.eta +0 -6
  133. package/dist/lib/templates/python/models/model-col-json.eta +0 -4
  134. package/dist/lib/templates/python/models/model-col-jsonb.eta +0 -4
  135. package/dist/lib/templates/python/models/model-col-numeric.eta +0 -4
  136. package/dist/lib/templates/python/models/model-col-string.eta +0 -6
  137. package/dist/lib/templates/python/models/model-col-text.eta +0 -6
  138. package/dist/lib/templates/python/models/model-col-timestamp.eta +0 -11
  139. package/dist/lib/templates/python/models/model-col-timestamptz.eta +0 -11
  140. package/dist/lib/templates/python/models/model-col-uuid.eta +0 -5
  141. package/dist/lib/templates/python/models/model-col-varchar.eta +0 -6
@@ -0,0 +1,1163 @@
1
+ "use strict";
2
+ /**
3
+ * The access rule cases that follow from a schema: given the entities, their
4
+ * scopeBy, permissions and mcp settings, and a running service, they seed two
5
+ * tenants and check the rules in rules.json over HTTP only. The same cases
6
+ * run in CI against a generated service in each language
7
+ * (scripts/auth-smoke.mjs) and on an owner's own project (`apso test access`).
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.runAccessCases = exports.buildModel = exports.call = void 0;
11
+ const tslib_1 = require("tslib");
12
+ /* eslint-disable no-await-in-loop */
13
+ const crypto_1 = require("crypto");
14
+ const pluralize_1 = tslib_1.__importDefault(require("pluralize"));
15
+ const guards_1 = require("../guards");
16
+ const casing_1 = require("../utils/casing");
17
+ const parse_1 = require("../utils/relationships/parse");
18
+ const crud_plan_1 = require("../verify/crud-plan");
19
+ async function call(method, url, { headers = {}, body } = {}) {
20
+ var _a;
21
+ try {
22
+ const res = await fetch(url, {
23
+ method,
24
+ headers: { "content-type": "application/json", ...headers },
25
+ body: body === undefined ? undefined : JSON.stringify(body),
26
+ });
27
+ const text = await res.text();
28
+ let json;
29
+ try {
30
+ json = JSON.parse(text);
31
+ }
32
+ catch {
33
+ json = undefined;
34
+ }
35
+ return { status: res.status, text, json, range: (_a = res.headers.get("content-range")) !== null && _a !== void 0 ? _a : undefined };
36
+ }
37
+ catch (error) {
38
+ return { status: 0, text: String(error) };
39
+ }
40
+ }
41
+ exports.call = call;
42
+ const rowsOf = (json) => {
43
+ var _a;
44
+ if (Array.isArray(json))
45
+ return json;
46
+ const list = (_a = json === null || json === void 0 ? void 0 : json.data) !== null && _a !== void 0 ? _a : json === null || json === void 0 ? void 0 : json.items;
47
+ return Array.isArray(list) ? list : [];
48
+ };
49
+ /** The total in a Content-Range header: 7 for "0-4/7" and for "*\/7", undefined for "0-4/*" or no header. */
50
+ const rangeTotal = (res) => {
51
+ var _a, _b;
52
+ const total = (_b = /\/(\d+)$/.exec((_a = res.range) !== null && _a !== void 0 ? _a : "")) === null || _b === void 0 ? void 0 : _b[1];
53
+ return total === undefined ? undefined : Number(total);
54
+ };
55
+ const routeOf = (language, name) => {
56
+ const plural = (0, pluralize_1.default)(name);
57
+ if (language === "typescript")
58
+ return `/${plural}`;
59
+ // Go routes are kebab-case (/api/role-permissions).
60
+ return `/api/${language === "go" ? (0, casing_1.kebabCase)(plural) : plural.toLowerCase()}`;
61
+ };
62
+ /**
63
+ * Describe a schema for the cases.
64
+ * @param {Entity[]} entities - The .apsorc entities
65
+ * @param {RelationshipMap} relationships - The parsed relationships
66
+ * @param {Language} language - The service's language
67
+ * @param {object} [auth] - The .apsorc auth block, if any
68
+ * @returns {AccessModel} The schema as the cases use it
69
+ */
70
+ function buildModel(entities, relationships, language, auth) {
71
+ var _a;
72
+ const plan = (0, crud_plan_1.planCrud)(entities, relationships);
73
+ const skipped = [...plan.skipped];
74
+ const scoped = auth ? (0, guards_1.getScopedEntities)(entities, relationships) : [];
75
+ let tenantRoot;
76
+ const model = plan.order.map((planned) => {
77
+ var _a, _b, _c;
78
+ const entity = entities.find((e) => e.name === planned.name);
79
+ const relations = ((_a = relationships[entity.name]) !== null && _a !== void 0 ? _a : []).map((r) => ({
80
+ property: r.type === "OneToMany" || r.type === "ManyToMany"
81
+ ? (0, pluralize_1.default)((0, parse_1.getRelationshipName)(r))
82
+ : (0, parse_1.getRelationshipName)(r),
83
+ entity: r.name,
84
+ ...(r.type === "ManyToOne" ? { fk: (0, parse_1.getRelationshipIdField)(r) } : {}),
85
+ }));
86
+ const config = scoped.find((s) => s.name === entity.name);
87
+ const direct = config === null || config === void 0 ? void 0 : config.scopes.find((s) => s.direct && s.contextKey !== "userId" && s.contextKey !== "email");
88
+ // Only TypeScript enforces a path through a parent; Python and Go refuse it at generate.
89
+ const nested = language === "typescript" ? config === null || config === void 0 ? void 0 : config.scopes.find((s) => s.fkField) : undefined;
90
+ let scope;
91
+ if (config && direct) {
92
+ scope = { field: direct.field, bypassRoles: config.bypassRoles };
93
+ const parent = ((_b = relationships[entity.name]) !== null && _b !== void 0 ? _b : []).find((r) => r.type !== "OneToMany" && r.type !== "ManyToMany" && (0, parse_1.getRelationshipIdField)(r) === direct.field);
94
+ tenantRoot = tenantRoot !== null && tenantRoot !== void 0 ? tenantRoot : parent === null || parent === void 0 ? void 0 : parent.name;
95
+ }
96
+ else if (config && nested) {
97
+ scope = { field: nested.fkField, parent: nested.parentEntity, bypassRoles: config.bypassRoles };
98
+ }
99
+ else if (config) {
100
+ skipped.push({ name: entity.name, reason: "its scopeBy is the caller's user id or email, which these cases do not cover" });
101
+ }
102
+ const ops = (0, guards_1.mcpOperations)(entity);
103
+ const one = (0, casing_1.snakeCase)(entity.name);
104
+ return {
105
+ name: entity.name,
106
+ route: routeOf(language, entity.name),
107
+ fields: (_c = entity.fields) !== null && _c !== void 0 ? _c : [],
108
+ payload: planned.payload,
109
+ parents: planned.parents,
110
+ relations,
111
+ scope,
112
+ permissions: auth ? entity.permissions : undefined,
113
+ tools: {
114
+ ...(ops.includes("read") ? { list: `list_${(0, casing_1.snakeCase)((0, pluralize_1.default)(entity.name))}`, get: `get_${one}` } : {}),
115
+ ...(ops.includes("create") ? { create: `create_${one}` } : {}),
116
+ ...(ops.includes("update") ? { update: `update_${one}` } : {}),
117
+ ...(ops.includes("delete") ? { delete: `delete_${one}` } : {}),
118
+ },
119
+ };
120
+ });
121
+ const grants = (_a = auth === null || auth === void 0 ? void 0 : auth.permissionEntity) !== null && _a !== void 0 ? _a : "RolePermission";
122
+ return {
123
+ language,
124
+ entities: model,
125
+ skipped,
126
+ tenantRoot,
127
+ grants: model.some((e) => e.name === grants && e.permissions) ? grants : undefined,
128
+ };
129
+ }
130
+ exports.buildModel = buildModel;
131
+ const TEXT = new Set(["text", "string", "varchar"]);
132
+ /** A create body for the nth row of an entity: text values differ per row so unique fields do not collide. */
133
+ function payloadFor(entity, n) {
134
+ const body = { ...entity.payload };
135
+ for (const field of entity.fields) {
136
+ const value = body[field.name];
137
+ if (typeof value !== "string")
138
+ continue;
139
+ if (field.is_email)
140
+ body[field.name] = `access${n}@example.com`;
141
+ else if (TEXT.has(field.type))
142
+ body[field.name] = `${value.slice(0, -1)}${n}`;
143
+ }
144
+ return body;
145
+ }
146
+ /** A tenant id of the scope column's type, for a schema with no tenant entity. */
147
+ function syntheticTenant(model, n) {
148
+ var _a;
149
+ for (const entity of model.entities) {
150
+ if (!entity.scope || entity.scope.parent)
151
+ continue;
152
+ const type = (_a = entity.fields.find((f) => f.name === entity.scope.field)) === null || _a === void 0 ? void 0 : _a.type;
153
+ if (type === "uuid")
154
+ return (0, crypto_1.randomUUID)();
155
+ if (type && TEXT.has(type))
156
+ return `apso-access-${n}`;
157
+ break;
158
+ }
159
+ return String(910000 + n);
160
+ }
161
+ const asColumn = (entity, value) => {
162
+ var _a;
163
+ const type = (_a = entity.fields.find((f) => { var _a; return f.name === ((_a = entity.scope) === null || _a === void 0 ? void 0 : _a.field); })) === null || _a === void 0 ? void 0 : _a.type;
164
+ return type && (TEXT.has(type) || type === "uuid") ? value : /^\d+$/.test(value) ? Number(value) : value;
165
+ };
166
+ /** Create one row of every entity for each of two tenants, as a service caller. */
167
+ async function seed(ctx) {
168
+ var _a, _b, _c, _d, _e;
169
+ const { model, base, key } = ctx;
170
+ const tenants = [];
171
+ for (const n of [1, 2]) {
172
+ const tenant = { value: "", rows: {} };
173
+ for (const entity of model.entities) {
174
+ const body = payloadFor(entity, n);
175
+ const missing = entity.parents.find((p) => !tenant.rows[p.entity]);
176
+ if (missing) {
177
+ (_a = ctx.log) === null || _a === void 0 ? void 0 : _a.call(ctx, ` skip ${entity.name}: needs a ${missing.entity} row, which could not be created`);
178
+ continue;
179
+ }
180
+ for (const parent of entity.parents)
181
+ body[parent.property] = tenant.rows[parent.entity].id;
182
+ if ((_b = entity.scope) === null || _b === void 0 ? void 0 : _b.parent) {
183
+ if (!tenant.rows[entity.scope.parent])
184
+ continue;
185
+ body[entity.scope.field] = tenant.rows[entity.scope.parent].id;
186
+ }
187
+ else if (entity.scope) {
188
+ if (!tenant.value) {
189
+ const root = model.tenantRoot && tenant.rows[model.tenantRoot];
190
+ tenant.value = root ? String(root.id) : model.tenantRoot ? "" : syntheticTenant(model, n);
191
+ }
192
+ if (!tenant.value) {
193
+ (_c = ctx.log) === null || _c === void 0 ? void 0 : _c.call(ctx, ` skip ${entity.name}: its tenant (${model.tenantRoot}) is created after it`);
194
+ continue;
195
+ }
196
+ body[entity.scope.field] = asColumn(entity, tenant.value);
197
+ }
198
+ const created = await call("POST", base + entity.route, { headers: key, body });
199
+ if ([200, 201].includes(created.status) && ((_d = created.json) === null || _d === void 0 ? void 0 : _d.id) !== undefined)
200
+ tenant.rows[entity.name] = created.json;
201
+ else
202
+ (_e = ctx.log) === null || _e === void 0 ? void 0 : _e.call(ctx, ` skip ${entity.name}: could not create a row (${created.status} ${created.text.slice(0, 200)})`);
203
+ }
204
+ if (!tenant.value) {
205
+ const root = model.tenantRoot && tenant.rows[model.tenantRoot];
206
+ tenant.value = root ? String(root.id) : syntheticTenant(model, n);
207
+ }
208
+ tenants.push(tenant);
209
+ }
210
+ return tenants;
211
+ }
212
+ /**
213
+ * The other tenant's rows in a response: every object of a scoped entity,
214
+ * at the top or under a joined relation, whose id is one the other tenant owns.
215
+ */
216
+ function foreignRows(model, entityName, value, theirs, depth = 0) {
217
+ return rowsWhere(model, entityName, value, (entity, row) => {
218
+ const other = theirs[entity.name];
219
+ return Boolean(entity.scope && other && row.id !== undefined && String(row.id) === String(other.id));
220
+ }, depth);
221
+ }
222
+ /** The alias the embed cases give a relation (select=x_projects:projects(*)). */
223
+ const alias = (property) => `x_${property}`;
224
+ /** Every row in a response, at the top or under a relation (by its name or the alias above), that `hit` picks. */
225
+ function rowsWhere(model, entityName, value, hit, depth = 0) {
226
+ var _a;
227
+ if (value === null || typeof value !== "object" || depth > 4)
228
+ return [];
229
+ if (Array.isArray(value))
230
+ return value.flatMap((v) => rowsWhere(model, entityName, v, hit, depth));
231
+ const entity = model.entities.find((e) => e.name === entityName);
232
+ if (!entity)
233
+ return [];
234
+ const row = value;
235
+ const found = hit(entity, row) ? [`${entityName} ${(_a = row.id) !== null && _a !== void 0 ? _a : ""}`.trim()] : [];
236
+ for (const relation of entity.relations)
237
+ for (const key of [relation.property, alias(relation.property)])
238
+ found.push(...rowsWhere(model, relation.entity, row[key], hit, depth + 1));
239
+ return found;
240
+ }
241
+ const POSTGREST = { "x-crud-dialect": "postgrest" };
242
+ /** A TypeScript service accepts the PostgREST query syntax only; Python and Go still accept nestjsx as well. */
243
+ const postgrestOnly = (model) => model.language === "typescript";
244
+ /**
245
+ * The forms a service of this language parses. Where nestjsx is refused its
246
+ * forms are left out: each has a PostgREST form beside it, and the refusal
247
+ * itself is proven once per parameter by nestjsxRefused.
248
+ */
249
+ const forms = (model, list) => postgrestOnly(model) ? list.filter((item) => !item.nestjsx) : list;
250
+ /**
251
+ * Every way a request can load `relation` of `entity` (and, one step further,
252
+ * each relation of that): the join parameter, and select embeds with and
253
+ * without the dialect header, with chosen columns, and under an alias.
254
+ */
255
+ function relationLoads(model, relation, nested = true) {
256
+ var _a, _b;
257
+ const p = relation.property;
258
+ const out = [
259
+ nx(`join ${p}`, `join=${enc(p)}`),
260
+ nx(`join ${p} with chosen fields`, `join=${enc(`${p}||id`)}`),
261
+ { name: `select embed ${p}`, query: `select=${enc(`*,${p}(*)`)}`, headers: POSTGREST },
262
+ { name: `select embed ${p}, no dialect header`, query: `select=${enc(`*,${p}(*)`)}` },
263
+ { name: `select embed ${p} with chosen columns, no dialect header`, query: `select=${enc(`id,${p}(id)`)}` },
264
+ { name: `select embed ${p} under an alias`, query: `select=${enc(`*,${alias(p)}:${p}(*)`)}` },
265
+ { name: `select embed ${p} with an inner join hint`, query: `select=${enc(`*,${p}!inner(*)`)}` },
266
+ ];
267
+ if (!nested)
268
+ return forms(model, out);
269
+ for (const second of (_b = (_a = model.entities.find((e) => e.name === relation.entity)) === null || _a === void 0 ? void 0 : _a.relations) !== null && _b !== void 0 ? _b : []) {
270
+ const q = second.property;
271
+ out.push(nx(`join ${p}.${q}`, `join=${enc(p)}&join=${enc(`${p}.${q}`)}`), nx(`join ${p}.${q} without joining ${p}`, `join=${enc(`${p}.${q}`)}`), { name: `select embed ${p}(${q})`, query: `select=${enc(`*,${p}(*,${q}(*))`)}`, headers: POSTGREST }, { name: `select embed ${p}(${q}), no dialect header`, query: `select=${enc(`id,${p}(id,${q}(*))`)}` }, { name: `select embed ${p}(${q}) under aliases`, query: `select=${enc(`*,${alias(p)}:${p}(*,${alias(q)}:${q}(*))`)}` });
272
+ }
273
+ return forms(model, out);
274
+ }
275
+ /** A field of an entity's seeded row to test for through a relation, and a value no row has. */
276
+ function probe(entity, row) {
277
+ var _a;
278
+ const field = (_a = Object.keys(entity.payload).find((k) => typeof row[k] === "string" && row[k] !== "")) !== null && _a !== void 0 ? _a : "id";
279
+ return { field, value: String(row[field]), absent: field === "id" ? "987654321" : "apso-access-absent" };
280
+ }
281
+ /** A value less its last character, for a "starts with" filter. */
282
+ const start = (v) => v.slice(0, Math.max(1, v.length - 1));
283
+ /**
284
+ * Filters on a field of a related entity the caller cannot read. If the
285
+ * filter matches for the real value and not for a value no row has, the
286
+ * caller can learn the field one guess at a time without ever being sent it.
287
+ * With `through`, the caller may read related rows of its own that match the
288
+ * same filter, so only an answer that holds that row (the one whose relation
289
+ * points at the row the caller cannot read) counts.
290
+ */
291
+ async function oracle(model, url, headers, property, target, row, through) {
292
+ const { field, value, absent } = probe(target, row);
293
+ const tries = [
294
+ { name: "filter", query: (v) => `filter=${f(`${property}.${field}`, "$eq", v)}`, nestjsx: true },
295
+ { name: "filter with join", query: (v) => `join=${enc(property)}&filter=${f(`${property}.${field}`, "$eq", v)}`, nestjsx: true },
296
+ { name: "filter $starts", query: (v) => `filter=${f(`${property}.${field}`, "$starts", start(v))}`, nestjsx: true },
297
+ { name: "s search", query: (v) => `s=${enc(JSON.stringify({ [`${property}.${field}`]: num(v) }))}`, nestjsx: true },
298
+ { name: "postgrest filter", query: (v) => `${property}.${field}=${enc(`eq.${v}`)}`, extra: POSTGREST },
299
+ { name: "postgrest inner embed filter", query: (v) => `select=${enc(`id,${property}!inner(id)`)}&${property}.${field}=${enc(`eq.${v}`)}` },
300
+ { name: "postgrest inner embed filter, like", query: (v) => `select=${enc(`id,${property}!inner(id)`)}&${property}.${field}=${enc(`like.${start(v)}*`)}` },
301
+ { name: "postgrest inner embed filter, in", query: (v) => `select=${enc(`id,${property}!inner(id)`)}&${property}.${field}=${enc(`in.(${v})`)}` },
302
+ ];
303
+ const leaks = [];
304
+ for (const { name, query, extra } of forms(model, tries)) {
305
+ const real = await call("GET", `${url}?${query(value)}`, { headers: { ...headers, ...extra } });
306
+ if (real.status !== 200 || rowsOf(real.json).length === 0)
307
+ continue;
308
+ if (through && !rowsOf(real.json).some((r) => String(r.id) === String(through.id)))
309
+ continue;
310
+ // "$starts" of a value no row has, cut the same way, still matches nothing.
311
+ const none = await call("GET", `${url}?${query(absent)}`, { headers: { ...headers, ...extra } });
312
+ if (none.status === 200 && rowsOf(none.json).length === 0)
313
+ leaks.push(`${name}: ?${query(value)}`);
314
+ }
315
+ return leaks.join("; ");
316
+ }
317
+ /** An attempt in nestjsx syntax. */
318
+ const nx = (name, query) => ({ name, query, nestjsx: true });
319
+ const enc = encodeURIComponent;
320
+ /** A token claim is text; a numeric column is filtered as a number in JSON. */
321
+ const num = (v) => (/^\d+$/.test(v) ? Number(v) : v);
322
+ /** One nestjsx-style condition, field||operator||value, encoded. */
323
+ const f = (...parts) => enc(parts.join("||"));
324
+ /**
325
+ * Query strings a caller of one tenant would try in order to read another
326
+ * tenant's rows of `entity`: both query dialects, nested and encoded forms.
327
+ * `mine` and `theirs` are the two tenants' values of the scope column and
328
+ * `theirId` is the id of the other tenant's row. Every nestjsx attempt has a
329
+ * PostgREST form in the list; a PostgREST-only service runs only those.
330
+ */
331
+ function widenAttempts(model, entity, mine, theirs, theirId) {
332
+ const col = entity.scope.field;
333
+ const s = (o) => `s=${enc(JSON.stringify(o))}`;
334
+ const postgrest = POSTGREST;
335
+ const out = [
336
+ // filter
337
+ nx("filter names the other tenant", `filter=${f(col, "$eq", theirs)}`),
338
+ nx("filter $in lists both tenants", `filter=${f(col, "$in", `${mine},${theirs}`)}`),
339
+ nx("filter $ne excludes the caller's tenant", `filter=${f(col, "$ne", mine)}`),
340
+ nx("filter $notnull on the tenant column", `filter=${f(col, "$notnull")}`),
341
+ nx("filter by the other tenant's row id", `filter=${f("id", "$eq", theirId)}`),
342
+ nx("filter sent twice (own tenant, then the other)", `filter=${f(col, "$eq", mine)}&filter=${f(col, "$eq", theirs)}`),
343
+ nx("filter as an array parameter", `filter[]=${f(col, "$eq", theirs)}`),
344
+ nx("filter as an indexed array parameter", `filter[0]=${f(col, "$eq", theirs)}&filter[1]=${f("id", "$eq", theirId)}`),
345
+ nx("filter with unencoded separators", `filter=${col}||$eq||${theirs}`),
346
+ nx("filter double-encoded", `filter=${enc(f(col, "$eq", theirs))}`),
347
+ nx("filter on the column's snake_case name", `filter=${f((0, casing_1.snakeCase)(col), "$eq", theirs)}`),
348
+ nx("filter on the column in upper case", `filter=${f(col.toUpperCase(), "$eq", theirs)}`),
349
+ { name: "the guard's own filter key", query: `filter.${col}=${enc(`$eq:${theirs}`)}` },
350
+ { name: "the guard's own filter key, sent twice", query: `filter.${col}=${enc(`$eq:${theirs}`)}&filter.${col}=${enc(`$eq:${theirs}`)}` },
351
+ nx("filter as a nested object parameter", `filter[${col}]=${enc(theirs)}`),
352
+ // or
353
+ nx("or names the other tenant", `or=${f(col, "$eq", theirs)}`),
354
+ nx("filter own tenant, or the other", `filter=${f(col, "$eq", mine)}&or=${f(col, "$eq", theirs)}`),
355
+ nx("two or conditions", `or=${f(col, "$eq", theirs)}&or=${f("id", "$eq", theirId)}`),
356
+ nx("filter and or by the other tenant's row id", `filter=${f("id", "$eq", theirId)}&or=${f("id", "$eq", theirId)}`),
357
+ nx("or matching every row", `or=${f("id", "$notnull")}&or=${f("id", "$isnull")}`),
358
+ nx("or as an array parameter", `or[]=${f(col, "$eq", theirs)}&or[]=${f("id", "$eq", theirId)}`),
359
+ // s (JSON search)
360
+ nx("s names the other tenant", s({ [col]: num(theirs) })),
361
+ nx("s $or of both tenants", s({ $or: [{ [col]: num(mine) }, { [col]: num(theirs) }] })),
362
+ nx("s $or of the other tenant and its row id", s({ $or: [{ [col]: num(theirs) }, { id: num(theirId) }] })),
363
+ nx("s $ne the caller's tenant", s({ [col]: { $ne: num(mine) } })),
364
+ nx("s $in both tenants", s({ [col]: { $in: [num(mine), num(theirs)] } })),
365
+ nx("s $or nested in $and", s({ $and: [{ $or: [{ [col]: num(theirs) }, { id: { $notnull: true } }] }] })),
366
+ nx("s $or nested in $or", s({ $or: [{ $or: [{ [col]: num(theirs) }] }, { $and: [{ id: num(theirId) }] }] })),
367
+ nx("s by the other tenant's row id", s({ id: num(theirId) })),
368
+ nx("s $or inside the column's condition", s({ [col]: { $or: { $eq: num(theirs), $notnull: true } } })),
369
+ nx("s as a nested object parameter", `s[${col}]=${enc(theirs)}`),
370
+ nx("s double-encoded", `s=${enc(enc(JSON.stringify({ [col]: num(theirs) })))}`),
371
+ nx("s with filter and or together", `${s({ [col]: num(theirs) })}&filter=${f(col, "$eq", theirs)}&or=${f(col, "$eq", theirs)}`),
372
+ // sort and pagination
373
+ nx("sort by tenant descending, first row only", `sort=${enc(`${col},DESC`)}&limit=1`),
374
+ nx("sort by tenant ascending, first row only", `sort=${enc(`${col},ASC`)}&limit=1`),
375
+ nx("sort by id, a very large page", `sort=${enc("id,DESC")}&limit=100000`),
376
+ { name: "limit 0", query: "limit=0" },
377
+ { name: "negative limit", query: "limit=-1" },
378
+ nx("second page", "limit=1&page=2"),
379
+ { name: "offset past the caller's rows", query: "limit=100&offset=1" },
380
+ { name: "negative offset", query: "offset=-1" },
381
+ nx("per_page and take", "per_page=1000&take=1000"),
382
+ nx("fields limited to the tenant column", `fields=${enc(col)}`),
383
+ nx("cache off", "cache=0"),
384
+ // the PostgREST dialect
385
+ { name: "postgrest: column eq the other tenant", query: `${col}=${enc(`eq.${theirs}`)}`, headers: postgrest },
386
+ { name: "postgrest: column eq, dialect inferred", query: `${col}=${enc(`eq.${theirs}`)}` },
387
+ { name: "postgrest: column in both tenants", query: `${col}=${enc(`in.(${mine},${theirs})`)}`, headers: postgrest },
388
+ { name: "postgrest: column neq the caller's tenant", query: `${col}=${enc(`neq.${mine}`)}`, headers: postgrest },
389
+ { name: "postgrest: not.eq the caller's tenant", query: `${col}=${enc(`not.eq.${mine}`)}`, headers: postgrest },
390
+ { name: "postgrest: id eq the other tenant's row", query: `id=${enc(`eq.${theirId}`)}`, headers: postgrest },
391
+ { name: "postgrest: or group", query: `or=${enc(`(${col}.eq.${theirs},id.eq.${theirId})`)}`, headers: postgrest },
392
+ { name: "postgrest: or group, dialect inferred", query: `or=${enc(`(${col}.eq.${theirs},id.eq.${theirId})`)}` },
393
+ { name: "postgrest: and group", query: `and=${enc(`(${col}.eq.${theirs})`)}`, headers: postgrest },
394
+ { name: "postgrest: not.and of the caller's tenant", query: `not.and=${enc(`(${col}.eq.${mine})`)}`, headers: postgrest },
395
+ { name: "postgrest: or nested in and", query: `and=${enc(`(or(${col}.eq.${theirs},id.eq.${theirId}))`)}`, headers: postgrest },
396
+ { name: "postgrest: order by tenant, first row", query: `order=${enc(`${col}.desc`)}&limit=1`, headers: postgrest },
397
+ { name: "postgrest: offset", query: "limit=100&offset=1", headers: postgrest },
398
+ { name: "postgrest: select all", query: `select=${enc("*")}`, headers: postgrest },
399
+ { name: "postgrest: Range header", query: "", headers: { ...postgrest, range: "0-999", prefer: "count=exact" } },
400
+ // the PostgREST form of each nestjsx attempt above that had none
401
+ { name: "postgrest: tenant column is not null", query: `${col}=${enc("not.is.null")}` },
402
+ { name: "postgrest: tenant column is.not_null", query: `${col}=${enc("is.not_null")}` },
403
+ { name: "postgrest: column filter sent twice (own tenant, then the other)", query: `${col}=${enc(`eq.${mine}`)}&${col}=${enc(`eq.${theirs}`)}` },
404
+ { name: "postgrest: column filter sent twice (the other tenant, then own)", query: `${col}=${enc(`eq.${theirs}`)}&${col}=${enc(`eq.${mine}`)}` },
405
+ { name: "postgrest: column filter as an array parameter", query: `${col}[]=${enc(`eq.${theirs}`)}` },
406
+ { name: "postgrest: column filter as an indexed array parameter", query: `${col}[0]=${enc(`eq.${theirs}`)}&${col}[1]=${enc(`eq.${theirs}`)}` },
407
+ { name: "postgrest: column filter as a nested object parameter", query: `${col}[eq]=${enc(theirs)}` },
408
+ { name: "postgrest: or group with unencoded separators", query: `or=(${col}.eq.${theirs},id.eq.${theirId})` },
409
+ { name: "postgrest: or group double-encoded", query: `or=${enc(enc(`(${col}.eq.${theirs},id.eq.${theirId})`))}` },
410
+ { name: "postgrest: column filter on the snake_case name", query: `${(0, casing_1.snakeCase)(col)}=${enc(`eq.${theirs}`)}` },
411
+ { name: "postgrest: column filter on the name in upper case", query: `${col.toUpperCase()}=${enc(`eq.${theirs}`)}` },
412
+ { name: "postgrest: filter own tenant, or group the other", query: `${col}=${enc(`eq.${mine}`)}&or=${enc(`(${col}.eq.${theirs})`)}` },
413
+ { name: "postgrest: or group of both tenants", query: `or=${enc(`(${col}.eq.${mine},${col}.eq.${theirs})`)}` },
414
+ { name: "postgrest: or group matching every row", query: `or=${enc("(id.not.is.null,id.is.null)")}` },
415
+ { name: "postgrest: or group as an array parameter", query: `or[]=${enc(`(${col}.eq.${theirs})`)}&or[]=${enc(`(id.eq.${theirId})`)}` },
416
+ { name: "postgrest: or nested in or", query: `or=${enc(`(or(${col}.eq.${theirs}),and(id.eq.${theirId}))`)}` },
417
+ { name: "postgrest: negated condition in an or group", query: `or=${enc(`(${col}.not.eq.${mine},id.eq.${theirId})`)}` },
418
+ { name: "postgrest: column filter with or and and groups together", query: `${col}=${enc(`eq.${theirs}`)}&or=${enc(`(${col}.eq.${theirs})`)}&and=${enc(`(${col}.eq.${theirs})`)}` },
419
+ { name: "postgrest: order by tenant ascending, first row", query: `order=${enc(`${col}.asc`)}&limit=1` },
420
+ { name: "postgrest: order by id, a very large page", query: `order=${enc("id.desc")}&limit=100000` },
421
+ { name: "postgrest: second page", query: "limit=1&offset=1" },
422
+ { name: "postgrest: select limited to the tenant column", query: `select=${enc(col)}` },
423
+ { name: "postgrest: count of both tenants", query: `${col}=${enc(`in.(${mine},${theirs})`)}`, headers: { prefer: "count=exact" } },
424
+ { name: "postgrest: count only, the other tenant", query: `${col}=${enc(`eq.${theirs}`)}&limit=0`, headers: { prefer: "count=exact" } },
425
+ { name: "postgrest: count with an or group of both tenants", query: `or=${enc(`(${col}.eq.${mine},${col}.eq.${theirs})`)}`, headers: { prefer: "count=exact" } },
426
+ ];
427
+ // every way to load a relation, and every relation of those
428
+ for (const relation of entity.relations) {
429
+ out.push(...relationLoads(model, relation), nx(`join ${relation.property} with a filter on it`, `join=${enc(relation.property)}&filter=${f(`${relation.property}.id`, "$notnull")}&or=${f(`${relation.property}.id`, "$isnull")}`), nx(`sort by a field of ${relation.property}`, `join=${enc(relation.property)}&sort=${enc(`${relation.property}.id,DESC`)}&limit=1`), { name: `select embed ${relation.property} with a filter on it`, query: `select=${enc(`*,${relation.property}(*)`)}&${relation.property}.id=${enc("not.is.null")}` }, { name: `select inner embed ${relation.property} with a filter on it`, query: `select=${enc(`*,${relation.property}!inner(*)`)}&${relation.property}.id=${enc("not.is.null")}` }, { name: `select inner embed ${relation.property} with a filter on it and a count`, query: `select=${enc(`id,${relation.property}!inner(id)`)}&${relation.property}.id=${enc("not.is.null")}`, headers: { prefer: "count=exact" } }, { name: `order by a field of ${relation.property}`, query: `select=${enc(`*,${relation.property}(id)`)}&order=${enc(`${relation.property}(id).desc`)}&limit=1` });
430
+ }
431
+ return forms(model, out);
432
+ }
433
+ /** A list answer is clean when it is refused, or holds none of the other tenant's rows and no more rows than the caller owns. */
434
+ function widened(model, entity, res, theirs, own) {
435
+ var _a, _b, _c, _d;
436
+ // Refused. A 5xx returned no rows either: it is a defect, reported as a warning, not a leak.
437
+ if (res.status >= 400)
438
+ return "";
439
+ // 206 is a page of a longer list (PostgREST).
440
+ if (res.status !== 200 && res.status !== 206)
441
+ return `status ${res.status} ${res.text.slice(0, 200)}`;
442
+ // A list answers with an envelope or a bare array; a read by id with the row.
443
+ const isList = Array.isArray(res.json) || Array.isArray((_a = res.json) === null || _a === void 0 ? void 0 : _a.data) || Array.isArray((_b = res.json) === null || _b === void 0 ? void 0 : _b.items);
444
+ const leaked = foreignRows(model, entity.name, isList ? rowsOf(res.json) : res.json, theirs);
445
+ if (leaked.length > 0)
446
+ return `returned another tenant's rows: ${[...new Set(leaked)].join(", ")}`;
447
+ const n = rowsOf(res.json).length;
448
+ // The total a list reports: in the nestjsx envelope, or in Content-Range.
449
+ const total = typeof ((_c = res.json) === null || _c === void 0 ? void 0 : _c.total) === "number" ? res.json.total : (_d = rangeTotal(res)) !== null && _d !== void 0 ? _d : n;
450
+ if (entity.scope && (n > own || total > own))
451
+ return `returned ${n} rows (total ${total}); the caller owns ${own}`;
452
+ return "";
453
+ }
454
+ // ---------- the cases ----------
455
+ async function whoIsCalling(ctx) {
456
+ var _a;
457
+ const { base, model, t, key } = ctx;
458
+ t.expect("[R1] /health is public", await call("GET", `${base}/health`), 200);
459
+ for (const entity of model.entities)
460
+ t.expect(`[R1] ${entity.name}: no credential`, await call("GET", base + entity.route), 401);
461
+ const first = model.entities[0];
462
+ if (!first)
463
+ return;
464
+ for (const bad of (_a = ctx.badTokens) !== null && _a !== void 0 ? _a : [])
465
+ t.expect(`[R2] ${bad.label}`, await call("GET", base + first.route, { headers: bad.headers }), 401);
466
+ t.expect("[R5] a key that is not the service's key", await call("GET", base + first.route, { headers: { "x-api-key": "apso-access-wrong-key" } }), 401);
467
+ t.expect("[R13] the service's key is a service caller", await call("GET", base + first.route, { headers: key }), 200);
468
+ if (ctx.user)
469
+ t.expect("[R14] a wrong key is refused even with a valid user token", await call("GET", base + first.route, { headers: { ...ctx.user({ tenant: "1" }), "x-api-key": "apso-access-wrong-key" } }), 401);
470
+ }
471
+ /**
472
+ * The roles the test callers hold: every role a permissions list names, so a
473
+ * role check does not hide a tenant check. Bypass roles are left out.
474
+ */
475
+ function callerRoles(model) {
476
+ const bypass = new Set(model.entities.flatMap((e) => { var _a, _b; return (_b = (_a = e.scope) === null || _a === void 0 ? void 0 : _a.bypassRoles) !== null && _b !== void 0 ? _b : []; }));
477
+ return [...new Set(model.entities.flatMap((e) => { var _a; return Object.values((_a = e.permissions) !== null && _a !== void 0 ? _a : {}).flat(); }))].filter((r) => !bypass.has(r));
478
+ }
479
+ /** True for the 400 a TypeScript service gives an embed that names no embeddable relation: it names the embed and lists the relations. */
480
+ const notEmbeddable = (res, name) => { var _a; return res.status === 400 && typeof ((_a = res.json) === null || _a === void 0 ? void 0 : _a.message) === "string" && res.json.message.includes(`'${name}' cannot be embedded`) && res.json.message.includes("Embeddable relations:"); };
481
+ /** The message of a JSON error body (message in TypeScript, detail in Python, error in Go), or the text itself. */
482
+ const messageOf = (text) => {
483
+ var _a, _b, _c, _d;
484
+ try {
485
+ const body = JSON.parse(text !== null && text !== void 0 ? text : "");
486
+ return (_d = (_c = (_b = (_a = body === null || body === void 0 ? void 0 : body.message) !== null && _a !== void 0 ? _a : body === null || body === void 0 ? void 0 : body.detail) !== null && _b !== void 0 ? _b : body === null || body === void 0 ? void 0 : body.error) !== null && _c !== void 0 ? _c : text) !== null && _d !== void 0 ? _d : "";
487
+ }
488
+ catch {
489
+ return text !== null && text !== void 0 ? text : "";
490
+ }
491
+ };
492
+ /** True for the 400 a PostgREST-only service gives a nestjsx parameter: it names the parameter. */
493
+ const refused = (res, parameter) => { var _a; return res.status === 400 && typeof ((_a = res.json) === null || _a === void 0 ? void 0 : _a.message) === "string" && res.json.message.includes(`'${parameter}'`) && /PostgREST/.test(res.json.message); };
494
+ /**
495
+ * A PostgREST-only service answers 400 to each nestjsx query parameter and
496
+ * says what to send instead. One case per parameter: the forms left out by
497
+ * forms() above are all spelled with these.
498
+ */
499
+ async function nestjsxRefused(ctx) {
500
+ var _a, _b, _c, _d, _e;
501
+ const { base, model, t, key } = ctx;
502
+ const entity = (_a = model.entities.find((e) => e.scope)) !== null && _a !== void 0 ? _a : model.entities[0];
503
+ if (!entity)
504
+ return;
505
+ const url = base + entity.route;
506
+ const relation = (_c = (_b = entity.relations[0]) === null || _b === void 0 ? void 0 : _b.property) !== null && _c !== void 0 ? _c : "x";
507
+ const parameters = [
508
+ ["fields", "id"],
509
+ ["filter", "id||$notnull"],
510
+ ["or", "id||$notnull"],
511
+ ["join", relation],
512
+ ["sort", "id,DESC"],
513
+ ["s", JSON.stringify({ id: { $notnull: true } })],
514
+ ["per_page", "1000"],
515
+ ["page", "1"],
516
+ ["cache", "0"],
517
+ ];
518
+ for (const [parameter, value] of parameters) {
519
+ const res = await call("GET", `${url}?${parameter}=${enc(value)}`, { headers: key });
520
+ t.assert(`[R7] ${entity.name}: the nestjsx parameter ${parameter} is refused with a 400 that names it`, refused(res, parameter), `${res.status} ${res.text.slice(0, 300)}`);
521
+ }
522
+ const array = await call("GET", `${url}?filter[]=${enc("id||$notnull")}`, { headers: key });
523
+ t.assert(`[R7] ${entity.name}: a nestjsx parameter sent as an array is refused with a 400`, refused(array, "filter"), `${array.status} ${array.text.slice(0, 300)}`);
524
+ const byId = await call("GET", `${url}/1?join=${enc(relation)}`, { headers: key });
525
+ t.assert(`[R7] ${entity.name}: a nestjsx parameter on a read by id is refused with a 400`, refused(byId, "join"), `${byId.status} ${byId.text.slice(0, 300)}`);
526
+ t.expect(`[R7] ${entity.name}: the X-Crud-Dialect: nestjsx header is refused with a 400`, await call("GET", url, { headers: { ...key, "x-crud-dialect": "nestjsx" } }), 400);
527
+ const user = (_d = ctx.user) === null || _d === void 0 ? void 0 : _d.call(ctx, { tenant: "1", roles: callerRoles(model) });
528
+ if (user)
529
+ t.expect(`[R7] ${entity.name}: a nestjsx parameter from a signed-in caller is refused with a 400`, await call("GET", `${url}?filter=${enc("id||$notnull")}`, { headers: user }), 400);
530
+ const plain = await call("GET", `${url}?limit=1`, { headers: key });
531
+ t.assert(`[R7] ${entity.name}: a list is a JSON array with a Content-Range header`, plain.status === 200 && Array.isArray(plain.json) && /^(\d+-\d+|\*)\/(\d+|\*)$/.test((_e = plain.range) !== null && _e !== void 0 ? _e : ""), `${plain.status} Content-Range ${plain.range} ${plain.text.slice(0, 200)}`);
532
+ }
533
+ async function tenantScope(ctx, entity, a, b, asA) {
534
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
535
+ const { base, model, t, key } = ctx;
536
+ const url = base + entity.route;
537
+ const mine = a.rows[entity.name];
538
+ const other = b.rows[entity.name];
539
+ const col = entity.scope.field;
540
+ const [mineValue, theirValue] = [String(mine[col]), String(other[col])];
541
+ const n = entity.name;
542
+ // R6
543
+ const plain = await call("GET", url, { headers: asA });
544
+ const own = rowsOf(plain.json);
545
+ t.assert(`[R6] ${n}: a caller lists its own row and not the other tenant's`, plain.status === 200 && own.some((r) => String(r.id) === String(mine.id)) && !own.some((r) => String(r.id) === String(other.id)), `${plain.status} ${plain.text.slice(0, 200)}`);
546
+ const ownCount = typeof ((_a = plain.json) === null || _a === void 0 ? void 0 : _a.total) === "number" ? plain.json.total : own.length;
547
+ t.expect(`[R6] ${n}: read another tenant's row by id`, await call("GET", `${url}/${other.id}`, { headers: asA }), 403, 404);
548
+ t.expect(`[R6] ${n}: update another tenant's row`, await call("PATCH", `${url}/${other.id}`, { headers: asA, body: payloadFor(entity, 7) }), 403, 404);
549
+ t.expect(`[R6] ${n}: replace another tenant's row`, await call("PUT", `${url}/${other.id}`, { headers: asA, body: payloadFor(entity, 7) }), 403, 404, 405);
550
+ t.expect(`[R6] ${n}: delete another tenant's row`, await call("DELETE", `${url}/${other.id}`, { headers: asA }), 403, 404);
551
+ const still = await call("GET", `${url}/${other.id}`, { headers: key });
552
+ t.assert(`[R6] ${n}: the other tenant's row is unchanged after those attempts`, still.status === 200 && [col, ...Object.keys(entity.payload)].every((k) => { var _a; return JSON.stringify((_a = still.json) === null || _a === void 0 ? void 0 : _a[k]) === JSON.stringify(other[k]); }), `${still.status} ${still.text.slice(0, 200)}`);
553
+ const all = await call("GET", `${url}?limit=1000`, { headers: key });
554
+ t.assert(`[R10] ${n}: a service caller lists both tenants' rows`, all.status === 200 && [mine, other].every((row) => rowsOf(all.json).some((r) => String(r.id) === String(row.id))), `${all.status} ${all.text.slice(0, 200)}`);
555
+ // R7
556
+ const harmless = await call("GET", `${url}?select=${enc("*")}`, { headers: { ...asA, ...POSTGREST } });
557
+ if (harmless.status >= 400)
558
+ (_b = ctx.warn) === null || _b === void 0 ? void 0 : _b.call(ctx, `${n}: a harmless PostgREST-dialect request (select=*) answered ${harmless.status}, so the PostgREST cases on this entity were refused before they could test the tenant filter`);
559
+ for (const attempt of widenAttempts(model, entity, mineValue, theirValue, String(other.id))) {
560
+ const res = await call("GET", attempt.query ? `${url}?${attempt.query}` : url, { headers: { ...asA, ...attempt.headers } });
561
+ if (res.status >= 500)
562
+ (_c = ctx.warn) === null || _c === void 0 ? void 0 : _c.call(ctx, `${n}: GET ${entity.route}?${attempt.query} answered ${res.status}`);
563
+ t.assert(`[R7] ${n}: ${attempt.name} (${res.status})`, widened(model, entity, res, b.rows, ownCount) === "", `GET ${entity.route}?${attempt.query} ${widened(model, entity, res, b.rows, ownCount)}`);
564
+ }
565
+ for (const { name, query } of forms(model, [
566
+ nx("a filter", `filter=${f(col, "$eq", theirValue)}`),
567
+ nx("an s search", `s=${enc(JSON.stringify({ [col]: theirValue }))}`),
568
+ nx("an or", `or=${f("id", "$eq", String(other.id))}`),
569
+ ...entity.relations.map((r) => nx(`join ${r.property}`, `join=${enc(r.property)}`)),
570
+ { name: "a column filter", query: `${col}=${enc(`eq.${theirValue}`)}` },
571
+ { name: "an or group", query: `or=${enc(`(id.eq.${other.id},${col}.eq.${theirValue})`)}` },
572
+ { name: "a select", query: `select=${enc("*")}` },
573
+ ...entity.relations.map((r) => ({ name: `select embed ${r.property}`, query: `select=${enc(`*,${r.property}(*)`)}` })),
574
+ ]))
575
+ t.expect(`[R7] ${n}: read another tenant's row by id with ${name}`, await call("GET", `${url}/${other.id}?${query}`, { headers: asA }), 400, 403, 404);
576
+ // The count a list reports is a second way to learn about rows: it must
577
+ // cover the caller's rows only, whatever the query asks for.
578
+ if (postgrestOnly(model)) {
579
+ const exact = { prefer: "count=exact" };
580
+ const counts = [
581
+ ["a plain list", "", ownCount],
582
+ ["a count-only request (limit=0)", "limit=0", ownCount],
583
+ ["a filter that lists both tenants", `${col}=${enc(`in.(${mineValue},${theirValue})`)}`, ownCount],
584
+ ["an or group that names the other tenant's row", `or=${enc(`(id.eq.${mine.id},id.eq.${other.id})`)}`, 1],
585
+ ["a filter on the other tenant's row id", `id=${enc(`eq.${other.id}`)}`, 0],
586
+ ];
587
+ for (const [name, query, expected] of counts) {
588
+ const res = await call("GET", query ? `${url}?${query}` : url, { headers: { ...asA, ...exact } });
589
+ t.assert(`[R6,R7] ${n}: the Content-Range count of ${name} is the caller's rows only`, [200, 206].includes(res.status) && rangeTotal(res) === expected, `GET ${entity.route}?${query} answered ${res.status} with Content-Range ${res.range}; expected a total of ${expected}`);
590
+ }
591
+ const every = await call("GET", `${url}?limit=0`, { headers: { ...key, ...exact } });
592
+ t.assert(`[R10] ${n}: a service caller's Content-Range count covers both tenants`, every.status === 200 && ((_d = rangeTotal(every)) !== null && _d !== void 0 ? _d : 0) >= ownCount + 1, `${every.status} Content-Range ${every.range}`);
593
+ }
594
+ // R8: whatever a body says, a written row stays with the caller. For a
595
+ // scopeBy field the value is the tenant; for a path through a parent it is
596
+ // the caller's parent row.
597
+ {
598
+ const [myValue, theirs] = [mine[col], other[col]];
599
+ const watched = [col, ...Object.keys(entity.payload)];
600
+ const stored = async (label, id) => {
601
+ var _a, _b;
602
+ const row = await call("GET", `${url}/${id}`, { headers: key });
603
+ t.assert(label, row.status === 200 && String((_a = row.json) === null || _a === void 0 ? void 0 : _a[col]) === mineValue, `${col}=${(_b = row.json) === null || _b === void 0 ? void 0 : _b[col]} (${row.status})`);
604
+ };
605
+ const made = [];
606
+ // The relation whose foreign key is the scope column.
607
+ const relation = (_e = entity.relations.find((r) => `${r.property}Id` === col)) === null || _e === void 0 ? void 0 : _e.property;
608
+ const upper = (s) => s.charAt(0).toUpperCase() + s.slice(1);
609
+ const namings = [
610
+ ["names another tenant", { [col]: theirs }],
611
+ ["names another tenant as text", { [col]: String(theirs) }],
612
+ ["names another tenant as an object in the column", { [col]: { id: theirs } }],
613
+ ["names another tenant beside an empty bulk list", { [col]: theirs, bulk: [] }],
614
+ [`names another tenant as ${upper(col)}`, { [upper(col)]: theirs }],
615
+ ...((0, casing_1.snakeCase)(col) === col ? [] : [[`names another tenant as ${(0, casing_1.snakeCase)(col)}`, { [(0, casing_1.snakeCase)(col)]: theirs }]]),
616
+ ["carries the id of another tenant's row", { id: other.id }],
617
+ ...(relation
618
+ ? [
619
+ [`names another tenant through ${relation}`, { [relation]: { id: theirs } }],
620
+ [`names its own tenant in the column and another through ${relation}`, { [col]: myValue, [relation]: { id: theirs } }],
621
+ [`names another tenant through ${relation} as a list`, { [relation]: [{ id: theirs }] }],
622
+ [`names another tenant through ${relation} as a bare id`, { [relation]: theirs }],
623
+ [`names another tenant through ${upper(relation)}`, { [upper(relation)]: { id: theirs } }],
624
+ ]
625
+ : []),
626
+ ];
627
+ let k = 10;
628
+ for (const [what, extra] of namings) {
629
+ k += 1;
630
+ // A row scoped through its parent names the caller's own parent first.
631
+ const body = (i) => ({ ...payloadFor(entity, i), ...parentsOf(entity, a), ...(entity.scope.parent ? { [col]: myValue } : {}), ...extra });
632
+ const created = await call("POST", url, { headers: asA, body: body(k * 10) });
633
+ if (created.status >= 400 && created.status < 500)
634
+ t.assert(`[R8] ${n}: a create body that ${what} is refused (${created.status})`, true);
635
+ else if (t.expect(`[R8] ${n}: create with a body that ${what}`, created, 200, 201)) {
636
+ made.push((_f = created.json) === null || _f === void 0 ? void 0 : _f.id);
637
+ await stored(`[R8] ${n}: a create body that ${what} is stored in the caller's tenant`, (_g = created.json) === null || _g === void 0 ? void 0 : _g.id);
638
+ }
639
+ const bulk = await call("POST", `${url}/bulk`, { headers: asA, body: { bulk: [body(k * 10 + 1), body(k * 10 + 2)] } });
640
+ const bulkRows = Array.isArray(bulk.json) ? bulk.json : [];
641
+ if (bulk.status === 200 || bulk.status === 201) {
642
+ for (const row of bulkRows) {
643
+ made.push(row.id);
644
+ await stored(`[R8] ${n}: a bulk create that ${what} is stored in the caller's tenant`, row.id);
645
+ }
646
+ t.assert(`[R8] ${n}: a bulk create that ${what} answers with its rows`, bulkRows.length > 0, bulk.text.slice(0, 200));
647
+ }
648
+ else
649
+ t.assert(`[R8] ${n}: a bulk create that ${what} is refused (${bulk.status})`, bulk.status >= 400 && bulk.status < 500, bulk.text.slice(0, 200));
650
+ for (const [method, verb] of [["PATCH", "update"], ["PUT", "replace"]]) {
651
+ const res = await call(method, `${url}/${mine.id}`, { headers: asA, body: body(1) });
652
+ t.assert(`[R8] ${n}: ${verb} own row with a body that ${what} (${res.status})`, res.status < 500 && res.status !== 0, res.text.slice(0, 200));
653
+ await stored(`[R8] ${n}: after a ${verb} with a body that ${what} the row is still in the caller's tenant`, mine.id);
654
+ }
655
+ const theirsNow = await call("GET", `${url}/${other.id}`, { headers: key });
656
+ const untouched = theirsNow.status === 200 && watched.every((w) => { var _a; return JSON.stringify((_a = theirsNow.json) === null || _a === void 0 ? void 0 : _a[w]) === JSON.stringify(other[w]); });
657
+ t.assert(`[R8] ${n}: bodies that ${what} leave the other tenant's row as it was`, untouched, `${theirsNow.status} ${theirsNow.text.slice(0, 200)}`);
658
+ // Put both rows back if a write moved them, so one failure does not cause others.
659
+ if (!untouched)
660
+ await call("PATCH", `${url}/${other.id}`, { headers: key, body: pick(other, watched) });
661
+ await call("PATCH", `${url}/${mine.id}`, { headers: key, body: { [col]: myValue } });
662
+ }
663
+ const steal = await call("PATCH", `${url}/${other.id}`, { headers: asA, body: { [col]: myValue } });
664
+ t.expect(`[R8] ${n}: move another tenant's row into the caller's tenant`, steal, 403, 404);
665
+ const theirsAfter = await call("GET", `${url}/${other.id}`, { headers: key });
666
+ t.assert(`[R8] ${n}: that row is still the other tenant's`, theirsAfter.status === 200 && String((_h = theirsAfter.json) === null || _h === void 0 ? void 0 : _h[col]) === theirValue, `${col}=${(_j = theirsAfter.json) === null || _j === void 0 ? void 0 : _j[col]}`);
667
+ for (const id of made)
668
+ if (id !== undefined && ![String(mine.id), String(other.id)].includes(String(id)))
669
+ await call("DELETE", `${url}/${id}`, { headers: key });
670
+ }
671
+ // R9
672
+ if (ctx.user) {
673
+ const noTenant = ctx.user({});
674
+ t.expect(`[R9] ${n}: a caller with no tenant cannot list`, await call("GET", url, { headers: noTenant }), 403);
675
+ t.expect(`[R9] ${n}: a caller with no tenant cannot read a row`, await call("GET", `${url}/${mine.id}`, { headers: noTenant }), 403, 404);
676
+ t.expect(`[R9] ${n}: a caller with no tenant cannot create`, await call("POST", url, { headers: noTenant, body: { ...payloadFor(entity, 31), ...parentsOf(entity, a) } }), 403);
677
+ }
678
+ // R10
679
+ if (ctx.user && ctx.roles && entity.scope.bypassRoles.length > 0) {
680
+ const bypass = await call("GET", `${url}?limit=1000`, { headers: ctx.user({ tenant: a.value, roles: [entity.scope.bypassRoles[0]] }) });
681
+ t.assert(`[R10] ${n}: the "${entity.scope.bypassRoles[0]}" role the schema names lists another tenant's row`, bypass.status === 200 && rowsOf(bypass.json).some((r) => String(r.id) === String(other.id)), `${bypass.status} ${bypass.text.slice(0, 200)}`);
682
+ const not = await call("GET", `${url}?limit=1000`, { headers: ctx.user({ tenant: a.value, roles: ["apso-access-no-such-role"] }) });
683
+ t.assert(`[R10] ${n}: a role the schema does not name stays in its tenant`, not.status !== 200 || !rowsOf(not.json).some((r) => String(r.id) === String(other.id)), `${not.status} ${not.text.slice(0, 200)}`);
684
+ }
685
+ }
686
+ const pick = (row, keys) => Object.fromEntries(keys.map((k) => [k, row[k]]));
687
+ const parentsOf = (entity, tenant) => Object.fromEntries(entity.parents.map((p) => { var _a; return [p.property, (_a = tenant.rows[p.entity]) === null || _a === void 0 ? void 0 : _a.id]; }));
688
+ /** An entity with no scopeBy must not hand out scoped rows through a join. */
689
+ async function joinsFromShared(ctx, entity, b, asA) {
690
+ var _a;
691
+ const { base, model, t } = ctx;
692
+ const scoped = (name) => { var _a; return Boolean((_a = model.entities.find((e) => e.name === name)) === null || _a === void 0 ? void 0 : _a.scope); };
693
+ const attempts = [];
694
+ for (const relation of entity.relations) {
695
+ const target = model.entities.find((e) => e.name === relation.entity);
696
+ const reachesScoped = scoped(relation.entity) || ((_a = target === null || target === void 0 ? void 0 : target.relations) !== null && _a !== void 0 ? _a : []).some((second) => scoped(second.entity));
697
+ if (!reachesScoped)
698
+ continue;
699
+ attempts.push(...relationLoads(model, relation).map((a) => ({ ...a, query: `${a.query}&limit=1000` })));
700
+ // Refused, not answered with the relation left out: the caller is told the load is not allowed.
701
+ if (scoped(relation.entity))
702
+ t.expect(`[R7] ${entity.name} (not scoped): a select embed of ${relation.property}, whose rows are tenant-scoped, is refused`, await call("GET", `${base}${entity.route}?select=${enc(`*,${relation.property}(*)`)}`, { headers: asA }), 403);
703
+ // A relation the caller may not load is a 403 (above); a name that is no embeddable relation is a 400 that lists them.
704
+ if (postgrestOnly(model)) {
705
+ const missing = `${relation.property}_apso_access_absent`;
706
+ for (const select of [`*,${missing}(*)`, `*,${missing}!inner(*)`]) {
707
+ const res = await call("GET", `${base}${entity.route}?select=${enc(select)}`, { headers: asA });
708
+ t.assert(`[R7] ${entity.name} (not scoped): a select embed of ${select.slice(2)}, which is no relation, is a 400 that lists the embeddable relations`, notEmbeddable(res, missing), `${res.status} ${res.text.slice(0, 300)}`);
709
+ }
710
+ }
711
+ // A filter on a field of the other tenant's row must not say whether it matched.
712
+ const theirs = target && b.rows[target.name];
713
+ if ((target === null || target === void 0 ? void 0 : target.scope) && theirs) {
714
+ const told = await oracle(model, base + entity.route, asA, relation.property, target, theirs);
715
+ t.assert(`[R7] ${entity.name} (not scoped): a filter on a field of ${relation.property} does not reveal another tenant's values`, told === "", `GET ${entity.route} ${told}`);
716
+ }
717
+ }
718
+ // With no join at all: a service that loads relations on every read leaks here.
719
+ const plain = await call("GET", `${base}${entity.route}?limit=1000`, { headers: asA });
720
+ t.assert(`[R6] ${entity.name} (not scoped): a list holds no other tenant's scoped rows (${plain.status})`, widened(model, entity, plain, b.rows, 0) === "", `GET ${entity.route}?limit=1000 ${widened(model, entity, plain, b.rows, 0)}`);
721
+ for (const attempt of attempts) {
722
+ const res = await call("GET", `${base}${entity.route}?${attempt.query}`, { headers: { ...asA, ...attempt.headers } });
723
+ t.assert(`[R7] ${entity.name} (not scoped): ${attempt.name} (${res.status})`, widened(model, entity, res, b.rows, 0) === "", `GET ${entity.route}?${attempt.query} ${widened(model, entity, res, b.rows, 0)}`);
724
+ const theirs = b.rows[entity.name];
725
+ if (!theirs)
726
+ continue;
727
+ const one = await call("GET", `${base}${entity.route}/${theirs.id}?${attempt.query}`, { headers: { ...asA, ...attempt.headers } });
728
+ t.assert(`[R7] ${entity.name} (not scoped): by id, ${attempt.name} (${one.status})`, widened(model, entity, one, b.rows, 0) === "", `GET ${entity.route}/${theirs.id}?${attempt.query} ${widened(model, entity, one, b.rows, 0)}`);
729
+ }
730
+ }
731
+ /**
732
+ * A body must not reach another tenant's row through a relation: naming the
733
+ * row under a relation of the caller's own row, or of a shared row, must not
734
+ * move it or change its fields.
735
+ */
736
+ async function relationWrites(ctx, entity, a, b, asA) {
737
+ var _a, _b, _c, _d;
738
+ const { base, model, t, key } = ctx;
739
+ const mine = a.rows[entity.name];
740
+ const url = base + entity.route;
741
+ for (const relation of entity.relations) {
742
+ const target = model.entities.find((e) => e.name === relation.entity);
743
+ const theirs = (target === null || target === void 0 ? void 0 : target.scope) && b.rows[target.name];
744
+ if (!target || !theirs)
745
+ continue;
746
+ const watched = [target.scope.field, ...Object.keys(target.payload)];
747
+ const text = (_a = target.fields.find((f) => typeof target.payload[f.name] === "string" && !f.is_email && TEXT.has(f.type))) === null || _a === void 0 ? void 0 : _a.name;
748
+ const item = { id: theirs.id, ...(text ? { [text]: "apso-access-changed" } : {}) };
749
+ const fresh = { ...payloadFor(entity, 51), ...parentsOf(entity, a), ...(((_b = entity.scope) === null || _b === void 0 ? void 0 : _b.parent) ? { [entity.scope.field]: mine[entity.scope.field] } : {}) };
750
+ const writes = [
751
+ ["update", "PATCH", `${url}/${mine.id}`, {}],
752
+ ["replace", "PUT", `${url}/${mine.id}`, { ...fresh, ...payloadFor(entity, 1) }],
753
+ ["create", "POST", url, fresh],
754
+ ];
755
+ for (const [shape, value] of [["a list", [item]], ["an object", item]]) {
756
+ for (const [verb, method, to, body] of writes) {
757
+ const res = await call(method, to, { headers: asA, body: { ...body, [relation.property]: value } });
758
+ if (res.status >= 500)
759
+ (_c = ctx.warn) === null || _c === void 0 ? void 0 : _c.call(ctx, `${entity.name}: ${method} with ${relation.property} in the body answered ${res.status}`);
760
+ const now = await call("GET", `${base}${target.route}/${theirs.id}`, { headers: key });
761
+ const untouched = now.status === 200 && watched.every((w) => { var _a; return JSON.stringify((_a = now.json) === null || _a === void 0 ? void 0 : _a[w]) === JSON.stringify(theirs[w]); });
762
+ t.assert(`[R8] ${entity.name}: a ${verb} that names another tenant's ${target.name} under ${relation.property} as ${shape} leaves that row as it was (${res.status})`, untouched, `${now.status} ${now.text.slice(0, 200)}`);
763
+ // Put the rows back before deleting the new one, so one failure does not cause others.
764
+ if (!untouched)
765
+ await call("PATCH", `${base}${target.route}/${theirs.id}`, { headers: key, body: pick(theirs, watched) });
766
+ const own = a.rows[target.name];
767
+ if (own)
768
+ await call("PATCH", `${base}${target.route}/${own.id}`, { headers: key, body: pick(own, watched) });
769
+ if (method === "POST" && ((_d = res.json) === null || _d === void 0 ? void 0 : _d.id) !== undefined && String(res.json.id) !== String(mine.id))
770
+ await call("DELETE", `${url}/${res.json.id}`, { headers: key });
771
+ }
772
+ }
773
+ }
774
+ }
775
+ const upperFirst = (s) => s.charAt(0).toUpperCase() + s.slice(1);
776
+ /** True when a stored row's foreign key names the row with this id. */
777
+ const names = (row, fk, id) => row !== undefined && row[fk] !== null && row[fk] !== undefined && String(row[fk]) === String(id);
778
+ /** A row as stored, read by a service caller. */
779
+ async function storedRow(ctx, url) {
780
+ const res = await call("GET", url, { headers: ctx.key });
781
+ return res.json;
782
+ }
783
+ /**
784
+ * A foreign key to a tenant-scoped entity must name a row the caller can
785
+ * read (R8), and a stored key that names another tenant's row must not carry
786
+ * that row into a response (R7). Runs for every such key of `entity` other
787
+ * than its own scope column, with every body shape the tenant cases use.
788
+ */
789
+ async function foreignKeys(ctx, entity, a, b, asA, asB) {
790
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
791
+ const { base, model, t, key } = ctx;
792
+ const mine = a.rows[entity.name];
793
+ const url = base + entity.route;
794
+ const n = entity.name;
795
+ const upper = upperFirst;
796
+ for (const relation of entity.relations) {
797
+ const fk = relation.fk;
798
+ const target = model.entities.find((e) => e.name === relation.entity);
799
+ if (!fk || !(target === null || target === void 0 ? void 0 : target.scope) || fk === ((_a = entity.scope) === null || _a === void 0 ? void 0 : _a.field))
800
+ continue;
801
+ const [own, theirs] = [a.rows[target.name], b.rows[target.name]];
802
+ if (!own || !theirs)
803
+ continue;
804
+ const p = relation.property;
805
+ const what = `another tenant's ${target.name}`;
806
+ const required = entity.parents.some((parent) => parent.property === fk);
807
+ const made = [];
808
+ const fresh = (i) => {
809
+ var _a;
810
+ return ({
811
+ ...payloadFor(entity, i),
812
+ ...parentsOf(entity, a),
813
+ ...(((_a = entity.scope) === null || _a === void 0 ? void 0 : _a.parent) ? { [entity.scope.field]: mine[entity.scope.field] } : {}),
814
+ });
815
+ };
816
+ const restore = ["PATCH", `${url}/${mine.id}`, { headers: key, body: { [fk]: (_b = mine[fk]) !== null && _b !== void 0 ? _b : null } }];
817
+ // R8: the plain forms are refused with 403, in every language.
818
+ const plain = { [fk]: theirs.id };
819
+ t.expect(`[R8] ${n}: a create that names ${what} in ${fk} is refused`, await call("POST", url, { headers: asA, body: { ...fresh(61), ...plain } }), 403);
820
+ t.expect(`[R8] ${n}: an update that names ${what} in ${fk} is refused`, await call("PATCH", `${url}/${mine.id}`, { headers: asA, body: plain }), 403);
821
+ t.expect(`[R8] ${n}: a replace that names ${what} in ${fk} is refused`, await call("PUT", `${url}/${mine.id}`, { headers: asA, body: { ...fresh(1), ...plain } }), 403, 405);
822
+ await call(...restore);
823
+ // R8: whatever the body's shape, the reference is never stored.
824
+ const namings = [
825
+ [`in ${fk}`, plain],
826
+ [`in ${fk} as text`, { [fk]: String(theirs.id) }],
827
+ [`as an object in ${fk}`, { [fk]: { id: theirs.id } }],
828
+ [`in ${fk} beside an empty bulk list`, { [fk]: theirs.id, bulk: [] }],
829
+ [`as ${upper(fk)}`, { [upper(fk)]: theirs.id }],
830
+ ...((0, casing_1.snakeCase)(fk) === fk ? [] : [[`as ${(0, casing_1.snakeCase)(fk)}`, { [(0, casing_1.snakeCase)(fk)]: theirs.id }]]),
831
+ [`through ${p}`, { [p]: { id: theirs.id } }],
832
+ [`through ${p} beside its own ${target.name} in ${fk}`, { [fk]: own.id, [p]: { id: theirs.id } }],
833
+ [`through ${p} as a list`, { [p]: [{ id: theirs.id }] }],
834
+ [`through ${p} as a bare id`, { [p]: theirs.id }],
835
+ [`through ${upper(p)}`, { [upper(p)]: { id: theirs.id } }],
836
+ ];
837
+ let k = 62;
838
+ for (const [how, extra] of namings) {
839
+ k += 3;
840
+ const created = await call("POST", url, { headers: asA, body: { ...fresh(k), ...extra } });
841
+ if (((_c = created.json) === null || _c === void 0 ? void 0 : _c.id) !== undefined && created.status < 300)
842
+ made.push(created.json.id);
843
+ t.assert(`[R8] ${n}: a create that names ${what} ${how} does not store that reference (${created.status})`, created.status !== 0 && created.status < 500 && (created.status >= 400 || !names(await storedRow(ctx, `${url}/${(_d = created.json) === null || _d === void 0 ? void 0 : _d.id}`), fk, theirs.id)), created.text.slice(0, 200));
844
+ const bulk = await call("POST", `${url}/bulk`, { headers: asA, body: { bulk: [{ ...fresh(k + 1), [fk]: own.id }, { ...fresh(k + 2), ...extra }] } });
845
+ const bulkRows = bulk.status < 300 && Array.isArray(bulk.json) ? bulk.json : [];
846
+ let kept = false;
847
+ for (const row of bulkRows) {
848
+ made.push(row.id);
849
+ kept = kept || names(await storedRow(ctx, `${url}/${row.id}`), fk, theirs.id);
850
+ }
851
+ t.assert(`[R8] ${n}: a bulk create with a row that names ${what} ${how} does not store that reference (${bulk.status})`, bulk.status !== 0 && bulk.status < 500 && !kept, bulk.text.slice(0, 200));
852
+ for (const [method, verb, body] of [["PATCH", "update", extra], ["PUT", "replace", { ...fresh(1), ...extra }]]) {
853
+ const res = await call(method, `${url}/${mine.id}`, { headers: asA, body });
854
+ t.assert(`[R8] ${n}: ${verb === "update" ? "an" : "a"} ${verb} that names ${what} ${how} does not store that reference (${res.status})`, res.status !== 0 && res.status < 500 && !names(await storedRow(ctx, `${url}/${mine.id}`), fk, theirs.id), res.text.slice(0, 200));
855
+ await call(...restore);
856
+ }
857
+ }
858
+ // R8: the caller's own row, and no row at all, are still accepted.
859
+ const ok = await call("POST", url, { headers: asA, body: { ...fresh(98), [fk]: own.id } });
860
+ if (t.expect(`[R8] ${n}: a create that names its own tenant's ${target.name} in ${fk}`, ok, 200, 201))
861
+ made.push((_e = ok.json) === null || _e === void 0 ? void 0 : _e.id);
862
+ t.expect(`[R8] ${n}: an update that names its own tenant's ${target.name} in ${fk}`, await call("PATCH", `${url}/${mine.id}`, { headers: asA, body: { [fk]: own.id } }), 200);
863
+ if (!required)
864
+ t.expect(`[R8] ${n}: an update that sets ${fk} to null`, await call("PATCH", `${url}/${mine.id}`, { headers: asA, body: { [fk]: null } }), 200);
865
+ await call(...restore);
866
+ // R7: a row written by a service caller that names the other tenant's row.
867
+ const seeded = await call("POST", url, { headers: key, body: { ...fresh(99), ...(entity.scope && !entity.scope.parent ? { [entity.scope.field]: mine[entity.scope.field] } : {}), [fk]: theirs.id } });
868
+ if (t.assert(`[R7] ${n}: a service caller stores a row that names ${what} in ${fk} (${seeded.status})`, seeded.status < 300 && names(seeded.json, fk, theirs.id), seeded.text.slice(0, 200))) {
869
+ const row = seeded.json;
870
+ made.push(row.id);
871
+ const select = (embed) => `select=${enc(embed)}`;
872
+ const loads = [
873
+ [`select embed ${p}`, select(`*,${p}(*)`)],
874
+ [`select embed ${p} with chosen columns`, select(`id,${p}(id)`)],
875
+ [`select embed ${p} under an alias`, select(`*,${alias(p)}:${p}(*)`)],
876
+ [`select embed ${p} with an inner join hint`, select(`*,${p}!inner(*)`)],
877
+ // Python and Go load a relation on a read by id only through the join parameter.
878
+ ...(model.language === "typescript" ? [] : [[`join ${p}`, `join=${enc(p)}`]]),
879
+ ];
880
+ for (const [name, query] of loads) {
881
+ for (const [where, to] of [["a list", `${url}?${query}&limit=1000`], ["a read by id", `${url}/${row.id}?${query}`]]) {
882
+ const res = await call("GET", to, { headers: query.startsWith("join=") ? asA : { ...asA, ...POSTGREST } });
883
+ if (res.status >= 500)
884
+ (_f = ctx.warn) === null || _f === void 0 ? void 0 : _f.call(ctx, `${n}: GET ${to.slice(base.length)} answered ${res.status}`);
885
+ const leaked = res.status === 200 ? foreignRows(model, n, (_h = (_g = res.json) === null || _g === void 0 ? void 0 : _g.data) !== null && _h !== void 0 ? _h : res.json, b.rows) : [];
886
+ t.assert(`[R7] ${n}: ${where} with ${name} does not return ${what} through a stored ${fk} (${res.status})`, res.status !== 0 && leaked.length === 0, `GET ${to.slice(base.length)} returned ${leaked.join(", ")}`);
887
+ }
888
+ }
889
+ const told = await oracle(model, url, asA, p, target, theirs, row);
890
+ t.assert(`[R7] ${n}: a filter on a field of ${p} does not reveal ${what} through a stored ${fk}`, told === "", `GET ${entity.route} ${told}`);
891
+ // The tenant condition on the relation holds for an embedded filter, an
892
+ // inner embed and the count: the row reaches the other tenant's row only
893
+ // through the stored key, so nothing may match through it.
894
+ const counted = { ...asA, ...POSTGREST, prefer: "count=exact" };
895
+ const total = (res) => { var _a; return (typeof ((_a = res.json) === null || _a === void 0 ? void 0 : _a.total) === "number" ? res.json.total : rangeTotal(res)); };
896
+ const embedded = [
897
+ [`an inner embed of ${p} filtered on ${what}'s id`, `select=${enc(`id,${p}!inner(id)`)}&${p}.id=${enc(`eq.${theirs.id}`)}`],
898
+ [`an inner embed of ${p} filtered on ${what}'s id, count only`, `select=${enc(`id,${p}!inner(id)`)}&${p}.id=${enc(`eq.${theirs.id}`)}&limit=0`],
899
+ [`an inner embed of ${p} filtered on ${what}'s id and the row's own id`, `select=${enc(`*,${p}!inner(*)`)}&${p}.id=${enc(`eq.${theirs.id}`)}&id=${enc(`eq.${row.id}`)}`],
900
+ [`an inner embed of ${p} filtered on ${what}'s id with in`, `select=${enc(`id,${p}!inner(id)`)}&${p}.id=${enc(`in.(${theirs.id})`)}`],
901
+ ];
902
+ // Python and Go drop the !inner hint, so there the row itself may come back, with the relation empty.
903
+ for (const [name, query] of embedded) {
904
+ const res = await call("GET", `${url}?${query}`, { headers: counted });
905
+ if (res.status >= 500)
906
+ (_j = ctx.warn) === null || _j === void 0 ? void 0 : _j.call(ctx, `${n}: GET ${entity.route}?${query} answered ${res.status}`);
907
+ const reached = res.status < 300 ? rowsOf(res.json).filter((r) => (postgrestOnly(model) && String(r.id) === String(row.id)) || foreignRows(model, n, [r], b.rows).length > 0) : [];
908
+ const count = res.status < 300 ? total(res) : undefined;
909
+ t.assert(`[R7] ${n}: ${name} matches no row and counts none (${res.status})`, res.status !== 0 && res.status < 500 && reached.length === 0 && (count === undefined || count === 0), `GET ${entity.route}?${query} returned ${reached.length} row(s) through ${fk}, count ${count}, Content-Range ${res.range}`);
910
+ }
911
+ if (postgrestOnly(model)) {
912
+ // Listing both related rows counts what the caller's own row reaches, and no more.
913
+ const both = await call("GET", `${url}?select=${enc(`id,${p}!inner(id)`)}&${p}.id=${enc(`in.(${own.id},${theirs.id})`)}&limit=0`, { headers: counted });
914
+ const ownOnly = await call("GET", `${url}?select=${enc(`id,${p}!inner(id)`)}&${p}.id=${enc(`eq.${own.id}`)}&limit=0`, { headers: counted });
915
+ t.assert(`[R6,R7] ${n}: the Content-Range count of an inner embed of ${p} filtered on both tenants' rows counts the caller's own only`, both.status < 300 && rangeTotal(both) !== undefined && rangeTotal(both) === rangeTotal(ownOnly), `${both.status} Content-Range ${both.range}; own only ${ownOnly.status} ${ownOnly.range}`);
916
+ }
917
+ // MCP list tools go through the same route, so the same requests as tool arguments.
918
+ if (ctx.mcp && entity.tools.list) {
919
+ const client = await ctx.mcp(asA).catch(() => null);
920
+ const args = [
921
+ [`an inner embed of ${p} filtered on ${what}'s id`, { select: `id,${p}!inner(id)`, embedded: { [`${p}.id`]: `eq.${theirs.id}` }, limit: 1000 }],
922
+ [`an embed of ${p} filtered on ${what}'s id`, { select: `*,${p}(*)`, embedded: { [`${p}.id`]: `eq.${theirs.id}` }, limit: 1000 }],
923
+ [`an inner embed of ${p} filtered on ${what}'s id, one row`, { select: `id,${p}!inner(id)`, embedded: { [`${p}.id`]: `in.(${own.id},${theirs.id})` }, limit: 1 }],
924
+ ];
925
+ for (const [name, a2] of client ? args : []) {
926
+ const res = await client.callTool(entity.tools.list, a2);
927
+ const rows = res.error === undefined ? rowsOf(res.json) : [];
928
+ const reached = rows.filter((r) => foreignRows(model, n, [r], b.rows).length > 0 || (postgrestOnly(model) && String(a2.select).includes("!inner") && String(r.id) === String(row.id)));
929
+ t.assert(`[R7,R23] mcp ${entity.tools.list}: ${name} does not return ${what} through a stored ${fk}`, reached.length === 0, `${JSON.stringify(a2)} returned ${JSON.stringify(reached).slice(0, 200)}`);
930
+ }
931
+ t.assert(`[R7,R23] mcp ${entity.tools.list}: connects for the ${fk} cases`, client !== null);
932
+ }
933
+ // The other way round: the other tenant's caller loads its own row's relation back to this entity.
934
+ for (const back of entity.scope ? target.relations.filter((r) => r.entity === n) : []) {
935
+ const q = back.property;
936
+ const joined = model.language === "typescript" ? select(`*,${q}(*)`) : `join=${enc(q)}`;
937
+ for (const [where, to, headers] of [["a list", `${base}${target.route}?${select(`*,${q}(*)`)}&limit=1000`, POSTGREST], ["a read by id", `${base}${target.route}/${theirs.id}?${joined}`, model.language === "typescript" ? POSTGREST : {}]]) {
938
+ const res = await call("GET", to, { headers: { ...asB, ...headers } });
939
+ const leaked = res.status === 200 ? rowsWhere(model, target.name, (_l = (_k = res.json) === null || _k === void 0 ? void 0 : _k.data) !== null && _l !== void 0 ? _l : res.json, (e, r) => e.name === n && String(r.id) === String(row.id)) : [];
940
+ t.assert(`[R7] ${target.name}: ${where} that loads ${q} does not return another tenant's ${n} that names it in ${fk} (${res.status})`, res.status !== 0 && leaked.length === 0, `GET ${to.slice(base.length)} returned ${leaked.join(", ")}`);
941
+ }
942
+ }
943
+ // A relation inside the tenant still loads.
944
+ const within = ((_m = ok.json) === null || _m === void 0 ? void 0 : _m.id) === undefined ? undefined : await call("GET", `${url}?select=${enc(`*,${p}(*)`)}&id=${enc(`eq.${ok.json.id}`)}`, { headers: { ...asA, ...POSTGREST } });
945
+ if ((within === null || within === void 0 ? void 0 : within.status) === 200)
946
+ t.assert(`[R7] ${n}: a list with select embed ${p} returns its own tenant's ${target.name}`, String((_p = (_o = rowsOf(within.json)[0]) === null || _o === void 0 ? void 0 : _o[p]) === null || _p === void 0 ? void 0 : _p.id) === String(own.id), within.text.slice(0, 200));
947
+ }
948
+ for (const id of made)
949
+ if (id !== undefined && String(id) !== String(mine.id))
950
+ await call("DELETE", `${url}/${id}`, { headers: key });
951
+ }
952
+ }
953
+ const NO_ROLE = "apso-access-no-such-role";
954
+ async function permissions(ctx, entity, a, b) {
955
+ var _a, _b, _c, _d, _e, _f;
956
+ const { base, model, t } = ctx;
957
+ if (!ctx.user || !ctx.roles || !entity.permissions)
958
+ return;
959
+ const url = base + entity.route;
960
+ const row = a.rows[entity.name];
961
+ const n = entity.name;
962
+ const outsider = ctx.user({ tenant: a.value, roles: [NO_ROLE] });
963
+ const rule = entity.name === model.grants ? "R11,R12" : "R11";
964
+ const tries = {
965
+ read: [
966
+ ["list", () => call("GET", url, { headers: outsider })],
967
+ ...(row ? [["read by id", () => call("GET", `${url}/${row.id}`, { headers: outsider })]] : []),
968
+ ],
969
+ create: [["create", () => call("POST", url, { headers: outsider, body: { ...payloadFor(entity, 41), ...parentsOf(entity, a) } })]],
970
+ update: row ? [["update", () => call("PATCH", `${url}/${row.id}`, { headers: outsider, body: payloadFor(entity, 42) })]] : [],
971
+ delete: row ? [["delete", () => call("DELETE", `${url}/${row.id}`, { headers: outsider })]] : [],
972
+ };
973
+ for (const [op, roles] of Object.entries(entity.permissions)) {
974
+ for (const [what, attempt] of (_a = tries[op]) !== null && _a !== void 0 ? _a : [])
975
+ t.expect(`[${rule}] ${n}: a role outside ${op} [${roles.join(", ")}] cannot ${what}`, await attempt(), 403);
976
+ }
977
+ const readers = entity.permissions.read;
978
+ // A role that cannot read the entity must not be sent its rows through a
979
+ // relation of another entity, however the relation is loaded, nor learn
980
+ // their fields through a filter.
981
+ if (readers) {
982
+ const guarded = (e) => e.name === entity.name;
983
+ for (const from of model.entities) {
984
+ if ((_b = from.permissions) === null || _b === void 0 ? void 0 : _b.read)
985
+ continue;
986
+ for (const relation of from.relations) {
987
+ const target = model.entities.find((e) => e.name === relation.entity);
988
+ const direct = relation.entity === entity.name;
989
+ if (!direct && !((_c = target === null || target === void 0 ? void 0 : target.relations) !== null && _c !== void 0 ? _c : []).some((second) => second.entity === entity.name))
990
+ continue;
991
+ for (const attempt of relationLoads(model, relation)) {
992
+ const res = await call("GET", `${base}${from.route}?${attempt.query}&limit=1000`, { headers: { ...outsider, ...attempt.headers } });
993
+ const sent = res.status === 200 ? rowsWhere(model, from.name, rowsOf(res.json), guarded) : [];
994
+ t.assert(`[R11] ${n}: a role outside read is not sent ${n} rows by ${from.name}, ${attempt.name} (${res.status})`, res.status !== 0 && res.status < 500 && sent.length === 0, `GET ${from.route}?${attempt.query} returned ${sent.length} ${n} row(s)`);
995
+ }
996
+ if (direct && row) {
997
+ const told = await oracle(model, base + from.route, outsider, relation.property, entity, row);
998
+ t.assert(`[R11] ${n}: a role outside read cannot test ${n} fields through a filter on ${from.name}.${relation.property}`, told === "", `GET ${from.route} ${told}`);
999
+ if (!postgrestOnly(model))
1000
+ t.expect(`[R11] ${n}: a role outside read cannot join ${from.name}?join=${relation.property}`, await call("GET", `${base}${from.route}?join=${enc(relation.property)}`, { headers: outsider }), 403);
1001
+ t.expect(`[R11] ${n}: a role outside read cannot embed ${from.name}?select=*,${relation.property}(*)`, await call("GET", `${base}${from.route}?select=${enc(`*,${relation.property}(*)`)}`, { headers: outsider }), 403);
1002
+ }
1003
+ }
1004
+ }
1005
+ }
1006
+ if (readers && readers.length > 0)
1007
+ t.expect(`[R11] ${n}: the "${readers[0]}" role can list`, await call("GET", url, { headers: ctx.user({ tenant: a.value, roles: [readers[0]] }) }), 200);
1008
+ // R12: a grant made by a role that may grant applies in that tenant only.
1009
+ const grants = model.entities.find((e) => e.name === model.grants);
1010
+ const granter = (_e = (_d = grants === null || grants === void 0 ? void 0 : grants.permissions) === null || _d === void 0 ? void 0 : _d.create) === null || _e === void 0 ? void 0 : _e[0];
1011
+ if (!readers || !grants || !granter || entity === grants || !grants.scope)
1012
+ return;
1013
+ const permission = `${entity.name.charAt(0).toLowerCase()}${entity.name.slice(1)}:read`;
1014
+ const grant = await call("POST", base + grants.route, { headers: ctx.user({ tenant: a.value, roles: [granter] }), body: { ...payloadFor(grants, 51), ...parentsOf(grants, a), role: NO_ROLE, permission } });
1015
+ if (!t.expect(`[R12] ${n}: the "${granter}" role grants ${permission} to a role`, grant, 200, 201))
1016
+ return;
1017
+ t.expect(`[R12] ${n}: the role can list after the grant`, await call("GET", url, { headers: outsider }), 200);
1018
+ t.expect(`[R12] ${n}: the same role in another tenant still cannot`, await call("GET", url, { headers: ctx.user({ tenant: b.value, roles: [NO_ROLE] }) }), 403);
1019
+ if (entity.permissions.delete && row)
1020
+ t.expect(`[R12] ${n}: the grant adds read only, not delete`, await call("DELETE", `${url}/${row.id}`, { headers: outsider }), 403);
1021
+ await call("DELETE", `${base}${grants.route}/${(_f = grant.json) === null || _f === void 0 ? void 0 : _f.id}`, { headers: ctx.key });
1022
+ t.expect(`[R12] ${n}: the role cannot list once the grant is removed`, await call("GET", url, { headers: outsider }), 403);
1023
+ }
1024
+ async function mcpCases(ctx, a, b, asA) {
1025
+ var _a, _b, _c;
1026
+ const { base, model, t } = ctx;
1027
+ const expected = model.entities.flatMap((e) => Object.values(e.tools)).sort();
1028
+ if (!ctx.mcp || expected.length === 0)
1029
+ return;
1030
+ const rpc = (headers) => fetch(`${base}/mcp`, {
1031
+ method: "POST",
1032
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...headers },
1033
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
1034
+ }).then((r) => r.status, () => 0);
1035
+ if (ctx.user) {
1036
+ t.assert("[R22] mcp: listing tools with no credential is a 401", (await rpc({})) === 401);
1037
+ for (const bad of (_a = ctx.badTokens) !== null && _a !== void 0 ? _a : [])
1038
+ t.assert(`[R22] mcp: ${bad.label} is a 401`, (await rpc(bad.headers)) === 401);
1039
+ }
1040
+ let client;
1041
+ try {
1042
+ client = await ctx.mcp(asA);
1043
+ }
1044
+ catch (error) {
1045
+ t.assert("[R22] mcp: a signed-in caller connects", false, String(error));
1046
+ return;
1047
+ }
1048
+ const listed = await client.listTools();
1049
+ // Every name an entity operation could have as a tool. A tool with another
1050
+ // name is a hand-written route that opted in itself, which the schema does
1051
+ // not describe.
1052
+ const possible = new Set(model.entities.flatMap((e) => {
1053
+ const one = (0, casing_1.snakeCase)(e.name);
1054
+ return [`list_${(0, casing_1.snakeCase)((0, pluralize_1.default)(e.name))}`, ...["get", "create", "update", "delete"].map((op) => `${op}_${one}`)];
1055
+ }));
1056
+ const names = listed.filter((name) => possible.has(name)).sort();
1057
+ t.assert("[R21] mcp: the tools for entity operations are the ones the schema opts in, and no others", JSON.stringify(names) === JSON.stringify(expected), `listed ${names.join(",")}; expected ${expected.join(",")}`);
1058
+ // A list tool loads relations through the same route: refused where REST
1059
+ // refuses, with the same message (a 403 for a relation the caller may not
1060
+ // load, a 400 for a name that is no embeddable relation).
1061
+ for (const entity of model.entities) {
1062
+ if (!entity.tools.list)
1063
+ continue;
1064
+ const embeds = [...entity.relations.map((r) => r.property), ...(postgrestOnly(model) ? ["apso_access_absent"] : [])];
1065
+ for (const property of embeds) {
1066
+ // Python and Go list tools take the nestjsx arguments only, so a relation is loaded there with join.
1067
+ const select = `*,${property}(*)`;
1068
+ const [query, args] = postgrestOnly(model) ? [`select=${enc(select)}`, { select }] : [`join=${enc(property)}`, { join: [property] }];
1069
+ const rest = await call("GET", `${base}${entity.route}?${query}&limit=1000`, { headers: asA });
1070
+ const tool = await client.callTool(entity.tools.list, { ...args, limit: 1000 });
1071
+ const same = rest.status >= 400 ? tool.error !== undefined && messageOf(tool.error) === messageOf(rest.text) : tool.error === undefined;
1072
+ t.assert(`[R7,R23] mcp ${entity.tools.list}: ${postgrestOnly(model) ? "select embed" : "join"} ${property} answers as REST does (${rest.status})`, rest.status !== 0 && rest.status < 500 && same, `REST ${rest.status} ${rest.text.slice(0, 200)}; tool ${(_b = tool.error) !== null && _b !== void 0 ? _b : "ok"}`);
1073
+ if (property === "apso_access_absent")
1074
+ t.assert(`[R7,R23] mcp ${entity.tools.list}: select embed of a name that is no relation is refused, listing the embeddable relations`, notEmbeddable(rest, property) && tool.error !== undefined, `REST ${rest.status} ${rest.text.slice(0, 200)}`);
1075
+ }
1076
+ }
1077
+ for (const entity of model.entities) {
1078
+ const [mine, other] = [a.rows[entity.name], b.rows[entity.name]];
1079
+ if (!entity.scope || !entity.tools.list || !mine || !other)
1080
+ continue;
1081
+ const col = entity.scope.field;
1082
+ const rest = await call("GET", base + entity.route, { headers: asA });
1083
+ const own = typeof ((_c = rest.json) === null || _c === void 0 ? void 0 : _c.total) === "number" ? rest.json.total : rowsOf(rest.json).length;
1084
+ const [m, o] = [String(mine[col]), String(other[col])];
1085
+ const nestjsx = [
1086
+ ["filter names the other tenant", { filter: [`${col}||$eq||${o}`] }],
1087
+ ["filter own tenant, or the other", { filter: [`${col}||$eq||${m}`], or: [`${col}||$eq||${o}`] }],
1088
+ ["two or conditions", { or: [`${col}||$eq||${o}`, `id||$eq||${other.id}`] }],
1089
+ ["s names the other tenant", { s: JSON.stringify({ [col]: other[col] }) }],
1090
+ ["s $or of both tenants", { s: JSON.stringify({ $or: [{ [col]: mine[col] }, { [col]: other[col] }] }) }],
1091
+ ["sort by tenant, a large page", { sort: [`${col},DESC`], limit: 1000 }],
1092
+ ...entity.relations.map((r) => [`join ${r.property}`, { join: [r.property] }]),
1093
+ ];
1094
+ const attempts = [
1095
+ ["no arguments", {}],
1096
+ ...(postgrestOnly(model) ? [] : nestjsx),
1097
+ ["column filter names the other tenant", { [col]: `eq.${o}` }],
1098
+ ["column filter lists both tenants", { [col]: `in.(${m},${o})`, limit: 1000 }],
1099
+ ["column filter excludes the caller's tenant", { [col]: `neq.${m}` }],
1100
+ ["column filter by the other tenant's row id", { id: `eq.${other.id}` }],
1101
+ ["column filter own tenant, or group the other", { [col]: `eq.${m}`, or: `(${col}.eq.${o},id.eq.${other.id})` }],
1102
+ ["or group of both tenants", { or: `(${col}.eq.${m},${col}.eq.${o})` }],
1103
+ ["and group with a nested or", { and: `(or(${col}.eq.${o},id.eq.${other.id}))` }],
1104
+ ["order by tenant, a large page", { order: `${col}.desc`, limit: 1000 }],
1105
+ ...entity.relations.flatMap((r) => [
1106
+ [`select embed ${r.property}`, { select: `*,${r.property}(*)`, limit: 1000 }],
1107
+ [`embedded filter on ${r.property}`, { select: `*,${r.property}(*)`, embedded: { [`${r.property}.id`]: "not.is.null" }, limit: 1000 }],
1108
+ [`embedded filter on an inner embed of ${r.property}`, { select: `id,${r.property}!inner(id)`, embedded: { [`${r.property}.id`]: "not.is.null" }, limit: 1000 }],
1109
+ [`embedded filter on ${r.property} sent as a top-level argument`, { select: `*,${r.property}(*)`, [`${r.property}.id`]: "not.is.null", limit: 1000 }],
1110
+ ]),
1111
+ ];
1112
+ for (const [name, args] of attempts) {
1113
+ const res = await client.callTool(entity.tools.list, args);
1114
+ const problem = res.error === undefined ? widened(model, entity, { status: 200, text: "", json: res.json }, b.rows, own) : "";
1115
+ t.assert(`[R7,R23] mcp ${entity.tools.list}: ${name}`, problem === "", `${JSON.stringify(args)} ${problem}`);
1116
+ }
1117
+ const got = await client.callTool(entity.tools.get, { id: other.id });
1118
+ t.assert(`[R6,R23] mcp ${entity.tools.get}: another tenant's row by id is refused`, got.error !== undefined, JSON.stringify(got.json));
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Run every case the schema calls for against the service at ctx.base.
1123
+ * The service must be running with the API key in ctx.key accepted.
1124
+ * @param {AccessContext} ctx - The service, its schema and how to call it
1125
+ * @returns {Promise<void>} Resolves when the cases have run; results are on ctx.t
1126
+ */
1127
+ async function runAccessCases(ctx) {
1128
+ var _a;
1129
+ const { model } = ctx;
1130
+ await whoIsCalling(ctx);
1131
+ if (postgrestOnly(model))
1132
+ await nestjsxRefused(ctx);
1133
+ for (const s of model.skipped)
1134
+ (_a = ctx.log) === null || _a === void 0 ? void 0 : _a.call(ctx, ` skip ${s.name}: ${s.reason}`);
1135
+ const [a, b] = await seed(ctx);
1136
+ try {
1137
+ if (ctx.user) {
1138
+ const roles = callerRoles(model);
1139
+ const asA = ctx.user({ tenant: a.value, roles });
1140
+ const asB = ctx.user({ tenant: b.value, roles });
1141
+ for (const entity of model.entities) {
1142
+ if (entity.scope && a.rows[entity.name] && b.rows[entity.name])
1143
+ await tenantScope(ctx, entity, a, b, asA);
1144
+ else if (!entity.scope)
1145
+ await joinsFromShared(ctx, entity, b, asA);
1146
+ if (a.rows[entity.name])
1147
+ await relationWrites(ctx, entity, a, b, asA);
1148
+ if (a.rows[entity.name])
1149
+ await foreignKeys(ctx, entity, a, b, asA, asB);
1150
+ }
1151
+ await mcpCases(ctx, a, b, asA);
1152
+ for (const entity of model.entities)
1153
+ await permissions(ctx, entity, a, b);
1154
+ }
1155
+ }
1156
+ finally {
1157
+ for (const tenant of [b, a])
1158
+ for (const entity of [...model.entities].reverse())
1159
+ if (tenant.rows[entity.name])
1160
+ await call("DELETE", `${ctx.base}${entity.route}/${tenant.rows[entity.name].id}`, { headers: ctx.key });
1161
+ }
1162
+ }
1163
+ exports.runAccessCases = runAccessCases;