Blog

Assume prompt injection succeeds. Defense in depth for enterprise coding agents

Most engineering organizations hit the same deadlock when developers ask for coding agents. Security reviews local CLI tools, sees full access to the developer's filesystem, SSH keys and ~/.aws credentials and says no. Or security allows them with approval prompts, which trigger approval fatigue within a week until engineers switch to --dangerously-skip-permissions to get work done.[1]

The deadlock is structural. A coding agent needs three things to be useful: private source code and credentials, untrusted text from GitHub issues, pull requests, docs and third-party packages, and tools that run shell commands and make network requests. Simon Willison calls this the lethal trifecta,[2] and OWASP tracks the broader failure class as Excessive Agency.[3]

Frontier models keep getting better at resisting prompt injection, yet Anthropic still describes it as "far from a solved problem."[4] An enterprise security architecture can't rely on a model's system prompt refusing every crafted dependency, poisoned README or malicious issue comment.

Start from the opposite premise: assume prompt injection succeeds. Then put five independent boundaries around the agent so that a tricked model has nothing sensitive on disk, no ambient IAM roles, only narrow short-lived credentials, hard organization ceilings and an audit trail outside its reach.

Developer laptop · local CLI

Single boundary
Full developer blast radius
  • ExecutionShared laptop kernel, home directory and local Docker daemon
  • IdentityActs as the developer with SSH keys, ~/.aws and every repo
  • CredentialsLong-lived tokens sit on disk and leak into local transcripts
  • GovernanceApproval prompts bypassed via --dangerously-skip-permissions
  • ForensicsLocal logs in ~/.claude can be altered; commits show the user

Defense in depth · kosem

Five independent layers
Bounded & traceable
  1. 01ExecutionKata microVM per agent or self-hosted VPC runnerValidatingAdmissionPolicy · no 169.254.169.254
  2. 02IdentityAgents are resources, never IAM subjectsagent:ags_… · zero ambient access · maxGrantTtl
  3. 03CredentialsKeyless broker over /run/kosem/creds.sockprofile → grant → request · instant flush
  4. 04Governance & ZDRMonotonic org → project policies and BYOK / WIFallowedTools · selfHostedRequired · ZDR intact
  5. 05ForensicsExternal transcript and 400-day append-only audit logaws:SourceIdentity · GitHub hashed_token
Blast radius when prompt injection succeeds: a local CLI agent shares one boundary with the developer's laptop, while defense in depth puts five independent boundaries around execution, identity, credentials, policy and forensics.

Everything below is how we built these five layers in kosem, along with the mechanisms you can apply in your own infrastructure and the residual risks that defense in depth still leaves open.

Layer 1: Isolate execution below the kernel

Local OS sandboxes are a fragile boundary for coding agents. They share the laptop's kernel, Claude Code's docs note not to rely on them "to stop a malicious command,"[5] and they break docker workflows.[6] Standard Linux containers share the host kernel too, and break down as soon as a test suite needs docker compose or system packages.

Real execution isolation for untrusted agent commands starts below the Linux kernel:

  • One microVM per agent. Each kosem environment boots a separate Linux kernel inside a Kata Containers microVM on Cloud Hypervisor (or Apple's container VM runtime on Apple silicon Macs). The agent can run as root and start dockerd inside its guest without touching the host kernel or another environment.
  • Admission enforcement in the cluster. Don't rely on application code alone to remember the runtime class. Enforce it in Kubernetes with a ValidatingAdmissionPolicy[7] that rejects any Pod in the environments namespace unless it uses the microVM RuntimeClass and drops host namespaces, host ports and hostPath mounts.
  • No cluster token, no private network and no metadata server. Environments run in a separate, non-peered VPC with automountServiceAccountToken: false. A NetworkPolicy drops all inbound traffic and blocks egress to RFC 1918 private ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), carrier-grade NAT (100.64.0.0/10), loopback and link-local addresses including cloud metadata (169.254.169.254). On self-hosted Linux hosts, nftables enforces the same host, bridge and metadata blocks; on Apple silicon Macs, pf enforces them on the VM bridges.
  • Self-hosted VPC execution with zero inbound ports. Regulated teams often can't run proprietary code or pull private container images on a vendor's multi-tenant cluster. With self-hosted runners, you install kosem-runner on your own Linux KVM hosts or Macs inside your VPC. Each host registers once with a one-time token and an Ed25519 public key, then polls outbound using short-lived signed tokens. kosem opens no inbound connections to your network, and private registry credentials are requested only when pulling an image and never written to disk.

