DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Docker Security: 6 Practical Labs From Audit to AI Protection
  • Revolutionizing Kubernetes With K8sGPT: A Deep Dive Into AI-Driven Insights
  • Dynatrace Perform: Day Two
  • Containment Is a Feature: Sandboxing, Egress Control, and Provenance for Autonomous Agents

Trending

  • Using Middleware in LangChain: Recovering From Tool Failures
  • Bolting an LLM Onto a System That Can't Afford to Be Wrong
  • Should an AI Agent Have Write Access to Your AWS Account?
  • How (and Why) to Build Dynamic Data Pipelines

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Security
  4. Hands-On: Build a Least-Privilege Sandbox for AI Agents on Kubernetes

Hands-On: Build a Least-Privilege Sandbox for AI Agents on Kubernetes

Build a least-privilege sandbox for AI agents on Kubernetes: audience-bound tokens, TokenReview-verified broker, action budgets, default-deny egress.

By 
Sai Prasad Veluru
·
Nov. 30, 26 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
159 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

The Problem in One Section

A production AI agent is a process that reads data, calls tools, and writes things — at machine speed, along action sequences nobody enumerated in advance. When we put that process on Kubernetes, the instinct is to hand it a service account with broad permissions and move on. The result is a principal with standing access that nobody reviews and a blast radius nobody scoped.

Least privilege for agents is not a philosophy. It is a set of mechanisms, and Kubernetes already ships most of them: short-lived audience-bound tokens, RBAC, admission-enforced pod security, and network policy. In this lab, those mechanisms are five concrete enforcement points: projected tokens, TokenReview verification, the broker allowlist, the publish budget, and NetworkPolicy. The missing piece in most deployments is not the primitive — it is the pattern that wires them together. This tutorial builds that pattern as a reference implementation you can run in about 30–45 minutes, then tests every control the way an adversary would probe it.

Three things change when the workload is an agent instead of a controller. First, action sequences are non-deterministic: you can write an RBAC policy for a controller because it does the same thing every time, but an agent's next action depends on model output, tool results, and conversation state, so "allow exactly what it needs" is a moving target. Second, tools are the real attack surface: an agent with a dozen tools is a dozen small programs, and most teams authorize the agent once for all of them — read access to private data plus a publish-capable tool, combined by an actor that sees no reason not to, is the canonical failure shape. Third, identities outlive their tasks: tokens issued for a ten-minute job become standing access when the session never ends. I designed the lab below around exactly these three properties.

Nothing here is a production system. I built it as a lab, and it is labeled honestly as one. The point is that each mechanism in it is real, each boundary is enforced, and each test has an expected result you can verify with your own eyes.

What You Will Learn

By the end of this tutorial, you will be able to:

  • Issue short-lived, audience-bound projected service-account tokens for each agent identity instead of handing agents long-lived credentials.
  • Verify presented tokens through the Kubernetes TokenReview API — letting the API server, not local JWT decoding, decide whether a token is real and correctly scoped.
  • Separate read and write authority behind a trusted tool broker, so agents hold identity but no direct Kubernetes API permissions.
  • Enforce an action budget that halts a runaway agent after a fixed number of mutations.
  • Lock agent egress with NetworkPolicy so the only reachable destinations are DNS and the broker.
  • Read the broker's JSON audit trail to see exactly what each identity attempted and what the sandbox allowed.

What You Will Build

Two agent pods, agent-reader and agent-writer, each carrying a short-lived projected token for its own identity. They get no Kubernetes API permissions at all. Their only capability is talking to a trusted tool-broker service — the single write path in the system. The broker verifies every presented token through the Kubernetes TokenReview API, authorizes the caller against an allowlist, enforces a per-identity publish budget, and writes only to one named ConfigMap. NetworkPolicy then shrinks the blast radius further: agents can reach the broker and DNS, and nothing else.

Component Identity Can do Cannot do
agent-reader pod agent-reader SA, projected token (aud agent-tools, 1h) Read the internal note via the broker Publish; touch the K8s API; reach the internet
agent-writer pod agent-writer SA, projected token (aud agent-tools, 1h) Publish via the broker (budget: 3) Read the note; touch the K8s API; reach the internet
tool-broker tool-broker SA Create TokenReviews; get/patch/update the agent-output ConfigMap Everything else

Architecture: two agent identities, one trusted broker, one writable object.

Figure 1 — Architecture: two agent identities, one trusted broker, one writable object.


