-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathpolicy-utils.ts
1640 lines (1415 loc) · 58.7 KB
/
policy-utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
import deepmerge from 'deepmerge';
import { isPlainObject } from 'is-plain-object';
import { lowerCaseFirst } from 'lower-case-first';
import traverse from 'traverse';
import { upperCaseFirst } from 'upper-case-first';
import { z, type ZodError, type ZodObject, type ZodSchema } from 'zod';
import { fromZodError } from 'zod-validation-error';
import { CrudFailureReason, PrismaErrorCode } from '../../../constants';
import {
clone,
enumerate,
getFields,
getModelFields,
resolveField,
zip,
type FieldInfo,
type ModelMeta,
} from '../../../cross';
import {
AuthUser,
CrudContract,
DbClientContract,
EnhancementContext,
PolicyCrudKind,
PolicyOperationKind,
QueryContext,
ZodSchemas,
} from '../../../types';
import { getVersion } from '../../../version';
import type { InternalEnhancementOptions } from '../create-enhancement';
import { Logger } from '../logger';
import { QueryUtils } from '../query-utils';
import type {
DelegateConstraint,
EntityChecker,
ModelPolicyDef,
PermissionCheckerFunc,
PolicyDef,
PolicyFunc,
VariableConstraint,
} from '../types';
import { formatObject, prismaClientKnownRequestError } from '../utils';
/**
* Access policy enforcement utilities
*/
export class PolicyUtil extends QueryUtils {
private readonly logger: Logger;
private readonly modelMeta: ModelMeta;
private readonly policy: PolicyDef;
private readonly zodSchemas?: ZodSchemas;
private readonly prismaModule: any;
private readonly user?: AuthUser;
constructor(
private readonly db: DbClientContract,
options: InternalEnhancementOptions,
context?: EnhancementContext,
private readonly shouldLogQuery = false
) {
super(db, options);
this.logger = new Logger(db);
this.user = context?.user;
({
modelMeta: this.modelMeta,
policy: this.policy,
zodSchemas: this.zodSchemas,
prismaModule: this.prismaModule,
} = options);
}
//#region Logical operators
/**
* Creates a conjunction of a list of query conditions.
*/
and(...conditions: (boolean | object | undefined)[]): object {
const filtered = conditions.filter((c) => c !== undefined);
if (filtered.length === 0) {
return this.makeTrue();
} else if (filtered.length === 1) {
return this.reduce(filtered[0]);
} else {
return this.reduce({ AND: filtered });
}
}
/**
* Creates a disjunction of a list of query conditions.
*/
or(...conditions: (boolean | object | undefined)[]): object {
const filtered = conditions.filter((c) => c !== undefined);
if (filtered.length === 0) {
return this.makeFalse();
} else if (filtered.length === 1) {
return this.reduce(filtered[0]);
} else {
return this.reduce({ OR: filtered });
}
}
/**
* Creates a negation of a query condition.
*/
not(condition: object | boolean | undefined): object {
if (condition === undefined) {
return this.makeTrue();
} else if (typeof condition === 'boolean') {
return this.reduce(!condition);
} else {
return this.reduce({ NOT: condition });
}
}
// Static True/False conditions
// https://www.prisma.io/docs/concepts/components/prisma-client/null-and-undefined#the-effect-of-null-and-undefined-on-conditionals
private singleKey(obj: object | null | undefined, key: string): obj is { [key: string]: unknown } {
if (!obj) {
return false;
} else {
return Object.keys(obj).length === 1 && Object.keys(obj)[0] === key;
}
}
public isTrue(condition: object | null | undefined) {
if (condition === null || condition === undefined || !isPlainObject(condition)) {
return false;
}
// {} is true
if (Object.keys(condition).length === 0) {
return true;
}
// { OR: TRUE } is true
if (this.singleKey(condition, 'OR') && typeof condition.OR === 'object' && this.isTrue(condition.OR)) {
return true;
}
// { NOT: FALSE } is true
if (this.singleKey(condition, 'NOT') && typeof condition.NOT === 'object' && this.isFalse(condition.NOT)) {
return true;
}
// { AND: [] } is true
if (this.singleKey(condition, 'AND') && Array.isArray(condition.AND) && condition.AND.length === 0) {
return true;
}
return false;
}
public isFalse(condition: object | null | undefined) {
if (condition === null || condition === undefined || !isPlainObject(condition)) {
return false;
}
// { AND: FALSE } is false
if (this.singleKey(condition, 'AND') && typeof condition.AND === 'object' && this.isFalse(condition.AND)) {
return true;
}
// { NOT: TRUE } is false
if (this.singleKey(condition, 'NOT') && typeof condition.NOT === 'object' && this.isTrue(condition.NOT)) {
return true;
}
// { OR: [] } is false
if (this.singleKey(condition, 'OR') && Array.isArray(condition.OR) && condition.OR.length === 0) {
return true;
}
return false;
}
private makeTrue() {
return { AND: [] };
}
private makeFalse() {
return { OR: [] };
}
private reduce(condition: object | boolean | undefined): object {
if (condition === true || condition === undefined) {
return this.makeTrue();
}
if (condition === false) {
return this.makeFalse();
}
if (condition === null) {
return condition;
}
const result: any = {};
for (const [key, value] of Object.entries<any>(condition)) {
if (value === null || value === undefined) {
result[key] = value;
continue;
}
switch (key) {
case 'AND': {
const children = enumerate(value)
.map((c: any) => this.reduce(c))
.filter((c) => c !== undefined && !this.isTrue(c));
if (children.length === 0) {
// { ..., AND: [] }
result[key] = [];
} else if (children.some((c) => this.isFalse(c))) {
// { ..., AND: { OR: [] } }
result[key] = this.makeFalse();
} else {
result[key] = !Array.isArray(value) && children.length === 1 ? children[0] : children;
}
break;
}
case 'OR': {
const children = enumerate(value)
.map((c: any) => this.reduce(c))
.filter((c) => c !== undefined && !this.isFalse(c));
if (children.length === 0) {
// { ..., OR: [] }
result[key] = [];
} else if (children.some((c) => this.isTrue(c))) {
// { ..., OR: { AND: [] } }
result[key] = this.makeTrue();
} else {
result[key] = !Array.isArray(value) && children.length === 1 ? children[0] : children;
}
break;
}
case 'NOT': {
const children = enumerate(value).map((c: any) => this.reduce(c));
result[key] = !Array.isArray(value) && children.length === 1 ? children[0] : children;
break;
}
default: {
if (!isPlainObject(value)) {
// don't visit into non-plain object values - could be Date, array, etc.
result[key] = value;
} else {
result[key] = this.reduce(value);
}
break;
}
}
}
// finally normalize constant true/false conditions
if (this.isTrue(result)) {
return this.makeTrue();
} else if (this.isFalse(result)) {
return this.makeFalse();
} else {
return result;
}
}
//#endregion
//#region Auth guard
private readonly FULL_OPEN_MODEL_POLICY: ModelPolicyDef = {
modelLevel: {
read: { guard: true },
create: { guard: true, inputChecker: true },
update: { guard: true },
delete: { guard: true },
postUpdate: { guard: true },
},
};
private getModelPolicyDef(model: string): ModelPolicyDef {
if (this.options.kinds && !this.options.kinds.includes('policy')) {
// policy enhancement not enabled, return an fully open guard
return this.FULL_OPEN_MODEL_POLICY;
}
const def = this.policy.policy[lowerCaseFirst(model)];
if (!def) {
throw this.unknownError(`unable to load policy guard for ${model}`);
}
return def;
}
private getModelGuardForOperation(model: string, operation: PolicyOperationKind): PolicyFunc | boolean {
const def = this.getModelPolicyDef(model);
return def.modelLevel[operation].guard ?? true;
}
/**
* Gets pregenerated authorization guard object for a given model and operation.
*
* @returns true if operation is unconditionally allowed, false if unconditionally denied,
* otherwise returns a guard object
*/
getAuthGuard(db: CrudContract, model: string, operation: PolicyOperationKind, preValue?: any) {
const guard = this.getModelGuardForOperation(model, operation);
// constant guard
if (typeof guard === 'boolean') {
return this.reduce(guard);
}
// invoke guard function
const r = guard({ user: this.user, preValue }, db);
return this.reduce(r);
}
/**
* Get field-level read auth guard
*/
getFieldReadAuthGuard(db: CrudContract, model: string, field: string) {
const def = this.getModelPolicyDef(model);
const guard = def.fieldLevel?.read?.[field]?.guard;
if (guard === undefined) {
// field access is allowed by default
return this.makeTrue();
}
if (typeof guard === 'boolean') {
return this.reduce(guard);
}
const r = guard({ user: this.user }, db);
return this.reduce(r);
}
/**
* Get field-level read auth guard that overrides the model-level
*/
getFieldOverrideReadAuthGuard(db: CrudContract, model: string, field: string) {
const def = this.getModelPolicyDef(model);
const guard = def.fieldLevel?.read?.[field]?.overrideGuard;
if (guard === undefined) {
// field access is denied by default in override mode
return this.makeFalse();
}
if (typeof guard === 'boolean') {
return this.reduce(guard);
}
const r = guard({ user: this.user }, db);
return this.reduce(r);
}
/**
* Get field-level update auth guard
*/
getFieldUpdateAuthGuard(db: CrudContract, model: string, field: string) {
const def = this.getModelPolicyDef(model);
const guard = def.fieldLevel?.update?.[field]?.guard;
if (guard === undefined) {
// field access is allowed by default
return this.makeTrue();
}
if (typeof guard === 'boolean') {
return this.reduce(guard);
}
const r = guard({ user: this.user }, db);
return this.reduce(r);
}
/**
* Get field-level update auth guard that overrides the model-level
*/
getFieldOverrideUpdateAuthGuard(db: CrudContract, model: string, field: string) {
const def = this.getModelPolicyDef(model);
const guard = def.fieldLevel?.update?.[field]?.overrideGuard;
if (guard === undefined) {
// field access is denied by default in override mode
return this.makeFalse();
}
if (typeof guard === 'boolean') {
return this.reduce(guard);
}
const r = guard({ user: this.user }, db);
return this.reduce(r);
}
/**
* Checks if the given model has a policy guard for the given operation.
*/
hasAuthGuard(model: string, operation: PolicyOperationKind) {
const guard = this.getModelGuardForOperation(model, operation);
return typeof guard !== 'boolean' || guard !== true;
}
/**
* Checks if the given model has any field-level override policy guard for the given operation.
*/
hasOverrideAuthGuard(model: string, operation: PolicyOperationKind) {
if (operation !== 'read' && operation !== 'update') {
return false;
}
const def = this.getModelPolicyDef(model);
if (def.fieldLevel?.[operation]) {
return Object.values(def.fieldLevel[operation]).some(
(f) => f.overrideGuard !== undefined || f.overrideEntityChecker !== undefined
);
} else {
return false;
}
}
/**
* Checks model creation policy based on static analysis to the input args.
*
* @returns boolean if static analysis is enough to determine the result, undefined if not
*/
checkInputGuard(model: string, args: any, operation: 'create'): boolean | undefined {
const def = this.getModelPolicyDef(model);
const guard = def.modelLevel[operation].inputChecker;
if (guard === undefined) {
return undefined;
}
if (typeof guard === 'boolean') {
return guard;
}
return guard(args, { user: this.user });
}
/**
* Injects model auth guard as where clause.
*/
injectAuthGuardAsWhere(db: CrudContract, args: any, model: string, operation: PolicyOperationKind) {
let guard = this.getAuthGuard(db, model, operation);
if (operation === 'update' && args) {
// merge field-level policy guards
const fieldUpdateGuard = this.getFieldUpdateGuards(db, model, args);
if (fieldUpdateGuard.rejectedByField) {
// rejected
args.where = this.makeFalse();
return false;
} else {
if (fieldUpdateGuard.guard) {
// merge field-level guard
guard = this.and(guard, fieldUpdateGuard.guard);
}
if (fieldUpdateGuard.overrideGuard) {
// merge field-level override guard on the top level
guard = this.or(guard, fieldUpdateGuard.overrideGuard);
}
}
}
if (operation === 'read') {
// merge field-level read override guards
const fieldReadOverrideGuard = this.getFieldReadGuards(db, model, args);
if (fieldReadOverrideGuard) {
guard = this.or(guard, fieldReadOverrideGuard);
}
}
if (this.isFalse(guard)) {
args.where = this.makeFalse();
return false;
}
let mergedGuard = guard;
if (args.where) {
// inject into fields:
// to-many: some/none/every
// to-one: direct-conditions/is/isNot
// regular fields
mergedGuard = this.buildReadGuardForFields(db, model, args.where, guard);
}
args.where = this.and(args.where, mergedGuard);
return true;
}
// Injects guard for relation fields nested in `payload`. The `modelGuard` parameter represents the model-level guard for `model`.
// The function returns a modified copy of `modelGuard` with field-level policies combined.
private buildReadGuardForFields(db: CrudContract, model: string, payload: any, modelGuard: any) {
if (!payload || typeof payload !== 'object' || Object.keys(payload).length === 0) {
return modelGuard;
}
const allFieldGuards: object[] = [];
const allFieldOverrideGuards: object[] = [];
for (const [field, subPayload] of Object.entries<any>(payload)) {
if (!subPayload) {
continue;
}
allFieldGuards.push(this.getFieldReadAuthGuard(db, model, field));
allFieldOverrideGuards.push(this.getFieldOverrideReadAuthGuard(db, model, field));
const fieldInfo = resolveField(this.modelMeta, model, field);
if (fieldInfo?.isDataModel) {
if (fieldInfo.isArray) {
this.injectReadGuardForToManyField(db, fieldInfo, subPayload);
} else {
this.injectReadGuardForToOneField(db, fieldInfo, subPayload);
}
}
}
// all existing field-level guards must be true
const mergedGuard: object = this.and(...allFieldGuards);
// all existing field-level override guards must be true for override to take effect; override is disabled by default
const mergedOverrideGuard: object =
allFieldOverrideGuards.length === 0 ? this.makeFalse() : this.and(...allFieldOverrideGuards);
// (original-guard && field-level-guard) || field-level-override-guard
const updatedGuard = this.or(this.and(modelGuard, mergedGuard), mergedOverrideGuard);
return updatedGuard;
}
private injectReadGuardForToManyField(
db: CrudContract,
fieldInfo: FieldInfo,
payload: { some?: any; every?: any; none?: any }
) {
const guard = this.getAuthGuard(db, fieldInfo.type, 'read');
if (payload.some) {
const mergedGuard = this.buildReadGuardForFields(db, fieldInfo.type, payload.some, guard);
// turn "some" into: { some: { AND: [guard, payload.some] } }
payload.some = this.and(payload.some, mergedGuard);
}
if (payload.none) {
const mergedGuard = this.buildReadGuardForFields(db, fieldInfo.type, payload.none, guard);
// turn none into: { none: { AND: [guard, payload.none] } }
payload.none = this.and(payload.none, mergedGuard);
}
if (
payload.every &&
typeof payload.every === 'object' &&
// ignore empty every clause
Object.keys(payload.every).length > 0
) {
const mergedGuard = this.buildReadGuardForFields(db, fieldInfo.type, payload.every, guard);
// turn "every" into: { none: { AND: [guard, { NOT: payload.every }] } }
if (!payload.none) {
payload.none = {};
}
payload.none = this.and(payload.none, mergedGuard, this.not(payload.every));
delete payload.every;
}
}
private injectReadGuardForToOneField(
db: CrudContract,
fieldInfo: FieldInfo,
payload: { is?: any; isNot?: any } & Record<string, any>
) {
const guard = this.getAuthGuard(db, fieldInfo.type, 'read');
// is|isNot and flat fields conditions are mutually exclusive
// is and isNot can be null value
if (payload.is !== undefined || payload.isNot !== undefined) {
if (payload.is) {
const mergedGuard = this.buildReadGuardForFields(db, fieldInfo.type, payload.is, guard);
// merge guard with existing "is": { is: { AND: [originalIs, guard] } }
payload.is = this.and(payload.is, mergedGuard);
}
if (payload.isNot) {
const mergedGuard = this.buildReadGuardForFields(db, fieldInfo.type, payload.isNot, guard);
// merge guard with existing "isNot": { isNot: { AND: [originalIsNot, guard] } }
payload.isNot = this.and(payload.isNot, mergedGuard);
}
} else {
const mergedGuard = this.buildReadGuardForFields(db, fieldInfo.type, payload, guard);
// turn direct conditions into: { is: { AND: [ originalConditions, guard ] } }
const combined = this.and(clone(payload), mergedGuard);
Object.keys(payload).forEach((key) => delete payload[key]);
payload.is = combined;
}
}
/**
* Injects auth guard for read operations.
*/
injectForRead(db: CrudContract, model: string, args: any) {
// make select and include visible to the injection
const injected: any = { select: args.select, include: args.include };
if (!this.injectAuthGuardAsWhere(db, injected, model, 'read')) {
args.where = this.makeFalse();
return false;
}
if (args.where) {
// inject into fields:
// to-many: some/none/every
// to-one: direct-conditions/is/isNot
// regular fields
const mergedGuard = this.buildReadGuardForFields(db, model, args.where, {});
args.where = this.mergeWhereClause(args.where, mergedGuard);
}
if (args.where) {
if (injected.where && Object.keys(injected.where).length > 0) {
// merge injected guard with the user-provided where clause
args.where = this.mergeWhereClause(args.where, injected.where);
}
} else if (injected.where) {
// no user-provided where clause, use the injected one
args.where = injected.where;
}
// recursively inject read guard conditions into nested select, include, and _count
const hoistedConditions = this.injectNestedReadConditions(db, model, args);
// the injection process may generate conditions that need to be hoisted to the toplevel,
// if so, merge it with the existing where
if (hoistedConditions.length > 0) {
if (!args.where) {
args.where = this.and(...hoistedConditions);
} else {
args.where = this.mergeWhereClause(args.where, this.and(...hoistedConditions));
}
}
return true;
}
//#endregion
//#region Checker
/**
* Gets checker constraints for the given model and operation.
*/
getCheckerConstraint(model: string, operation: PolicyCrudKind): ReturnType<PermissionCheckerFunc> | boolean {
if (this.options.kinds && !this.options.kinds.includes('policy')) {
// policy enhancement not enabled, return a constant true checker result
return true;
}
const def = this.getModelPolicyDef(model);
const checker = def.modelLevel[operation].permissionChecker;
if (checker === undefined) {
throw new Error(
`Generated permission checkers not found. Please make sure the "generatePermissionChecker" option is set to true in the "@core/enhancer" plugin.`
);
}
if (typeof checker === 'boolean') {
return checker;
}
if (typeof checker !== 'function') {
throw this.unknownError(`invalid ${operation} checker function for ${model}`);
}
// call checker function
let result = checker({ user: this.user });
// the constraint may contain "delegate" ones that should be resolved
// by evaluating the corresponding checker of the delegated models
const isVariableConstraint = (value: any): value is VariableConstraint => {
return value && typeof value === 'object' && value.kind === 'variable';
};
const isDelegateConstraint = (value: any): value is DelegateConstraint => {
return value && typeof value === 'object' && value.kind === 'delegate';
};
// here we prefix the constraint variables coming from delegated checkers
// with the relation field name to avoid conflicts
const prefixConstraintVariables = (constraint: unknown, prefix: string) => {
return traverse(constraint).map(function (value) {
if (isVariableConstraint(value)) {
this.update(
{
...value,
name: `${prefix}${value.name}`,
},
true
);
}
});
};
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
result = traverse(result).forEach(function (value) {
if (isDelegateConstraint(value)) {
const { model: delegateModel, relation, operation: delegateOp } = value;
let newValue = that.getCheckerConstraint(delegateModel, delegateOp ?? operation);
newValue = prefixConstraintVariables(newValue, `${relation}.`);
this.update(newValue, true);
}
});
return result;
}
//#endregion
/**
* Gets unique constraints for the given model.
*/
getUniqueConstraints(model: string) {
return this.modelMeta.models[lowerCaseFirst(model)]?.uniqueConstraints ?? {};
}
private injectNestedReadConditions(db: CrudContract, model: string, args: any): any[] {
const injectTarget = args.select ?? args.include;
if (!injectTarget) {
return [];
}
if (injectTarget._count !== undefined) {
// _count needs to respect read policies of related models
if (injectTarget._count === true) {
// include count for all relations, expand to all fields
// so that we can inject guard conditions for each of them
injectTarget._count = { select: {} };
const modelFields = getFields(this.modelMeta, model);
if (modelFields) {
for (const [k, v] of Object.entries(modelFields)) {
if (v.isDataModel && v.isArray) {
// create an entry for to-many relation
injectTarget._count.select[k] = {};
}
}
}
}
// inject conditions for each relation
for (const field of Object.keys(injectTarget._count.select)) {
if (typeof injectTarget._count.select[field] !== 'object') {
injectTarget._count.select[field] = {};
}
const fieldInfo = resolveField(this.modelMeta, model, field);
if (!fieldInfo) {
continue;
}
// inject into the "where" clause inside select
this.injectAuthGuardAsWhere(db, injectTarget._count.select[field], fieldInfo.type, 'read');
}
}
// collect filter conditions that should be hoisted to the toplevel
const hoistedConditions: any[] = [];
for (const field of getModelFields(injectTarget)) {
if (injectTarget[field] === false) {
continue;
}
const fieldInfo = resolveField(this.modelMeta, model, field);
if (!fieldInfo || !fieldInfo.isDataModel) {
// only care about relation fields
continue;
}
let hoisted: any;
if (
fieldInfo.isArray ||
// Injecting where at include/select level for nullable to-one relation is supported since Prisma 4.8.0
// https://github.com/prisma/prisma/discussions/20350
fieldInfo.isOptional
) {
if (typeof injectTarget[field] !== 'object') {
injectTarget[field] = {};
}
// inject extra condition for to-many or nullable to-one relation
this.injectAuthGuardAsWhere(db, injectTarget[field], fieldInfo.type, 'read');
// recurse
const subHoisted = this.injectNestedReadConditions(db, fieldInfo.type, injectTarget[field]);
if (subHoisted.length > 0) {
// we can convert it to a where at this level
injectTarget[field].where = this.and(injectTarget[field].where, ...subHoisted);
}
} else {
// hoist non-nullable to-one filter to the parent level
let injected = this.safeClone(injectTarget[field]);
if (typeof injected !== 'object') {
injected = {};
}
this.injectAuthGuardAsWhere(db, injected, fieldInfo.type, 'read');
hoisted = injected.where;
// recurse
const subHoisted = this.injectNestedReadConditions(db, fieldInfo.type, injectTarget[field]);
if (subHoisted.length > 0) {
hoisted = this.and(hoisted, ...subHoisted);
}
}
if (hoisted && !this.isTrue(hoisted)) {
hoistedConditions.push({ [field]: hoisted });
}
}
return hoistedConditions;
}
/**
* Given a model and a unique filter, checks the operation is allowed by policies and field validations.
* Rejects with an error if not allowed.
*/
async checkPolicyForUnique(
model: string,
uniqueFilter: any,
operation: PolicyOperationKind,
db: CrudContract,
args: any,
preValue?: any
) {
let guard = this.getAuthGuard(db, model, operation, preValue);
if (this.isFalse(guard) && !this.hasOverrideAuthGuard(model, operation)) {
throw this.deniedByPolicy(
model,
operation,
`entity ${formatObject(uniqueFilter, false)} failed policy check`,
CrudFailureReason.ACCESS_POLICY_VIOLATION
);
}
let entityChecker: EntityChecker | undefined;
if (operation === 'update' && args) {
// merge field-level policy guards
const fieldUpdateGuard = this.getFieldUpdateGuards(db, model, args);
if (fieldUpdateGuard.rejectedByField) {
// rejected
throw this.deniedByPolicy(
model,
'update',
`entity ${formatObject(uniqueFilter, false)} failed update policy check for field "${
fieldUpdateGuard.rejectedByField
}"`,
CrudFailureReason.ACCESS_POLICY_VIOLATION
);
}
if (fieldUpdateGuard.guard) {
// merge field-level guard with AND
guard = this.and(guard, fieldUpdateGuard.guard);
}
if (fieldUpdateGuard.overrideGuard) {
// merge field-level override guard with OR
guard = this.or(guard, fieldUpdateGuard.overrideGuard);
}
// field-level entity checker
entityChecker = fieldUpdateGuard.entityChecker;
}
// Zod schema is to be checked for "create" and "postUpdate"
const schema = ['create', 'postUpdate'].includes(operation) ? this.getZodSchema(model) : undefined;
// combine field-level entity checker with model-level
const modelEntityChecker = this.getEntityChecker(model, operation);
entityChecker = this.combineEntityChecker(entityChecker, modelEntityChecker, 'and');
if (this.isTrue(guard) && !schema && !entityChecker) {
// unconditionally allowed
return;
}
let select = schema
? // need to validate against schema, need to fetch all fields
undefined
: // only fetch id fields
this.makeIdSelection(model);
if (entityChecker?.selector) {
if (!select) {
select = this.makeAllScalarFieldSelect(model);
}
select = { ...select, ...entityChecker.selector };
}
let where = this.safeClone(uniqueFilter);
// query args may have be of combined-id form, need to flatten it to call findFirst
this.flattenGeneratedUniqueField(model, where);
// query with policy guard
where = this.and(where, guard);
const query = { select, where };
if (this.shouldLogQuery) {
this.logger.info(`[policy] checking ${model} for ${operation}, \`findFirst\`:\n${formatObject(query)}`);
}
const result = await db[model].findFirst(query);
if (!result) {
throw this.deniedByPolicy(
model,
operation,
`entity ${formatObject(uniqueFilter, false)} failed policy check`,
CrudFailureReason.ACCESS_POLICY_VIOLATION
);
}
if (entityChecker) {
if (this.logger.enabled('info')) {
this.logger.info(`[policy] running entity checker on ${model} for ${operation}`);
}
if (!entityChecker.func(result, { user: this.user, preValue })) {
throw this.deniedByPolicy(
model,
operation,
`entity ${formatObject(uniqueFilter, false)} failed policy check`,
CrudFailureReason.ACCESS_POLICY_VIOLATION
);
}
}
if (schema) {
// TODO: push down schema check to the database
this.validateZodSchema(model, undefined, result, true, (err) => {
throw this.deniedByPolicy(
model,
operation,
`entity ${formatObject(uniqueFilter, false)} failed validation: [${fromZodError(err)}]`,
CrudFailureReason.DATA_VALIDATION_VIOLATION,
err
);
});
}
}
getEntityChecker(model: string, operation: PolicyOperationKind, field?: string) {
const def = this.getModelPolicyDef(model);
if (field) {
return def.fieldLevel?.[operation as 'read' | 'update']?.[field]?.entityChecker;
} else {
return def.modelLevel[operation].entityChecker;
}
}
getUpdateOverrideEntityCheckerForField(model: string, field: string) {
const def = this.getModelPolicyDef(model);
return def.fieldLevel?.update?.[field]?.overrideEntityChecker;
}
private getFieldReadGuards(db: CrudContract, model: string, args: { select?: any; include?: any }) {
const allFields = Object.values(getFields(this.modelMeta, model));
// all scalar fields by default
let fields = allFields.filter((f) => !f.isDataModel);
if (args.select) {
// explicitly selected fields
fields = allFields.filter((f) => args.select?.[f.name] === true);
} else if (args.include) {
// included relations
fields.push(...allFields.filter((f) => !fields.includes(f) && args.include[f.name]));
}
if (fields.length === 0) {
// this can happen if only selecting pseudo fields like "_count"
return undefined;
}
const allFieldGuards = fields.map((field) => this.getFieldOverrideReadAuthGuard(db, model, field.name));
return this.and(...allFieldGuards);
}
private getFieldUpdateGuards(db: CrudContract, model: string, args: any) {
const allFieldGuards = [];
const allOverrideFieldGuards = [];
let entityChecker: EntityChecker | undefined;
for (const [field, value] of Object.entries<any>(args.data ?? args)) {
if (typeof value === 'undefined') {
continue;
}
const fieldInfo = resolveField(this.modelMeta, model, field);