|
| 1 | +package webhooks |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "slices" |
| 8 | + |
| 9 | + "github.com/minio/pkg/wildcard" |
| 10 | + "go.uber.org/multierr" |
| 11 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 12 | + "k8s.io/apimachinery/pkg/util/sets" |
| 13 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 14 | + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" |
| 15 | + |
| 16 | + "github.com/appuio/appuio-cloud-agent/skipper" |
| 17 | +) |
| 18 | + |
| 19 | +// +kubebuilder:webhook:path=/validate-namespace-metadata,name=validate-namespace-metadata.appuio.io,admissionReviewVersions=v1,sideEffects=none,mutating=false,failurePolicy=Fail,groups="",resources=namespaces,verbs=create;update,versions=v1,matchPolicy=equivalent |
| 20 | +// +kubebuilder:webhook:path=/validate-namespace-metadata,name=validate-namespace-metadata-projectrequests.appuio.io,admissionReviewVersions=v1,sideEffects=none,mutating=false,failurePolicy=Fail,groups=project.openshift.io,resources=projectrequests,verbs=create;update,versions=v1,matchPolicy=equivalent |
| 21 | + |
| 22 | +// NamespaceMetadataValidator validates the metadata of a namespace. |
| 23 | +type NamespaceMetadataValidator struct { |
| 24 | + Decoder admission.Decoder |
| 25 | + |
| 26 | + Skipper skipper.Skipper |
| 27 | + |
| 28 | + // ReservedNamespace is a list of namespaces that are reserved and do not count towards the quota. |
| 29 | + // Supports '*' and '?' wildcards. |
| 30 | + ReservedNamespaces []string |
| 31 | + // AllowedAnnotations is a list of annotations that are allowed on the namespace. |
| 32 | + // Supports '*' and '?' wildcards. |
| 33 | + AllowedAnnotations []string |
| 34 | + // AllowedLabels is a list of labels that are allowed on the namespace. |
| 35 | + // Supports '*' and '?' wildcards. |
| 36 | + AllowedLabels []string |
| 37 | +} |
| 38 | + |
| 39 | +// Handle handles the admission requests |
| 40 | +func (v *NamespaceMetadataValidator) Handle(ctx context.Context, req admission.Request) admission.Response { |
| 41 | + ctx = log.IntoContext(ctx, log.FromContext(ctx). |
| 42 | + WithName("webhook.validate-namespace-metadata.appuio.io"). |
| 43 | + WithValues("id", req.UID, "user", req.UserInfo.Username). |
| 44 | + WithValues("namespace", req.Namespace, "name", req.Name, |
| 45 | + "group", req.Kind.Group, "version", req.Kind.Version, "kind", req.Kind.Kind)) |
| 46 | + |
| 47 | + return logAdmissionResponse(ctx, v.handle(ctx, req)) |
| 48 | +} |
| 49 | + |
| 50 | +func (v *NamespaceMetadataValidator) handle(ctx context.Context, req admission.Request) admission.Response { |
| 51 | + skip, err := v.Skipper.Skip(ctx, req) |
| 52 | + if err != nil { |
| 53 | + return admission.Errored(http.StatusInternalServerError, err) |
| 54 | + } |
| 55 | + if skip { |
| 56 | + return admission.Allowed("skipped") |
| 57 | + } |
| 58 | + |
| 59 | + for _, ns := range v.ReservedNamespaces { |
| 60 | + if wildcard.Match(ns, req.Name) { |
| 61 | + return admission.Denied("Changing or creating reserved namespaces is not allowed.") |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + var oldObj unstructured.Unstructured |
| 66 | + if len(req.OldObject.Raw) > 0 { |
| 67 | + if err := v.Decoder.DecodeRaw(req.OldObject, &oldObj); err != nil { |
| 68 | + return admission.Errored(http.StatusBadRequest, fmt.Errorf("failed to decode old object: %w", err)) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + var newObj unstructured.Unstructured |
| 73 | + if err := v.Decoder.Decode(req, &newObj); err != nil { |
| 74 | + return admission.Errored(http.StatusBadRequest, fmt.Errorf("failed to decode object from request: %w", err)) |
| 75 | + } |
| 76 | + |
| 77 | + if err := validateChangedMap(oldObj.GetAnnotations(), newObj.GetAnnotations(), v.AllowedAnnotations, "annotation"); err != nil { |
| 78 | + return admission.Denied(formatDeniedMessage(err, "annotations", v.AllowedAnnotations, newObj.GetAnnotations(), oldObj.GetAnnotations())) |
| 79 | + } |
| 80 | + if err := validateChangedMap(oldObj.GetLabels(), newObj.GetLabels(), v.AllowedLabels, "label"); err != nil { |
| 81 | + return admission.Denied(formatDeniedMessage(err, "labels", v.AllowedLabels, newObj.GetLabels(), oldObj.GetLabels())) |
| 82 | + } |
| 83 | + |
| 84 | + return admission.Allowed("allowed") |
| 85 | +} |
| 86 | + |
| 87 | +func formatDeniedMessage(err error, errMapRef string, allowed []string, newMap, oldMap map[string]string) string { |
| 88 | + msg := `The request was denied: |
| 89 | + %v |
| 90 | +The following %s can be modified: |
| 91 | + %s |
| 92 | +%s given: |
| 93 | + %s |
| 94 | +%s before modification: |
| 95 | + %s |
| 96 | +` |
| 97 | + |
| 98 | + return fmt.Sprintf(msg, err, errMapRef, allowed, errMapRef, newMap, errMapRef, oldMap) |
| 99 | +} |
| 100 | + |
| 101 | +func validateChangedMap(old, new map[string]string, allowedKeys []string, errObjectRef string) error { |
| 102 | + changed := changedKeys(old, new) |
| 103 | + errs := make([]error, 0, len(changed)) |
| 104 | + for _, k := range changed { |
| 105 | + allowed := slices.ContainsFunc(allowedKeys, func(a string) bool { return wildcard.Match(a, k) }) |
| 106 | + if !allowed { |
| 107 | + errs = append(errs, fmt.Errorf("%s %q is not allowed to be changed", errObjectRef, k)) |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + return multierr.Combine(errs...) |
| 112 | +} |
| 113 | + |
| 114 | +func changedKeys(a, b map[string]string) []string { |
| 115 | + changed := sets.New[string]() |
| 116 | + |
| 117 | + for k, v := range a { |
| 118 | + if bV, ok := b[k]; !ok || v != bV { |
| 119 | + changed.Insert(k) |
| 120 | + } |
| 121 | + } |
| 122 | + for k, v := range b { |
| 123 | + if aV, ok := a[k]; !ok || v != aV { |
| 124 | + changed.Insert(k) |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + return sets.List(changed) |
| 129 | +} |
0 commit comments