-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathhandler.ts
1754 lines (1488 loc) · 71.6 KB
/
handler.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 { lowerCaseFirst } from 'lower-case-first';
import invariant from 'tiny-invariant';
import { upperCaseFirst } from 'upper-case-first';
import { fromZodError } from 'zod-validation-error';
import { CrudFailureReason } from '../../../constants';
import {
ModelDataVisitor,
NestedWriteVisitor,
NestedWriteVisitorContext,
enumerate,
getIdFields,
getModelInfo,
requireField,
resolveField,
type FieldInfo,
type ModelMeta,
} from '../../../cross';
import { EnhancementContext, PolicyOperationKind, type CrudContract, type DbClientContract } from '../../../types';
import type { InternalEnhancementOptions } from '../create-enhancement';
import { Logger } from '../logger';
import { createDeferredPromise, createFluentPromise } from '../promise';
import { PrismaProxyHandler } from '../proxy';
import { QueryUtils } from '../query-utils';
import type { EntityCheckerFunc, PermissionCheckArgs } from '../types';
import { formatObject, isUnsafeMutate, prismaClientValidationError } from '../utils';
import { checkPermission } from './check-utils';
import { PolicyUtil } from './policy-utils';
// a record for post-write policy check
type PostWriteCheckRecord = {
model: string;
operation: PolicyOperationKind;
uniqueFilter: any;
preValue?: any;
};
type FindOperations = 'findUnique' | 'findUniqueOrThrow' | 'findFirst' | 'findFirstOrThrow' | 'findMany';
/**
* Prisma proxy handler for injecting access policy check.
*/
export class PolicyProxyHandler<DbClient extends DbClientContract> implements PrismaProxyHandler {
private readonly logger: Logger;
private readonly policyUtils: PolicyUtil;
private readonly model: string;
private readonly modelMeta: ModelMeta;
private readonly prismaModule: any;
private readonly queryUtils: QueryUtils;
constructor(
private readonly prisma: DbClient,
model: string,
private readonly options: InternalEnhancementOptions,
private readonly context?: EnhancementContext
) {
this.logger = new Logger(prisma);
this.model = lowerCaseFirst(model);
({ modelMeta: this.modelMeta, prismaModule: this.prismaModule } = options);
this.policyUtils = new PolicyUtil(prisma, options, context, this.shouldLogQuery);
this.queryUtils = new QueryUtils(prisma, options);
}
private get modelClient() {
return this.prisma[this.model];
}
//#region Find
// find operations behaves as if the entities that don't match access policies don't exist
findUnique(args: any) {
if (!args) {
throw prismaClientValidationError(this.prisma, this.prismaModule, 'query argument is required');
}
if (!args.where) {
throw prismaClientValidationError(
this.prisma,
this.prismaModule,
'where field is required in query argument'
);
}
return this.findWithFluent('findUnique', args, () => null);
}
findUniqueOrThrow(args: any) {
if (!args) {
throw prismaClientValidationError(this.prisma, this.prismaModule, 'query argument is required');
}
if (!args.where) {
throw prismaClientValidationError(
this.prisma,
this.prismaModule,
'where field is required in query argument'
);
}
return this.findWithFluent('findUniqueOrThrow', args, () => {
throw this.policyUtils.notFound(this.model);
});
}
findFirst(args?: any) {
return this.findWithFluent('findFirst', args, () => null);
}
findFirstOrThrow(args: any) {
return this.findWithFluent('findFirstOrThrow', args, () => {
throw this.policyUtils.notFound(this.model);
});
}
findMany(args?: any) {
return createDeferredPromise<unknown[]>(() => this.doFind(args, 'findMany', () => [], true));
}
// make a find query promise with fluent API call stubs installed
private findWithFluent(method: FindOperations, args: any, handleRejection: () => any) {
args = this.policyUtils.safeClone(args);
return createFluentPromise(
() => this.doFind(args, method, handleRejection),
args,
this.options.modelMeta,
this.model
);
}
private async doFind(args: any, actionName: FindOperations, handleRejection: () => any, isList: boolean = false) {
const origArgs = args;
const _args = this.policyUtils.safeClone(args);
if (!this.policyUtils.injectForReadOrList(this.prisma, this.model, _args, isList)) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`${actionName}\` ${this.model}: unconditionally denied`);
}
return handleRejection();
}
this.policyUtils.injectReadCheckSelect(this.model, _args);
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`${actionName}\` ${this.model}:\n${formatObject(_args)}`);
}
const result = await this.modelClient[actionName](_args);
return this.policyUtils.postProcessForRead(result, this.model, origArgs);
}
//#endregion
//#region Create
create(args: any) {
if (!args) {
throw prismaClientValidationError(this.prisma, this.prismaModule, 'query argument is required');
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.prismaModule,
'data field is required in query argument'
);
}
return createDeferredPromise(async () => {
this.policyUtils.tryReject(this.prisma, this.model, 'create');
const origArgs = args;
args = this.policyUtils.safeClone(args);
// static input policy check for top-level create data
const inputCheck = this.policyUtils.checkInputGuard(this.model, args.data, 'create');
if (inputCheck === false) {
throw this.policyUtils.deniedByPolicy(
this.model,
'create',
undefined,
CrudFailureReason.ACCESS_POLICY_VIOLATION
);
}
const hasNestedCreateOrConnect = await this.hasNestedCreateOrConnect(args);
const { result, error } = await this.queryUtils.transaction(this.prisma, async (tx) => {
if (
// MUST check true here since inputCheck can be undefined (meaning static input check not possible)
inputCheck === true &&
// simple create: no nested create/connect
!hasNestedCreateOrConnect
) {
// there's no nested write and we've passed input check, proceed with the create directly
// validate zod schema if any
args.data = this.validateCreateInputSchema(this.model, args.data);
// make a create args only containing data and ID selection
const createArgs: any = { data: args.data, select: this.policyUtils.makeIdSelection(this.model) };
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`create\` ${this.model}: ${formatObject(createArgs)}`);
}
const result = await tx[this.model].create(createArgs);
// filter the read-back data
return this.policyUtils.readBack(tx, this.model, 'create', args, result);
} else {
// proceed with a complex create and collect post-write checks
const { result, postWriteChecks } = await this.doCreate(this.model, args, tx);
// execute post-write checks
await this.runPostWriteChecks(postWriteChecks, tx);
// filter the read-back data
return this.policyUtils.readBack(tx, this.model, 'create', origArgs, result);
}
});
if (error) {
throw error;
} else {
return result;
}
});
}
// create with nested write
private async doCreate(model: string, args: any, db: CrudContract) {
// record id fields involved in the nesting context
const idSelections: Array<{ path: FieldInfo[]; ids: string[] }> = [];
const pushIdFields = (model: string, context: NestedWriteVisitorContext) => {
const idFields = getIdFields(this.modelMeta, model);
idSelections.push({
path: context.nestingPath.map((p) => p.field).filter((f): f is FieldInfo => !!f),
ids: idFields.map((f) => f.name),
});
};
// create a string key that uniquely identifies an entity
const getEntityKey = (model: string, ids: any) =>
`${upperCaseFirst(model)}#${Object.keys(ids)
.sort()
.map((f) => `${f}:${ids[f]?.toString()}`)
.join('_')}`;
// record keys of entities that are connected instead of created
const connectedEntities = new Set<string>();
// visit the create payload
const visitor = new NestedWriteVisitor(this.modelMeta, {
create: async (model, args, context) => {
const validateResult = this.validateCreateInputSchema(model, args);
if (validateResult !== args) {
this.policyUtils.replace(args, validateResult);
}
pushIdFields(model, context);
},
createMany: async (model, args, context) => {
enumerate(args.data).forEach((item) => {
const r = this.validateCreateInputSchema(model, item);
if (r !== item) {
this.policyUtils.replace(item, r);
}
});
pushIdFields(model, context);
},
connectOrCreate: async (model, args, context) => {
if (!args.where) {
throw this.policyUtils.validationError(`'where' field is required for connectOrCreate`);
}
if (args.create) {
args.create = this.validateCreateInputSchema(model, args.create);
}
const existing = await this.policyUtils.checkExistence(db, model, args.where);
if (existing) {
// connect case
if (context.field?.backLink) {
const backLinkField = resolveField(this.modelMeta, model, context.field.backLink);
if (backLinkField?.isRelationOwner) {
// the target side of relation owns the relation,
// check if it's updatable
await this.policyUtils.checkPolicyForUnique(model, args.where, 'update', db, args);
}
}
this.mergeToParent(context.parent, 'connect', args.where);
// record the key of connected entities so we can avoid validating them later
connectedEntities.add(getEntityKey(model, existing));
} else {
// create case
pushIdFields(model, context);
// create a new "create" clause at the parent level
this.mergeToParent(context.parent, 'create', args.create);
}
// remove the connectOrCreate clause
this.removeFromParent(context.parent, 'connectOrCreate', args);
// return false to prevent visiting the nested payload
return false;
},
connect: async (model, args, context) => {
if (!args || typeof args !== 'object' || Object.keys(args).length === 0) {
throw this.policyUtils.validationError(`'connect' field must be an non-empty object`);
}
if (context.field?.backLink) {
const backLinkField = resolveField(this.modelMeta, model, context.field.backLink);
if (backLinkField?.isRelationOwner) {
// check existence
await this.policyUtils.checkExistence(db, model, args, true);
// the target side of relation owns the relation,
// check if it's updatable
await this.policyUtils.checkPolicyForUnique(model, args, 'update', db, args);
}
}
},
});
await visitor.visit(model, 'create', args);
// build the final "select" clause including all nested ID fields
let select: any = undefined;
if (idSelections.length > 0) {
select = {};
idSelections.forEach(({ path, ids }) => {
let curr = select;
for (const p of path) {
if (!curr[p.name]) {
curr[p.name] = { select: {} };
}
curr = curr[p.name].select;
}
Object.assign(curr, ...ids.map((f) => ({ [f]: true })));
});
}
// proceed with the create
const createArgs = { data: args.data, select };
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`create\` ${model}: ${formatObject(createArgs)}`);
}
const result = await db[model].create(createArgs);
// post create policy check for the top-level and nested creates
const postCreateChecks = new Map<string, PostWriteCheckRecord>();
// visit the create result and collect entities that need to be post-checked
const modelDataVisitor = new ModelDataVisitor(this.modelMeta);
modelDataVisitor.visit(model, result, (model, _data, scalarData) => {
const key = getEntityKey(model, scalarData);
// only check if entity is created, not connected
if (!connectedEntities.has(key) && !postCreateChecks.has(key)) {
const idFields = this.policyUtils.getIdFieldValues(model, scalarData);
postCreateChecks.set(key, { model, operation: 'create', uniqueFilter: idFields });
}
});
// return only the ids of the top-level entity
const ids = this.policyUtils.getEntityIds(model, result);
return { result: ids, postWriteChecks: [...postCreateChecks.values()] };
}
// Checks if the given create payload has nested create or connect
private async hasNestedCreateOrConnect(args: any) {
let hasNestedCreateOrConnect = false;
const visitor = new NestedWriteVisitor(this.modelMeta, {
async create(_model, _args, context) {
if (context.field) {
hasNestedCreateOrConnect = true;
return false;
} else {
return true;
}
},
async connect() {
hasNestedCreateOrConnect = true;
return false;
},
async connectOrCreate() {
hasNestedCreateOrConnect = true;
return false;
},
async createMany() {
hasNestedCreateOrConnect = true;
return false;
},
});
await visitor.visit(this.model, 'create', args);
return hasNestedCreateOrConnect;
}
// Validates the given create payload against Zod schema if any
private validateCreateInputSchema(model: string, data: any) {
if (!data) {
return data;
}
return this.policyUtils.validateZodSchema(model, 'create', data, false, (err) => {
throw this.policyUtils.deniedByPolicy(
model,
'create',
`input failed validation: ${fromZodError(err)}`,
CrudFailureReason.DATA_VALIDATION_VIOLATION,
err
);
});
}
createMany(args: { data: any; skipDuplicates?: boolean }) {
if (!args) {
throw prismaClientValidationError(this.prisma, this.prismaModule, 'query argument is required');
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.prismaModule,
'data field is required in query argument'
);
}
return createDeferredPromise(async () => {
this.policyUtils.tryReject(this.prisma, this.model, 'create');
args = this.policyUtils.safeClone(args);
// `createManyAndReturn` may need to be converted to regular `create`s
const shouldConvertToCreate = this.preprocessCreateManyPayload(args);
if (!shouldConvertToCreate) {
// direct `createMany`
return this.modelClient.createMany(args);
} else {
// create entities in a transaction with post-create checks
return this.queryUtils.transaction(this.prisma, async (tx) => {
const { result, postWriteChecks } = await this.doCreateMany(this.model, args, tx, 'createMany');
// post-create check
await this.runPostWriteChecks(postWriteChecks, tx);
return { count: result.length };
});
}
});
}
createManyAndReturn(args: { data: any; select?: any; skipDuplicates?: boolean }) {
if (!args) {
throw prismaClientValidationError(this.prisma, this.prismaModule, 'query argument is required');
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.prismaModule,
'data field is required in query argument'
);
}
return createDeferredPromise(async () => {
this.policyUtils.tryReject(this.prisma, this.model, 'create');
const origArgs = args;
args = this.policyUtils.safeClone(args);
// `createManyAndReturn` may need to be converted to regular `create`s
const shouldConvertToCreate = this.preprocessCreateManyPayload(args);
let result: { result: unknown; error?: Error }[];
if (!shouldConvertToCreate) {
// direct `createManyAndReturn`
const created = await this.modelClient.createManyAndReturn(args);
// process read-back
result = await Promise.all(
created.map((item) => this.policyUtils.readBack(this.prisma, this.model, 'create', origArgs, item))
);
} else {
// create entities in a transaction with post-create checks
result = await this.queryUtils.transaction(this.prisma, async (tx) => {
const { result: created, postWriteChecks } = await this.doCreateMany(
this.model,
args,
tx,
'createManyAndReturn'
);
// post-create check
await this.runPostWriteChecks(postWriteChecks, tx);
// process read-back
return Promise.all(
created.map((item) => this.policyUtils.readBack(tx, this.model, 'create', origArgs, item))
);
});
}
// throw read-back error if any of create result read-back fails
const error = result.find((r) => !!r.error)?.error;
if (error) {
throw error;
} else {
return result.map((r) => r.result);
}
});
}
/**
* Preprocess the payload of `createMany` and `createManyAndReturn` and update in place if needed.
* @returns `true` if the operation should be converted to regular `create`s; false otherwise.
*/
private preprocessCreateManyPayload(args: { data: any; select?: any; skipDuplicates?: boolean }) {
if (!args) {
return false;
}
// if post-create check is needed
const needPostCreateCheck = this.validateCreateInput(args);
// if the payload has any relation fields. Note that other enhancements (`withDefaultInAuth` for now)
// can introduce relation fields into the payload
let hasRelationFields = false;
if (args.data) {
hasRelationFields = this.hasRelationFieldsInPayload(this.model, args.data);
}
return needPostCreateCheck || hasRelationFields;
}
private hasRelationFieldsInPayload(model: string, payload: any) {
const modelInfo = getModelInfo(this.modelMeta, model);
if (!modelInfo) {
return false;
}
for (const item of enumerate(payload)) {
for (const field of Object.keys(item)) {
const fieldInfo = resolveField(this.modelMeta, model, field);
if (fieldInfo?.isDataModel) {
return true;
}
}
}
return false;
}
private validateCreateInput(args: { data: any; skipDuplicates?: boolean | undefined }) {
let needPostCreateCheck = false;
for (const item of enumerate(args.data)) {
const validationResult = this.validateCreateInputSchema(this.model, item);
if (validationResult !== item) {
this.policyUtils.replace(item, validationResult);
}
const inputCheck = this.policyUtils.checkInputGuard(this.model, item, 'create');
if (inputCheck === false) {
// unconditionally deny
throw this.policyUtils.deniedByPolicy(
this.model,
'create',
undefined,
CrudFailureReason.ACCESS_POLICY_VIOLATION
);
} else if (inputCheck === true) {
// unconditionally allow
} else if (inputCheck === undefined) {
// static policy check is not possible, need to do post-create check
needPostCreateCheck = true;
}
}
return needPostCreateCheck;
}
private async doCreateMany(
model: string,
args: { data: any; skipDuplicates?: boolean },
db: CrudContract,
action: 'createMany' | 'createManyAndReturn'
) {
// We can't call the native "createMany" because we can't get back what was created
// for post-create checks. Instead, do a "create" for each item and collect the results.
let createResult = await Promise.all(
enumerate(args.data).map(async (item) => {
if (args.skipDuplicates) {
if (await this.hasDuplicatedUniqueConstraint(model, item, undefined, db)) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`createMany\` skipping duplicate ${formatObject(item)}`);
}
return undefined;
}
}
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`create\` for \`${action}\` ${model}: ${formatObject(item)}`);
}
return await db[model].create({ select: this.policyUtils.makeIdSelection(model), data: item });
})
);
// filter undefined values due to skipDuplicates
createResult = createResult.filter((p) => !!p);
return {
result: createResult,
postWriteChecks: createResult.map((item) => ({
model,
operation: 'create' as PolicyOperationKind,
uniqueFilter: item,
})),
};
}
private async hasDuplicatedUniqueConstraint(model: string, createData: any, upstreamQuery: any, db: CrudContract) {
// check unique constraint conflicts
// we can't rely on try/catch/ignore constraint violation error: https://github.com/prisma/prisma/issues/20496
// TODO: for simple cases we should be able to translate it to an `upsert` with empty `update` payload
// for each unique constraint, check if the input item has all fields set, and if so, check if
// an entity already exists, and ignore accordingly
const uniqueConstraints = this.policyUtils.getUniqueConstraints(model);
for (const constraint of Object.values(uniqueConstraints)) {
// the unique filter used to check existence
const uniqueFilter: any = {};
// unique constraint fields not covered yet
const remainingConstraintFields = new Set<string>(constraint.fields);
// collect constraint fields from the create data
for (const [k, v] of Object.entries<any>(createData)) {
if (v === undefined) {
continue;
}
if (remainingConstraintFields.has(k)) {
uniqueFilter[k] = v;
remainingConstraintFields.delete(k);
}
}
// collect constraint fields from the upstream query
if (upstreamQuery) {
for (const [k, v] of Object.entries<any>(upstreamQuery)) {
if (v === undefined) {
continue;
}
if (remainingConstraintFields.has(k)) {
uniqueFilter[k] = v;
remainingConstraintFields.delete(k);
continue;
}
// check if the upstream query contains a relation field which covers
// a foreign key field constraint
const fieldInfo = requireField(this.modelMeta, model, k);
if (!fieldInfo.isDataModel) {
// only care about relation fields
continue;
}
// merge the upstream query into the unique filter
uniqueFilter[k] = v;
// mark the corresponding foreign key fields as covered
const fkMapping = fieldInfo.foreignKeyMapping ?? {};
for (const fk of Object.values(fkMapping)) {
remainingConstraintFields.delete(fk);
}
}
}
if (remainingConstraintFields.size === 0) {
// all constraint fields set, check existence
const existing = await this.policyUtils.checkExistence(db, model, uniqueFilter);
if (existing) {
return true;
}
}
}
return false;
}
//#endregion
//#region Update & Upsert
// "update" and "upsert" work against unique entity, so we actively rejects the request if the
// entity fails policy check
//
// "updateMany" works against a set of entities, entities not passing policy check are silently
// ignored
update(args: any) {
if (!args) {
throw prismaClientValidationError(this.prisma, this.prismaModule, 'query argument is required');
}
if (!args.where) {
throw prismaClientValidationError(
this.prisma,
this.prismaModule,
'where field is required in query argument'
);
}
if (!args.data) {
throw prismaClientValidationError(
this.prisma,
this.prismaModule,
'data field is required in query argument'
);
}
return createDeferredPromise(async () => {
args = this.policyUtils.safeClone(args);
const { result, error } = await this.queryUtils.transaction(this.prisma, async (tx) => {
// proceed with nested writes and collect post-write checks
const { result, postWriteChecks } = await this.doUpdate(args, tx);
// post-write check
await this.runPostWriteChecks(postWriteChecks, tx);
// filter the read-back data
return this.policyUtils.readBack(tx, this.model, 'update', args, result);
});
if (error) {
throw error;
} else {
return result;
}
});
}
private async doUpdate(args: any, db: CrudContract) {
// collected post-update checks
const postWriteChecks: PostWriteCheckRecord[] = [];
// registers a post-update check task
const _registerPostUpdateCheck = async (
model: string,
preUpdateLookupFilter: any,
postUpdateLookupFilter: any
) => {
// both "post-update" rules and Zod schemas require a post-update check
if (this.policyUtils.hasAuthGuard(model, 'postUpdate') || this.policyUtils.getZodSchema(model)) {
// select pre-update field values
let preValue: any;
const preValueSelect = this.policyUtils.getPreValueSelect(model);
if (preValueSelect && Object.keys(preValueSelect).length > 0) {
preValue = await db[model].findFirst({ where: preUpdateLookupFilter, select: preValueSelect });
}
postWriteChecks.push({
model,
operation: 'postUpdate',
uniqueFilter: postUpdateLookupFilter,
preValue,
});
}
};
// We can't let the native "update" to handle nested "create" because we can't get back what
// was created for doing post-update checks.
// Instead, handle nested create inside update as an atomic operation that creates an entire
// subtree (containing nested creates/connects)
const _create = async (model: string, args: any, context: NestedWriteVisitorContext) => {
let createData = args;
if (context.field?.backLink) {
// Check if the create payload contains any "unsafe" assignment:
// assign id or foreign key fields.
//
// The reason why we need to do that is Prisma's mutations payload
// structure has two mutually exclusive forms for safe and unsafe
// operations. E.g.:
// - safe: { data: { user: { connect: { id: 1 }} } }
// - unsafe: { data: { userId: 1 } }
const unsafe = isUnsafeMutate(model, args, this.modelMeta);
// handles the connection to upstream entity
const reversedQuery = this.policyUtils.buildReversedQuery(context, true, unsafe);
if ((!unsafe || context.field.isRelationOwner) && reversedQuery[context.field.backLink]) {
// if mutation is safe, or current field owns the relation (so the other side has no fk),
// and the reverse query contains the back link, then we can build a "connect" with it
createData = {
...createData,
[context.field.backLink]: {
connect: reversedQuery[context.field.backLink],
},
};
} else {
// otherwise, the reverse query should be translated to foreign key setting
// and merged to the create data
const backLinkField = this.requireBackLink(context.field);
invariant(backLinkField.foreignKeyMapping);
// try to extract foreign key values from the reverse query
let fkValues = Object.values(backLinkField.foreignKeyMapping).reduce<any>((obj, fk) => {
obj[fk] = reversedQuery[fk];
return obj;
}, {});
if (Object.values(fkValues).every((v) => v !== undefined)) {
// all foreign key values are available, merge them to the create data
createData = {
...createData,
...fkValues,
};
} else {
// some foreign key values are missing, need to look up the upstream entity,
// this can happen when the upstream entity doesn't have a unique where clause,
// for example when it's nested inside a one-to-one update
const upstreamQuery = {
where: reversedQuery[backLinkField.name],
select: this.policyUtils.makeIdSelection(backLinkField.type),
};
// fetch the upstream entity
if (this.shouldLogQuery) {
this.logger.info(
`[policy] \`findUniqueOrThrow\` ${model}: looking up upstream entity of ${
backLinkField.type
}, ${formatObject(upstreamQuery)}`
);
}
const upstreamEntity = await this.prisma[backLinkField.type].findUniqueOrThrow(upstreamQuery);
// map ids to foreign keys
fkValues = Object.entries(backLinkField.foreignKeyMapping).reduce<any>((obj, [id, fk]) => {
obj[fk] = upstreamEntity[id];
return obj;
}, {});
// merge them to the create data
createData = { ...createData, ...fkValues };
}
}
}
// proceed with the create and collect post-create checks
const { postWriteChecks: checks, result } = await this.doCreate(model, { data: createData }, db);
postWriteChecks.push(...checks);
return result;
};
const _createMany = async (
model: string,
args: { data: any; skipDuplicates?: boolean },
context: NestedWriteVisitorContext
) => {
for (const item of enumerate(args.data)) {
if (args.skipDuplicates) {
// get a reversed query to include fields inherited from upstream mutation,
// it'll be merged with the create payload for unique constraint checking
const upstreamQuery = this.policyUtils.buildReversedQuery(context);
if (await this.hasDuplicatedUniqueConstraint(model, item, upstreamQuery, db)) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`createMany\` skipping duplicate ${formatObject(item)}`);
}
continue;
}
}
await _create(model, item, context);
}
};
const _connectDisconnect = async (
model: string,
args: any,
context: NestedWriteVisitorContext,
operation: 'connect' | 'disconnect'
) => {
if (context.field?.backLink) {
const backLinkField = this.policyUtils.getModelField(model, context.field.backLink);
if (backLinkField?.isRelationOwner) {
let uniqueFilter = args;
if (operation === 'disconnect') {
// disconnect filter is not unique, need to build a reversed query to
// locate the entity and use its id fields as unique filter
const reversedQuery = this.policyUtils.buildReversedQuery(context);
const found = await db[model].findUnique({
where: reversedQuery,
select: this.policyUtils.makeIdSelection(model),
});
uniqueFilter = found && this.policyUtils.getIdFieldValues(model, found);
}
// update happens on the related model, require updatable,
// translate args to foreign keys so field-level policies can be checked
const checkArgs: any = {};
if (args && typeof args === 'object' && backLinkField.foreignKeyMapping) {
for (const key of Object.keys(args)) {
const fk = backLinkField.foreignKeyMapping[key];
if (fk) {
checkArgs[fk] = args[key];
}
}
}
// `uniqueFilter` can be undefined if the entity to be disconnected doesn't exist
if (uniqueFilter) {
// check for update
await this.policyUtils.checkPolicyForUnique(model, uniqueFilter, 'update', db, checkArgs);
// register post-update check
await _registerPostUpdateCheck(model, uniqueFilter, uniqueFilter);
}
}
}
};
// visit nested writes
const visitor = new NestedWriteVisitor(this.modelMeta, {
update: async (model, args, context) => {
// build a unique query including upstream conditions
const uniqueFilter = this.policyUtils.buildReversedQuery(context);
// handle not-found
const existing = await this.policyUtils.checkExistence(db, model, uniqueFilter, true);
// check if the update actually writes to this model
let thisModelUpdate = false;
const updatePayload = (args as any).data ?? args;
const validatedPayload = this.validateUpdateInputSchema(model, updatePayload);
if (validatedPayload !== updatePayload) {
this.policyUtils.replace(updatePayload, validatedPayload);
}
if (updatePayload) {
for (const key of Object.keys(updatePayload)) {
const field = resolveField(this.modelMeta, model, key);
if (field) {
if (!field.isDataModel) {
// scalar field, require this model to be updatable
thisModelUpdate = true;
break;
} else if (field.isRelationOwner) {
// relation is being updated and this model owns foreign key, require updatable
thisModelUpdate = true;
break;
}
}
}
}
if (thisModelUpdate) {
this.policyUtils.tryReject(db, this.model, 'update');
// check pre-update guard
await this.policyUtils.checkPolicyForUnique(model, uniqueFilter, 'update', db, args);
// handle the case where id fields are updated
const _args: any = args;
const updatePayload = _args.data && typeof _args.data === 'object' ? _args.data : _args;
const postUpdateIds = this.calculatePostUpdateIds(model, existing, updatePayload);
// register post-update check
await _registerPostUpdateCheck(model, existing, postUpdateIds);
}
},
updateMany: async (model, args, context) => {
// prepare for post-update check
if (this.policyUtils.hasAuthGuard(model, 'postUpdate') || this.policyUtils.getZodSchema(model)) {
let select = this.policyUtils.makeIdSelection(model);
const preValueSelect = this.policyUtils.getPreValueSelect(model);
if (preValueSelect) {
select = { ...select, ...preValueSelect };
}
const reversedQuery = this.policyUtils.buildReversedQuery(context);
const currentSetQuery = { select, where: reversedQuery };
this.policyUtils.injectAuthGuardAsWhere(db, currentSetQuery, model, 'read');
if (this.shouldLogQuery) {
this.logger.info(
`[policy] \`findMany\` for post update check ${model}:\n${formatObject(currentSetQuery)}`
);
}
const currentSet = await db[model].findMany(currentSetQuery);
postWriteChecks.push(
...currentSet.map((preValue) => ({