generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathvalidator.go
418 lines (368 loc) · 15.3 KB
/
validator.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package objects
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"github.com/go-logr/logr"
k8sadm "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
api "sigs.k8s.io/hierarchical-namespaces/api/v1alpha2"
"sigs.k8s.io/hierarchical-namespaces/internal/config"
"sigs.k8s.io/hierarchical-namespaces/internal/forest"
"sigs.k8s.io/hierarchical-namespaces/internal/metadata"
"sigs.k8s.io/hierarchical-namespaces/internal/selectors"
"sigs.k8s.io/hierarchical-namespaces/internal/webhooks"
)
const (
// ServingPath is where the validator will run. Must be kept in sync
// with the kubebuilder markers below.
ServingPath = "/validate-objects"
)
type Validator struct {
Log logr.Logger
Forest *forest.Forest
client client.Client
decoder *admission.Decoder
}
type request struct {
obj *unstructured.Unstructured
oldObj *unstructured.Unstructured
op k8sadm.Operation
gvr metav1.GroupVersionResource
}
func (req request) gr() schema.GroupResource {
return schema.GroupResource{Group: req.gvr.Group, Resource: req.gvr.Resource}
}
func (req request) name() string {
name := types.NamespacedName{Namespace: req.obj.GetNamespace(), Name: req.obj.GetName()}
return name.String()
}
func (v *Validator) Handle(ctx context.Context, req admission.Request) admission.Response {
log := v.Log.WithValues("resource", req.Resource, "ns", req.Namespace, "nm", req.Name, "op", req.Operation, "user", req.UserInfo.Username)
// Before even looking at the objects, early-exit for any changes we shouldn't be involved in.
// This reduces the chance we'll hose some aspect of the cluster we weren't supposed to touch.
//
// Firstly, skip namespaces we're excluded from (like kube-system).
// Note: This is added just in case the "hnc.x-k8s.io/excluded-namespace=true"
// label is not added on the excluded namespaces. VWHConfiguration of this VWH
// already has a `namespaceSelector` to exclude namespaces with the label.
if !config.IsManagedNamespace(req.Namespace) {
return webhooks.Allow("unmanaged namespace " + req.Namespace)
}
// Allow changes to the types that are not in Propagate or AllowPropagate mode. This is to dynamically enable/disable
// object webhooks based on the types configured in hncconfig. Since the current admission rules only
// apply to propagated objects, we can disable object webhooks on all other non-propagate-mode types.
if !v.canPropagateType(req.Kind) {
return webhooks.Allow("Non-propagate-mode types")
}
// Finally, let the HNC SA do whatever it wants.
if webhooks.IsHNCServiceAccount(&req.AdmissionRequest.UserInfo) {
log.V(1).Info("Allowed change by HNC SA")
return webhooks.Allow("HNC SA")
}
decoded, err := v.decodeRequest(log, req)
if err != nil {
return webhooks.DenyBadRequest(err)
}
// Run the actual logic.
resp := v.handle(ctx, decoded)
if !resp.Allowed {
log.Info("Denied", "code", resp.Result.Code, "reason", resp.Result.Reason, "message", resp.Result.Message)
} else {
log.V(1).Info("Allowed", "message", resp.Result.Message)
}
return resp
}
func (v *Validator) syncType(gvk metav1.GroupVersionKind) api.SynchronizationMode {
ts := v.Forest.GetTypeSyncerFromGroupKind(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind})
if ts == nil {
return api.Ignore
}
return ts.GetMode()
}
func (v *Validator) isPropagateType(gvk metav1.GroupVersionKind) bool {
return v.syncType(gvk) == api.Propagate
}
func (v *Validator) isAllowPropagateType(gvk metav1.GroupVersionKind) bool {
return v.syncType(gvk) == api.AllowPropagate
}
func (v *Validator) canPropagateType(gvk metav1.GroupVersionKind) bool {
v.Forest.Lock()
defer v.Forest.Unlock()
return (v.isPropagateType(gvk) || v.isAllowPropagateType(gvk))
}
// handle implements the non-webhook-y businesss logic of this validator, allowing it to be more
// easily unit tested (ie without constructing an admission.Request, setting up user infos, etc).
func (v *Validator) handle(ctx context.Context, req *request) admission.Response {
inst := req.obj
oldInst := req.oldObj
// Find out if the object was/is inherited, and where it's inherited from.
oldSource, oldInherited := metadata.GetLabel(oldInst, api.LabelInheritedFrom)
newSource, newInherited := metadata.GetLabel(inst, api.LabelInheritedFrom)
// If the object wasn't and isn't inherited, we will check to see if the
// source can be created without causing any conflict.
if !oldInherited && !newInherited {
// check if there is any invalid HNC annotation
if msg := validateSelectorAnnot(inst); msg != "" {
return webhooks.DenyBadRequest(errors.New(msg))
}
// check selector format
// If this is a selector change, and the new selector is not valid, we'll deny this operation
if err := validateSelectorChange(inst, oldInst); err != nil {
return webhooks.DenyBadRequest(fmt.Errorf("invalid Kubernetes labelSelector: %w", err))
}
if err := validateTreeSelectorChange(inst, oldInst); err != nil {
return webhooks.DenyBadRequest(fmt.Errorf("invalid HNC %q value: %w", api.AnnotationTreeSelector, err))
}
if err := validateNoneSelectorChange(inst, oldInst); err != nil {
return webhooks.DenyBadRequest(err)
}
if err := validateAllSelectorChange(inst, oldInst); err != nil {
return webhooks.DenyBadRequest(err)
}
if msg := validateSelectorUniqueness(inst, oldInst); msg != "" {
return webhooks.DenyBadRequest(errors.New(msg))
}
if yes, dnses := v.hasConflict(inst); yes {
dnsesStr := strings.Join(dnses, ",")
err := fmt.Errorf("would overwrite objects in the following descendant namespace(s): %s. To fix this, choose a different name for the object, or remove the conflicting objects from the listed namespaces", dnsesStr)
return webhooks.DenyConflict(req.gr(), req.name(), err)
}
return webhooks.Allow("source object")
}
// This is a propagated object.
return v.handleInherited(ctx, req, newSource, oldSource)
}
func validateSelectorAnnot(inst *unstructured.Unstructured) string {
annots := inst.GetAnnotations()
for key := range annots {
// for example: segs = ["propagate.hnc.x-k8s.io", "select"]
segs := strings.SplitN(key, "/", 2)
// for example: prefix = ["propagate", "hnc.x-k8s.io"]
prefix := strings.SplitN(segs[0], ".", 2)
if len(prefix) < 2 || prefix[1] != api.MetaGroup {
continue
}
msg := "invalid HNC exceptions annotation: %v, should be one of the following: " +
api.AnnotationSelector +
"; " + api.AnnotationTreeSelector +
"; " + api.AnnotationNoneSelector +
"; " + api.AnnotationAllSelector
// If this annotation is part of HNC metagroup, we check if the prefix value is valid
if segs[0] != api.AnnotationPropagatePrefix {
return fmt.Sprintf(msg, key)
}
// check if the suffix is valid by checking the whole annotation key
if key != api.AnnotationSelector &&
key != api.AnnotationTreeSelector &&
key != api.AnnotationNoneSelector &&
key != api.AnnotationAllSelector {
return fmt.Sprintf(msg, key)
}
}
return ""
}
func validateSelectorUniqueness(inst, oldInst *unstructured.Unstructured) string {
sel := selectors.GetSelectorAnnotation(inst)
treeSel := selectors.GetTreeSelectorAnnotation(inst)
noneSel := selectors.GetNoneSelectorAnnotation(inst)
allSel := selectors.GetAllSelectorAnnotation(inst)
oldSel := selectors.GetSelectorAnnotation(oldInst)
oldTreeSel := selectors.GetTreeSelectorAnnotation(oldInst)
oldNoneSel := selectors.GetNoneSelectorAnnotation(oldInst)
oldAllSel := selectors.GetAllSelectorAnnotation(oldInst)
isSelectorChange := oldSel != sel || oldTreeSel != treeSel || oldNoneSel != noneSel || oldAllSel != allSel
if !isSelectorChange {
return ""
}
found := []string{}
if sel != "" {
found = append(found, api.AnnotationSelector)
}
if treeSel != "" {
found = append(found, api.AnnotationTreeSelector)
}
if noneSel != "" {
found = append(found, api.AnnotationNoneSelector)
}
if allSel != "" {
found = append(found, api.AnnotationAllSelector)
}
if len(found) <= 1 {
return ""
}
msg := "cannot have more than one selector at the same time, but got multiple: %v"
return fmt.Sprintf(msg, strings.Join(found, ", "))
}
func validateSelectorChange(inst, oldInst *unstructured.Unstructured) error {
oldSelectorStr := selectors.GetSelectorAnnotation(oldInst)
newSelectorStr := selectors.GetSelectorAnnotation(inst)
if newSelectorStr == "" || oldSelectorStr == newSelectorStr {
return nil
}
_, err := selectors.GetSelector(inst)
return err
}
func validateTreeSelectorChange(inst, oldInst *unstructured.Unstructured) error {
oldSelectorStr := selectors.GetTreeSelectorAnnotation(oldInst)
newSelectorStr := selectors.GetTreeSelectorAnnotation(inst)
if newSelectorStr == "" || oldSelectorStr == newSelectorStr {
return nil
}
_, err := selectors.GetTreeSelector(inst)
return err
}
func validateNoneSelectorChange(inst, oldInst *unstructured.Unstructured) error {
oldSelectorStr := selectors.GetNoneSelectorAnnotation(oldInst)
newSelectorStr := selectors.GetNoneSelectorAnnotation(inst)
if newSelectorStr == "" || oldSelectorStr == newSelectorStr {
return nil
}
_, err := selectors.GetNoneSelector(inst)
return err
}
func validateAllSelectorChange(inst, oldInst *unstructured.Unstructured) error {
oldSelectorStr := selectors.GetAllSelectorAnnotation(oldInst)
newSelectorStr := selectors.GetAllSelectorAnnotation(inst)
if newSelectorStr == "" || oldSelectorStr == newSelectorStr {
return nil
}
_, err := selectors.GetAllSelector(inst)
return err
}
func (v *Validator) handleInherited(ctx context.Context, req *request, newSource, oldSource string) admission.Response {
op := req.op
inst := req.obj
oldInst := req.oldObj
// Propagated objects cannot be created or deleted (except by the HNC SA, but the HNC SA
// never gets this far in the validation). They *can* have their statuses updated, so
// if this is an update, make sure that the canonical form of the object hasn't changed.
switch op {
case k8sadm.Create:
err := fmt.Errorf("cannot create objects with the label \"%s\"", api.LabelInheritedFrom)
return webhooks.DenyForbidden(req.gr(), req.name(), err)
case k8sadm.Delete:
// There are few things more irritating in (K8s) life than having some stupid controller stop
// your namespace from being deleted. If there's an object in here and we've decided that the
// namespace should be deleted, then don't block anything!
isDeleting, err := v.isDeletingNS(ctx, oldInst.GetNamespace())
if err != nil {
return webhooks.DenyInternalError(fmt.Errorf("cannot delete object propagated from namespace %s with error: %w", oldSource, err))
}
if !isDeleting {
err := fmt.Errorf("cannot delete object propagated from namespace \"%s\"", oldSource)
return webhooks.DenyForbidden(req.gr(), req.name(), err)
}
return webhooks.Allow("allowing deletion of propagated object since namespace is being deleted")
case k8sadm.Update:
// If the values have changed, that's an illegal modification. This includes if the label is
// added or deleted. Note that this label is *not* included in canonical(), below, so we
// need to check it manually.
if newSource != oldSource {
err := fmt.Errorf("cannot modify the label \"%s\"", api.LabelInheritedFrom)
return webhooks.DenyForbidden(req.gr(), req.name(), err)
}
// If the existing object has an inheritedFrom label, it's a propagated object. Any user changes
// should be rejected. Note that canonical does *not* compare any HNC labels or
// annotations.
if !reflect.DeepEqual(canonical(inst), canonical(oldInst)) {
err := fmt.Errorf("cannot modify object propagated from namespace \"%s\"", oldSource)
return webhooks.DenyForbidden(req.gr(), req.name(), err)
}
// Check for all the labels and annotations (including HNC and non HNC)
if !reflect.DeepEqual(oldInst.GetLabels(), inst.GetLabels()) || !reflect.DeepEqual(oldInst.GetAnnotations(), inst.GetAnnotations()) {
err := fmt.Errorf("cannot modify object propagated from namespace \"%s\"", oldSource)
return webhooks.DenyForbidden(req.gr(), req.name(), err)
}
return webhooks.Allow("no illegal updates to propagated object")
}
// If you get here, it means the webhook config is misconfigured to include an operation that we
// actually don't support.
return webhooks.DenyInternalError(fmt.Errorf("unknown operation: %s", op))
}
// validateDeletingNS validates if the namespace of the object is already being deleted
func (v *Validator) isDeletingNS(ctx context.Context, ns string) (bool, error) {
nsObj := &corev1.Namespace{}
nnm := types.NamespacedName{Name: ns}
if err := v.client.Get(ctx, nnm, nsObj); err != nil {
// `IsNotFound` should never happen, but if for some bizarre reason the namespace appears to be deleted before the object,
// we should allow the object to be deleted too.
if apierrors.IsNotFound(err) {
return true, nil
}
return false, fmt.Errorf("while determining whether namespace %q is being deleted: %w", ns, err)
}
if !nsObj.DeletionTimestamp.IsZero() {
return true, nil
}
return false, nil
}
// hasConflict checks if there's any conflicting objects in the descendants. Returns
// true and a list of conflicting descendants, if yes.
func (v *Validator) hasConflict(inst *unstructured.Unstructured) (bool, []string) {
v.Forest.Lock()
defer v.Forest.Unlock()
// If the instance is empty (for a delete operation) or it's not namespace-scoped,
// there must be no conflict.
if inst == nil || inst.GetNamespace() == "" {
return false, nil
}
nm := inst.GetName()
gvk := inst.GroupVersionKind()
descs := v.Forest.Get(inst.GetNamespace()).DescendantNames()
conflicts := []string{}
// Get a list of conflicting descendants if there's any.
for _, desc := range descs {
if v.Forest.Get(desc).HasSourceObject(gvk, nm) {
// If the user have chosen not to propagate the object to this descendant,
// there shouldn't be any conflict reported here
nsLabels := v.Forest.Get(inst.GetNamespace()).GetLabels()
mode := v.syncType(metav1.GroupVersionKind(gvk))
if ok, _ := selectors.ShouldPropagate(inst, nsLabels, mode); ok {
conflicts = append(conflicts, desc)
}
}
}
return len(conflicts) != 0, conflicts
}
func (v *Validator) decodeRequest(log logr.Logger, req admission.Request) (*request, error) {
// Decode the old and new object, if we expect them to exist ("old" won't exist for creations,
// while "new" won't exist for deletions).
inst := &unstructured.Unstructured{}
oldInst := &unstructured.Unstructured{}
if req.Operation != k8sadm.Delete {
if err := v.decoder.Decode(req, inst); err != nil {
log.Error(err, "Couldn't decode req.Object", "raw", req.Object)
return nil, fmt.Errorf("while decoding object: %w", err)
}
}
if req.Operation != k8sadm.Create {
if err := v.decoder.DecodeRaw(req.OldObject, oldInst); err != nil {
log.Error(err, "Couldn't decode req.OldObject", "raw", req.OldObject)
return nil, fmt.Errorf("while decoding old object: %w", err)
}
}
return &request{
obj: inst,
oldObj: oldInst,
op: req.Operation,
gvr: req.Resource,
}, nil
}
func (v *Validator) InjectClient(c client.Client) error {
v.client = c
return nil
}
func (v *Validator) InjectDecoder(d *admission.Decoder) error {
v.decoder = d
return nil
}