@zenstackhq/runtime 1.0.0-beta.8 → 1.0.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 (86) hide show
  1. package/browser/index.d.mts +13 -0
  2. package/browser/index.d.ts +13 -0
  3. package/browser/index.js +70 -0
  4. package/browser/index.js.map +1 -0
  5. package/browser/index.mjs +32 -0
  6. package/browser/index.mjs.map +1 -0
  7. package/constants.d.ts +66 -13
  8. package/constants.js +69 -15
  9. package/constants.js.map +1 -1
  10. package/enhancements/enhance.d.ts +18 -0
  11. package/enhancements/enhance.js +42 -0
  12. package/enhancements/enhance.js.map +1 -0
  13. package/enhancements/index.d.ts +5 -0
  14. package/enhancements/index.js +5 -0
  15. package/enhancements/index.js.map +1 -1
  16. package/enhancements/model-data-visitor.d.ts +16 -0
  17. package/enhancements/model-data-visitor.js +41 -0
  18. package/enhancements/model-data-visitor.js.map +1 -0
  19. package/enhancements/model-meta.d.ts +3 -6
  20. package/enhancements/model-meta.js +3 -28
  21. package/enhancements/model-meta.js.map +1 -1
  22. package/enhancements/nested-write-visitor.d.ts +75 -0
  23. package/enhancements/{nested-write-vistor.js → nested-write-visitor.js} +68 -29
  24. package/enhancements/nested-write-visitor.js.map +1 -0
  25. package/enhancements/omit.d.ts +4 -4
  26. package/enhancements/omit.js +2 -1
  27. package/enhancements/omit.js.map +1 -1
  28. package/enhancements/password.d.ts +4 -4
  29. package/enhancements/password.js +4 -4
  30. package/enhancements/password.js.map +1 -1
  31. package/enhancements/policy/handler.d.ts +34 -18
  32. package/enhancements/policy/handler.js +844 -157
  33. package/enhancements/policy/handler.js.map +1 -1
  34. package/enhancements/policy/index.d.ts +4 -4
  35. package/enhancements/policy/index.js +20 -38
  36. package/enhancements/policy/index.js.map +1 -1
  37. package/enhancements/policy/logger.js +1 -1
  38. package/enhancements/policy/logger.js.map +1 -1
  39. package/enhancements/policy/policy-utils.d.ts +106 -48
  40. package/enhancements/policy/policy-utils.js +778 -650
  41. package/enhancements/policy/policy-utils.js.map +1 -1
  42. package/enhancements/policy/promise.d.ts +5 -0
  43. package/enhancements/policy/promise.js +42 -0
  44. package/enhancements/policy/promise.js.map +1 -0
  45. package/enhancements/preset.d.ts +3 -8
  46. package/enhancements/preset.js +2 -4
  47. package/enhancements/preset.js.map +1 -1
  48. package/enhancements/proxy.d.ts +3 -1
  49. package/enhancements/proxy.js +45 -28
  50. package/enhancements/proxy.js.map +1 -1
  51. package/enhancements/types.d.ts +24 -7
  52. package/enhancements/types.js +1 -0
  53. package/enhancements/types.js.map +1 -1
  54. package/enhancements/utils.d.ts +5 -1
  55. package/enhancements/utils.js +62 -12
  56. package/enhancements/utils.js.map +1 -1
  57. package/enhancements/where-visitor.d.ts +33 -0
  58. package/enhancements/where-visitor.js +87 -0
  59. package/enhancements/where-visitor.js.map +1 -0
  60. package/error.js +9 -3
  61. package/error.js.map +1 -1
  62. package/index.d.ts +4 -2
  63. package/index.js +4 -2
  64. package/index.js.map +1 -1
  65. package/loader.d.ts +22 -0
  66. package/loader.js +99 -0
  67. package/loader.js.map +1 -0
  68. package/package.json +33 -7
  69. package/types.d.ts +28 -14
  70. package/types.js +2 -0
  71. package/types.js.map +1 -1
  72. package/validation.d.ts +5 -0
  73. package/validation.js +13 -1
  74. package/validation.js.map +1 -1
  75. package/version.d.ts +5 -0
  76. package/version.js +34 -1
  77. package/version.js.map +1 -1
  78. package/zod/index.d.ts +1 -0
  79. package/zod/index.js +1 -0
  80. package/zod/objects.d.ts +1 -0
  81. package/zod/objects.js +8 -0
  82. package/enhancements/nested-write-vistor.d.ts +0 -71
  83. package/enhancements/nested-write-vistor.js.map +0 -1
  84. package/utils/serialization-utils.d.ts +0 -1
  85. package/utils/serialization-utils.js +0 -22
  86. package/utils/serialization-utils.js.map +0 -1
@@ -14,683 +14,755 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  };
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.PolicyUtil = void 0;
17
- const cuid2_1 = require("@paralleldrive/cuid2");
18
17
  const deepcopy_1 = __importDefault(require("deepcopy"));
19
18
  const lower_case_first_1 = require("lower-case-first");
20
- const pluralize_1 = __importDefault(require("pluralize"));
21
19
  const upper_case_first_1 = require("upper-case-first");
22
20
  const zod_validation_error_1 = require("zod-validation-error");
23
21
  const constants_1 = require("../../constants");
24
22
  const version_1 = require("../../version");
25
23
  const model_meta_1 = require("../model-meta");
26
- const nested_write_vistor_1 = require("../nested-write-vistor");
27
24
  const utils_1 = require("../utils");
28
25
  const logger_1 = require("./logger");
29
26
  /**
30
27
  * Access policy enforcement utilities
31
28
  */
