| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 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 |
|
| 54 |
|
| 55 |
|
| 56 |
func exercise1() { |
| 57 |
fmt.Println("=== Exercise 1: Hello World ===\n") |
| 58 |
|
| 59 |
env, err := cel.NewEnv() |
| 60 |
if err != nil { |
| 61 |
glog.Exitf("env error: %v", err) |
| 62 |
} |
| 63 |
|
| 64 |
ast, iss := env.Parse(`"Hello, World!"`) |
| 65 |
|
| 66 |
if iss.Err() != nil { |
| 67 |
glog.Exit(iss.Err()) |
| 68 |
} |
| 69 |
|
| 70 |
checked, iss := env.Check(ast) |
| 71 |
|
| 72 |
if iss.Err() != nil { |
| 73 |
glog.Exit(iss.Err()) |
| 74 |
} |
| 75 |
|
| 76 |
if checked.OutputType() != cel.StringType { |
| 77 |
glog.Exitf( |
| 78 |
"Got %v, wanted %v result type", |
| 79 |
checked.OutputType(), cel.StringType) |
| 80 |
} |
| 81 |
|
| 82 |
program, err := env.Program(checked) |
| 83 |
if err != nil { |
| 84 |
glog.Exitf("program error: %v", err) |
| 85 |
} |
| 86 |
|
| 87 |
eval(program, cel.NoVars()) |
| 88 |
fmt.Println() |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
func exercise2() { |
| 96 |
fmt.Println("=== Exercise 2: Variables ===\n") |
| 97 |
|
| 98 |
|
| 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 |
|
| 112 |
|
| 113 |
claims := map[string]string{"group": "admin"} |
| 114 |
eval(program, request(auth("user:[email protected]", claims), time.Now())) |
| 115 |
fmt.Println() |
| 116 |
} |
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 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 |
|
| 142 |
|
| 143 |
eval(program, request(auth("user:[email protected]", emptyClaims), time.Now())) |
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
eval(program, request(auth("other:[email protected]", emptyClaims), time.Now())) |
| 148 |
|
| 149 |
fmt.Println() |
| 150 |
} |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
func exercise4() { |
| 157 |
fmt.Println("=== Exercise 4: Customization ===\n") |
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
typeParamA := cel.TypeParamType("A") |
| 164 |
typeParamB := cel.TypeParamType("B") |
| 165 |
mapAB := cel.MapType(typeParamA, typeParamB) |
| 166 |
|
| 167 |
|
| 168 |
env, _ := cel.NewEnv( |
| 169 |
cel.Types(&rpcpb.AttributeContext_Request{}), |
| 170 |
|
| 171 |
cel.Variable("request", |
| 172 |
cel.ObjectType("google.rpc.context.AttributeContext.Request"), |
| 173 |
), |
| 174 |
|
| 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 |
|
| 187 |
|
| 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 |
|
| 200 |
|
| 201 |
|
| 202 |
func exercise5() { |
| 203 |
fmt.Println("=== Exercise 5: Building JSON ===\n") |
| 204 |
|
| 205 |
|
| 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 |
|
| 230 |
|
| 231 |
fmt.Printf("------ type conversion ------\n%v\n", valueToJSON(out)) |
| 232 |
fmt.Println() |
| 233 |
} |
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
func exercise6() { |
| 241 |
fmt.Println("=== Exercise 6: Building Protos ===\n") |
| 242 |
|
| 243 |
|
| 244 |
|
| 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 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 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 |
|
| 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 |
|
| 289 |
|
| 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 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 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 |
|
| 320 |
|
| 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 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
func exercise8() { |
| 344 |
fmt.Println("=== Exercise 8: Tuning ===\n") |
| 345 |
|
| 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 |
|
| 354 |
trueVars := map[string]any{"x": int64(4), "y": uint64(2)} |
| 355 |
program, _ := env.Program(ast, cel.EvalOptions(cel.OptOptimize)) |
| 356 |
|
| 357 |
eval(program, trueVars) |
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
|
| 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 |
|
| 367 |
|
| 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 |
|
| 375 |
|
| 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 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 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 |
|
| 402 |
|
| 403 |
|
| 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 |
|
| 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 |
|
| 464 |
|
| 465 |
|
| 466 |
func mapContainsKeyValue(args ...ref.Val) ref.Val { |
| 467 |
|
| 468 |
|
| 469 |
m := args[0].(traits.Mapper) |
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
key := args[1] |
| 475 |
v, found := m.Find(key) |
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
if !found { |
| 480 |
if v != nil { |
| 481 |
return types.ValOrErr(v, "unsupported key type") |
| 482 |
} |
| 483 |
|
| 484 |
return types.False |
| 485 |
} |
| 486 |
|
| 487 |
return v.Equal(args[2]) |
| 488 |
} |
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 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 |
|
| 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 |
|
| 514 |
|
| 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 |
) |