Guardrail checklists and architecture essays describe this pattern; the tutorial below implements it end-to-end as runnable code you can break and re-run. Most hand-rolled agent identity schemes stumble on the same step — verifying the token. This implementation gets it right by design: the broker never parses the JWT itself, and the API server, through TokenReview, is the only party that can vouch for a token's validity, identity, and audience.

The trust boundary is the broker. The broker never decodes or verifies the JWT itself — that is the classic mistake. Verifying a signature locally only tells you who signed the token; only the API server can tell you whether it is currently valid, issued to that identity, and scoped to your audience. Re-implementing any of that yourself is how confused-deputy holes are born.

Prerequisites

  • A Kubernetes cluster with a policy-enforcing CNI such as Calico or Cilium. This matters: kind's default CNI does not enforce NetworkPolicy, so the egress test will not fail there. minikube start --cni=calico is a known-good starting point. An existing cluster with Calico or Cilium works too.
  • kubectl, and kustomize (or kubectl 1.14+, which embeds it).
  • About 30–45 minutes. Python 3.12 container images are pulled from the public registry, so the cluster nodes need registry access.

Step 1: The Namespace and the Two Identities

Everything lives in agent-lab. The namespace carries the restricted Pod Security Standard on all three tracks — enforce, audit, warn — so any pod that does not meet the restricted profile is rejected outright:

YAML
 
apiVersion: v1
kind: Namespace
metadata:
  name: agent-lab
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: latest
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/audit-version: latest
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/warn-version: latest


The identities are plain ServiceAccounts with no roles attached. That is a deliberate choice: I made the projected tokens, not RBAC grants, the source of their authority.

YAML
 
apiVersion: v1
kind: ServiceAccount
metadata:
  name: agent-reader
  namespace: agent-lab
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: agent-writer
  namespace: agent-lab
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: tool-broker
  namespace: agent-lab


Step 2: Give the Broker — and Only the Broker — Scoped API Rights

The broker needs exactly two capabilities from the Kubernetes API, and both are scoped to the minimum:

  1. create on tokenreviews (a ClusterRole, since TokenReview is cluster-scoped) so it can ask the API server to verify agent tokens.
  2. get/patch/update on the single named ConfigMap agent-output, so it can record publishes.

The agent identities receive nothing:

