Debian Codegraph @

codelab/solution/codelab.go

raw
1 // Copyright 2020 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 // This file contains code that demonstrates common CEL features.
16 // This code is intended for use with the CEL Codelab: http://go/cel-codelab-go
17 package main
18
19 import (
20 "encoding/json"
21 "fmt"
22 "reflect"
23 "sort"
24 "strings"
25 "time"
26
27 "github.com/google/cel-go/cel"
28 "github.com/google/cel-go/common/types"
29 "github.com/google/cel-go/common/types/ref"
30 "github.com/google/cel-go/common/types/traits"
31
32 "github.com/golang/glog"
33 "google.golang.org/protobuf/encoding/protojson"
34 "google.golang.org/protobuf/encoding/prototext"
35 "google.golang.org/protobuf/proto"
36
37 rpcpb "google.golang.org/genproto/googleapis/rpc/context/attribute_context"
38 structpb "google.golang.org/protobuf/types/known/structpb"
39 tpb "google.golang.org/protobuf/types/known/timestamppb"
40 )
41
42 func main() {
43 exercise1()
44 exercise2()
45 exercise3()
46 exercise4()
47 exercise5()
48 exercise6()
49 exercise7()
50 exercise8()
51 }
52
53 // exercise1 evaluates a simple literal expression: "Hello, World!"
54 //
55 // Compile, eval, profit!
56 func exercise1() {
57 fmt.Println("=== Exercise 1: Hello World ===\n")
58 // Create the standard environment.
59 env, err := cel.NewEnv()
60 if err != nil {
61 glog.Exitf("env error: %v", err)
62 }
63 // Check that the expression compiles and returns a String.
64 ast, iss := env.Parse(`"Hello, World!"`)
65 // Report syntactic errors, if present.
66 if iss.Err() != nil {
67 glog.Exit(iss.Err())
68 }
69 // Type-check the expression for correctness.
70 checked, iss := env.Check(ast)
71 // Report semantic errors, if present.
72 if iss.Err() != nil {
73 glog.Exit(iss.Err())
74 }
75 // Check the output type is a string.
76 if checked.OutputType() != cel.StringType {
77 glog.Exitf(
78 "Got %v, wanted %v result type",
79 checked.OutputType(), cel.StringType)
80 }
81 // Plan the program.
82 program, err := env.Program(checked)
83 if err != nil {
84 glog.Exitf("program error: %v", err)
85 }
86 // Evaluate the program without any additional arguments.
87 eval(program, cel.NoVars())
88 fmt.Println()
89 }
90
91 // exercise2 shows how to declare and use variables in expressions.
92 //
93 // Given a `request` of type `google.rpc.context.AttributeContext.Request`
94 // determine whether a specific auth claim is set.
95 func exercise2() {
96 fmt.Println("=== Exercise 2: Variables ===\n")
97 // Construct a standard environment that accepts 'request' as input and uses
98 // the google.rpc.context.AttributeContext.Request type.
99 env, err := cel.NewEnv(
100 cel.Types(&rpcpb.AttributeContext_Request{}),
101 cel.Variable("request",
102 cel.ObjectType("google.rpc.context.AttributeContext.Request"),
103 ),
104 )
105 if err != nil {
106 glog.Exit(err)
107 }
108 ast := compile(env, `request.auth.claims.group == 'admin'`, cel.BoolType)
109 program, _ := env.Program(ast)
110
111 // Evaluate a request object that sets the proper group claim.
112 // Output: true
113 claims := map[string]string{"group": "admin"}
114 eval(program, request(auth("user:[email protected]", claims), time.Now()))
115 fmt.Println()
116 }
117
118 // exercise3 demonstrates how CEL's commutative logical operators work.
119 //
120 // Construct an expression which checks whether the `request.auth.claims.group`
121 // value is equal to `admin` or the `request.auth.principal` is
122 // `user:[email protected]` and the `request.time` is during work hours (9:00 - 17:00)
123 //
124 // Evaluate the expression once with a request containing no claims but which
125 // sets the appropriate principal and occurs at 12:00 hours. Then evaluate the
126 // request a second time at midnight. Observe the difference in output.
127 func exercise3() {
128 fmt.Println("=== Exercise 3: Logical AND/OR ===\n")
129 env, _ := cel.NewEnv(
130 cel.Types(&rpcpb.AttributeContext_Request{}),
131 cel.Variable("request",
132 cel.ObjectType("google.rpc.context.AttributeContext.Request"),
133 ),
134 )
135 ast := compile(env,
136 `request.auth.claims.group == 'admin'
137 || request.auth.principal == 'user:[email protected]'`,
138 cel.BoolType)
139 program, _ := env.Program(ast)
140
141 // Evaluate once with no claims and the proper user.
142 // Output: true
143 eval(program, request(auth("user:[email protected]", emptyClaims), time.Now()))
144
145 // Evaluate again with no claims and an unexpected user.
146 // Output: error, no such key
147 eval(program, request(auth("other:[email protected]", emptyClaims), time.Now()))
148
149 fmt.Println()
150 }
151
152 // exercise4 demonstrates how to extend CEL with custom functions.
153 //
154 // Declare a `contains` member function on map types that returns a boolean
155 // indicating whether the map contains the key-value pair.
156 func exercise4() {
157 fmt.Println("=== Exercise 4: Customization ===\n")
158 // Determine whether an optional claim is set to the proper value. The custom
159 // map.contains(key, value) function is used as an alternative to:
160 // key in map && map[key] == value
161
162 // Useful components of the type-signature for 'contains'.
163 typeParamA := cel.TypeParamType("A")
164 typeParamB := cel.TypeParamType("B")
165 mapAB := cel.MapType(typeParamA, typeParamB)
166
167 // Env declaration.
168 env, _ := cel.NewEnv(
169 cel.Types(&rpcpb.AttributeContext_Request{}),
170 // Declare the request.
171 cel.Variable("request",
172 cel.ObjectType("google.rpc.context.AttributeContext.Request"),
173 ),
174 // Declare the custom contains function and its implementation.
175 cel.Function("contains",
176 cel.MemberOverload("map_contains_key_value",
177 []*cel.Type{mapAB, typeParamA, typeParamB},
178 cel.BoolType,
179 cel.FunctionBinding(mapContainsKeyValue)),
180 ),
181 )
182 ast := compile(env,
183 `request.auth.claims.contains('group', 'admin')`,
184 cel.BoolType)
185
186 // Construct the program plan.
187 // Output: false
188 program, err := env.Program(ast)
189 if err != nil {
190 glog.Exit(err)
191 }
192
193 eval(program, request(auth("user:[email protected]", emptyClaims), time.Now()))
194 claims := map[string]string{"group": "admin"}
195 eval(program, request(auth("user:[email protected]", claims), time.Now()))
196 fmt.Println()
197 }
198
199 // exercise5 covers how to build complex objects as CEL literals.
200 //
201 // Given the input `now`, construct a JWT with an expiry of 5 minutes.
202 func exercise5() {
203 fmt.Println("=== Exercise 5: Building JSON ===\n")
204 // Note the quoted keys in the CEL map literal. For proto messages the
205 // field names are unquoted as they represent well-defined identifiers.
206 env, _ := cel.NewEnv(
207 cel.Variable("now", cel.TimestampType),
208 )
209 ast := compile(env, `
210 {'aud': 'my-project',
211 'exp': now + duration('300s'),
212 'extra_claims': {
213 'group': 'admin'
214 },
215 'iat': now,
216 'iss': 'auth.acme.com:12350',
217 'nbf': now,
218 'sub': 'serviceAccount:[email protected]'
219 }`,
220 cel.MapType(cel.StringType, cel.DynType))
221
222 program, _ := env.Program(ast)
223 out, _, _ := eval(
224 program,
225 map[string]any{
226 "now": time.Now(),
227 },
228 )
229 // The output of the program is a CEL map type, but it can be converted
230 // to a JSON representation using the `ConvertToNative` method.
231 fmt.Printf("------ type conversion ------\n%v\n", valueToJSON(out))
232 fmt.Println()
233 }
234
235 // exercise6 describes how to build proto message types within CEL.
236 //
237 // Given an input `jwt` and time `now` construct a
238 // `google.rpc.context.AttributeContext.Request` with the `time` and `auth`
239 // fields populated according to the go/api-attributes specification.
240 func exercise6() {
241 fmt.Println("=== Exercise 6: Building Protos ===\n")
242
243 // Construct an environment and indicate that the container for all references
244 // within the expression is `google.rpc.context.AttributeContext`.
245 requestType := &rpcpb.AttributeContext_Request{}
246 env, _ := cel.NewEnv(
247 cel.Container("google.rpc.context.AttributeContext"),
248 cel.Types(requestType),
249 cel.Variable("jwt", cel.MapType(cel.StringType, cel.DynType)),
250 cel.Variable("now", cel.TimestampType),
251 )
252
253 // Compile the `Request` message construction expression and validate that the
254 // resulting expression type matches the fully qualified message name.
255 //
256 // Note: the field names within the proto message types are not quoted as they
257 // are well-defined names composed of valid identifier characters. Also, note
258 // that when building nested proto objects, the message name needs to prefix the
259 // object construction.
260 ast := compile(env, `
261 Request{
262 auth: Auth{
263 principal: jwt.iss + '/' + jwt.sub,
264 audiences: [jwt.aud],
265 presenter: 'azp' in jwt ? jwt.azp : "",
266 claims: jwt
267 },
268 time: now
269 }`,
270 cel.ObjectType("google.rpc.context.AttributeContext.Request"))
271 program, _ := env.Program(ast)
272
273 // Construct the message. The result is a ref.Val that returns a dynamic proto message.
274 out, _, _ := eval(
275 program,
276 map[string]any{
277 "jwt": map[string]any{
278 "sub": "serviceAccount:[email protected]",
279 "aud": "my-project",
280 "iss": "auth.acme.com:12350",
281 "extra_claims": map[string]string{
282 "group": "admin",
283 },
284 },
285 "now": time.Now(),
286 },
287 )
288 // Unwrap the CEL value to a proto. Make sure to use the `ConvertToNative` to convert
289 // the dynamic proto message to the concrete type expected.
290 req, err := out.ConvertToNative(reflect.TypeOf(requestType))
291 if err != nil {
292 glog.Exit(err)
293 }
294 bytes, err := prototext.Marshal(req.(proto.Message))
295 if err != nil {
296 glog.Exitf("failed to marshal proto to text: %v", req)
297 }
298 fmt.Printf("------ type unwrap ------\n%v\n", string(bytes))
299 fmt.Println()
300 }
301
302 // exercise7 introduces macros for dealing with repeated fields and maps.
303 //
304 // Determine whether the `jwt.extra_claims` has at least one key that starts
305 // with the `group` prefix, and ensure that all group-like keys have list
306 // values containing only strings that end with '@acme.co`.
307 func exercise7() {
308 fmt.Println("=== Exercise 7: Macros ===\n")
309 env, _ := cel.NewEnv(cel.Variable("jwt", cel.DynType))
310 ast := compile(env,
311 `jwt.extra_claims.exists(c, c.startsWith('group'))
312 && jwt.extra_claims
313 .filter(c, c.startsWith('group'))
314 .all(c, jwt.extra_claims[c]
315 .all(g, g.endsWith('@acme.co')))`,
316 cel.BoolType)
317 program, _ := env.Program(ast)
318
319 // Evaluate a complex-ish JWT with two groups that satisfy the criteria.
320 // Output: true.
321 eval(program,
322 map[string]any{
323 "jwt": map[string]any{
324 "sub": "serviceAccount:[email protected]",
325 "aud": "my-project",
326 "iss": "auth.acme.com:12350",
327 "extra_claims": map[string][]string{
328 "group1": {"[email protected]", "[email protected]"},
329 "labels": {"metadata", "prod", "pii"},
330 "groupN": {"[email protected]"},
331 },
332 },
333 })
334
335 fmt.Println()
336 }
337
338 // exercise8 covers some useful features of CEL-Go which can be used to
339 // improve performance and better understand evaluation behavior.
340 //
341 // Turn on the optimization, exhaustive eval, and state tracking
342 // `cel.ProgramOption` flags to see the impact on evaluation behavior.
343 func exercise8() {
344 fmt.Println("=== Exercise 8: Tuning ===\n")
345 // Declare the `x` and 'y' variables as input into the expression.
346 env, _ := cel.NewEnv(
347 cel.Variable("x", cel.IntType),
348 cel.Variable("y", cel.UintType),
349 )
350 ast := compile(env,
351 `x in [1, 2, 3, 4, 5] && type(y) == uint`,
352 cel.BoolType)
353 // Turn on optimization.
354 trueVars := map[string]any{"x": int64(4), "y": uint64(2)}
355 program, _ := env.Program(ast, cel.EvalOptions(cel.OptOptimize))
356 // Try benchmarking this evaluation with the optimization flag on and off.
357 eval(program, trueVars)
358
359 // Turn on exhaustive eval to see what the evaluation state looks like.
360 // The input is structure to show a false on the first branch, and true
361 // on the second.
362 falseVars := map[string]any{"x": int64(6), "y": uint64(2)}
363 program, _ = env.Program(ast, cel.EvalOptions(cel.OptExhaustiveEval))
364 eval(program, falseVars)
365
366 // Turn on optimization and state tracking to see the typical eval
367 // behavior, but with partial input.
368 xVar := map[string]any{"x": int64(3)}
369 partialVars, _ := cel.PartialVars(xVar, cel.AttributePattern("y"))
370 program, _ = env.Program(ast,
371 cel.EvalOptions(cel.OptPartialEval, cel.OptOptimize, cel.OptTrackState))
372 _, details, _ := eval(program, partialVars)
373
374 // Convert the unknown parts of the expression to a new AST and format it back
375 // to a human-readable expression.
376 residualAst, _ := env.ResidualAst(ast, details)
377 residual, _ := cel.AstToString(residualAst)
378 fmt.Printf("------ residual ------\n%s\n", residual)
379
380 fmt.Println()
381 }
382
383 // Functions to assist with CEL execution.
384
385 // compile will parse and check an expression `expr` against a given
386 // environment `env` and determine whether the resulting type of the expression
387 // matches the `exprType` provided as input.
388 func compile(env *cel.Env, expr string, celType *cel.Type) *cel.Ast {
389 ast, iss := env.Compile(expr)
390 if iss.Err() != nil {
391 glog.Exit(iss.Err())
392 }
393 if !reflect.DeepEqual(ast.OutputType(), celType) {
394 glog.Exitf(
395 "Got %v, wanted %v result type", ast.OutputType(), celType)
396 }
397 fmt.Printf("%s\n\n", strings.ReplaceAll(expr, "\t", " "))
398 return ast
399 }
400
401 // eval will evaluate a given program `prg` against a set of variables `vars`
402 // and return the output, eval details (optional), or error that results from
403 // evaluation.
404 func eval(prg cel.Program,
405 vars any) (out ref.Val, det *cel.EvalDetails, err error) {
406 varMap, isMap := vars.(map[string]any)
407 fmt.Println("------ input ------")
408 if !isMap {
409 fmt.Printf("(%T)\n", vars)
410 } else {
411 for k, v := range varMap {
412 switch val := v.(type) {
413 case proto.Message:
414 bytes, err := prototext.Marshal(val)
415 if err != nil {
416 glog.Exitf("failed to marshal proto to text: %v", val)
417 }
418 fmt.Printf("%s = %s", k, string(bytes))
419 case map[string]any:
420 b, _ := json.MarshalIndent(v, "", " ")
421 fmt.Printf("%s = %v\n", k, string(b))
422 case uint64:
423 fmt.Printf("%s = %vu\n", k, v)
424 default:
425 fmt.Printf("%s = %v\n", k, v)
426 }
427 }
428 }
429 fmt.Println()
430 out, det, err = prg.Eval(vars)
431 report(out, det, err)
432 fmt.Println()
433 return
434 }
435
436 // report prints out the result of evaluation in human-friendly terms.
437 func report(result ref.Val, details *cel.EvalDetails, err error) {
438 fmt.Println("------ result ------")
439 if err != nil {
440 fmt.Printf("error: %s\n", err)
441 } else {
442 fmt.Printf("value: %v (%T)\n", result, result)
443 }
444 if details != nil {
445 fmt.Printf("\n------ eval states ------\n")
446 state := details.State()
447 stateIDs := state.IDs()
448 ids := make([]int, len(stateIDs), len(stateIDs))
449 for i, id := range stateIDs {
450 ids[i] = int(id)
451 }
452 sort.Ints(ids)
453 for _, id := range ids {
454 v, found := state.Value(int64(id))
455 if !found {
456 continue
457 }
458 fmt.Printf("%d: %v (%T)\n", id, v, v)
459 }
460 }
461 }
462
463 // mapContainsKeyValue implements the custom function:
464 //
465 // `map.contains(key, value) bool`.
466 func mapContainsKeyValue(args ...ref.Val) ref.Val {
467 // The declaration of the function ensures that only arguments which match
468 // the mapContainsKey signature will be provided to the function.
469 m := args[0].(traits.Mapper)
470
471 // CEL has many interfaces for dealing with different type abstractions.
472 // The traits.Mapper interface unifies field presence testing on proto
473 // messages and maps.
474 key := args[1]
475 v, found := m.Find(key)
476
477 // If not found and the value was non-nil, the value is an error per the
478 // `Find` contract. Propagate it accordingly.
479 if !found {
480 if v != nil {
481 return types.ValOrErr(v, "unsupported key type")
482 }
483 // Return CEL False if the key was not found.
484 return types.False
485 }
486 // Otherwise whether the value at the key equals the value provided.
487 return v.Equal(args[2])
488 }
489
490 // Functions for constructing CEL inputs.
491
492 // auth constructs a `google.rpc.context.AttributeContext.Auth` message.
493 func auth(user string, claims map[string]string) *rpcpb.AttributeContext_Auth {
494 claimFields := make(map[string]*structpb.Value)
495 for k, v := range claims {
496 claimFields[k] = structpb.NewStringValue(v)
497 }
498 return &rpcpb.AttributeContext_Auth{
499 Principal: user,
500 Claims: &structpb.Struct{Fields: claimFields},
501 }
502 }
503
504 // request constructs a `google.rpc.context.AttributeContext.Request` message.
505 func request(auth *rpcpb.AttributeContext_Auth, t time.Time) map[string]any {
506 req := &rpcpb.AttributeContext_Request{
507 Auth: auth,
508 Time: &tpb.Timestamp{Seconds: t.Unix()},
509 }
510 return map[string]any{"request": req}
511 }
512
513 // valueToJSON converts the CEL type to a protobuf JSON representation and
514 // marshals the result to a string.
515 func valueToJSON(val ref.Val) string {
516 v, err := val.ConvertToNative(reflect.TypeOf(&structpb.Value{}))
517 if err != nil {
518 glog.Exit(err)
519 }
520 marshaller := protojson.MarshalOptions{Indent: " "}
521 bytes, err := marshaller.Marshal(v.(proto.Message))
522 if err != nil {
523 glog.Exit(err)
524 }
525 return string(bytes)
526 }
527
528 var (
529 emptyClaims = make(map[string]string)
530 )