-
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathpolicy-handler.ts
More file actions
1366 lines (1177 loc) · 53.4 KB
/
policy-handler.ts
File metadata and controls
1366 lines (1177 loc) · 53.4 KB
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
import { invariant } from '@zenstackhq/common-helpers';
import type { BaseCrudDialect, ClientContract, CRUD_EXT, ProceedKyselyQueryFunction } from '@zenstackhq/orm';
import { getCrudDialect, QueryUtils, RejectedByPolicyReason, SchemaUtils } from '@zenstackhq/orm';
import {
ExpressionUtils,
type BuiltinType,
type Expression,
type MemberExpression,
type SchemaDef,
} from '@zenstackhq/orm/schema';
import {
AliasNode,
BinaryOperationNode,
ColumnNode,
DeleteQueryNode,
expressionBuilder,
ExpressionWrapper,
FromNode,
IdentifierNode,
InsertQueryNode,
JoinNode,
OperationNodeTransformer,
OperatorNode,
ParensNode,
PrimitiveValueListNode,
ReferenceNode,
ReturningNode,
SelectAllNode,
SelectionNode,
SelectQueryNode,
sql,
TableNode,
UpdateQueryNode,
ValueNode,
ValuesNode,
WhereNode,
type Expression as KyselyExpression,
type OperationNode,
type QueryResult,
type RootOperationNode,
} from 'kysely';
import { match } from 'ts-pattern';
import { ColumnCollector } from './column-collector';
import { ExpressionTransformer } from './expression-transformer';
import type { Policy, PolicyOperation } from './types';
import {
buildIsFalse,
conjunction,
createRejectedByPolicyError,
createUnsupportedError,
disjunction,
falseNode,
getTableName,
isBeforeInvocation,
isTrueNode,
logicalNot,
trueNode,
} from './utils';
export type CrudQueryNode = SelectQueryNode | InsertQueryNode | UpdateQueryNode | DeleteQueryNode;
export type MutationQueryNode = InsertQueryNode | UpdateQueryNode | DeleteQueryNode;
type FieldLevelPolicyOperations = Exclude<CRUD_EXT, 'create' | 'delete'>;
export class PolicyHandler<Schema extends SchemaDef> extends OperationNodeTransformer {
private readonly dialect: BaseCrudDialect<Schema>;
private readonly eb = expressionBuilder<any, any>();
constructor(private readonly client: ClientContract<Schema>) {
super();
this.dialect = getCrudDialect(this.client.$schema, this.client.$options);
}
// #region main entry point
async handle(node: RootOperationNode, proceed: ProceedKyselyQueryFunction) {
if (!this.isCrudQueryNode(node)) {
// non-CRUD queries are not allowed
throw createRejectedByPolicyError(
undefined,
RejectedByPolicyReason.OTHER,
'non-CRUD queries are not allowed',
);
}
if (!this.isMutationQueryNode(node)) {
// transform and proceed with read directly
return proceed(this.transformNode(node));
}
const { mutationModel } = this.getMutationModel(node);
// reject non-existing model
this.tryRejectNonexistentModel(mutationModel);
// #region Pre mutation work
// create
if (InsertQueryNode.is(node)) {
await this.preCreateCheck(mutationModel, node, proceed);
}
// update
if (UpdateQueryNode.is(node)) {
await this.preUpdateCheck(mutationModel, node, proceed);
}
// post-update: load before-update entities if needed
const needsPostUpdateCheck = UpdateQueryNode.is(node) && this.hasPostUpdatePolicies(mutationModel);
let beforeUpdateInfo: Awaited<ReturnType<typeof this.loadBeforeUpdateEntities>> | undefined;
if (needsPostUpdateCheck) {
beforeUpdateInfo = await this.loadBeforeUpdateEntities(
mutationModel,
node.where,
proceed,
// force load pre-update entities if dialect doesn't support returning,
// so we can rely on pre-update ids to read back updated entities
!this.dialect.supportsReturning,
);
}
// #endregion
// #region mutation execution
const result = await proceed(this.transformNode(node));
// #endregion
// #region Post mutation work
if ((result.numAffectedRows ?? 0) > 0 && needsPostUpdateCheck) {
await this.postUpdateCheck(mutationModel, beforeUpdateInfo, result, proceed);
}
// #endregion
// #region Read back
if (!node.returning || this.onlyReturningId(node)) {
// no need to check read back
return this.postProcessMutationResult(result, node);
} else {
const readBackResult = await this.processReadBack(node, result, proceed);
if (readBackResult.rows.length !== result.rows.length) {
throw createRejectedByPolicyError(
mutationModel,
RejectedByPolicyReason.CANNOT_READ_BACK,
'result is not allowed to be read back',
);
}
return readBackResult;
}
// #endregion
}
private async preCreateCheck(mutationModel: string, node: InsertQueryNode, proceed: ProceedKyselyQueryFunction) {
const isManyToManyJoinTable = this.isManyToManyJoinTable(mutationModel);
let needCheckPreCreate = true;
// many-to-many join table is not a model so can't have policies on it
if (!isManyToManyJoinTable) {
// check constant policies
const constCondition = this.tryGetConstantPolicy(mutationModel, 'create');
if (constCondition === true) {
needCheckPreCreate = false;
} else if (constCondition === false) {
throw createRejectedByPolicyError(mutationModel, RejectedByPolicyReason.NO_ACCESS);
}
}
if (needCheckPreCreate) {
await this.enforcePreCreatePolicy(node, mutationModel, isManyToManyJoinTable, proceed);
}
}
private async preUpdateCheck(mutationModel: string, node: UpdateQueryNode, proceed: ProceedKyselyQueryFunction) {
// check if any rows will be filtered out by field-level update policies, and reject the whole update if so
const fieldsToUpdate =
node.updates
?.map((u) => (ColumnNode.is(u.column) ? u.column.column.name : undefined))
.filter((f): f is string => !!f) ?? [];
const fieldUpdatePolicies = fieldsToUpdate.map((f) => this.buildFieldPolicyFilter(mutationModel, f, 'update'));
// filter combining field-level update policies
const fieldLevelFilter = conjunction(this.dialect, fieldUpdatePolicies);
if (isTrueNode(fieldLevelFilter)) {
return;
}
// model-level update policy filter
const modelLevelFilter = this.buildPolicyFilter(mutationModel, undefined, 'update');
// filter combining model-level update policy and update where
const updateFilter = conjunction(this.dialect, [modelLevelFilter, node.where?.where ?? trueNode(this.dialect)]);
// build a query to count rows that will be rejected by field-level policies
// `SELECT COALESCE(SUM((not <fieldsFilter>) as integer), 0) AS $filteredCount WHERE <updateFilter> AND <rowFilter>`
const preUpdateCheckQuery = this.eb
.selectFrom(mutationModel)
.select((eb) =>
eb.fn
.coalesce(
eb.fn.sum(
this.dialect.castInt(new ExpressionWrapper(logicalNot(this.dialect, fieldLevelFilter))),
),
eb.lit(0),
)
.as('$filteredCount'),
)
.where(() => new ExpressionWrapper(updateFilter));
const preUpdateResult = await proceed(preUpdateCheckQuery.toOperationNode());
if (preUpdateResult.rows[0].$filteredCount > 0) {
throw createRejectedByPolicyError(
mutationModel,
RejectedByPolicyReason.NO_ACCESS,
'some rows cannot be updated due to field policies',
);
}
}
private async postUpdateCheck(
model: string,
beforeUpdateInfo: Awaited<ReturnType<typeof this.loadBeforeUpdateEntities>>,
updateResult: QueryResult<any>,
proceed: ProceedKyselyQueryFunction,
) {
let postUpdateRows: Record<string, unknown>[];
if (this.dialect.supportsReturning) {
// if dialect supports returning, use returned rows directly
postUpdateRows = updateResult.rows;
} else {
// otherwise, need to read back updated rows using pre-update ids
invariant(beforeUpdateInfo, 'beforeUpdateInfo must be defined for dialects not supporting returning');
const idConditions = this.buildIdConditions(model, beforeUpdateInfo!.rows);
const idFields = QueryUtils.requireIdFields(this.client.$schema, model);
const postUpdateQuery: SelectQueryNode = {
kind: 'SelectQueryNode',
from: FromNode.create([TableNode.create(model)]),
where: WhereNode.create(idConditions),
selections: idFields.map((field) => SelectionNode.create(ColumnNode.create(field))),
};
const postUpdateQueryResult = await proceed(postUpdateQuery);
postUpdateRows = postUpdateQueryResult.rows;
}
if (beforeUpdateInfo) {
// verify if before-update rows and post-update rows still id-match
if (beforeUpdateInfo.rows.length !== postUpdateRows.length) {
throw createRejectedByPolicyError(
model,
RejectedByPolicyReason.OTHER,
'Before-update and after-update rows do not match. If you have post-update policies on a model, updating id fields is not supported.',
);
}
const idFields = QueryUtils.requireIdFields(this.client.$schema, model);
for (const postRow of postUpdateRows) {
const beforeRow = beforeUpdateInfo.rows.find((r) => idFields.every((f) => r[f] === postRow[f]));
if (!beforeRow) {
throw createRejectedByPolicyError(
model,
RejectedByPolicyReason.OTHER,
'Before-update and after-update rows do not match. If you have post-update policies on a model, updating id fields is not supported.',
);
}
}
}
// entities updated filter
const idConditions = this.buildIdConditions(model, postUpdateRows);
// post-update policy filter
const postUpdateFilter = this.buildPolicyFilter(model, undefined, 'post-update');
// read the post-update row with filter applied
const eb = expressionBuilder<any, any>();
// before update table is joined if fields from `before()` are used in post-update policies
const needsBeforeUpdateJoin = !!beforeUpdateInfo?.fields;
let beforeUpdateTable: SelectQueryNode | undefined = undefined;
if (needsBeforeUpdateJoin) {
// create a `SELECT column1 as field1, column2 as field2, ... FROM (VALUES (...))` table for before-update rows
const fieldDefs = beforeUpdateInfo.fields!.map((name) =>
QueryUtils.requireField(this.client.$schema, model, name),
);
const rows = beforeUpdateInfo.rows.map((r) => beforeUpdateInfo!.fields!.map((f) => r[f]));
beforeUpdateTable = this.dialect.buildValuesTableSelect(fieldDefs, rows).toOperationNode();
}
const postUpdateQuery = eb
.selectFrom(model)
.select(() => [
eb(eb.fn('COUNT', [eb.lit(1)]), '=', Number(updateResult.numAffectedRows ?? 0)).as('$condition'),
])
.where(() => new ExpressionWrapper(conjunction(this.dialect, [idConditions, postUpdateFilter])))
.$if(needsBeforeUpdateJoin, (qb) =>
qb.leftJoin(
() => new ExpressionWrapper(beforeUpdateTable!).as('$before'),
(join) => {
const idFields = QueryUtils.requireIdFields(this.client.$schema, model);
return idFields.reduce((acc, f) => acc.onRef(`${model}.${f}`, '=', `$before.${f}`), join);
},
),
);
const postUpdateResult = await proceed(postUpdateQuery.toOperationNode());
if (!postUpdateResult.rows[0]?.$condition) {
throw createRejectedByPolicyError(
model,
RejectedByPolicyReason.NO_ACCESS,
'some or all updated rows failed to pass post-update policy check',
);
}
}
// #endregion
// #region Transformations
protected override transformSelectQuery(node: SelectQueryNode) {
if (!node.from) {
return super.transformSelectQuery(node);
}
// reject non-existing tables
this.tryRejectNonexistingTables(node.from.froms);
let result = super.transformSelectQuery(node);
const hasFieldLevelPolicies = node.from.froms.some((table) => {
const extractedTable = this.extractTableName(table);
if (extractedTable) {
return this.hasFieldLevelPolicies(extractedTable.model, 'read');
} else {
return false;
}
});
if (hasFieldLevelPolicies) {
// when a select query involves field-level policies, we build a nested query selecting all fields guarded with:
// CASE WHEN <field policy> THEN <field> ELSE NULL END
// model-level policies are also applied at this nested query level
const updatedFroms: OperationNode[] = [];
for (const table of result.from!.froms) {
const extractedTable = this.extractTableName(table);
if (extractedTable?.model && QueryUtils.getModel(this.client.$schema, extractedTable.model)) {
const { query } = this.createSelectAllFieldsWithPolicies(
extractedTable.model,
extractedTable.alias,
'read',
);
updatedFroms.push(query);
} else {
// keep the original from
updatedFroms.push(table);
}
}
result = { ...result, from: FromNode.create(updatedFroms) };
} else {
// when there's no field-level policies, we merge model-level policy filters into where clause directly
// for generating simpler SQL
let whereNode = result.where;
const policyFilter = this.createPolicyFilterForFrom(result.from);
if (policyFilter && !isTrueNode(policyFilter)) {
whereNode = WhereNode.create(
whereNode?.where ? conjunction(this.dialect, [whereNode.where, policyFilter]) : policyFilter,
);
}
result = { ...result, where: whereNode };
}
return result;
}
protected override transformJoin(node: JoinNode) {
const table = this.extractTableName(node.table);
if (!table) {
// unable to extract table name, can be a subquery, which will be handled when nested transformation happens
return super.transformJoin(node);
}
// reject non-existing model
this.tryRejectNonexistentModel(table.model);
if (!QueryUtils.getModel(this.client.$schema, table.model)) {
// not a defined model, could be m2m join table, keep as is
return super.transformJoin(node);
}
const result = super.transformJoin(node);
const { hasPolicies, query: nestedQuery } = this.createSelectAllFieldsWithPolicies(
table.model,
table.alias,
'read',
);
// join table has no policies, keep it as is
if (!hasPolicies) {
return result;
}
// otherwise replace it with the nested query guarded with policies
return {
...result,
table: nestedQuery,
};
}
protected override transformInsertQuery(node: InsertQueryNode) {
// pre-insert check is done in `handle()`
let processedNode = node;
let onConflict = node.onConflict;
if (onConflict?.updates) {
// for "on conflict do update", we need to apply policy filter to the "where" clause
const { mutationModel, alias } = this.getMutationModel(node);
const filter = this.buildPolicyFilter(mutationModel, alias, 'update');
if (onConflict.updateWhere) {
onConflict = {
...onConflict,
updateWhere: WhereNode.create(conjunction(this.dialect, [onConflict.updateWhere.where, filter])),
};
} else {
onConflict = {
...onConflict,
updateWhere: WhereNode.create(filter),
};
}
processedNode = { ...node, onConflict };
}
let onDuplicateKey = node.onDuplicateKey;
if (onDuplicateKey?.updates) {
// for "on duplicate key update", we need to wrap updates in IF(filter, newValue, oldValue)
// so that updates only happen when the policy filter is satisfied
const { mutationModel } = this.getMutationModel(node);
// Build the filter without alias, but will still contain model name as table reference
const filterWithTableRef = this.buildPolicyFilter(mutationModel, undefined, 'update');
// Strip table references from the filter since ON DUPLICATE KEY UPDATE doesn't support them
const filter = this.stripTableReferences(filterWithTableRef, mutationModel);
// transform each update to: IF(filter, newValue, oldValue)
const wrappedUpdates = onDuplicateKey.updates.map((update) => {
// For each column update, wrap it with IF condition
// IF(filter, newValue, columnName) - columnName references the existing row value
const columnName = ColumnNode.is(update.column) ? update.column.column.name : undefined;
if (!columnName) {
// keep original update if we can't extract column name
return update;
}
// Create the wrapped value: IF(filter, newValue, columnName)
// In MySQL's ON DUPLICATE KEY UPDATE context:
// - VALUES(col) = the value from the INSERT statement
// - col = the existing row value before update
const wrappedValue =
sql`IF(${new ExpressionWrapper(filter)}, ${new ExpressionWrapper(update.value)}, ${sql.ref(columnName)})`.toOperationNode();
return {
...update,
value: wrappedValue,
};
});
onDuplicateKey = {
...onDuplicateKey,
updates: wrappedUpdates,
};
processedNode = { ...processedNode, onDuplicateKey };
}
const result = super.transformInsertQuery(processedNode);
// if any field is to be returned, we select ID fields here which will be used
// for reading back post-insert
let returning = result.returning;
if (returning) {
const { mutationModel } = this.getMutationModel(node);
const idFields = QueryUtils.requireIdFields(this.client.$schema, mutationModel);
returning = ReturningNode.create(idFields.map((f) => SelectionNode.create(ColumnNode.create(f))));
}
return {
...result,
returning,
};
}
protected override transformUpdateQuery(node: UpdateQueryNode) {
const result = super.transformUpdateQuery(node);
const { mutationModel, alias } = this.getMutationModel(node);
let filter = this.buildPolicyFilter(mutationModel, alias, 'update');
if (node.from) {
// reject non-existing tables
this.tryRejectNonexistingTables(node.from.froms);
// for update with from (join), we need to merge join tables' policy filters to the "where" clause
const joinFilter = this.createPolicyFilterForFrom(node.from);
if (joinFilter) {
filter = conjunction(this.dialect, [filter, joinFilter]);
}
}
let returning = result.returning;
// regarding returning:
// 1. if fields are to be returned, we only select id fields here which will be used for reading back
// post-update
// 2. if there are post-update policies, we need to make sure id fields are selected for joining with
// before-update rows
if (this.dialect.supportsReturning && (returning || this.hasPostUpdatePolicies(mutationModel))) {
const idFields = QueryUtils.requireIdFields(this.client.$schema, mutationModel);
returning = ReturningNode.create(idFields.map((f) => SelectionNode.create(ColumnNode.create(f))));
}
return {
...result,
where: WhereNode.create(result.where ? conjunction(this.dialect, [result.where.where, filter]) : filter),
returning,
};
}
protected override transformDeleteQuery(node: DeleteQueryNode) {
const result = super.transformDeleteQuery(node);
const { mutationModel, alias } = this.getMutationModel(node);
let filter = this.buildPolicyFilter(mutationModel, alias, 'delete');
if (node.using) {
// reject non-existing tables
this.tryRejectNonexistingTables(node.using.tables);
// for delete with using (join), we need to merge join tables' policy filters to the "where" clause
const joinFilter = this.createPolicyFilterForTables(node.using.tables);
if (joinFilter) {
filter = conjunction(this.dialect, [filter, joinFilter]);
}
}
return {
...result,
where: WhereNode.create(result.where ? conjunction(this.dialect, [result.where.where, filter]) : filter),
};
}
// #endregion
// #region post-update
private async loadBeforeUpdateEntities(
model: string,
where: WhereNode | undefined,
proceed: ProceedKyselyQueryFunction,
forceLoad: boolean = false,
) {
const beforeUpdateAccessFields = this.getFieldsAccessForBeforeUpdatePolicies(model);
if (!forceLoad && (!beforeUpdateAccessFields || beforeUpdateAccessFields.length === 0)) {
return undefined;
}
// combine update's where with policy filter
const policyFilter = this.buildPolicyFilter(model, model, 'update');
const combinedFilter = where ? conjunction(this.dialect, [where.where, policyFilter]) : policyFilter;
const selections = beforeUpdateAccessFields ?? QueryUtils.requireIdFields(this.client.$schema, model);
const query: SelectQueryNode = {
kind: 'SelectQueryNode',
from: FromNode.create([TableNode.create(model)]),
where: WhereNode.create(combinedFilter),
selections: selections.map((f) => SelectionNode.create(ColumnNode.create(f))),
};
const result = await proceed(query);
return { fields: beforeUpdateAccessFields, rows: result.rows };
}
private getFieldsAccessForBeforeUpdatePolicies(model: string) {
const policies = this.getModelPolicies(model, 'post-update');
if (policies.length === 0) {
return undefined;
}
const fields = new Set<string>();
const fieldCollector = new (class extends SchemaUtils.ExpressionVisitor {
protected override visitMember(e: MemberExpression): void {
if (isBeforeInvocation(e.receiver)) {
invariant(e.members.length === 1, 'before() can only be followed by a scalar field access');
fields.add(e.members[0]!);
}
super.visitMember(e);
}
})();
for (const policy of policies) {
fieldCollector.visit(policy.condition);
}
if (fields.size === 0) {
return undefined;
}
// make sure id fields are included
QueryUtils.requireIdFields(this.client.$schema, model).forEach((f) => fields.add(f));
return Array.from(fields).sort();
}
private hasPostUpdatePolicies(model: string) {
const policies = this.getModelPolicies(model, 'post-update');
return policies.length > 0;
}
// #endregion
// #region field-level policies
private createSelectAllFieldsWithPolicies(
model: string,
alias: string | undefined,
operation: FieldLevelPolicyOperations,
) {
let hasPolicies = false;
const modelDef = QueryUtils.requireModel(this.client.$schema, model);
let selections: SelectionNode[] = [];
for (const fieldDef of Object.values(modelDef.fields).filter(
// exclude relation/computed/inherited fields
(f) => !f.relation && !f.computed && !f.originModel,
)) {
const { hasPolicies: fieldHasPolicies, selection } = this.createFieldSelectionWithPolicy(
model,
fieldDef.name,
operation,
);
hasPolicies = hasPolicies || fieldHasPolicies;
selections.push(selection);
}
if (!hasPolicies) {
// if there're no field-level policies, simplify to select all
selections = [SelectionNode.create(SelectAllNode.create())];
}
const modelPolicyFilter = this.buildPolicyFilter(model, model, operation);
if (!isTrueNode(modelPolicyFilter)) {
hasPolicies = true;
}
const nestedQuery: SelectQueryNode = {
kind: 'SelectQueryNode',
from: FromNode.create([TableNode.create(model)]),
where: isTrueNode(modelPolicyFilter) ? undefined : WhereNode.create(modelPolicyFilter),
selections,
};
return {
hasPolicies,
query: AliasNode.create(ParensNode.create(nestedQuery), IdentifierNode.create(alias ?? model)),
};
}
private createFieldSelectionWithPolicy(model: string, field: string, operation: FieldLevelPolicyOperations) {
const filter = this.buildFieldPolicyFilter(model, field, operation);
if (isTrueNode(filter)) {
return { hasPolicies: false, selection: SelectionNode.create(ColumnNode.create(field)) };
}
const eb = expressionBuilder<any, any>();
// CASE WHEN <filter> THEN <field> ELSE NULL END
const selection = eb
.case()
.when(new ExpressionWrapper(filter))
.then(eb.ref(field))
.else(null)
.end()
.as(field)
.toOperationNode();
return { hasPolicies: true, selection: SelectionNode.create(selection) };
}
private hasFieldLevelPolicies(model: string, operation: FieldLevelPolicyOperations) {
const modelDef = QueryUtils.getModel(this.client.$schema, model);
if (!modelDef) {
return false;
}
return Object.keys(modelDef.fields).some((field) => this.getFieldPolicies(model, field, operation).length > 0);
}
private buildFieldPolicyFilter(model: string, field: string, operation: FieldLevelPolicyOperations) {
const policies = this.getFieldPolicies(model, field, operation);
const allows = policies
.filter((policy) => policy.kind === 'allow')
.map((policy) => this.compilePolicyCondition(model, model, operation, policy));
const denies = policies
.filter((policy) => policy.kind === 'deny')
.map((policy) => this.compilePolicyCondition(model, model, operation, policy));
// 'post-update' is by default allowed, other operations are by default denied
let combinedPolicy: OperationNode;
if (allows.length === 0) {
// field access is allowed by default
combinedPolicy = trueNode(this.dialect);
} else {
// or(...allows)
combinedPolicy = disjunction(this.dialect, allows);
}
// and(...!denies)
if (denies.length !== 0) {
const combinedDenies = conjunction(
this.dialect,
denies.map((d) => buildIsFalse(d, this.dialect)),
);
// or(...allows) && and(...!denies)
combinedPolicy = conjunction(this.dialect, [combinedPolicy, combinedDenies]);
}
return combinedPolicy;
}
// #endregion
// #region helpers
private onlyReturningId(node: MutationQueryNode) {
if (!node.returning) {
return true;
}
const { mutationModel } = this.getMutationModel(node);
const idFields = QueryUtils.requireIdFields(this.client.$schema, mutationModel);
if (node.returning.selections.some((s) => SelectAllNode.is(s.selection))) {
const modelDef = QueryUtils.requireModel(this.client.$schema, mutationModel);
if (Object.keys(modelDef.fields).some((f) => !idFields.includes(f))) {
// there are fields other than ID fields
return false;
} else {
// select all but model only has ID fields
return true;
}
}
// analyze selected columns
const collector = new ColumnCollector();
const selectedColumns = collector.collect(node.returning);
return selectedColumns.every((c) => idFields.includes(c));
}
private async enforcePreCreatePolicy(
node: InsertQueryNode,
mutationModel: string,
isManyToManyJoinTable: boolean,
proceed: ProceedKyselyQueryFunction,
) {
const fields = node.columns?.map((c) => c.column.name) ?? [];
const valueRows = node.values
? this.unwrapCreateValueRows(node.values, mutationModel, fields, isManyToManyJoinTable)
: [[]];
for (const values of valueRows) {
if (isManyToManyJoinTable) {
await this.enforcePreCreatePolicyForManyToManyJoinTable(
mutationModel,
fields,
values.map((v) => v.node),
proceed,
);
} else {
await this.enforcePreCreatePolicyForOne(
mutationModel,
fields,
values.map((v) => v.node),
proceed,
);
}
}
}
private async enforcePreCreatePolicyForManyToManyJoinTable(
tableName: string,
fields: string[],
values: OperationNode[],
proceed: ProceedKyselyQueryFunction,
) {
const m2m = this.resolveManyToManyJoinTable(tableName);
invariant(m2m);
// m2m create requires both sides to be updatable
invariant(fields.includes('A') && fields.includes('B'), 'many-to-many join table must have A and B fk fields');
const aIndex = fields.indexOf('A');
const aNode = values[aIndex]!;
const bIndex = fields.indexOf('B');
const bNode = values[bIndex]!;
invariant(ValueNode.is(aNode) && ValueNode.is(bNode), 'A and B values must be ValueNode');
const aValue = aNode.value;
const bValue = bNode.value;
invariant(aValue !== null && aValue !== undefined, 'A value cannot be null or undefined');
invariant(bValue !== null && bValue !== undefined, 'B value cannot be null or undefined');
const eb = expressionBuilder<any, any>();
const filterA = this.buildPolicyFilter(m2m.firstModel, undefined, 'update');
const queryA = eb
.selectFrom(m2m.firstModel)
.where(eb(eb.ref(`${m2m.firstModel}.${m2m.firstIdField}`), '=', aValue))
.select(() => new ExpressionWrapper(filterA).as('_'));
const filterB = this.buildPolicyFilter(m2m.secondModel, undefined, 'update');
const queryB = eb
.selectFrom(m2m.secondModel)
.where(eb(eb.ref(`${m2m.secondModel}.${m2m.secondIdField}`), '=', bValue))
.select(() => new ExpressionWrapper(filterB).as('_'));
// select both conditions in one query
const queryNode: SelectQueryNode = {
kind: 'SelectQueryNode',
selections: [
SelectionNode.create(AliasNode.create(queryA.toOperationNode(), IdentifierNode.create('$conditionA'))),
SelectionNode.create(AliasNode.create(queryB.toOperationNode(), IdentifierNode.create('$conditionB'))),
],
};
const result = await proceed(queryNode);
if (!result.rows[0]?.$conditionA) {
throw createRejectedByPolicyError(
m2m.firstModel,
RejectedByPolicyReason.CANNOT_READ_BACK,
`many-to-many relation participant model "${m2m.firstModel}" not updatable`,
);
}
if (!result.rows[0]?.$conditionB) {
throw createRejectedByPolicyError(
m2m.secondModel,
RejectedByPolicyReason.NO_ACCESS,
`many-to-many relation participant model "${m2m.secondModel}" not updatable`,
);
}
}
private async enforcePreCreatePolicyForOne(
model: string,
fields: string[],
values: OperationNode[],
proceed: ProceedKyselyQueryFunction,
) {
const allFields = QueryUtils.getModelFields(this.client.$schema, model, { inherited: true });
const allValues: KyselyExpression<any>[] = [];
for (const def of allFields) {
const index = fields.indexOf(def.name);
if (index >= 0) {
allValues.push(new ExpressionWrapper(values[index]!));
} else {
// set non-provided fields to null
allValues.push(this.eb.lit(null));
}
}
// create a `SELECT column1 as field1, column2 as field2, ... FROM (VALUES (...))` table for policy evaluation
const valuesTable = this.dialect.buildValuesTableSelect(allFields, [allValues]);
const filter = this.buildPolicyFilter(model, undefined, 'create');
const preCreateCheck = this.eb
.selectFrom(valuesTable.as(model))
.select(this.eb(this.eb.fn.count(this.eb.lit(1)), '>', 0).as('$condition'))
.where(() => new ExpressionWrapper(filter));
const result = await proceed(preCreateCheck.toOperationNode());
if (!result.rows[0]?.$condition) {
throw createRejectedByPolicyError(model, RejectedByPolicyReason.NO_ACCESS);
}
}
private unwrapCreateValueRows(
node: OperationNode,
model: string,
fields: string[],
isManyToManyJoinTable: boolean,
) {
if (ValuesNode.is(node)) {
return node.values.map((v) => this.unwrapCreateValueRow(v.values, model, fields, isManyToManyJoinTable));
} else if (PrimitiveValueListNode.is(node)) {
return [this.unwrapCreateValueRow(node.values, model, fields, isManyToManyJoinTable)];
} else {
invariant(false, `Unexpected node kind: ${node.kind} for unwrapping create values`);
}
}
private unwrapCreateValueRow(
data: readonly unknown[],
model: string,
fields: string[],
isImplicitManyToManyJoinTable: boolean,
) {
invariant(data.length === fields.length, 'data length must match fields length');
const result: { node: OperationNode; raw: unknown }[] = [];
for (let i = 0; i < data.length; i++) {
const item = data[i]!;
if (typeof item === 'object' && item && 'kind' in item) {
if (item.kind === 'DefaultInsertValueNode') {
result.push({ node: ValueNode.create(null), raw: null });
continue;
}
const fieldDef = QueryUtils.requireField(this.client.$schema, model, fields[i]!);
invariant(item.kind === 'ValueNode', 'expecting a ValueNode');
result.push({
node: ValueNode.create(
this.dialect.transformInput(
(item as ValueNode).value,
fieldDef.type as BuiltinType,
!!fieldDef.array,
),
),
raw: (item as ValueNode).value,
});
} else {
let value: unknown = item;
// many-to-many join table is not a model so we don't have field definitions,
// but there's no need to transform values anyway because they're the fields
// are all foreign keys
if (!isImplicitManyToManyJoinTable) {
const fieldDef = QueryUtils.requireField(this.client.$schema, model, fields[i]!);
value = this.dialect.transformInput(item, fieldDef.type as BuiltinType, !!fieldDef.array);
}
// handle the case for list column
if (Array.isArray(value)) {
const fieldDef = QueryUtils.requireField(this.client.$schema, model, fields[i]!);
result.push({
node: this.dialect.buildArrayValue(value, fieldDef.type).toOperationNode(),
raw: value,
});
} else {
result.push({ node: ValueNode.create(value), raw: value });
}
}
}
return result;
}
private tryGetConstantPolicy(model: string, operation: PolicyOperation) {
const policies = this.getModelPolicies(model, operation);
if (!policies.some((p) => p.kind === 'allow')) {
// no allow -> unconditional deny
return false;
} else if (
// unconditional deny
policies.some((p) => p.kind === 'deny' && this.isTrueExpr(p.condition))
) {
return false;
} else if (
// unconditional allow
!policies.some((p) => p.kind === 'deny') &&
policies.some((p) => p.kind === 'allow' && this.isTrueExpr(p.condition))
) {
return true;
} else {
return undefined;
}
}
private isTrueExpr(expr: Expression) {
return ExpressionUtils.isLiteral(expr) && expr.value === true;
}
private async processReadBack(node: CrudQueryNode, result: QueryResult<any>, proceed: ProceedKyselyQueryFunction) {
if (result.rows.length === 0) {
return result;
}
if (!this.isMutationQueryNode(node) || !node.returning) {
return result;
}
// do a select (with policy) in place of returning
const { mutationModel } = this.getMutationModel(node);
const idConditions = this.buildIdConditions(mutationModel, result.rows);
const policyFilter = this.buildPolicyFilter(mutationModel, undefined, 'read');
const select: SelectQueryNode = {