-
Notifications
You must be signed in to change notification settings - Fork 10
/
webhook.go
212 lines (174 loc) · 6.46 KB
/
webhook.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package main
import (
"strings"
"fmt"
"net/http"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/api/admission/v1beta1"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
extv1beta1 "k8s.io/api/extensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
var webhookCmd = &cobra.Command {
Use: "webhook",
Short:"Starts admission validation webhook",
Long: "Starts admission validation webhook verifying incoming objects based on rules specified by flags",
Run: startWebhook,
}
var webhookViper = viper.New()
func init() {
rootCmd.AddCommand(webhookCmd)
webhookCmd.Flags().String("tls-cert-file", "",
"Path to the certificate file. Required, unless --no-tls is set.")
webhookCmd.Flags().Bool("no-tls", false,
"Do not use TLS.")
webhookCmd.Flags().String("tls-private-key-file", "",
"Path to the certificate key file. Required, unless --no-tls is set.")
webhookCmd.Flags().Int32("listen-port", 443,
"Port to listen on.")
initCommonFlags(webhookCmd)
if err := webhookViper.BindPFlags(webhookCmd.Flags()); err != nil {
errorWithUsage(err)
}
webhookViper.AutomaticEnv()
webhookViper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
}
func startWebhook(cmd *cobra.Command, args []string) {
config := &config{}
if err := webhookViper.Unmarshal(config); err != nil {
errorWithUsage(err)
}
if !config.NoTLS && (config.TLSPrivateKeyFile == "" || config.TLSCertFile == "") {
errorWithUsage(errors.New("Both --tls-cert-file and --tls-private-key-file are required (unless TLS is disabled by setting --no-tls)"))
}
log.Debugf("Configuration is: %+v", config)
//initialize kube client
kubeClientSet, kubeClientSetErr := KubeClientSet(true)
if kubeClientSetErr != nil {
log.Fatal(kubeClientSetErr)
}
http.HandleFunc("/validate", admitFunc(validate).serve(config, kubeClientSet))
addr := fmt.Sprintf(":%v", config.ListenPort)
var httpErr error
if config.NoTLS {
log.Infof("Starting webserver at %v (no TLS)", addr)
httpErr = http.ListenAndServe(addr, nil)
} else {
log.Infof("Starting webserver at %v (TLS)", addr)
httpErr = http.ListenAndServeTLS(addr, config.TLSCertFile, config.TLSPrivateKeyFile, nil)
}
if httpErr != nil {
log.Fatal(httpErr)
} else {
log.Info("Finished")
}
}
func validate(ar v1beta1.AdmissionReview, config *config, clientSet *kubernetes.Clientset) *v1beta1.AdmissionResponse {
validation := &objectValidation{ar.Request.Kind.Kind, nil, &validationViolationSet{}}
deserializer := codecs.UniversalDeserializer()
raw := ar.Request.Object.Raw
var configMessage string
switch ar.Request.Kind.Kind {
case "Pod":
configMessage = config.RuleResourceViolationMessage
pod := corev1.Pod{}
if _, _, err := deserializer.Decode(raw, nil, &pod); err != nil {
log.Error(err)
return toAdmissionResponse(err)
}
log.Debugf("Admitting Pod: %+v", pod)
validation.ObjMeta = &pod.ObjectMeta
validatePodSpec(validation, &pod.ObjectMeta, &pod.Spec, config)
case "ReplicaSet":
configMessage = config.RuleResourceViolationMessage
replicaSet := appsv1.ReplicaSet{}
if _, _, err := deserializer.Decode(raw, nil, &replicaSet); err != nil {
log.Error(err)
return toAdmissionResponse(err)
}
log.Debugf("Admitting ReplicaSet: %+v", replicaSet)
validation.ObjMeta = &replicaSet.ObjectMeta
validatePodSpec(validation, &replicaSet.Spec.Template.ObjectMeta, &replicaSet.Spec.Template.Spec, config)
case "Deployment":
configMessage = config.RuleResourceViolationMessage
deployment := appsv1.Deployment{}
if _, _, err := deserializer.Decode(raw, nil, &deployment); err != nil {
log.Error(err)
return toAdmissionResponse(err)
}
log.Debugf("Admitting deployment: %+v", deployment)
validation.ObjMeta = &deployment.ObjectMeta
validatePodSpec(validation, &deployment.Spec.Template.ObjectMeta, &deployment.Spec.Template.Spec, config)
case "DaemonSet":
configMessage = config.RuleResourceViolationMessage
daemonSet := appsv1.DaemonSet{}
if _, _, err := deserializer.Decode(raw, nil, &daemonSet); err != nil {
log.Error(err)
return toAdmissionResponse(err)
}
log.Debugf("Admitting DaemonSet: %+v", daemonSet)
validation.ObjMeta = &daemonSet.ObjectMeta
validatePodSpec(validation, &daemonSet.Spec.Template.ObjectMeta, &daemonSet.Spec.Template.Spec, config)
case "Job":
configMessage = config.RuleResourceViolationMessage
job := batchv1.Job{}
if _, _, err := deserializer.Decode(raw, nil, &job); err != nil {
log.Error(err)
return toAdmissionResponse(err)
}
log.Debugf("Admitting Job: %+v", job)
validation.ObjMeta = &job.ObjectMeta
validatePodSpec(validation, &job.Spec.Template.ObjectMeta, &job.Spec.Template.Spec, config)
case "CronJob":
configMessage = config.RuleResourceViolationMessage
cronJob := batchv1beta1.CronJob{}
if _, _, err := deserializer.Decode(raw, nil, &cronJob); err != nil {
log.Error(err)
return toAdmissionResponse(err)
}
log.Debugf("Admitting CronJob: %+v", cronJob)
validation.ObjMeta = &cronJob.ObjectMeta
validatePodSpec(validation, &cronJob.Spec.JobTemplate.Spec.Template.ObjectMeta, &cronJob.Spec.JobTemplate.Spec.Template.Spec, config)
case "Ingress":
configMessage = config.RuleIngressViolationMessage
ingress := extv1beta1.Ingress{}
if _, _, err := deserializer.Decode(raw, nil, &ingress); err != nil {
log.Error(err)
return toAdmissionResponse(err)
}
log.Debugf("Admitting Ingress: %+v", ingress)
validation.ObjMeta = &ingress.ObjectMeta
err := ValidateIngress(validation, &ingress, config, clientSet)
if err != nil {
return toAdmissionResponse(err)
}
case "StatefulSet":
configMessage = config.RuleResourceViolationMessage
statefulSet := appsv1.StatefulSet{}
if _, _, err := deserializer.Decode(raw, nil, &statefulSet); err != nil {
log.Error(err)
return toAdmissionResponse(err)
}
log.Debugf("Admitting stateful set: %+v", statefulSet)
validation.ObjMeta = &statefulSet.ObjectMeta
validatePodSpec(validation, &statefulSet.Spec.Template.ObjectMeta, &statefulSet.Spec.Template.Spec, config)
default:
log.Warnf("Admitted an unexpected resource: %v", ar.Request.Kind)
}
reviewResponse := v1beta1.AdmissionResponse{}
message := validation.message(configMessage)
if len(message) > 0 {
reviewResponse.Allowed = false
reviewResponse.Result = &metav1.Status{Message: message}
} else {
reviewResponse.Allowed = true
}
return &reviewResponse
}