This repository has been archived by the owner on Apr 5, 2021. It is now read-only.
/
policy.go
87 lines (76 loc) 路 1.75 KB
/
policy.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
package attester
import (
"context"
"fmt"
"io"
"os"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/topdown"
)
type policy struct {
name string
module string
trace bool
compiler *ast.Compiler
}
// Policy is the interface for managing policy
type Policy interface {
Evaluate(context.Context, interface{}) []*Violation
Serialize(out io.Writer) error
}
// NewPolicy creates a new policy
func NewPolicy(name string, module string, trace bool) (Policy, error) {
compiler, err := ast.CompileModules(map[string]string{
fmt.Sprintf("%s.rego", name): module,
})
if err != nil {
return nil, err
}
return &policy{
name,
module,
trace,
compiler,
}, nil
}
// ReadPolicy creates a signer from reader
func ReadPolicy(in io.Reader) (Policy, error) {
// TODO: implement
return nil, fmt.Errorf("not implemented")
}
// Evaluate the policy
func (p *policy) Evaluate(context context.Context, input interface{}) []*Violation {
violations := make([]*Violation, 0)
var tracer *topdown.BufferTracer
if p.trace {
tracer = topdown.NewBufferTracer()
}
rego := rego.New(
rego.Query(fmt.Sprintf("data.%s.violation", p.name)),
rego.Compiler(p.compiler),
rego.Input(input),
rego.Tracer(tracer),
)
rs, err := rego.Eval(context)
if err != nil {
violations = append(violations, NewViolation(err))
}
if p.trace {
topdown.PrettyTrace(os.Stdout, *tracer)
}
if len(rs) > 0 {
for _, v := range rs {
for _, e := range v.Expressions {
for _, val := range e.Value.([]interface{}) {
violations = append(violations, NewViolation(val))
}
}
}
}
return violations
}
func (p *policy) Serialize(out io.Writer) error {
// TODO: implement
return fmt.Errorf("not implemented")
}