TExcelTAD
Home › Kubernetes › Admission Control & Policies

Admission Control & Policies

RBAC answers "may this user create Pods in this namespace?". It can't answer "may this Pod run as root?", "does every Deployment have an owner label?" or "should this Pod get a sidecar injected?". Those questions are answered by admission control: code that runs inside the API server's request pipeline, after authorization and before anything is written to etcd. Admission is where Pod Security, ResourceQuota, LimitRanges, Istio's sidecar injection, Kyverno and Gatekeeper all plug in.

The request pipeline

text
kubectl apply ──► authentication ──► authorization (RBAC)
                                          │
                                          ▼
                 ┌──────── mutating admission ────────┐
                 │ built-in plugins (ServiceAccount,  │
                 │ LimitRanger, DefaultStorageClass…) │
                 │ MutatingAdmissionPolicies (CEL)    │
                 │ mutating webhooks                  │
                 └────────────────┬───────────────────┘
                                  ▼
                       schema validation (OpenAPI)
                                  ▼
                 ┌─────── validating admission ───────┐
                 │ built-in plugins (PodSecurity,     │
                 │ ResourceQuota, NamespaceLifecycle) │
                 │ ValidatingAdmissionPolicies (CEL)  │
                 │ validating webhooks (in parallel)  │
                 └────────────────┬───────────────────┘
                                  ▼
                                etcd

Two rules shape everything: mutation happens before validation, so validators see the final object, and any single rejection fails the whole request. Mutating webhooks run one after another (each sees the previous patches); validating webhooks run in parallel because they can't change anything.

Built-in admission plugins

The API server compiles in a few dozen plugins and enables a sensible set by default. The ones you notice daily:

Plugin Kind What it does
NamespaceLifecycle validating Refuses new objects in a namespace that is terminating
ServiceAccount mutating Sets serviceAccountName: default and mounts the token (ServiceAccounts)
LimitRanger both Applies default requests/limits and enforces min/max (Quotas)
DefaultStorageClass mutating Fills in storageClassName on PVCs
ResourceQuota validating Rejects objects that would exceed a quota
PodSecurity validating Enforces the Pod Security Standards per namespace (Security Contexts)

Webhooks

For anything custom, the API server can call out to your HTTPS service with an AdmissionReview request. A mutating webhook answers with a base64-encoded JSONPatch; a validating one with allowed: true/false and a message.

yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: team-defaults
webhooks:
  - name: defaults.platform.example.com
    clientConfig:
      service: {namespace: platform, name: admission, path: /mutate, port: 443}
      caBundle: LS0tLS1CRUdJTi...           # usually injected by cert-manager's CA injector
    rules:
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments"]
    namespaceSelector:
      matchExpressions:
        - {key: kubernetes.io/metadata.name, operator: NotIn, values: [kube-system, platform]}
    matchConditions:                         # CEL pre-filter, saves a network call
      - name: not-a-node
        expression: "!request.userInfo.username.startsWith('system:node:')"
    failurePolicy: Fail                      # or Ignore
    sideEffects: None
    timeoutSeconds: 5
    reinvocationPolicy: IfNeeded             # re-run if a later webhook changed the object
    admissionReviewVersions: ["v1"]

Sample response the webhook sends back:

json
{
  "apiVersion": "admission.k8s.io/v1",
  "kind": "AdmissionReview",
  "response": {
    "uid": "7f3c2a1e-0b9d-4c55-9a8e-2d1f6b3e4a10",
    "allowed": true,
    "patchType": "JSONPatch",
    "patch": "W3sib3AiOiJhZGQiLCJwYXRoIjoiL21ldGFkYXRhL2xhYmVscy90ZWFtIiwidmFsdWUiOiJ1bmtub3duIn1d"
  }
}

The failurePolicy is the important operational choice. Fail means "if my webhook is down, nobody can create Deployments", which is safe for security policy but can lock you out of your own cluster. Ignore means a broken webhook silently lets everything through. Always exclude kube-system and the webhook's own namespace, keep timeouts short, and run the webhook with several replicas and a PodDisruptionBudget.

The model below sends one Deployment through a chain: two mutating webhooks, one of them down, then two validators.

python · try it yourself
import copy

def add_team_label(obj):
    labels = obj["metadata"].setdefault("labels", {})
    return [] if "team" in labels else [("add", "/metadata/labels/team", "unknown")]

def inject_sidecar(obj):
    names = [c["name"] for c in obj["spec"]["containers"]]
    return [] if "proxy" in names else [("add", "/spec/containers/-", {"name": "proxy", "image": "envoy:1.36"})]

