Debian Codegraph @

policy/helper_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 "log"
19 "os"
20 "testing"
21
22 "github.com/google/cel-go/cel"
23 "github.com/google/cel-go/common/env"
24 "github.com/google/cel-go/common/types"
25 "github.com/google/cel-go/common/types/ref"
26 "github.com/google/cel-go/test"
27
28 "go.yaml.in/yaml/v3"
29
30 proto3pb "github.com/google/cel-go/test/proto3pb"
31 )
32
33 var (
34 policyTests = []struct {
35 name string
36 envOpts []cel.EnvOption
37 parseOpts []ParserOption
38 expr string
39 }{
40 {
41 name: "k8s",
42 parseOpts: []ParserOption{func(p *Parser) (*Parser, error) {
43 p.TagVisitor = K8sTestTagHandler()
44 return p, nil
45 }},
46 expr: `
47 cel.@block([
48 resource.labels.?environment.orValue("prod"),
49 resource.labels.?break_glass.orValue("false") == "true"],
50 !(@index1 || resource.containers.all(c, c.startsWith(@index0 + ".")))
51 ? optional.of("only %s containers are allowed in namespace %s".format([@index0, resource.namespace]))
52 : optional.none())`,
53 },
54 {
55 name: "nested_rule",
56 expr: `
57 cel.@block([
58 ["us", "uk", "es"],
59 {"us": false, "ru": false, "ir": false}],
60 ((resource.origin in @index1 && !(resource.origin in @index0))
61 ? optional.of({"banned": true}) : optional.none()).orValue(
62 (resource.origin in @index0) ? {"banned": false} : {"banned": true}))`,
63 },
64 {
65 name: "nested_rule2",
66 expr: `
67 cel.@block([
68 ["us", "uk", "es"],
69 {"us": false, "ru": false, "ir": false}],
70 resource.?user.orValue("").startsWith("bad")
71 ? ((resource.origin in @index1 && !(resource.origin in @index0))
72 ? {"banned": "restricted_region"}
73 : {"banned": "bad_actor"})
74 : (!(resource.origin in @index0)
75 ? {"banned": "unconfigured_region"} : {}))`,
76 },
77 {
78 name: "nested_rule3",
79 expr: `
80 cel.@block([
81 ["us", "uk", "es"],
82 {"us": false, "ru": false, "ir": false}],
83 resource.?user.orValue("").startsWith("bad")
84 ? optional.of((resource.origin in @index1 && !(resource.origin in @index0))
85 ? {"banned": "restricted_region"} : {"banned": "bad_actor"})
86 : (!(resource.origin in @index0)
87 ? optional.of({"banned": "unconfigured_region"}) : optional.none()))`,
88 },
89 {
90 name: "nested_rule4",
91 expr: `(x > 0) ? true : false`,
92 },
93 {
94 name: "nested_rule5",
95 expr: `
96 (x > 0)
97 ? ((x > 2) ? optional.of(true) : optional.none())
98 : ((x > 1)
99 ? ((x >= 2) ? optional.of(true) : optional.none())
100 : optional.of(false))`,
101 },
102 {
103 name: "nested_rule6",
104 expr: `
105 ((x > 2) ? optional.of(true) : optional.none())
106 .orValue(((x > 3) ? optional.of(true) : optional.none())
107 .orValue(false))`,
108 },
109 {
110 name: "nested_rule7",
111 expr: `
112 ((x > 2) ? optional.of(true) : optional.none())
113 .or(((x > 3) ? optional.of(true) : optional.none())
114 .or((x > 1) ? optional.of(false) : optional.none()))`,
115 },
116 {
117 name: "unnest",
118 expr: `
119 cel.@block([values.filter(x, x > 2)],
120 ((@index0.size() == 0) ? false : @index0.all(x, x % 2 == 0))
121 ? optional.of("some divisible by 2")
122 : (values.map(x, x * 3).exists(x, x % 4 == 0)
123 ? optional.of("at least one divisible by 4")
124 : (values.map(x, x * x * x).exists(x, x % 6 == 0)
125 ? optional.of("at least one power of 6")
126 : optional.none())))
127 `,
128 },
129 {
130 name: "context_pb",
131 expr: `
132 (single_int32 > google.expr.proto3.test.TestAllTypes{single_int64: 10}.single_int64)
133 ? optional.of("invalid spec, got single_int32=%d, wanted <= 10".format([single_int32]))
134 : ((standalone_enum == google.expr.proto3.test.TestAllTypes.NestedEnum.BAR ||
135 google.expr.proto3.test.ImportedGlobalEnum.IMPORT_BAR in imported_enums)
136 ? optional.of("invalid spec, neither nested nor imported enums may refer to BAR or IMPORT_BAR")
137 : optional.none())`,
138 envOpts: []cel.EnvOption{
139 cel.Types(&proto3pb.TestAllTypes{}),
140 },
141 },
142 {
143 name: "pb",
144 expr: `
145 (spec.single_int32 > google.expr.proto3.test.TestAllTypes{single_int64: 10}.single_int64)
146 ? optional.of("invalid spec, got single_int32=%d, wanted <= 10".format([spec.single_int32]))
147 : ((spec.standalone_enum == google.expr.proto3.test.TestAllTypes.NestedEnum.BAR ||
148 google.expr.proto3.test.ImportedGlobalEnum.IMPORT_BAR in spec.imported_enums)
149 ? optional.of("invalid spec, neither nested nor imported enums may refer to BAR or IMPORT_BAR")
150 : optional.none())`,
151 envOpts: []cel.EnvOption{
152 cel.Types(&proto3pb.TestAllTypes{}),
153 },
154 },
155 {
156 name: "required_labels",
157 expr: `
158 cel.@block([
159 spec.labels,
160 @index0.filter(l, !(l in resource.labels)),
161 resource.labels.transformList(l, value, l in @index0 && value != @index0[l], l)],
162 (@index1.size() > 0)
163 ? optional.of("missing one or more required labels: %s".format([@index1]))
164 : ((@index2.size() > 0)
165 ? optional.of("invalid values provided on one or more labels: %s".format([@index2]))
166 : optional.none()))`,
167 },
168 {
169 name: "restricted_destinations",
170 expr: `
171 cel.@block([
172 locationCode(origin.ip) == spec.origin,
173 has(request.auth.claims.nationality),
174 @index1 && request.auth.claims.nationality == spec.origin,
175 locationCode(destination.ip) in spec.restricted_destinations,
176 resource.labels.location in spec.restricted_destinations,
177 @index3 || @index4],
178 (@index2 && @index5) ? true : ((!@index1 && @index0 && @index5) ? true : false))`,
179 envOpts: []cel.EnvOption{
180 cel.Function("locationCode",
181 cel.Overload("locationCode_string", []*cel.Type{cel.StringType}, cel.StringType,
182 cel.UnaryBinding(func(ip ref.Val) ref.Val {
183 switch ip.(types.String) {
184 case types.String("10.0.0.1"):
185 return types.String("us")
186 case types.String("10.0.0.2"):
187 return types.String("de")
188 default:
189 return types.String("ir")
190 }
191 }))),
192 },
193 },
194 {
195 name: "limits",
196 expr: `
197 cel.@block([
198 "hello",
199 "goodbye",
200 "me",
201 "%s, %s",
202 @index3.format([@index1, @index2])],
203 (now.getHours() >= 20)
204 ? ((now.getHours() < 21)
205 ? optional.of(@index4 + "!")
206 : ((now.getHours() < 22)
207 ? optional.of(@index4 + "!!")
208 : ((now.getHours() < 24)
209 ? optional.of(@index4 + "!!!")
210 : optional.none())))
211 : optional.of(@index3.format([@index0, @index2])))`,
212 },
213 }
214
215 composerUnnestTests = []struct {
216 name string
217 expr string
218 composed string
219 composerOpts []ComposerOption
220 outputType *cel.Type
221 }{
222 {
223 name: "unnest",
224 composerOpts: []ComposerOption{ExpressionUnnestHeight(2)},
225 composed: `
226 cel.@block([
227 values.filter(x, x > 2),
228 @index0.size() == 0,
229 @index1 ? false : @index0.all(x, x % 2 == 0),
230 values.map(x, x * x * x).exists(x, x % 6 == 0)
231 ? optional.of("at least one power of 6")
232 : optional.none(),
233 values.map(x, x * 3).exists(x, x % 4 == 0)
234 ? optional.of("at least one divisible by 4")
235 : @index3],
236 @index2 ? optional.of("some divisible by 2") : @index4)
237 `,
238 outputType: cel.OptionalType(cel.StringType),
239 },
240 {
241 name: "required_labels",
242 composerOpts: []ComposerOption{ExpressionUnnestHeight(2)},
243 composed: `
244 cel.@block([
245 spec.labels,
246 @index0.filter(l, !(l in resource.labels)),
247 resource.labels.transformList(l, value, l in @index0 && value != @index0[l], l),
248 @index1.size() > 0,
249 "missing one or more required labels: %s".format([@index1]),
250 @index2.size() > 0,
251 "invalid values provided on one or more labels: %s".format([@index2])],
252 @index3 ? optional.of(@index4) : (@index5 ? optional.of(@index6) : optional.none()))
253 `,
254 outputType: cel.OptionalType(cel.StringType),
255 },
256 {
257 name: "required_labels",
258 composerOpts: []ComposerOption{ExpressionUnnestHeight(4)},
259 composed: `
260 cel.@block([
261 spec.labels,
262 @index0.filter(l, !(l in resource.labels)),
263 resource.labels.transformList(l, value, l in @index0 && value != @index0[l], l),
264 (@index2.size() > 0)
265 ? optional.of("invalid values provided on one or more labels: %s".format([@index2]))
266 : optional.none()
267 ],
268 (@index1.size() > 0)
269 ? optional.of("missing one or more required labels: %s".format([@index1]))
270 : @index3)`,
271 outputType: cel.OptionalType(cel.StringType),
272 },
273 {
274 name: "nested_rule2",
275 composerOpts: []ComposerOption{ExpressionUnnestHeight(4)},
276 composed: `
277 cel.@block([
278 ["us", "uk", "es"],
279 {"us": false, "ru": false, "ir": false},
280 resource.origin in @index1 && !(resource.origin in @index0),
281 !(resource.origin in @index0) ? {"banned": "unconfigured_region"} : {}],
282 resource.?user.orValue("").startsWith("bad")
283 ? (@index2 ? {"banned": "restricted_region"} : {"banned": "bad_actor"})
284 : @index3)`,
285 outputType: cel.MapType(cel.StringType, cel.StringType),
286 },
287 {
288 name: "nested_rule2",
289 composerOpts: []ComposerOption{ExpressionUnnestHeight(5)},
290 composed: `
291 cel.@block([
292 ["us", "uk", "es"],
293 {"us": false, "ru": false, "ir": false},
294 (resource.origin in @index1 && !(resource.origin in @index0))
295 ? {"banned": "restricted_region"}
296 : {"banned": "bad_actor"}],
297 resource.?user.orValue("").startsWith("bad")
298 ? @index2
299 : (!(resource.origin in @index0)
300 ? {"banned": "unconfigured_region"}
301 : {}))`,
302 outputType: cel.MapType(cel.StringType, cel.StringType),
303 },
304 {
305 name: "limits",
306 composerOpts: []ComposerOption{ExpressionUnnestHeight(3)},
307 composed: `
308 cel.@block([
309 "hello",
310 "goodbye",
311 "me",
312 "%s, %s",
313 @index3.format([@index1, @index2]),
314 (now.getHours() < 24) ? optional.of(@index4 + "!!!") : optional.none(),
315 optional.of(@index3.format([@index0, @index2]))],
316 (now.getHours() >= 20)
317 ? ((now.getHours() < 21) ? optional.of(@index4 + "!") :
318 ((now.getHours() < 22) ? optional.of(@index4 + "!!") : @index5))
319 : @index6)`,
320 outputType: cel.OptionalType(cel.StringType),
321 },
322 {
323 name: "limits",
324 composerOpts: []ComposerOption{ExpressionUnnestHeight(4)},
325 composed: `
326 cel.@block([
327 "hello",
328 "goodbye",
329 "me",
330 "%s, %s",
331 @index3.format([@index1, @index2]),
332 (now.getHours() < 22) ? optional.of(@index4 + "!!") :
333 ((now.getHours() < 24) ? optional.of(@index4 + "!!!") : optional.none())],
334 (now.getHours() >= 20)
335 ? ((now.getHours() < 21) ? optional.of(@index4 + "!") : @index5)
336 : optional.of(@index3.format([@index0, @index2])))
337 `,
338 outputType: cel.OptionalType(cel.StringType),
339 },
340 {
341 name: "limits",
342 composerOpts: []ComposerOption{ExpressionUnnestHeight(5)},
343 composed: `
344 cel.@block([
345 "hello",
346 "goodbye",
347 "me",
348 "%s, %s",
349 @index3.format([@index1, @index2]),
350 (now.getHours() < 21) ? optional.of(@index4 + "!") :
351 ((now.getHours() < 22) ? optional.of(@index4 + "!!") :
352 ((now.getHours() < 24) ? optional.of(@index4 + "!!!") : optional.none()))],
353 (now.getHours() >= 20) ? @index5 : optional.of(@index3.format([@index0, @index2])))`,
354 outputType: cel.OptionalType(cel.StringType),
355 },
356 }
357
358 policyErrorTests = []struct {
359 name string
360 err string
361 compilerOpts []CompilerOption
362 }{
363 {
364 name: "errors",
365 err: `ERROR: testdata/errors/policy.yaml:19:1: error configuring import: invalid qualified name: punc.Import!, wanted name of the form 'qualified.name'
366 | punc.Import!
367 | ^
368 ERROR: testdata/errors/policy.yaml:20:12: error configuring import: invalid qualified name: bad import, wanted name of the form 'qualified.name'
369 | - name: "bad import"
370 | ...........^
371 ERROR: testdata/errors/policy.yaml:24:19: undeclared reference to 'spec' (in container '')
372 | expression: spec.labels
373 | ..................^
374 ERROR: testdata/errors/policy.yaml:25:7: invalid variable declaration: overlapping identifier for name 'variables.want'
375 | - name: want
376 | ......^
377 ERROR: testdata/errors/policy.yaml:28:50: Syntax error: mismatched input 'resource' expecting ')'
378 | expression: variables.want.filter(l, !(lin resource.labels))
379 | .................................................^
380 ERROR: testdata/errors/policy.yaml:28:66: Syntax error: extraneous input ')' expecting <EOF>
381 | expression: variables.want.filter(l, !(lin resource.labels))
382 | .................................................................^
383 ERROR: testdata/errors/policy.yaml:30:27: Syntax error: mismatched input '2' expecting {'}', ','}
384 | expression: "{1:305 2:569}"
385 | ..........................^
386 ERROR: testdata/errors/policy.yaml:38:75: Syntax error: extraneous input ']' expecting ')'
387 | "missing one or more required labels: %s".format(variables.missing])
388 | ..........................................................................^
389 ERROR: testdata/errors/policy.yaml:41:67: undeclared reference to 'format' (in container '')
390 | "invalid values provided on one or more labels: %s".format([variables.invalid])
391 | ..................................................................^
392 ERROR: testdata/errors/policy.yaml:45:16: incompatible output types: block has output type string, but previous outputs have type bool
393 | output: "'false'"
394 | ...............^`,
395 },
396 {
397 name: "limits",
398 err: `ERROR: testdata/limits/policy.yaml:22:14: variable exceeds nested expression limit
399 | - name: "person"
400 | .............^`,
401 compilerOpts: []CompilerOption{MaxNestedExpressions(2)},
402 },
403 {
404 name: "limits",
405 err: `ERROR: testdata/limits/policy.yaml:30:9: rule exceeds nested expression limit
406 | id: "farewells"
407 | ........^`,
408 compilerOpts: []CompilerOption{MaxNestedExpressions(5)},
409 },
410 {
411 name: "errors_unreachable",
412 err: `ERROR: testdata/errors_unreachable/policy.yaml:28:9: rule creates unreachable outputs
413 | match:
414 | ........^
415 ERROR: testdata/errors_unreachable/policy.yaml:36:13: match creates unreachable outputs
416 | - output: |
417 | ............^`,
418 },
419 {
420 name: "nested_incompatible_outputs",
421 err: `ERROR: testdata/nested_incompatible_outputs/policy.yaml:22:9: incompatible output types: block has output type string, but previous outputs have type bool
422 | match:
423 | ........^`,
424 },
425 }
426 )
427
428 func readPolicy(t testing.TB, fileName string) *Source {
429 t.Helper()
430 policyBytes, err := os.ReadFile(fileName)
431 if err != nil {
432 t.Fatalf("os.ReadFile(%s) failed: %v", fileName, err)
433 }
434 return ByteSource(policyBytes, fileName)
435 }
436
437 func readPolicyConfig(t testing.TB, fileName string) *env.Config {
438 t.Helper()
439 testCaseBytes, err := os.ReadFile(fileName)
440 if err != nil {
441 t.Fatalf("os.ReadFile(%s) failed: %v", fileName, err)
442 }
443 config := &env.Config{}
444 err = yaml.Unmarshal(testCaseBytes, config)
445 if err != nil {
446 log.Fatalf("yaml.Unmarshal(%s) error: %v", fileName, err)
447 }
448 return config
449 }
450
451 func readTestSuite(t testing.TB, fileName string) *test.Suite {
452 t.Helper()
453 testCaseBytes, err := os.ReadFile(fileName)
454 if err != nil {
455 t.Fatalf("os.ReadFile(%s) failed: %v", fileName, err)
456 }
457 suite := &test.Suite{}
458 err = yaml.Unmarshal(testCaseBytes, suite)
459 if err != nil {
460 log.Fatalf("yaml.Unmarshal(%s) error: %v", fileName, err)
461 }
462 return suite
463 }