32
29
  class PolicyUtil {
33
- constructor(db, modelMeta, policy, zodSchemas, user, logPrismaQuery) {
30
+ constructor(db, modelMeta, policy, zodSchemas, user, shouldLogQuery = false) {
34
31
  this.db = db;
35
32
  this.modelMeta = modelMeta;
36
33
  this.policy = policy;
37
34
  this.zodSchemas = zodSchemas;
38
35
  this.user = user;
39
- this.logPrismaQuery = logPrismaQuery;
36
+ this.shouldLogQuery = shouldLogQuery;
40
37
  this.logger = new logger_1.Logger(db);
41
38
  }
39
+ //#region Logical operators
42
40
  /**
43
41
  * Creates a conjunction of a list of query conditions.
44
42
  */
45
43
  and(...conditions) {
46
- if (conditions.includes(false)) {
47
- // always false
48
- return { [constants_1.GUARD_FIELD_NAME]: false };
49
- }
50
- const filtered = conditions.filter((c) => typeof c === 'object' && !!c && Object.keys(c).length > 0);
44
+ const filtered = conditions.filter((c) => c !== undefined);
51
45
  if (filtered.length === 0) {
52
- return undefined;
46
+ return this.makeTrue();
53
47
  }
54
48
  else if (filtered.length === 1) {
55
- return filtered[0];
49
+ return this.reduce(filtered[0]);
56
50
  }
57
51
  else {
58
- return { AND: filtered };
52
+ return this.reduce({ AND: filtered });
59
53
  }
60
54
  }
61
55
  /**
62
56
  * Creates a disjunction of a list of query conditions.
63
57
  */
64
58
  or(...conditions) {
65
- if (conditions.includes(true)) {
66
- // always true
67
- return { [constants_1.GUARD_FIELD_NAME]: true };
68
- }
69
- const filtered = conditions.filter((c) => typeof c === 'object' && !!c);
59
+ const filtered = conditions.filter((c) => c !== undefined);
70
60
  if (filtered.length === 0) {
71
- return undefined;
61
+ return this.makeFalse();
72
62
  }
73
63
  else if (filtered.length === 1) {
74
- return filtered[0];
64
+ return this.reduce(filtered[0]);
75
65
  }
76
66
  else {
77
- return { OR: filtered };
67
+ return this.reduce({ OR: filtered });
78
68
  }
79
69
  }
80
70
  /**
81
71
  * Creates a negation of a query condition.
82
72
  */
83
73
  not(condition) {
84
- if (typeof condition === 'boolean') {
85
- return !condition;
74
+ if (condition === undefined) {
75
+ return this.makeTrue();
76
+ }
77
+ else if (typeof condition === 'boolean') {
78
+ return this.reduce(!condition);
79
+ }
80
+ else {
81
+ return this.reduce({ NOT: condition });
82
+ }
83
+ }
84
+ // Static True/False conditions
85
+ // https://www.prisma.io/docs/concepts/components/prisma-client/null-and-undefined#the-effect-of-null-and-undefined-on-conditionals
86
+ isTrue(condition) {
87
+ if (condition === null || condition === undefined) {
88
+ return false;
89
+ }
90
+ else {
91
+ return ((typeof condition === 'object' && Object.keys(condition).length === 0) ||
92
+ ('AND' in condition && Array.isArray(condition.AND) && condition.AND.length === 0));
93
+ }
94
+ }
95
+ isFalse(condition) {
96
+ if (condition === null || condition === undefined) {
97
+ return false;
86
98
  }
87
99
  else {
88
- return { NOT: condition };
100
+ return 'OR' in condition && Array.isArray(condition.OR) && condition.OR.length === 0;
101
+ }
102
+ }
103
+ makeTrue() {
104
+ return { AND: [] };
105
+ }
106
+ makeFalse() {
107
+ return { OR: [] };
108
+ }
109
+ reduce(condition) {
110
+ if (condition === true || condition === undefined) {
111
+ return this.makeTrue();
112
+ }
113
+ if (condition === false) {
114
+ return this.makeFalse();
115
+ }
116
+ if (condition === null) {
117
+ return condition;
118
+ }
119
+ const result = {};
120
+ for (const [key, value] of Object.entries(condition)) {
121
+ if (value === null || value === undefined) {
122
+ result[key] = value;
123
+ continue;
124
+ }
125
+ switch (key) {
126
+ case 'AND': {
127
+ const children = (0, utils_1.enumerate)(value)
128
+ .map((c) => this.reduce(c))
129
+ .filter((c) => c !== undefined && !this.isTrue(c));
130
+ if (children.length === 0) {
131
+ result[key] = []; // true
132
+ }
133
+ else if (children.some((c) => this.isFalse(c))) {
134
+ result['OR'] = []; // false
135
+ }
136
+ else {
137
+ if (!this.isTrue({ AND: result[key] })) {
138
+ // use AND only if it's not already true
139
+ result[key] = !Array.isArray(value) && children.length === 1 ? children[0] : children;
140
+ }
141
+ }
142
+ break;
143
+ }
144
+ case 'OR': {
145
+ const children = (0, utils_1.enumerate)(value)
146
+ .map((c) => this.reduce(c))
147
+ .filter((c) => c !== undefined && !this.isFalse(c));
148
+ if (children.length === 0) {
149
+ result[key] = []; // false
150
+ }
151
+ else if (children.some((c) => this.isTrue(c))) {
152
+ result['AND'] = []; // true
153
+ }
154
+ else {
155
+ if (!this.isFalse({ OR: result[key] })) {
156
+ // use OR only if it's not already false
157
+ result[key] = !Array.isArray(value) && children.length === 1 ? children[0] : children;
158
+ }
159
+ }
160
+ break;
161
+ }
162
+ case 'NOT': {
163
+ result[key] = this.reduce(value);
164
+ break;
165
+ }
166
+ default: {
167
+ const booleanKeys = ['AND', 'OR', 'NOT', 'is', 'isNot', 'none', 'every', 'some'];
168
+ if (typeof value === 'object' &&
169
+ value &&
170
+ // recurse only if the value has at least one boolean key
171
+ Object.keys(value).some((k) => booleanKeys.includes(k))) {
172
+ result[key] = this.reduce(value);
173
+ }
174
+ else {
175
+ result[key] = value;
176
+ }
177
+ break;
178
+ }
179
+ }
89
180
  }
181
+ return result;
90
182
  }
183
+ //#endregion
184
+ //# Auth guard
91
185
  /**
92
186
  * Gets pregenerated authorization guard object for a given model and operation.
93
187
  *
94
188
  * @returns true if operation is unconditionally allowed, false if unconditionally denied,
95
189
  * otherwise returns a guard object
96
190
  */
97
- getAuthGuard(model, operation, preValue) {
191
+ getAuthGuard(db, model, operation, preValue) {
98
192
  const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
99
193
  if (!guard) {
100
194
  throw this.unknownError(`unable to load policy guard for ${model}`);
101
195
  }
102
196
  const provider = guard[operation];
103
197
  if (typeof provider === 'boolean') {
104
- return provider;
198
+ return this.reduce(provider);
105
199
  }
106
200
  if (!provider) {
107
201
  throw this.unknownError(`zenstack: unable to load authorization guard for ${model}`);
108
202
  }
109
- return provider({ user: this.user, preValue });
203
+ const r = provider({ user: this.user, preValue }, db);
204
+ return this.reduce(r);
110
205
  }
111
- hasValidation(model) {
112
- var _a, _b;
113
- return ((_b = (_a = this.policy.validation) === null || _a === void 0 ? void 0 : _a[(0, lower_case_first_1.lowerCaseFirst)(model)]) === null || _b === void 0 ? void 0 : _b.hasValidation) === true;
206
+ /**
207
+ * Get field-level auth guard
208
+ */
209
+ getFieldUpdateAuthGuard(db, model, field) {
210
+ const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
211
+ if (!guard) {
212
+ throw this.unknownError(`unable to load policy guard for ${model}`);
213
+ }
214
+ const provider = guard[`${constants_1.FIELD_LEVEL_UPDATE_GUARD_PREFIX}${field}`];
215
+ if (typeof provider === 'boolean') {
216
+ return this.reduce(provider);
217
+ }
218
+ if (!provider) {
219
+ return this.makeTrue();
220
+ }
221
+ const r = provider({ user: this.user }, db);
222
+ return this.reduce(r);
114
223
  }
115
- getPreValueSelect(model) {
116
- return __awaiter(this, void 0, void 0, function* () {
117
- const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
118
- if (!guard) {
119
- throw this.unknownError(`unable to load policy guard for ${model}`);
120
- }
121
- return guard.preValueSelect;
122
- });
224
+ /**
225
+ * Checks if the given model has a policy guard for the given operation.
226
+ */
227
+ hasAuthGuard(model, operation) {
228
+ const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
229
+ if (!guard) {
230
+ return false;
231
+ }
232
+ const provider = guard[operation];
233
+ return typeof provider !== 'boolean' || provider !== true;
123
234
  }
124
- getModelSchema(model) {
125
- var _a, _b;
126
- return this.hasValidation(model) && ((_b = (_a = this.zodSchemas) === null || _a === void 0 ? void 0 : _a.models) === null || _b === void 0 ? void 0 : _b[`${(0, upper_case_first_1.upperCaseFirst)(model)}Schema`]);
235
+ /**
236
+ * Checks model creation policy based on static analysis to the input args.
237
+ *
238
+ * @returns boolean if static analysis is enough to determine the result, undefined if not
239
+ */
240
+ checkInputGuard(model, args, operation) {
241
+ const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
242
+ if (!guard) {
243
+ return undefined;
244
+ }
245
+ const provider = guard[`${operation}_input`];
246
+ if (typeof provider === 'boolean') {
247
+ return provider;
248
+ }
249
+ if (!provider) {
250
+ return undefined;
251
+ }
252
+ return provider(args, { user: this.user });
127
253
  }
128
254
  /**
129
255
  * Injects model auth guard as where clause.
130
256
  */
131
- injectAuthGuard(args, model, operation) {
132
- return __awaiter(this, void 0, void 0, function* () {
133
- if (args.where) {
134
- // inject into relation fields:
135
- // to-many: some/none/every
136
- // to-one: direct-conditions/is/isNot
137
- yield this.injectGuardForFields(model, args.where, operation);
138
- }
139
- const guard = this.getAuthGuard(model, operation);
140
- args.where = this.and(args.where, guard);
141
- });
257
+ injectAuthGuard(db, args, model, operation) {
258
+ let guard = this.getAuthGuard(db, model, operation);
259
+ if (this.isFalse(guard)) {
260
+ args.where = this.makeFalse();
261
+ return false;
262
+ }
263
+ if (operation === 'update' && args) {
264
+ // merge field-level policy guards
265
+ const fieldUpdateGuard = this.getFieldUpdateGuards(db, model, args);
266
+ if (fieldUpdateGuard.rejectedByField) {
267
+ // rejected
268
+ args.where = this.makeFalse();
269
+ return false;
270
+ }
271
+ else if (fieldUpdateGuard.guard) {
272
+ // merge
273
+ guard = this.and(guard, fieldUpdateGuard.guard);
274
+ }
275
+ }
276
+ if (args.where) {
277
+ // inject into relation fields:
278
+ // to-many: some/none/every
279
+ // to-one: direct-conditions/is/isNot
280
+ this.injectGuardForRelationFields(db, model, args.where, operation);
281
+ }
282
+ args.where = this.and(args.where, guard);
283
+ return true;
142
284
  }
143
- injectGuardForFields(model, payload, operation) {
144
- return __awaiter(this, void 0, void 0, function* () {
145
- for (const [field, subPayload] of Object.entries(payload)) {
146
- if (!subPayload) {
147
- continue;
148
- }
149
- const fieldInfo = yield (0, model_meta_1.resolveField)(this.modelMeta, model, field);
150
- if (!fieldInfo || !fieldInfo.isDataModel) {
151
- continue;
152
- }
153
- if (fieldInfo.isArray) {
154
- yield this.injectGuardForToManyField(fieldInfo, subPayload, operation);
155
- }
156
- else {
157
- yield this.injectGuardForToOneField(fieldInfo, subPayload, operation);
158
- }
285
+ injectGuardForRelationFields(db, model, payload, operation) {
286
+ for (const [field, subPayload] of Object.entries(payload)) {
287
+ if (!subPayload) {
288
+ continue;
159
289
  }
160
- });
290
+ const fieldInfo = (0, model_meta_1.resolveField)(this.modelMeta, model, field);
291
+ if (!fieldInfo || !fieldInfo.isDataModel) {
292
+ continue;
293
+ }
294
+ if (fieldInfo.isArray) {
295
+ this.injectGuardForToManyField(db, fieldInfo, subPayload, operation);
296
+ }
297
+ else {
298
+ this.injectGuardForToOneField(db, fieldInfo, subPayload, operation);
299
+ }
300
+ }
161
301
  }
162
- injectGuardForToManyField(fieldInfo, payload, operation) {
163
- return __awaiter(this, void 0, void 0, function* () {
164
- const guard = this.getAuthGuard(fieldInfo.type, operation);
165
- if (payload.some) {
166
- yield this.injectGuardForFields(fieldInfo.type, payload.some, operation);
167
- // turn "some" into: { some: { AND: [guard, payload.some] } }
168
- payload.some = this.and(payload.some, guard);
169
- }
170
- if (payload.none) {
171
- yield this.injectGuardForFields(fieldInfo.type, payload.none, operation);
172
- // turn none into: { none: { AND: [guard, payload.none] } }
173
- payload.none = this.and(payload.none, guard);
174
- }
175
- if (payload.every &&
176
- typeof payload.every === 'object' &&
177
- // ignore empty every clause
178
- Object.keys(payload.every).length > 0) {
179
- yield this.injectGuardForFields(fieldInfo.type, payload.every, operation);
180
- // turn "every" into: { none: { AND: [guard, { NOT: payload.every }] } }
181
- if (!payload.none) {
182
- payload.none = {};
183
- }
184
- payload.none = this.and(payload.none, guard, this.not(payload.every));
185
- delete payload.every;
302
+ injectGuardForToManyField(db, fieldInfo, payload, operation) {
303
+ const guard = this.getAuthGuard(db, fieldInfo.type, operation);
304
+ if (payload.some) {
305
+ this.injectGuardForRelationFields(db, fieldInfo.type, payload.some, operation);
306
+ // turn "some" into: { some: { AND: [guard, payload.some] } }
307
+ payload.some = this.and(payload.some, guard);
308
+ }
309
+ if (payload.none) {
310
+ this.injectGuardForRelationFields(db, fieldInfo.type, payload.none, operation);
311
+ // turn none into: { none: { AND: [guard, payload.none] } }
312
+ payload.none = this.and(payload.none, guard);
313
+ }
314
+ if (payload.every &&
315
+ typeof payload.every === 'object' &&
316
+ // ignore empty every clause
317
+ Object.keys(payload.every).length > 0) {
318
+ this.injectGuardForRelationFields(db, fieldInfo.type, payload.every, operation);
319
+ // turn "every" into: { none: { AND: [guard, { NOT: payload.every }] } }
320
+ if (!payload.none) {
321
+ payload.none = {};
186
322
  }
187
- });
323
+ payload.none = this.and(payload.none, guard, this.not(payload.every));
324
+ delete payload.every;
325
+ }
188
326
  }
189
- injectGuardForToOneField(fieldInfo, payload, operation) {
190
- return __awaiter(this, void 0, void 0, function* () {
191
- const guard = this.getAuthGuard(fieldInfo.type, operation);
192
- if (payload.is || payload.isNot) {
193
- if (payload.is) {
194
- yield this.injectGuardForFields(fieldInfo.type, payload.is, operation);
195
- // turn "is" into: { is: { AND: [ originalIs, guard ] }
196
- payload.is = this.and(payload.is, guard);
197
- }
198
- if (payload.isNot) {
199
- yield this.injectGuardForFields(fieldInfo.type, payload.isNot, operation);
200
- // turn "isNot" into: { isNot: { AND: [ originalIsNot, { NOT: guard } ] } }
201
- payload.isNot = this.and(payload.isNot, this.not(guard));
202
- delete payload.isNot;
203
- }
327
+ injectGuardForToOneField(db, fieldInfo, payload, operation) {
328
+ const guard = this.getAuthGuard(db, fieldInfo.type, operation);
329
+ // is|isNot and flat fields conditions are mutually exclusive
330
+ if (payload.is || payload.isNot) {
331
+ if (payload.is) {
332
+ this.injectGuardForRelationFields(db, fieldInfo.type, payload.is, operation);
204
333
  }
205
- else {
206
- yield this.injectGuardForFields(fieldInfo.type, payload, operation);
207
- // turn direct conditions into: { is: { AND: [ originalConditions, guard ] } }
208
- const combined = this.and((0, deepcopy_1.default)(payload), guard);
209
- Object.keys(payload).forEach((key) => delete payload[key]);
210
- payload.is = combined;
334
+ if (payload.isNot) {
335
+ this.injectGuardForRelationFields(db, fieldInfo.type, payload.isNot, operation);
211
336
  }
212
- });
337
+ // merge guard with existing "is": { is: [originalIs, guard] }
338
+ payload.is = this.and(payload.is, guard);
339
+ }
340
+ else {
341
+ this.injectGuardForRelationFields(db, fieldInfo.type, payload, operation);
342
+ // turn direct conditions into: { is: { AND: [ originalConditions, guard ] } }
343
+ const combined = this.and((0, deepcopy_1.default)(payload), guard);
344
+ Object.keys(payload).forEach((key) => delete payload[key]);
345
+ payload.is = combined;
346
+ }
213
347
  }
214
348
  /**
215
- * Read model entities w.r.t the given query args. The result list
216
- * are guaranteed to fully satisfy 'read' policy rules recursively.
217
- *
218
- * For to-many relations involved, items not satisfying policy are
219
- * silently trimmed. For to-one relation, if relation data fails policy
220
- * an error is thrown.
349
+ * Injects auth guard for read operations.
221
350
  */
222
- readWithCheck(model, args) {
223
- return __awaiter(this, void 0, void 0, function* () {
224
- args = this.clone(args);
225
- if (args.where) {
226
- // query args will be used with findMany, so we need to
227
- // translate unique constraint filters into a flat filter
228
- // e.g.: { a_b: { a: '1', b: '1' } } => { a: '1', b: '1' }
229
- yield this.flattenGeneratedUniqueField(model, args.where);
230
- }
231
- yield this.injectAuthGuard(args, model, 'read');
232
- // recursively inject read guard conditions into the query args
233
- yield this.injectNestedReadConditions(model, args);
234
- if (this.shouldLogQuery) {
235
- this.logger.info(`[withPolicy] \`findMany\`:\n${(0, utils_1.formatObject)(args)}`);
351
+ injectForRead(db, model, args) {
352
+ const injected = {};
353
+ if (!this.injectAuthGuard(db, injected, model, 'read')) {
354
+ return false;
355
+ }
356
+ if (args.where) {
357
+ // inject into relation fields:
358
+ // to-many: some/none/every
359
+ // to-one: direct-conditions/is/isNot
360
+ this.injectGuardForRelationFields(db, model, args.where, 'read');
361
+ }
362
+ if (injected.where && Object.keys(injected.where).length > 0 && !this.isTrue(injected.where)) {
363
+ if (!args.where) {
364
+ args.where = injected.where;
236
365
  }
237
- const result = yield this.db[model].findMany(args);
238
- yield this.postProcessForRead(result, model, args, 'read');
239
- return result;
240
- });
366
+ else {
367
+ this.mergeWhereClause(args.where, injected.where);
368
+ }
369
+ }
370
+ // recursively inject read guard conditions into nested select, include, and _count
371
+ const hoistedConditions = this.injectNestedReadConditions(db, model, args);
372
+ // the injection process may generate conditions that need to be hoisted to the toplevel,
373
+ // if so, merge it with the existing where
374
+ if (hoistedConditions.length > 0) {
375
+ if (!args.where) {
376
+ args.where = this.and(...hoistedConditions);
377
+ }
378
+ else {
379
+ this.mergeWhereClause(args.where, this.and(...hoistedConditions));
380
+ }
381
+ }
382
+ return true;
241
383
  }
242
384
  // flatten unique constraint filters
243
385
  flattenGeneratedUniqueField(model, args) {
244
386
  var _a;
245
- return __awaiter(this, void 0, void 0, function* () {
246
- // e.g.: { a_b: { a: '1', b: '1' } } => { a: '1', b: '1' }
247
- const uniqueConstraints = (_a = this.modelMeta.uniqueConstraints) === null || _a === void 0 ? void 0 : _a[(0, lower_case_first_1.lowerCaseFirst)(model)];
248
- let flattened = false;
249
- if (uniqueConstraints && Object.keys(uniqueConstraints).length > 0) {
250
- for (const [field, value] of Object.entries(args)) {
251
- if (uniqueConstraints[field] && typeof value === 'object') {
252
- for (const [f, v] of Object.entries(value)) {
253
- args[f] = v;
254
- }
255
- delete args[field];
256
- flattened = true;
387
+ // e.g.: { a_b: { a: '1', b: '1' } } => { a: '1', b: '1' }
388
+ const uniqueConstraints = (_a = this.modelMeta.uniqueConstraints) === null || _a === void 0 ? void 0 : _a[(0, lower_case_first_1.lowerCaseFirst)(model)];
389
+ if (uniqueConstraints && Object.keys(uniqueConstraints).length > 0) {
390
+ for (const [field, value] of Object.entries(args)) {
391
+ if (uniqueConstraints[field] &&
392
+ uniqueConstraints[field].fields.length > 1 &&
393
+ typeof value === 'object') {
394
+ // multi-field unique constraint, flatten it
395
+ delete args[field];
396
+ for (const [f, v] of Object.entries(value)) {
397
+ args[f] = v;
257
398
  }
258
399
  }
259
400
  }
260
- if (flattened) {
261
- // DEBUG
262
- // this.logger.info(`Filter flattened: ${JSON.stringify(args)}`);
263
- }
264
- });
401
+ }
265
402
  }
266
- injectNestedReadConditions(model, args) {
403
+ /**
404
+ * Gets unique constraints for the given model.
405
+ */
406
+ getUniqueConstraints(model) {
267
407
  var _a, _b;
268
- return __awaiter(this, void 0, void 0, function* () {
269
- const injectTarget = (_a = args.select) !== null && _a !== void 0 ? _a : args.include;
270
- if (!injectTarget) {
271
- return;
408
+ return (_b = (_a = this.modelMeta.uniqueConstraints) === null || _a === void 0 ? void 0 : _a[(0, lower_case_first_1.lowerCaseFirst)(model)]) !== null && _b !== void 0 ? _b : {};
409
+ }
410
+ /**
411
+ * Builds a reversed query for the given nested path.
412
+ */
413
+ buildReversedQuery(context, mutating = false, unsafeOperation = false) {
414
+ let result, currQuery;
415
+ let currField;
416
+ for (let i = context.nestingPath.length - 1; i >= 0; i--) {
417
+ const { field, model, where } = context.nestingPath[i];
418
+ // never modify the original where because it's shared in the structure
419
+ const visitWhere = Object.assign({}, where);
420
+ if (model && where) {
421
+ // make sure composite unique condition is flattened
422
+ this.flattenGeneratedUniqueField(model, visitWhere);
272
423
  }
273
- if (injectTarget._count !== undefined) {
274
- // _count needs to respect read policies of related models
275
- if (injectTarget._count === true) {
276
- // include count for all relations, expand to all fields
277
- // so that we can inject guard conditions for each of them
278
- injectTarget._count = { select: {} };
279
- const modelFields = (0, model_meta_1.getFields)(this.modelMeta, model);
280
- if (modelFields) {
281
- for (const [k, v] of Object.entries(modelFields)) {
282
- if (v.isDataModel && v.isArray) {
283
- // create an entry for to-many relation
284
- injectTarget._count.select[k] = {};
285
- }
424
+ if (!result) {
425
+ // first segment (bottom), just use its where clause
426
+ result = currQuery = Object.assign({}, visitWhere);
427
+ currField = field;
428
+ }
429
+ else {
430
+ if (!currField) {
431
+ throw this.unknownError(`missing field in nested path`);
432
+ }
433
+ if (!currField.backLink) {
434
+ throw this.unknownError(`field ${currField.type}.${currField.name} doesn't have a backLink`);
435
+ }
436
+ const backLinkField = this.getModelField(currField.type, currField.backLink);
437
+ if (!backLinkField) {
438
+ throw this.unknownError(`missing backLink field ${currField.backLink} in ${currField.type}`);
439
+ }
440
+ if (backLinkField.isArray) {
441
+ // many-side of relationship, wrap with "some" query
442
+ currQuery[currField.backLink] = { some: Object.assign({}, visitWhere) };
443
+ }
444
+ else {
445
+ const fkMapping = where && backLinkField.isRelationOwner && backLinkField.foreignKeyMapping;
446
+ // calculate if we should preserve the relation condition (e.g., { user: { id: 1 } })
447
+ const shouldPreserveRelationCondition =
448
+ // doing a mutation
449
+ mutating &&
450
+ // and it's a safe mutate
451
+ !unsafeOperation &&
452
+ // and the current segment is the direct parent (the last one is the mutate itself),
453
+ // the relation condition should be preserved and will be converted to a "connect" later
454
+ i === context.nestingPath.length - 2;
455
+ if (fkMapping && !shouldPreserveRelationCondition) {
456
+ // turn relation condition into foreign key condition, e.g.:
457
+ // { user: { id: 1 } } => { userId: 1 }
458
+ for (const [r, fk] of Object.entries(fkMapping)) {
459
+ currQuery[fk] = visitWhere[r];
460
+ }
461
+ if (i > 0) {
462
+ // prepare for the next segment
463
+ currQuery[currField.backLink] = {};
286
464
  }
287
465
  }
288
- }
289
- // inject conditions for each relation
290
- for (const field of Object.keys(injectTarget._count.select)) {
291
- if (typeof injectTarget._count.select[field] !== 'object') {
292
- injectTarget._count.select[field] = {};
466
+ else {
467
+ // preserve the original structure
468
+ currQuery[currField.backLink] = Object.assign({}, visitWhere);
293
469
  }
294
- const fieldInfo = (0, model_meta_1.resolveField)(this.modelMeta, model, field);
295
- if (!fieldInfo) {
296
- continue;
470
+ }
471
+ currQuery = currQuery[currField.backLink];
472
+ currField = field;
473
+ }
474
+ }
475
+ return result;
476
+ }
477
+ injectNestedReadConditions(db, model, args) {
478
+ var _a;
479
+ const injectTarget = (_a = args.select) !== null && _a !== void 0 ? _a : args.include;
480
+ if (!injectTarget) {
481
+ return [];
482
+ }
483
+ if (injectTarget._count !== undefined) {
484
+ // _count needs to respect read policies of related models
485
+ if (injectTarget._count === true) {
486
+ // include count for all relations, expand to all fields
487
+ // so that we can inject guard conditions for each of them
488
+ injectTarget._count = { select: {} };
489
+ const modelFields = (0, model_meta_1.getFields)(this.modelMeta, model);
490
+ if (modelFields) {
491
+ for (const [k, v] of Object.entries(modelFields)) {
492
+ if (v.isDataModel && v.isArray) {
493
+ // create an entry for to-many relation
494
+ injectTarget._count.select[k] = {};
495
+ }
297
496
  }
298
- // inject into the "where" clause inside select
299
- yield this.injectAuthGuard(injectTarget._count.select[field], fieldInfo.type, 'read');
300
497
  }
301
498
  }
302
- const idFields = this.getIdFields(model);
303
- for (const field of (0, utils_1.getModelFields)(injectTarget)) {
499
+ // inject conditions for each relation
500
+ for (const field of Object.keys(injectTarget._count.select)) {
501
+ if (typeof injectTarget._count.select[field] !== 'object') {
502
+ injectTarget._count.select[field] = {};
503
+ }
304
504
  const fieldInfo = (0, model_meta_1.resolveField)(this.modelMeta, model, field);
305
- if (!fieldInfo || !fieldInfo.isDataModel) {
306
- // only care about relation fields
505
+ if (!fieldInfo) {
307
506
  continue;
308
507
  }
309
- if (fieldInfo.isArray) {
310
- if (typeof injectTarget[field] !== 'object') {
311
- injectTarget[field] = {};
312
- }
313
- // inject extra condition for to-many relation
314
- yield this.injectAuthGuard(injectTarget[field], fieldInfo.type, 'read');
315
- }
316
- else {
317
- // there's no way of injecting condition for to-one relation, so if there's
318
- // "select" clause we make sure 'id' fields are selected and check them against
319
- // query result; nothing needs to be done for "include" clause because all
320
- // fields are already selected
321
- if ((_b = injectTarget[field]) === null || _b === void 0 ? void 0 : _b.select) {
322
- for (const idField of idFields) {
323
- if (injectTarget[field].select[idField.name] !== true) {
324
- injectTarget[field].select[idField.name] = true;
325
- }
326
- }
327
- }
508
+ // inject into the "where" clause inside select
509
+ this.injectAuthGuard(db, injectTarget._count.select[field], fieldInfo.type, 'read');
510
+ }
511
+ }
512
+ // collect filter conditions that should be hoisted to the toplevel
513
+ const hoistedConditions = [];
514
+ for (const field of (0, utils_1.getModelFields)(injectTarget)) {
515
+ const fieldInfo = (0, model_meta_1.resolveField)(this.modelMeta, model, field);
516
+ if (!fieldInfo || !fieldInfo.isDataModel) {
517
+ // only care about relation fields
518
+ continue;
519
+ }
520
+ let hoisted;
521
+ if (fieldInfo.isArray ||
522
+ // Injecting where at include/select level for nullable to-one relation is supported since Prisma 4.8.0
523
+ // https://github.com/prisma/prisma/discussions/20350
524
+ fieldInfo.isOptional) {
525
+ if (typeof injectTarget[field] !== 'object') {
526
+ injectTarget[field] = {};
527
+ }
528
+ // inject extra condition for to-many or nullable to-one relation
529
+ this.injectAuthGuard(db, injectTarget[field], fieldInfo.type, 'read');
530
+ // recurse
531
+ const subHoisted = this.injectNestedReadConditions(db, fieldInfo.type, injectTarget[field]);
532
+ if (subHoisted.length > 0) {
533
+ // we can convert it to a where at this level
534
+ injectTarget[field].where = this.and(injectTarget[field].where, ...subHoisted);
328
535
  }
536
+ }
537
+ else {
538
+ // hoist non-nullable to-one filter to the parent level
539
+ hoisted = this.getAuthGuard(db, fieldInfo.type, 'read');
329
540
  // recurse
330
- yield this.injectNestedReadConditions(fieldInfo.type, injectTarget[field]);
541
+ const subHoisted = this.injectNestedReadConditions(db, fieldInfo.type, injectTarget[field]);
542
+ if (subHoisted.length > 0) {
543
+ hoisted = this.and(hoisted, ...subHoisted);
544
+ }
331
545
  }
332
- });
546
+ if (hoisted && !this.isTrue(hoisted)) {
547
+ hoistedConditions.push({ [field]: hoisted });
548
+ }
549
+ }
550
+ return hoistedConditions;
333
551
  }
334
552
  /**
335
- * Post processing checks for read model entities. Validates to-one relations
336
- * (which can't be trimmed at query time) and removes fields that should be
337
- * omitted.
553
+ * Given a model and a unique filter, checks the operation is allowed by policies and field validations.
554
+ * Rejects with an error if not allowed.
338
555
  */
339
- postProcessForRead(data, model, args, operation) {
340
- var _a;
556
+ checkPolicyForUnique(model, uniqueFilter, operation, db, args, preValue) {
341
557
  return __awaiter(this, void 0, void 0, function* () {
342
- for (const entityData of (0, utils_1.enumerate)(data)) {
343
- if (typeof entityData !== 'object' || !entityData) {
344
- continue;
345
- }
346
- // strip auxiliary fields
347
- for (const auxField of constants_1.AUXILIARY_FIELDS) {
348
- if (auxField in entityData) {
349
- delete entityData[auxField];
350
- }
558
+ let guard = this.getAuthGuard(db, model, operation, preValue);
559
+ if (this.isFalse(guard)) {
560
+ throw this.deniedByPolicy(model, operation, `entity ${(0, utils_1.formatObject)(uniqueFilter)} failed policy check`, constants_1.CrudFailureReason.ACCESS_POLICY_VIOLATION);
561
+ }
562
+ if (operation === 'update' && args) {
563
+ // merge field-level policy guards
564
+ const fieldUpdateGuard = this.getFieldUpdateGuards(db, model, args);
565
+ if (fieldUpdateGuard.rejectedByField) {
566
+ // rejected
567
+ throw this.deniedByPolicy(model, 'update', `entity ${(0, utils_1.formatObject)(uniqueFilter)} failed update policy check for field "${fieldUpdateGuard.rejectedByField}"`, constants_1.CrudFailureReason.ACCESS_POLICY_VIOLATION);
351
568
  }
352
- const injectTarget = (_a = args.select) !== null && _a !== void 0 ? _a : args.include;
353
- if (!injectTarget) {
354
- continue;
569
+ else if (fieldUpdateGuard.guard) {
570
+ // merge
571
+ guard = this.and(guard, fieldUpdateGuard.guard);
355
572
  }
356
- // recurse into nested entities
357
- for (const field of Object.keys(injectTarget)) {
358
- const fieldData = entityData[field];
359
- if (typeof fieldData !== 'object' || !fieldData) {
360
- continue;
361
- }
362
- const fieldInfo = (0, model_meta_1.resolveField)(this.modelMeta, model, field);
363
- if (fieldInfo) {
364
- if (fieldInfo.isDataModel && !fieldInfo.isArray) {
365
- // to-one relation data cannot be trimmed by injected guards, we have to
366
- // post-check them
367
- const ids = this.getEntityIds(fieldInfo.type, fieldData);
368
- if (Object.keys(ids).length !== 0) {
369
- // if (this.logger.enabled('info')) {
370
- // this.logger.info(
371
- // `Validating read of to-one relation: ${fieldInfo.type}#${formatObject(ids)}`
372
- // );
373
- // }
374
- yield this.checkPolicyForFilter(fieldInfo.type, ids, operation, this.db);
375
- }
376
- }
377
- // recurse
378
- yield this.postProcessForRead(fieldData, fieldInfo.type, injectTarget[field], operation);
573
+ }
574
+ // Zod schema is to be checked for "create" and "postUpdate"
575
+ const schema = ['create', 'postUpdate'].includes(operation) ? this.getZodSchema(model) : undefined;
576
+ if (this.isTrue(guard) && !schema) {
577
+ // unconditionally allowed
578
+ return;
579
+ }
580
+ const select = schema
581
+ ? // need to validate against schema, need to fetch all fields
582
+ undefined
583
+ : // only fetch id fields
584
+ this.makeIdSelection(model);
585
+ let where = this.clone(uniqueFilter);
586
+ // query args may have be of combined-id form, need to flatten it to call findFirst
587
+ this.flattenGeneratedUniqueField(model, where);
588
+ // query with policy guard
589
+ where = this.and(where, guard);
590
+ const query = { select, where };
591
+ if (this.shouldLogQuery) {
592
+ this.logger.info(`[policy] checking ${model} for ${operation}, \`findFirst\`:\n${(0, utils_1.formatObject)(query)}`);
593
+ }
594
+ const result = yield db[model].findFirst(query);
595
+ if (!result) {
596
+ throw this.deniedByPolicy(model, operation, `entity ${(0, utils_1.formatObject)(uniqueFilter)} failed policy check`, constants_1.CrudFailureReason.ACCESS_POLICY_VIOLATION);
597
+ }
598
+ if (schema) {
599
+ // TODO: push down schema check to the database
600
+ const parseResult = schema.safeParse(result);
601
+ if (!parseResult.success) {
602
+ const error = (0, zod_validation_error_1.fromZodError)(parseResult.error);
603
+ if (this.logger.enabled('info')) {
604
+ this.logger.info(`entity ${model} failed validation for operation ${operation}: ${error}`);
379
605
  }
606
+ throw this.deniedByPolicy(model, operation, `entities ${JSON.stringify(uniqueFilter)} failed validation: [${error}]`, constants_1.CrudFailureReason.DATA_VALIDATION_VIOLATION, parseResult.error);
380
607
  }
381
608
  }
382
609
  });
383
610
  }
611
+ getFieldUpdateGuards(db, model, args) {
612
+ var _a;
613
+ const allFieldGuards = [];
614
+ for (const [k, v] of Object.entries((_a = args.data) !== null && _a !== void 0 ? _a : args)) {
615
+ if (typeof v === 'undefined') {
616
+ continue;
617
+ }
618
+ const fieldGuard = this.getFieldUpdateAuthGuard(db, model, k);
619
+ if (this.isFalse(fieldGuard)) {
620
+ return { guard: allFieldGuards, rejectedByField: k };
621
+ }
622
+ allFieldGuards.push(fieldGuard);
623
+ }
624
+ return { guard: this.and(...allFieldGuards), rejectedByField: undefined };
625
+ }
384
626
  /**
385
- * Process Prisma write actions.
627
+ * Tries rejecting a request based on static "false" policy.
386
628
  */
387
- processWrite(model, action, args, writeAction) {
629
+ tryReject(db, model, operation) {
630
+ const guard = this.getAuthGuard(db, model, operation);
631
+ if (this.isFalse(guard)) {
632
+ throw this.deniedByPolicy(model, operation, undefined, constants_1.CrudFailureReason.ACCESS_POLICY_VIOLATION);
633
+ }
634
+ }
635
+ /**
636
+ * Checks if a model exists given a unique filter.
637
+ */
638
+ checkExistence(db, model, uniqueFilter, throwIfNotFound = false) {
388
639
  return __awaiter(this, void 0, void 0, function* () {
389
- // record model types for which new entities are created
390
- // so we can post-check if they satisfy 'create' policies
391
- const createdModels = new Set();
392
- // record model entities that are updated, together with their
393
- // values before update, so we can post-check if they satisfy
394
- // model => { ids, entity value }
395
- const updatedModels = new Map();
396
- function addUpdatedEntity(model, ids, entity) {
397
- let modelEntities = updatedModels.get(model);
398
- if (!modelEntities) {
399
- modelEntities = [];
400
- updatedModels.set(model, modelEntities);
401
- }
402
- modelEntities.push({ ids, value: entity });
403
- }
404
- const idFields = this.getIdFields(model);
405
- if (args.select) {
406
- // make sure id fields are selected, we need it to
407
- // read back the updated entity
408
- for (const idField of idFields) {
409
- if (!args.select[idField.name]) {
410
- args.select[idField.name] = true;
411
- }
412
- }
640
+ uniqueFilter = this.clone(uniqueFilter);
641
+ this.flattenGeneratedUniqueField(model, uniqueFilter);
642
+ if (this.shouldLogQuery) {
643
+ this.logger.info(`[policy] checking ${model} existence, \`findFirst\`:\n${(0, utils_1.formatObject)(uniqueFilter)}`);
413
644
  }
414
- // use a transaction to conduct write, so in case any create or nested create
415
- // fails access policies, we can roll back the entire operation
416
- const transactionId = (0, cuid2_1.createId)();
417
- // args processor for create
418
- const processCreate = (model, args) => __awaiter(this, void 0, void 0, function* () {
419
- const guard = this.getAuthGuard(model, 'create');
420
- const schema = this.getModelSchema(model);
421
- if (guard === false) {
422
- throw this.deniedByPolicy(model, 'create');
423
- }
424
- else if (guard !== true || schema) {
425
- // mark the create with a transaction tag so we can check them later
426
- args[constants_1.TRANSACTION_FIELD_NAME] = `${transactionId}:create`;
427
- createdModels.add(model);
428
- }
429
- });
430
- // build a reversed query for fetching entities affected by nested updates
431
- const buildReversedQuery = (context) => __awaiter(this, void 0, void 0, function* () {
432
- let result, currQuery;
433
- let currField;
434
- for (let i = context.nestingPath.length - 1; i >= 0; i--) {
435
- const { field, model, where, unique } = context.nestingPath[i];
436
- // never modify the original where because it's shared in the structure
437
- const visitWhere = Object.assign({}, where);
438
- if (model && where) {
439
- // make sure composite unique condition is flattened
440
- yield this.flattenGeneratedUniqueField(model, visitWhere);
441
- }
442
- if (!result) {
443
- // first segment (bottom), just use its where clause
444
- result = currQuery = Object.assign({}, visitWhere);
445
- currField = field;
446
- }
447
- else {
448
- if (!currField) {
449
- throw this.unknownError(`missing field in nested path`);
450
- }
451
- if (!currField.backLink) {
452
- throw this.unknownError(`field ${currField.type}.${currField.name} doesn't have a backLink`);
453
- }
454
- const backLinkField = this.getModelField(currField.type, currField.backLink);
455
- if (backLinkField === null || backLinkField === void 0 ? void 0 : backLinkField.isArray) {
456
- // many-side of relationship, wrap with "some" query
457
- currQuery[currField.backLink] = { some: Object.assign({}, visitWhere) };
458
- }
459
- else {
460
- currQuery[currField.backLink] = Object.assign({}, visitWhere);
461
- }
462
- currQuery = currQuery[currField.backLink];
463
- currField = field;
464
- }
465
- if (unique) {
466
- // hit a unique filter, no need to traverse further up
467
- break;
468
- }
469
- }
470
- return result;
471
- });
472
- // args processor for update/upsert
473
- const processUpdate = (model, where, context) => __awaiter(this, void 0, void 0, function* () {
474
- const preGuard = this.getAuthGuard(model, 'update');
475
- if (preGuard === false) {
476
- throw this.deniedByPolicy(model, 'update');
477
- }
478
- else if (preGuard !== true) {
479
- if (this.isToOneRelation(context.field)) {
480
- // To-one relation field is complicated because there's no way to
481
- // filter it during update (args doesn't carry a 'where' clause).
482
- //
483
- // We need to recursively walk up its hierarcy in the query args
484
- // to construct a reversed query to identify the nested entity
485
- // under update, and then check if it satisfies policy.
486
- //
487
- // E.g.:
488
- // A - B - C
489
- //
490
- // update A with:
491
- // {
492
- // where: { id: 'aId' },
493
- // data: {
494
- // b: {
495
- // c: { value: 1 }
496
- // }
497
- // }
498
- // }
499
- //
500
- // To check if the update to 'c' field is permitted, we
501
- // reverse the query stack into a filter for C model, like:
502
- // {
503
- // where: {
504
- // b: { a: { id: 'aId' } }
505
- // }
506
- // }
507
- // , and with this we can filter out the C entity that's going
508
- // to be nestedly updated, and check if it's allowed.
509
- //
510
- // The same logic applies to nested delete.
511
- const subQuery = yield buildReversedQuery(context);
512
- yield this.checkPolicyForFilter(model, subQuery, 'update', this.db);
513
- }
514
- else {
515
- if (!where) {
516
- throw this.unknownError(`Missing 'where' parameter`);
517
- }
518
- yield this.checkPolicyForFilter(model, where, 'update', this.db);
519
- }
520
- }
521
- yield preparePostUpdateCheck(model, context);
522
- });
523
- // args processor for updateMany
524
- const processUpdateMany = (model, args, context) => __awaiter(this, void 0, void 0, function* () {
525
- const guard = this.getAuthGuard(model, 'update');
526
- if (guard === false) {
527
- throw this.deniedByPolicy(model, 'update');
528
- }
529
- else if (guard !== true) {
530
- // inject policy filter
531
- yield this.injectAuthGuard(args, model, 'update');
532
- }
533
- yield preparePostUpdateCheck(model, context);
534
- });
535
- // for models with post-update rules, we need to read and store
536
- // entity values before the update for post-update check
537
- const preparePostUpdateCheck = (model, context) => __awaiter(this, void 0, void 0, function* () {
538
- const postGuard = this.getAuthGuard(model, 'postUpdate');
539
- const schema = this.getModelSchema(model);
540
- // post-update check is needed if there's post-update rule or validation schema
541
- if (postGuard !== true || schema) {
542
- // fetch preValue selection (analyzed from the post-update rules)
543
- const preValueSelect = yield this.getPreValueSelect(model);
544
- const filter = yield buildReversedQuery(context);
545
- // query args will be used with findMany, so we need to
546
- // translate unique constraint filters into a flat filter
547
- // e.g.: { a_b: { a: '1', b: '1' } } => { a: '1', b: '1' }
548
- yield this.flattenGeneratedUniqueField(model, filter);
549
- const idFields = this.getIdFields(model);
550
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
551
- const select = Object.assign({}, preValueSelect);
552
- for (const idField of idFields) {
553
- select[idField.name] = true;
554
- }
555
- const query = { where: filter, select };
556
- if (this.shouldLogQuery) {
557
- this.logger.info(`[withPolicy] \`findMany\` for fetching pre-update entities:\n${(0, utils_1.formatObject)(args)}`);
558
- }
559
- const entities = yield this.db[model].findMany(query);
560
- entities.forEach((entity) => {
561
- addUpdatedEntity(model, this.getEntityIds(model, entity), entity);
562
- });
563
- }
564
- });
565
- // args processor for delete
566
- const processDelete = (model, args, context) => __awaiter(this, void 0, void 0, function* () {
567
- const guard = this.getAuthGuard(model, 'delete');
568
- if (guard === false) {
569
- throw this.deniedByPolicy(model, 'delete');
570
- }
571
- else if (guard !== true) {
572
- if (this.isToOneRelation(context.field)) {
573
- // see comments in processUpdate
574
- const subQuery = yield buildReversedQuery(context);
575
- yield this.checkPolicyForFilter(model, subQuery, 'delete', this.db);
576
- }
577
- else {
578
- yield this.checkPolicyForFilter(model, args, 'delete', this.db);
579
- }
580
- }
645
+ const existing = yield db[model].findFirst({
646
+ where: uniqueFilter,
647
+ select: this.makeIdSelection(model),
581
648
  });
582
- // process relation updates: connect, connectOrCreate, and disconnect
583
- const processRelationUpdate = (model, args, context) => __awaiter(this, void 0, void 0, function* () {
584
- // CHECK ME: equire the entity being connected readable?
585
- // await this.checkPolicyForFilter(model, args, 'read', this.db);
586
- var _a;
587
- if ((_a = context.field) === null || _a === void 0 ? void 0 : _a.backLink) {
588
- // fetch the backlink field of the model being connected
589
- const backLinkField = (0, model_meta_1.resolveField)(this.modelMeta, model, context.field.backLink);
590
- if (backLinkField.isRelationOwner) {
591
- // the target side of relation owns the relation,
592
- // mark it as updated
593
- yield processUpdate(model, args, context);
594
- }
595
- }
596
- });
597
- // use a visitor to process args before conducting the write action
598
- const visitor = new nested_write_vistor_1.NestedWriteVisitor(this.modelMeta, {
599
- create: (model, args) => __awaiter(this, void 0, void 0, function* () {
600
- yield processCreate(model, args);
601
- }),
602
- connectOrCreate: (model, args, context) => __awaiter(this, void 0, void 0, function* () {
603
- if (args.create) {
604
- yield processCreate(model, args.create);
605
- }
606
- if (args.where) {
607
- yield processRelationUpdate(model, args.where, context);
608
- }
609
- }),
610
- connect: (model, args, context) => __awaiter(this, void 0, void 0, function* () {
611
- yield processRelationUpdate(model, args, context);
612
- }),
613
- disconnect: (model, args, context) => __awaiter(this, void 0, void 0, function* () {
614
- yield processRelationUpdate(model, args, context);
615
- }),
616
- update: (model, args, context) => __awaiter(this, void 0, void 0, function* () {
617
- yield processUpdate(model, args.where, context);
618
- }),
619
- updateMany: (model, args, context) => __awaiter(this, void 0, void 0, function* () {
620
- yield processUpdateMany(model, args, context);
621
- }),
622
- upsert: (model, args, context) => __awaiter(this, void 0, void 0, function* () {
623
- if (args.create) {
624
- yield processCreate(model, args.create);
625
- }
626
- if (args.update) {
627
- yield processUpdate(model, args.where, context);
628
- }
629
- }),
630
- delete: (model, args, context) => __awaiter(this, void 0, void 0, function* () {
631
- yield processDelete(model, args, context);
632
- }),
633
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
634
- deleteMany: (model, args, _context) => __awaiter(this, void 0, void 0, function* () {
635
- const guard = this.getAuthGuard(model, 'delete');
636
- if (guard === false) {
637
- throw this.deniedByPolicy(model, 'delete');
638
- }
639
- else if (guard !== true) {
640
- if (args.where) {
641
- args.where = this.and(args.where, guard);
642
- }
643
- else {
644
- const copy = (0, deepcopy_1.default)(args);
645
- for (const key of Object.keys(args)) {
646
- delete args[key];
647
- }
648
- const combined = this.and(copy, guard);
649
- Object.assign(args, combined);
650
- }
651
- }
652
- }),
653
- });
654
- yield visitor.visit(model, action, args);
655
- if (createdModels.size === 0 && updatedModels.size === 0) {
656
- // no post-check needed, we can proceed with the write without transaction
657
- return yield writeAction(this.db[model], args);
649
+ if (!existing && throwIfNotFound) {
650
+ throw this.notFound(model);
658
651
  }
659
- else {
660
- return yield this.transaction(this.db, (tx) => __awaiter(this, void 0, void 0, function* () {
661
- // proceed with the update (with args processed)
662
- const result = yield writeAction(tx[model], args);
663
- if (createdModels.size > 0) {
664
- // do post-check on created entities
665
- yield Promise.all([...createdModels].map((model) => this.checkPolicyForFilter(model, { [constants_1.TRANSACTION_FIELD_NAME]: `${transactionId}:create` }, 'create', tx)));
666
- }
667
- if (updatedModels.size > 0) {
668
- // do post-check on updated entities
669
- yield Promise.all([...updatedModels.entries()]
670
- .map(([model, modelEntities]) => modelEntities.map(({ ids, value: preValue }) => __awaiter(this, void 0, void 0, function* () { return this.checkPostUpdate(model, ids, tx, preValue); })))
671
- .flat());
672
- }
673
- return result;
674
- }));
652
+ return existing;
653
+ });
654
+ }
655
+ /**
656
+ * Returns an entity given a unique filter with read policy checked. Reject if not readable.
657
+ */
658
+ readBack(db, model, operation, selectInclude, uniqueFilter) {
659
+ return __awaiter(this, void 0, void 0, function* () {
660
+ uniqueFilter = this.clone(uniqueFilter);
661
+ this.flattenGeneratedUniqueField(model, uniqueFilter);
662
+ const readArgs = { select: selectInclude.select, include: selectInclude.include, where: uniqueFilter };
663
+ const error = this.deniedByPolicy(model, operation, 'result is not allowed to be read back', constants_1.CrudFailureReason.RESULT_NOT_READABLE);
664
+ const injectResult = this.injectForRead(db, model, readArgs);
665
+ if (!injectResult) {
666
+ return { error, result: undefined };
667
+ }
668
+ // inject select needed for field-level read checks
669
+ this.injectReadCheckSelect(model, readArgs);
670
+ if (this.shouldLogQuery) {
671
+ this.logger.info(`[policy] checking read-back, \`findFirst\` ${model}:\n${(0, utils_1.formatObject)(readArgs)}`);
675
672
  }
673
+ const result = yield db[model].findFirst(readArgs);
674
+ if (!result) {
675
+ return { error, result: undefined };
676
+ }
677
+ this.postProcessForRead(result, model, selectInclude);
678
+ return { result, error: undefined };
676
679
  });
677
680
  }
678
- getModelField(model, field) {
679
- var _a;
680
- model = (0, lower_case_first_1.lowerCaseFirst)(model);
681
- return (_a = this.modelMeta.fields[model]) === null || _a === void 0 ? void 0 : _a[field];
681
+ /**
682
+ * Injects field selection needed for checking field-level read policy into query args.
683
+ * @returns
684
+ */
685
+ injectReadCheckSelect(model, args) {
686
+ if (!this.hasFieldLevelPolicy(model)) {
687
+ return;
688
+ }
689
+ const readFieldSelect = this.getReadFieldSelect(model);
690
+ if (!readFieldSelect) {
691
+ return;
692
+ }
693
+ this.doInjectReadCheckSelect(model, args, { select: readFieldSelect });
682
694
  }
683
- transaction(db, action) {
684
- if (db.__zenstack_tx) {
685
- // already in transaction, don't nest
686
- return action(db);
695
+ doInjectReadCheckSelect(model, args, input) {
696
+ if (!(input === null || input === void 0 ? void 0 : input.select)) {
697
+ return;
698
+ }
699
+ let target; // injection target
700
+ let isInclude = false; // if the target is include or select
701
+ if (args.select) {
702
+ target = args.select;
703
+ isInclude = false;
704
+ }
705
+ else if (args.include) {
706
+ target = args.include;
707
+ isInclude = true;
687
708
  }
688
709
  else {
689
- return db.$transaction((tx) => action(tx));
710
+ target = args.select = this.makeAllScalarFieldSelect(model);
711
+ isInclude = false;
712
+ }
713
+ if (!isInclude) {
714
+ // merge selects
715
+ for (const [k, v] of Object.entries(input.select)) {
716
+ if (v === true) {
717
+ if (!target[k]) {
718
+ target[k] = true;
719
+ }
720
+ }
721
+ }
722
+ }
723
+ // recurse into nested selects (relation fields)
724
+ for (const [k, v] of Object.entries(input.select)) {
725
+ if (typeof v === 'object' && (v === null || v === void 0 ? void 0 : v.select)) {
726
+ const field = (0, model_meta_1.resolveField)(this.modelMeta, model, k);
727
+ if (field === null || field === void 0 ? void 0 : field.isDataModel) {
728
+ // recurse into relation
729
+ if (isInclude && target[k] === true) {
730
+ // select all fields for the relation
731
+ target[k] = { select: this.makeAllScalarFieldSelect(field.type) };
732
+ }
733
+ else if (!target[k]) {
734
+ // ensure an empty select clause
735
+ target[k] = { select: {} };
736
+ }
737
+ // recurse
738
+ this.doInjectReadCheckSelect(field.type, target[k], v);
739
+ }
740
+ }
690
741
  }
691
742
  }
692
- deniedByPolicy(model, operation, extra, reason) {
693
- return (0, utils_1.prismaClientKnownRequestError)(this.db, `denied by policy: ${model} entities failed '${operation}' check${extra ? ', ' + extra : ''}`, { clientVersion: (0, version_1.getVersion)(), code: 'P2004', meta: { reason } });
743
+ makeAllScalarFieldSelect(model) {
744
+ const fields = this.modelMeta.fields[(0, lower_case_first_1.lowerCaseFirst)(model)];
745
+ const result = {};
746
+ if (fields) {
747
+ Object.entries(fields).forEach(([k, v]) => {
748
+ if (!v.isDataModel) {
749
+ result[k] = true;
750
+ }
751
+ });
752
+ }
753
+ return result;
754
+ }
755
+ //#endregion
756
+ //#region Errors
757
+ deniedByPolicy(model, operation, extra, reason, zodErrors) {
758
+ const args = { clientVersion: (0, version_1.getVersion)(), code: constants_1.PrismaErrorCode.CONSTRAINED_FAILED, meta: {} };
759
+ if (reason) {
760
+ args.meta.reason = reason;
761
+ }
762
+ if (zodErrors) {
763
+ args.meta.zodErrors = zodErrors;
764
+ }
765
+ return (0, utils_1.prismaClientKnownRequestError)(this.db, `denied by policy: ${model} entities failed '${operation}' check${extra ? ', ' + extra : ''}`, args);
694
766
  }
695
767
  notFound(model) {
696
768
  return (0, utils_1.prismaClientKnownRequestError)(this.db, `entity not found for model ${model}`, {
@@ -698,122 +770,150 @@ class PolicyUtil {
698
770
  code: 'P2025',
699
771
  });
700
772
  }
773
+ validationError(message) {
774
+ return (0, utils_1.prismaClientValidationError)(this.db, message);
775
+ }
701
776
  unknownError(message) {
702
777
  return (0, utils_1.prismaClientUnknownRequestError)(this.db, message, {
703
778
  clientVersion: (0, version_1.getVersion)(),
704
779
  });
705
780
  }
781
+ //#endregion
782
+ //#region Misc
706
783
  /**
707
- * Given a filter, check if applying access policy filtering will result
708
- * in data being trimmed, and if so, throw an error.
784
+ * Gets field selection for fetching pre-update entity values for the given model.
709
785
  */
710
- checkPolicyForFilter(model, filter, operation, db) {
711
- return __awaiter(this, void 0, void 0, function* () {
712
- const guard = this.getAuthGuard(model, operation);
713
- const schema = (operation === 'create' || operation === 'update') && this.getModelSchema(model);
714
- if (guard === true && !schema) {
715
- // unconditionally allowed
716
- return;
717
- }
718
- // if (this.logger.enabled('info')) {
719
- // this.logger.info(`Checking policy for ${model}#${JSON.stringify(filter)} for ${operation}`);
720
- // }
721
- const queryFilter = (0, deepcopy_1.default)(filter);
722
- // query args will be used with findMany, so we need to
723
- // translate unique constraint filters into a flat filter
724
- // e.g.: { a_b: { a: '1', b: '1' } } => { a: '1', b: '1' }
725
- yield this.flattenGeneratedUniqueField(model, queryFilter);
726
- const countArgs = { where: queryFilter };
727
- // if (this.shouldLogQuery) {
728
- // this.logger.info(
729
- // `[withPolicy] \`count\` for policy check without guard:\n${formatObject(countArgs)}`
730
- // );
731
- // }
732
- const count = (yield db[model].count(countArgs));
733
- if (count === 0) {
734
- // there's nothing to filter out
786
+ getPreValueSelect(model) {
787
+ const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
788
+ if (!guard) {
789
+ throw this.unknownError(`unable to load policy guard for ${model}`);
790
+ }
791
+ return guard[constants_1.PRE_UPDATE_VALUE_SELECTOR];
792
+ }
793
+ getReadFieldSelect(model) {
794
+ const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
795
+ if (!guard) {
796
+ throw this.unknownError(`unable to load policy guard for ${model}`);
797
+ }
798
+ return guard[constants_1.FIELD_LEVEL_READ_CHECKER_SELECTOR];
799
+ }
800
+ checkReadField(model, field, entity) {
801
+ const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
802
+ if (!guard) {
803
+ throw this.unknownError(`unable to load policy guard for ${model}`);
804
+ }
805
+ const func = guard[`${constants_1.FIELD_LEVEL_READ_CHECKER_PREFIX}${field}`];
806
+ if (!func) {
807
+ return true;
808
+ }
809
+ else {
810
+ return func(entity, { user: this.user });
811
+ }
812
+ }
813
+ hasFieldValidation(model) {
814
+ var _a, _b;
815
+ return ((_b = (_a = this.policy.validation) === null || _a === void 0 ? void 0 : _a[(0, lower_case_first_1.lowerCaseFirst)(model)]) === null || _b === void 0 ? void 0 : _b.hasValidation) === true;
816
+ }
817
+ hasFieldLevelPolicy(model) {
818
+ const guard = this.policy.guard[(0, lower_case_first_1.lowerCaseFirst)(model)];
819
+ if (!guard) {
820
+ throw this.unknownError(`unable to load policy guard for ${model}`);
821
+ }
822
+ return !!guard[constants_1.HAS_FIELD_LEVEL_POLICY_FLAG];
823
+ }
824
+ /**
825
+ * Gets Zod schema for the given model and access kind.
826
+ *
827
+ * @param kind If undefined, returns the full schema.
828
+ */
829
+ getZodSchema(model, kind = undefined) {
830
+ var _a, _b;
831
+ if (!this.hasFieldValidation(model)) {
832
+ return undefined;
833
+ }
834
+ const schemaKey = `${(0, upper_case_first_1.upperCaseFirst)(model)}${kind ? (0, upper_case_first_1.upperCaseFirst)(kind) : ''}Schema`;
835
+ return (_b = (_a = this.zodSchemas) === null || _a === void 0 ? void 0 : _a.models) === null || _b === void 0 ? void 0 : _b[schemaKey];
836
+ }
837
+ /**
838
+ * Post processing checks and clean-up for read model entities.
839
+ */
840
+ postProcessForRead(data, model, queryArgs) {
841
+ // preserve the original data as it may be needed for checking field-level readability,
842
+ // while the "data" will be manipulated during traversal (deleting unreadable fields)
843
+ const origData = this.clone(data);
844
+ this.doPostProcessForRead(data, model, origData, queryArgs, this.hasFieldLevelPolicy(model));
845
+ }
846
+ doPostProcessForRead(data, model, fullData, queryArgs, hasFieldLevelPolicy, path = '') {
847
+ var _a, _b;
848
+ if (data === null || data === undefined) {
849
+ return;
850
+ }
851
+ for (const [entityData, entityFullData] of (0, utils_1.zip)(data, fullData)) {
852
+ if (typeof entityData !== 'object' || !entityData) {
735
853
  return;
736
854
  }
737
- if (guard === false) {
738
- // unconditionally denied
739
- throw this.deniedByPolicy(model, operation, `${count} ${(0, pluralize_1.default)('entity', count)} failed policy check`);
740
- }
741
- // build a query condition with policy injected
742
- const guardedQuery = { where: this.and(queryFilter, guard) };
743
- if (schema) {
744
- // we've got schemas, so have to fetch entities and validate them
745
- // if (this.shouldLogQuery) {
746
- // this.logger.info(
747
- // `[withPolicy] \`findMany\` for policy check with guard:\n${formatObject(countArgs)}`
748
- // );
749
- // }
750
- const entities = yield db[model].findMany(guardedQuery);
751
- if (entities.length < count) {
752
- if (this.logger.enabled('info')) {
753
- this.logger.info(`entity ${model} failed policy check for operation ${operation}`);
754
- }
755
- throw this.deniedByPolicy(model, operation, `${count - entities.length} ${(0, pluralize_1.default)('entity', count - entities.length)} failed policy check`);
855
+ for (const [field, fieldData] of Object.entries(entityData)) {
856
+ if (fieldData === undefined) {
857
+ continue;
756
858
  }
757
- // TODO: push down schema check to the database
758
- const schemaCheckErrors = entities.map((entity) => schema.safeParse(entity)).filter((r) => !r.success);
759
- if (schemaCheckErrors.length > 0) {
760
- const error = schemaCheckErrors.map((r) => !r.success && (0, zod_validation_error_1.fromZodError)(r.error).message).join(', ');
761
- if (this.logger.enabled('info')) {
762
- this.logger.info(`entity ${model} failed schema check for operation ${operation}: ${error}`);
763
- }
764
- throw this.deniedByPolicy(model, operation, `entities failed schema check: [${error}]`);
859
+ const fieldInfo = (0, model_meta_1.resolveField)(this.modelMeta, model, field);
860
+ if (!fieldInfo) {
861
+ // could be _count, etc.
862
+ continue;
765
863
  }
766
- }
767
- else {
768
- // count entities with policy injected and see if any of them are filtered out
769
- // if (this.shouldLogQuery) {
770
- // this.logger.info(
771
- // `[withPolicy] \`count\` for policy check with guard:\n${formatObject(guardedQuery)}`
772
- // );
773
- // }
774
- const guardedCount = (yield db[model].count(guardedQuery));
775
- if (guardedCount < count) {
776
- if (this.logger.enabled('info')) {
777
- this.logger.info(`entity ${model} failed policy check for operation ${operation}`);
864
+ if (hasFieldLevelPolicy) {
865
+ // 1. remove fields selected for checking field-level policies but not selected by the original query args
866
+ // 2. evaluate field-level policies and remove fields that are not readable
867
+ if (!fieldInfo.isDataModel) {
868
+ // scalar field, delete unselected ones
869
+ const select = queryArgs === null || queryArgs === void 0 ? void 0 : queryArgs.select;
870
+ if (select && typeof select === 'object' && select[field] !== true) {
871
+ // there's a select clause but this field is not included
872
+ delete entityData[field];
873
+ continue;
874
+ }
778
875
  }
779
- throw this.deniedByPolicy(model, operation, `${count - guardedCount} ${(0, pluralize_1.default)('entity', count - guardedCount)} failed policy check`);
780
- }
781
- }
782
- });
783
- }
784
- checkPostUpdate(model, ids, db, preValue) {
785
- return __awaiter(this, void 0, void 0, function* () {
786
- // if (this.logger.enabled('info')) {
787
- // this.logger.info(`Checking post-update policy for ${model}#${ids}, preValue: ${formatObject(preValue)}`);
788
- // }
789
- const guard = this.getAuthGuard(model, 'postUpdate', preValue);
790
- // build a query condition with policy injected
791
- const guardedQuery = { where: this.and(ids, guard) };
792
- // query with policy injected
793
- const entity = yield db[model].findFirst(guardedQuery);
794
- // see if we get fewer items with policy, if so, reject with an throw
795
- if (!entity) {
796
- if (this.logger.enabled('info')) {
797
- this.logger.info(`entity ${model} failed policy check for operation postUpdate`);
798
- }
799
- throw this.deniedByPolicy(model, 'postUpdate');
800
- }
801
- // TODO: push down schema check to the database
802
- const schema = this.getModelSchema(model);
803
- if (schema) {
804
- const schemaCheckResult = schema.safeParse(entity);
805
- if (!schemaCheckResult.success) {
806
- const error = (0, zod_validation_error_1.fromZodError)(schemaCheckResult.error).message;
807
- if (this.logger.enabled('info')) {
808
- this.logger.info(`entity ${model} failed schema check for operation postUpdate: ${error}`);
876
+ else {
877
+ // relation field, delete if not selected or included
878
+ const include = queryArgs === null || queryArgs === void 0 ? void 0 : queryArgs.include;
879
+ const select = queryArgs === null || queryArgs === void 0 ? void 0 : queryArgs.select;
880
+ if (!(include === null || include === void 0 ? void 0 : include[field]) && !(select === null || select === void 0 ? void 0 : select[field])) {
881
+ // relation field not included or selected
882
+ delete entityData[field];
883
+ continue;
884
+ }
885
+ }
886
+ // delete unreadable fields
887
+ if (!this.checkReadField(model, field, entityFullData)) {
888
+ if (this.shouldLogQuery) {
889
+ this.logger.info(`[policy] dropping unreadable field ${path ? path + '.' : ''}${field}`);
890
+ }
891
+ delete entityData[field];
892
+ continue;
809
893
  }
810
- throw this.deniedByPolicy(model, 'postUpdate', `entity failed schema check: ${error}`);
894
+ }
895
+ if (fieldInfo.isDataModel) {
896
+ // recurse into nested fields
897
+ const nextArgs = (_b = ((_a = queryArgs === null || queryArgs === void 0 ? void 0 : queryArgs.select) !== null && _a !== void 0 ? _a : queryArgs === null || queryArgs === void 0 ? void 0 : queryArgs.include)) === null || _b === void 0 ? void 0 : _b[field];
898
+ this.doPostProcessForRead(fieldData, fieldInfo.type, entityFullData[field], nextArgs, hasFieldLevelPolicy, path ? path + '.' + field : field);
811
899
  }
812
900
  }
813
- });
901
+ }
814
902
  }
815
- isToOneRelation(field) {
816
- return !!field && field.isDataModel && !field.isArray;
903
+ /**
904
+ * Gets information for all fields of a model.
905
+ */
906
+ getModelFields(model) {
907
+ model = (0, lower_case_first_1.lowerCaseFirst)(model);
908
+ return this.modelMeta.fields[model];
909
+ }
910
+ /**
911
+ * Gets information for a specific model field.
912
+ */
913
+ getModelField(model, field) {
914
+ var _a;
915
+ model = (0, lower_case_first_1.lowerCaseFirst)(model);
916
+ return (_a = this.modelMeta.fields[model]) === null || _a === void 0 ? void 0 : _a[field];
817
917
  }
818
918
  /**
819
919
  * Clones an object and makes sure it's not empty.
@@ -822,13 +922,13 @@ class PolicyUtil {
822
922
  return value ? (0, deepcopy_1.default)(value) : {};
823
923
  }
824
924
  /**
825
- * Gets "id" field for a given model.
925
+ * Gets "id" fields for a given model.
826
926
  */
827
927
  getIdFields(model) {
828
928
  return (0, utils_1.getIdFields)(this.modelMeta, model, true);
829
929
  }
830
930
  /**
831
- * Gets id field value from an entity.
931
+ * Gets id field values from an entity.
832
932
  */
833
933
  getEntityIds(model, entityData) {
834
934
  const idFields = this.getIdFields(model);
@@ -838,8 +938,36 @@ class PolicyUtil {
838
938
  }
839
939
  return result;
840
940
  }
841
- get shouldLogQuery() {
842
- return this.logPrismaQuery && this.logger.enabled('info');
941
+ /**
942
+ * Creates a selection object for id fields for the given model.
943
+ */
944
+ makeIdSelection(model) {
945
+ const idFields = this.getIdFields(model);
946
+ return Object.assign({}, ...idFields.map((f) => ({ [f.name]: true })));
947
+ }
948
+ mergeWhereClause(where, extra) {
949
+ var _a;
950
+ if (!where) {
951
+ throw new Error('invalid where clause');
952
+ }
953
+ if (this.isTrue(extra)) {
954
+ return;
955
+ }
956
+ // instead of simply wrapping with AND, we preserve the structure
957
+ // of the original where clause and merge `extra` into it so that
958
+ // unique query can continue working
959
+ if (where.AND) {
960
+ // merge into existing AND clause
961
+ const conditions = Array.isArray(where.AND) ? [...where.AND] : [where.AND];
962
+ conditions.push(extra);
963
+ const combined = this.and(...conditions);
964
+ // make sure the merging always goes under AND
965
+ where.AND = (_a = combined.AND) !== null && _a !== void 0 ? _a : combined;
966
+ }
967
+ else {
968
+ // insert an AND clause
969
+ where.AND = [extra];
970
+ }
843
971
  }
844
972
  }
845
973
  exports.PolicyUtil = PolicyUtil;