def cost_annotations(obj):
    raise TimeoutError("context deadline exceeded")

def apply_patch(obj, ops):
    for op, path, value in ops:
        if path == "/metadata/labels/team":
            obj["metadata"]["labels"]["team"] = value
        elif path == "/spec/containers/-":
            obj["spec"]["containers"].append(value)

def no_latest(obj):
    bad = [c["name"] for c in obj["spec"]["containers"] if c["image"].endswith(":latest")]
    return f"containers {bad} use the :latest tag" if bad else None

def team_known(obj):
    team = obj["metadata"]["labels"].get("team")
    return None if team != "unknown" else "label team must name a real team"

MUTATING = [("team-defaults", add_team_label, "Fail"),
            ("cost-annotator", cost_annotations, "Ignore"),
            ("mesh-injector", inject_sidecar, "Fail")]
VALIDATING = [("no-latest", no_latest), ("team-required", team_known)]

def admit(obj):
    obj = copy.deepcopy(obj)
    for name, hook, policy in MUTATING:
        try:
            ops = hook(obj)
        except TimeoutError as e:
            if policy == "Fail":
                return f'DENIED: failed calling webhook "{name}": {e}'
            print(f"  {name}: {e} (failurePolicy=Ignore, skipped)")
            continue
        apply_patch(obj, ops)
        print(f"  {name}: {len(ops)} patch op(s)")
    problems = [msg for name, check in VALIDATING if (msg := check(obj))]
    if problems:
        return "DENIED: " + "; ".join(problems)
    return f"ALLOWED: labels={obj['metadata']['labels']} containers={[c['name'] for c in obj['spec']['containers']]}"

good = {"metadata": {"labels": {"app": "api", "team": "payments"}},
        "spec": {"containers": [{"name": "api", "image": "ghcr.io/acme/api:2.4.1"}]}}
sloppy = {"metadata": {"labels": {"app": "web"}},
          "spec": {"containers": [{"name": "web", "image": "nginx:latest"}]}}
for name, obj in [("good", good), ("sloppy", sloppy)]:
    print(f"{name}:")
    print("  ->", admit(obj))
good:
  team-defaults: 0 patch op(s)
  cost-annotator: context deadline exceeded (failurePolicy=Ignore, skipped)
  mesh-injector: 1 patch op(s)
  -> ALLOWED: labels={'app': 'api', 'team': 'payments'} containers=['api', 'proxy']
sloppy:
  team-defaults: 1 patch op(s)
  cost-annotator: context deadline exceeded (failurePolicy=Ignore, skipped)
  mesh-injector: 1 patch op(s)
  -> DENIED: containers ['web'] use the :latest tag; label team must name a real team

The "sloppy" Deployment was mutated first (it got team: unknown and a sidecar) and only then rejected, with all validation messages at once, which is exactly what a user wants to see.

ValidatingAdmissionPolicy: policies without a webhook

Since Kubernetes 1.30, ValidatingAdmissionPolicy (GA) lets you write validation rules in CEL directly in the API server: no service to deploy, no certificates, no network hop, no outage risk. A policy defines the checks; a binding says where they apply and what to do on failure. MutatingAdmissionPolicy (CEL-based mutation) is following the same path and is beta in 1.34, off by default.

yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: replica-limit
spec:
  failurePolicy: Fail
  paramKind: {apiVersion: v1, kind: ConfigMap}       # limits come from a ConfigMap
  matchConstraints:
    resourceRules:
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments"]
  matchConditions:
    - name: skip-system-users
      expression: "!request.userInfo.username.startsWith('system:')"
  validations:
    - expression: "object.spec.replicas <= int(params.data.maxReplicas)"
      messageExpression: "'replicas must be <= ' + params.data.maxReplicas"
      reason: Invalid
    - expression: "object.spec.template.spec.containers.all(c, has(c.resources) && has(c.resources.limits))"
      message: every container needs resource limits
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: replica-limit-dev
spec:
  policyName: replica-limit
  paramRef: {name: dev-limits, namespace: policy, parameterNotFoundAction: Deny}
  validationActions: [Warn, Audit]     # roll out softly first; switch to [Deny] later
  matchResources:
    namespaceSelector:
      matchLabels: {env: dev}

validationActions is what makes policies safe to roll out: Warn returns a warning to the client (kubectl prints it) but lets the request through, Audit records the violation in the audit log, and Deny rejects. A sample kubectl apply while the binding is in Warn mode:

