Orchestration

Don’t Let Your AI Agent Run kubectl: Sandboxing LLM-Generated Code on Kubernetes

October 13, 2026 Kubezilla Team 13 min read

Give a coding agent a kubeconfig and you have handed a text generator the keys to your cluster. Anything that can steer the model’s output can steer your cluster too: a README it reads, a GitHub issue, a web page it fetches.

This isn’t hypothetical hand-wringing. Prompt injection sits at the top of the OWASP Top 10 for LLM Applications, and “Excessive Agency” (LLM06) describes exactly this case: an agent holding more permissions than its task needs. An agent that runs kubectl with your admin context is the textbook example.

So don’t let it. Let the agent write code, but run that code somewhere boring, with no credentials, no network and a timer. In this post I build that somewhere on plain Kubernetes, using only features that ship in the box:

  1. A dedicated namespace with Pod Security Admission set to restricted
  2. RBAC that lets the agent create Jobs and read logs, nothing more
  3. A ResourceQuota and LimitRange so a runaway loop can’t eat the cluster
  4. A default-deny NetworkPolicy
  5. A ValidatingAdmissionPolicy that checks what the agent submits

Every config below was applied to a real Kubernetes v1.34.1 API server, and every error message in this post is copied from that run. At the end there’s a script you can run on your laptop with kind.

Step 1: Two Namespaces and Pod Security

The agent and the code it writes should never share a namespace. If they do, a generated script only has to read a ConfigMap or Secret next to it to learn whatever the agent knows. So I use two: agent-system for the agent, agent-sandbox for the code.

# 01-namespaces.yaml
# agent-system  : where the agent itself (and its ServiceAccount) lives.
# agent-sandbox : the only place the agent may run generated code.
apiVersion: v1
kind: Namespace
metadata:
  name: agent-system
---
apiVersion: v1
kind: Namespace
metadata:
  name: agent-sandbox
  labels:
    # Pod Security Admission, built into the API server (stable since v1.25).
    # "restricted" rejects privileged pods, hostPath, hostNetwork, root users,
    # added capabilities, and pods without a seccomp profile.
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: latest
    # Also warn in kubectl output, so violations show up immediately.
    pod-security.kubernetes.io/warn: restricted

Those labels switch on Pod Security Admission with the restricted profile. No webhook, no extra install. To check it, I tried a privileged pod as cluster admin:

$ kubectl run root-shell -n agent-sandbox --image=python:3.13-slim --privileged
The Pod "root-shell" is invalid: spec.containers[0].securityContext.privileged:
Forbidden: disallowed by cluster policy

Note that this blocks admins too, which is what you want for a sandbox namespace.

Step 2: An Identity that can do one thing

The agent gets its own ServiceAccount. Its permissions are a namespaced Role, so outside agent-sandbox it has nothing at all.

# 02-rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: code-agent
  namespace: agent-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role            # namespaced on purpose: no ClusterRole
metadata:
  name: code-runner
  namespace: agent-sandbox
rules:
  # Each piece of generated code is submitted as a Job.
  - apiGroups: ["batch"]
    resources: ["jobs"]
    verbs: ["create", "get", "list", "watch", "delete"]
  # It can watch the resulting pods and read their output.
  - apiGroups: [""]
    resources: ["pods", "pods/log"]
    verbs: ["get", "list", "watch"]
  # Deliberately missing:
  #   secrets        -> no reading credentials
  #   pods/exec      -> no shell into running containers
  #   pods (create)  -> raw pods would skip the Job checks in step 5
  #   roles/bindings -> no granting itself more rights
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: code-agent-can-run-code
  namespace: agent-sandbox
subjects:
  - kind: ServiceAccount
    name: code-agent
    namespace: agent-system   # the SA lives in the other namespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: code-runner

Why Jobs and not Pods? A Job gives me activeDeadlineSeconds, backoffLimit and ttlSecondsAfterFinished for free (Job docs). Removing create pods also means the agent can’t route around the checks I add later.

kubectl auth can-i with --as asks the API server what that identity may do:

$ AGENT=system:serviceaccount:agent-system:code-agent
$ kubectl auth can-i create jobs.batch -n agent-sandbox --as=$AGENT
yes
$ kubectl auth can-i get secrets -n agent-sandbox --as=$AGENT
no
$ kubectl auth can-i create pods --subresource=exec -n agent-sandbox --as=$AGENT
no
$ kubectl auth can-i create jobs.batch -n default --as=$AGENT
no
$ kubectl auth can-i create rolebindings -n agent-sandbox --as=$AGENT
no

