Sub topic 12
Keeping Secrets and Credentials Out of Reach
A coding agent works inside your account. It can read your files, inherit your environment variables, and run commands with your network access. Anything you can reach, it can usually reach too. This chapter covers how credentials leak through an agent session and how to layer defenses so one mistake does not expose them.
This chapter assumes you know how approval modes and allow and deny rules work, and what a sandbox is. It also assumes you are comfortable with environment variables and basic git.
Where secrets leak in an agent session
Secrets rarely leave through one dramatic action. They leak through ordinary steps that nobody flagged as sensitive.
- File reads. The agent opens
.env,~/.aws/credentials, or~/.ssh/id_rsawhile "looking for configuration." - Inherited environment. Every shell command the agent starts receives your environment variables, including
AWS_SECRET_ACCESS_KEYorGITHUB_TOKEN. - Command output.
printenv,git remote -vwith a token in the URL, or a verbose error message puts a secret into the conversation. - Model context. Once a secret is in the conversation, it is sent to the model provider with every later request. It may also be saved in transcripts or logs on disk.
- Outbound network. An injected instruction can tell the agent to send a secret to an attacker's server.
- Version control. The agent writes a key into source code, and you commit it.
The diagram shows why one control is not enough. Blocking file reads does nothing about environment variables, and blocking the network does nothing about a commit.
Layer 1: Deny reads of secret locations
The first layer is a deny rule on paths that hold credentials. Typical targets are .env and .env.*, *.pem, ~/.ssh/**, ~/.aws/**, ~/.gnupg/**, and .netrc. Deny rules win over allow rules, so a broad "read anything in the project" allow rule does not override them.
The function below shows the idea. It resolves the path first, so .. segments and ~ cannot hide the target.
from fnmatch import fnmatch
from pathlib import Path
SECRET_NAMES = [".env", ".env.*", "*.pem", "id_rsa*", ".netrc"]
SECRET_DIRS = {".ssh", ".aws", ".gnupg"}
def is_secret_path(path: str) -> bool:
p = Path(path).expanduser().resolve()
if SECRET_DIRS.intersection(p.parts):
return True
return any(fnmatch(p.name, pattern) for pattern in SECRET_NAMES)
print(is_secret_path("~/.ssh/id_rsa")) # True
print(is_secret_path("project/.env")) # True
print(is_secret_path("project/src/app.py")) # False
print(is_secret_path("project/.env.example")) # True (false positive, see below)The last line shows a trade-off. .env.example holds no secrets, but the pattern .env.* blocks it. Over-blocking is safer than under-blocking. If the agent needs the example file, add a narrow allow exception and check that your tool lets that exception override the deny. Many tools do not.
The shell bypass
Read rules usually apply only to the agent's built-in file-reading tool. They do not apply to a shell command such as cat .env, grep -r KEY ., or python -c "print(open('.env').read())". If the agent can run arbitrary shell commands, a deny rule on the read tool is a speed bump, not a wall.
You have three ways to close this gap:
- Write matching deny rules for shell commands that touch these paths. This is fragile, because commands can be rewritten, encoded, or split across steps.
- Require approval for every shell command and read each one carefully.
- Run the agent in a sandbox where the secret files do not exist. This is the only reliable option.
Layer 2: Scrub the environment
Environment variables are the most overlooked leak because they are invisible. A shell command started by the agent inherits all of them. The fix is to pass an explicit allowlist instead of the whole environment. This matters for any tool you build that launches agent commands, and it is also the pattern to look for in sandbox or container settings.
import os
import subprocess
import sys
SAFE_VARS = {"PATH", "HOME", "LANG", "TERM", "TMPDIR"}
def clean_env(extra=None):
env = {k: v for k, v in os.environ.items() if k in SAFE_VARS}
env.update(extra or {})
return env
os.environ["DEMO_API_KEY"] = "do-not-leak"
result = subprocess.run(
[sys.executable, "-c", "import os; print('DEMO_API_KEY' in os.environ)"],
env=clean_env(),
capture_output=True,
text=True,
)
print(result.stdout.strip()) # False: the child process never saw the keyUse an allowlist rather than a blocklist of names like *_KEY. A blocklist misses DATABASE_URL, which often has a password embedded in it. An allowlist fails safe: a variable you forgot about stays hidden.
Note that HOME is still in the list. A process that knows your home directory can read ~/.aws/credentials unless the filesystem is restricted. Scrubbing the environment and restricting the filesystem work together.
Layer 3: Limit where data can go
Suppose a secret reaches the model context anyway. The next question is whether it can leave. Network controls answer that.
- Block outbound network by default in the sandbox, then allow specific hosts such as your package registry and git remote.
- Deny or require approval for
curl,wget,nc, and similar tools. Prefix rules are weak here, becausepython -ccan make the same request. - Treat the model provider itself as a destination. Everything in the context is sent there. Check your provider's data retention and training terms before you let production data into a session.
Layer 4: Make the credentials less valuable
The strongest defense is a secret that is worthless when stolen. Reduce what a leak can do.
- Use short-lived credentials. Temporary tokens from a single sign-on login or a cloud security token service expire in hours. A leaked long-lived access key can be abused for months.
- Scope them narrowly. Give the agent a token that can read one repository, not your whole organization. Give a cloud role access to a dev account, not production.
- Use a separate identity. A dedicated "agent" account or machine user makes audit logs readable and lets you revoke access without locking yourself out.
- Keep production credentials off the machine where the agent runs. If a task needs production access, a human should perform that step.
Layer 5: Detect and recover
Prevention fails sometimes, so plan for detection.
- Scan before you commit. Secret scanners such as
gitleaksortrufflehogcan run as a pre-commit hook or in CI. They catch keys the agent wrote into code or config. - Review the diff. Look for new strings that resemble keys, URLs with embedded passwords, and changes to
.gitignorethat expose.env. - Check transcripts. Session logs may contain every command output. Keep them out of the repository and apply the same access controls as the secrets themselves.
- Rotate on suspicion. If a secret appeared in a conversation, a log, or a commit, assume it is exposed. Revoke and replace it. Deleting the commit or the message is not enough, because history, forks, and provider logs may keep copies.
Common mistakes
| Mistake | Why it fails | Better approach |
|---|---|---|
| Denying only the file-read tool | `cat .env` through the shell still works | Sandbox the filesystem, or deny shell patterns too |
| Blocklisting variable names like `*_KEY` | Misses `DATABASE_URL` and custom names | Pass an allowlist of variables |
| Putting a token in a git remote URL | `git remote -v` prints it into the context | Use a credential helper or SSH agent |
| Trusting `.gitignore` alone | It does not stop the agent reading the file | Keep secrets outside the workspace |
| Reusing your personal admin credentials | A leak has the full blast radius | Issue a scoped, short-lived agent credential |
| Fixing a leak by deleting the message | Copies persist in logs and provider systems | Rotate the secret |
Putting the layers together
No single layer is complete, and each covers a gap in another:
- Path deny rules stop the obvious reads.
- Environment scrubbing and a restricted filesystem stop the reads that bypass those rules.
- Network limits stop exfiltration of anything that gets through.
- Scoped, short-lived credentials limit the damage if everything else fails.
- Scanning and rotation handle the leaks you miss.
This is also why prompt injection and secrets belong together. An injected instruction usually needs two things: access to a secret and a way to send it out. Removing either one stops the attack.
Exercise
A teammate says: "I added a deny rule for .env on the agent's file-read tool, so the agent can't see our secrets." Give two ways the agent could still obtain the secrets, and name one control for each.
Show answer
First, the agent can run a shell command such as cat .env or grep -r KEY ., because the deny rule covers only the file-read tool. A sandbox that does not mount the file, or shell deny rules plus per-command approval, closes this. Second, the secrets may also be in inherited environment variables, so printenv shows them. Passing an allowlisted environment to agent commands closes this. Scoped, short-lived credentials would limit the damage from either leak.
Exercise
In the clean_env example, why is an allowlist of variable names safer than a blocklist of names matching *_KEY?
Show answer
A blocklist only removes names you thought of. Variables like DATABASE_URL, which may contain a password, or custom names would pass through. An allowlist removes everything you did not explicitly approve, so a forgotten variable stays hidden.
Exercise
A token appeared in the agent's command output during a session. You delete that message from the conversation. What else must you do, and why?
Show answer
Rotate the token by revoking it and issuing a new one. The text was already sent to the model provider as context and may be stored in transcripts or logs, so deleting the visible message does not remove every copy.