/
util.go
274 lines (237 loc) · 7.2 KB
/
util.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package commands
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/golang/protobuf/ptypes/timestamp"
"k8s.io/helm/pkg/renderutil"
"github.com/mitchellh/colorstring"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/tester"
"github.com/open-policy-agent/opa/topdown"
yaml "gopkg.in/yaml.v3"
"k8s.io/helm/pkg/chartutil"
"k8s.io/helm/pkg/proto/hapi/chart"
)
var FilepathValueEmpty = errors.New("given filepath value is empty")
var FilepathDirUnexpected = errors.New("filepath given is a Dir. We expect a path to a file")
var UnmatchedQuery = errors.New("your given query did not yield any matches")
var InvalidPolicyPath = errors.New("invalid policy path")
var PolicyFailure = errors.New("your policy failed")
var DuplicatePolicyFailure = errors.New("duplicate rule names found")
var expectQuery = regexp.MustCompile("^expect(_[a-zA-Z]+)*$")
func mergeValues(valueFiles []string) (map[string]interface{}, error) {
base := map[string]interface{}{}
for _, filePath := range valueFiles {
currentMap := map[string]interface{}{}
bytes, err := readFile(filePath)
if err != nil {
return nil, err
}
if err := yaml.Unmarshal(bytes, ¤tMap); err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", filePath, err)
}
base = mergeMaps(base, currentMap)
}
return base, nil
}
func mergeMaps(a, b map[string]interface{}) map[string]interface{} {
out := make(map[string]interface{}, len(a))
for k, v := range a {
out[k] = v
}
for k, v := range b {
if v, ok := v.(map[string]interface{}); ok {
if bv, ok := out[k]; ok {
if bv, ok := bv.(map[string]interface{}); ok {
out[k] = mergeMaps(bv, v)
continue
}
}
}
out[k] = v
}
return out
}
func readFile(filePath string) ([]byte, error) {
if strings.TrimSpace(filePath) == "-" {
return ioutil.ReadAll(os.Stdin)
}
return ioutil.ReadFile(filePath)
}
func validateAndRender(templatePath string, valuesMap map[string]interface{}) (map[string]string, error) {
templateFiles, err := WalkTemplatePath(templatePath)
if err != nil {
return nil, fmt.Errorf("template validation failed: %w", err)
}
values, err := yaml.Marshal(valuesMap)
if err != nil {
return nil, fmt.Errorf("couldnt marshal values: %w", err)
}
valuesFile := ioutil.NopCloser(bytes.NewReader(values))
return render(valuesFile, templateFiles)
}
func UnmarshalYamlMap(in map[string]string) (map[string]interface{}, error) {
out := make(map[string]interface{})
for fpath, template := range in {
if filepath.Ext(fpath) == ".yml" || filepath.Ext(fpath) == ".yaml" {
documents := strings.Split(template, "\n---\n")
var configDocs []interface{}
for _, doc := range documents {
var config interface{}
err := yaml.Unmarshal([]byte(doc), &config)
if err != nil {
return nil, fmt.Errorf("Unmarshal '%s' failed: %v", fpath, err)
}
if config != nil {
configDocs = append(configDocs, config)
}
}
if configDocs != nil && len(configDocs) > 1 {
out[filepath.Base(fpath)] = configDocs
}
if configDocs != nil && len(configDocs) == 1 {
out[filepath.Base(fpath)] = configDocs[0]
}
} else {
out[filepath.Base(fpath)] = template
}
}
return out, nil
}
func render(values io.ReadCloser, templates map[string]io.ReadCloser) (map[string]string, error) {
var name string
var reader io.ReadCloser
var data []byte
defer values.Close()
chartTemplates := make([]*chart.Template, 0)
for name, reader = range templates {
defer reader.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(reader)
data = buf.Bytes()
chartTemplates = append(chartTemplates, &chart.Template{Name: name, Data: data})
}
buf := new(bytes.Buffer)
buf.ReadFrom(values)
valuesRaw := buf.String()
testChart := &chart.Chart{
Metadata: &chart.Metadata{Name: "hcunit"},
Templates: chartTemplates,
Values: &chart.Config{Raw: valuesRaw},
}
defaultConfig := &chart.Config{Raw: ""}
defaultOptions := renderutil.Options{
ReleaseOptions: chartutil.ReleaseOptions{
Name: "hcunit-name",
Time: new(timestamp.Timestamp),
Namespace: "hcunit-namespace",
Revision: 1,
IsUpgrade: false,
IsInstall: true,
},
}
return renderutil.Render(testChart, defaultConfig, defaultOptions)
}
//WalkTemplatePath - walk a given template path to read all
// of the templates (even nested templates) into a map
func WalkTemplatePath(templatePath string) (map[string]io.ReadCloser, error) {
templates := make(map[string]io.ReadCloser)
err := filepath.Walk(templatePath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("failure accessing a path %q: %w", path, err)
}
if !info.IsDir() {
template, err := os.Open(path)
if err != nil {
return fmt.Errorf("reading file failed: %w", err)
}
templates[path] = template
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error walking the path %q: %v\n", templatePath, err)
}
return templates, nil
}
func getQueryList(policy string) map[string]int {
res := map[string]int{}
mods, _, _ := tester.Load([]string{policy}, nil)
for _, mod := range mods {
for _, rule := range mod.Rules {
if strings.HasPrefix("expect[", string(rule.Head.Name)) ||
strings.HasPrefix("assert[", string(rule.Head.Name)) {
res[fmt.Sprintf("%s[%s]", rule.Head.Name, rule.Head.Key)] += 1
}
}
}
return res
}
func evalPolicyOnInput(writer io.Writer, policy string, namespace string, input interface{}) error {
testResults := make(map[string]bool)
ctx := context.Background()
var results rego.ResultSet
queryList := getQueryList(policy)
for querySuffix, querymatches := range queryList {
if querymatches > 1 {
colorstring.Println("[red]ERROR: you are using duplicate test names or variables. This could cause test failures to NOT be detected properly")
colorstring.Println(fmt.Sprintf("[yellow]DUPLICATE KEY: %s", querySuffix))
return DuplicatePolicyFailure
}
queryString := fmt.Sprintf("data.%s.%s", namespace, querySuffix)
buf := topdown.NewBufferTracer()
r := rego.New(
rego.Query(queryString),
rego.Tracer(buf),
rego.Load([]string{policy}, nil),
)
query, err := r.PrepareForEval(ctx)
if err != nil {
return fmt.Errorf("failed preparing for eval on policies: %w", err)
}
resultSet, err := query.Eval(ctx, rego.EvalInput(input))
if err != nil {
return fmt.Errorf("failed eval on policies: %w", err)
}
testResults[queryString] = false
for _, result := range resultSet {
for _, expression := range result.Expressions {
if expression.Text == queryString {
testResults[queryString] = true
}
}
}
if len(resultSet) > 0 {
results = append(results, resultSet...)
}
topdown.PrettyTrace(writer, *buf)
}
if len(queryList) <= 0 {
return UnmatchedQuery
}
testFailed := false
for testname, passed := range testResults {
if passed {
colorstring.Print("[green]PASS: ")
fmt.Println(testname)
} else {
testFailed = true
colorstring.Print("[red]FAIL: ")
fmt.Println(testname)
}
}
if testFailed {
colorstring.Println("[_red_][FAILURE] Policy violations found on the Helm Chart!")
return PolicyFailure
}
colorstring.Println("[green][SUCCESS] Your Helm Chart complies with all policies!")
return nil
}