Debian Codegraph @

policy/compiler_test.go

raw symbols SCIP
1 // Copyright 2024 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 // https://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 policy
16
17 import (
18 "fmt"
19 "reflect"
20 "strings"
21 "testing"
22
23 "google.golang.org/protobuf/encoding/prototext"
24 "google.golang.org/protobuf/proto"
25
26 "github.com/google/cel-go/cel"
27 "github.com/google/cel-go/common/types"
28 "github.com/google/cel-go/common/types/ref"
29 "github.com/google/cel-go/ext"
30 "github.com/google/cel-go/interpreter"
31 "github.com/google/go-cmp/cmp"
32 )
33
34 func TestCompile(t *testing.T) {
35 for _, tst := range policyTests {
36 tc := tst
37 t.Run(tc.name, func(t *testing.T) {
38 r := newRunner(tc.name, tc.expr, tc.parseOpts)
39 env, ast, iss := r.compile(t, tc.envOpts, []CompilerOption{})
40 if iss.Err() != nil {
41 t.Fatalf("Compile(%s) failed: %v", r.name, iss.Err())
42 }
43 r.setup(t, env, ast)
44 r.run(t)
45 })
46 }
47 }
48
49 func TestRuleComposerError(t *testing.T) {
50 env, err := cel.NewEnv()
51 if err != nil {
52 t.Fatalf("NewEnv() failed: %v", err)
53 }
54 _, err = NewRuleComposer(env, ExpressionUnnestHeight(-1))
55 if err == nil || !strings.Contains(err.Error(), "invalid unnest") {
56 t.Errorf("NewRuleComposer() got %v, wanted 'invalid unnest'", err)
57 }
58 }
59
60 func TestRuleComposerUnnest(t *testing.T) {
61 for _, tst := range composerUnnestTests {
62 tc := tst
63 t.Run(tc.name, func(t *testing.T) {
64 r := newRunner(tc.name, tc.expr, []ParserOption{})
65 env, rule, iss := r.compileRule(t)
66 if iss.Err() != nil {
67 t.Fatalf("CompileRule() failed: %v", iss.Err())
68 }
69 rc, err := NewRuleComposer(env, tc.composerOpts...)
70 if err != nil {
71 t.Fatalf("NewRuleComposer() failed: %v", err)
72 }
73 ast, iss := rc.Compose(rule)
74 if iss.Err() != nil {
75 t.Fatalf("Compose(rule) failed: %v", iss.Err())
76 }
77 policy := parsePolicy(t, tc.name, []ParserOption{})
78 verifySourceInfoCoverage(t, policy, ast)
79 unparsed, err := cel.AstToString(ast)
80 if err != nil {
81 t.Fatalf("cel.AstToString() failed: %v", err)
82 }
83 if normalize(unparsed) != normalize(tc.composed) {
84 t.Errorf("cel.AstToString() got %s, wanted %s", unparsed, tc.composed)
85 }
86 if !ast.OutputType().IsEquivalentType(tc.outputType) {
87 t.Errorf("ast.OutputType() got %v, wanted %v", ast.OutputType(), tc.outputType)
88 }
89 r.setup(t, env, ast)
90 r.run(t)
91 })
92 }
93 }
94
95 func TestCompileError(t *testing.T) {
96 for _, tst := range policyErrorTests {
97 policy := parsePolicy(t, tst.name, []ParserOption{})
98 _, _, iss := compile(t, tst.name, policy, []cel.EnvOption{}, tst.compilerOpts)
99 if iss.Err() == nil {
100 t.Fatalf("compile(%s) did not error, wanted %s", tst.name, tst.err)
101 }
102 if iss.Err().Error() != tst.err {
103 t.Errorf("compile(%s) got error %s, wanted %s", tst.name, iss.Err().Error(), tst.err)
104 }
105 }
106 }
107
108 func TestCompiledRuleHasOptionalOutput(t *testing.T) {
109 env, err := cel.NewEnv()
110 if err != nil {
111 t.Fatalf("cel.NewEnv() failed: %v", err)
112 }
113 tests := []struct {
114 rule *CompiledRule
115 optional bool
116 }{
117 {rule: &CompiledRule{}, optional: false},
118 {
119 rule: &CompiledRule{
120 matches: []*CompiledMatch{{}},
121 },
122 optional: true,
123 },
124 {
125 rule: &CompiledRule{
126 matches: []*CompiledMatch{{}},
127 },
128 optional: true,
129 },
130 {
131 rule: &CompiledRule{
132 matches: []*CompiledMatch{{cond: mustCompileExpr(t, env, "true")}},
133 },
134 optional: false,
135 },
136 {
137 rule: &CompiledRule{
138 matches: []*CompiledMatch{{cond: mustCompileExpr(t, env, "1 < 0")}},
139 },
140 optional: true,
141 },
142 }
143 for _, tst := range tests {
144 got := tst.rule.HasOptionalOutput()
145 if got != tst.optional {
146 t.Errorf("rule.HasOptionalOutput() got %v, wanted, %v", got, tst.optional)
147 }
148 }
149 }
150
151 func TestMaxNestedExpressions_Error(t *testing.T) {
152 policyName := "required_labels"
153 wantError := `ERROR: testdata/required_labels/policy.yaml:15:8: error configuring compiler option: nested expression limit must be non-negative, non-zero value: -1
154 | name: "required_labels"
155 | .......^`
156 policy := parsePolicy(t, policyName, []ParserOption{})
157 _, _, iss := compile(t, policyName, policy, []cel.EnvOption{}, []CompilerOption{MaxNestedExpressions(-1)})
158 if iss.Err() == nil {
159 t.Fatalf("compile(%s) did not error, wanted %s", policyName, wantError)
160 }
161 if iss.Err().Error() != wantError {
162 t.Errorf("compile(%s) got error %s, wanted %s", policyName, iss.Err().Error(), wantError)
163 }
164 }
165
166 func TestWhitespaceHanlding(t *testing.T) {
167
168 testCases := []struct {
169 matchID string
170 want string
171 }{
172 {
173 matchID: "folded_unambiguous",
174 want: "a string expression that is folded",
175 },
176 {
177 matchID: "folded_line_break",
178 // 8 spaces (4 indents)
179 want: "a string expression that\n is folded",
180 },
181 {
182 matchID: "folded_line_break_indent",
183 // 10 spaces (5 indents)
184 want: "a string expression that\n is folded",
185 },
186 {
187 matchID: "literal_unambiguous",
188 want: "a string expression that is a literal block",
189 },
190 {
191 matchID: "literal_line_break",
192 // 8 spaces (4 indents)
193 want: "a string expression that\n is a literal block",
194 },
195 {
196 matchID: "literal_line_break_indent",
197 // 10 spaces (5 indents)
198 want: "a string expression that\n is a literal block",
199 },
200 }
201
202 policy := parsePolicy(t, "yaml_parsing", []ParserOption{})
203 env, ast, iss := compile(t, "yaml_parsing", policy, []cel.EnvOption{}, []CompilerOption{})
204 if iss.Err() != nil {
205 t.Fatalf("compile('yaml_parsing') failed, %s", iss.Err().Error())
206 }
207
208 p, err := env.PlanProgram(ast.NativeRep())
209
210 if err != nil {
211 t.Fatalf("env.PlanProgram() failed, %s", err.Error())
212 }
213
214 for _, tst := range testCases {
215 t.Run(tst.matchID, func(t *testing.T) {
216
217 in := map[string]any{"match_id": types.String(tst.matchID)}
218
219 result, _, err := p.Eval(in)
220 if err != nil {
221 t.Fatalf("p.Eval(match_id: '%s') failed, %s", tst.matchID, err.Error())
222 }
223 s, ok := result.(types.String)
224 if !ok {
225 t.Fatalf("p.Eval(match_id: '%s') got %v, wanted string", tst.matchID, result)
226 }
227 if dx := cmp.Diff(tst.want, s.Value()); dx != "" {
228 t.Errorf("p.Eval(match_id: '%s') has diffs. (-want, +got): %s", tst.matchID, dx)
229 }
230 })
231 }
232 }
233
234 func TestWhitespaceHandlingErrorPresentation(t *testing.T) {
235 policy := parsePolicy(t, "yaml_parsing_cel_error", []ParserOption{})
236 _, _, iss := compile(t, "yaml_parsing_cel_error", policy, []cel.EnvOption{}, []CompilerOption{})
237 if iss.Err() == nil {
238 t.Fatalf("compile('yaml_parsing_cel_error') did not error, wanted error")
239 }
240
241 wantErrors := []string{
242 `ERROR: testdata/yaml_parsing_cel_error/policy.yaml:11:16: found no matching overload for '_+_' applied to '(string, int)'
243 | ("bar" + 1)
244 | ...............^`,
245 `ERROR: testdata/yaml_parsing_cel_error/policy.yaml:15:18: found no matching overload for '_+_' applied to '(string, int)'
246 | ("bar" + 1)
247 | .................^`,
248 `ERROR: testdata/yaml_parsing_cel_error/policy.yaml:19:16: found no matching overload for '_+_' applied to '(string, int)'
249 | ("bar" + 1)
250 | ...............^`,
251 `ERROR: testdata/yaml_parsing_cel_error/policy.yaml:23:18: found no matching overload for '_+_' applied to '(string, int)'
252 | ("bar" + 1)
253 | .................^`,
254 }
255 found := false
256 for _, wantError := range wantErrors {
257 if !strings.Contains(iss.Err().Error(), wantError) {
258 found = true
259 t.Errorf("compile('yaml_parsing_cel_error') does not contain error %s", wantError)
260 }
261 }
262 if found {
263 t.Errorf("compile('yaml_parsing_cel_error') missing errors, got: %s", iss.Err().Error())
264 }
265 }
266
267 func BenchmarkCompile(b *testing.B) {
268 for _, tst := range policyTests {
269 r := newRunner(tst.name, tst.expr, tst.parseOpts)
270 env, ast, iss := r.compile(b, tst.envOpts, []CompilerOption{})
271 if iss.Err() != nil {
272 b.Fatalf("Compile() failed: %v", iss.Err())
273 }
274 r.setup(b, env, ast)
275 r.bench(b)
276 }
277 }
278
279 func newRunner(name, expr string, parseOpts []ParserOption, opts ...cel.EnvOption) *runner {
280 return &runner{
281 name: name,
282 parseOpts: parseOpts,
283 expr: expr}
284 }
285
286 type runner struct {
287 name string
288 parseOpts []ParserOption
289 env *cel.Env
290 expr string
291 prg cel.Program
292 }
293
294 func (r *runner) compile(t testing.TB, envOpts []cel.EnvOption, compilerOpts []CompilerOption) (*cel.Env, *cel.Ast, *cel.Issues) {
295 policy := parsePolicy(t, r.name, r.parseOpts)
296 return compile(t, r.name, policy, envOpts, compilerOpts)
297 }
298
299 func (r *runner) compileRule(t testing.TB) (*cel.Env, *CompiledRule, *cel.Issues) {
300 t.Helper()
301 config := readPolicyConfig(t, fmt.Sprintf("testdata/%s/config.yaml", r.name))
302 policy := parsePolicy(t, r.name, r.parseOpts)
303 env, err := cel.NewCustomEnv(
304 cel.OptionalTypes(),
305 cel.EnableMacroCallTracking(),
306 cel.ExtendedValidations(),
307 ext.Bindings())
308 if err != nil {
309 t.Fatalf("cel.NewEnv() failed: %v", err)
310 }
311 // Configure declarations
312 env, err = env.Extend(FromConfig(config))
313 if err != nil {
314 t.Fatalf("env.Extend() with config options %v, failed: %v", config, err)
315 }
316 rule, iss := CompileRule(env, policy)
317 return env, rule, iss
318 }
319
320 func (r *runner) setup(t testing.TB, env *cel.Env, ast *cel.Ast) {
321 t.Helper()
322 pExpr, err := cel.AstToString(ast)
323 if err != nil {
324 t.Fatalf("cel.AstToString() failed: %v", err)
325 }
326 _, err = cel.AstToCheckedExpr(ast)
327 if err != nil {
328 t.Fatalf("cel.AstToCheckedExpr() failed: %v", err)
329 }
330 if r.expr != "" && normalize(pExpr) != normalize(r.expr) {
331 t.Errorf("cel.AstToString() got %s, wanted %s", pExpr, r.expr)
332 }
333 prg, err := env.Program(ast, cel.EvalOptions(cel.OptOptimize))
334 if err != nil {
335 t.Fatalf("env.Program() failed: %v", err)
336 }
337 r.env = env
338 r.prg = prg
339 }
340
341 func (r *runner) run(t *testing.T) {
342 tests := readTestSuite(t, fmt.Sprintf("testdata/%s/tests.yaml", r.name))
343 for _, s := range tests.Sections {
344 section := s.Name
345 for _, tst := range s.Tests {
346 tc := tst
347 t.Run(fmt.Sprintf("%s/%s/%s", r.name, section, tc.Name), func(t *testing.T) {
348 input := map[string]any{}
349 var err error
350 var activation interpreter.Activation
351 if tc.InputContext != nil && tc.InputContext.ContextExpr != "" {
352 ctxExpr := tc.InputContext.ContextExpr
353 ctx, err := r.eval(t, ctxExpr).ConvertToNative(
354 reflect.TypeOf(((*proto.Message)(nil))).Elem())
355 if err != nil {
356 t.Fatalf("context variable is not a valid proto: %v", err)
357 }
358 activation, err = cel.ContextProtoVars(ctx.(proto.Message))
359 if err != nil {
360 t.Fatalf("cel.ContextProtoVars() failed: %v", err)
361 }
362 } else if len(tc.Input) != 0 {
363 for k, v := range tc.Input {
364 if v.Expr != "" {
365 input[k] = r.eval(t, v.Expr)
366 continue
367 }
368 input[k] = v.Value
369 }
370 }
371 if activation == nil {
372 activation, err = interpreter.NewActivation(input)
373 if err != nil {
374 t.Fatalf("interpreter.NewActivation(input) failed: %v", err)
375 }
376 }
377 out, _, err := r.prg.Eval(activation)
378 if err != nil {
379 t.Fatalf("prg.Eval(input) failed: %v", err)
380 }
381 var testOut ref.Val
382 if tc.Output.Expr != "" {
383 testOut = r.eval(t, tc.Output.Expr)
384 } else if tc.Output.Value != nil {
385 testOut = r.env.CELTypeAdapter().NativeToValue(tc.Output.Value)
386 }
387 if optOut, ok := out.(*types.Optional); ok {
388 if optOut.Equal(types.OptionalNone) == types.True {
389 if testOut.Equal(types.OptionalNone) != types.True {
390 t.Errorf("policy eval got %v, wanted %v", out, testOut)
391 }
392 } else if testOut.Equal(optOut.GetValue()) != types.True {
393 t.Errorf("policy eval got %v, wanted %v", out, testOut)
394 }
395 } else if testOut.Equal(out) != types.True {
396 t.Errorf("policy eval got %v, wanted %v", out, testOut)
397 }
398 })
399 }
400 }
401 }
402
403 func (r *runner) bench(b *testing.B) {
404 tests := readTestSuite(b, fmt.Sprintf("testdata/%s/tests.yaml", r.name))
405 for _, s := range tests.Sections {
406 section := s.Name
407 for _, tst := range s.Tests {
408 tc := tst
409 b.Run(fmt.Sprintf("%s/%s/%s", r.name, section, tc.Name), func(b *testing.B) {
410 input := map[string]any{}
411 var err error
412 var activation interpreter.Activation
413 if tc.InputContext != nil && tc.InputContext.ContextExpr != "" {
414 ctxExpr := tc.InputContext.ContextExpr
415 ctx, err := r.eval(b, ctxExpr).ConvertToNative(
416 reflect.TypeOf(((*proto.Message)(nil))).Elem())
417 if err != nil {
418 b.Fatalf("context variable is not a valid proto: %v", err)
419 }
420 activation, err = cel.ContextProtoVars(ctx.(proto.Message))
421 if err != nil {
422 b.Fatalf("cel.ContextProtoVars() failed: %v", err)
423 }
424 } else if tc.Input != nil {
425 for k, v := range tc.Input {
426 if v.Expr != "" {
427 input[k] = r.eval(b, v.Expr)
428 continue
429 }
430 input[k] = v.Value
431 }
432 }
433 if activation == nil {
434 activation, err = interpreter.NewActivation(input)
435 if err != nil {
436 b.Fatalf("interpreter.NewActivation(input) failed: %v", err)
437 }
438 }
439 for i := 0; i < b.N; i++ {
440 _, _, err := r.prg.Eval(activation)
441 if err != nil {
442 b.Fatalf("policy eval failed: %v", err)
443 }
444 }
445 })
446 }
447 }
448 }
449
450 func (r *runner) eval(t testing.TB, expr string) ref.Val {
451 wantExpr, iss := r.env.Compile(expr)
452 if iss.Err() != nil {
453 t.Fatalf("env.Compile(%q) failed :%v", expr, iss.Err())
454 }
455 prg, err := r.env.Program(wantExpr)
456 if err != nil {
457 t.Fatalf("env.Program(wantExpr) failed: %v", err)
458 }
459 out, _, err := prg.Eval(cel.NoVars())
460 if err != nil {
461 t.Fatalf("prg.Eval() failed: %v", err)
462 }
463 return out
464 }
465
466 func mustCompileExpr(t testing.TB, env *cel.Env, expr string) *cel.Ast {
467 t.Helper()
468 out, iss := env.Compile(expr)
469 if iss.Err() != nil {
470 t.Fatalf("env.Compile(%s) failed: %v", expr, iss.Err())
471 }
472 return out
473 }
474
475 func parsePolicy(t testing.TB, name string, parseOpts []ParserOption) *Policy {
476 t.Helper()
477 srcFile := readPolicy(t, fmt.Sprintf("testdata/%s/policy.yaml", name))
478 parser, err := NewParser(parseOpts...)
479 if err != nil {
480 t.Fatalf("NewParser() failed: %v", err)
481 }
482 policy, iss := parser.Parse(srcFile)
483 if iss.Err() != nil {
484 t.Fatalf("Parse() failed: %v", iss.Err())
485 }
486 if policy.name.Value != name {
487 t.Errorf("policy name is %v, wanted %q", policy.name, name)
488 }
489 return policy
490 }
491
492 func compile(t testing.TB, name string, policy *Policy, envOpts []cel.EnvOption, compilerOpts []CompilerOption) (*cel.Env, *cel.Ast, *cel.Issues) {
493 config := readPolicyConfig(t, fmt.Sprintf("testdata/%s/config.yaml", name))
494 env, err := cel.NewCustomEnv(
495 cel.OptionalTypes(),
496 cel.EnableMacroCallTracking(),
497 cel.ExtendedValidations(),
498 ext.Bindings())
499 if err != nil {
500 t.Fatalf("cel.NewEnv() failed: %v", err)
501 }
502 // Configure any custom environment options.
503 env, err = env.Extend(envOpts...)
504 if err != nil {
505 t.Fatalf("env.Extend() with env options %v, failed: %v", config, err)
506 }
507 // Configure declarations
508 env, err = env.Extend(FromConfig(config))
509 if err != nil {
510 t.Fatalf("env.Extend() with config options %v, failed: %v", config, err)
511 }
512 ast, iss := Compile(env, policy, compilerOpts...)
513 if iss.Err() == nil {
514 verifySourceInfoCoverage(t, policy, ast)
515 }
516 return env, ast, iss
517 }
518
519 func normalize(s string) string {
520 return strings.ReplaceAll(
521 strings.ReplaceAll(
522 strings.ReplaceAll(s, " ", ""), "\n", ""),
523 "\t", "")
524 }
525
526 func verifySourceInfoCoverage(t testing.TB, policy *Policy, ast *cel.Ast) {
527 t.Helper()
528 info := ast.SourceInfo()
529
530 exprLines := exprLinesFromPolicy(policy)
531 coveredLines := make(map[int]bool)
532 ids := ast.NativeRep().IDs()
533 for id, offset := range info.GetPositions() {
534 if offset <= 0 {
535 t.Errorf("id %d has invalid offset %v", id, offset)
536 }
537 // Check that each position in the SourceInfo corresponds to a valid AST node.
538 if !ids[id] {
539 t.Errorf("id %d not found in AST", id)
540 }
541 loc, found := ast.Source().OffsetLocation(offset)
542 if found {
543 coveredLines[loc.Line()] = true
544 } else {
545 t.Errorf("invalid source location for offset %d", offset)
546 }
547 }
548 // Verify that each source line inside an expression is covered by the at least one node in the
549 // AST.
550 for line := range exprLines {
551 if !coveredLines[line] {
552 t.Errorf("Line %d expected to be covered by SourceInfo, but was not", line)
553 }
554 }
555
556 if t.Failed() {
557 checked, err := cel.AstToCheckedExpr(ast)
558 if err != nil {
559 t.Logf("cel.AstToCheckedExpr() failed: %v", err)
560 } else {
561 t.Logf("AST:\n%s", prototext.Format(checked.GetExpr()))
562 }
563 }
564 }
565
566 // exprLinesFromPolicy returns a set of line numbers within a policy where expressions (variables,
567 // conditions, etc.) are defined.
568 func exprLinesFromPolicy(policy *Policy) map[int]bool {
569 lines := make(map[int]bool)
570 addExpectedLines := func(vs ValueString) {
571 if offset, found := policy.SourceInfo().GetOffsetRange(vs.ID); found {
572 startLoc, foundStart := policy.Source().OffsetLocation(offset.Start)
573 // Multiline strings can span multiple lines, but the SourceInfo will only contain the start
574 // position of the expression. So just skip the check if the expression contains a multiline
575 // string literal.
576 hasMultiline := strings.Contains(vs.Value, "'''") || strings.Contains(vs.Value, "\"\"\"")
577 if foundStart && !hasMultiline {
578 numLines := strings.Count(vs.Value, "\n")
579 for i := 0; i <= numLines; i++ {
580 lines[startLoc.Line()+i] = true
581 }
582 }
583 }
584 }
585 var traverseRule func(r *Rule)
586 traverseRule = func(r *Rule) {
587 for _, v := range r.Variables() {
588 addExpectedLines(v.Expression())
589 }
590 for _, m := range r.Matches() {
591 addExpectedLines(m.Condition())
592 if m.HasOutput() {
593 addExpectedLines(m.Output())
594 }
595 if m.HasRule() {
596 traverseRule(m.Rule())
597 }
598 }
599 }
600 traverseRule(policy.Rule())
601 return lines
602 }