-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvalidate.go
99 lines (82 loc) · 2.52 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
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"encoding/json"
"fmt"
"strings"
mapset "github.com/deckarep/golang-set/v2"
"github.com/kubewarden/gjson"
kubewarden "github.com/kubewarden/policy-sdk-go"
kubewarden_protocol "github.com/kubewarden/policy-sdk-go/protocol"
)
func validate(payload []byte) ([]byte, error) {
// Create a ValidationRequest instance from the incoming payload
validationRequest := kubewarden_protocol.ValidationRequest{}
err := json.Unmarshal(payload, &validationRequest)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(err.Error()),
kubewarden.Code(400))
}
settings, err := NewSettingsFromValidationReq(validationRequest)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(err.Error()),
kubewarden.Code(400))
}
data := gjson.GetBytes(
payload,
"request.object.metadata.annotations")
annotations := mapset.NewThreadUnsafeSet[string]()
deniedAnnotationsViolations := []string{}
constrainedAnnotationsViolations := []string{}
data.ForEach(func(key, value gjson.Result) bool {
annotation := key.String()
annotations.Add(annotation)
if settings.DeniedAnnotations.Contains(annotation) {
deniedAnnotationsViolations = append(deniedAnnotationsViolations, annotation)
return true
}
regExp, found := settings.ConstrainedAnnotations[annotation]
if found {
// This is a constrained annotation
if !regExp.Match([]byte(value.String())) {
constrainedAnnotationsViolations = append(constrainedAnnotationsViolations, annotation)
return true
}
}
return true
})
errorMsgs := []string{}
if len(deniedAnnotationsViolations) > 0 {
errorMsgs = append(
errorMsgs,
fmt.Sprintf(
"The following annotations are not allowed: %s",
strings.Join(deniedAnnotationsViolations, ","),
))
}
if len(constrainedAnnotationsViolations) > 0 {
errorMsgs = append(
errorMsgs,
fmt.Sprintf(
"The following annotations are violating user constraints: %s",
strings.Join(constrainedAnnotationsViolations, ","),
))
}
mandatoryAnnotationsViolations := settings.MandatoryAnnotations.Difference(annotations)
if mandatoryAnnotationsViolations.Cardinality() > 0 {
violations := mandatoryAnnotationsViolations.ToSlice()
errorMsgs = append(
errorMsgs,
fmt.Sprintf(
"The following mandatory annotations are missing: %s",
strings.Join(violations, ","),
))
}
if len(errorMsgs) > 0 {
return kubewarden.RejectRequest(
kubewarden.Message(strings.Join(errorMsgs, ". ")),
kubewarden.NoCode)
}
return kubewarden.AcceptRequest()
}