| 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: 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 |
|
| 59 |
fmt.Println() |
| 60 |
} |
| 61 |
|
| 62 |
// exercise2 shows how to declare and use variables in expressions. |
| 63 |
// |
| 64 |
// Given a `request` of type `google.rpc.context.AttributeContext.Request` |
| 65 |
// determine whether a specific auth claim is set. |
| 66 |
func exercise2() { |
| 67 |
fmt.Println("=== Exercise 2: Variables ===\n") |
| 68 |
|
| 69 |
fmt.Println() |
| 70 |
} |
| 71 |
|
| 72 |
// exercise3 demonstrates how CEL's commutative logical operators work. |
| 73 |
// |
| 74 |
// Construct an expression which checks whether the `request.auth.claims.group` |
| 75 |
// value is equal to `admin` or the `request.auth.principal` is |
| 76 |
// `user:[email protected]` and the `request.time` is during work hours (9:00 - 17:00) |
| 77 |
// |
| 78 |
// Evaluate the expression once with a request containing no claims but which |
| 79 |
// sets the appropriate principal and occurs at 12:00 hours. Then evaluate the |
| 80 |
// request a second time at midnight. Observe the difference in output. |
| 81 |
func exercise3() { |
| 82 |
fmt.Println("=== Exercise 3: Logical AND/OR ===\n") |
| 83 |
|
| 84 |
fmt.Println() |
| 85 |
} |
| 86 |
|
| 87 |
// exercise4 demonstrates how to extend CEL with custom functions. |
| 88 |
// |
| 89 |
// Declare a `contains` member function on map types that returns a boolean |
| 90 |
// indicating whether the map contains the key-value pair. |
| 91 |
func exercise4() { |
| 92 |
fmt.Println("=== Exercise 4: Customization ===\n") |
| 93 |
|
| 94 |
fmt.Println() |
| 95 |
} |
| 96 |
|
| 97 |
// exercise5 covers how to build complex objects as CEL literals. |
| 98 |
// |
| 99 |
// Given the input `now`, construct a JWT with an expiry of 5 minutes. |
| 100 |
func exercise5() { |
| 101 |
fmt.Println("=== Exercise 5: Building JSON ===\n") |
| 102 |
|
| 103 |
fmt.Println() |
| 104 |
} |
| 105 |
|
| 106 |
// exercise6 describes how to build proto message types within CEL. |
| 107 |
// |
| 108 |
// Given an input `jwt` and time `now` construct a |
| 109 |
// `google.rpc.context.AttributeContext.Request` with the `time` and `auth` |
| 110 |
// fields populated according to the go/api-attributes specification. |
| 111 |
func exercise6() { |
| 112 |
fmt.Println("=== Exercise 6: Building Protos ===\n") |
| 113 |
|
| 114 |
fmt.Println() |
| 115 |
} |
| 116 |
|
| 117 |
// exercise7 introduces macros for dealing with repeated fields and maps. |
| 118 |
// |
| 119 |
// Determine whether the `jwt.extra_claims` has at least one key that starts |
| 120 |
// with the `group` prefix, and ensure that all group-like keys have list |
| 121 |
// values containing only strings that end with '@acme.co`. |
| 122 |
func exercise7() { |
| 123 |
fmt.Println("=== Exercise 7: Macros ===\n") |
| 124 |
|
| 125 |
fmt.Println() |
| 126 |
} |
| 127 |
|
| 128 |
// exercise8 covers some useful features of CEL-Go which can be used to |
| 129 |
// improve performance and better understand evaluation behavior. |
| 130 |
// |
| 131 |
// Turn on the optimization, exhaustive eval, and state tracking |
| 132 |
// `cel.ProgramOption` flags to see the impact on evaluation behavior. |
| 133 |
// |
| 134 |
// Also, turn on the homogeneous aggregate literals flag to disable |
| 135 |
// heterogeneous list and map literals. |
| 136 |
func exercise8() { |
| 137 |
fmt.Println("=== Exercise 8: Tuning ===\n") |
| 138 |
|
| 139 |
fmt.Println() |
| 140 |
} |
| 141 |
|
| 142 |
// Functions to assist with CEL execution. |
| 143 |
|
| 144 |
// compile will parse and check an expression `expr` against a given |
| 145 |
// environment `env` and determine whether the resulting type of the expression |
| 146 |
// matches the `exprType` provided as input. |
| 147 |
func compile(env *cel.Env, expr string, celType *cel.Type) *cel.Ast { |
| 148 |
ast, iss := env.Compile(expr) |
| 149 |
if iss.Err() != nil { |
| 150 |
glog.Exit(iss.Err()) |
| 151 |
} |
| 152 |
if !reflect.DeepEqual(ast.OutputType(), celType) { |
| 153 |
glog.Exitf( |
| 154 |
"Got %v, wanted %v result type", ast.OutputType(), celType) |
| 155 |
} |
| 156 |
fmt.Printf("%s\n\n", strings.ReplaceAll(expr, "\t", " ")) |
| 157 |
return ast |
| 158 |
} |
| 159 |
|
| 160 |
// eval will evaluate a given program `prg` against a set of variables `vars` |
| 161 |
// and return the output, eval details (optional), or error that results from |
| 162 |
// evaluation. |
| 163 |
func eval(prg cel.Program, |
| 164 |
vars any) (out ref.Val, det *cel.EvalDetails, err error) { |
| 165 |
varMap, isMap := vars.(map[string]any) |
| 166 |
fmt.Println("------ input ------") |
| 167 |
if !isMap { |
| 168 |
fmt.Printf("(%T)\n", vars) |
| 169 |
} else { |
| 170 |
for k, v := range varMap { |
| 171 |
switch val := v.(type) { |
| 172 |
case proto.Message: |
| 173 |
bytes, err := prototext.Marshal(val) |
| 174 |
if err != nil { |
| 175 |
glog.Exitf("failed to marshal proto to text: %v", val) |
| 176 |
} |
| 177 |
fmt.Printf("%s = %s", k, string(bytes)) |
| 178 |
case map[string]any: |
| 179 |
b, _ := json.MarshalIndent(v, "", " ") |
| 180 |
fmt.Printf("%s = %v\n", k, string(b)) |
| 181 |
case uint64: |
| 182 |
fmt.Printf("%s = %vu\n", k, v) |
| 183 |
default: |
| 184 |
fmt.Printf("%s = %v\n", k, v) |
| 185 |
} |
| 186 |
} |
| 187 |
} |
| 188 |
fmt.Println() |
| 189 |
out, det, err = prg.Eval(vars) |
| 190 |
report(out, det, err) |
| 191 |
fmt.Println() |
| 192 |
return |
| 193 |
} |
| 194 |
|
| 195 |
// report prints out the result of evaluation in human-friendly terms. |
| 196 |
func report(result ref.Val, details *cel.EvalDetails, err error) { |
| 197 |
fmt.Println("------ result ------") |
| 198 |
if err != nil { |
| 199 |
fmt.Printf("error: %s\n", err) |
| 200 |
} else { |
| 201 |
fmt.Printf("value: %v (%T)\n", result, result) |
| 202 |
} |
| 203 |
if details != nil { |
| 204 |
fmt.Printf("\n------ eval states ------\n") |
| 205 |
state := details.State() |
| 206 |
stateIDs := state.IDs() |
| 207 |
ids := make([]int, len(stateIDs), len(stateIDs)) |
| 208 |
for i, id := range stateIDs { |
| 209 |
ids[i] = int(id) |
| 210 |
} |
| 211 |
sort.Ints(ids) |
| 212 |
for _, id := range ids { |
| 213 |
v, found := state.Value(int64(id)) |
| 214 |
if !found { |
| 215 |
continue |
| 216 |
} |
| 217 |
fmt.Printf("%d: %v (%T)\n", id, v, v) |
| 218 |
} |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
// mapContainsKeyValue implements the custom function: |
| 223 |
// |
| 224 |
// `map.contains(key, value) bool`. |
| 225 |
func mapContainsKeyValue(args ...ref.Val) ref.Val { |
| 226 |
// The declaration of the function ensures that only arguments which match |
| 227 |
// the mapContainsKey signature will be provided to the function. |
| 228 |
m := args[0].(traits.Mapper) |
| 229 |
|
| 230 |
// CEL has many interfaces for dealing with different type abstractions. |
| 231 |
// The traits.Mapper interface unifies field presence testing on proto |
| 232 |
// messages and maps. |
| 233 |
key := args[1] |
| 234 |
v, found := m.Find(key) |
| 235 |
|
| 236 |
// If not found and the value was non-nil, the value is an error per the |
| 237 |
// `Find` contract. Propagate it accordingly. |
| 238 |
if !found { |
| 239 |
if v != nil { |
| 240 |
return types.ValOrErr(v, "unsupported key type") |
| 241 |
} |
| 242 |
// Return CEL False if the key was not found. |
| 243 |
return types.False |
| 244 |
} |
| 245 |
// Otherwise whether the value at the key equals the value provided. |
| 246 |
return v.Equal(args[2]) |
| 247 |
} |
| 248 |
|
| 249 |
// Functions for constructing CEL inputs. |
| 250 |
|
| 251 |
// auth constructs a `google.rpc.context.AttributeContext.Auth` message. |
| 252 |
func auth(user string, claims map[string]string) *rpcpb.AttributeContext_Auth { |
| 253 |
claimFields := make(map[string]*structpb.Value) |
| 254 |
for k, v := range claims { |
| 255 |
claimFields[k] = structpb.NewStringValue(v) |
| 256 |
} |
| 257 |
return &rpcpb.AttributeContext_Auth{ |
| 258 |
Principal: user, |
| 259 |
Claims: &structpb.Struct{Fields: claimFields}, |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
// request constructs a `google.rpc.context.AttributeContext.Request` message. |
| 264 |
func request(auth *rpcpb.AttributeContext_Auth, t time.Time) map[string]any { |
| 265 |
req := &rpcpb.AttributeContext_Request{ |
| 266 |
Auth: auth, |
| 267 |
Time: &tpb.Timestamp{Seconds: t.Unix()}, |
| 268 |
} |
| 269 |
return map[string]any{"request": req} |
| 270 |
} |
| 271 |
|
| 272 |
// valueToJSON converts the CEL type to a protobuf JSON representation and |
| 273 |
// marshals the result to a string. |
| 274 |
func valueToJSON(val ref.Val) string { |
| 275 |
v, err := val.ConvertToNative(reflect.TypeOf(&structpb.Value{})) |
| 276 |
if err != nil { |
| 277 |
glog.Exit(err) |
| 278 |
} |
| 279 |
marshaller := protojson.MarshalOptions{Indent: " "} |
| 280 |
bytes, err := marshaller.Marshal(v.(proto.Message)) |
| 281 |
if err != nil { |
| 282 |
glog.Exit(err) |
| 283 |
} |
| 284 |
return string(bytes) |
| 285 |
} |
| 286 |
|
| 287 |
var ( |
| 288 |
emptyClaims = make(map[string]string) |
| 289 |
) |