-
Notifications
You must be signed in to change notification settings - Fork 10
/
query.go
88 lines (77 loc) · 2.36 KB
/
query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// © 2022-2023 Snyk Limited All rights reserved.
//
// 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 policy
import (
"context"
"fmt"
"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"
)
type Query struct {
ResourcesResolver ResourcesResolver
}
func (*Query) name() string {
return queryName
}
func (*Query) decl() *types.Function {
return builtinDeclarations[queryName]
}
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 {
return nil, err
}
resources, err := q.ResolveResources(bctx.Context, query)
if err != nil {
return nil, err
}
regoResources, err := resourceStatesToRegoInputs(resources)
if err != nil {
return nil, err
}
return ast.ArrayTerm(regoResources...), nil
}
func (q *Query) ResolveResources(ctx context.Context, query ResourcesQuery) ([]models.ResourceState, error) {
res, err := q.ResourcesResolver(ctx, query)
if err != nil {
return nil, fmt.Errorf("error in ResourcesResolver: %s", err)
}
if res.ScopeFound {
return res.Resources, nil
}
return []models.ResourceState{}, nil
}