YAML
 
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: agent-lab-tokenreview
rules:
- apiGroups: ["authentication.k8s.io"]
  resources: ["tokenreviews"]
  verbs: ["create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: agent-lab-broker-tokenreview
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: agent-lab-tokenreview
subjects:
- kind: ServiceAccount
  name: tool-broker
  namespace: agent-lab
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: agent-lab-output-writer
  namespace: agent-lab
rules:
- apiGroups: [""]
  resources: ["configmaps"]
  resourceNames: ["agent-output"]
  verbs: ["get", "patch", "update"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: agent-lab-broker-output-writer
  namespace: agent-lab
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: agent-lab-output-writer
subjects:
- kind: ServiceAccount
  name: tool-broker
  namespace: agent-lab


Note the resourceNames restriction. A Role that allows patching "ConfigMaps" is a very different thing from a Role that allows patching the agent-output ConfigMap. Least privilege is always measured against the specific resource.

Step 3: The Broker — TokenReview, Allowlist, Budget, Audit Log

The broker is a stdlib-only Python service (no dependencies to audit, no framework to misconfigure). Read it carefully; every control in the lab is implemented here:

  • Authentication: the presented bearer token is sent to POST /apis/authentication.k8s.io/v1/tokenreviews with spec.audiences: ["agent-tools"], using the broker pod's own in-cluster credentials. The broker then checks status.authenticatedand that status.audiences contains agent-tools — the TokenReview API docs call this out explicitly, because a token valid only against the API server's own audience would otherwise pass.
  • Authorization: reader may GET /artifacts/internal-note; writer may POST /publish. The wrong pairing returns 403; a missing or bad token returns 401.
  • Budget: three successful publishes per identity per broker process; the fourth returns 429. The counter is in memory on purpose — the code says so in a comment, and the production section below says what to use instead.
  • Audit: one JSON line per request — timestamp, request id, username, action, status. The token is never logged. That rule matters more than it looks: the most common way identity systems leak is through their own logs.
  • Inputs: JSON body only, 100 KiB cap, non-empty title/body strings with length limits.
Python
 
#!/usr/bin/env python3
"""tool-broker -- the only write path for agent pods in agent-lab."""

import json
import os
import ssl
import time
import uuid
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

NAMESPACE = "agent-lab"
EXPECTED_AUDIENCE = "agent-tools"
READER = "system:serviceaccount:%s:agent-reader" % NAMESPACE
WRITER = "system:serviceaccount:%s:agent-writer" % NAMESPACE

NOTE_PATH = os.environ.get("NOTE_PATH", "/data/internal-note.txt")
OUTPUT_NAME = os.environ.get("OUTPUT_CONFIGMAP", "agent-output")
PUBLISH_BUDGET = 3
MAX_BODY_BYTES = 100 * 1024
LISTEN_PORT = int(os.environ.get("PORT", "8080"))
SA_DIR = "/var/run/secrets/kubernetes.io/serviceaccount"


def _k8s_request(method, path, body=None, content_type="application/json"):
    # Use the in-cluster DNS name so TLS hostname verification stays on.
    host = os.environ.get("KUBERNETES_SERVICE_DNS", "kubernetes.default.svc")
    port = os.environ.get("KUBERNETES_SERVICE_PORT", "443")
    with open(os.path.join(SA_DIR, "token"), "r", encoding="utf-8") as fh:
        sa_token = fh.read().strip()
    with open(os.path.join(SA_DIR, "ca.crt"), "rb") as fh:
        ca_data = fh.read()
    url = "https://%s:%s%s" % (host, port, path)
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(
        url, data=data, method=method,
        headers={"Content-Type": content_type,
                 "Authorization": "Bearer %s" % sa_token})
    ctx = ssl.create_default_context(cadata=ca_data)  # chain + hostname verified
    try:
        with urllib.request.urlopen(req, context=ctx, timeout=10) as resp:
            return resp.status, json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        payload = exc.read().decode("utf-8", "replace")
        try:
            return exc.code, json.loads(payload)
        except ValueError:
            return exc.code, {"error": payload}


def verify_token(token):
    review = {
        "apiVersion": "authentication.k8s.io/v1",
        "kind": "TokenReview",
        "spec": {"token": token, "audiences": [EXPECTED_AUDIENCE]},
    }
    status_code, payload = _k8s_request(
        "POST", "/apis/authentication.k8s.io/v1/tokenreviews", review)
    if status_code not in (200, 201, 202):
        return None
    status = payload.get("status", {})
    if not status.get("authenticated"):
        return None
    if EXPECTED_AUDIENCE not in status.get("audiences", []):
        return None
    return status.get("user", {}).get("username")


def record_publish(title, body):
    patch = {"data": {"lastTitle": title, "lastBody": body}}
    status_code, _ = _k8s_request(
        "PATCH",
        "/api/v1/namespaces/%s/configmaps/%s" % (NAMESPACE, OUTPUT_NAME),
        patch,
        content_type="application/merge-patch+json",
    )
    if status_code not in (200, 201, 202):
        raise RuntimeError("ConfigMap patch failed with status %s"
                           % status_code)


class BrokerHandler(BaseHTTPRequestHandler):
    server_version = "tool-broker/1.0"
    budgets = {}  # in-memory on purpose; production needs durable state

    def log_message(self, *args):
        pass  # silence default access logging

    def log_json(self, username, action, status, extra=None):
        record = {
            "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "rid": getattr(self, "rid", "-"),
            "username": username,
            "action": action,
            "status": status,
        }
        if extra:
            record.update(extra)
        print(json.dumps(record), flush=True)  # the token is never logged

    def _respond(self, status, payload, username, action, extra=None):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)
        self.log_json(username, action, status, extra)

    def _bearer_token(self):
        auth = self.headers.get("Authorization", "")
        scheme, _, value = auth.partition(" ")
        if scheme.lower() != "bearer" or not value:
            return None
        return value

    def _authenticate(self, action):
        token = self._bearer_token()
        if not token:
            self._respond(401, {"error": "missing bearer token"},
                          "anonymous", action)
            return None
        try:
            username = verify_token(token)
        except Exception as exc:
            self._respond(502, {"error": "identity verification unavailable"},
                          "anonymous", action, {"detail": str(exc)})
            return None
        if not username:
            self._respond(401, {"error": "invalid or mis-scoped token"},
                          "anonymous", action)
            return None
        return username

    def do_GET(self):
        self.rid = uuid.uuid4().hex[:12]
        path = self.path.split("?", 1)[0]
        action = "GET %s" % path
        username = self._authenticate(action)
        if not username:
            return
        if path == "/artifacts/internal-note":
            if username != READER:
                self._respond(403, {"error": "forbidden"}, username, action)
                return
            try:
                with open(NOTE_PATH, "r", encoding="utf-8") as fh:
                    note = fh.read()
            except OSError as exc:
                self._respond(500, {"error": "note unavailable"},
                              username, action, {"detail": str(exc)})
                return
            self._respond(200, {"note": note}, username, action)
            return
        self._respond(404, {"error": "not found"}, username, action)

    def do_POST(self):
        self.rid = uuid.uuid4().hex[:12]
        path = self.path.split("?", 1)[0]
        action = "POST %s" % path
        username = self._authenticate(action)
        if not username:
            return
        if path != "/publish":
            self._respond(404, {"error": "not found"}, username, action)
            return
        if username != WRITER:
            self._respond(403, {"error": "forbidden"}, username, action)
            return
        length = self.headers.get("Content-Length")
        try:
            n = int(length) if length else 0
        except ValueError:
            n = 0
        if n > MAX_BODY_BYTES:
            self._respond(413, {"error": "body too large"}, username, action)
            return
        raw = self.rfile.read(n) if n else b""
        try:
            payload = json.loads(raw.decode("utf-8")) if raw else {}
        except (UnicodeDecodeError, ValueError):
            self._respond(400, {"error": "body must be JSON"},
                          username, action)
            return
        title = payload.get("title")
        body = payload.get("body")
        if (not isinstance(title, str) or not isinstance(body, str)
                or not title or not body):
            self._respond(400, {"error": "need non-empty 'title' and 'body' "
                                         "strings"}, username, action)
            return
        if len(title) > 2000 or len(body) > 100000:
            self._respond(400, {"error": "title/body exceed length limits"},
                          username, action)
            return
        used = BrokerHandler.budgets.get(username, 0)
        if used >= PUBLISH_BUDGET:
            self._respond(429, {"error": "publish budget exhausted"},
                          username, action,
                          {"used": used, "budget": PUBLISH_BUDGET})
            return
        try:
            record_publish(title, body)
        except Exception as exc:
            self._respond(500, {"error": "publish failed"},
                          username, action, {"detail": str(exc)})
            return
        BrokerHandler.budgets[username] = used + 1
        self._respond(202, {"published": True, "budget_used": used + 1,
                            "budget": PUBLISH_BUDGET},
                      username, action, {"title": title})


def main():
    server = HTTPServer(("0.0.0.0", LISTEN_PORT), BrokerHandler)
    print(json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
                      "event": "broker listening", "port": LISTEN_PORT}),
          flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()


