Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/interpreter/attributes_test.go

raw symbols SCIP
1 // Copyright 2019 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 interpreter
16
17 import (
18 "errors"
19 "fmt"
20 "reflect"
21 "testing"
22
23 "github.com/google/cel-go/checker"
24 "github.com/google/cel-go/common"
25 "github.com/google/cel-go/common/containers"
26 "github.com/google/cel-go/common/decls"
27 "github.com/google/cel-go/common/stdlib"
28 "github.com/google/cel-go/common/types"
29 "github.com/google/cel-go/common/types/ref"
30 "github.com/google/cel-go/parser"
31
32 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
33 anypb "google.golang.org/protobuf/types/known/anypb"
34
35 proto3pb "github.com/google/cel-go/test/proto3pb"
36 )
37
38 func TestAttributesAbsoluteAttr(t *testing.T) {
39 reg := newTestRegistry(t)
40 cont, err := containers.NewContainer(containers.Name("acme.ns"))
41 if err != nil {
42 t.Fatal(err)
43 }
44 attrs := NewAttributeFactory(cont, reg, reg)
45 vars, _ := NewActivation(map[string]any{
46 "acme.a": map[string]any{
47 "b": map[uint]any{
48 4: map[bool]string{
49 false: "success",
50 },
51 },
52 },
53 })
54
55 // acme.a.b[4][false]
56 attr := attrs.AbsoluteAttribute(1, "acme.a")
57 qualB := makeQualifier(t, attrs, nil, 2, "b")
58 qual4 := makeQualifier(t, attrs, nil, 3, uint64(4))
59 qualFalse := makeQualifier(t, attrs, nil, 4, false)
60 attr.AddQualifier(qualB)
61 attr.AddQualifier(qual4)
62 attr.AddQualifier(qualFalse)
63 out, err := attr.Resolve(vars)
64 if err != nil {
65 t.Fatal(err)
66 }
67 if out != types.String("success") {
68 t.Errorf("Got %v (%T), wanted success", out, out)
69 }
70 }
71
72 func TestAttributesAbsoluteAttrType(t *testing.T) {
73 reg := newTestRegistry(t)
74 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
75
76 // int
77 attr := attrs.AbsoluteAttribute(1, "int")
78 out, err := attr.Resolve(EmptyActivation())
79 if err != nil {
80 t.Fatal(err)
81 }
82 if out != types.IntType {
83 t.Errorf("Got %v, wanted success", out)
84 }
85 }
86
87 func TestAttributesAbsoluteAttrError(t *testing.T) {
88 reg := newTestRegistry(t)
89 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
90 vars, err := NewActivation(map[string]any{
91 "err": types.NewErr("invalid variable computation"),
92 })
93 if err != nil {
94 t.Fatalf("NewActivation() failed: %v", err)
95 }
96
97 // acme.a.b[4][false]
98 attr := attrs.AbsoluteAttribute(1, "err")
99 qualMsg := makeQualifier(t, attrs, nil, 2, "message")
100 attr.AddQualifier(qualMsg)
101 out, err := attr.Resolve(vars)
102 if err == nil {
103 t.Errorf("attr.Resolve('err') got %v, wanted error", out)
104 }
105 }
106
107 func TestAttributesRelativeAttr(t *testing.T) {
108 reg := newTestRegistry(t)
109 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
110 data := map[string]any{
111 "a": map[int]any{
112 -1: []int32{2, 42},
113 },
114 "b": 1,
115 }
116 vars, _ := NewActivation(data)
117
118 // The relative attribute under test is applied to a map literal:
119 // {
120 // a: {-1: [2, 42], b: 1}
121 // b: 1
122 // }
123 //
124 // The expression being evaluated is: <map-literal>.a[-1][b] -> 42
125 op := NewConstValue(1, reg.NativeToValue(data))
126 attr := attrs.RelativeAttribute(1, op)
127 qualA := makeQualifier(t, attrs, nil, 2, "a")
128 qualNeg1 := makeQualifier(t, attrs, nil, 3, int64(-1))
129 attr.AddQualifier(qualA)
130 attr.AddQualifier(qualNeg1)
131 attr.AddQualifier(attrs.AbsoluteAttribute(4, "b"))
132 out, err := attr.Resolve(vars)
133 if err != nil {
134 t.Fatal(err)
135 }
136 if out != types.Int(42) {
137 t.Errorf("Got %v (%T), wanted 42", out, out)
138 }
139 }
140
141 func TestAttributesRelativeAttrOneOf(t *testing.T) {
142 reg := newTestRegistry(t)
143 cont, err := containers.NewContainer(containers.Name("acme.ns"))
144 if err != nil {
145 t.Fatal(err)
146 }
147 attrs := NewAttributeFactory(cont, reg, reg)
148 data := map[string]any{
149 "a": map[int]any{
150 -1: []int32{2, 42},
151 },
152 "acme.b": 1,
153 }
154 vars, _ := NewActivation(data)
155
156 // The relative attribute under test is applied to a map literal:
157 // {
158 // a: {-1: [2, 42], b: 1}
159 // b: 1
160 // }
161 //
162 // The expression being evaluated is: <map-literal>.a[-1][b] -> 42
163 //
164 // However, since the test is validating what happens with maybe attributes
165 // the attribute resolution must also consider the following variations:
166 // - <map-literal>.a[-1][acme.ns.b]
167 // - <map-literal>.a[-1][acme.b]
168 //
169 // The correct behavior should yield the value of the last alternative.
170 op := NewConstValue(1, reg.NativeToValue(data))
171 attr := attrs.RelativeAttribute(1, op)
172 qualA := makeQualifier(t, attrs, nil, 2, "a")
173 qualNeg1 := makeQualifier(t, attrs, nil, 3, int64(-1))
174 attr.AddQualifier(qualA)
175 attr.AddQualifier(qualNeg1)
176 attr.AddQualifier(attrs.MaybeAttribute(4, "b"))
177 out, err := attr.Resolve(vars)
178 if err != nil {
179 t.Fatal(err)
180 }
181 if out != types.Int(42) {
182 t.Errorf("Got %v (%T), wanted 42", out, out)
183 }
184 }
185
186 func TestAttributesRelativeAttrConditional(t *testing.T) {
187 reg := newTestRegistry(t)
188 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
189 data := map[string]any{
190 "a": map[int]any{
191 -1: []int32{2, 42},
192 },
193 "b": []int{0, 1},
194 "c": []any{1, 0},
195 }
196 vars, _ := NewActivation(data)
197
198 // The relative attribute under test is applied to a map literal:
199 // {
200 // a: {-1: [2, 42], b: 1}
201 // b: [0, 1],
202 // c: {1, 0},
203 // }
204 //
205 // The expression being evaluated is:
206 // <map-literal>.a[-1][(false ? b : c)[0]] -> 42
207 //
208 // Effectively the same as saying <map-literal>.a[-1][c[0]]
209 cond := NewConstValue(2, types.False)
210 condAttr := attrs.ConditionalAttribute(4, cond,
211 attrs.AbsoluteAttribute(5, "b"),
212 attrs.AbsoluteAttribute(6, "c"))
213 qual0 := makeQualifier(t, attrs, nil, 7, 0)
214 condAttr.AddQualifier(qual0)
215
216 obj := NewConstValue(1, reg.NativeToValue(data))
217 attr := attrs.RelativeAttribute(1, obj)
218 qualA := makeQualifier(t, attrs, nil, 2, "a")
219 qualNeg1 := makeQualifier(t, attrs, nil, 3, int64(-1))
220 attr.AddQualifier(qualA)
221 attr.AddQualifier(qualNeg1)
222 attr.AddQualifier(condAttr)
223 out, err := attr.Resolve(vars)
224 if err != nil {
225 t.Fatal(err)
226 }
227 if out != types.Int(42) {
228 t.Errorf("Got %v (%T), wanted 42", out, out)
229 }
230 }
231
232 func TestAttributesRelativeAttrRelativeQualifier(t *testing.T) {
233 cont, err := containers.NewContainer(containers.Name("acme.ns"))
234 if err != nil {
235 t.Fatal(err)
236 }
237 reg := newTestRegistry(t)
238 attrs := NewAttributeFactory(cont, reg, reg)
239 data := map[string]any{
240 "a": map[int]any{
241 -1: map[string]any{
242 "first": uint(1),
243 "second": uint(2),
244 "third": uint(3),
245 },
246 },
247 "b": uint32(2),
248 }
249 vars, _ := NewActivation(data)
250
251 // The environment declares the following variables:
252 // {
253 // a: {
254 // -1: {
255 // "first": 1u,
256 // "second": 2u,
257 // "third": 3u,
258 // }
259 // },
260 // b: 2u,
261 // }
262 //
263 // The map of input variables is also re-used as a map-literal <obj> in the expression.
264 //
265 // The relative object under test is the following map literal.
266 // <mp> {
267 // 1u: "first",
268 // 2u: "second",
269 // 3u: "third",
270 // }
271 //
272 // The expression under test is:
273 // <obj>.a[-1][<mp>[b]]
274 //
275 // This is equivalent to:
276 // <obj>.a[-1]["second"] -> 2u
277 obj := NewConstValue(1, reg.NativeToValue(data))
278 mp := NewConstValue(1, reg.NativeToValue(map[uint32]any{
279 1: "first",
280 2: "second",
281 3: "third",
282 }))
283 relAttr := attrs.RelativeAttribute(4, mp)
284 qualB := makeQualifier(t, attrs, nil, 5, attrs.AbsoluteAttribute(5, "b"))
285 relAttr.AddQualifier(qualB)
286 attr := attrs.RelativeAttribute(1, obj)
287 qualA := makeQualifier(t, attrs, nil, 2, "a")
288 qualNeg1 := makeQualifier(t, attrs, nil, 3, int64(-1))
289 attr.AddQualifier(qualA)
290 attr.AddQualifier(qualNeg1)
291 attr.AddQualifier(relAttr)
292
293 out, err := attr.Resolve(vars)
294 if err != nil {
295 t.Fatal(err)
296 }
297 if out != types.Uint(2) {
298 t.Errorf("Got %v (%T), wanted 2", out, out)
299 }
300 }
301
302 func TestAttributesOneofAttr(t *testing.T) {
303 reg := newTestRegistry(t)
304 cont, err := containers.NewContainer(containers.Name("acme.ns"))
305 if err != nil {
306 t.Fatal(err)
307 }
308 attrs := NewAttributeFactory(cont, reg, reg)
309 data := map[string]any{
310 "a": map[string]any{
311 "b": []int32{2, 42},
312 },
313 "acme.a.b": 1,
314 "acme.ns.a.b": "found",
315 }
316 vars, _ := NewActivation(data)
317
318 // a.b -> should resolve to acme.ns.a.b per namespace resolution rules.
319 attr := attrs.MaybeAttribute(1, "a")
320 qualB := makeQualifier(t, attrs, nil, 2, "b")
321 attr.AddQualifier(qualB)
322 out, err := attr.Resolve(vars)
323 if err != nil {
324 t.Fatal(err)
325 }
326 if out != "found" {
327 t.Errorf("Got %v, wanted 'found'", out)
328 }
329 }
330
331 func TestAttributesConditionalAttrTrueBranch(t *testing.T) {
332 reg := newTestRegistry(t)
333 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
334 data := map[string]any{
335 "a": map[int]any{
336 -1: []int32{2, 42},
337 },
338 "b": map[string]any{
339 "c": map[int32]any{
340 -1: []uint{2, 42},
341 },
342 },
343 }
344 vars, _ := NewActivation(data)
345
346 // (true ? a : b.c)[-1][1]
347 tv := attrs.AbsoluteAttribute(2, "a")
348 fv := attrs.MaybeAttribute(3, "b")
349 qualC := makeQualifier(t, attrs, nil, 4, "c")
350 fv.AddQualifier(qualC)
351 cond := attrs.ConditionalAttribute(1, NewConstValue(0, types.True), tv, fv)
352 qualNeg1 := makeQualifier(t, attrs, nil, 5, int64(-1))
353 qual1 := makeQualifier(t, attrs, nil, 6, int64(1))
354 cond.AddQualifier(qualNeg1)
355 cond.AddQualifier(qual1)
356 out, err := cond.Resolve(vars)
357 if err != nil {
358 t.Fatal(err)
359 }
360 if out != int32(42) {
361 t.Errorf("Got %v (%T), wanted 42", out, out)
362 }
363 }
364
365 func TestAttributesConditionalAttrFalseBranch(t *testing.T) {
366 reg := newTestRegistry(t)
367 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
368 data := map[string]any{
369 "a": map[int]any{
370 -1: []int32{2, 42},
371 },
372 "b": map[string]any{
373 "c": map[int32]any{
374 -1: []uint{2, 42},
375 },
376 },
377 }
378 vars, _ := NewActivation(data)
379
380 // (false ? a : b.c)[-1][1]
381 tv := attrs.AbsoluteAttribute(2, "a")
382 fv := attrs.MaybeAttribute(3, "b")
383 qualC := makeQualifier(t, attrs, nil, 4, "c")
384 fv.AddQualifier(qualC)
385 cond := attrs.ConditionalAttribute(1, NewConstValue(0, types.False), tv, fv)
386 qualNeg1 := makeQualifier(t, attrs, nil, 5, int64(-1))
387 qual1 := makeQualifier(t, attrs, nil, 6, int64(1))
388 cond.AddQualifier(qualNeg1)
389 cond.AddQualifier(qual1)
390 out, err := cond.Resolve(vars)
391 if err != nil {
392 t.Fatal(err)
393 }
394 if out != uint(42) {
395 t.Errorf("Got %v (%T), wanted 42", out, out)
396 }
397 }
398
399 func TestAttributesOptional(t *testing.T) {
400 reg := newTestRegistry(t, &proto3pb.TestAllTypes{})
401 cont, err := containers.NewContainer(containers.Name("ns"))
402 if err != nil {
403 t.Fatalf("")
404 }
405 attrs := NewAttributeFactory(cont, reg, reg)
406 tests := []struct {
407 varName string
408 quals []any
409 optQuals []any
410 vars map[string]any
411 out any
412 err error
413 }{
414 {
415 // a.?b[0][false]
416 varName: "a",
417 optQuals: []any{"b", int32(0), false},
418 vars: map[string]any{
419 "a": map[string]any{
420 "b": map[int]any{
421 0: map[bool]string{
422 false: "success",
423 },
424 },
425 },
426 },
427 out: types.OptionalOf(reg.NativeToValue("success")),
428 },
429 {
430 // a.?b[0][false]
431 varName: "a",
432 optQuals: []any{"b", uint32(0), false},
433 vars: map[string]any{
434 "a": map[string]any{
435 "b": map[int]any{
436 0: map[bool]string{
437 false: "success",
438 },
439 },
440 },
441 },
442 out: types.OptionalOf(reg.NativeToValue("success")),
443 },
444 {
445 // a.?b[0][false]
446 varName: "a",
447 optQuals: []any{"b", float32(0), false},
448 vars: map[string]any{
449 "a": map[string]any{
450 "b": map[int]any{
451 0: map[bool]string{
452 false: "success",
453 },
454 },
455 },
456 },
457 out: types.OptionalOf(reg.NativeToValue("success")),
458 },
459 {
460 // a.?b[1] with no value
461 varName: "a",
462 optQuals: []any{"b", uint(1)},
463 vars: map[string]any{
464 "a": map[string]any{
465 "b": map[uint]any{},
466 },
467 },
468 out: types.OptionalNone,
469 },
470 {
471 // a.b[1] with no value where b is a map[uint]
472 varName: "a",
473 quals: []any{"b", uint(1)},
474 vars: map[string]any{
475 "a": map[string]any{
476 "b": map[uint]any{},
477 },
478 },
479 err: errors.New("no such key: 1"),
480 },
481 {
482 // a.b[?1] with no value where 'b' is a []int
483 varName: "a",
484 quals: []any{"b"},
485 optQuals: []any{1},
486 vars: map[string]any{
487 "a": map[string]any{
488 "b": []int{},
489 },
490 },
491 out: types.OptionalNone,
492 },
493 {
494 // a.b[1] with no value where 'b' is a map[int]any
495 varName: "a",
496 quals: []any{"b", 1},
497 vars: map[string]any{
498 "a": map[string]any{
499 "b": map[int]any{},
500 },
501 },
502 err: errors.New("no such key: 1"),
503 },
504 {
505 // a.b[?1] with no value where 'b' is a []int
506 varName: "a",
507 quals: []any{"b", 1, false},
508 optQuals: []any{},
509 vars: map[string]any{
510 "a": map[string]any{
511 "b": []int{},
512 },
513 },
514 err: errors.New("index out of bounds: 1"),
515 },
516 {
517 // a.?b[0][true] with no value
518 varName: "a",
519 optQuals: []any{"b", 0, false},
520 vars: map[string]any{
521 "a": map[string]any{
522 "b": map[int]any{
523 0: map[bool]any{},
524 },
525 },
526 },
527 out: types.OptionalNone,
528 },
529 {
530 // a.b[0][?true] with no value
531 varName: "a",
532 quals: []any{"b", 0},
533 optQuals: []any{true},
534 vars: map[string]any{
535 "a": map[string]any{
536 "b": map[int]any{
537 0: map[bool]any{},
538 },
539 },
540 },
541 out: types.OptionalNone,
542 },
543 {
544 // a.b[0][true] with no value
545 varName: "a",
546 quals: []any{"b", 0, true},
547 vars: map[string]any{
548 "a": map[string]any{
549 "b": map[int]any{
550 0: map[bool]any{},
551 },
552 },
553 },
554 err: errors.New("no such key: true"),
555 },
556 {
557 // a.b[0][false] where 'a' is optional
558 varName: "a",
559 quals: []any{"b", int32(0), false},
560 vars: map[string]any{
561 "a": types.OptionalOf(reg.NativeToValue(map[string]any{
562 "b": map[int]any{
563 0: map[bool]string{
564 false: "success",
565 },
566 },
567 })),
568 },
569 out: types.OptionalOf(reg.NativeToValue("success")),
570 },
571 {
572 // a.b[0][false] where 'a' is optional none.
573 varName: "a",
574 quals: []any{"b", int32(0), false},
575 vars: map[string]any{
576 "a": types.OptionalNone,
577 },
578 out: types.OptionalNone,
579 },
580 {
581 // a.?c[1][true]
582 varName: "a",
583 optQuals: []any{"c", int32(1), true},
584 vars: map[string]any{
585 "a": map[string]any{},
586 },
587 out: types.OptionalNone,
588 },
589 {
590 // a[?b] where 'b' is dynamically computed.
591 varName: "a",
592 optQuals: []any{attrs.AbsoluteAttribute(0, "b")},
593 vars: map[string]any{
594 "a": map[string]any{
595 "hello": "world",
596 },
597 "b": "hello",
598 },
599 out: types.OptionalOf(reg.NativeToValue("world")),
600 },
601 {
602 // a[?(false ? : b : c.d.e)]
603 varName: "a",
604 optQuals: []any{
605 attrs.ConditionalAttribute(0,
606 NewConstValue(100, types.False),
607 attrs.AbsoluteAttribute(101, "b"),
608 attrs.MaybeAttribute(102, "c.d.e")),
609 },
610 vars: map[string]any{
611 "a": map[string]any{
612 "hello": "world",
613 "goodbye": "universe",
614 },
615 "b": "hello",
616 "c.d.e": "goodbye",
617 },
618 out: types.OptionalOf(reg.NativeToValue("universe")),
619 },
620 {
621 // a[?c.d.e]
622 varName: "a",
623 optQuals: []any{
624 attrs.MaybeAttribute(102, "c.d.e"),
625 },
626 vars: map[string]any{
627 "a": map[string]any{
628 "hello": "world",
629 "goodbye": "universe",
630 },
631 "b": "hello",
632 "c.d.e": "goodbye",
633 },
634 out: types.OptionalOf(reg.NativeToValue("universe")),
635 },
636 {
637 // a[c.d.e] where the c.d.e errors
638 varName: "a",
639 quals: []any{
640 addQualifier(t, attrs.MaybeAttribute(102, "c.d"), makeQualifier(t, attrs, nil, 103, "e")),
641 },
642 vars: map[string]any{
643 "a": map[string]any{
644 "goodbye": "universe",
645 },
646 "c.d": map[string]any{},
647 },
648 err: errors.New("no such key: e"),
649 },
650 {
651 // a[?c.d.e] where the c.d.e errors
652 varName: "a",
653 optQuals: []any{
654 addQualifier(t, attrs.MaybeAttribute(102, "c.d"), makeQualifier(t, attrs, nil, 103, "e")),
655 },
656 vars: map[string]any{
657 "a": map[string]any{
658 "goodbye": "universe",
659 },
660 "c.d": map[string]any{},
661 },
662 err: errors.New("no such key: e"),
663 },
664 {
665 // a.?single_int32 with a value.
666 varName: "a",
667 optQuals: []any{"single_int32"},
668 vars: map[string]any{
669 "a": &proto3pb.TestAllTypes{SingleInt32: 1},
670 },
671 out: types.OptionalOf(reg.NativeToValue(1)),
672 },
673 {
674 // a.?single_int32 where the field is not set.
675 varName: "a",
676 optQuals: []any{"single_int32"},
677 vars: map[string]any{
678 "a": &proto3pb.TestAllTypes{},
679 },
680 out: types.OptionalNone,
681 },
682 {
683 // a.?single_int32 where the field is set (uses more optimal selection logic)
684 varName: "a",
685 optQuals: []any{
686 makeOptQualifier(t,
687 attrs,
688 types.NewObjectType("google.expr.proto3.test.TestAllTypes"),
689 103,
690 "single_int32",
691 ),
692 },
693 vars: map[string]any{
694 "a": &proto3pb.TestAllTypes{SingleInt32: 1},
695 },
696 out: types.OptionalOf(reg.NativeToValue(1)),
697 },
698 {
699 // a.c[1][true]
700 varName: "a",
701 quals: []any{"c", int32(1), true},
702 vars: map[string]any{
703 "a": map[string]any{},
704 },
705 err: errors.New("no such key: c"),
706 },
707 {
708 // a, no bindings
709 varName: "a",
710 quals: []any{},
711 vars: map[string]any{},
712 err: errors.New("no such attribute(s): a"),
713 },
714 }
715 for i, tst := range tests {
716 tc := tst
717 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
718 i := int64(1)
719 attr := attrs.AbsoluteAttribute(i, tc.varName)
720 for _, q := range tc.quals {
721 i++
722 attr.AddQualifier(makeQualifier(t, attrs, nil, i, q))
723 }
724 for _, oq := range tc.optQuals {
725 i++
726 attr.AddQualifier(makeOptQualifier(t, attrs, nil, i, oq))
727 }
728 vars, err := NewActivation(tc.vars)
729 if err != nil {
730 t.Fatalf("NewActivation() failed: %v", err)
731 }
732 out, err := attr.Resolve(vars)
733 if err != nil {
734 if tc.err != nil {
735 if tc.err.Error() == err.Error() {
736 return
737 }
738 t.Fatalf("attr.Resolve() errored with %v, wanted error %v", err, tc.err)
739 }
740 t.Fatalf("attr.Resolve() failed: %v", err)
741 }
742 if !reflect.DeepEqual(out, tc.out) {
743 t.Errorf("attr.Resolve() got %v, wanted %v", out, tc.out)
744 }
745 })
746 }
747 }
748
749 func TestAttributesConditionalAttrErrorUnknown(t *testing.T) {
750 reg := newTestRegistry(t)
751 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
752
753 // err ? a : b
754 tv := attrs.AbsoluteAttribute(2, "a")
755 fv := attrs.MaybeAttribute(3, "b")
756 cond := attrs.ConditionalAttribute(1, NewConstValue(0, types.NewErr("test error")), tv, fv)
757 out, err := cond.Resolve(EmptyActivation())
758 if err == nil {
759 t.Errorf("Got %v, wanted error", out)
760 }
761
762 // unk ? a : b
763 condUnk := attrs.ConditionalAttribute(1, NewConstValue(0, types.NewUnknown(1, nil)), tv, fv)
764 out, err = condUnk.Resolve(EmptyActivation())
765 if err != nil {
766 t.Fatal(err)
767 }
768 if !types.IsUnknown(out.(ref.Val)) {
769 t.Errorf("Got %v, wanted unknown", out)
770 }
771 }
772
773 func BenchmarkResolverFieldQualifier(b *testing.B) {
774 msg := &proto3pb.TestAllTypes{
775 NestedType: &proto3pb.TestAllTypes_SingleNestedMessage{
776 SingleNestedMessage: &proto3pb.TestAllTypes_NestedMessage{
777 Bb: 123,
778 },
779 },
780 }
781 reg := newTestRegistry(b, msg)
782 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
783 vars, _ := NewActivation(map[string]any{
784 "msg": msg,
785 })
786 attr := attrs.AbsoluteAttribute(1, "msg")
787 opType, found := reg.FindType("google.expr.proto3.test.TestAllTypes")
788 if !found {
789 b.Fatal("FindType() could not find TestAllTypes")
790 }
791 fieldType, found := reg.FindType("google.expr.proto3.test.TestAllTypes.NestedMessage")
792 if !found {
793 b.Fatal("FindType() could not find NestedMessage")
794 }
795 attr.AddQualifier(makeQualifier(b, attrs, testExprTypeToType(b, opType), 2, "single_nested_message"))
796 attr.AddQualifier(makeQualifier(b, attrs, testExprTypeToType(b, fieldType), 3, "bb"))
797 b.ResetTimer()
798 for i := 0; i < b.N; i++ {
799 _, err := attr.Resolve(vars)
800 if err != nil {
801 b.Fatal(err)
802 }
803 }
804 }
805
806 func TestResolverCustomQualifier(t *testing.T) {
807 reg := newTestRegistry(t)
808 attrs := &custAttrFactory{
809 AttributeFactory: NewAttributeFactory(containers.DefaultContainer, reg, reg),
810 }
811 msg := &proto3pb.TestAllTypes_NestedMessage{
812 Bb: 123,
813 }
814 vars, _ := NewActivation(map[string]any{
815 "msg": msg,
816 })
817 attr := attrs.AbsoluteAttribute(1, "msg")
818 fieldType := types.NewObjectType("google.expr.proto3.test.TestAllTypes.NestedMessage")
819 qualBB := makeQualifier(t, attrs, fieldType, 2, "bb")
820 attr.AddQualifier(qualBB)
821 out, err := attr.Resolve(vars)
822 if err != nil {
823 t.Error(err)
824 }
825 if out != int32(123) {
826 t.Errorf("Got %v, wanted 123", out)
827 }
828 }
829
830 func TestAttributesMissingMsg(t *testing.T) {
831 reg := newTestRegistry(t)
832 attrs := NewAttributeFactory(containers.DefaultContainer, reg, reg)
833 anyPB, _ := anypb.New(&proto3pb.TestAllTypes{})
834 vars, _ := NewActivation(map[string]any{
835 "missing_msg": anyPB,
836 })
837
838 // missing_msg.field
839 attr := attrs.AbsoluteAttribute(1, "missing_msg")
840 field := makeQualifier(t, attrs, nil, 2, "field")
841 attr.AddQualifier(field)
842 out, err := attr.Resolve(vars)
843 if err == nil {
844 t.Fatalf("got %v, wanted error", out)
845 }
846 if err.Error() != "unknown type: 'google.expr.proto3.test.TestAllTypes'" {
847 t.Fatalf("got %v, wanted unknown type: 'google.expr.proto3.test.TestAllTypes'", err)
848 }
849 }
850
851 func TestAttributeMissingMsgUnknownField(t *testing.T) {
852 reg := newTestRegistry(t)
853 attrs := NewPartialAttributeFactory(containers.DefaultContainer, reg, reg)
854 anyPB, _ := anypb.New(&proto3pb.TestAllTypes{})
855 vars, _ := NewPartialActivation(map[string]any{
856 "missing_msg": anyPB,
857 }, NewAttributePattern("missing_msg").QualString("field"))
858
859 // missing_msg.field
860 attr := attrs.AbsoluteAttribute(1, "missing_msg")
861 field := makeQualifier(t, attrs, nil, 2, "field")
862 attr.AddQualifier(field)
863 out, err := attr.Resolve(vars)
864 if err != nil {
865 t.Fatal(err)
866 }
867 _, isUnk := out.(*types.Unknown)
868 if !isUnk {
869 t.Errorf("got %v, wanted unknown value", out)
870 }
871 }
872
873 func TestAttributeStateTracking(t *testing.T) {
874 var tests = []struct {
875 expr string
876 vars []*decls.VariableDecl
877 in any
878 out ref.Val
879 attrs []*AttributePattern
880 state map[int64]any
881 }{
882 {
883 expr: `[{"field": true}][0].field`,
884 vars: []*decls.VariableDecl{},
885 in: map[string]any{},
886 out: types.True,
887 state: map[int64]any{
888 // [{"field": true}]
889 1: []ref.Val{types.DefaultTypeAdapter.NativeToValue(map[ref.Val]ref.Val{types.String("field"): types.True})},
890 // [{"field": true}][0]
891 6: map[ref.Val]ref.Val{types.String("field"): types.True},
892 // [{"field": true}][0].field
893 8: true,
894 },
895 },
896 {
897 expr: `a[1]['two']`,
898 vars: []*decls.VariableDecl{
899 decls.NewVariable("a", types.NewMapType(
900 types.IntType,
901 types.NewMapType(types.StringType, types.BoolType))),
902 },
903 in: map[string]any{
904 "a": map[int64]any{
905 1: map[string]bool{
906 "two": true,
907 },
908 },
909 },
910 out: types.True,
911 state: map[int64]any{
912 // a[1]
913 2: map[string]bool{"two": true},
914 // a[1]["two"]
915 4: true,
916 },
917 },
918 {
919 expr: `a[1][2][3]`,
920 vars: []*decls.VariableDecl{
921 decls.NewVariable("a", types.NewMapType(
922 types.IntType,
923 types.NewMapType(types.DynType, types.DynType))),
924 },
925 in: map[string]any{
926 "a": map[int64]any{
927 1: map[int64]any{
928 1: 0,
929 2: []string{"index", "middex", "outdex", "dex"},
930 },
931 },
932 },
933 out: types.String("dex"),
934 state: map[int64]any{
935 // a[1]
936 2: map[int64]any{
937 1: 0,
938 2: []string{"index", "middex", "outdex", "dex"},
939 },
940 // a[1][2]
941 4: []string{"index", "middex", "outdex", "dex"},
942 // a[1][2][3]
943 6: "dex",
944 },
945 },
946 {
947 expr: `a[1][2][a[1][1]]`,
948 vars: []*decls.VariableDecl{
949 decls.NewVariable("a", types.NewMapType(
950 types.IntType,
951 types.NewMapType(types.DynType, types.DynType))),
952 },
953 in: map[string]any{
954 "a": map[int64]any{
955 1: map[int64]any{
956 1: 0,
957 2: []string{"index", "middex", "outdex", "dex"},
958 },
959 },
960 },
961 out: types.String("index"),
962 state: map[int64]any{
963 // a[1]
964 2: map[int64]any{
965 1: 0,
966 2: []string{"index", "middex", "outdex", "dex"},
967 },
968 // a[1][2]
969 4: []string{"index", "middex", "outdex", "dex"},
970 // a[1][2][a[1][1]]
971 6: "index",
972 // dynamic index into a[1][2]
973 // a[1]
974 8: map[int64]any{
975 1: 0,
976 2: []string{"index", "middex", "outdex", "dex"},
977 },
978 // a[1][1]
979 10: int64(0),
980 },
981 },
982 {
983 expr: `true ? a : b`,
984 vars: []*decls.VariableDecl{
985 decls.NewVariable("a", types.StringType),
986 decls.NewVariable("b", types.StringType),
987 },
988 in: map[string]any{
989 "a": "hello",
990 "b": "world",
991 },
992 out: types.String("hello"),
993 state: map[int64]any{
994 // 'hello'
995 2: types.String("hello"),
996 },
997 },
998 {
999 expr: `(a.size() != 0 ? a : b)[0]`,
1000 vars: []*decls.VariableDecl{
1001 decls.NewVariable("a", types.NewListType(types.StringType)),
1002 decls.NewVariable("b", types.NewListType(types.StringType)),
1003 },
1004 in: map[string]any{
1005 "a": []string{"hello", "world"},
1006 "b": []string{"world", "hello"},
1007 },
1008 out: types.String("hello"),
1009 state: map[int64]any{
1010 // ["hello", "world"]
1011 1: types.DefaultTypeAdapter.NativeToValue([]string{"hello", "world"}),
1012 // ["hello", "world"].size() // 2
1013 2: types.Int(2),
1014 // ["hello", "world"].size() != 0
1015 3: types.True,
1016 // constant 0
1017 4: types.IntZero,
1018 // 'hello'
1019 8: types.String("hello"),
1020 },
1021 },
1022 {
1023 expr: `a.?b.c`,
1024 vars: []*decls.VariableDecl{
1025 decls.NewVariable("a", types.NewMapType(types.StringType, types.NewMapType(types.StringType, types.StringType))),
1026 },
1027 in: map[string]any{
1028 "a": map[string]any{"b": map[string]any{"c": "world"}},
1029 },
1030 out: types.OptionalOf(types.String("world")),
1031 state: map[int64]any{
1032 // {c: world}
1033 3: types.DefaultTypeAdapter.NativeToValue(map[string]string{"c": "world"}),
1034 // 'world'
1035 4: types.OptionalOf(types.String("world")),
1036 },
1037 },
1038 {
1039 expr: `a.?b.c`,
1040 vars: []*decls.VariableDecl{
1041 decls.NewVariable("a", types.NewMapType(types.StringType, types.NewMapType(types.StringType, types.StringType))),
1042 },
1043 in: map[string]any{
1044 "a": map[string]any{"b": map[string]string{"random": "value"}},
1045 },
1046 out: types.OptionalNone,
1047 state: map[int64]any{
1048 // {random: value}
1049 3: types.DefaultTypeAdapter.NativeToValue(map[string]string{"random": "value"}),
1050 // optional.none()
1051 4: types.OptionalNone,
1052 },
1053 },
1054 {
1055 expr: `a.b.c`,
1056 vars: []*decls.VariableDecl{
1057 decls.NewVariable("a", types.NewMapType(types.StringType, types.NewMapType(types.StringType, types.StringType))),
1058 },
1059 in: map[string]any{
1060 "a": map[string]any{"b": map[string]any{"c": "world"}},
1061 },
1062 out: types.String("world"),
1063 state: map[int64]any{
1064 // {c: world}
1065 2: types.DefaultTypeAdapter.NativeToValue(map[string]string{"c": "world"}),
1066 // 'world'
1067 3: types.String("world"),
1068 },
1069 },
1070 {
1071 expr: `m[has(a.b)]`,
1072 vars: []*decls.VariableDecl{
1073 decls.NewVariable("a", types.NewMapType(types.StringType, types.StringType)),
1074 decls.NewVariable("m", types.NewMapType(types.BoolType, types.StringType)),
1075 },
1076 in: map[string]any{
1077 "a": map[string]string{"b": ""},
1078 "m": map[bool]string{true: "world"},
1079 },
1080 out: types.String("world"),
1081 },
1082 {
1083 expr: `m[?has(a.b)]`,
1084 vars: []*decls.VariableDecl{
1085 decls.NewVariable("a", types.NewMapType(types.StringType, types.StringType)),
1086 decls.NewVariable("m", types.NewMapType(types.BoolType, types.StringType)),
1087 },
1088 in: map[string]any{
1089 "a": map[string]string{"b": ""},
1090 "m": map[bool]string{true: "world"},
1091 },
1092 out: types.OptionalOf(types.String("world")),
1093 },
1094 {
1095 expr: `m[?has(a.b.c)]`,
1096 vars: []*decls.VariableDecl{
1097 decls.NewVariable("a", types.NewMapType(types.StringType, types.DynType)),
1098 decls.NewVariable("m", types.NewMapType(types.BoolType, types.StringType)),
1099 },
1100 in: partialActivation(
1101 map[string]any{
1102 "a": map[string]any{},
1103 "m": map[bool]string{true: "world"},
1104 },
1105 NewAttributePattern("a").QualString("b"),
1106 ),
1107 out: types.NewUnknown(5, types.QualifyAttribute[string](types.NewAttributeTrail("a"), "b")),
1108 },
1109 }
1110 for _, test := range tests {
1111 tc := test
1112 t.Run(tc.expr, func(t *testing.T) {
1113 src := common.NewTextSource(tc.expr)
1114 p, err := parser.NewParser(
1115 parser.EnableOptionalSyntax(true),
1116 parser.Macros(parser.AllMacros...),
1117 )
1118 if err != nil {
1119 t.Fatalf("parser.NewParser() failed: %v", err)
1120 }
1121 parsed, errors := p.Parse(src)
1122 if len(errors.GetErrors()) != 0 {
1123 t.Fatal(errors.ToDisplayString())
1124 }
1125 cont := containers.DefaultContainer
1126 reg := newTestRegistry(t)
1127 env, err := checker.NewEnv(cont, reg)
1128 if err != nil {
1129 t.Fatalf("checker.NewEnv() failed: %v", err)
1130 }
1131 env.AddFunctions(stdlib.Functions()...)
1132 env.AddFunctions(optionalDecls(t)...)
1133 if tc.vars != nil {
1134 env.AddIdents(tc.vars...)
1135 }
1136 checked, errors := checker.Check(parsed, src, env)
1137 if len(errors.GetErrors()) != 0 {
1138 t.Fatal(errors.ToDisplayString())
1139 }
1140 in, err := NewActivation(tc.in)
1141 if err != nil {
1142 t.Fatalf("NewActivation(%v) failed: %v", tc.in, err)
1143 }
1144 var attrs AttributeFactory
1145 _, isPartial := in.(PartialActivation)
1146 if isPartial {
1147 attrs = NewPartialAttributeFactory(cont, reg, reg)
1148 } else {
1149 attrs = NewAttributeFactory(cont, reg, reg)
1150 }
1151 interp := newStandardInterpreter(t, cont, reg, reg, attrs)
1152 // Show that program planning will now produce an error.
1153 type stateHolder struct {
1154 st EvalState
1155 }
1156 holder := stateHolder{}
1157 i, err := interp.NewInterpretable(checked, Optimize(),
1158 EvalStateObserver(EvalStateFactory(func() EvalState {
1159 holder.st = NewEvalState()
1160 return holder.st
1161 })))
1162 if err != nil {
1163 t.Fatal(err)
1164 }
1165 if err != nil {
1166 t.Fatal(err)
1167 }
1168 out := i.Eval(in)
1169 if types.IsUnknown(tc.out) && types.IsUnknown(out) {
1170 if !reflect.DeepEqual(tc.out, out) {
1171 t.Errorf("got %v, wanted %v", out, tc.out)
1172 }
1173 } else if tc.out.Equal(out) != types.True {
1174 t.Errorf("got %v, wanted %v", out, tc.out)
1175 }
1176 for id, val := range tc.state {
1177 stVal, found := holder.st.Value(id)
1178 if !found {
1179 for _, id := range holder.st.IDs() {
1180 v, _ := holder.st.Value(id)
1181 t.Error(id, v)
1182 }
1183 t.Errorf("state not found for %d=%v", id, val)
1184 continue
1185 }
1186 wantStVal := types.DefaultTypeAdapter.NativeToValue(val)
1187 if wantStVal.Equal(stVal) != types.True {
1188 t.Errorf("got %v, wanted %v for id: %d", stVal.Value(), val, id)
1189 }
1190 }
1191 })
1192 }
1193 }
1194
1195 func BenchmarkResolverCustomQualifier(b *testing.B) {
1196 reg := newTestRegistry(b)
1197 attrs := &custAttrFactory{
1198 AttributeFactory: NewAttributeFactory(containers.DefaultContainer, reg, reg),
1199 }
1200 msg := &proto3pb.TestAllTypes_NestedMessage{
1201 Bb: 123,
1202 }
1203 vars, _ := NewActivation(map[string]any{
1204 "msg": msg,
1205 })
1206 attr := attrs.AbsoluteAttribute(1, "msg")
1207 fieldType := types.NewObjectType("google.expr.proto3.test.TestAllTypes.NestedMessage")
1208 qualBB := makeQualifier(b, attrs, fieldType, 2, "bb")
1209 attr.AddQualifier(qualBB)
1210 for i := 0; i < b.N; i++ {
1211 attr.Resolve(vars)
1212 }
1213 }
1214
1215 type custAttrFactory struct {
1216 AttributeFactory
1217 }
1218
1219 func (r *custAttrFactory) NewQualifier(objType *types.Type, qualID int64, val any, opt bool) (Qualifier, error) {
1220 if objType.Kind() == types.StructKind && objType.TypeName() == "google.expr.proto3.test.TestAllTypes.NestedMessage" {
1221 switch v := val.(type) {
1222 case string:
1223 return &nestedMsgQualifier{id: qualID, field: v, opt: opt}, nil
1224 case types.String:
1225 return &nestedMsgQualifier{id: qualID, field: string(v), opt: opt}, nil
1226 }
1227 }
1228 return r.AttributeFactory.NewQualifier(objType, qualID, val, opt)
1229 }
1230
1231 type nestedMsgQualifier struct {
1232 id int64
1233 field string
1234 opt bool
1235 }
1236
1237 func (q *nestedMsgQualifier) ID() int64 {
1238 return q.id
1239 }
1240
1241 func (q *nestedMsgQualifier) IsOptional() bool {
1242 return q.opt
1243 }
1244
1245 func (q *nestedMsgQualifier) Qualify(vars Activation, obj any) (any, error) {
1246 pb := obj.(*proto3pb.TestAllTypes_NestedMessage)
1247 return pb.GetBb(), nil
1248 }
1249
1250 func (q *nestedMsgQualifier) QualifyIfPresent(vars Activation, obj any, presenceOnly bool) (any, bool, error) {
1251 pb := obj.(*proto3pb.TestAllTypes_NestedMessage)
1252 if pb.GetBb() == 0 {
1253 return nil, false, nil
1254 }
1255 return pb.GetBb(), true, nil
1256 }
1257
1258 func addQualifier(t testing.TB, attr Attribute, qual Qualifier) Attribute {
1259 t.Helper()
1260 _, err := attr.AddQualifier(qual)
1261 if err != nil {
1262 t.Fatalf("attr.AddQualifier(%v) failed: %v", qual, err)
1263 }
1264 return attr
1265 }
1266
1267 func makeQualifier(t testing.TB, attrs AttributeFactory, fieldType *types.Type, qualID int64, val any) Qualifier {
1268 t.Helper()
1269 qual, err := attrs.NewQualifier(fieldType, qualID, val, false)
1270 if err != nil {
1271 t.Fatalf("attrs.NewQualifier() failed: %v", err)
1272 }
1273 return qual
1274 }
1275
1276 func makeOptQualifier(t testing.TB, attrs AttributeFactory, fieldType *types.Type, qualID int64, val any) Qualifier {
1277 t.Helper()
1278 qual, err := attrs.NewQualifier(fieldType, qualID, val, true)
1279 if err != nil {
1280 t.Fatalf("attrs.NewQualifier() failed: %v", err)
1281 }
1282 return qual
1283 }
1284
1285 func findField(t testing.TB, reg ref.TypeRegistry, typeName, field string) *ref.FieldType {
1286 t.Helper()
1287 ft, found := reg.FindFieldType(typeName, field)
1288 if !found {
1289 t.Fatalf("reg.FindFieldType(%v, %v) failed", typeName, field)
1290 }
1291 return ft
1292 }
1293
1294 func testExprTypeToType(t testing.TB, fieldType *exprpb.Type) *types.Type {
1295 t.Helper()
1296 ft, err := types.ExprTypeToType(fieldType)
1297 if err != nil {
1298 t.Fatalf("types.ExprTypeToType() failed: %v", err)
1299 }
1300 return ft
1301 }