Step 3: A Budget it can’t exceed

Agents retry. When a script fails, many agent loops rewrite it and submit again, and a confused agent can do that a few hundred times. OWASP lists this as LLM10: Unbounded Consumption. A ResourceQuota caps the namespace; a LimitRange caps each container and fills in defaults, because generated code almost never sets resources.

# 03-limits.yaml
apiVersion: v1
kind: ResourceQuota
metadata:
  name: sandbox-quota
  namespace: agent-sandbox
spec:
  hard:
    count/jobs.batch: "10"   # at most 10 Job objects at a time
    pods: "10"
    requests.cpu: "2"
    requests.memory: 2Gi
    limits.cpu: "4"
    limits.memory: 4Gi
---
apiVersion: v1
kind: LimitRange
metadata:
  name: sandbox-container-limits
  namespace: agent-sandbox
spec:
  limits:
    - type: Container
      default:            # becomes the limit when none is set
        cpu: 500m
        memory: 256Mi
      defaultRequest:     # becomes the request when none is set
        cpu: 100m
        memory: 64Mi
      max:                # anything bigger is rejected
        cpu: "1"
        memory: 512Mi

I had the agent identity submit the same Job 12 times in a loop. Nine went through on top of the one already there, then the quota kicked in:

jobs.batch "agent-run-j4gn2" is forbidden: exceeded quota: sandbox-quota,
requested: count/jobs.batch=1, used: count/jobs.batch=10, limited: count/jobs.batch=10

A container asking for 8Gi got maximum memory usage per Container is 512Mi, but limit is 8Gi. A container with no resources at all came back from the API server with cpu: 500m / memory: 256Mi limits filled in.

The ttlSecondsAfterFinished on each Job (step 6) deletes finished Jobs, which frees quota for the next run.

Step 4: No way out

Most of the damage an injected prompt can do needs the network: sending your data somewhere, pulling a second-stage payload, or calling the cloud metadata endpoint at 169.254.169.254 for node credentials. A default-deny NetworkPolicy closes all of that.

# 04-network.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all
  namespace: agent-sandbox
spec:
  podSelector: {}      # empty selector = every pod in the namespace
  policyTypes:
    - Ingress
    - Egress
  # No rules listed, so nothing is allowed in either direction (DNS included).
  # Need pip installs? Add one narrow egress rule here, not a blanket allow.

One catch that trips people up: the API server will happily store this object on any cluster, but only a network plugin that implements NetworkPolicy enforces it. If your CNI doesn’t, the policy is decoration. kind’s default plugin, kindnet, implements network policies through the kube-network-policies project, and the job in step 6 tests it by trying to reach example.com. Check that output on your own cluster rather than trusting the YAML.

Step 5: Check what the agent submits

RBAC answers “may the agent create a Job?” It has no opinion on which Job. The agent could still ask for a different image, mount the API token, or run forever. A ValidatingAdmissionPolicy (stable since v1.30) closes that gap with CEL rules evaluated inside the API server.

