How to Handle Secrets and API Keys Inside an Agent Sandbox
Keep raw credentials out of an agent's reach, not just its prompts.

Handling secrets and API keys inside an agent sandbox is an architecture problem. The central design choice is whether an agent can reach raw service credentials at all. Secret injection, task-level scoping, and isolation belong in the runtime, where they can constrain an agent even when its instructions have been manipulated.
Why secrets in agent sandboxes are a different problem than secrets in traditional apps
A traditional server-side application authenticates against a small, fixed set of services, usually with credentials loaded at startup. A production agent may call dozens of services, including LLM providers, vector databases, search APIs, cloud storage, and MCP servers. Its credential surface is an order of magnitude wider. When those credentials are in the same process, the agent can use all the access that was meant for separate integrations.
A cron job follows a predictable pattern, while an agent decides at runtime which tools to invoke, against which data, and on whose behalf. Which credentials will the task actually require? With startup-loaded secrets, the answer comes too late, because the credentials are already available before the agent chooses its path. Environment variables and .env files therefore expose permissions speculatively.
Agents read webpages, documents, and tool outputs that may contain instructions designed to redirect their behavior. OWASP’s 2026 LLM Top 10 ranks Prompt Injection at #1. GitGuardian’s State of Secrets Sprawl 2026 also found that Claude Code-assisted commits added secrets at roughly double the baseline rate, leaving more secrets exposed before the code even runs. One compromised agent can hand an attacker a master key ring to an entire infrastructure, a structural risk beyond a misplaced password.
How the three standard patterns fail under agentic conditions
Long-lived keys in environment variables are appealing because they need no extra infrastructure and work much like familiar integrations. In this pattern, a key without expiration, scope constraints, or environment isolation grants the same authority during a read-only lookup as during an attempted production overwrite. A compromised dependency can then obtain every key loaded into the process. The environment becomes a collection point for unrelated secrets.
Shared service accounts create a different failure. When several agents authenticate through one account, the audit trail identifies the account but not the individual agent or the user who authorized its task. Attribution disappears at the point of authentication. Revoking a misbehaving agent then requires cutting off every agent using that account, forcing a choice between containment and continuity. Can the deployment stop one agent without stopping its neighbors?
An agent inheriting a user’s full session receives permissions unrelated to its assignment. The April 2026 Railway incident illustrates the consequence of account-wide authority crossing an environment boundary. An AI coding agent found an account-scoped API token in an unrelated file and used it to delete a production database from a staging context. The deletion took nine seconds. The token had no environment isolation, so the location of the task did not constrain the reach of the credential.
Agent autonomy turns those familiar weaknesses into routes from an unexpected tool choice to infrastructure-wide consequences.
How prompt injection and MCP tool poisoning turn credential exposure into active exfiltration
Current LLM architectures do not reliably distinguish developer instructions from instructions embedded in retrieved content or tool responses. An attacker therefore need not obtain direct access to the sandbox to influence what the agent does inside it. Once raw secrets are readable, an injected instruction can turn passive exposure into an attempt to send them elsewhere.
The Agentjacking via Sentry MCP case shows that route concretely. Exposed DSNs in public JavaScript or GitHub repositories allowed attackers to POST fake Sentry error events containing malicious payloads. The Sentry MCP server then returned those events to agents as tool output. Controlled testing found that agents at over a hundred organizations executed the payloads, silently exfiltrating cloud credentials, registry tokens, and CI/CD secrets.
ASSET Research Group’s GhostSplice, disclosed in August 2026, showed a less conspicuous approach. A malicious MCP tool server broke requests into parts that looked routine, which an AI coding assistant put together into actions that exposed SSH keys, environment secrets, source code, and customer data. Sandworm_Mode, the February 2026 npm supply-chain attack, used typosquatting packages to install rogue MCP servers targeting Claude Code, Cursor, and Windsurf users. Those servers used prompt injection to exfiltrate secrets.
MCP amplifies the problem by expanding the tool surface without a native mechanism for separating trusted from untrusted instructions. What boundary remains when a legitimate agent follows a malicious request? Isolation must do more than keep attackers out of the sandbox. It must leave a manipulated agent with no raw service credentials worth stealing inside it.
The three-layer credential architecture that eliminates raw secrets from agent reach
Proxy-based credential injection addresses the direct exfiltration path. The agent makes an API request without holding the service key, and a proxy outside the sandbox attaches that key server-side only for allowlisted hosts. Keeping credentials outside environment variables and mounted files also covers a gap in scanning. An agent given a secret at runtime can generate code that reads it, even if no hardcoded secret appeared in the scanned source.
Instead of retaining a static credential, a secrets manager generates temporary access with a short TTL. HashiCorp Vault’s dynamic secrets engine, for example, creates database credentials on demand and revokes them automatically after the TTL. Expiration narrows the theft window, although a stolen credential can still be usable before it expires. For cloud access, workload identity federation replaces static API keys with the compute environment’s identity, such as an AWS IAM role or GCP service account.
Scoped token vaults address delegated access to third-party services. The agent receives a scoped session token or handle, while the underlying OAuth or service credential remains in the vault and is used server-side by an MCP server or application backend. Scope enforcement sits outside the agent’s code. In multi-tenant deployments, the credentials for each customer also need their own encryption keys. WorkOS Vault uses envelope encryption, protecting each piece of data with a unique data encryption key that is itself encrypted by a root key held in an HSM.
These layers solve distinct failures. These layers work without trusting the agent to follow a request to protect its own credentials.
Why sandbox isolation is the runtime enforcement layer that makes credential architecture hold
An external proxy offers little protection if the agent can cross the sandbox boundary and reach the infrastructure holding its secrets. Credential separation needs an enforceable runtime boundary. For agents processing user-supplied prompts, executing AI-generated code, or operating in multi-tenant environments, the minimum isolation tier is a microVM, using Firecracker or an equivalent. Hardware-virtualized separation keeps the host kernel and neighboring tenants outside the agent’s execution boundary without depending on the generated code to stay within it.
Long-running agents need to keep conversation history, working context, and authentication context across sessions, but keeping raw tokens with that state gives thieves more time to steal them. Duration alone is not the deciding risk. Persistent sandboxes can be as safe as ephemeral ones when isolation, patching, and monitoring are solid. The distinction is between preserving useful working state and leaving reusable credentials embedded in it, with session resume providing the point for fresh credential injection.
Networking supplies another enforcement point when an agent is manipulated. Deny-by-default networking blocks outbound connections that have not been allowed, so the agent cannot just choose an attacker-controlled destination for stolen data. Allowed API traffic instead follows the credential proxy’s constrained path. This limits what successful manipulation can accomplish, making the sandbox an active part of credential protection.
Applying least privilege and per-agent identity at the runtime level
Isolation limits where an agent can reach, but it does not determine what an authorized call may do. That requires a task-scoped identity for each agent. A shared service account erases the distinction needed to revoke one agent, attribute its actions, or compare its behavior with its own history. Identity and scope are therefore inseparable. A permission boundary has little operational precision when every agent appears to be the same actor.
The task determines the permissions an agent needs. An agent assigned to read data should not receive permission to delete it. For example, Gmail read access should not authorize Gmail delete, even when an injected instruction asks for deletion. The vault must enforce that restriction. When the check is in the agent’s own code, the rules are enforced in the same environment whose behavior may have been redirected.
Per-agent identity also makes behavioral monitoring more useful. An agent that normally reads a handful of documents but suddenly requests dozens of API keys presents a deviation that a static permission policy may still allow. Honeytokens provide a different, high-signal warning by placing decoy credentials where the agent should never read them and alerting on access. Legitimate-access logs alone do not provide that signal.
Attribution requires a timestamped record of every tool call, secret access, and API call under the individual agent’s identity. Such records support incident investigation and the access-control and audit obligations associated with SOC 2, HIPAA, and GDPR. Without individual identity, a detailed log still leaves the central question unanswered. Which agent exercised the permission?
What production-ready secrets handling actually looks like, from injection to revocation
In production, the architecture becomes a sequence of handoffs. Before the first run, pre-merge and workspace scanning catch hardcoded credentials before they get into the agent environment. Service secrets are kept in an encrypted vault, with per-customer keys in multi-tenant deployments, and are kept out of configuration files and environment variables. When a task starts, the agent gets its own short-lived, task-scoped token. It does not inherit the user’s full session or a shared service account credential.
During execution, API calls pass through a proxy or MCP server outside the sandbox, where downstream credentials are attached and the host allowlist is enforced. The microVM supplies isolation and deny-by-default networking, while its filesystem does not inherit host credentials or the user’s home directory. Each tool call and secret access is logged under the agent’s identity. Irreversible actions need a separate gate. Deny-by-default controls require a prompt before the agent can write, send, delete, or spend.
When the task ends, dynamic credentials are revoked, session tokens are invalidated, and raw credentials are kept out of the state saved for another session. When an agent resumes, it gets fresh authentication context through re-injection. Its filesystem state and conversation history can persist separately. This separation resolves the operational tension between an agent that remembers its work and a credential that should not survive that work.
Compliance follows the same runtime logic. Data handling, access controls, and audit trails must operate at the sandbox and vault layers. Procurement checks should establish whether certifications cover the sandbox product itself. Stateful execution, sub-90ms provisioning, and Docker-native compatibility can make purpose-built infrastructure easier to adopt, but it still needs to enforce the rules. A manipulated agent must remain confined to its task-scoped authority from the first request through revocation.