The broker runs as a Deployment with its code and the internal note mounted from ConfigMaps (read-only), a ClusterIP Service on port 8080, and the same restricted hardening as everything else in this lab. Its own service account token is automounted — the broker is a trusted first-party component and needs its identity to call the API server.

The demo data the broker serves is fictional, and it says so in the file itself:

YAML
 
apiVersion: v1
kind: ConfigMap
metadata:
  name: internal-note
  namespace: agent-lab
data:
  internal-note.txt: |
    DEMO CONTENT — this note is fictional and exists only for the lab.
    ...


Step 4: The Agent Pods — Projected Tokens, Nothing Else

Each agent pod gets exactly one credential: a projected ServiceAccount token with audience: agent-tools and a one-hour lifetime, mounted at /var/run/secrets/agent/token. The in-cluster token is not automounted (automountServiceAccountToken: false), which is the whole point — kubectl auth can-i will confirm these identities cannot touch the API at all.

YAML
 
spec:
  serviceAccountName: agent-reader
  automountServiceAccountToken: false
  ...
  volumes:
  - name: agent-token
    projected:
      sources:
      - serviceAccountToken:
          audience: agent-tools
          expirationSeconds: 3600
          path: token


Every container in the lab — broker and agents — runs with the same restricted-compatible profile: non-root user, seccompProfile.type: RuntimeDefault, allowPrivilegeEscalation: false, all capabilities dropped, read-only root filesystem, PYTHONDONTWRITEBYTECODE=1 so the interpreter never tries to write .pyc files.

A tiny caller.py (stdlib only) rides along in each agent pod via a ConfigMap. It reads the projected token fresh from disk on every call — projected tokens rotate, so caching them is a bug — and performs the requested action against the broker:

Python
 
def _call(method, path, payload=None):
    with open(TOKEN_PATH, "r", encoding="utf-8") as fh:
        token = fh.read().strip()          # fresh read every call
    req = urllib.request.Request(
        BROKER_URL + path, data=data, method=method,
        headers={"Authorization": "Bearer %s" % token,
                 "Content-Type": "application/json"})
    ...

# usage inside the pod:
#   python3 /app/caller.py read
#   python3 /app/caller.py publish "demo title" "demo body"