# 05-admission-policy.yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: agent-job-guardrails
spec:
  failurePolicy: Fail                 # if the policy itself errors, reject
  matchConstraints:
    resourceRules:
      - apiGroups: ["batch"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["jobs"]
  # Only police the agent. Humans and CI are not affected.
  matchConditions:
    - name: only-the-agent
      expression: >-
        request.userInfo.username ==
        'system:serviceaccount:agent-system:code-agent'
  variables:
    - name: pod                       # shorthand for the pod template
      expression: object.spec.template.spec
  validations:
    # 1. No API token in the sandbox, so generated code can't call kubectl.
    - expression: >-
        has(variables.pod.automountServiceAccountToken) &&
        variables.pod.automountServiceAccountToken == false
      message: "agent jobs must set automountServiceAccountToken: false"
    # 2. Hard time limit of 5 minutes or less.
    - expression: >-
        has(object.spec.activeDeadlineSeconds) &&
        object.spec.activeDeadlineSeconds <= 300
      message: "agent jobs must set activeDeadlineSeconds <= 300"
    # 3. Fail once, don't retry six times (the default backoffLimit).
    - expression: >-
        has(object.spec.backoffLimit) && object.spec.backoffLimit == 0
      message: "agent jobs must set backoffLimit: 0"
    # 4. One approved image. Edit this list for your own tools.
    - expression: >-
        variables.pod.containers.all(c,
          c.image in ['python:3.13-slim', 'docker.io/library/python:3.13-slim'])
      message: "agent jobs may only use the python:3.13-slim image"
    # 5. No hostPath volumes (Pod Security blocks these too; belt and braces).
    - expression: >-
        !has(variables.pod.volumes) ||
        variables.pod.volumes.all(v, !has(v.hostPath))
      message: "agent jobs may not mount hostPath volumes"
---
# The binding turns the policy on, for the sandbox namespace only.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: agent-job-guardrails
spec:
  policyName: agent-job-guardrails
  validationActions: ["Deny"]         # reject, don't just audit
  matchResources:
    namespaceSelector:
      matchLabels:
        kubernetes.io/metadata.name: agent-sandbox

I broke a valid Job one field at a time and submitted each version as the agent. Every rule fired with its own message:

Change to a valid JobAPI server response
image: alpine/k8s:1.34.1agent jobs may only use the python:3.13-slim image
activeDeadlineSeconds: 3600agent jobs must set activeDeadlineSeconds <= 300
backoffLimit: 6agent jobs must set backoffLimit: 0
automountServiceAccountToken: trueagent jobs must set automountServiceAccountToken: false

The same bad Job submitted by the cluster admin went through, with only Pod Security warnings. That’s the matchConditions doing its job: the rules are aimed at the agent, not at your platform team.

The gotcha I didn’t expect

My first scripted run applied the policy and then immediately submitted the bad Job as the agent. It was accepted. Run by hand a minute later, the same Job was denied.

A new policy takes a moment to go live after kubectl apply returns. To measure it, I deleted and re-created the policy five times. Each time I submitted the bad Job straight away, and again after two seconds. One of the five immediate attempts got through. All five delayed attempts were denied.

The fix is cheap. Before the agent gets its credentials, prove the policy is live with a server-side dry run:

# Wait until the API server actually rejects the bad job.
until ! kubectl create -f 07-bad-job.yaml --as=$AGENT --dry-run=server \
        >/dev/null 2>&1; do
  echo "waiting for admission policy..."; sleep 1
done

In three more full runs with this loop, it waited at least once every time, and the bad Job was rejected every time. If you deploy guardrails from CI right before starting an agent, put a check like this in the pipeline.

Step 6: Try it on your laptop

You need Docker, kind and kubectl. Save the five files above, plus these two Jobs and the script, in one folder.

This is what a well-behaved agent submits. The Python in args stands in for whatever the model generated; your agent’s tool code owns everything around it.

That split is the design choice that matters most. In your agent’s tool definition, the model should only fill in one string: the code. Your tool function drops that string into a fixed Job template, submits it with the code-agent token, waits for the Job to finish, and hands the pod logs back to the model as the tool result. The model never sees YAML, never picks an image and never touches a kubeconfig. If it gets prompt-injected into writing something nasty, the worst case is a script that runs for two minutes as user nobody, in a namespace with no network and no secrets. The admission policy is there for the day someone changes the tool function and forgets one of these fields.

# 06-good-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  generateName: agent-run-      # unique name per run
  namespace: agent-sandbox
spec:
  backoffLimit: 0               # run once
  activeDeadlineSeconds: 120    # killed after 2 minutes, whatever happens
  ttlSecondsAfterFinished: 300  # deleted 5 minutes after it finishes
  template:
    spec:
      restartPolicy: Never
      automountServiceAccountToken: false   # no API credentials in the pod
      securityContext:
        runAsNonRoot: true
        runAsUser: 65534        # "nobody"
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: run
          image: python:3.13-slim
          command: ["python", "-c"]
          args:
            - |
              # --- LLM-generated code goes here ---
              import math, urllib.request
              print("primes:", [n for n in range(2, 50)
                    if all(n % d for d in range(2, int(math.sqrt(n)) + 1))])
              # The agent "decided" to phone home. The NetworkPolicy says no.
              try:
                  urllib.request.urlopen("https://example.com", timeout=3)
                  print("network: OPEN (bad)")
              except Exception as e:
                  print("network: blocked ->", type(e).__name__)
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          resources:
            limits:
              cpu: 500m
              memory: 128Mi

This Job passed every check in this post: no Pod Security warnings, accepted by the policy. Here’s what a prompt-injected agent might send instead:

# 07-bad-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: agent-run-evil
  namespace: agent-sandbox
spec:                        # no deadline, default retries
  template:
    spec:
      restartPolicy: Never   # API token mounted by default
      containers:
        - name: run
          image: alpine/k8s:1.34.1          # ships with kubectl
          command: ["sh", "-c", "kubectl get secrets -A"]
      volumes:
        - name: host
          hostPath:
            path: /                         # the node's whole filesystem

And the script that ties it together:

#!/usr/bin/env bash
# demo.sh: lock down where an AI agent runs code, then try to break it.
set -euo pipefail
AGENT=system:serviceaccount:agent-system:code-agent   # the agent's identity

# 1. A throwaway cluster. kind's default CNI enforces NetworkPolicy.
kind create cluster --name agent-lab

# 2. Guardrails.
for f in 01-namespaces 02-rbac 03-limits 04-network 05-admission-policy; do
  kubectl apply -f "$f.yaml"
done

# Don't let the agent in until the admission policy is provably live.
until ! kubectl create -f 07-bad-job.yaml --as=$AGENT --dry-run=server \
        >/dev/null 2>&1; do
  echo "waiting for admission policy..."; sleep 1
done

# 3. What can the agent do? (--as impersonates its ServiceAccount)
for check in "create jobs.batch -n agent-sandbox" \
             "get secrets -n agent-sandbox" \
             "create pods --subresource=exec -n agent-sandbox" \
             "create jobs.batch -n default"; do
  printf '%-48s %s\n' "$check" "$(kubectl auth can-i $check --as=$AGENT)"
done

# 4. The injected job. Expect: denied.
kubectl create -f 07-bad-job.yaml --as=$AGENT || echo ">> rejected, as intended"

# 5. The good job. Expect: runs, prints primes, network blocked.
JOB=$(kubectl create -f 06-good-job.yaml --as=$AGENT -o name)
kubectl wait -n agent-sandbox --for=condition=complete "$JOB" --timeout=180s
kubectl logs -n agent-sandbox "$JOB"

# Clean up: kind delete cluster --name agent-lab

Steps 2 to 4 of this script produced this output against the v1.34.1 API server:

waiting for admission policy...
create jobs.batch -n agent-sandbox               yes
get secrets -n agent-sandbox                     no
create pods --subresource=exec -n agent-sandbox  no
create jobs.batch -n default                     no
The jobs "agent-run-evil" is invalid: : ValidatingAdmissionPolicy
'agent-job-guardrails' with binding 'agent-job-guardrails' denied request:
agent jobs must set automountServiceAccountToken: false
>> rejected, as intended

Step 5 prints the job’s logs. The primes line is deterministic: primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]. The second line is the one that matters. If it says network: blocked, your NetworkPolicy is enforced. If it says network: OPEN (bad), your CNI is ignoring it.

