Shrinking the blast radius of a coding agent

If a coding agent's session leaked tonight, what could someone do with it, and for how long? Five controls that shrink both answers, and what each costs in friction.

Task Agent session Credential broker Pinned tools Write gate Target system Redacted traces Undo log own short-lived, revocable identity secrets at call time diff and undo 30-day retention
A task runs through an agent session with its own identity, a broker, pinned tools and a write gate, with traces and undo kept aside.
On this page
  1. A credential with two names on it
  2. Secrets stay out of the context window
  3. Tools from a lockfile, never from latest
  4. A gate for writes that leave the repo
  5. Revocation only works where something checks
  6. One flaky test with and without the controls
  7. A blast-radius review in twelve questions
  8. Tiers, so nobody routes around it

Two hours into a session, a coding agent has read the repo’s .env, run commands under the developer’s cloud profile, and written every step, file contents included, to a trace that may sync to a vendor. Whoever ends up with the session, through a stolen laptop or a trace someone pasted into a ticket, can reach everything it could.

For every layer I want two answers: if this session leaked tonight, what could someone do with it, and for how long?

“What” is scope: which systems, which actions. “How long” is lifetime: how long a stolen piece stays useful. Each control below shrinks one of them and costs some friction. I’ll name it, because unplanned friction is what developers route around.

A credential with two names on it

The default is to let the agent borrow everything the developer has, from the cloud profile in ~/.aws to the personal access token made in a hurry. Those last for months and can do anything the developer can, so a leaked session is a leaked developer.

The agent should get its own credential, minted at session start, scoped to the repo and the services the task needs, and good for about an hour. It names both parties: this agent, acting for this person. OAuth token exchange has a place for that, the actor (act) claim, so audit logs can record both.

I want an agent to act as the user it serves, and this doesn’t change that. Permission checks still see the person, so it can’t reach anything they couldn’t. It just gets there on a narrower credential that dies sooner.

The friction is plumbing. Some CLIs only take a static token, so the broker must refresh quietly while the developer is signed in. If it prompts hourly, someone will paste a personal token into the config by Friday.

Secrets stay out of the context window

Anything the model reads can end up in a trace, so the agent shouldn’t see a real secret at all. .env holds references such as DATABASE_URL=broker://staging/app-db, and a broker swaps in the real value inside the tool’s process. The model sees the reference. The test runner gets a working connection string.

That isn’t airtight. A shell tool can still run printenv, and test output can echo a connection string. So traces are redacted before they touch disk or sync, and deleted after 30 days. An unredacted trace folder is a secrets store with no access control.

import json
import re

# Names that suggest a secret: DB_PASSWORD, api_key, X-Auth-Token, Cookie
SECRET_NAME = (r"[A-Z0-9_-]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD|CREDENTIALS?"
               r"|DSN|DATABASE_URL|AUTHORIZATION|COOKIE)[A-Z0-9_-]*")
SECRET_FIELD = re.compile(rf"(?i){SECRET_NAME}")