Step 5: Shrink the Network Blast Radius

Identity controls what an agent may ask for. NetworkPolicy controls what it can reach. Agents accept no inbound traffic at all and may only talk to the broker on port 8080, plus DNS in kube-system:

YAML
 
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: agent-default-deny
  namespace: agent-lab
spec:
  podSelector:
    matchLabels:
      agent-lab/component: agent
  policyTypes: [Ingress, Egress]
  ingress: []  # deny all inbound traffic to agent pods
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: tool-broker
    ports:
    - protocol: TCP
      port: 8080
  - to:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: kube-system
      podSelector: {}
    ports:
    - protocol: UDP
      port: 53
    - protocol: TCP
      port: 53


A second policy locks the broker's ingress to agent pods on port 8080. This is the control that turns "the agent decided to exfiltrate" into "the connection timed out."

Step 6: Run the Tests

How this was verified. No live cluster was used during writing: the broker's authorization and budget logic was checked with an automated test suite that stubs the TokenReview call and the ConfigMap patch: missing token → 401, bad token → 401, reader read → 200, reader publish → 403, writer read → 403, three publishes → 202 each, fourth publish → 429, with exactly three patches recorded (10/10 checks passed). The cluster steps below are your live run of that same matrix; this tutorial does not claim an observed live-cluster execution.

Deploy everything with kustomize, which generates the ConfigMaps from the Python files:

Shell
 
cd agent-security-lab
kubectl apply -k .
kubectl rollout status deploy/tool-broker -n agent-lab
kubectl get pods -n agent-lab


Now probe the sandbox the way an adversary — or a confused agent — would.

1. The reader can read (expect 200):

Shell
 
kubectl exec -n agent-lab agent-reader -- python3 /app/caller.py read
HTTP
 
HTTP 200
{"note": "DEMO CONTENT — this note is fictional and exists only for the lab.\n..."}


2. The reader cannot publish (expect 403):

Shell
 
kubectl exec -n agent-lab agent-reader -- python3 /app/caller.py publish "x" "y"
HTTP
 
HTTP 403
{"error": "forbidden"}


3. The writer cannot read (expect 403):

Shell
 
kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py read
HTTP
 
HTTP 403
{"error": "forbidden"}


4. The writer can publish — three times — and the ConfigMap shows it:

Shell
 
kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-1" "first write"
kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-2" "second write"
kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-3" "third write"
kubectl get configmap agent-output -n agent-lab -o jsonpath='{.data.lastTitle}{"\n"}{.data.lastBody}{"\n"}'
HTTP
 
HTTP 202
{"published": true, "budget_used": 1, "budget": 3}
HTTP 202
{"published": true, "budget_used": 2, "budget": 3}
HTTP 202
{"published": true, "budget_used": 3, "budget": 3}
demo-3
third write


5. The fourth publish is refused (expect 429):

Shell
 
kubectl exec -n agent-lab agent-writer -- python3 /app/caller.py publish "demo-4" "over budget"
HTTP
 
HTTP 429
{"error": "publish budget exhausted", "used": 3, "budget": 3}


This is the containment control working as designed: a runaway agent gets exactly three mutations and then stops, no matter what it believes it should do next.

6. The agent identities have no Kubernetes API access:

Shell
 
kubectl auth can-i get secrets --as=system:serviceaccount:agent-lab:agent-reader -n agent-lab
kubectl auth can-i get configmaps --as=system:serviceaccount:agent-lab:agent-writer -n agent-lab
Plain Text
 
no
no


7. Every request leaves one audit line, and tokens never appear in logs:

Shell
 
kubectl logs -n agent-lab deploy/tool-broker | tail -4
JSON
 
...
{"ts": "2026-10-14T19:40:02Z", "rid": "a3f19c2d81be", "username": "system:serviceaccount:agent-lab:agent-writer", "action": "POST /publish", "status": 202, "title": "demo-3"}
{"ts": "2026-10-14T19:40:11Z", "rid": "2c1e4b9f30d2", "username": "system:serviceaccount:agent-lab:agent-writer", "action": "POST /publish", "status": 429, "used": 3, "budget": 3}


8. External egress fails on a policy-enforcing CNI (CNI-dependent test):

Shell
 
kubectl exec -n agent-lab agent-reader -- timeout 8 python3 -c \
  "import socket; socket.create_connection(('1.1.1.1', 443), timeout=5)"
Python
 
Traceback (most recent call last):
  ...
TimeoutError: timed out


