Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 78 ยท Security

Admission Control and Policy

Learn how admission controllers, webhooks and ValidatingAdmissionPolicy with CEL reject bad manifests, and how Kyverno and OPA Gatekeeper fit in, with a Python policy engine.

RBAC decides whether you may create a Deployment. It says nothing about what is in it. A developer who is allowed to create Deployments can still ask for replicas: 5000, pull latest from a random registry, or forget the labels your cost report relies on. To enforce rules about the content of objects, Kubernetes has admission control.

Admission control is a stage in the API server, after authentication and authorization and before an object is stored in etcd. Admission plugins can change the object (mutating) or accept or reject it (validating). Some are built in (like Pod Security Admission from the last lesson); you can add your own through webhooks, through built-in CEL policies, or through policy engines such as Kyverno and OPA Gatekeeper.

The path of a request

flowchart LR
    A["kubectl apply"] --> B["Authentication"]
    B --> C["Authorization (RBAC)"]
    C --> D["Mutating admission"]
    D --> E["Schema validation"]
    E --> F["Validating admission"]
    F --> G["Saved to etcd"]

A request must pass every stage in order. Any validating plugin can reject it, and nothing is stored.

Two details are worth remembering. Mutating plugins run before validating ones, so validation sees the final object, including defaults and injected sidecars. And admission applies to writes (create, update, delete, and the connect operation for things like exec), never to reads. Because it runs inside the write path, a slow or broken admission service can slow down or block the whole cluster, so reliability matters.

Three ways to add rules

Webhooks Your own HTTPS service decides.
CEL policies Built into the API server, no extra pods.
Policy engines Kyverno or Gatekeeper with ready-made rules.
1 / 2

Admission webhooks

A webhook is the original extension point. You write an HTTPS service, and register it with a configuration object that tells the API server which operations and resources to send to it:

YAML
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: image-policy
webhooks:
  - name: images.policy.example.com
    admissionReviewVersions: ["v1"]
    sideEffects: None
    timeoutSeconds: 5
    failurePolicy: Fail
    clientConfig:
      service:
        name: image-policy
        namespace: policy-system
        path: /validate
      caBundle: "LS0tLS1CRUdJTi4uLg=="
    rules:
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments"]
    namespaceSelector:
      matchExpressions:
        - key: policy
          operator: NotIn
          values: ["skip"]

For each matching request, the API server POSTs an AdmissionReview JSON document containing the object (and the old object for updates), and expects a reply with allowed: true or false and an optional message. A mutating webhook returns a JSON Patch to apply.

The fields that matter most operationally:

  • failurePolicy: Fail rejects requests when the webhook is unreachable (safe but risky for availability); Ignore lets them through (available but bypassable). Pick deliberately.
  • timeoutSeconds: up to 30. Keep it short.
  • namespaceSelector / objectSelector: exclude kube-system and the webhook's own namespace, or you can deadlock the cluster: the webhook pod cannot start because the webhook that must approve it is not running.
  • sideEffects: tells the API server whether a dry run may call it safely.

Webhooks can do anything, but you must run, secure, scale and monitor the service. That is why simpler options now exist.

ValidatingAdmissionPolicy with CEL

Since Kubernetes 1.30, ValidatingAdmissionPolicy is stable. Rules are written in CEL (Common Expression Language), a small, safe expression language, and evaluated inside the API server. No extra service, no network call, no failurePolicy outage.

A policy has two parts: the policy (the rule) and a binding (where and how it applies).

YAML
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: deployment-guardrails
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments"]
  validations:
    - expression: "object.spec.replicas <= 10"
      message: "A Deployment may have at most 10 replicas."
    - expression: "has(object.metadata.labels) && 'owner' in object.metadata.labels"
      message: "The label 'owner' is required."
    - expression: >-
        object.spec.template.spec.containers.all(c,
          c.image.startsWith('registry.example.com/'))
      messageExpression: "'Images must come from registry.example.com'"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: deployment-guardrails-prod
spec:
  policyName: deployment-guardrails
  validationActions: ["Deny"]
  matchResources:
    namespaceSelector:
      matchLabels:
        environment: production

Reading the CEL: object is the incoming object, oldObject the previous one (on updates), request holds user info and operation, and params can refer to a parameter resource. all(c, ...) is a macro that checks a list, has(x.y) tests for a field, and &&, ||, ! are the logic operators. The validationActions of the binding can be Deny, Warn and Audit, so you can roll out a new rule in warn mode first, the same trick as with Pod Security.

