-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathvalidate.go
65 lines (54 loc) · 1.94 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
package main
import (
"encoding/json"
"fmt"
"strings"
onelog "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"
)
const httpBadRequestStatusCode = 400
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(httpBadRequestStatusCode))
}
// Create a Settings instance from the ValidationRequest object
settings, err := NewSettingsFromValidationReq(&validationRequest)
if err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(err.Error()),
kubewarden.Code(httpBadRequestStatusCode))
}
// Access the **raw** JSON that describes the object
podJSON := validationRequest.Request.Object
// Try to create a Pod instance using the RAW JSON we got from the
// ValidationRequest.
pod := &corev1.Pod{}
if err = json.Unmarshal([]byte(podJSON), pod); err != nil {
return kubewarden.RejectRequest(
kubewarden.Message(
fmt.Sprintf("Cannot decode Pod object: %s", err.Error())),
kubewarden.Code(httpBadRequestStatusCode))
}
logger.DebugWithFields("validating pod object", func(e onelog.Entry) {
e.String("name", pod.Metadata.Name)
e.String("namespace", pod.Metadata.Namespace)
})
if settings.IsNameDenied(pod.Metadata.Name) {
logger.InfoWithFields("rejecting pod object", func(e onelog.Entry) {
e.String("name", pod.Metadata.Name)
e.String("denied_names", strings.Join(settings.DeniedNames, ","))
})
return kubewarden.RejectRequest(
kubewarden.Message(
fmt.Sprintf("The '%s' name is on the deny list", pod.Metadata.Name)),
kubewarden.NoCode)
}
return kubewarden.AcceptRequest()
}