For the storage, EROFS and memory-cgroup work that keeps these microVMs fast enough for tight test loops, read Making microVMs fast for coding agents.

Layer 2: Keep agents out of your IAM policies

When teams move agents off laptops, they usually fall into one of two traps: either the agent keeps acting as the developer who triggered it, or someone creates a shared service account in IAM and attaches broad roles to it. Both break least privilege and create non-human identity sprawl that outlives the task.

A cleaner boundary separates human authorization from agent capabilities completely:

  • Agents are resources, never IAM subjects. In kosem, GCP-style RBAC governs people, groups and service accounts. An agent (agent:ags_…) can hold no IAM role; any policy binding that names an agent is rejected. People get roles on an agent (who can view, steer or delete it), while the agent itself holds zero ambient permissions.
  • Explicit, non-escalating grants. Every agent starts with no access at all. A teammate grants specific access profiles or static secrets to that agent, and nobody can grant more than they hold: granting an access profile requires connections.accessProfiles.issue, and granting a secret requires secrets.versions.access.
  • Mandatory expiry and cross-revocation. Organization policy (agents.maxGrantTtl) can cap every grant to a fixed lifetime (from 1 to 720 hours), removing open-ended grants completely. Either the agent's owner or the IAM admin of the underlying secret or access profile can revoke a grant at any time, even on private agents whose transcripts the admin can't read. Deleting an agent deletes its environment and revokes its access at once.

Layer 3: Broker keyless credentials that can only narrow

We wrote in Agent transcripts are the new .env about why redacting agent logs isn't enough: if a long-lived key ever enters an agent's environment, it ends up in tool output, stack traces, backups or training buckets. The fix is to keep long-lived keys out of the microVM and mint narrow, short-lived credentials on demand.

01 · Connection

No stored keys
Keyless org trustGitHub App, AWS IAM OIDC or GCP Workload Identity Federation.trust: org_01m5… · 20 roles max

02 · Access profile

Hard cap
Named scope sliceCaps repos, permissions, IAM session policies and max TTL.github/payments · 2 repos · 60 min

03 · Agent grant

TTL-capped
Per-agent leaseOnly narrows the profile; revocable by owner or profile IAM admin.acme/checkout · expires in 4 h

04 · MicroVM socket

In-memory
Out-of-band mintgit, gh, aws and gcloud ask /run/kosem/creds.sock; widening fails.CREDENTIAL_REFUSED on widen
Forensic join · logged outside the microVM
CloudTrail · aws:SourceIdentity = agent:ags_… + accessKeyId GitHub Audit Log · hashed_token + Kosem-Agent trailer
Keyless credential narrowing from organization trust to a single command: each layer can only restrict scope and lifetime, and minted tokens join directly to AWS CloudTrail and GitHub audit logs.