# Applied in order to every string in a trace event, before it is written or synced.
RULES = [
    # PEM private key blocks
    (re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?-----END [A-Z0-9 ]*PRIVATE KEY-----", re.S),
     "[REDACTED PRIVATE KEY]"),
    # .env-style lines and headers: DB_PASSWORD=..., export API_TOKEN="...", x-api-key: ...
    (re.compile(rf"(?im)^(\s*(?:export\s+)?[\"']?{SECRET_NAME}[\"']?\s*[=:]\s*).+$"),
     r"\1[REDACTED]"),
    # Authorization headers and bearer tokens anywhere in a line
    (re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|basic|token)\s+)[^\s'\"]+"), r"\1[REDACTED]"),
    (re.compile(r"(?i)\b(bearer\s+)[A-Za-z0-9._~+/=-]{16,}"), r"\1[REDACTED]"),
    # Passwords inside connection strings, up to the last "@": postgres://user:p@ss@host
    (re.compile(r"\b([a-z][a-z0-9+.-]*://[^:/\s@]+:)\S+@"), r"\1[REDACTED]@"),
    # Keyword/value connection strings anywhere in a line: host=db user=app password=...
    (re.compile(r"(?i)\b(password|passwd|pwd)\s*=\s*(?:'[^']*'|\"[^\"]*\"|[^\s;'\"]+)"), r"\1=[REDACTED]"),
    # Common cloud key and token shapes
    (re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), "[REDACTED AWS KEY]"),
    (re.compile(r"\bAIza[0-9A-Za-z_-]{35}"), "[REDACTED GOOGLE KEY]"),
    (re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})"), "[REDACTED GITHUB TOKEN]"),
    (re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}"), "[REDACTED SLACK TOKEN]"),
    (re.compile(r"\b[sr]k_(?:live|test)_[0-9A-Za-z]{16,}"), "[REDACTED STRIPE KEY]"),
    (re.compile(r"\bsk-[A-Za-z0-9_-]{20,}"), "[REDACTED API KEY]"),
    (re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"), "[REDACTED JWT]"),
]


def redact(text: str) -> str:
    for pattern, replacement in RULES:
        text = pattern.sub(replacement, text)
    return text


def redact_event(value, field: str = ""):
    """Walk a trace event and redact every string. Strings, objects and lists under secret-looking names go entirely."""
    if isinstance(value, (str, dict, list)) and SECRET_FIELD.fullmatch(field):
        return "[REDACTED]"
    if isinstance(value, str):
        return redact(value)
    if isinstance(value, dict):
        return {key: redact_event(item, str(key)) for key, item in value.items()}
    if isinstance(value, list):
        return [redact_event(item) for item in value]
    return value


def write_trace_event(path: str, event: dict) -> None:
    """Append one event to the trace as a JSON line, redacted first."""
    with open(path, "a", encoding="utf-8") as trace_file:
        trace_file.write(json.dumps(redact_event(event)) + "\n")

The filter is greedy on purpose: monkey = 3 gets masked for containing “key”, and a false positive beats a leak. Whole values go under secret-looking field names, nested objects included, since {"password": "hunter2"} has no shape a regex could spot. Regexes still miss things, so the broker matters more. Debugging takes the hit: masked traces are harder to read, and month-old sessions are gone.

Tools from a lockfile, never from latest

Plenty of MCP configs start servers with npx -y some-server: no version, no install prompt, whatever npm resolves at startup. After last year’s poisoned npm packages, and at least one MCP server that turned malicious in an update, I don’t think that’s defensible for a process that will hold a credential.

Install servers like any other dependency. tools/mcp/package.json pins exact versions, package-lock.json records an integrity hash for each package, and npm ci --ignore-scripts installs exactly that set or fails. The flag also skips the install scripts several of those attacks used. The config launches the local copy through the broker, so each server gets its secrets and the model doesn’t.

{
  "mcpServers": {
    "tickets": {
      "command": "agent-broker",
      "args": ["exec", "--", "node", "tools/mcp/node_modules/@yourorg/mcp-tickets/dist/index.js"],
      "env": {
        "TICKETS_URL": "https://tickets.example.internal",
        "TICKETS_TOKEN": "broker://agent-session/tickets"
      }
    },
    "staging-db": {
      "command": "agent-broker",
      "args": [
        "exec", "--", "node",
        "tools/mcp/node_modules/@yourorg/mcp-staging-db/dist/index.js",
        "--read-only"
      ],
      "env": {
        "DATABASE_URL": "broker://agent-session/staging-db"
      }
    }
  }
}

agent-broker and the @yourorg packages are placeholders. The broker swaps each broker:// value for the secret and launches the server, as several secret-manager CLIs do.

Every update then becomes a pull request someone has to read, and a few packages break without their install scripts. Worth it.

