Skip to content
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

chore: use rego.Bind to parse resources query #249

Merged
merged 2 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changes/unreleased/Updated-20230816-141748.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
kind: Updated
body: refactor unmarshalling of resources query
time: 2023-08-16T14:17:48.58234+02:00
4 changes: 2 additions & 2 deletions pkg/policy/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 4 additions & 23 deletions pkg/policy/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}

Expand Down