generated from kubewarden/go-policy-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
78 lines (66 loc) · 2.14 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
package main
import (
"fmt"
"github.com/francoispqt/onelog"
corev1 "github.com/kubewarden/k8s-objects/api/core/v1"
kubewarden "github.com/kubewarden/policy-sdk-go"
kubewarden_protocol "github.com/kubewarden/policy-sdk-go/protocol"
"github.com/mailru/easyjson"
)
func validate(payload []byte) ([]byte, error) {
validationRequest := kubewarden_protocol.ValidationRequest{}
err := easyjson.Unmarshal(payload, &validationRequest)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(
fmt.Sprintf("unmarshaling validation request: %s", err.Error())),
kubewarden.Code(400))
}
settings, err := NewSettingsFromValidationReq(&validationRequest)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(
fmt.Sprintf("unmarshaling policy settings: %s", err.Error())),
kubewarden.Code(400))
}
var pod corev1.Pod
if err = easyjson.Unmarshal(validationRequest.Request.Object, &pod); err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(
fmt.Sprintf("unmarshaling Pod object: %s", err.Error())),
kubewarden.Code(400))
}
logger.DebugWithFields("validating pod object", func(e onelog.Entry) {
e.String("name", pod.Metadata.Name)
e.String("namespace", pod.Metadata.Namespace)
})
for label, value := range pod.Metadata.Labels {
if err := validateLabel(label, value, &settings); err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(err.Error()),
kubewarden.NoCode)
}
}
for requiredLabel := range settings.ConstrainedLabels {
_, found := pod.Metadata.Labels[requiredLabel]
if !found {
return kubewarden.RejectRequest(
kubewarden.Message(fmt.Sprintf(
"constrained label %q not found inside of Pod",
requiredLabel),
),
kubewarden.NoCode)
}
}
return kubewarden.AcceptRequest()
}
func validateLabel(label, value string, settings *Settings) error {
if settings.DeniedLabels.Contains(label) {
return fmt.Errorf("label %q is on the deny list", label)
}
regExp, found := settings.ConstrainedLabels[label]
if found && !regExp.Match([]byte(value)) {
return fmt.Errorf("label %q does not pass user-defined constraint", label)
}
return nil
}