What this doesn’t cover

The sandbox pods still share the node’s Linux kernel with everything else on that node. Pod Security and the RuntimeDefault seccomp profile shrink the attack surface, but a kernel bug is still a way out. For code you truly don’t trust, add a second kernel boundary.

gVisor runs each pod against a user-space kernel. Once the nodes have runsc installed, it’s one object plus one field:

# Requires gVisor (runsc) installed and configured in containerd on the nodes.
apiVersion: node.k8s.io/v1
kind: RuntimeClass
metadata:
  name: gvisor
handler: runsc
# Then in the Job's pod template:  runtimeClassName: gvisor
# And a sixth policy rule:  variables.pod.runtimeClassName == 'gvisor'

I haven’t tested gVisor for this post, because it needs node-level setup that a stock kind cluster doesn’t have. The same goes for Agent Sandbox, a SIG Apps project the Kubernetes blog covered in March 2026. It adds a Sandbox resource (agents.x-k8s.io/v1beta1) for long-running, stateful agent workloads and hands isolation to runtimes like gVisor or Kata Containers. If your agents need a persistent workspace rather than one-shot Jobs, start there. The namespace, RBAC, quota and network rules above still apply underneath it.

Two smaller gaps. The quota counts Jobs, not tokens, so a model can still burn your API budget on its side; cap that in the agent itself. And everything here protects the cluster from the code, not the agent’s own credentials. Keep the code-agent token out of prompts and logs, because whoever holds it gets exactly the rights in step 2.

If you take one thing from this post: the agent writes code, Kubernetes runs it, and the agent never holds kubectl with anything more than create jobs in one namespace.

Sources

Test environment: kube-apiserver and kubectl v1.34.1 with etcd, from the controller-tools envtest release, RBAC enabled.

2 thoughts on “Don’t Let Your AI Agent Run kubectl: Sandboxing LLM-Generated Code on Kubernetes”

Leave a comment