Four rules make credential brokering hold under pressure:

  1. Keyless trust at the organization edge. Connect GitHub through a GitHub App installation,[8] AWS through IAM OIDC federation (AssumeRoleWithWebIdentity)[9] and Google Cloud through Workload Identity Federation.[10] No long-lived AWS keys or GCP service account JSON keys sit in a database waiting to be stolen. When you verify a Google Cloud connection in kosem, verification probes Google STS with three fabricated identities (another connection in the same organization, another organization's connection and an environment) and refuses to save the connection unless Google rejects all three. Overly broad trust conditions fail at setup rather than in production.
  2. Monotonic ceiling and narrowing. Slice each connection into named access profiles (such as github/payments-read or aws/staging-logs) that define a hard ceiling. Every credential request composes three layers: [profile, grant, request]. An access profile caps repositories, permissions, IAM roles, AWS session policies[11] or lifetimes. An agent grant can only narrow that profile, and a command inside the microVM can only narrow its grant further. Any attempt to widen returns CREDENTIAL_REFUSED.
  3. Out-of-band socket delivery. Inside the microVM, git, gh, aws, gcloud and cloud SDKs authenticate through a local unix socket (/run/kosem/creds.sock), native shims and a loopback metadata server. The GitHub App private key and OIDC signing keys never enter the VM. For third-party SaaS APIs that only support static keys, kosem injects a granted secret for a single command into tmpfs (/run/kosem/secrets), off the persistent disk, and redacts its value live from stdout and stderr as a backstop.
  4. Immediate revocation. When someone revokes a grant or unshares an organization access profile, kosem sends an invalidation call over the environment's control tunnel so the in-VM daemon flushes its in-memory credential cache immediately.

Layer 4: Enforce monotonic guardrails and preserve ZDR

Security postures rarely fail on day one. They erode on day ninety when a single project loosens a limit, connects a personal cloud account or adds an unapproved model key.

Monotonic organization policies

In kosem, product admins (Agents Admin, Environment Admin, LLM Gateway Admin) manage day-to-day defaults, while Owners and Policy Admins control organization policies. Every project inherits its organization's policies and can only tighten them:

  • Default-closed tool allow-lists. Setting agents.allowedTools at the organization level intersects with any project list, and any new tool added to the platform later stays off until explicitly permitted.
  • Anti-shadow-IT locks. Organizations can disable project-owned model providers (llmgateway.projectProvidersDisabled), project-owned cloud and GitHub connections (connections.projectConnectionsDisabled), project-owned container registries (environments.projectRegistriesDisabled) and public preview sites (sites.publicDisabled). Teams use only the providers, images and access profiles vetted centrally.
  • Mandatory self-hosted compute. Enforcing environments.selfHostedRequired blocks every project from starting environments on kosem-managed machines so workloads stay on your runner pools.
  • Immediate kill switches and retention bounds. Turning on llmgateway.disabled or llmgateway.projectProvidersDisabled stops matching model calls immediately. Retention policies bound how long transcripts (agents.retentionDays), stopped disks (environments.maxStoppedTtl) and gateway logs persist, while agents.maxModelCalls stops runaway agent loops.

Keeping your model provider agreements intact

Many hosted coding tools route prompts through the vendor's own model provider account. Anthropic's Linked Billing OAuth flow, for instance, executes requests inside the tool vendor's Console organization, dropping the customer's Zero Data Retention (ZDR) agreement, BAA and customer-managed encryption keys.[12]

Routing agent inference through an organization-controlled LLM Gateway on your own accounts avoids that trade-off. Connect Anthropic, OpenAI, Google Gemini, keyless Google Vertex AI (via Workload Identity Federation) or your own OpenAI- or Anthropic-compatible server in your VPC. Provider keys stay sealed with Cloud KMS outside every microVM, token usage bills directly on your contracts with zero markup, monthly spend limits cap each organization and project, and your ZDR and residency agreements remain in force.

Layer 5: Keep an audit trail that joins to your cloud logs

When something goes wrong, incident response needs to answer three questions fast: what did the agent read and run, which credentials did it receive and what did those credentials touch outside the platform?

  • Transcripts stored outside the VM. Every message, config change, command, tool result and grant change lives in kosem's append-only transcript store, never in a local ~/.claude folder the agent can rewrite or clear.
  • Same-transaction, append-only audit logs. Following the Cloud Audit Logs model, every Admin Activity change commits its audit entry in the same Postgres transaction as the change itself, enforced by append-only database triggers and kept for 400 days. Automated follow-ups record System Events linked by cause to the action that triggered them. Read-only viewers and audit log viewers are free on Team and Enterprise plans so security teams don't pay builder seat fees to inspect logs.
  • Direct join to AWS CloudTrail and GitHub.
    • AWS: Every STS session sets SourceIdentity to the agent's ID (agent:ags_…), which AWS propagates across role chaining into CloudTrail and exposes to IAM Deny rules via aws:SourceIdentity.[13] Sessions also carry structured tags (kosem-organization, kosem-project, kosem-agent, kosem-environment) and log the issued accessKeyId.
    • GitHub: Every minted installation token logs GitHub's hashed_token, letting security teams correlate kosem's issuance record directly with GitHub's organization audit log.[14]
    • Git commits: Agent commits carry Assisted-by and Kosem-Agent trailers linking code changes straight back to the run.

What defense in depth still doesn't solve

No architecture removes every risk of giving an LLM execution tools, and any security review should account for what stays open:

  • Misuse inside a valid token window. If an agent holds a 1-hour GitHub token with write access to acme/checkout, a prompt injection during that hour can still push bad code to that repository. The win is reducing blast radius from every repository and cloud account a developer can reach down to one repository for one hour, contained by branch protection, CI checks and human pull request review.
  • Data exfiltration over open public egress. Hosted kosem microVMs block private ranges, sibling environments, cloud metadata and crypto-miners, yet still allow outbound HTTPS to the public internet so agents can install dependencies and fetch documentation. Any agent that can read private code and reach the public internet can attempt to exfiltrate that code if tricked. Organizations that need strict domain-level egress allow-lists today run self-hosted runners inside their own VPC behind an existing egress firewall or proxy, enforced org-wide with environments.selfHostedRequired.
  • Host root on self-hosted runners. MicroVM isolation protects the host from environments and isolates environments from one another, yet anyone with root access on a runner host can inspect what runs there, including command output and minted credentials. Treat runner hosts as trusted build infrastructure and restrict who holds Environment Admin.
  • Insecure code produced by the model. Runtime isolation contains the agent while it works; it doesn't stop the agent from writing a missing auth check or a vulnerable query. Keep deterministic SAST, dependency scanning, policy-as-code and mandatory human review in CI.

The security review summary

Whether you adopt a platform or build your own internal agent infrastructure, here is the minimum bar across all five layers:

If you want to verify these controls firsthand, get started on Hobby with $10 in starter credits, connect a test GitHub repository or AWS OIDC role and watch SourceIdentity land in CloudTrail in five minutes.

Evaluating coding agents for an engineering or security team? Compare governance controls on pricing, read the Policies and Self-hosted runners docs, or get in touch for a 20-minute architecture walkthrough with the team building kosem.

Notes

  1. Anthropic, Beyond permission prompts: making Claude Code more secure and autonomous, October 2025. ↩
  2. Simon Willison, The lethal trifecta for AI agents, June 2025. ↩
  3. OWASP GenAI Security Project, OWASP Top 10 for LLM Applications, Excessive Agency. ↩
  4. Anthropic, Mitigating the risk of prompt injections in browser use, November 2025. ↩
  5. Claude Code's docs: Configure the sandboxed Bash tool, Security limitations. ↩
  6. Claude Code's docs: docker commands fail. ↩
  7. Kubernetes docs: Validating Admission Policy. ↩
  8. GitHub's docs: Authenticating as a GitHub App installation. ↩
  9. AWS STS API Reference: AssumeRoleWithWebIdentity. ↩
  10. Google Cloud docs: Workload Identity Federation. ↩
  11. AWS IAM User Guide: Session policies. ↩
  12. Anthropic's docs: Linked billing, November 2026. ↩
  13. AWS IAM User Guide: Monitor and control actions taken with assumed roles, on sts:SourceIdentity and aws:SourceIdentity. ↩
  14. GitHub's docs: Identifying audit log events performed by an access token. ↩