|
| 1 | +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +/* |
| 5 | +Package cel provides a generic CEL expression engine for compiling and evaluating |
| 6 | +expressions against arbitrary data contexts. |
| 7 | +
|
| 8 | +The engine provides lazy-initialized, thread-safe environment caching, expression |
| 9 | +compilation with structured parse and type-check error reporting, boolean and |
| 10 | +generic value evaluation helpers, and built-in safeguards against denial-of-service |
| 11 | +via configurable expression length and runtime cost limits. |
| 12 | +
|
| 13 | +# Basic Usage |
| 14 | +
|
| 15 | +Create an engine with variable declarations, compile an expression, and evaluate it: |
| 16 | +
|
| 17 | + engine := cel.NewEngine( |
| 18 | + celgo.Variable("claims", celgo.MapType(celgo.StringType, celgo.DynType)), |
| 19 | + ) |
| 20 | +
|
| 21 | + expr, err := engine.Compile(`claims["sub"] == "user123"`) |
| 22 | + if err != nil { |
| 23 | + // handle compilation error |
| 24 | + } |
| 25 | +
|
| 26 | + ctx := map[string]any{"claims": map[string]any{"sub": "user123"}} |
| 27 | + result, err := expr.EvaluateBool(ctx) |
| 28 | + // result == true |
| 29 | +
|
| 30 | +# Expression Validation |
| 31 | +
|
| 32 | +Use Check to validate an expression without creating a compiled program. This is |
| 33 | +useful for validating configuration at startup: |
| 34 | +
|
| 35 | + err := engine.Check(`claims["sub"] == "user123"`) |
| 36 | + if err != nil { |
| 37 | + // expression is invalid |
| 38 | + } |
| 39 | +
|
| 40 | +# Error Handling |
| 41 | +
|
| 42 | +Compilation errors are returned as structured types with location information: |
| 43 | +
|
| 44 | + expr, err := engine.Compile(`claims["sub"`) |
| 45 | + var parseErr *cel.ParseError |
| 46 | + if errors.As(err, &parseErr) { |
| 47 | + fmt.Println(parseErr.Source) // the original expression |
| 48 | + fmt.Println(parseErr.Errors) // line/column/message details |
| 49 | + } |
| 50 | +
|
| 51 | + expr, err = engine.Compile(`undefined_var == "test"`) |
| 52 | + var checkErr *cel.CheckError |
| 53 | + if errors.As(err, &checkErr) { |
| 54 | + fmt.Println(checkErr.AsJSON()) // structured JSON error details |
| 55 | + } |
| 56 | +
|
| 57 | +# DoS Protection |
| 58 | +
|
| 59 | +The engine includes configurable safeguards against denial-of-service: |
| 60 | +
|
| 61 | + engine := cel.NewEngine(opts...). |
| 62 | + WithMaxExpressionLength(5000). // reject overly long expressions |
| 63 | + WithCostLimit(500000) // limit runtime evaluation cost |
| 64 | +
|
| 65 | +# Concurrency |
| 66 | +
|
| 67 | +The Engine and CompiledExpression types are safe for concurrent use. A compiled |
| 68 | +expression can be evaluated from multiple goroutines simultaneously. |
| 69 | +*/ |
| 70 | +package cel |
0 commit comments