diff --git a/changes/unreleased/Updated-20230816-141748.yaml b/changes/unreleased/Updated-20230816-141748.yaml new file mode 100644 index 00000000..43ebdfb6 --- /dev/null +++ b/changes/unreleased/Updated-20230816-141748.yaml @@ -0,0 +1,3 @@ +kind: Updated +body: refactor unmarshalling of resources query +time: 2023-08-16T14:17:48.58234+02:00 diff --git a/pkg/policy/api.go b/pkg/policy/api.go index 82ee7348..7192a668 100644 --- a/pkg/policy/api.go +++ b/pkg/policy/api.go @@ -39,8 +39,8 @@ var RegoAPIProvider = data.FSProvider(regoApi, "regoapi") // ResourcesQuery describes a request for a specific resource type from the given scope. // An empty scope is interpreted as the scope of the current input. type ResourcesQuery struct { - ResourceType string `json:"resource_type"` - Scope map[string]string `json:"scope"` + ResourceType string `json:"resource_type" rego:"resource_type"` + Scope map[string]string `json:"scope" rego:"scope"` } // ResourcesResult contains an indication of whether the Scope specified in the diff --git a/pkg/policy/query.go b/pkg/policy/query.go index e53870e5..60c95039 100644 --- a/pkg/policy/query.go +++ b/pkg/policy/query.go @@ -20,9 +20,10 @@ import ( "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/topdown" - "github.com/open-policy-agent/opa/topdown/builtins" "github.com/open-policy-agent/opa/types" + "github.com/snyk/policy-engine/pkg/models" + "github.com/snyk/policy-engine/pkg/rego" ) type Query struct { @@ -38,28 +39,8 @@ func (*Query) decl() *types.Function { } func (q *Query) impl(bctx topdown.BuiltinContext, operands []*ast.Term) (*ast.Term, error) { - scopeOpaObj, err := builtins.ObjectOperand(operands[0].Value, 0) - if err != nil { - return nil, err - } - query := ResourcesQuery{Scope: map[string]string{}} - if err := scopeOpaObj.Iter(func(k, v *ast.Term) error { - key := string(k.Value.(ast.String)) - if key == "resource_type" { - query.ResourceType = string(v.Value.(ast.String)) - } else if key == "scope" { - err := v.Value.(ast.Object).Iter(func(k, v *ast.Term) error { - scopeKey := string(k.Value.(ast.String)) - scopeValue := string(v.Value.(ast.String)) - query.Scope[scopeKey] = scopeValue - return nil - }) - if err != nil { - return err - } - } - return nil - }); err != nil { + query := ResourcesQuery{} + if err := rego.Bind(operands[0].Value, &query); err != nil { return nil, err }