Debian Codegraph @

cel/validator_test.go

raw
1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package cel
16
17 import (
18 "reflect"
19 "testing"
20
21 "github.com/google/cel-go/common/operators"
22 "github.com/google/cel-go/common/overloads"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/common/types/ref"
25 "github.com/google/cel-go/common/types/traits"
26 "github.com/google/cel-go/test"
27 )
28
29 func TestValidateDurationLiterals(t *testing.T) {
30 env, err := NewEnv(
31 Variable("x", types.StringType),
32 ASTValidators(ValidateDurationLiterals()))
33 if err != nil {
34 t.Fatalf("NewEnv(ValidateDurationLiterals()) failed: %v", err)
35 }
36
37 tests := []struct {
38 expr string
39 iss string
40 }{
41 {
42 expr: `duration('1')`,
43 iss: `ERROR: <input>:1:10: invalid duration argument
44 | duration('1')
45 | .........^`,
46 },
47 {
48 expr: `duration('1d')`,
49 iss: `ERROR: <input>:1:10: invalid duration argument
50 | duration('1d')
51 | .........^`,
52 },
53 {
54 expr: "duration('1us')\n < duration('1nns')",
55 iss: `ERROR: <input>:2:13: invalid duration argument
56 | < duration('1nns')
57 | ............^`,
58 },
59 {
60 expr: `duration('2h3m4s5us')`,
61 },
62 {
63 expr: `duration(x)`,
64 },
65 }
66 for _, tst := range tests {
67 tc := tst
68 t.Run(tc.expr, func(t *testing.T) {
69 _, iss := env.Compile(tc.expr)
70 if tc.iss != "" {
71 if iss.Err() == nil {
72 t.Fatalf("e.Compile(%v) returned ast, expected error: %v", tc.expr, tc.iss)
73 }
74 if !test.Compare(iss.Err().Error(), tc.iss) {
75 t.Fatalf("e.Compile(%v) returned %v, expected error: %v", tc.expr, iss.Err(), tc.iss)
76 }
77 return
78 }
79 if iss.Err() != nil {
80 t.Fatalf("e.Compile(%v) failed: %v", tc.expr, iss.Err())
81 }
82 })
83 }
84 }
85
86 func TestValidateTimestampLiterals(t *testing.T) {
87 env, err := NewEnv(
88 Variable("x", types.StringType),
89 ASTValidators(ValidateTimestampLiterals()))
90 if err != nil {
91 t.Fatalf("NewEnv(ValidateTimestampLiterals()) failed: %v", err)
92 }
93
94 tests := []struct {
95 expr string
96 iss string
97 }{
98 {
99 expr: `timestamp('1000-00-00T00:00:00Z')`,
100 iss: `ERROR: <input>:1:11: invalid timestamp argument
101 | timestamp('1000-00-00T00:00:00Z')
102 | ..........^`,
103 },
104 {
105 expr: `timestamp('1000-01-01T00:00:00ZZ')`,
106 iss: `ERROR: <input>:1:11: invalid timestamp argument
107 | timestamp('1000-01-01T00:00:00ZZ')
108 | ..........^`,
109 },
110 {
111 expr: `timestamp('1000-01-01T00:00:00Z')`,
112 },
113 {
114 expr: `timestamp(-6213559680)`, // min unix epoch time.
115 },
116 {
117 expr: `timestamp(-62135596801)`,
118 iss: `ERROR: <input>:1:11: invalid timestamp argument
119 | timestamp(-62135596801)
120 | ..........^`,
121 },
122 {
123 expr: `timestamp(x)`,
124 },
125 }
126 for _, tst := range tests {
127 tc := tst
128 t.Run(tc.expr, func(t *testing.T) {
129 _, iss := env.Compile(tc.expr)
130 if tc.iss != "" {
131 if iss.Err() == nil {
132 t.Fatalf("e.Compile(%v) returned ast, expected error: %v", tc.expr, tc.iss)
133 }
134 if !test.Compare(iss.Err().Error(), tc.iss) {
135 t.Fatalf("e.Compile(%v) returned %v, expected error: %v", tc.expr, iss.Err(), tc.iss)
136 }
137 return
138 }
139 if iss.Err() != nil {
140 t.Fatalf("e.Compile(%v) failed: %v", tc.expr, iss.Err())
141 }
142 })
143 }
144 }
145
146 func TestValidateRegexLiterals(t *testing.T) {
147 env, err := NewEnv(
148 Variable("x", types.StringType),
149 ASTValidators(ValidateRegexLiterals()))
150 if err != nil {
151 t.Fatalf("NewEnv(ValidateRegexLiterals()) failed: %v", err)
152 }
153
154 tests := []struct {
155 expr string
156 iss string
157 }{
158 {
159 expr: `'hello'.matches('el*')`,
160 },
161 {
162 expr: `'hello'.matches('x++')`,
163 iss: `
164 ERROR: <input>:1:17: invalid matches argument
165 | 'hello'.matches('x++')
166 | ................^`,
167 },
168 {
169 expr: `'hello'.matches('(?<name%>el*)')`,
170 iss: `
171 ERROR: <input>:1:17: invalid matches argument
172 | 'hello'.matches('(?<name%>el*)')
173 | ................^`,
174 },
175 {
176 expr: `'hello'.matches('??el*')`,
177 iss: `
178 ERROR: <input>:1:17: invalid matches argument
179 | 'hello'.matches('??el*')
180 | ................^`,
181 },
182 {
183 expr: `'hello'.matches(x)`,
184 },
185 }
186 for _, tst := range tests {
187 tc := tst
188 t.Run(tc.expr, func(t *testing.T) {
189 _, iss := env.Compile(tc.expr)
190 if tc.iss != "" {
191 if iss.Err() == nil {
192 t.Fatalf("e.Compile(%v) returned ast, expected error: %v", tc.expr, tc.iss)
193 }
194 if !test.Compare(iss.Err().Error(), tc.iss) {
195 t.Fatalf("e.Compile(%v) returned %v, expected error: %v", tc.expr, iss.Err(), tc.iss)
196 }
197 return
198 }
199 if iss.Err() != nil {
200 t.Fatalf("e.Compile(%v) failed: %v", tc.expr, iss.Err())
201 }
202 })
203 }
204 }
205
206 func TestValidateHomogeneousAggregateLiterals(t *testing.T) {
207 env, err := NewCustomEnv(
208 Variable("name", StringType),
209 Function(operators.In,
210 Overload(overloads.InList, []*Type{StringType, ListType(StringType)}, BoolType,
211 BinaryBinding(func(lhs, rhs ref.Val) ref.Val {
212 return rhs.(traits.Container).Contains(lhs)
213 }),
214 ),
215 Overload(overloads.InMap, []*Type{StringType, MapType(StringType, BoolType)}, BoolType,
216 BinaryBinding(func(lhs, rhs ref.Val) ref.Val {
217 return rhs.(traits.Container).Contains(lhs)
218 }),
219 ),
220 ),
221 OptionalTypes(),
222 HomogeneousAggregateLiterals(),
223 ASTValidators(ValidateHomogeneousAggregateLiterals()),
224 )
225 if err != nil {
226 t.Fatalf("NewCustomEnv() failed: %v", err)
227 }
228
229 tests := []struct {
230 expr string
231 iss string
232 }{
233 {
234 expr: `name in ['hello', 0]`,
235 iss: `
236 ERROR: <input>:1:19: expected type 'string' but found 'int'
237 | name in ['hello', 0]
238 | ..................^`,
239 },
240 {
241 expr: `{'hello':'world', 1:'!'}`,
242 iss: `
243 ERROR: <input>:1:19: expected type 'string' but found 'int'
244 | {'hello':'world', 1:'!'}
245 | ..................^`,
246 },
247 {
248 expr: `name in {'hello':'world', 'goodbye':true}`,
249 iss: `
250 ERROR: <input>:1:37: expected type 'string' but found 'bool'
251 | name in {'hello':'world', 'goodbye':true}
252 | ....................................^`,
253 },
254 {
255 expr: `name in ['hello', 'world']`,
256 },
257 {
258 expr: `name in ['hello', ?optional.ofNonZeroValue('')]`,
259 },
260 {
261 expr: `name in [?optional.ofNonZeroValue(''), 'hello', ?optional.of('')]`,
262 },
263 {
264 expr: `name in {'hello': false, 'world': true}`,
265 },
266 {
267 expr: `{'hello': false, ?'world': optional.ofNonZeroValue(true)}`,
268 },
269 {
270 expr: `{?'hello': optional.ofNonZeroValue(false), 'world': true}`,
271 },
272 }
273 for _, tst := range tests {
274 tc := tst
275 t.Run(tc.expr, func(t *testing.T) {
276 _, iss := env.Compile(tc.expr)
277 if tc.iss != "" {
278 if iss.Err() == nil {
279 t.Fatalf("e.Compile(%v) returned ast, expected error: %v", tc.expr, tc.iss)
280 }
281 if !test.Compare(iss.Err().Error(), tc.iss) {
282 t.Fatalf("e.Compile(%v) returned %v, expected error: %v", tc.expr, iss.Err(), tc.iss)
283 }
284 return
285 }
286 if iss.Err() != nil {
287 t.Fatalf("e.Compile(%v) failed: %v", tc.expr, iss.Err())
288 }
289 })
290 }
291 }
292
293 func TestValidateComprehensionNestingLimit(t *testing.T) {
294 env, err := NewEnv(
295 ASTValidators(ValidateComprehensionNestingLimit(2)),
296 )
297 if err != nil {
298 t.Fatalf("NewEnv() failed: %v", err)
299 }
300 tests := []struct {
301 expr string
302 iss string
303 }{
304 {
305 expr: `[1, 2, 3].exists(i, i < 1)`,
306 },
307 {
308 expr: `[1, 2, 3].exists(i, [4, 5, 6].filter(j, j % i != 0).size() > 0)`,
309 },
310 {
311 // three comprehensions, but not three levels deep
312 expr: `[1, 2, 3].exists(i, [4, 5, 6].filter(j, j % i != 0).size() > 0) && [1, 2, 3].exists(i, i < 1)`,
313 },
314 {
315 // the empty iteration range in [].all(k, k) does not impact the actual runtime complexity,
316 // so it does not trip the comprehension limit.
317 expr: `[1, 2, 3].exists(i, [4, 5, 6].filter(j, [].all(k, k) && j % i != 0).size() > 0)`,
318 },
319 {
320 // three comprehensions, three levels deep
321 expr: `[1, 2, 3].map(i, [4, 5, 6].map(j, [7, 8, 9].map(k, i * j * k)))`,
322 iss: `
323 ERROR: <input>:1:48: comprehension exceeds nesting limit
324 | [1, 2, 3].map(i, [4, 5, 6].map(j, [7, 8, 9].map(k, i * j * k)))
325 | ...............................................^`,
326 },
327 }
328 for _, tst := range tests {
329 tc := tst
330 t.Run(tc.expr, func(t *testing.T) {
331 _, iss := env.Compile(tc.expr)
332 if tc.iss != "" {
333 if iss.Err() == nil {
334 t.Fatalf("e.Compile(%v) returned ast, expected error: %v", tc.expr, tc.iss)
335 }
336 if !test.Compare(iss.Err().Error(), tc.iss) {
337 t.Fatalf("e.Compile(%v) returned %v, expected error: %v", tc.expr, iss.Err(), tc.iss)
338 }
339 return
340 }
341 if iss.Err() != nil {
342 t.Fatalf("e.Compile(%v) failed: %v", tc.expr, iss.Err())
343 }
344 })
345 }
346 }
347
348 func TestExtendedValidations(t *testing.T) {
349 env, err := NewEnv(
350 Variable("x", types.StringType),
351 ExtendedValidations(),
352 )
353 if err != nil {
354 t.Fatalf("NewEnv(ExtendedValidations()) failed: %v", err)
355 }
356 tests := []struct {
357 expr string
358 iss string
359 }{
360 {
361 expr: `x in ['hello', 0]
362 && duration(x) < duration('1d')
363 && timestamp(x) != timestamp('1000-01-00T00:00:00Z')
364 && x.matches('x++')`,
365 iss: `
366 ERROR: <input>:1:16: expected type 'string' but found 'int'
367 | x in ['hello', 0]
368 | ...............^
369 ERROR: <input>:2:30: invalid duration argument
370 | && duration(x) < duration('1d')
371 | .............................^
372 ERROR: <input>:3:33: invalid timestamp argument
373 | && timestamp(x) != timestamp('1000-01-00T00:00:00Z')
374 | ................................^
375 ERROR: <input>:4:17: invalid matches argument
376 | && x.matches('x++')
377 | ................^`,
378 },
379 }
380 for _, tst := range tests {
381 tc := tst
382 t.Run(tc.expr, func(t *testing.T) {
383 _, iss := env.Compile(tc.expr)
384 if tc.iss != "" {
385 if iss.Err() == nil {
386 t.Fatalf("e.Compile(%v) returned ast, expected error: %v", tc.expr, tc.iss)
387 }
388 if !test.Compare(iss.Err().Error(), tc.iss) {
389 t.Fatalf("e.Compile(%v) returned %v, expected error: %v", tc.expr, iss.Err(), tc.iss)
390 }
391 return
392 }
393 if iss.Err() != nil {
394 t.Fatalf("e.Compile(%v) failed: %v", tc.expr, iss.Err())
395 }
396 })
397 }
398 }
399
400 func TestValidatorConfig(t *testing.T) {
401 config := newValidatorConfig()
402 result := config.GetOrDefault("ext.validate.custom", 2)
403 if result != 2 {
404 t.Errorf("config.GetOrDefault() got %v, wanted default of 2", result)
405 }
406 result = config.GetOrDefault(HomogeneousAggregateLiteralExemptFunctions, []string{})
407 if reflect.TypeOf(result) != reflect.TypeOf([]string{}) {
408 t.Errorf("config.GetOrDefault() got %T, wanted type %T", result, []string{})
409 }
410 err := config.Set(HomogeneousAggregateLiteralExemptFunctions, []string{"_==_"})
411 if err != nil {
412 t.Errorf("config.Set() failed: %v", err)
413 }
414 err = config.Set(HomogeneousAggregateLiteralExemptFunctions, map[string]any{})
415 if err == nil {
416 t.Error("config.Set() with incorrect value type did not fail")
417 }
418 }