-
Notifications
You must be signed in to change notification settings - Fork 44
feat(policies): allow custom builtin functions in Rego policies #2552
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
30e03ed
custom builtins for rego
jiparis e5d4404
add hello builtin
jiparis 89755e5
add example and some tests
jiparis 965ceff
fix claude
jiparis 633a358
undo import change
jiparis aa08f47
undo change
jiparis f8baa9a
upgrade to opa/v1
jiparis c865b4d
lint
jiparis 479a242
fix coyright notice
jiparis a720e2a
refactor to use opa registry directly
jiparis 520022d
add skill
jiparis eb94f8b
fix comment
jiparis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| --- | ||
| name: custom-builtin-functions | ||
| description: Create a custom builtin function to be used in the Rego policy engine | ||
| --- | ||
|
|
||
| ### Policy Engine Extension | ||
|
|
||
| The OPA/Rego policy engine supports custom built-in functions written in Go. | ||
|
|
||
| **Adding Custom Built-ins**: | ||
|
|
||
| 1. **Create Built-in Implementation** (e.g., `pkg/policies/engine/rego/builtins/myfeature.go`): | ||
| ```go | ||
| package builtins | ||
|
|
||
| import ( | ||
| "github.com/open-policy-agent/opa/ast" | ||
| "github.com/open-policy-agent/opa/topdown" | ||
| "github.com/open-policy-agent/opa/types" | ||
| ) | ||
|
|
||
| const myFuncName = "chainloop.my_function" | ||
|
|
||
| func RegisterMyBuiltins() error { | ||
| return Register(&ast.Builtin{ | ||
| Name: myFuncName, | ||
| Description: "Description of what this function does", | ||
| Decl: types.NewFunction( | ||
| types.Args(types.Named("input", types.S).Description("this is the input")), | ||
| types.Named("result", types.S).Description("this is the result"), | ||
| ), | ||
| }, myFunctionImpl) | ||
| } | ||
|
|
||
| func myFunctionImpl(bctx topdown.BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { | ||
| // Extract arguments | ||
| input, ok := operands[0].Value.(ast.String) | ||
| if !ok { | ||
| return fmt.Errorf("input must be a string") | ||
| } | ||
|
|
||
| // Implement logic | ||
| result := processInput(string(input)) | ||
|
|
||
| // Return result | ||
| return iter(ast.StringTerm(result)) | ||
| } | ||
|
|
||
| // Autoregisters on package load | ||
| func init() { | ||
| if err := RegisterMyBuiltins(); err != nil { | ||
| panic(fmt.Sprintf("failed to register built-ins: %v", err)) | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| 2. **Use in Policies** (`*.rego`): | ||
| ```rego | ||
| package example | ||
| import rego.v1 | ||
|
|
||
| result := { | ||
| "violations": violations, | ||
| "skipped": false | ||
| } | ||
|
|
||
| violations contains msg if { | ||
| output := chainloop.my_function(input.value) | ||
| output != "expected" | ||
| msg := "Function returned unexpected value" | ||
| } | ||
| ``` | ||
|
|
||
| **Guidelines**: | ||
| - Use `chainloop.*` namespace for all custom built-ins | ||
| - Functions that call third party services should be marked as non-restrictive by adding the `NonRestrictiveBuiltin` category to the builtin definition | ||
| - Always implement proper error handling and return meaningful error messages | ||
| - Use context from `BuiltinContext` for timeout/cancellation support | ||
| - Document function signatures and behavior in the `Description` field and parameter definitions |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| // | ||
| // Copyright 2025 The Chainloop Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package builtins | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
|
|
||
| "github.com/open-policy-agent/opa/v1/ast" | ||
| "github.com/open-policy-agent/opa/v1/topdown" | ||
| "github.com/open-policy-agent/opa/v1/types" | ||
| ) | ||
|
|
||
| const helloBuiltinName = "chainloop.hello" | ||
|
|
||
| func RegisterHelloBuiltin() error { | ||
| return Register(&ast.Builtin{ | ||
| Name: helloBuiltinName, | ||
| Description: "Example builtin", | ||
| Decl: types.NewFunction( | ||
| types.Args( | ||
| types.Named("name", types.S).Description("Name of the person to greet"), // Digest to fetch | ||
| ), | ||
| types.Named("response", types.A).Description("the hello world message"), // Response as object | ||
| ), | ||
| }, getHelloImpl) | ||
| } | ||
|
|
||
| type helloResponse struct { | ||
| Message string `json:"message"` | ||
| } | ||
|
|
||
| func getHelloImpl(_ topdown.BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { | ||
| if len(operands) < 1 { | ||
| return errors.New("need one operand") | ||
| } | ||
|
|
||
| name, ok := operands[0].Value.(ast.String) | ||
| if !ok { | ||
| return errors.New("digest must be a string") | ||
| } | ||
|
|
||
| message := fmt.Sprintf("Hello, %s!", string(name)) | ||
|
|
||
| // call the iterator with the output value | ||
| return iter(ast.NewTerm(ast.MustInterfaceToValue(helloResponse{message}))) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| // | ||
| // Copyright 2025 The Chainloop Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package builtins | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
|
|
||
| "github.com/open-policy-agent/opa/v1/rego" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestHelloBuiltin(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| policy string | ||
| mockErr error | ||
| expectedMessage string | ||
| expectError bool | ||
| }{ | ||
| { | ||
| name: "successful render", | ||
| policy: `package test | ||
| import rego.v1 | ||
|
|
||
| result := chainloop.hello("world")`, | ||
| expectedMessage: "Hello, world!", | ||
| expectError: false, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| require.NoError(t, RegisterHelloBuiltin()) | ||
| // Prepare rego evaluation | ||
| ctx := context.Background() | ||
| r := rego.New( | ||
| rego.Query("data.test.result"), | ||
| rego.Module("test.rego", tt.policy), | ||
| ) | ||
| rs, err := r.Eval(ctx) | ||
|
|
||
| if tt.expectError { | ||
| assert.Error(t, err) | ||
| return | ||
| } | ||
|
|
||
| require.NoError(t, err) | ||
| require.Len(t, rs, 1) | ||
| require.Len(t, rs[0].Expressions, 1) | ||
|
|
||
| result, ok := rs[0].Expressions[0].Value.(map[string]interface{}) | ||
| require.True(t, ok) | ||
|
|
||
| // The status is returned as a number, convert it appropriately | ||
| msgVal := result["message"] | ||
| assert.Equal(t, tt.expectedMessage, msgVal) | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| // Copyright 2025 The Chainloop Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package builtins | ||
|
|
||
| import ( | ||
| "github.com/open-policy-agent/opa/v1/ast" | ||
| "github.com/open-policy-agent/opa/v1/topdown" | ||
| ) | ||
|
|
||
| const ( | ||
| // NonRestrictiveBuiltin is used in builtin definition categories to mark a builtin as non-suitable for Chainloop's restrictive mode | ||
| NonRestrictiveBuiltin = "non-restrictive" | ||
| ) | ||
|
|
||
| // Register registers built-ins globally with OPA | ||
| // This should be called once during initialization | ||
| func Register(def *ast.Builtin, builtinFunc topdown.BuiltinFunc) error { | ||
| // Register the built-in declaration with AST | ||
| ast.RegisterBuiltin(def) | ||
|
|
||
| // Register the implementation with topdown | ||
| topdown.RegisterBuiltinFunc(def.Name, builtinFunc) | ||
| return nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
to be able to devel
CONTAINER_IMAGEpolicies.