Newer Kubernetes releases also add a mutating variant based on the same ideas, so check your cluster version before depending on it.

Policy engines: Kyverno and OPA Gatekeeper

If you want a library of ready-made policies, reports, exceptions and mutation, a policy engine saves a lot of work. Both run as admission webhooks and install through Helm.

  • Kyverno writes policies as Kubernetes YAML, with no new language. Rules can validate, mutate, generate (create a NetworkPolicy in every new namespace) and verify image signatures.
  • OPA Gatekeeper uses the Open Policy Agent. You write rules in Rego inside a ConstraintTemplate, then create Constraint objects that use the template with parameters. It is powerful and popular in larger organizations that already use OPA elsewhere.

A Kyverno policy looks like this:

YAML
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-latest-tag
spec:
  validationFailureAction: Enforce
  rules:
    - name: no-latest
      match:
        any:
          - resources:
              kinds: ["Pod"]
      validate:
        message: "Images must use a pinned tag, not :latest."
        pattern:
          spec:
            containers:
              - image: "!*:latest"

How to choose: use built-in Pod Security Admission for the basic pod standards, ValidatingAdmissionPolicy for simple field checks without new components, and Kyverno or Gatekeeper when you need mutation, generation, reports, exceptions or a large shared policy library.

A policy engine in Python

The stand-in below mimics the validating stage. Each policy is a name, a message and a condition. The engine evaluates all policies against a manifest and collects every failure, as the API server does for ValidatingAdmissionPolicy. The conditions are written as Python expressions over a small Obj wrapper (so object.spec.replicas works). Real CEL uses && and startsWith; here they are and and .startswith. It is a model of the idea, not a CEL implementation.

Python Rejecting bad manifests with policies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the messy case: the engine reports all violations at once, not only the first. That mirrors how the API server returns every failed validation, so users can fix them in one pass.

A second stand-in shows the staged flow, with a mutating step that adds a default label before validation, plus the Deny versus Warn actions of a binding:

Python Mutate first, then validate (Deny and Warn)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first manifest gets the managed-by label from the mutating stage, passes both Deny rules and triggers only a warning. The second never gets an owner, so validation rejects it, and nothing is stored.

Practical advice

  • Start every new rule in Warn or Audit mode and watch what it would block.
  • Exempt system namespaces, and never let a webhook intercept the objects that run the webhook itself.
  • Prefer built-in CEL policies when they are expressive enough; fewer moving parts means fewer outages.
  • Keep policy YAML in Git and deploy it like any other manifest.
  • Policies are guardrails, not a security boundary on their own. Combine them with RBAC and Pod Security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order do the API server stages run?

    Identity first, then permission, then mutating plugins change the object, then validating plugins check the final result before it is stored.
  2. 2. What is a main advantage of ValidatingAdmissionPolicy over a validating webhook?

    CEL expressions are evaluated in-process. There is no HTTPS service to deploy, scale or secure, and no network failure mode.
  3. 3. A validating webhook has failurePolicy: Fail and runs as a Deployment in the cluster it protects. What is a danger?

    If the webhook intercepts its own pods and is unavailable, the pods cannot be recreated and the policy service never comes back. Exclude the webhook's namespace.
  4. 4. Which tool lets you write policies as plain Kubernetes YAML, and can also generate and mutate resources?

    Kyverno policies are Kubernetes resources and support validate, mutate, generate and image verification rules. Gatekeeper uses Rego.
  5. 5. What does validationActions: ["Warn"] on a policy binding do?

    Warn lets the request through and shows a warning, which is a safe way to roll out new rules.

Summary

  • Admission control runs after authorization and before storage: mutating plugins first, then schema validation, then validating plugins.
  • Webhooks are flexible but need a reliable HTTPS service; failurePolicy and namespace exclusions decide how risky they are.
  • ValidatingAdmissionPolicy evaluates CEL expressions inside the API server, with bindings that choose Deny, Warn or Audit.
  • Kyverno and OPA Gatekeeper add rich policy libraries, mutation, generation and reports.
  • Roll out new rules in warn mode, and keep policies in Git.

Next: protect what runs and where it comes from, in Supply Chain and Cluster Hardening.