Platform Engineering · Lesson 178

Kubernetes Admission Control: Webhooks, ValidatingAdmissionPolicy, and Failing Safely

After the API server knows who you are and that you may create a pod, admission control decides whether this particular pod may exist, and what it should look like. Mutating admission changes the object (adding defaults, labels, sidecars), schema validation checks its shape, and validating admission accepts or rejects it, either with in-process ValidatingAdmissionPolicies written in CEL or with webhooks such as Kyverno and Gatekeeper. Admission is where cluster-wide rules are enforced, and a webhook that is down can stop a whole cluster from changing. This lesson follows one Deployment through the admission chain, a request the policy rejects, and a webhook outage.

Difficulty: Advanced · Know this first: Lesson 177, Lesson 174, Lesson 101

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar splits one write request, in milliseconds. It is a worked example, not a measurement. Webhooks are the only network calls in the chain, which is why they are both the slowest part and the part that can stop it.

Try it: what happens when the webhook is down?

Choose the webhook's timeout, its failure policy, and whether it is answering. Then see what every request it matches experiences.

Webhook down: every matched request waits timeoutSeconds, then is rejected (Fail) or admitted unchecked (Ignore)

10 sadded to every matched request
rejectedresult
stuckrisk

Safe but stuck: nothing it matches can change

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Admission control grows in four levels: first where admission sits, then writing policies, then running webhooks safely, and finally a policy program for a whole organization.

Basic — Where admission sits

At the basic level you know the order: authentication, authorization, mutating admission, schema validation, validating admission, then storage. Admission sees the object being written, so it can enforce content rules.

Tools: Pod Security Admission (built in, per namespace), ValidatingAdmissionPolicy (built in, CEL), Kyverno and OPA Gatekeeper (webhooks with policy languages), and service mesh sidecar injectors (mutating webhooks).

Where it breaks: assuming RBAC alone keeps clusters safe; it cannot see what is inside a pod.

Try it: Basic

Which runs first?

Now do it: Run admission_chain.py in Go deeper and read the four results.

Intermediate — Write policies