A gate for writes that leave the repo

Inside the repo, git is already the undo button. Outside it, nothing is. So a write to a staging database row or a customer ticket takes two steps. The first proposes it and returns a diff, plus the reverse operation for the undo log. The second applies it, and only with the confirmation token the first returned. A tool that can’t describe its own reversal never applies anything on its own: a person approves that write, or it doesn’t happen.

The undo log matters most to me, because a diff approved in a hurry can’t put anything back.

Approvals interrupt. An agent that asks every thirty seconds gets waved through on reflex. Gate only what leaves the repo, and batch related writes into one proposal.

Revocation only works where something checks

The kill switch I want revokes the agent’s credential and everything the broker issued under it, in one command. Someone should have run it before the night they need it, so it’s one more path to keep tested.

The broker stops minting at once, and a dynamic database user can be dropped on the spot, though some databases leave its open connections running. A self-contained access token is different: nothing asks whether it’s still good, so it works until it expires. That’s the strongest argument for a short lifetime.

One flaky test with and without the controls

I made this scenario up from ordinary steps. The task is a flaky integration test. The agent reads .env to see how the test connects, then adds a debug line that prints the connection string and reruns the suite. The staging password lands in the tool output, then in the trace, which syncs to the vendor.

Without the controls, the password is in every copy of that trace: the vendor’s store, an export attached to a bug report, a teammate’s laptop. Nobody knows to rotate it.

With all five, .env holds only a broker reference. Each test run gets its own database credential on a one-hour lease, tied to this session and never extended. The debug line still prints it, and the model sees it: a leak no broker can stop. The redactor masks it before the event is written, so the trace and its copies stay clean. Twenty minutes later the engineer spots the line in review and revokes the session, lease included. Unnoticed, the lease would still have expired at the hour mark.

Pinned tools and the write gate never came into it. Each control closes a different way out.

A blast-radius review in twelve questions

Run it once per place the agent runs. The answers differ.

Blast-radius review for one agent setup
If this session leaked tonight, what could someone do with it, and for how long?

Identity
 1. Does the agent run on its own credential, or on a developer's tokens?
 2. Does that credential name both the agent and the person it works for?
 3. When does it expire, and what happens to the session when it does?

Secrets and traces
 4. Can the agent read a real secret anywhere: .env, shell history, ~/.aws, CI variables?
 5. Where do traces go, and is anything redacted before they are written?
 6. How long are traces kept, and who outside the team can read them?

Tools
 7. Is every tool and MCP server installed from a lockfile, pinned by version and hash?
 8. Who reviews a version bump, and can any server update itself at startup?

Writes
 9. Which writes can leave the repo: git push, cloud APIs, databases, tickets, chat?
10. Does each of those writes show a diff first and record how to undo it?
11. Which writes have no undo, and are they blocked or sent to a person?

Stopping it
12. What single command revokes this session's access, and when did someone last run it?

Tiers, so nobody routes around it

Applying the strictest set everywhere backfires. A developer with an agent sandboxed on one repo doesn’t need to approve every file edit, and if forced to, will run it outside the sandbox. Tier the controls by where the agent runs.

Control Laptop sandbox, one repo CI Near production
Own short-lived credential One hour, renewed while the developer is signed in One per job, minted from the runner’s OIDC token Minutes, one task per credential
Brokered secrets, redacted traces Redaction on, broker for anything shared Broker for every secret, logs kept 30 days Broker only, nothing readable in the workspace
Pinned tools Lockfile for MCP servers Lockfile, nothing fetched after setup Lockfile plus an allow-list of servers
Write gate with undo Off inside the repo, on for anything outside it Writes only to its own branch and pull request Every write gated, no-undo writes go to a person
Kill switch that revokes Signing out revokes the session Cancel the run and revoke what the job was issued One command, tested on a schedule

The tier follows what the session can reach. A laptop session holding a production credential belongs in the third column, wherever the laptop is.