|
| 1 | +// Copyright 2020-2021 Clastix Labs |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package tenant |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "strings" |
| 10 | + |
| 11 | + rbacv1 "k8s.io/api/rbac/v1" |
| 12 | + "k8s.io/apimachinery/pkg/util/validation" |
| 13 | + "k8s.io/client-go/tools/record" |
| 14 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 15 | + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" |
| 16 | + |
| 17 | + capsulev1beta1 "github.com/clastix/capsule/api/v1beta1" |
| 18 | + capsulewebhook "github.com/clastix/capsule/pkg/webhook" |
| 19 | + "github.com/clastix/capsule/pkg/webhook/utils" |
| 20 | +) |
| 21 | + |
| 22 | +type rbRegexHandler struct { |
| 23 | +} |
| 24 | + |
| 25 | +func RoleBindingRegexHandler() capsulewebhook.Handler { |
| 26 | + return &rbRegexHandler{} |
| 27 | +} |
| 28 | + |
| 29 | +func (h *rbRegexHandler) validate(req admission.Request, decoder *admission.Decoder) *admission.Response { |
| 30 | + tenant := &capsulev1beta1.Tenant{} |
| 31 | + if err := decoder.Decode(req, tenant); err != nil { |
| 32 | + return utils.ErroredResponse(err) |
| 33 | + } |
| 34 | + |
| 35 | + if len(tenant.Spec.AdditionalRoleBindings) > 0 { |
| 36 | + for _, binding := range tenant.Spec.AdditionalRoleBindings { |
| 37 | + for _, subject := range binding.Subjects { |
| 38 | + if subject.Kind == rbacv1.ServiceAccountKind { |
| 39 | + err := validation.IsDNS1123Subdomain(subject.Name) |
| 40 | + if len(err) > 0 { |
| 41 | + response := admission.Denied(fmt.Sprintf("Subject Name '%v' for binding '%v' is invalid. %v", subject.Name, binding.ClusterRoleName, strings.Join(err, ", "))) |
| 42 | + return &response |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + return nil |
| 49 | +} |
| 50 | +func (h *rbRegexHandler) OnCreate(_ client.Client, decoder *admission.Decoder, _ record.EventRecorder) capsulewebhook.Func { |
| 51 | + return func(_ context.Context, req admission.Request) *admission.Response { |
| 52 | + return h.validate(req, decoder) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +func (h *rbRegexHandler) OnDelete(client.Client, *admission.Decoder, record.EventRecorder) capsulewebhook.Func { |
| 57 | + return func(context.Context, admission.Request) *admission.Response { |
| 58 | + return nil |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func (h *rbRegexHandler) OnUpdate(_ client.Client, decoder *admission.Decoder, _ record.EventRecorder) capsulewebhook.Func { |
| 63 | + return func(_ context.Context, req admission.Request) *admission.Response { |
| 64 | + return h.validate(req, decoder) |
| 65 | + } |
| 66 | +} |
0 commit comments