On kind's default CNI, this test will succeed — that is the prerequisite warning, not a lab bug. The policy is applied correctly; kindnetd simply does not enforce it.

Cleanup:

Shell
 
kubectl delete namespace agent-lab


The broker's decision path, drawn from broker.py, is worth keeping in front of you while you read the tests above — every request walks the same corridor, and every rejection is a gate with a code:

The broker's decision path for every request: token check, TokenReview, allowlist, budget, and one audit line for every response.

Figure 2 — The broker's decision path for every request.


Troubleshooting

External-egress test still succeeds. Symptom: test 8 reaches 1.1.1.1:443 instead of timing out. Cause: the cluster's CNI does not enforce NetworkPolicy — kind's default CNI (kindnetd) installs the policy objects but never applies them. Fix: run the lab on a policy-enforcing CNI such as Calico or Cilium; minikube start --cni=calico is a known-good starting point.

Every broker call returns 401 or 502. Symptom: the caller gets {"error": "invalid or mis-scoped token"}, or the broker answers 502 identity verification unavailable. Cause: the broker cannot reach the TokenReview endpoint, or the presented token is not meant for this service. Fix: check kubectl logs -n agent-lab deploy/tool-broker for the underlying error; confirm the ClusterRoleBinding grants the broker's ServiceAccount create on tokenreviews; and confirm the projected volume's audience is exactly agent-tools in both agent pod specs.

Agent pods stuck Pending or rejected at admission. Symptom: kubectl get pods -n agent-lab shows Pending, or kubectl describe pod reports a forbidden admission error. Cause: the agent-lab namespace enforces the restricted Pod Security Standard, and any pod that violates it is rejected. Fix: confirm each pod's securityContext sets runAsNonRoot: true, seccompProfile.type: RuntimeDefault, allowPrivilegeEscalation: false, and capabilities.drop: ["ALL"] — the manifests in this lab already do.

Publish returns 500. Symptom: {"error": "publish failed"} on a POST the allowlist should permit. Cause: the broker's own Role does not actually permit the write. Fix: confirm the agent-lab-output-writer RoleBinding exists in agent-lab and its resourceNames contains exactly agent-output; the broker patches one named ConfigMap and nothing else, so a renamed or missing ConfigMap fails closed.

Taking This to Production: What the Lab Deliberately Leaves Out

The lab's budget counter lives in broker memory; a restart resets it. Production budgets must be durable — etcd, Redis, or a database with atomic increments — and scoped per task, not per process. The audit lines go to stdout; production ships them to a tamper-evident store the agent cannot reach, with alerts on the 429s and 403s, not just retention.

Three more things a real deployment adds. First, admission policy: the pattern in this lab should be enforced, not suggested. A policy engine such as Kyverno or OPA Gatekeeper can require automountServiceAccountToken: false, projected tokens with a sane expirationSeconds, and the restricted security context on every agent pod — so the sandbox is the default, not an option somebody remembers to apply. Second, per-task pods: long-lived agent identities accumulate authority. Minting a fresh pod and identity per task, with the token expiring with the task, bounds every session the way the lab bounds every publish. Third, human approval for high-risk actions: the broker's allowlist is static here. In production, the dangerous subset of tools — anything that writes, deletes, or crosses a trust boundary — sits behind an approval step or a policy check, not just an allowlist entry.

And one response mechanism the lab does not demonstrate, but every deployment needs: a kill switch with quarantine-first semantics. When monitoring flags anomalous agent behavior — unusual data access patterns, write volume spikes, calls to unexpected destinations — the response should be automatic containment: revoke the session tokens, freeze the write identity, preserve the audit trail. You can always re-issue access after review; you cannot un-publish what a runaway agent already sent. The budget 429s and the 403s in the broker logs are the signals this switch consumes. And the internal note's stand-in for a secret store should be exactly that: a secret store with dynamic, short-lived credentials, never a ConfigMap.

Trade-Offs, Stated Plainly

This pattern is friction, and friction has a price. Per-agent projected tokens mean token plumbing everywhere a caller touches. A broker in front of every tool is a new service to operate, scale, and secure — and it becomes the most attractive target in the system, which is why its own RBAC is the tightest in the lab. Budgets turn "the agent did something wrong a thousand times" into "it did it three times and stopped," but they also turn a legitimate long task into a 429 that needs a human to raise the ceiling. Default-deny egress breaks the first integration that assumed the open internet, and the person who allowlists the fix had better write down why.

