Kubernetes Network Policy Testing: Validating Traffic Rules and Segmentation

Kubernetes Network Policy Testing: Validating Traffic Rules and Segmentation

Kubernetes NetworkPolicies are firewall rules for pods. They specify which pods can communicate with which other pods, on which ports, using which protocols. The problem: they're easy to misconfigure, and a misconfiguration either blocks legitimate traffic (causing an outage) or permits traffic that should be blocked (creating a security gap).

Unlike most Kubernetes resources, NetworkPolicies can't be validated by reading the YAML alone. You have to actually test connectivity between pods to know if the policy does what you think.

Understanding What Makes NetworkPolicy Testing Hard

Default-allow behavior: Without any NetworkPolicy, all pods in a namespace can communicate. A NetworkPolicy only takes effect when at least one policy targets a pod. This means a misidentified label selector can leave a pod completely open.

CNI plugin dependency: NetworkPolicies are enforced by the CNI plugin (Calico, Cilium, Weave). If your cluster uses a CNI that doesn't support NetworkPolicy (like Flannel without a plugin), policies are silently ignored. Test connectivity to verify enforcement actually happens.

Egress is often forgotten: Teams write ingress rules (who can reach my pod) and forget egress rules (where can my pod call out to). An egress NetworkPolicy that blocks DNS breaks all network communication.

Label matching is exact: A pod with label app=myapp and a pod with label app=myapp,version=v2 are different for NetworkPolicy purposes. Test with the exact labels your pods have.

Setting Up a Test Environment

For NetworkPolicy testing, you need a CNI that enforces policies. In kind, install Calico:

# Create kind cluster without default CNI
cat > kind-calico-config.yaml << 'EOF'
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
  disableDefaultCNI: true  # Disable kindnet
  podSubnet: "192.168.0.0/16"  # Calico default
nodes:
  - role: control-plane
  - role: worker
  - role: worker
EOF

kind create cluster --name netpol-test --config kind-calico-config.yaml

# Install Calico
kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.26.4/manifests/calico.yaml

# Wait for Calico to be ready
kubectl wait --for=condition=ready pod -n kube-system -l k8s-app=calico-node --timeout=120s

The Test Connectivity Pattern

The standard approach for NetworkPolicy testing:

  1. Deploy a "server" pod with known labels
  2. Deploy "client" pods with different label combinations
  3. Apply a NetworkPolicy
  4. Verify which clients can and cannot reach the server
#!/bin/bash
# test-connectivity.sh
# Returns 0 if connectivity succeeds, 1 if blocked

SOURCE_POD=$1
TARGET_HOST=$2
TARGET_PORT=$3
NAMESPACE=${4:-default}

kubectl exec -n "$NAMESPACE" "$SOURCE_POD" -- \
  timeout 5 nc -zv "$TARGET_HOST" "$TARGET_PORT" 2>&1

Testing Ingress NetworkPolicies

# policies/ingress-restrict.yaml
# Only allow traffic from pods with label app=frontend
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-ingress
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8080

Test this policy:

// netpol_test.go
package netpol_test

import (
    "context"
    "testing"
    "time"

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

func TestIngressNetworkPolicy(t *testing.T) {
    ctx := context.Background()
    client := getClient(t)
    ns := createTestNamespace(t, client)

    // Deploy server pod (backend)
    serverPod := deployPod(t, client, ctx, ns, "backend", map[string]string{"app": "backend"})
    serverIP := waitForPodIP(t, client, ctx, ns, "backend")

    // Deploy allowed client pod (frontend)
    allowedPod := deployPod(t, client, ctx, ns, "frontend", map[string]string{"app": "frontend"})

    // Deploy denied client pod (other)
    deniedPod := deployPod(t, client, ctx, ns, "other", map[string]string{"app": "other"})

    // Before applying policy: all pods can reach backend
    t.Run("BeforePolicy_AllCanConnect", func(t *testing.T) {
        assert.True(t, canConnect(t, client, ctx, ns, allowedPod, serverIP, 8080),
            "frontend should reach backend before policy")
        assert.True(t, canConnect(t, client, ctx, ns, deniedPod, serverIP, 8080),
            "other should reach backend before policy")
    })

    // Apply the NetworkPolicy
    applyNetworkPolicy(t, client, ctx, ns, "policies/ingress-restrict.yaml")
    time.Sleep(2 * time.Second) // Allow time for CNI to enforce policy

    // After applying policy: only frontend can reach backend
    t.Run("AfterPolicy_OnlyFrontendCanConnect", func(t *testing.T) {
        assert.True(t, canConnect(t, client, ctx, ns, allowedPod, serverIP, 8080),
            "frontend should still reach backend")
        assert.False(t, canConnect(t, client, ctx, ns, deniedPod, serverIP, 8080),
            "other should be blocked by policy")
    })

    // Test wrong port is also blocked
    t.Run("AfterPolicy_WrongPortIsBlocked", func(t *testing.T) {
        assert.False(t, canConnect(t, client, ctx, ns, allowedPod, serverIP, 9090),
            "port 9090 should be blocked even for frontend")
    })
}

func canConnect(t *testing.T, client *kubernetes.Clientset, ctx context.Context, ns, fromPod, toIP string, port int) bool {
    t.Helper()
    stdout, _, err := execInPod(client, ns, fromPod,
        "timeout", "3", "nc", "-zv", toIP, fmt.Sprintf("%d", port))
    return err == nil && strings.Contains(stdout, "succeeded")
}

Testing Egress NetworkPolicies

Egress rules are trickier because DNS (port 53) must usually remain open, or all name resolution fails:

# policies/egress-restrict.yaml
# Allow egress to database only, plus DNS
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: app-egress
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: myapp
  policyTypes:
    - Egress
  egress:
    # Allow DNS (critical - without this, DNS fails and all networking breaks)
    - ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

    # Allow database access only
    - to:
        - podSelector:
            matchLabels:
              app: postgres
      ports:
        - protocol: TCP
          port: 5432
func TestEgressNetworkPolicy(t *testing.T) {
    ctx := context.Background()
    client := getClient(t)
    ns := createTestNamespace(t, client)

    deployPod(t, client, ctx, ns, "myapp", map[string]string{"app": "myapp"})
    dbIP := deployPodAndGetIP(t, client, ctx, ns, "postgres", map[string]string{"app": "postgres"})
    otherIP := deployPodAndGetIP(t, client, ctx, ns, "other-service", map[string]string{"app": "other"})

    applyNetworkPolicy(t, client, ctx, ns, "policies/egress-restrict.yaml")
    time.Sleep(2 * time.Second)

    // Verify DNS still works (critical test)
    t.Run("DNS_StillWorks", func(t *testing.T) {
        out, _, err := execInPod(client, ns, "myapp", "nslookup", "kubernetes.default.svc.cluster.local")
        require.NoError(t, err, "DNS should still work after egress policy")
        assert.Contains(t, out, "Address")
    })

    // Verify database is reachable
    t.Run("Database_IsReachable", func(t *testing.T) {
        assert.True(t, canConnect(t, client, ctx, ns, "myapp", dbIP, 5432),
            "App should reach postgres on port 5432")
    })

    // Verify other services are blocked
    t.Run("OtherServices_AreBlocked", func(t *testing.T) {
        assert.False(t, canConnect(t, client, ctx, ns, "myapp", otherIP, 8080),
            "App should not reach other services")
    })

    // Verify internet access is blocked
    t.Run("Internet_IsBlocked", func(t *testing.T) {
        _, _, err := execInPod(client, ns, "myapp", "timeout", "3", "curl", "-sf", "https://google.com")
        assert.Error(t, err, "App should not reach the internet")
    })
}

Testing Namespace Isolation Policies

A common pattern: deny all cross-namespace traffic by default, allow specific exceptions:

# Deny all ingress from other namespaces
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-cross-namespace
  namespace: production
spec:
  podSelector: {}  # Applies to all pods in namespace
  policyTypes:
    - Ingress
  ingress:
    - from:
        - podSelector: {}  # Only pods within the same namespace
func TestNamespaceIsolation(t *testing.T) {
    ctx := context.Background()
    client := getClient(t)

    nsA := createNamespaceWithLabel(t, client, "env", "production")
    nsB := createNamespaceWithLabel(t, client, "env", "staging")

    serverIP := deployPodAndGetIP(t, client, ctx, nsA, "server", map[string]string{"app": "server"})

    // Pod within same namespace
    deployPod(t, client, ctx, nsA, "internal-client", map[string]string{"app": "client"})

    // Pod from different namespace
    deployPod(t, client, ctx, nsB, "external-client", map[string]string{"app": "client"})

    applyNamespacePolicy(t, client, ctx, nsA)
    time.Sleep(2 * time.Second)

    // Internal access should work
    assert.True(t, canConnect(t, client, ctx, nsA, "internal-client", serverIP, 8080))

    // Cross-namespace access should be blocked
    assert.False(t, canConnect(t, client, ctx, nsB, "external-client", serverIP, 8080))
}

Automated Policy Validation With netassert

For teams wanting a declarative approach to NetworkPolicy testing:

# netassert.yaml — declarative connectivity matrix
tests:
  - name: frontend-to-backend
    from:
      namespace: default
      pod:
        matchLabels:
          app: frontend
    to:
      namespace: default
      pod:
        matchLabels:
          app: backend
      port: 8080
    expected: allowed

  - name: backend-to-database
    from:
      namespace: default
      pod:
        matchLabels:
          app: backend
    to:
      namespace: default
      pod:
        matchLabels:
          app: postgres
      port: 5432
    expected: allowed

  - name: frontend-to-database-blocked
    from:
      namespace: default
      pod:
        matchLabels:
          app: frontend
    to:
      namespace: default
      pod:
        matchLabels:
          app: postgres
      port: 5432
    expected: denied
# Run netassert
docker run --rm \
  -v "$HOME/.kube/config:/root/.kube/config" \
  -v "$(pwd)/netassert.yaml:/netassert.yaml" \
  controlplane/netassert netassert.yaml

CI Configuration

# .github/workflows/network-policy-tests.yml
name: Network Policy Tests

on:
  pull_request:
    paths:
      - 'policies/**'
      - 'k8s/network/**'

jobs:
  netpol-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Create kind cluster with Calico
        run: |
          kind create cluster --name netpol-ci --config kind-calico-config.yaml
          kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.26.4/manifests/calico.yaml
          kubectl wait --for=condition=ready pod -n kube-system -l k8s-app=calico-node --timeout=120s

      - uses: actions/setup-go@v4

      - name: Run NetworkPolicy tests
        run: go test ./test/netpol/... -v --timeout=10m

      - name: Cleanup
        if: always()
        run: kind delete cluster --name netpol-ci

NetworkPolicy tests are slow (they require real network calls and CNI enforcement) but they catch the security gaps and misconfigurations that static analysis can't. Run them on every change to policy files, not on every commit.


HelpMeTest monitors application behavior in Kubernetes environments, catching failures that network policy changes can cause in production. Start free →

Read more

Start now free