Day 8: Validation – Markers, CEL and Webhooks
Goal: Invalid StaticSites never make it into the cluster: OpenAPI markers and CEL rules in the API server, plus a defaulting and a validating webhook for everything CEL cannot do – tested in envtest · Duration: approx. 150 min · Prerequisite: Day 7
Briefing
- The earlier something is rejected, the better: an error on
kubectl applyis cheaper than aDegradedin the status. - OpenAPI markers (min/max/length/default) and
CEL (
x-kubernetes-validations) run in the API server – no code, no certificates, no outage risk. - Transition rules (
oldSelf) compare old and new: immutable fields, values that may only grow. - Webhooks only for what CEL cannot do: reading neighboring objects, policy from the operator configuration, normalizing.
kubectl apply
-> Mutating Webhook (default: normalize path)
-> Schema + Defaults + CEL (types, 1..10, exactly one, immutable)
-> Validating Webhook (registry policy, warning on missing ConfigMap)
-> etcd
Drill 1: What the markers already do
source ~/op-lab/env.sh
cp -r ~/op-lab/tag07-site-operator ~/op-lab/tag08-site-operator
cd ~/op-lab/tag08-site-operatorTerminal 1: Start the control plane with today’s CRD state (it runs until the end of the day):
source ~/op-lab/env.sh
cd ~/op-lab/tag08-site-operator && envtest-up --crds config/crd/basesTerminal 2: A StaticSite with three errors at once:
cat > lab/kaputt.yaml <<'EOF'
apiVersion: web.lab.example/v1alpha1
kind: StaticSite
metadata:
name: kaputt
spec:
content: "<h1>Hallo</h1>"
contentFrom:
configMapRef:
name: html
replicas: 11
image: nginx:latest
EOF
kubectl apply -f lab/kaputt.yamlExpected (wrapped):
The StaticSite "kaputt" is invalid: spec.replicas: Invalid value: 11:
spec.replicas in body should be less than or equal to 10
Only replicas gets caught. The schema lets it through
that both content and
contentFrom are set and that :latest sneaks in
– you fix that now.
Save your progress? Sign up for free
Drill 2: CEL – exactly one, no latest
Two markers in api/v1alpha1/staticsite_types.go.
ExactlyOneOf (controller-tools v0.18 and later) goes on the
type, the custom CEL rule on the
field:
// StaticSiteSpec ist der Wunschzustand einer StaticSite.
// +kubebuilder:validation:ExactlyOneOf=content;contentFrom
type StaticSiteSpec struct {
// ...
// image ist das Webserver-Image.
// +kubebuilder:default="nginxinc/nginx-unprivileged:1.31-alpine"
// +kubebuilder:validation:XValidation:rule="!self.endsWith(':latest')"
// +optional
Image string `json:"image,omitempty"`Warning: Marker lines cannot be wrapped. A
message="…"is optional – without it, the API server reportsfailed rule: <rule>. For short rules that is perfectly enough.
Regenerate the CRD and look at the generated rule:
make manifests
grep -A3 'x-kubernetes-validations' \
config/crd/bases/web.lab.example_staticsites.yamlExpected (shortened):
x-kubernetes-validations:
- rule: '!self.endsWith('':latest'')'
--
x-kubernetes-validations:
- message: exactly one of the fields in [content contentFrom] must be
set
rule: (has(self.content)?1:0)+(has(self.contentFrom)?1:0) == 1
The running control plane gets the new CRD without a restart, then the same attempt:
kubectl replace -f config/crd/bases/
kubectl apply -f lab/kaputt.yamlExpected (wrapped):
customresourcedefinition.apiextensions.k8s.io/staticsites.web.lab.example replaced
The StaticSite "kaputt" is invalid:
* spec.replicas: Invalid value: 11:
spec.replicas in body should be less than or equal to 10
* spec: Invalid value: exactly one of the fields in [content contentFrom] must be set
* spec.image: Invalid value: "nginx:latest": failed rule: !self.endsWith(':latest')
Why has()? For optional fields, “not set” means “not
present” in CEL. Accessing a missing field would be a runtime error of
the rule.
Save your progress? Sign up for free
Drill 3: Transition rule – path stays as it is
The path determines the mount directory in the pod (Day 4). If someone changes it while the site is running, old links lead nowhere – so make it immutable:
// path ist der URL-Pfad, unter dem die Seite ausgeliefert wird.
// +kubebuilder:default="/"
// +kubebuilder:validation:XValidation:rule="self == oldSelf"
// +optional
Path string `json:"path,omitempty"`oldSelf only exists on updates – on create the rule is
skipped. Try it:
make manifests && kubectl replace -f config/crd/bases/
kubectl apply -f - <<'EOF'
apiVersion: web.lab.example/v1alpha1
kind: StaticSite
metadata:
name: demo
spec:
content: "<h1>Hallo</h1>"
path: /docs/
EOF
kubectl patch staticsite demo --type merge -p '{"spec":{"path":"/neu/"}}'
kubectl patch staticsite demo --type merge -p '{"spec":{"replicas":3}}'Expected (wrapped):
staticsite.web.lab.example/demo created
The StaticSite "demo" is invalid: spec.path: Invalid value: "/neu/":
failed rule: self == oldSelf
staticsite.web.lab.example/demo patched
Save your progress? Sign up for free
Drill 4: Pinning down CEL rules in envtest
The rules run in envtest’s real kube-apiserver – so they
belong in the controller suite. newStaticSite,
newNamespace and siteMutator come from Day
6.
cat > internal/controller/cel_test.go <<'EOF'
package controller
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"sigs.k8s.io/controller-runtime/pkg/client"
webv1alpha1 "example.com/site-operator/api/v1alpha1"
)
var _ = DescribeTable("CEL-Regeln im API-Server",
func(ctx SpecContext, mutate siteMutator, msg string) {
site := newStaticSite(newNamespace(ctx), "cel", mutate)
Expect(k8sClient.Create(ctx, site)).To(MatchError(ContainSubstring(msg)))
},
Entry("content und contentFrom", func(s *webv1alpha1.StaticSite) {
s.Spec.ContentFrom = &webv1alpha1.ContentSource{
ConfigMapRef: &webv1alpha1.ConfigMapReference{Name: "html"}}
}, "exactly one of the fields"),
Entry("weder noch", func(s *webv1alpha1.StaticSite) { s.Spec.Content = "" },
"exactly one of the fields"),
Entry(":latest", func(s *webv1alpha1.StaticSite) { s.Spec.Image = "nginx:latest" },
"failed rule: !self.endsWith(':latest')"),
)
var _ = It("verbietet, path nachträglich zu ändern", func(ctx SpecContext) {
site := newStaticSite(newNamespace(ctx), "pfad")
Expect(k8sClient.Create(ctx, site)).To(Succeed())
patch := client.MergeFrom(site.DeepCopy()) // Patch statt Update: kein Konflikt
site.Spec.Path = "/neu/"
Expect(k8sClient.Patch(ctx, site, patch)).
To(MatchError(ContainSubstring("failed rule: self == oldSelf")))
})
EOF
go test ./internal/controller/ -count=1 -v -ginkgo.no-color -ginkgo.focus='CEL|path' \
2>&1 | grep -E '^(Ran|SUCCESS|FAIL|ok)'Expected:
Ran 4 of 21 Specs in 5.163 seconds
SUCCESS! -- 4 Passed | 0 Failed | 0 Pending | 17 Skipped
ok example.com/site-operator/internal/controller 5.601s
Why Patch instead of Update? Your
controller writes the finalizer and status in parallel. An
Update with an outdated resourceVersion then
fails with Conflict – and the test would check the wrong
error.
Save your progress? Sign up for free
Drill 5: Generating webhooks, writing the defaulter
kubebuilder create webhook --group web --version v1alpha1 --kind StaticSite \
--defaulting --programmatic-validation
ls internal/webhook/v1alpha1/Expected:
staticsite_webhook.go staticsite_webhook_test.go webhook_suite_test.go
Kubebuilder has also extended cmd/main.go (the
ENABLE_WEBHOOKS block), created
config/webhook/ and updated PROJECT. The two
+kubebuilder:webhook markers in
staticsite_webhook.go are over 250 characters long – you
save them into a file of their own and rewrite the rest:
cd internal/webhook/v1alpha1
{ echo '// Marker für controller-gen: erzeugen config/webhook/manifests.yaml.'
echo 'package v1alpha1'; echo
grep '+kubebuilder:webhook:' staticsite_webhook.go; } > markers.go
cd ~/op-lab/tag08-site-operatorThe defaulter normalizes spec.path: docs,
/docs or docs/ becomes /docs/. A
schema default cannot do that; it only sets missing values. The
validator follows in Drill 6, but here is the whole file already:
cat > internal/webhook/v1alpha1/staticsite_webhook.go <<'EOF'
package v1alpha1
import (
"context"
"fmt"
"strings"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
webv1alpha1 "example.com/site-operator/api/v1alpha1"
)
// AllowedImagePrefixes is the registry policy of the lab cluster.
var AllowedImagePrefixes = []string{"nginxinc/", "registry.lab.example/"}
var siteGK = webv1alpha1.GroupVersion.WithKind("StaticSite").GroupKind()
// SetupStaticSiteWebhookWithManager registers the defaulter and validator.
func SetupStaticSiteWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr, &webv1alpha1.StaticSite{}).
WithDefaulter(&StaticSiteDefaulter{}).
WithValidator(&StaticSiteValidator{Reader: mgr.GetAPIReader()}).
Complete()
}
// StaticSiteDefaulter normalizes spec.path.
// +kubebuilder:object:generate=false
type StaticSiteDefaulter struct{}
// Default turns "docs" or "/docs" into the path "/docs/".
func (d *StaticSiteDefaulter) Default(_ context.Context,
site *webv1alpha1.StaticSite) error {
p := strings.Trim(site.Spec.Path, "/")
if p == "" {
site.Spec.Path = "/"
return nil
}
site.Spec.Path = "/" + p + "/"
return nil
}
// StaticSiteValidator checks what CEL cannot: policy and neighboring objects.
// +kubebuilder:object:generate=false
type StaticSiteValidator struct {
Reader client.Reader // liest direkt vom API-Server, ohne Cache
}
func (v *StaticSiteValidator) ValidateCreate(ctx context.Context,
site *webv1alpha1.StaticSite) (admission.Warnings, error) {
return v.validate(ctx, site)
}
func (v *StaticSiteValidator) ValidateUpdate(ctx context.Context,
_, site *webv1alpha1.StaticSite) (admission.Warnings, error) {
return v.validate(ctx, site)
}
func (v *StaticSiteValidator) ValidateDelete(context.Context,
*webv1alpha1.StaticSite) (admission.Warnings, error) {
return nil, nil
}
// validate: enforce the registry policy strictly, only report a missing ConfigMap.
func (v *StaticSiteValidator) validate(ctx context.Context,
site *webv1alpha1.StaticSite) (admission.Warnings, error) {
if !allowedImage(site.Spec.Image) {
return nil, apierrors.NewInvalid(siteGK, site.Name, field.ErrorList{
field.Forbidden(field.NewPath("spec", "image"),
fmt.Sprintf("erlaubt sind nur %v", AllowedImagePrefixes)),
})
}
src := site.Spec.ContentFrom
if src == nil || src.ConfigMapRef == nil {
return nil, nil
}
key := client.ObjectKey{Namespace: site.Namespace, Name: src.ConfigMapRef.Name}
err := v.Reader.Get(ctx, key, &corev1.ConfigMap{})
if apierrors.IsNotFound(err) { // GitOps: Die ConfigMap kommt evtl. später
return admission.Warnings{"ConfigMap " + key.Name + " fehlt (noch)"}, nil
}
return nil, nil // andere Fehler blockieren nicht, der Controller meldet sie
}
func allowedImage(image string) bool {
for _, p := range AllowedImagePrefixes {
if strings.HasPrefix(image, p) {
return true
}
}
return false
}
EOF
make manifests && go build ./... && echo okExpected:
ok
In controller-runtime v0.25, the defaulter and validator are
generic: Default(ctx, *StaticSite) instead
of runtime.Object with a type assertion. The builder
ctrl.NewWebhookManagedBy(mgr, &StaticSite{}) wires up
path and type.
Save your progress? Sign up for free
Drill 6: The validator – what CEL cannot do
Two checks from validate above:
- Registry policy: images only from
AllowedImagePrefixes. The list is Go code (or a flag, see the challenge) – CEL in the CRD would be the same for every cluster. - Neighboring object: if
contentFrompoints to a missing ConfigMap, there is a warning, not an error. With GitOps, the ConfigMap often arrives seconds after the site.
Why mgr.GetAPIReader()? The normal client reads from the
cache and would start an informer on all ConfigMaps in
the cluster for this. The API reader asks directly, once – exactly right
for rare lookups in a webhook.
Warning: A webhook with
failurePolicy: Failis a hard dependency path: if your operator is not running, nobody can create or change StaticSites anymore (Drill 8). Keep the validator fast and free of external calls.
Save your progress? Sign up for free
Drill 7: Webhook tests in envtest
Kubebuilder has already written the suite
webhook_suite_test.go: it starts envtest with
WebhookInstallOptions – envtest creates a certificate,
starts the webhook server on a free port and registers the configuration
from config/webhook/ with that address in the API server.
You only replace the specs: a table for the defaulter (a plain Go call)
and three specs through the real API server.
cat > internal/webhook/v1alpha1/staticsite_webhook_test.go <<'EOF'
package v1alpha1
import (
"context"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
webv1alpha1 "example.com/site-operator/api/v1alpha1"
)
func site(name string) *webv1alpha1.StaticSite {
return &webv1alpha1.StaticSite{
ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"},
Spec: webv1alpha1.StaticSiteSpec{Content: "<h1>Hallo</h1>"},
}
}
var _ = Describe("Defaulter (Unit)", func() {
DescribeTable("normalisiert spec.path",
func(in, want string) {
s := site("x")
s.Spec.Path = in
Expect((&StaticSiteDefaulter{}).Default(ctx, s)).To(Succeed())
Expect(s.Spec.Path).To(Equal(want))
},
Entry("leer", "", "/"),
Entry("ohne Slashes", "docs", "/docs/"),
Entry("schon normal", "/docs/", "/docs/"),
Entry("verschachtelt", "a/b", "/a/b/"),
)
})
var _ = Describe("Webhooks im API-Server (envtest)", func() {
It("normalisiert den Pfad beim Anlegen", func() {
s := site("mutate")
s.Spec.Path = "docs"
Expect(k8sClient.Create(ctx, s)).To(Succeed())
Expect(s.Spec.Path).To(Equal("/docs/")) // Antwort enthält den Patch
})
It("lehnt fremde Registries ab", func() {
s := site("evil")
s.Spec.Image = "evil.example/nginx:1.0"
err := k8sClient.Create(ctx, s)
Expect(apierrors.IsInvalid(err)).To(BeTrue())
Expect(err.Error()).To(ContainSubstring("spec.image"))
})
It("warnt bei fehlender ConfigMap, lehnt aber nicht ab", func() {
var got warnings
cfgW := rest.CopyConfig(cfg)
cfgW.WarningHandlerWithContext = &got
c, err := client.New(cfgW, client.Options{Scheme: k8sClient.Scheme()})
Expect(err).NotTo(HaveOccurred())
s := site("later")
s.Spec.Content = ""
s.Spec.ContentFrom = &webv1alpha1.ContentSource{
ConfigMapRef: &webv1alpha1.ConfigMapReference{Name: "kommt-noch"}}
Expect(c.Create(ctx, s)).To(Succeed())
Expect(got).To(ContainElement(ContainSubstring("kommt-noch fehlt")))
})
})
// warnings collects the API server's warning headers.
type warnings []string
func (w *warnings) HandleWarningHeaderWithContext(_ context.Context, _ int,
_ string, text string) {
*w = append(*w, text)
}
EOF
go test ./internal/webhook/... -count=1 -v -ginkgo.no-color \
2>&1 | grep -E '^(Ran|SUCCESS|FAIL|ok)'Expected:
Ran 7 of 7 Specs in 5.800 seconds
SUCCESS! -- 7 Passed | 0 Failed | 0 Pending | 0 Skipped
ok example.com/site-operator/internal/webhook/v1alpha1 6.168s
Why a custom WarningHandler? Warnings come back as the
HTTP header Warning:. The standard client only logs them;
to check them, you collect them yourself.
Save your progress? Sign up for free
Drill 8: Webhooks live against envtest-up
envtest-up knows no webhooks – you register them by
hand. The API server must trust your webhook server via TLS, so: a
certificate for 127.0.0.1, the CA bundle in the
configuration, url instead of service.
mkdir -p lab/certs
openssl req -x509 -newkey rsa:2048 -nodes -days 30 \
-keyout lab/certs/tls.key -out lab/certs/tls.crt \
-subj /CN=127.0.0.1 -addext subjectAltName=IP:127.0.0.1 2>/dev/null
CA=$(base64 < lab/certs/tls.crt | tr -d '\n')
perl -0pe "s|service:\n\s+name: webhook-service\n\s+namespace: system\n\s+path: (\S+)\
|caBundle: $CA\n url: https://127.0.0.1:9443\$1|g" \
config/webhook/manifests.yaml > lab/webhooks-local.yaml
grep 'url:' lab/webhooks-local.yaml
kubectl apply -f lab/webhooks-local.yamlExpected (shortened):
url: https://127.0.0.1:9443/mutate-web-lab-example-v1alpha1-staticsite
url: https://127.0.0.1:9443/validate-web-lab-example-v1alpha1-staticsite
mutatingwebhookconfiguration.admissionregistration.k8s.io/mutating-webhook-... created
validatingwebhookconfiguration.admissionregistration.k8s.io/validating-webh... created
Security:
lab/certs/tls.keyis a lab key with a lifetime of one day. Do not check it in (echo 'lab/certs/' >> .gitignore); in the cluster, cert-manager takes care of this.
No operator is running yet. What happens now with
failurePolicy: Fail?
kubectl delete site demo --ignore-not-found
kubectl apply -f lab/demo.yamlExpected (wrapped):
Error from server (InternalError): error when creating "lab/demo.yaml": Internal error
occurred: failed calling webhook "mstaticsite-v1alpha1.kb.io": failed to call webhook:
Post "https://127.0.0.1:9443/mutate-web-lab-example-v1alpha1-staticsite?timeout=10s":
dial tcp 127.0.0.1:9443: connect: connection refused
Terminal 3: Start the operator with the certificate.
Without --webhook-cert-path it aborts
(open …/k8s-webhook-server/serving-certs/tls.crt: no such file or directory);
if you do not need webhooks, start it with
ENABLE_WEBHOOKS=false.
cd ~/op-lab/tag08-site-operator
go run ./cmd/main.go -health-probe-bind-address=0 --webhook-cert-path=lab/certs \
2>&1 | tee run.logTerminal 2: Defaulter, validator and warning one after another:
kubectl apply -f lab/demo.yaml
kubectl apply -f - <<'EOF'
apiVersion: web.lab.example/v1alpha1
kind: StaticSite
metadata:
name: docs
spec:
content: "<h1>Doku</h1>"
path: docs
EOF
kubectl get site docs -o jsonpath='{.spec.path}{"\n"}'
kubectl apply -f - <<'EOF'
apiVersion: web.lab.example/v1alpha1
kind: StaticSite
metadata:
name: fremd
spec:
content: "<h1>x</h1>"
image: docker.io/library/nginx:1.29
EOF
kubectl apply -f - <<'EOF'
apiVersion: web.lab.example/v1alpha1
kind: StaticSite
metadata:
name: spaeter
spec:
contentFrom:
configMapRef:
name: html
EOFExpected (wrapped):
staticsite.web.lab.example/demo created
staticsite.web.lab.example/docs created
/docs/
The StaticSite "fremd" is invalid: spec.image: Forbidden:
erlaubt sind nur [nginxinc/ registry.lab.example/]
Warning: ConfigMap html fehlt (noch)
staticsite.web.lab.example/spaeter created
The whole chain works: defaulter (docs →
/docs/), schema and CEL, validator with error
(erlaubt sind nur, “only … are allowed”) and warning
(fehlt (noch), “is missing (yet)”), then Reconcile. Stop
the operator (Terminal 3) with Ctrl+C.
Save your progress? Sign up for free
Checkpoint
Start the operator in Terminal 3 once more (command from Drill 8), then:
cd ~/op-lab/tag08-site-operator
ok() { echo "✔ $1"; }; nok() { echo "✘ $1"; }
CRD=config/crd/bases/web.lab.example_staticsites.yaml
go test ./internal/... -count=1 >/dev/null 2>&1 && ok "Tests grün" || nok "Tests"
grep -q 'has(self.contentFrom)' $CRD && ok "CEL: genau eins" || nok "ExactlyOneOf"
grep -q 'self == oldSelf' $CRD && ok "Transition Rule" || nok "Transition Rule"
kubectl apply -f lab/kaputt.yaml 2>&1 | grep -q 'exactly one' \
&& ok "API-Server lehnt kaputt.yaml ab" || nok "kaputt.yaml"
kubectl get site docs -o jsonpath='{.spec.path}' | grep -qx '/docs/' \
&& ok "Defaulter normalisiert path" || nok "Defaulter"
kubectl apply --dry-run=server -f lab/demo.yaml >/dev/null 2>&1 \
&& ok "Webhook erreichbar" || nok "Webhook (läuft der Operator?)"Expected:
✔ Tests grün
✔ CEL: genau eins
✔ Transition Rule
✔ API-Server lehnt kaputt.yaml ab
✔ Defaulter normalisiert path
✔ Webhook erreichbar
Afterwards, stop the operator and envtest-up with
Ctrl+C.
Challenge
The registry policy is hard-wired in the code. Make it configurable
via the flag --allowed-image-prefixes (comma-separated) and
try out docker.io/library/.
Hint: Set
webhookv1alpha1.AllowedImagePrefixes in
cmd/main.go before
SetupStaticSiteWebhookWithManager runs.
Solution
In cmd/main.go (add the import
"strings"):
var registrarURL, allowedImages string
flag.StringVar(&allowedImages, "allowed-image-prefixes",
"nginxinc/,registry.lab.example/", "erlaubte Image-Präfixe, kommagetrennt")
// ...
if os.Getenv("ENABLE_WEBHOOKS") != "false" {
webhookv1alpha1.AllowedImagePrefixes = strings.Split(allowedImages, ",")Restart the operator in Terminal 3 with
--allowed-image-prefixes=docker.io/library/, then:
kubectl apply -f - <<'EOF'
apiVersion: web.lab.example/v1alpha1
kind: StaticSite
metadata:
name: fremd
spec:
content: "<h1>x</h1>"
image: docker.io/library/nginx:1.29
EOF
kubectl apply -f - <<'EOF'
apiVersion: web.lab.example/v1alpha1
kind: StaticSite
metadata:
name: standard
spec:
content: "<h1>x</h1>"
EOFExpected (wrapped):
staticsite.web.lab.example/fremd created
The StaticSite "standard" is invalid: spec.image: Forbidden:
erlaubt sind nur [docker.io/library/]
Instructive: the schema default
nginxinc/nginx-unprivileged:… now fails the policy itself.
Defaults and policy belong together in tests – otherwise nobody can
create a minimal StaticSite anymore.
Save your progress? Sign up for free
Enterprise Note
- CEL first, then webhooks: CEL has no failure path, no certificate, no latency. Use webhooks only for lookups and configuration.
- Certificates in the cluster: cert-manager
(
config/certmanagerand the[CERTMANAGER]sections inconfig/default/kustomization.yaml) including CA injection into thecaBundle; rotation without a restart via the cert watcher incmd/main.go. failurePolicy: Fail+ only one replica = outage of the API for your CRs. At least two replicas, a PodDisruptionBudget, a shorttimeoutSeconds(2–5 s), anamespaceSelectorto exclude system namespaces.- Mutating webhooks must be idempotent – the API server calls them
multiple times when needed (
reinvocationPolicy). - Cluster-wide policies (registries, labels) are better placed in
Kyverno, Gatekeeper or
ValidatingAdmissionPolicy(CEL, without a server of its own) – the operator webhook only checks what concerns its own API.