forked from zenstackhq/zenstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction-invocation-validator.ts
More file actions
314 lines (281 loc) · 11.5 KB
/
function-invocation-validator.ts
File metadata and controls
314 lines (281 loc) · 11.5 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
import {
AbstractCallable,
AliasDecl,
Argument,
DataModel,
DataModelAttribute,
DataModelFieldAttribute,
Expression,
FunctionParam,
InvocationExpr,
isAliasDecl,
isArrayExpr,
isDataModel,
isDataModelAttribute,
isDataModelFieldAttribute,
isInvocationExpr,
isLiteralExpr,
} from '@zenstackhq/language/ast';
import {
ExpressionContext,
getFieldReference,
getFunctionExpressionContext,
getLiteral,
isDataModelFieldReference,
isEnumFieldReference,
isFromStdlib,
isValidationAttribute,
} from '@zenstackhq/sdk';
import { AstNode, streamAst, ValidationAcceptor } from 'langium';
import { match, P } from 'ts-pattern';
import { isCheckInvocation } from '../../utils/ast-utils';
import { AstValidator } from '../types';
import { isAuthOrAuthMemberAccess, typeAssignable } from './utils';
// a registry of function handlers marked with @func
const invocationCheckers = new Map<string, PropertyDescriptor>();
// function handler decorator
function func(name: string) {
return function (_target: unknown, _propertyKey: string, descriptor: PropertyDescriptor) {
if (!invocationCheckers.get(name)) {
invocationCheckers.set(name, descriptor);
}
return descriptor;
};
}
/**
* InvocationExpr validation
*/
export default class FunctionInvocationValidator implements AstValidator<Expression> {
validate(expr: InvocationExpr, accept: ValidationAcceptor): void {
const callableDecl = expr.function.ref;
if (!callableDecl) {
accept('error', 'function or alias cannot be resolved', { node: expr });
return;
}
if (!this.validateArgs(callableDecl, expr.args, accept)) {
return;
}
if (isFromStdlib(callableDecl)) {
// validate standard library functions
// find the containing attribute context for the invocation
let curr: AstNode | undefined = expr.$container;
let containerAttribute: DataModelAttribute | DataModelFieldAttribute | AliasDecl | undefined;
while (curr) {
if (isDataModelAttribute(curr) || isDataModelFieldAttribute(curr) || isAliasDecl(curr)) {
containerAttribute = curr;
break;
}
curr = curr.$container;
}
// validate the context allowed for the function
const exprContext = this.getExpressionContext(containerAttribute);
// get the context allowed for the function
const funcAllowedContext = getFunctionExpressionContext(callableDecl);
if (funcAllowedContext.length > 0 && (!exprContext || !funcAllowedContext.includes(exprContext))) {
accept(
'error',
`function "${callableDecl.name}" is not allowed in the current context${
exprContext ? ': ' + exprContext : ''
}`,
{
node: expr,
}
);
return;
}
// TODO: express function validation rules declaratively in ZModel
const allCasing = ['original', 'upper', 'lower', 'capitalize', 'uncapitalize'];
if (['currentModel', 'currentOperation'].includes(callableDecl.name)) {
const arg = getLiteral<string>(expr.args[0]?.value);
if (arg && !allCasing.includes(arg)) {
accept('error', `argument must be one of: ${allCasing.map((c) => '"' + c + '"').join(', ')}`, {
node: expr.args[0],
});
}
} else if (
funcAllowedContext.includes(ExpressionContext.AccessPolicy) ||
funcAllowedContext.includes(ExpressionContext.ValidationRule)
) {
// filter operation functions validation
// first argument must refer to a model field
const firstArg = expr.args?.[0]?.value;
if (firstArg) {
if (!getFieldReference(firstArg)) {
accept('error', 'first argument must be a field reference', { node: firstArg });
}
}
// second argument must be a literal or array of literal
const secondArg = expr.args?.[1]?.value;
if (
secondArg &&
// literal
!isLiteralExpr(secondArg) &&
// enum field
!isEnumFieldReference(secondArg) &&
// `auth()...` expression
!isAuthOrAuthMemberAccess(secondArg) &&
// static function calls that are runtime constants: `currentModel`, `currentOperation`
!this.isStaticFunctionCall(secondArg) &&
// array of literal/enum
!(
isArrayExpr(secondArg) &&
secondArg.items.every(
(item: Expression) =>
isLiteralExpr(item) || isEnumFieldReference(item) || isAuthOrAuthMemberAccess(item)
)
)
) {
accept(
'error',
'second argument must be a literal, an enum, an expression starting with `auth().`, or an array of them',
{
node: secondArg,
}
);
}
}
// run checkers for specific functions
const checker = invocationCheckers.get(expr.function.$refText);
if (checker) {
checker.value.call(this, expr, accept);
}
}
}
private getExpressionContext(
containerAttribute: DataModelAttribute | DataModelFieldAttribute | AliasDecl | undefined
) {
if (!containerAttribute) {
return undefined;
}
if (isAliasDecl(containerAttribute)) {
return ExpressionContext.AliasFunction;
}
if (isValidationAttribute(containerAttribute)) {
return ExpressionContext.ValidationRule;
}
return match(containerAttribute?.decl.$refText)
.with('@default', () => ExpressionContext.DefaultValue)
.with(P.union('@@allow', '@@deny', '@allow', '@deny'), () => ExpressionContext.AccessPolicy)
.with('@@index', () => ExpressionContext.Index)
.otherwise(() => undefined);
}
private isStaticFunctionCall(expr: Expression) {
return isInvocationExpr(expr) && ['currentModel', 'currentOperation'].includes(expr.function.$refText);
}
private validateArgs(funcDecl: AbstractCallable, args: Argument[], accept: ValidationAcceptor) {
let success = true;
for (let i = 0; i < funcDecl.params.length; i++) {
const param = funcDecl.params[i];
const arg = args[i];
if (!arg) {
if (!param.optional) {
accept('error', `missing argument for parameter "${param.name}"`, { node: funcDecl });
success = false;
}
} else {
if (!this.validateInvocationArg(arg, param, accept)) {
success = false;
}
}
}
// TODO: do we need to complain for extra arguments?
return success;
}
private validateInvocationArg(arg: Argument, param: FunctionParam, accept: ValidationAcceptor) {
const argResolvedType = arg?.value?.$resolvedType;
if (!argResolvedType) {
accept('error', 'argument type cannot be resolved', { node: arg });
return false;
}
const dstType = param.type.type;
if (!dstType) {
accept('error', 'parameter type cannot be resolved', { node: param });
return false;
}
const dstIsArray = param.type.array;
const dstRef = param.type.reference;
if (dstType === 'Any' && !dstIsArray) {
// scalar 'any' can be assigned with anything
return true;
}
if (typeof argResolvedType.decl === 'string') {
// scalar type
if (!typeAssignable(dstType, argResolvedType.decl, arg.value) || dstIsArray !== argResolvedType.array) {
accept('error', `argument is not assignable to parameter`, {
node: arg,
});
return false;
}
} else {
// enum or model type
if ((dstRef?.ref !== argResolvedType.decl && dstType !== 'Any') || dstIsArray !== argResolvedType.array) {
accept('error', `argument is not assignable to parameter`, {
node: arg,
});
return false;
}
}
return true;
}
@func('check')
private _checkCheck(expr: InvocationExpr, accept: ValidationAcceptor) {
let valid = true;
const fieldArg = expr.args[0].value;
if (!isDataModelFieldReference(fieldArg) || !isDataModel(fieldArg.$resolvedType?.decl)) {
accept('error', 'argument must be a relation field', { node: expr.args[0] });
valid = false;
}
if (fieldArg.$resolvedType?.array) {
accept('error', 'argument cannot be an array field', { node: expr.args[0] });
valid = false;
}
const opArg = expr.args[1]?.value;
if (opArg) {
const operation = getLiteral<string>(opArg);
if (!operation || !['read', 'create', 'update', 'delete'].includes(operation)) {
accept('error', 'argument must be a "read", "create", "update", or "delete"', { node: expr.args[1] });
valid = false;
}
}
if (!valid) {
return;
}
// check for cyclic relation checking
const start = fieldArg.$resolvedType?.decl as DataModel;
const tasks = [expr];
const seen = new Set<DataModel>();
while (tasks.length > 0) {
const currExpr = tasks.pop()!;
const arg = currExpr.args[0]?.value;
if (!isDataModel(arg?.$resolvedType?.decl)) {
continue;
}
const currModel = arg.$resolvedType.decl;
if (seen.has(currModel)) {
if (currModel === start) {
accept('error', 'cyclic dependency detected when following the `check()` call', { node: expr });
} else {
// a cycle is detected but it doesn't start from the invocation expression we're checking,
// just break here and the cycle will be reported when we validate the start of it
}
break;
} else {
seen.add(currModel);
}
const policyAttrs = currModel.attributes.filter(
(attr: DataModelAttribute) => attr.decl.$refText === '@@allow' || attr.decl.$refText === '@@deny'
);
for (const attr of policyAttrs) {
const rule = attr.args[1];
if (!rule) {
continue;
}
streamAst(rule).forEach((node) => {
if (isCheckInvocation(node)) {
tasks.push(node as InvocationExpr);
}
});
}
}
}
}