|
| 1 | +--- |
| 2 | +name: custom-builtin-functions |
| 3 | +description: Create a custom builtin function to be used in the Rego policy engine |
| 4 | +--- |
| 5 | + |
| 6 | +### Policy Engine Extension |
| 7 | + |
| 8 | +The OPA/Rego policy engine supports custom built-in functions written in Go. |
| 9 | + |
| 10 | +**Adding Custom Built-ins**: |
| 11 | + |
| 12 | +1. **Create Built-in Implementation** (e.g., `pkg/policies/engine/rego/builtins/myfeature.go`): |
| 13 | +```go |
| 14 | +package builtins |
| 15 | + |
| 16 | +import ( |
| 17 | + "github.com/open-policy-agent/opa/ast" |
| 18 | + "github.com/open-policy-agent/opa/topdown" |
| 19 | + "github.com/open-policy-agent/opa/types" |
| 20 | +) |
| 21 | + |
| 22 | +const myFuncName = "chainloop.my_function" |
| 23 | + |
| 24 | +func RegisterMyBuiltins() error { |
| 25 | + return Register(&ast.Builtin{ |
| 26 | + Name: myFuncName, |
| 27 | + Description: "Description of what this function does", |
| 28 | + Decl: types.NewFunction( |
| 29 | + types.Args(types.Named("input", types.S).Description("this is the input")), |
| 30 | + types.Named("result", types.S).Description("this is the result"), |
| 31 | + ), |
| 32 | + }, myFunctionImpl) |
| 33 | +} |
| 34 | + |
| 35 | +func myFunctionImpl(bctx topdown.BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { |
| 36 | + // Extract arguments |
| 37 | + input, ok := operands[0].Value.(ast.String) |
| 38 | + if !ok { |
| 39 | + return fmt.Errorf("input must be a string") |
| 40 | + } |
| 41 | + |
| 42 | + // Implement logic |
| 43 | + result := processInput(string(input)) |
| 44 | + |
| 45 | + // Return result |
| 46 | + return iter(ast.StringTerm(result)) |
| 47 | +} |
| 48 | + |
| 49 | +// Autoregisters on package load |
| 50 | +func init() { |
| 51 | + if err := RegisterMyBuiltins(); err != nil { |
| 52 | + panic(fmt.Sprintf("failed to register built-ins: %v", err)) |
| 53 | + } |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +2. **Use in Policies** (`*.rego`): |
| 58 | +```rego |
| 59 | +package example |
| 60 | +import rego.v1 |
| 61 | +
|
| 62 | +result := { |
| 63 | + "violations": violations, |
| 64 | + "skipped": false |
| 65 | +} |
| 66 | +
|
| 67 | +violations contains msg if { |
| 68 | + output := chainloop.my_function(input.value) |
| 69 | + output != "expected" |
| 70 | + msg := "Function returned unexpected value" |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +**Guidelines**: |
| 75 | +- Use `chainloop.*` namespace for all custom built-ins |
| 76 | +- Functions that call third party services should be marked as non-restrictive by adding the `NonRestrictiveBuiltin` category to the builtin definition |
| 77 | +- Always implement proper error handling and return meaningful error messages |
| 78 | +- Use context from `BuiltinContext` for timeout/cancellation support |
| 79 | +- Document function signatures and behavior in the `Description` field and parameter definitions |
0 commit comments