text
Warning: Validation failed for ValidatingAdmissionPolicy 'replica-limit' with binding 'replica-limit-dev': replicas must be <= 5
deployment.apps/web created

The next model evaluates the same policy against three Deployments under different bindings. The CEL expressions become Python lambdas, params is the ConfigMap:

python · try it yourself
policy = {
    "matchCondition": lambda req: not req["user"].startswith("system:"),
    "validations": [
        (lambda o, p: o["replicas"] <= int(p["maxReplicas"]),
         lambda o, p: f"replicas must be <= {p['maxReplicas']}"),
        (lambda o, p: all("limits" in c.get("resources", {}) for c in o["containers"]),
         lambda o, p: "every container needs resource limits"),
    ],
}
bindings = {"dev": (["Warn", "Audit"], {"maxReplicas": "5"}),
            "prod": (["Deny"], {"maxReplicas": "50"})}

def evaluate(req):
    actions, params = bindings[req["ns"]]
    if not policy["matchCondition"](req):
        return "allowed (match condition excluded the request)"
    failures = [msg(req["obj"], params) for check, msg in policy["validations"] if not check(req["obj"], params)]
    if not failures:
        return "allowed"
    out = []
    if "Deny" in actions:
        return "DENIED: " + "; ".join(failures)
    if "Warn" in actions:
        out += [f"Warning: {f}" for f in failures]
    if "Audit" in actions:
        out.append(f"audit annotation: {len(failures)} violation(s)")
    return "allowed | " + " | ".join(out)

limited = [{"name": "app", "resources": {"limits": {"cpu": "1"}}}]
unlimited = [{"name": "app", "resources": {}}]
requests = [
    ("web -> dev", {"ns": "dev", "user": "alice", "obj": {"replicas": 8, "containers": limited}}),
    ("web -> prod", {"ns": "prod", "user": "alice", "obj": {"replicas": 8, "containers": unlimited}}),
    ("api -> prod", {"ns": "prod", "user": "alice", "obj": {"replicas": 12, "containers": limited}}),
    ("hpa scale", {"ns": "prod", "user": "system:serviceaccount:kube-system:horizontal-pod-autoscaler",
                   "obj": {"replicas": 80, "containers": unlimited}}),
]
for label, req in requests:
    print(f"{label:12} {evaluate(req)}")
web -> dev   allowed | Warning: replicas must be <= 5 | audit annotation: 1 violation(s)
web -> prod  DENIED: every container needs resource limits
api -> prod  allowed
hpa scale    allowed (match condition excluded the request)

Policy engines

For larger rule sets, teams install a policy engine that runs as an admission webhook (and increasingly compiles rules into ValidatingAdmissionPolicies):

Kyverno OPA Gatekeeper
Rule language YAML patterns + CEL Rego
Mutation Yes, plus generating objects (e.g. a default NetworkPolicy per namespace) Yes (Assign/ModifySet)
Audit of existing objects Policy reports Audit + constraint status
Learning curve Low for Kubernetes people Higher, but Rego is reusable outside Kubernetes

Whatever you choose, test policies in CI against your manifests (kyverno test, gator verify, or kubectl apply --dry-run=server, which runs the full admission chain without storing anything) and roll them out in Warn/Audit mode before Deny.

Tip: When a request is rejected and you don't know by whom, the error names the webhook or policy (admission webhook "defaults.platform.example.com" denied the request: …). kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations,validatingadmissionpolicies lists every suspect.

Learn more: Custom Resources & CRDs (CEL in CRD schemas) · Security Contexts & Pod Security · Service Meshes (sidecar injection is a mutating webhook)

Go further: Admission Control: Gatekeeper, Kyverno and Built-In Policies shows how admission is bypassed and writes the same rule in Kyverno and CEL.

Test yourself

In which order does the API server run admission?

  1. Validating, then mutating
  2. Mutating, then schema validation, then validating
  3. Only webhooks, never built-in plugins
  4. Validating webhooks before RBAC

A validating webhook with failurePolicy: Fail is unreachable. What happens to matching requests?

  1. They are allowed
  2. They are rejected
  3. They are queued until the webhook returns
  4. They are written to etcd unvalidated

What does validationActions: [Warn, Audit] on a ValidatingAdmissionPolicyBinding do?

  1. Rejects violating requests
  2. Lets violating requests through but warns the client and records an audit annotation
  3. Disables the policy
  4. Mutates the object to comply