forked from zenstackhq/zenstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression-validator.ts
More file actions
312 lines (283 loc) · 12 KB
/
expression-validator.ts
File metadata and controls
312 lines (283 loc) · 12 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
import {
AstNode,
BinaryExpr,
DataModelAttribute,
Expression,
ExpressionType,
isAliasDecl,
isArrayExpr,
isDataModel,
isDataModelAttribute,
isDataModelField,
isEnum,
isLiteralExpr,
isMemberAccessExpr,
isNullExpr,
isReferenceExpr,
isThisExpr,
} from '@zenstackhq/language/ast';
import {
getAttributeArgLiteral,
isAuthInvocation,
isDataModelFieldReference,
isEnumFieldReference,
} from '@zenstackhq/sdk';
import { ValidationAcceptor, getContainerOfType, streamAst } from 'langium';
import { findUpAst, getContainingDataModel } from '../../utils/ast-utils';
import { AstValidator } from '../types';
import { isAuthOrAuthMemberAccess, typeAssignable } from './utils';
/**
* Validates expressions.
*/
export default class ExpressionValidator implements AstValidator<Expression> {
validate(expr: Expression, accept: ValidationAcceptor): void {
// deal with a few cases where reference resolution fail silently
if (!expr.$resolvedType) {
if (isAuthInvocation(expr) && !getContainerOfType(expr, isAliasDecl)) {
// check was done at link time
accept(
'error',
'auth() cannot be resolved because no model marked with "@@auth()" or named "User" is found',
{ node: expr }
);
} else {
const hasReferenceResolutionError = streamAst(expr).some((node) => {
if (isMemberAccessExpr(node)) {
return !!node.member.error;
}
if (isReferenceExpr(node)) {
return !!node.target.error;
}
return false;
});
if (hasReferenceResolutionError) {
// report silent errors not involving linker errors
accept('error', `Expression cannot be resolved: ${expr.$cstNode?.text}`, {
node: expr,
});
}
}
}
// extra validations by expression type
switch (expr.$type) {
case 'BinaryExpr':
this.validateBinaryExpr(expr, accept);
break;
}
}
private validateBinaryExpr(expr: BinaryExpr, accept: ValidationAcceptor) {
switch (expr.operator) {
case 'in': {
if (typeof expr.left.$resolvedType?.decl !== 'string' && !isEnum(expr.left.$resolvedType?.decl)) {
accept('error', 'left operand of "in" must be of scalar type', { node: expr.left });
}
if (!expr.right.$resolvedType?.array) {
accept('error', 'right operand of "in" must be an array', {
node: expr.right,
});
}
this.validateCrossModelFieldComparison(expr, accept);
break;
}
case '>':
case '>=':
case '<':
case '<=':
case '&&':
case '||': {
if (expr.left.$resolvedType?.array) {
accept('error', 'operand cannot be an array', { node: expr.left });
break;
}
if (expr.right.$resolvedType?.array) {
accept('error', 'operand cannot be an array', { node: expr.right });
break;
}
let supportedShapes: ExpressionType[];
if (['>', '>=', '<', '<='].includes(expr.operator)) {
supportedShapes = ['Int', 'Float', 'DateTime', 'Any'];
} else {
supportedShapes = ['Boolean', 'Any'];
}
if (!this.isValidOperandType(expr.left, supportedShapes)) {
accept('error', `invalid operand type for "${expr.operator}" operator`, {
node: expr.left,
});
return;
}
if (!this.isValidOperandType(expr.right, supportedShapes)) {
accept('error', `invalid operand type for "${expr.operator}" operator`, {
node: expr.right,
});
return;
}
// DateTime comparison is only allowed between two DateTime values
if (expr.left.$resolvedType?.decl === 'DateTime' && expr.right.$resolvedType?.decl !== 'DateTime') {
accept('error', 'incompatible operand types', { node: expr });
} else if (
expr.right.$resolvedType?.decl === 'DateTime' &&
expr.left.$resolvedType?.decl !== 'DateTime'
) {
accept('error', 'incompatible operand types', { node: expr });
}
if (expr.operator !== '&&' && expr.operator !== '||') {
this.validateCrossModelFieldComparison(expr, accept);
}
break;
}
case '==':
case '!=': {
if (this.isInValidationContext(expr)) {
// in validation context, all fields are optional, so we should allow
// comparing any field against null
if (
(isDataModelFieldReference(expr.left) && isNullExpr(expr.right)) ||
(isDataModelFieldReference(expr.right) && isNullExpr(expr.left))
) {
return;
}
}
if (!!expr.left.$resolvedType?.array !== !!expr.right.$resolvedType?.array) {
accept('error', 'incompatible operand types', { node: expr });
break;
}
if (!this.validateCrossModelFieldComparison(expr, accept)) {
break;
}
if (
(expr.left.$resolvedType?.nullable && isNullExpr(expr.right)) ||
(expr.right.$resolvedType?.nullable && isNullExpr(expr.left))
) {
// comparing nullable field with null
return;
}
if (
typeof expr.left.$resolvedType?.decl === 'string' &&
typeof expr.right.$resolvedType?.decl === 'string'
) {
// scalar types assignability
if (
!typeAssignable(expr.left.$resolvedType.decl, expr.right.$resolvedType.decl) &&
!typeAssignable(expr.right.$resolvedType.decl, expr.left.$resolvedType.decl)
) {
accept('error', 'incompatible operand types', { node: expr });
}
return;
}
// disallow comparing model type with scalar type or comparison between
// incompatible model types
const leftType = expr.left.$resolvedType?.decl;
const rightType = expr.right.$resolvedType?.decl;
if (isDataModel(leftType) && isDataModel(rightType)) {
if (leftType != rightType) {
// incompatible model types
// TODO: inheritance case?
accept('error', 'incompatible operand types', { node: expr });
}
// not supported:
// - foo == bar
// - foo == this
if (
isDataModelFieldReference(expr.left) &&
(isThisExpr(expr.right) || isDataModelFieldReference(expr.right))
) {
accept('error', 'comparison between model-typed fields are not supported', { node: expr });
} else if (
isDataModelFieldReference(expr.right) &&
(isThisExpr(expr.left) || isDataModelFieldReference(expr.left))
) {
accept('error', 'comparison between model-typed fields are not supported', { node: expr });
}
} else if (
(isDataModel(leftType) && !isNullExpr(expr.right)) ||
(isDataModel(rightType) && !isNullExpr(expr.left))
) {
// comparing model against scalar (except null)
accept('error', 'incompatible operand types', { node: expr });
}
break;
}
case '?':
case '!':
case '^':
this.validateCollectionPredicate(expr, accept);
break;
}
}
private validateCrossModelFieldComparison(expr: BinaryExpr, accept: ValidationAcceptor) {
// not supported in "read" rules:
// - foo.a == bar
// - foo.user.id == userId
// except:
// - future().userId == userId
if (
(isMemberAccessExpr(expr.left) &&
isDataModelField(expr.left.member.ref) &&
expr.left.member.ref.$container != getContainingDataModel(expr)) ||
(isMemberAccessExpr(expr.right) &&
isDataModelField(expr.right.member.ref) &&
expr.right.member.ref.$container != getContainingDataModel(expr))
) {
// foo.user.id == auth().id
// foo.user.id == "123"
// foo.user.id == null
// foo.user.id == EnumValue
if (!(this.isNotModelFieldExpr(expr.left) || this.isNotModelFieldExpr(expr.right))) {
const containingPolicyAttr = findUpAst(
expr,
(node) => isDataModelAttribute(node) && ['@@allow', '@@deny'].includes(node.decl.$refText)
) as DataModelAttribute | undefined;
if (containingPolicyAttr) {
const operation = getAttributeArgLiteral<string>(containingPolicyAttr, 'operation');
if (operation?.split(',').includes('all') || operation?.split(',').includes('read')) {
accept(
'error',
'comparison between fields of different models is not supported in model-level "read" rules',
{
node: expr,
}
);
return false;
}
}
}
}
return true;
}
private validateCollectionPredicate(expr: BinaryExpr, accept: ValidationAcceptor) {
if (!expr.$resolvedType) {
accept('error', 'collection predicate can only be used on an array of model type', { node: expr });
return;
}
}
private isInValidationContext(node: AstNode) {
return findUpAst(node, (n) => isDataModelAttribute(n) && n.decl.$refText === '@@validate');
}
private isNotModelFieldExpr(expr: Expression): boolean {
return (
// literal
isLiteralExpr(expr) ||
// enum field
isEnumFieldReference(expr) ||
// null
isNullExpr(expr) ||
// `auth()` access
isAuthOrAuthMemberAccess(expr) ||
// array
(isArrayExpr(expr) && expr.items.every((item) => this.isNotModelFieldExpr(item)))
);
}
private isValidOperandType(operand: Expression, supportedShapes: string[]): boolean {
let decl = operand.$resolvedType?.decl;
if (isAliasDecl(decl)) {
// If it's an alias, we check the resolved type of the expression
decl = decl.expression?.$resolvedType?.decl;
}
// Check for valid type
if (typeof decl === 'string') {
return supportedShapes.includes(decl);
}
// Any other type is invalid
return false;
}
}