-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathattribute-application-validator.ts
389 lines (347 loc) · 13.9 KB
/
attribute-application-validator.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
import {
ArrayExpr,
Attribute,
AttributeArg,
AttributeParam,
DataModelAttribute,
DataModelField,
DataModelFieldAttribute,
InternalAttribute,
ReferenceExpr,
isArrayExpr,
isAttribute,
isDataModel,
isDataModelField,
isEnum,
isReferenceExpr,
isTypeDef,
isTypeDefField,
} from '@zenstackhq/language/ast';
import {
hasAttribute,
isDataModelFieldReference,
isDelegateModel,
isFutureExpr,
isRelationshipField,
resolved,
} from '@zenstackhq/sdk';
import { ValidationAcceptor, streamAllContents, streamAst } from 'langium';
import pluralize from 'pluralize';
import { AstValidator } from '../types';
import { getStringLiteral, mapBuiltinTypeToExpressionType, typeAssignable } from './utils';
// a registry of function handlers marked with @check
const attributeCheckers = new Map<string, PropertyDescriptor>();
// function handler decorator
function check(name: string) {
return function (_target: unknown, _propertyKey: string, descriptor: PropertyDescriptor) {
if (!attributeCheckers.get(name)) {
attributeCheckers.set(name, descriptor);
}
return descriptor;
};
}
type AttributeApplication = DataModelAttribute | DataModelFieldAttribute | InternalAttribute;
/**
* Validates function declarations.
*/
export default class AttributeApplicationValidator implements AstValidator<AttributeApplication> {
validate(attr: AttributeApplication, accept: ValidationAcceptor) {
const decl = attr.decl.ref;
if (!decl) {
return;
}
const targetDecl = attr.$container;
if (decl.name === '@@@targetField' && !isAttribute(targetDecl)) {
accept('error', `attribute "${decl.name}" can only be used on attribute declarations`, { node: attr });
return;
}
if (isDataModelField(targetDecl) && !isValidAttributeTarget(decl, targetDecl)) {
accept('error', `attribute "${decl.name}" cannot be used on this type of field`, { node: attr });
}
if (isTypeDefField(targetDecl) && !hasAttribute(decl, '@@@supportTypeDef')) {
accept('error', `attribute "${decl.name}" cannot be used on type declaration fields`, { node: attr });
}
if (isTypeDef(targetDecl) && !hasAttribute(decl, '@@@supportTypeDef')) {
accept('error', `attribute "${decl.name}" cannot be used on type declarations`, { node: attr });
}
const filledParams = new Set<AttributeParam>();
for (const arg of attr.args) {
let paramDecl: AttributeParam | undefined;
if (!arg.name) {
paramDecl = decl.params.find((p) => p.default && !filledParams.has(p));
if (!paramDecl) {
accept('error', `Unexpected unnamed argument`, {
node: arg,
});
return;
}
} else {
paramDecl = decl.params.find((p) => p.name === arg.name);
if (!paramDecl) {
accept('error', `Attribute "${decl.name}" doesn't have a parameter named "${arg.name}"`, {
node: arg,
});
return;
}
}
if (!assignableToAttributeParam(arg, paramDecl, attr)) {
accept('error', `Value is not assignable to parameter`, {
node: arg,
});
return;
}
if (filledParams.has(paramDecl)) {
accept('error', `Parameter "${paramDecl.name}" is already provided`, { node: arg });
return;
}
filledParams.add(paramDecl);
arg.$resolvedParam = paramDecl;
}
const missingParams = decl.params.filter((p) => !p.type.optional && !filledParams.has(p));
if (missingParams.length > 0) {
accept(
'error',
`Required ${pluralize('parameter', missingParams.length)} not provided: ${missingParams
.map((p) => p.name)
.join(', ')}`,
{ node: attr }
);
return;
}
// run checkers for specific attributes
const checker = attributeCheckers.get(decl.name);
if (checker) {
checker.value.call(this, attr, accept);
}
}
@check('@@allow')
@check('@@deny')
private _checkModelLevelPolicy(attr: AttributeApplication, accept: ValidationAcceptor) {
const kind = getStringLiteral(attr.args[0].value);
if (!kind) {
accept('error', `expects a string literal`, { node: attr.args[0] });
return;
}
this.validatePolicyKinds(kind, ['create', 'read', 'update', 'delete', 'all', 'list'], attr, accept);
// @encrypted fields cannot be used in policy rules
this.rejectEncryptedFields(attr, accept);
}
@check('@allow')
@check('@deny')
private _checkFieldLevelPolicy(attr: AttributeApplication, accept: ValidationAcceptor) {
const kind = getStringLiteral(attr.args[0].value);
if (!kind) {
accept('error', `expects a string literal`, { node: attr.args[0] });
return;
}
const kindItems = this.validatePolicyKinds(kind, ['read', 'update', 'all'], attr, accept);
const expr = attr.args[1].value;
if (streamAst(expr).some((node) => isFutureExpr(node))) {
accept('error', `"future()" is not allowed in field-level policy rules`, { node: expr });
}
// 'update' rules are not allowed for relation fields
if (kindItems.includes('update') || kindItems.includes('all')) {
const field = attr.$container as DataModelField;
if (isRelationshipField(field)) {
accept(
'error',
`Field-level policy rules with "update" or "all" kind are not allowed for relation fields. Put rules on foreign-key fields instead.`,
{ node: attr }
);
}
}
// @encrypted fields cannot be used in policy rules
this.rejectEncryptedFields(attr, accept);
}
@check('@@validate')
private _checkValidate(attr: AttributeApplication, accept: ValidationAcceptor) {
const condition = attr.args[0]?.value;
if (
condition &&
streamAst(condition).some(
(node) => isDataModelFieldReference(node) && isDataModel(node.$resolvedType?.decl)
)
) {
accept('error', `\`@@validate\` condition cannot use relation fields`, { node: condition });
}
}
@check('@@unique')
private _checkUnique(attr: AttributeApplication, accept: ValidationAcceptor) {
const fields = attr.args[0]?.value;
if (fields && isArrayExpr(fields)) {
fields.items.forEach((item) => {
if (!isReferenceExpr(item)) {
accept('error', `Expecting a field reference`, { node: item });
return;
}
if (!isDataModelField(item.target.ref)) {
accept('error', `Expecting a field reference`, { node: item });
return;
}
if (item.target.ref.$container !== attr.$container && isDelegateModel(item.target.ref.$container)) {
accept('error', `Cannot use fields inherited from a polymorphic base model in \`@@unique\``, {
node: item,
});
}
});
} else {
accept('error', `Expected an array of field references`, { node: fields });
}
}
private rejectEncryptedFields(attr: AttributeApplication, accept: ValidationAcceptor) {
streamAllContents(attr).forEach((node) => {
if (isDataModelFieldReference(node) && hasAttribute(node.target.ref as DataModelField, '@encrypted')) {
accept('error', `Encrypted fields cannot be used in policy rules`, { node });
}
});
}
private validatePolicyKinds(
kind: string,
candidates: string[],
attr: AttributeApplication,
accept: ValidationAcceptor
) {
const items = kind.split(',').map((x) => x.trim());
items.forEach((item) => {
if (!candidates.includes(item)) {
accept(
'error',
`Invalid policy rule kind: "${item}", allowed: ${candidates.map((c) => '"' + c + '"').join(', ')}`,
{ node: attr }
);
}
});
return items;
}
}
function assignableToAttributeParam(arg: AttributeArg, param: AttributeParam, attr: AttributeApplication): boolean {
const argResolvedType = arg.$resolvedType;
if (!argResolvedType) {
return false;
}
let dstType = param.type.type;
let dstIsArray = param.type.array;
if (dstType === 'ContextType') {
// ContextType is inferred from the attribute's container's type
if (isDataModelField(attr.$container)) {
dstIsArray = attr.$container.type.array;
}
}
const dstRef = param.type.reference;
if (dstType === 'Any' && !dstIsArray) {
return true;
}
if (argResolvedType.decl === 'Any') {
// arg is any type
if (!argResolvedType.array) {
// if it's not an array, it's assignable to any type
return true;
} else {
// otherwise it's assignable to any array type
return argResolvedType.array === dstIsArray;
}
}
// destination is field reference or transitive field reference, check if
// argument is reference or array or reference
if (dstType === 'FieldReference' || dstType === 'TransitiveFieldReference') {
if (dstIsArray) {
return (
isArrayExpr(arg.value) &&
!arg.value.items.find((item) => !isReferenceExpr(item) || !isDataModelField(item.target.ref))
);
} else {
return isReferenceExpr(arg.value) && isDataModelField(arg.value.target.ref);
}
}
if (isEnum(argResolvedType.decl)) {
// enum type
let attrArgDeclType = dstRef?.ref;
if (dstType === 'ContextType' && isDataModelField(attr.$container) && attr.$container?.type?.reference) {
// attribute parameter type is ContextType, need to infer type from
// the attribute's container
attrArgDeclType = resolved(attr.$container.type.reference);
dstIsArray = attr.$container.type.array;
}
return attrArgDeclType === argResolvedType.decl && dstIsArray === argResolvedType.array;
} else if (dstType) {
// scalar type
if (typeof argResolvedType?.decl !== 'string') {
// destination type is not a reference, so argument type must be a plain expression
return false;
}
if (dstType === 'ContextType') {
// attribute parameter type is ContextType, need to infer type from
// the attribute's container
if (isDataModelField(attr.$container)) {
if (!attr.$container?.type?.type) {
return false;
}
dstType = mapBuiltinTypeToExpressionType(attr.$container.type.type);
dstIsArray = attr.$container.type.array;
} else {
dstType = 'Any';
}
}
return typeAssignable(dstType, argResolvedType.decl, arg.value) && dstIsArray === argResolvedType.array;
} else {
// reference type
return (dstRef?.ref === argResolvedType.decl || dstType === 'Any') && dstIsArray === argResolvedType.array;
}
}
function isValidAttributeTarget(attrDecl: Attribute, targetDecl: DataModelField) {
const targetField = attrDecl.attributes.find((attr) => attr.decl.ref?.name === '@@@targetField');
if (!targetField) {
// no field type constraint
return true;
}
const fieldTypes = (targetField.args[0].value as ArrayExpr).items.map(
(item) => (item as ReferenceExpr).target.ref?.name
);
let allowed = false;
for (const allowedType of fieldTypes) {
switch (allowedType) {
case 'StringField':
allowed = allowed || targetDecl.type.type === 'String';
break;
case 'IntField':
allowed = allowed || targetDecl.type.type === 'Int';
break;
case 'BigIntField':
allowed = allowed || targetDecl.type.type === 'BigInt';
break;
case 'FloatField':
allowed = allowed || targetDecl.type.type === 'Float';
break;
case 'DecimalField':
allowed = allowed || targetDecl.type.type === 'Decimal';
break;
case 'BooleanField':
allowed = allowed || targetDecl.type.type === 'Boolean';
break;
case 'DateTimeField':
allowed = allowed || targetDecl.type.type === 'DateTime';
break;
case 'JsonField':
allowed = allowed || targetDecl.type.type === 'Json';
break;
case 'BytesField':
allowed = allowed || targetDecl.type.type === 'Bytes';
break;
case 'ModelField':
allowed = allowed || isDataModel(targetDecl.type.reference?.ref);
break;
case 'TypeDefField':
allowed = allowed || isTypeDef(targetDecl.type.reference?.ref);
break;
default:
break;
}
if (allowed) {
break;
}
}
return allowed;
}
export function validateAttributeApplication(attr: AttributeApplication, accept: ValidationAcceptor) {
new AttributeApplicationValidator().validate(attr, accept);
}