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- 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- 01ExecutionKata microVM per agent or self-hosted VPC runner
ValidatingAdmissionPolicy · no 169.254.169.254 - 02IdentityAgents are resources, never IAM subjects
agent:ags_… · zero ambient access · maxGrantTtl - 03CredentialsKeyless broker over /run/kosem/creds.sock
profile → grant → request · instant flush - 04Governance & ZDRMonotonic org → project policies and BYOK / WIF
allowedTools · selfHostedRequired · ZDR intact - 05ForensicsExternal transcript and 400-day append-only audit log
aws:SourceIdentity · GitHub hashed_token
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
containerVM runtime on Apple silicon Macs). The agent can run asrootand startdockerdinside 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 microVMRuntimeClassand drops host namespaces, host ports andhostPathmounts. - No cluster token, no private network and no metadata server. Environments run in a separate, non-peered VPC with
automountServiceAccountToken: false. ANetworkPolicydrops 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,nftablesenforces the same host, bridge and metadata blocks; on Apple silicon Macs,pfenforces 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-runneron 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 requiressecrets.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 keystrust: org_01m5… · 20 roles max02 · Access profile
Hard capgithub/payments · 2 repos · 60 min03 · Agent grant
TTL-cappedacme/checkout · expires in 4 h04 · MicroVM socket
In-memorygit, gh, aws and gcloud ask /run/kosem/creds.sock; widening fails.CREDENTIAL_REFUSED on widenaws:SourceIdentity = agent:ags_… + accessKeyId GitHub Audit Log · hashed_token + Kosem-Agent trailerFour rules make credential brokering hold under pressure:
- 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. - Monotonic ceiling and narrowing. Slice each connection into named access profiles (such as
github/payments-readoraws/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 returnsCREDENTIAL_REFUSED. - Out-of-band socket delivery. Inside the microVM,
git,gh,aws,gcloudand 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. - 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.allowedToolsat 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.selfHostedRequiredblocks 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.disabledorllmgateway.projectProvidersDisabledstops matching model calls immediately. Retention policies bound how long transcripts (agents.retentionDays), stopped disks (environments.maxStoppedTtl) and gateway logs persist, whileagents.maxModelCallsstops 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
~/.claudefolder 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
causeto 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
SourceIdentityto the agent's ID (agent:ags_…), which AWS propagates across role chaining into CloudTrail and exposes to IAM Deny rules viaaws:SourceIdentity.[13] Sessions also carry structured tags (kosem-organization,kosem-project,kosem-agent,kosem-environment) and log the issuedaccessKeyId. - 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-byandKosem-Agenttrailers linking code changes straight back to the run.
- AWS: Every STS session sets
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:
| Layer | Threat contained | Concrete control |
|---|---|---|
| 1. Execution | Host escape, lateral movement, metadata SSRF | Hardware microVM per agent, ValidatingAdmissionPolicy, no cluster SA token, metadata/RFC 1918 blocked, outbound-only VPC runners |
| 2. Identity | Developer-key inheritance, NHI sprawl | Agents forbidden as IAM subjects, zero ambient access, non-escalating grants with maxGrantTtl and cross-revocation |
| 3. Credentials | Transcript leaks, static key theft, scope creep | Keyless GitHub App / AWS OIDC / GCP WIF, out-of-band credential socket, monotonic [profile, grant, request] narrowing, instant cache flush |
| 4. Governance & ZDR | Project drift, shadow providers, broken ZDR/BAA | Policy Admin separated from product admins, monotonic org → project tightening, default-closed tool allow-lists, BYOK / keyless Vertex AI WIF |
| 5. Forensics | Tampered logs, unattributable commits and cloud calls | External transcripts, same-transaction append-only audit logs, AWS SourceIdentity + GitHub hashed_token correlation, commit trailers |
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
- Anthropic, Beyond permission prompts: making Claude Code more secure and autonomous, October 2025. ↩
- Simon Willison, The lethal trifecta for AI agents, June 2025. ↩
- OWASP GenAI Security Project, OWASP Top 10 for LLM Applications, Excessive Agency. ↩
- Anthropic, Mitigating the risk of prompt injections in browser use, November 2025. ↩
- Claude Code's docs: Configure the sandboxed Bash tool, Security limitations. ↩
- Claude Code's docs:
dockercommands fail. ↩ - Kubernetes docs: Validating Admission Policy. ↩
- GitHub's docs: Authenticating as a GitHub App installation. ↩
- AWS STS API Reference:
AssumeRoleWithWebIdentity. ↩ - Google Cloud docs: Workload Identity Federation. ↩
- AWS IAM User Guide: Session policies. ↩
- Anthropic's docs: Linked billing, November 2026. ↩
- AWS IAM User Guide: Monitor and control actions taken with assumed roles, on
sts:SourceIdentityandaws:SourceIdentity. ↩ - GitHub's docs: Identifying audit log events performed by an access token. ↩