forked from kyverno/kyverno
/
scenario.go
440 lines (392 loc) · 13 KB
/
scenario.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package testrunner
import (
"bytes"
"encoding/json"
"io/ioutil"
"os"
ospath "path"
"reflect"
"testing"
kyverno "github.com/nirmata/kyverno/pkg/api/kyverno/v1"
client "github.com/nirmata/kyverno/pkg/dclient"
"github.com/nirmata/kyverno/pkg/engine"
"github.com/nirmata/kyverno/pkg/engine/response"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/scheme"
"gopkg.in/yaml.v2"
apiyaml "k8s.io/apimachinery/pkg/util/yaml"
)
type scenarioT struct {
testCases []scaseT
}
//scase defines input and output for a case
type scaseT struct {
Input sInput `yaml:"input"`
Expected sExpected `yaml:"expected"`
}
//sInput defines input for a test scenario
type sInput struct {
Policy string `yaml:"policy"`
Resource string `yaml:"resource"`
LoadResources []string `yaml:"loadresources,omitempty"`
}
type sExpected struct {
Mutation sMutation `yaml:"mutation,omitempty"`
Validation sValidation `yaml:"validation,omitempty"`
Generation sGeneration `yaml:"generation,omitempty"`
}
type sMutation struct {
// path to the patched resource to be compared with
PatchedResource string `yaml:"patchedresource,omitempty"`
// expected response from the policy engine
PolicyResponse response.PolicyResponse `yaml:"policyresponse"`
}
type sValidation struct {
// expected response from the policy engine
PolicyResponse response.PolicyResponse `yaml:"policyresponse"`
}
type sGeneration struct {
// generated resources
GeneratedResources []kyverno.ResourceSpec `yaml:"generatedResources"`
// expected response from the policy engine
PolicyResponse response.PolicyResponse `yaml:"policyresponse"`
}
//getRelativePath expects a path relative to project and builds the complete path
func getRelativePath(path string) string {
gp := os.Getenv("GOPATH")
ap := ospath.Join(gp, projectPath)
return ospath.Join(ap, path)
}
func loadScenario(t *testing.T, path string) (*scenarioT, error) {
fileBytes, err := loadFile(t, path)
if err != nil {
return nil, err
}
var testCases []scaseT
// load test cases separated by '---'
// each test case defines an input & expected result
scenariosBytes := bytes.Split(fileBytes, []byte("---"))
for _, scenarioBytes := range scenariosBytes {
tc := scaseT{}
if err := yaml.Unmarshal([]byte(scenarioBytes), &tc); err != nil {
t.Errorf("failed to decode test case YAML: %v", err)
continue
}
testCases = append(testCases, tc)
}
scenario := scenarioT{
testCases: testCases,
}
return &scenario, nil
}
// loadFile loads file in byte buffer
func loadFile(t *testing.T, path string) ([]byte, error) {
path = getRelativePath(path)
t.Logf("reading file %s", path)
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err
}
return ioutil.ReadFile(path)
}
func runScenario(t *testing.T, s *scenarioT) bool {
for _, tc := range s.testCases {
runTestCase(t, tc)
}
return true
}
func runTestCase(t *testing.T, tc scaseT) bool {
policy := loadPolicy(t, tc.Input.Policy)
if policy == nil {
t.Error("Policy not loaded")
t.FailNow()
}
resource := loadPolicyResource(t, tc.Input.Resource)
if resource == nil {
t.Error("Resources not loaded")
t.FailNow()
}
var er response.EngineResponse
er = engine.Mutate(engine.PolicyContext{Policy: *policy, NewResource: *resource, ExcludeGroupRole: []string{}})
t.Log("---Mutation---")
validateResource(t, er.PatchedResource, tc.Expected.Mutation.PatchedResource)
validateResponse(t, er.PolicyResponse, tc.Expected.Mutation.PolicyResponse)
// pass the patched resource from mutate to validate
if len(er.PolicyResponse.Rules) > 0 {
resource = &er.PatchedResource
}
er = engine.Validate(engine.PolicyContext{Policy: *policy, NewResource: *resource, ExcludeGroupRole: []string{}})
t.Log("---Validation---")
validateResponse(t, er.PolicyResponse, tc.Expected.Validation.PolicyResponse)
// Generation
if resource.GetKind() == "Namespace" {
// generate mock client if resources are to be loaded
// - create mock client
// - load resources
client := getClient(t, tc.Input.LoadResources)
t.Logf("creating NS %s", resource.GetName())
if err := createNamespace(client, resource); err != nil {
t.Error(err)
} else {
policyContext := engine.PolicyContext{
NewResource: *resource,
Policy: *policy,
Client: client,
ExcludeGroupRole: []string{},
}
er = engine.Generate(policyContext)
t.Log(("---Generation---"))
validateResponse(t, er.PolicyResponse, tc.Expected.Generation.PolicyResponse)
// Expected generate resource will be in same namespaces as resource
validateGeneratedResources(t, client, *policy, resource.GetName(), tc.Expected.Generation.GeneratedResources)
}
}
return true
}
func createNamespace(client *client.Client, ns *unstructured.Unstructured) error {
_, err := client.CreateResource("", "Namespace", "", ns, false)
return err
}
func validateGeneratedResources(t *testing.T, client *client.Client, policy kyverno.ClusterPolicy, namespace string, expected []kyverno.ResourceSpec) {
t.Log("--validate if resources are generated---")
// list of expected generated resources
for _, resource := range expected {
if _, err := client.GetResource("", resource.Kind, namespace, resource.Name); err != nil {
t.Errorf("generated resource %s/%s/%s not found. %v", resource.Kind, namespace, resource.Name, err)
}
}
}
func validateResource(t *testing.T, responseResource unstructured.Unstructured, expectedResourceFile string) {
resourcePrint := func(obj unstructured.Unstructured, msg string) {
t.Logf("-----%s----", msg)
if data, err := obj.MarshalJSON(); err == nil {
t.Log(string(data))
}
}
if expectedResourceFile == "" {
t.Log("expected resource file not specified, wont compare resources")
return
}
// load expected resource
expectedResource := loadPolicyResource(t, expectedResourceFile)
if expectedResource == nil {
t.Logf("failed to get the expected resource: %s", expectedResourceFile)
return
}
resourcePrint(responseResource, "response resource")
resourcePrint(*expectedResource, "expected resource")
// compare the resources
if !reflect.DeepEqual(responseResource, *expectedResource) {
t.Error("failed: response resource returned does not match expected resource")
return
}
t.Log("success: response resource returned matches expected resource")
}
func validateResponse(t *testing.T, er response.PolicyResponse, expected response.PolicyResponse) {
if reflect.DeepEqual(expected, (response.PolicyResponse{})) {
t.Log("no response expected")
return
}
// cant do deepEquals and the stats will be different, or we nil those fields and then do a comparison
// forcing only the fields that are specified to be comprared
// doing a field by fields comparison will allow us to provied more details logs and granular error reporting
// check policy name is same :P
if er.Policy != expected.Policy {
t.Errorf("Policy name: expected %s, received %s", expected.Policy, er.Policy)
}
// compare resource spec
compareResourceSpec(t, er.Resource, expected.Resource)
// //TODO stats
// if er.RulesAppliedCount != expected.RulesAppliedCount {
// t.Log("RulesAppliedCount: error")
// }
// rules
if len(er.Rules) != len(expected.Rules) {
t.Errorf("rule count error, er.Rules=%d, expected.Rules=%d", len(er.Rules), len(expected.Rules))
return
}
if len(er.Rules) == len(expected.Rules) {
// if there are rules being applied then we compare the rule response
// as the rules are applied in the order defined, the comparison of rules will be in order
for index, r := range expected.Rules {
compareRules(t, er.Rules[index], r)
}
}
}
func compareResourceSpec(t *testing.T, resource response.ResourceSpec, expectedResource response.ResourceSpec) {
// kind
if resource.Kind != expectedResource.Kind {
t.Errorf("kind: expected %s, received %s", expectedResource.Kind, resource.Kind)
}
// //TODO apiVersion
// if resource.APIVersion != expectedResource.APIVersion {
// t.Error("error: apiVersion")
// }
// namespace
if resource.Namespace != expectedResource.Namespace {
t.Errorf("namespace: expected %s, received %s", expectedResource.Namespace, resource.Namespace)
}
// name
if resource.Name != expectedResource.Name {
t.Errorf("name: expected %s, received %s", expectedResource.Name, resource.Name)
}
}
func compareRules(t *testing.T, rule response.RuleResponse, expectedRule response.RuleResponse) {
// name
if rule.Name != expectedRule.Name {
t.Errorf("rule name: expected %s, received %+v", expectedRule.Name, rule.Name)
// as the rule names dont match no need to compare the rest of the information
}
// type
if rule.Type != expectedRule.Type {
t.Errorf("rule type: expected %s, received %s", expectedRule.Type, rule.Type)
}
// message
// compare messages if expected rule message is not empty
if expectedRule.Message != "" && rule.Message != expectedRule.Message {
t.Errorf("rule message: expected %s, received %s", expectedRule.Message, rule.Message)
}
// //TODO patches
// if reflect.DeepEqual(rule.Patches, expectedRule.Patches) {
// t.Log("error: patches")
// }
// success
if rule.Success != expectedRule.Success {
t.Errorf("rule success: expected %t, received %t", expectedRule.Success, rule.Success)
}
}
func loadPolicyResource(t *testing.T, file string) *unstructured.Unstructured {
// expect only one resource to be specified in the YAML
resources := loadResource(t, file)
if resources == nil {
t.Log("no resource specified")
return nil
}
if len(resources) > 1 {
t.Logf("more than one resource specified in the file %s", file)
t.Log("considering the first one for policy application")
}
return resources[0]
}
func getClient(t *testing.T, files []string) *client.Client {
var objects []runtime.Object
if files != nil {
for _, file := range files {
objects = loadObjects(t, file)
}
}
// create mock client
scheme := runtime.NewScheme()
// mock client expects the resource to be as runtime.Object
c, err := client.NewMockClient(scheme, objects...)
if err != nil {
t.Errorf("failed to create client. %v", err)
return nil
}
// get GVR from GVK
gvrs := getGVRForResources(objects)
c.SetDiscovery(client.NewFakeDiscoveryClient(gvrs))
t.Log("created mock client with pre-loaded resources")
return c
}
func getGVRForResources(objects []runtime.Object) []schema.GroupVersionResource {
var gvrs []schema.GroupVersionResource
for _, obj := range objects {
gvk := obj.GetObjectKind().GroupVersionKind()
gv := gvk.GroupVersion()
// maintain a static map for kind -> Resource
gvr := gv.WithResource(getResourceFromKind(gvk.Kind))
gvrs = append(gvrs, gvr)
}
return gvrs
}
func loadResource(t *testing.T, path string) []*unstructured.Unstructured {
var unstrResources []*unstructured.Unstructured
t.Logf("loading resource from %s", path)
data, err := loadFile(t, path)
if err != nil {
return nil
}
rBytes := bytes.Split(data, []byte("---"))
for _, r := range rBytes {
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, _, err := decode(r, nil, nil)
if err != nil {
t.Logf("failed to decode resource: %v", err)
continue
}
data, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&obj)
if err != nil {
t.Logf("failed to unmarshall resource. %v", err)
continue
}
unstr := unstructured.Unstructured{Object: data}
t.Logf("loaded resource %s/%s/%s", unstr.GetKind(), unstr.GetNamespace(), unstr.GetName())
unstrResources = append(unstrResources, &unstr)
}
return unstrResources
}
func loadObjects(t *testing.T, path string) []runtime.Object {
var resources []runtime.Object
t.Logf("loading objects from %s", path)
data, err := loadFile(t, path)
if err != nil {
return nil
}
rBytes := bytes.Split(data, []byte("---"))
for _, r := range rBytes {
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, gvk, err := decode(r, nil, nil)
if err != nil {
t.Logf("failed to decode resource: %v", err)
continue
}
t.Log(gvk)
//TODO: add more details
t.Logf("loaded object %s", gvk.Kind)
resources = append(resources, obj)
}
return resources
}
func loadPolicy(t *testing.T, path string) *kyverno.ClusterPolicy {
t.Logf("loading policy from %s", path)
data, err := loadFile(t, path)
if err != nil {
return nil
}
var policies []*kyverno.ClusterPolicy
pBytes := bytes.Split(data, []byte("---"))
for _, p := range pBytes {
policy := kyverno.ClusterPolicy{}
pBytes, err := apiyaml.ToJSON(p)
if err != nil {
t.Error(err)
continue
}
if err := json.Unmarshal(pBytes, &policy); err != nil {
t.Logf("failed to marshall polic. %v", err)
continue
}
t.Logf("loaded policy %s", policy.Name)
policies = append(policies, &policy)
}
if len(policies) == 0 {
t.Log("no policies loaded")
return nil
}
if len(policies) > 1 {
t.Log("more than one policy defined, considering first for processing")
}
return policies[0]
}
func testScenario(t *testing.T, path string) {
// flag.Set("logtostderr", "true")
// flag.Set("v", "8")
scenario, err := loadScenario(t, path)
if err != nil {
t.Error(err)
return
}
runScenario(t, scenario)
}