The alternative is standing access for non-deterministic actors, reviewed never and rotated never, with no containment when the run goes sideways. That is not a trade-off; that is the absence of one. The mechanisms in this lab — verified identity, separated authorities, budgets, egress that defaults to no, audit trails that assume the actor will surprise you — are the price of running agents in production. Pay it deliberately, or pay it later in incident reviews.

Conclusion

Agents are principals now, but Kubernetes still provisions most of them like interns on their first day: broad access, issued once, reviewed never. This lab shows the other shape — short-lived audience-bound identity verified through TokenReview, a trusted broker as the only write path, allow-listed tools, action budgets, and a network that defaults to no — as running code you can test in about 30–45 minutes. None of these mechanisms is new. What the lab adds is their composition in one request path — TokenReview, then allowlist, then budget, then a single named write, then an audit line — applied to the workloads that need it most.

The complete lab — every manifest, the kustomize setup, and both Python files — is printed in full in this article and its appendix, so you can reproduce it exactly; only the stubbed broker unit tests live outside it, and their results are quoted in Step 6. Run it, break it, and then decide which controls your agents are missing.

References

  • ServiceAccount token volume projection – projected tokens, audiences, and expirationSeconds
  • TokenReview API reference – authentication.k8s.io/v1 request/response shapes and audience validation
  • NetworkPolicy – ingress/egress rules and the policy-enforcing CNI requirement
  • Pod Security Standards – the restricted profile enforced on the lab namespace

Appendix: The Remaining Manifests

The walkthrough above prints the namespace, the service accounts, the RBAC, the demo data ConfigMap, the agent NetworkPolicy, and the broker code in full. The rest of the lab — the pieces the steps describe but do not print — is reproduced here, copied verbatim, so the article is self-contained.

The broker's Deployment and Service:

YAML
 
# The tool-broker is the only write path in the lab. It is a trusted
# first-party component: its own service account token is automounted so it
# can call the TokenReview API and patch the single "agent-output"
# ConfigMap -- nothing else.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: tool-broker
  namespace: agent-lab
spec:
  replicas: 1
  selector:
    matchLabels:
      app: tool-broker
  template:
    metadata:
      labels:
        app: tool-broker
    spec:
      serviceAccountName: tool-broker
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: broker
        image: python:3.12-alpine
        command: ["python3", "/app/broker.py"]
        ports:
        - name: http
          containerPort: 8080
        env:
        - name: PYTHONDONTWRITEBYTECODE
          value: "1"
        - name: NOTE_PATH
          value: /data/internal-note.txt
        volumeMounts:
        - name: code
          mountPath: /app
          readOnly: true
        - name: note
          mountPath: /data
          readOnly: true
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            drop: ["ALL"]
          readOnlyRootFilesystem: true
          runAsNonRoot: true
      volumes:
      - name: code
        configMap:
          name: broker-code
          items:
          - key: broker.py
            path: broker.py
          defaultMode: 0444
      - name: note
        configMap:
          name: internal-note
          items:
          - key: internal-note.txt
            path: internal-note.txt
          defaultMode: 0444
---
apiVersion: v1
kind: Service
metadata:
  name: tool-broker
  namespace: agent-lab
spec:
  type: ClusterIP
  selector:
    app: tool-broker
  ports:
  - name: http
    port: 8080
    targetPort: 8080


The two agent pods in full:

YAML
 
# Two agent pods. Each carries a short-lived, audience-bound projected
# token (audience "agent-tools", 1 hour) for its own identity, mounted at
# /var/run/secrets/agent/token. The in-cluster service account token is
# NOT automounted, so the pods cannot talk to the Kubernetes API at all.
apiVersion: v1
kind: Pod
metadata:
  name: agent-reader
  namespace: agent-lab
  labels:
    agent-lab/component: agent
    agent-lab/role: reader
spec:
  serviceAccountName: agent-reader
  automountServiceAccountToken: false
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    runAsGroup: 10001
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: agent
    image: python:3.12-alpine
    command: ["tail", "-f", "/dev/null"]
    env:
    - name: PYTHONDONTWRITEBYTECODE
      value: "1"
    - name: AGENT_ROLE
      value: reader
    - name: AGENT_TOKEN_PATH
      value: /var/run/secrets/agent/token
    - name: BROKER_URL
      value: "http://tool-broker:8080"
    volumeMounts:
    - name: agent-token
      mountPath: /var/run/secrets/agent
      readOnly: true
    - name: caller-code
      mountPath: /app
      readOnly: true
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]
      readOnlyRootFilesystem: true
      runAsNonRoot: true
  volumes:
  - name: agent-token
    projected:
      sources:
      - serviceAccountToken:
          audience: agent-tools
          expirationSeconds: 3600
          path: token
  - name: caller-code
    configMap:
      name: caller-code
      items:
      - key: caller.py
        path: caller.py
      defaultMode: 0444
