-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
76 lines (64 loc) · 2.32 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
package main
import (
"encoding/json"
"fmt"
mapset "github.com/deckarep/golang-set/v2"
corev1 "github.com/kubewarden/k8s-objects/api/core/v1"
kubewarden "github.com/kubewarden/policy-sdk-go"
kubewardenProtocol "github.com/kubewarden/policy-sdk-go/protocol"
)
const httpBadRequestStatusCode = 400
func validate(input []byte) ([]byte, error) {
validationRequest := kubewardenProtocol.ValidationRequest{}
err := json.Unmarshal(input, &validationRequest)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(fmt.Sprintf("Error deserializing validation request: %v", err)),
kubewarden.Code(httpBadRequestStatusCode))
}
settings, err := NewSettingsFromValidationReq(&validationRequest)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(fmt.Sprintf("Error serializing RawMessage: %v", err)),
kubewarden.Code(httpBadRequestStatusCode))
}
return validateAdmissionReview(settings, validationRequest.Request)
}
func validateAdmissionReview(policySettings Settings, request kubewardenProtocol.KubernetesAdmissionRequest) ([]byte, error) {
pod := corev1.Pod{}
err := json.Unmarshal(request.Object, &pod)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(fmt.Sprintf("Error deserializing request object into unstructured: %v", err)),
kubewarden.Code(httpBadRequestStatusCode))
}
annotations := pod.Metadata.Annotations
if annotations == nil {
annotations = make(map[string]string)
}
// check if one of the annotations is forbidden
annotationsSet := mapset.NewSet[string]()
for key := range annotations {
annotationsSet.Add(key)
}
forbiddenAnnotations := annotationsSet.Intersect(policySettings.ForbiddenAnnotations)
if forbiddenAnnotations.Cardinality() > 0 {
return kubewarden.RejectRequest(
kubewarden.Message("The following annotations are forbidden: "+forbiddenAnnotations.String()),
kubewarden.Code(httpBadRequestStatusCode))
}
// eventually mutate the current annotations
annotationsChanged := false
for key, value := range policySettings.RequiredAnnotations {
currentValue, hasKey := annotations[key]
if !hasKey || currentValue != value {
annotations[key] = value
annotationsChanged = true
}
}
if annotationsChanged {
pod.Metadata.Annotations = annotations
return kubewarden.MutateRequest(&pod)
}
return kubewarden.AcceptRequest()
}