generated from kubewarden/go-policy-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
validate.go
88 lines (76 loc) · 2.25 KB
/
validate.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
package main
import (
"errors"
"fmt"
onelog "github.com/francoispqt/onelog"
"github.com/kubewarden/gjson"
kubewarden "github.com/kubewarden/policy-sdk-go"
)
func validate(payload []byte) ([]byte, error) {
settings, err := NewSettingsFromValidationReq(payload)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(err.Error()),
kubewarden.Code(400))
}
if settings.AllowedTypes.Cardinality() == 0 {
// empty AllowedType list, rejecting
return kubewarden.RejectRequest(
kubewarden.Message("No volume type is allowed"),
kubewarden.NoCode)
}
if (settings.AllowedTypes.Cardinality() == 1) &&
settings.AllowedTypes.Contains("*") {
// all volume types accepted
return kubewarden.AcceptRequest()
}
volumes := gjson.GetBytes(
payload,
"request.object.spec.volumes")
if !volumes.Exists() {
// pod defines no volumes, accepting
return kubewarden.AcceptRequest()
}
logger.DebugWithFields("validating pod object", func(e onelog.Entry) {
name := gjson.GetBytes(payload, "request.object.metadata.name").String()
namespace := gjson.GetBytes(payload,
"request.object.metadata.namespace").String()
e.String("name", name)
e.String("namespace", namespace)
})
for _, volume := range volumes.Array() {
// obtain volumeName, volumeType:
var volumeName, volumeType string
volume.ForEach(func(key, value gjson.Result) bool {
if key.String() == "name" {
volumeName = value.String()
} else {
// must be the type
volumeType = key.String()
}
return true // keep iterating
})
if !settings.AllowedTypes.Contains(volumeType) {
errMsg := fmt.Sprintf("volume '%s' of type '%s' is not in the AllowedTypes list",
volumeName, volumeType)
if err == nil {
err = errors.New(errMsg)
} else {
err = fmt.Errorf("%w; %s", err, errMsg)
}
}
}
if err != nil {
logger.DebugWithFields("rejecting pod object", func(e onelog.Entry) {
name := gjson.GetBytes(payload, "request.object.metadata.name").String()
namespace := gjson.
GetBytes(payload, "request.object.metadata.namespace").String()
e.String("name", name)
e.String("namespace", namespace)
})
return kubewarden.RejectRequest(
kubewarden.Message(err.Error()),
kubewarden.NoCode)
}
return kubewarden.AcceptRequest()
}