---
apiVersion: v1
kind: Pod
metadata:
  name: agent-writer
  namespace: agent-lab
  labels:
    agent-lab/component: agent
    agent-lab/role: writer
spec:
  serviceAccountName: agent-writer
  automountServiceAccountToken: false
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    runAsGroup: 10001
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: agent
    image: python:3.12-alpine
    command: ["tail", "-f", "/dev/null"]
    env:
    - name: PYTHONDONTWRITEBYTECODE
      value: "1"
    - name: AGENT_ROLE
      value: writer
    - name: AGENT_TOKEN_PATH
      value: /var/run/secrets/agent/token
    - name: BROKER_URL
      value: "http://tool-broker:8080"
    volumeMounts:
    - name: agent-token
      mountPath: /var/run/secrets/agent
      readOnly: true
    - name: caller-code
      mountPath: /app
      readOnly: true
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]
      readOnlyRootFilesystem: true
      runAsNonRoot: true
  volumes:
  - name: agent-token
    projected:
      sources:
      - serviceAccountToken:
          audience: agent-tools
          expirationSeconds: 3600
          path: token
  - name: caller-code
    configMap:
      name: caller-code
      items:
      - key: caller.py
        path: caller.py
      defaultMode: 0444


The broker-side NetworkPolicy, which locks the broker's ingress to agent pods on port 8080:

YAML
 
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: broker-ingress
  namespace: agent-lab
spec:
  podSelector:
    matchLabels:
      app: tool-broker
  policyTypes: [Ingress]
  ingress:
  - from:
    - podSelector:
        matchLabels:
          agent-lab/component: agent
    ports:
    - protocol: TCP
      port: 8080


The kustomize entry point:

YAML
 
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: agent-lab

resources:
- manifests/namespace.yaml
- manifests/serviceaccounts.yaml
- manifests/rbac.yaml
- manifests/data-configmaps.yaml
- manifests/broker.yaml
- manifests/agents.yaml
- manifests/networkpolicy.yaml

configMapGenerator:
- name: broker-code
  files:
  - code/broker.py
- name: caller-code
  files:
  - code/caller.py

generatorOptions:
  disableNameSuffixHash: true


The full caller.py:

Python
 
#!/usr/bin/env python3
"""caller -- runs inside the agent pods to exercise the tool-broker.

Reads the projected ServiceAccount token fresh from disk on every call.
Projected tokens are rotated by the kubelet, so the token is deliberately
never cached. The token is presented in an Authorization header and never
printed.
"""

import json
import os
import sys
import urllib.error
import urllib.request

TOKEN_PATH = os.environ.get("AGENT_TOKEN_PATH", "/var/run/secrets/agent/token")
BROKER_URL = os.environ.get("BROKER_URL", "http://tool-broker:8080")


def _call(method, path, payload=None):
    with open(TOKEN_PATH, "r", encoding="utf-8") as fh:
        token = fh.read().strip()
    data = json.dumps(payload).encode("utf-8") if payload is not None else None
    req = urllib.request.Request(
        BROKER_URL + path, data=data, method=method,
        headers={"Authorization": "Bearer %s" % token,
                 "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return resp.status, resp.read().decode("utf-8")
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read().decode("utf-8", "replace")


def main(argv):
    if len(argv) < 2 or argv[1] not in ("read", "publish"):
        print("usage: caller.py read | caller.py publish <title> <body>",
              file=sys.stderr)
        return 2
    if argv[1] == "read":
        status, body = _call("GET", "/artifacts/internal-note")
    else:
        if len(argv) != 4:
            print("usage: caller.py publish <title> <body>", file=sys.stderr)
            return 2
        status, body = _call("POST", "/publish",
                             {"title": argv[2], "body": argv[3]})
    print("HTTP %s" % status)
    print(body)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))


With these files, kubectl apply -k . from the lab directory deploys the complete sandbox exactly as tested in Step 6.

AI Kubernetes security

Opinions expressed by DZone contributors are their own.

Related

  • Docker Security: 6 Practical Labs From Audit to AI Protection
  • Revolutionizing Kubernetes With K8sGPT: A Deep Dive Into AI-Driven Insights
  • Dynatrace Perform: Day Two
  • Containment Is a Feature: Sandboxing, Egress Control, and Provenance for Autonomous Agents

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook