-
Notifications
You must be signed in to change notification settings - Fork 2
/
policyeval.go
74 lines (68 loc) · 2.11 KB
/
policyeval.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
package validator
import (
"context"
"fmt"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/rego"
)
//Evaluator OPA evaluate interface
type Evaluator interface {
EvaluatePolicy(queryParam []string, policy string, data string) ([]*ValidateResult, error)
}
//policyEval opa evaluate object
type policyEval struct {
}
//NewPolicyEval instantiate new OPA eval Object
func NewPolicyEval() Evaluator {
return &policyEval{}
}
//EvaluatePolicy evaluate opa policy against given json input , accept opa pkg name ,policy rule(deny/allow),policy and input data
// return evaluation result in a bool form
func (pe policyEval) EvaluatePolicy(queryParam []string, policy string, data string) ([]*ValidateResult, error) {
ctx := context.Background()
var inputObject interface{}
// try to read data as json format
inputObject, err := ParseJSON(data)
if err != nil {
var convertedJSON []byte
// try to read data as yaml format and convert it to json
convertedJSON, err = YamlToJSON(data)
if err != nil {
return nil, err
}
// read data as yaml format
inputObject, err = ParseJSON(string(convertedJSON))
if err != nil {
return nil, err
}
}
// Compile the module. The keys are used as identifiers in error messages.
policyKey := fmt.Sprintf("%s.rego", "eval")
compiler, err := ast.CompileModules(map[string]string{
policyKey: policy,
})
if err != nil {
return nil, err
}
packageName := compiler.Modules[policyKey].Package.Path.String()
regoFunc := make([]func(r *rego.Rego), 0)
for _, pr := range queryParam {
regoFunc = append(regoFunc, rego.Query(fmt.Sprintf("%s.%s", packageName, pr)))
}
regoFunc = append(regoFunc, rego.Compiler(compiler))
regoFunc = append(regoFunc, rego.Input(inputObject))
rego := rego.New(regoFunc...)
res, err := rego.Eval(ctx)
if err != nil {
return nil, err
}
validateResult := make([]*ValidateResult, 0)
if len(res) > 0 {
validateResult = append(validateResult, &ValidateResult{ExpressionValue: res[0].Expressions})
}
return validateResult, nil
}
//ValidateResult opa validation results
type ValidateResult struct {
ExpressionValue []*rego.ExpressionValue
}