Skip to content

Commit 4c4f303

Browse files
authored
feat(policies): allow arrays as input for policies (#1438)
Signed-off-by: Jose I. Paris <[email protected]>
1 parent 1a74531 commit 4c4f303

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

pkg/policies/engine/rego/rego.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ const (
4343
// EnvironmentModePermissive allows all operations on the compiler
4444
EnvironmentModePermissive EnvironmentMode = 1
4545
inputArgs = "args"
46+
inputElements = "elements"
4647
deprecatedRule = "violations"
4748
mainRule = "result"
4849
)
@@ -79,6 +80,13 @@ func (r *Rego) Verify(ctx context.Context, policy *engine.Policy, input []byte,
7980
return nil, fmt.Errorf("failed to parse input: %w", err)
8081
}
8182

83+
// if input is an array, transform it to an object
84+
if array, ok := decodedInput.([]interface{}); ok {
85+
inputMap := make(map[string]interface{})
86+
inputMap[inputElements] = array
87+
decodedInput = inputMap
88+
}
89+
8290
// put arguments embedded in the input object
8391
if args != nil {
8492
inputMap, ok := decodedInput.(map[string]interface{})

pkg/policies/engine/rego/rego_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,23 @@ func TestRego_VerifyWithValidPolicy(t *testing.T) {
6767
})
6868
}
6969

70+
func TestRego_VerifyWithInputArray(t *testing.T) {
71+
regoContent, err := os.ReadFile("testfiles/arrays.rego")
72+
require.NoError(t, err)
73+
74+
r := &Rego{}
75+
policy := &engine.Policy{
76+
Name: "foobar",
77+
Source: regoContent,
78+
}
79+
80+
t.Run("creates 'elements' field", func(t *testing.T) {
81+
result, err := r.Verify(context.TODO(), policy, []byte(`[{"foo": "bar"}, {"foo2":"bar2"}]`), nil)
82+
require.NoError(t, err)
83+
assert.Equal(t, "2", result.SkipReason)
84+
})
85+
}
86+
7087
func TestRego_VerifyWithArguments(t *testing.T) {
7188
regoContent, err := os.ReadFile("testfiles/arguments.rego")
7289
require.NoError(t, err)
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package main
2+
3+
import rego.v1
4+
5+
result := {
6+
"violations": [],
7+
"skipped": true,
8+
"skip_reason": sprintf("%d", [count(input.elements)])
9+
}

0 commit comments

Comments
 (0)