At the intermediate level you write and test policies.

  • Pod Security Admission labels on every namespace: enforce: restricted where possible, warn and audit while migrating.
  • ValidatingAdmissionPolicies in CEL for registry, labels, and resource rules, with validationActions: [Deny], or [Warn, Audit] to roll out.
  • Policies tested in CI against example manifests (Kyverno CLI, Gatekeeper's gator, or kubectl apply --dry-run=server on a test cluster).

Troubleshooting: server-side dry run shows exactly what admission would say.

Try it: Intermediate

You want to roll out a new policy without breaking teams. How?

Now do it: Write the ValidatingAdmissionPolicy in Go deeper with validationActions [Warn] and apply a non-compliant pod with --dry-run=server.

Advanced — Run webhooks safely

At the advanced level you make webhooks safe to depend on.

  • Several replicas, a PodDisruptionBudget, and spread across nodes and zones.
  • A short timeoutSeconds (1 to 5) so a slow webhook does not slow every write.
  • namespaceSelector and objectSelector that exclude kube-system, the webhook's own namespace, and anything that must always work.
  • Narrow rules: only the resources and operations the policy needs.
  • failurePolicy: Fail for security rules, Ignore only for helpers whose absence is harmless; sideEffects: None so dry runs work.
  • Metrics: apiserver_admission_webhook_admission_duration_seconds and rejection counts per webhook.

Try it: Advanced

A webhook matches all pods in all namespaces with failurePolicy Fail. Its own pods crash. What happens?

Now do it: Read the namespaceSelector of every validating webhook in a cluster you use and check that kube-system and the webhook's namespace are excluded.

Master — A policy program

At the master level policy is a product with owners and a lifecycle.

  • Catalogue: every policy has an owner, a reason, a test suite, and a message that tells authors how to comply.
  • Layers: CI checks (fast feedback), admission (enforcement), and background scans (existing objects), with the same rules in each.
  • Exceptions: time-limited, recorded, and reviewed, not permanent namespace exclusions.
  • Supply chain: admission verifies image signatures and provenance (Sigstore, Kyverno verifyImages) so only built-here images run.
  • Reliability: admission webhooks have SLOs, and their latency budget counts towards the API server's.

Trade-off: more policies catch more mistakes and slow every write a little and frustrate teams a lot when messages are unclear. Fewer, well-explained policies at the right layer do more.

Try it: Master

Teams keep asking for namespace-wide exclusions from the image policy. What is the better pattern?

Now do it: List your cluster's admission policies, each with its owner and the message a developer sees on denial.

Go deeper

This script plays a request through mutating admission, an in-process validating policy, and an external webhook, then repeats it with the webhook down under each failure policy. Standard library only; python3 admission_chain.py.

The admission chain, and a webhook outage

# admission_chain.py - one request through mutating admission, schema, and validating admission
def mutate(pod):
    pod = dict(pod)
    pod.setdefault("labels", {}).setdefault("team", "unknown")       # a mutating webhook adds defaults
    pod["containers"] = [dict(c, resources=c.get("resources") or {"limits": {"cpu": "500m", "memory": "256Mi"}})
                         for c in pod["containers"]]
    return pod

def validating_policy(pod):
    """A ValidatingAdmissionPolicy: CEL rules evaluated inside the API server."""
    errors = []
    for c in pod["containers"]:
        if c.get("privileged"):
            errors.append(f"container {c['name']}: privileged is not allowed")
        if not c["image"].startswith("registry.example.com/"):
            errors.append(f"container {c['name']}: image must come from registry.example.com")
    return errors

def webhook(pod, up, failure_policy):
    """An external validating webhook (Kyverno, Gatekeeper): it can be down."""
    if not up:
        return (["failed calling webhook: context deadline exceeded after 10s"] if failure_policy == "Fail" else []), 10_000
    return [], 25

def admit(pod, webhook_up=True, failure_policy="Fail"):
    pod = mutate(pod)
    errors = validating_policy(pod)
    if errors:
        return "DENIED by policy: " + "; ".join(errors)
    errors, ms = webhook(pod, webhook_up, failure_policy)
    if errors:
        return f"DENIED after {ms} ms: " + errors[0]
    return f"ADMITTED ({ms} ms in the webhook), labels={pod['labels']}, limits={pod['containers'][0]['resources']['limits']}"

good = {"name": "api", "containers": [{"name": "api", "image": "registry.example.com/shop/api:1.4"}]}
bad = {"name": "debug", "containers": [{"name": "sh", "image": "docker.io/library/busybox", "privileged": True}]}
print("1.", admit(good))
print("2.", admit(bad))
print("3.", admit(good, webhook_up=False, failure_policy="Fail"))
print("4.", admit(good, webhook_up=False, failure_policy="Ignore"))
$ python3 admission_chain.py
1. ADMITTED (25 ms in the webhook), labels={'team': 'unknown'}, limits={'cpu': '500m', 'memory': '256Mi'}
2. DENIED by policy: container sh: privileged is not allowed; container sh: image must come from registry.example.com
3. DENIED after 10000 ms: failed calling webhook: context deadline exceeded after 10s
4. ADMITTED (10000 ms in the webhook), labels={'team': 'unknown'}, limits={'cpu': '500m', 'memory': '256Mi'}

Read it like this: mutation filled in a label and limits the author forgot; the in-process policy rejected the privileged Docker Hub pod with both reasons and never called the webhook; and with the webhook down, Fail rejected a good request after the full timeout while Ignore admitted it with nothing checked. Neither outcome is free.

A ValidatingAdmissionPolicy and its binding

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: images-and-privilege
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments"]
  validations:
    - expression: "object.spec.template.spec.containers.all(c, c.image.startsWith('registry.example.com/'))"
      message: "images must come from registry.example.com"
    - expression: "object.spec.template.spec.containers.all(c, !has(c.securityContext) || !has(c.securityContext.privileged) || c.securityContext.privileged == false)"
      message: "privileged containers are not allowed"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: images-and-privilege
spec:
  policyName: images-and-privilege
  validationActions: ["Deny"]
  matchResources:
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: NotIn
          values: ["kube-system", "kyverno"]

A validating webhook that can always be repaired

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: image-signatures
webhooks:
  - name: verify.images.example.com
    admissionReviewVersions: ["v1"]
    sideEffects: None
    failurePolicy: Fail
    timeoutSeconds: 3
    clientConfig:
      service:
        name: image-verifier
        namespace: policy-system
        path: /validate
    rules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE"]
        resources: ["pods"]
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: NotIn
          values: ["kube-system", "policy-system"]

The manifests parse as YAML and use the admissionregistration.k8s.io/v1 API (ValidatingAdmissionPolicy is v1 from Kubernetes 1.30). The webhook needs a CA bundle and a running service before it does anything; apply the policy with validationActions: ["Warn"] on a test cluster first and check what it reports.

One time it broke

This is a composite of a failure pattern that has been reported many times; the details are illustrative. A cluster ran a policy webhook with failurePolicy Fail that matched every pod in every namespace, with one replica.

Timeline

  • 02:10The node running the webhook's only pod fails. Every pod creation in the cluster now waits 10 seconds and is rejected.
  • 02:15The webhook's own Deployment tries to create a replacement pod. The webhook rejects it, because it matches its own namespace. CoreDNS and other system pods cannot be rescheduled either.
  • 03:05An administrator deletes the ValidatingWebhookConfiguration, the system recovers, and the webhook is reinstalled.

What changed after

The webhook runs three replicas across zones with a PodDisruptionBudget, a 3-second timeout, and a namespaceSelector that excludes kube-system and its own namespace. The simple rules moved to a ValidatingAdmissionPolicy, which has no pods to lose. The runbook now starts with "check admission webhooks" for any cluster-wide creation failure.

If you remember nothing else

Design exercise

Design admission control for a multi-team cluster that must allow only signed images from the company registry, forbid privileged pods, and require team labels and resource limits.

Clarifying questions to ask

Which rules can be CEL, and which need a webhook? What may fail closed, and what may fail open? Which namespaces must always work? How will teams find out before a rule blocks them? Who owns each policy?

Rough sizing

Say 40 namespaces, 300 deployments a day, an API server p99 write budget of 200 ms, and three zones.

Shape of the answer

Pod Security Admission at restricted on application namespaces; ValidatingAdmissionPolicies for registry, labels, and limits, rolled out Warn then Deny; Kyverno only for image signature verification, three replicas with a PDB, timeout 3 s, failurePolicy Fail, excluding kube-system and its own namespace; the same rules in CI with the Kyverno CLI; mutation for default labels and limits where safe; dashboards of webhook latency and denials; time-limited exceptions recorded in Git.

Trade-offs to name

Fail-closed webhooks guarantee enforcement and make the webhook a dependency of every write; fail-open keeps the cluster moving and lets outages become bypasses. In-process CEL is fast and robust but cannot call out to verify signatures. Mutation fixes common omissions silently and can surprise authors; prefer validation with clear messages where the fix is the author's to make.

Saved on this device, in this browser.
Next in this series · Lesson 179
Workload Identity with SPIFFE and SPIRE: Short-Lived Certificates for Every Service

Services need to prove who they are to each other, and long-lived API keys and shared passwords are the usual way that goes wrong: copied, leaked, never rotated.

Go to Lesson 179 →

Or browse the full course from the Lessons index.