Kubernetes Admission Webhook Testing: Validating and Mutating Webhooks in CI

Kubernetes Admission Webhook Testing: Validating and Mutating Webhooks in CI

Kubernetes admission webhooks intercept API server requests before they're persisted. Validating webhooks reject non-compliant resources. Mutating webhooks modify resources on their way in. Both are powerful mechanisms for enforcing policy and setting defaults — and both can break your cluster if they're misconfigured or have bugs.

Testing admission webhooks is harder than testing most Kubernetes components because they require TLS, run as servers that receive calls from the API server, and must respond within a tight timeout. This guide covers how to do it correctly.

Understanding Admission Webhook Testing Challenges

TLS is mandatory. The API server won't call a webhook over plain HTTP. In production, webhooks use certificates signed by a CA the API server trusts. In tests, you need either self-signed certs or the TLS bypass that kind provides.

Timeouts are short. A webhook that doesn't respond within the timeout (default: 10 seconds) causes the admission request to fail — and depending on failurePolicy, can block all resource creation.

Ordering matters for mutating webhooks. If multiple mutating webhooks run, they run in alphabetical order by webhook name. A mutating webhook that sets a label expects the resource to not already have conflicting labels.

Side effects must be testable. A validating webhook that checks external state (a database, another API) needs to handle failures gracefully.

Project Structure

admission-webhook/
├── main.go                    # Webhook server
├── pkg/
│   ├── webhook/
│   │   ├── validating.go      # Validating webhook handler
│   │   ├── mutating.go        # Mutating webhook handler
│   │   └── handler_test.go    # Unit tests for handlers
│   └── server/
│       └── server.go          # HTTP server setup
├── test/
│   └── integration/
│       └── webhook_test.go    # Integration tests with kind
├── k8s/
│   ├── webhook-config.yaml    # ValidatingWebhookConfiguration
│   └── certs/                 # TLS certificates for tests
└── kind-config.yaml

Unit Testing Webhook Handler Logic

The core of a webhook is the admission review logic. Unit test it by constructing admission requests directly:

// pkg/webhook/validating.go
package webhook

import (
    admissionv1 "k8s.io/api/admission/v1"
    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/runtime"
    "encoding/json"
)

// ValidatePod validates pod admission requests.
// Rules:
// 1. Pods must have resource limits set
// 2. Pods must not run as root
// 3. Pods must have at least one label
func ValidatePod(req *admissionv1.AdmissionRequest) *admissionv1.AdmissionResponse {
    pod := &corev1.Pod{}
    if err := json.Unmarshal(req.Object.Raw, pod); err != nil {
        return &admissionv1.AdmissionResponse{
            Allowed: false,
            Result: &metav1.Status{Message: "Failed to decode pod: " + err.Error()},
        }
    }

    for _, container := range pod.Spec.Containers {
        if container.Resources.Limits == nil {
            return &admissionv1.AdmissionResponse{
                Allowed: false,
                Result: &metav1.Status{
                    Message: "Container '" + container.Name + "' must have resource limits",
                },
            }
        }
    }

    if pod.Spec.SecurityContext != nil &&
        pod.Spec.SecurityContext.RunAsNonRoot != nil &&
        !*pod.Spec.SecurityContext.RunAsNonRoot {
        return &admissionv1.AdmissionResponse{
            Allowed: false,
            Result:  &metav1.Status{Message: "Pod must not run as root"},
        }
    }

    if len(pod.Labels) == 0 {
        return &admissionv1.AdmissionResponse{
            Allowed: false,
            Result:  &metav1.Status{Message: "Pod must have at least one label"},
        }
    }

    return &admissionv1.AdmissionResponse{Allowed: true}
}
// pkg/webhook/handler_test.go
package webhook_test

import (
    "encoding/json"
    "testing"

    admissionv1 "k8s.io/api/admission/v1"
    corev1 "k8s.io/api/core/v1"
    "k8s.io/apimachinery/pkg/api/resource"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/runtime"

    "github.com/myorg/webhook/pkg/webhook"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func makeAdmissionRequest(pod corev1.Pod) *admissionv1.AdmissionRequest {
    raw, _ := json.Marshal(pod)
    return &admissionv1.AdmissionRequest{
        UID:    "test-uid",
        Kind:   metav1.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"},
        Object: runtime.RawExtension{Raw: raw},
    }
}

func validPod() corev1.Pod {
    runAsNonRoot := true
    return corev1.Pod{
        ObjectMeta: metav1.ObjectMeta{
            Name:   "test-pod",
            Labels: map[string]string{"app": "test"},
        },
        Spec: corev1.PodSpec{
            SecurityContext: &corev1.PodSecurityContext{
                RunAsNonRoot: &runAsNonRoot,
            },
            Containers: []corev1.Container{{
                Name:  "app",
                Image: "nginx:latest",
                Resources: corev1.ResourceRequirements{
                    Limits: corev1.ResourceList{
                        corev1.ResourceCPU:    resource.MustParse("500m"),
                        corev1.ResourceMemory: resource.MustParse("128Mi"),
                    },
                },
            }},
        },
    }
}

func TestValidatePod_AllowsValidPod(t *testing.T) {
    req := makeAdmissionRequest(validPod())
    resp := webhook.ValidatePod(req)
    assert.True(t, resp.Allowed)
}

func TestValidatePod_RejectsContainerWithoutLimits(t *testing.T) {
    pod := validPod()
    pod.Spec.Containers[0].Resources.Limits = nil

    req := makeAdmissionRequest(pod)
    resp := webhook.ValidatePod(req)

    assert.False(t, resp.Allowed)
    assert.Contains(t, resp.Result.Message, "resource limits")
}

func TestValidatePod_RejectsPodWithNoLabels(t *testing.T) {
    pod := validPod()
    pod.Labels = nil

    req := makeAdmissionRequest(pod)
    resp := webhook.ValidatePod(req)

    assert.False(t, resp.Allowed)
    assert.Contains(t, resp.Result.Message, "label")
}

func TestValidatePod_RejectsRootContainer(t *testing.T) {
    pod := validPod()
    runAsRoot := false
    pod.Spec.SecurityContext = &corev1.PodSecurityContext{
        RunAsNonRoot: &runAsRoot,
    }

    req := makeAdmissionRequest(pod)
    resp := webhook.ValidatePod(req)

    assert.False(t, resp.Allowed)
    assert.Contains(t, resp.Result.Message, "root")
}

func TestValidatePod_HandlesMultipleContainers(t *testing.T) {
    pod := validPod()
    // Add a second container without limits
    pod.Spec.Containers = append(pod.Spec.Containers, corev1.Container{
        Name:  "sidecar",
        Image: "envoy:latest",
        // No resource limits
    })

    req := makeAdmissionRequest(pod)
    resp := webhook.ValidatePod(req)

    assert.False(t, resp.Allowed)
    assert.Contains(t, resp.Result.Message, "sidecar")
}

Unit Testing Mutating Webhooks

Mutating webhooks modify incoming resources. Test that the mutations are correct:

// pkg/webhook/mutating.go
func MutatePod(req *admissionv1.AdmissionRequest) *admissionv1.AdmissionResponse {
    pod := &corev1.Pod{}
    json.Unmarshal(req.Object.Raw, pod)

    // Mutation: add default labels if none present
    if pod.Labels == nil {
        pod.Labels = map[string]string{}
    }
    if _, exists := pod.Labels["managed-by"]; !exists {
        pod.Labels["managed-by"] = "admission-webhook"
    }

    // Mutation: set default resource limits if not set
    for i := range pod.Spec.Containers {
        if pod.Spec.Containers[i].Resources.Limits == nil {
            pod.Spec.Containers[i].Resources.Limits = corev1.ResourceList{
                corev1.ResourceCPU:    resource.MustParse("200m"),
                corev1.ResourceMemory: resource.MustParse("64Mi"),
            }
        }
    }

    // Generate patch
    originalJSON, _ := json.Marshal(&corev1.Pod{})
    modifiedJSON, _ := json.Marshal(pod)
    patch, _ := createJSONPatch(originalJSON, modifiedJSON)

    return &admissionv1.AdmissionResponse{
        Allowed:   true,
        Patch:     patch,
        PatchType: patchTypePtr(admissionv1.PatchTypeJSONPatch),
    }
}
func TestMutatePod_AddsDefaultLabel(t *testing.T) {
    pod := corev1.Pod{
        ObjectMeta: metav1.ObjectMeta{Name: "test"},
        Spec: corev1.PodSpec{
            Containers: []corev1.Container{{Name: "app", Image: "nginx"}},
        },
    }

    req := makeAdmissionRequest(pod)
    resp := webhook.MutatePod(req)

    require.True(t, resp.Allowed)
    require.NotEmpty(t, resp.Patch)

    // Parse the JSON patch and verify it adds the label
    var patches []map[string]interface{}
    json.Unmarshal(resp.Patch, &patches)

    labelPatch := findPatch(patches, "/metadata/labels/managed-by")
    require.NotNil(t, labelPatch, "Expected patch for managed-by label")
    assert.Equal(t, "admission-webhook", labelPatch["value"])
}

func TestMutatePod_DoesNotOverrideExistingLimits(t *testing.T) {
    pod := validPod() // Has limits set

    req := makeAdmissionRequest(pod)
    resp := webhook.MutatePod(req)

    require.True(t, resp.Allowed)

    // Patch should not modify resource limits if already set
    var patches []map[string]interface{}
    json.Unmarshal(resp.Patch, &patches)

    limitsPatch := findPatch(patches, "/spec/containers/0/resources/limits")
    assert.Nil(t, limitsPatch, "Should not patch existing resource limits")
}

Integration Testing With kind

Unit tests verify the logic. Integration tests verify the webhook works in a real Kubernetes cluster:

// test/integration/webhook_test.go
package integration_test

import (
    "context"
    "testing"

    corev1 "k8s.io/api/core/v1"
    "k8s.io/apimachinery/pkg/api/errors"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func getK8sClient(t *testing.T) *kubernetes.Clientset {
    t.Helper()
    config, err := clientcmd.BuildConfigFromFlags("", "~/.kube/config")
    require.NoError(t, err)
    client, err := kubernetes.NewForConfig(config)
    require.NoError(t, err)
    return client
}

func TestWebhook_RejectsInvalidPodInCluster(t *testing.T) {
    client := getK8sClient(t)
    ctx := context.Background()

    // Try to create a pod without resource limits
    pod := &corev1.Pod{
        ObjectMeta: metav1.ObjectMeta{
            Name:      "test-no-limits",
            Namespace: "default",
            Labels:    map[string]string{"app": "test"},
        },
        Spec: corev1.PodSpec{
            Containers: []corev1.Container{{
                Name:  "app",
                Image: "nginx:latest",
                // No resource limits
            }},
        },
    }

    _, err := client.CoreV1().Pods("default").Create(ctx, pod, metav1.CreateOptions{})

    require.Error(t, err, "Expected webhook to reject pod without limits")
    statusErr, ok := err.(*errors.StatusError)
    require.True(t, ok)
    assert.Contains(t, statusErr.ErrStatus.Message, "resource limits")
}

func TestWebhook_AllowsValidPodInCluster(t *testing.T) {
    client := getK8sClient(t)
    ctx := context.Background()

    runAsNonRoot := true
    pod := &corev1.Pod{
        ObjectMeta: metav1.ObjectMeta{
            Name:      "test-valid-pod",
            Namespace: "default",
            Labels:    map[string]string{"app": "test"},
        },
        Spec: corev1.PodSpec{
            SecurityContext: &corev1.PodSecurityContext{RunAsNonRoot: &runAsNonRoot},
            Containers: []corev1.Container{{
                Name:  "app",
                Image: "nginx:latest",
                Resources: corev1.ResourceRequirements{
                    Limits: corev1.ResourceList{
                        corev1.ResourceCPU:    resource.MustParse("500m"),
                        corev1.ResourceMemory: resource.MustParse("128Mi"),
                    },
                },
            }},
        },
    }

    createdPod, err := client.CoreV1().Pods("default").Create(ctx, pod, metav1.CreateOptions{})
    require.NoError(t, err)

    t.Cleanup(func() {
        client.CoreV1().Pods("default").Delete(ctx, "test-valid-pod", metav1.DeleteOptions{})
    })

    // Verify mutating webhook added the managed-by label
    assert.Equal(t, "admission-webhook", createdPod.Labels["managed-by"])
}

Setting Up TLS for kind Tests

kind provides a way to install the webhook's CA certificate so the API server trusts it:

#!/bin/bash
# setup-webhook-test.sh

# Generate self-signed certificate for the webhook
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem \
  -days 365 -nodes -subj "/CN=webhook-service.default.svc"

# Create the TLS secret in the cluster
kubectl create secret tls webhook-tls \
  --cert=cert.pem \
  --key=key.pem

# Deploy the webhook server
kubectl apply -f k8s/webhook-deployment.yaml

# Register the webhook with the API server (using the CA bundle)
CA_BUNDLE=$(base64 -w0 cert.pem)
sed "s/CA_BUNDLE_PLACEHOLDER/$CA_BUNDLE/g" \
  k8s/webhook-config.yaml.template > k8s/webhook-config.yaml
kubectl apply -f k8s/webhook-config.yaml

CI Configuration

# .github/workflows/webhook-tests.yml
name: Admission Webhook Tests

on: [push, pull_request]

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v4
      - run: go test ./pkg/... -v -cover

  integration-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v4

      - name: Create kind cluster
        run: |
          kind create cluster --name webhook-test

      - name: Setup TLS and deploy webhook
        run: bash scripts/setup-webhook-test.sh

      - name: Run integration tests
        run: go test ./test/integration/... -v --timeout 5m

      - name: Cleanup
        if: always()
        run: kind delete cluster --name webhook-test

Testing Failure Modes

Don't forget to test what happens when the webhook itself fails:

func TestWebhook_FailurePolicy_WhenWebhookDown(t *testing.T) {
    // This test verifies failurePolicy behavior
    // Scale down the webhook deployment
    client := getK8sClient(t)
    ctx := context.Background()

    // Scale to zero
    scale := &autoscalingv1.Scale{Spec: autoscalingv1.ScaleSpec{Replicas: 0}}
    client.AppsV1().Deployments("default").UpdateScale(ctx, "webhook-server", scale, metav1.UpdateOptions{})

    // Wait for scale-down
    time.Sleep(5 * time.Second)

    t.Cleanup(func() {
        // Scale back up
        scale.Spec.Replicas = 1
        client.AppsV1().Deployments("default").UpdateScale(ctx, "webhook-server", scale, metav1.UpdateOptions{})
    })

    // Try to create a pod — behavior depends on failurePolicy
    _, err := client.CoreV1().Pods("default").Create(ctx, validPod(), metav1.CreateOptions{})

    // If failurePolicy=Fail: err is not nil
    // If failurePolicy=Ignore: err is nil (webhook failure is ignored)
    // Your test should verify whichever policy your configuration uses
    if yourWebhookUsesFailPolicyFail {
        assert.Error(t, err)
    } else {
        assert.NoError(t, err)
    }
}

Admission webhook testing has two critical layers: unit tests for the handler logic (fast, no cluster needed) and integration tests against a real cluster (slower but verifies TLS, registration, and API server interaction). Both are necessary for confident webhook deployments.


HelpMeTest can verify application behavior after Kubernetes policy changes — including admission webhook deployments that change what resources are allowed. Start free →

Read more

Start now free