Skip to content

Secrets Handling for Headless AI Coding Agents: Environment Inheritance, Sandboxes, Egress, Brokering and Redaction

Scope. Agents that run shell commands on a developer machine or in CI with nobody watching: Claude Code, Codex CLI, Gemini CLI, the GitHub Copilot coding agent, and orchestrators that spawn them. The question throughout is which control stops which leak. Vendor behaviour is as documented on 2026-11-30; version-specific statements say so. Bracketed numbers refer to the source list at the end. “Experiment N” refers to Appendix A.

Reading the evidence. Claims about vendor products come from the vendor’s own documentation or source where possible. Incident accounts come from the researcher who found the issue; where a vendor statement is known only through the researcher, the text says so.

1. Decision ladder

Ordered by how much each step removes. Sections 3 to 8 give the evidence.

StepControlStopsDoes not stop
1The secret is not in the agent’s process tree at all (section 7)Every read path: environment, /proc, files, transcriptMisuse of whatever the broker will do on the agent’s behalf
2Short-lived, narrowly scoped credential where one must be present (section 7)Long-term damage from a leak; cross-repository reachUse during its lifetime
3Environment allowlist for every child and MCP server (section 3)Accidental inheritance by tools, build scripts and MCP serversA child reading the parent’s environment unless PID-isolated
4OS sandbox with home denied for reads, failing closed (section 4)Reads of ~/.ssh, ~/.aws, other projects’ .env by any subprocessTools that run outside the sandbox (hooks, MCP servers, the agent’s own file tools)
5Egress allowlist kept minimal (section 5)Uploads to arbitrary hosts, DNS tunnelling where DNS is coveredExfiltration through an allowed host
6Transcript and telemetry hygiene (section 8)Secrets persisting on disk for weeks after a runExposure during the run
7Scanning on the way in, masking on the way out (section 8)Accidental pasting and printingA deliberately transformed value

2. Threat model: what the 2025 to 2026 incident record shows

The design test most sources converge on is Willison’s “lethal trifecta”: an agent with access to private data, exposure to untrusted content, and “the ability to externally communicate in a way that could be used to steal your data” can be made to leak that data, and a filter that catches 95% of attacks is “very much a failing grade” [31]. Meta’s “Agents Rule of Two” restates it as a budget: an agent should satisfy “no more than two” of processing untrustworthy inputs, access to sensitive systems or private data, and changing state or communicating externally; with all three it “should not be permitted to operate autonomously” [32].

DateProductVectorWhat left, and howSource
2025-05 (fixed v1.0.4)Claude Code, CVE-2025-55284Prompt injection in a source file.env contents encoded as subdomains in DNS lookups through then auto-approved ping, nslookup, host, dig; environment also read from /proc/PID/environ[3]
2025-05GitHub MCP serverMalicious issue in a public repositoryPrivate-repository data written into a public pull request; Invariant calls it “a fundamental architectural issue”[10]
2025-06 (fixed v0.1.14)Gemini CLIREADME injection plus a weak command-allowlist matchAll environment variables sent to a remote server by a command that looked like an approved grep; default no-sandbox mode[6]
2025-06 to 2025-08Copilot Chat (“CamoLeak”)Hidden pull-request commentPrivate-repository content encoded as a sequence of pre-signed image-proxy URLs; fixed by disabling image rendering[11]
2025-08-26Nx (“s1ngularity”)Stolen npm token, malicious postinstallScript searched for secrets, invoked local Claude, Gemini and Amazon Q CLIs with their permission-bypass flags to inventory sensitive files, and uploaded results to public repositories on the victim’s own GitHub account[1][2]
2025-10Claude code-interpreter sandboxPrompt injectionUser data uploaded to the attacker’s account through the vendor’s own Files API, because api.anthropic.com was on the egress allowlist[12]
2025-12Gemini CLI GitHub Action (“PromptPwnd”)Issue text interpolated into the promptGEMINI_API_KEY, GOOGLE_CLOUD_ACCESS_TOKEN and GITHUB_TOKEN written into an issue body with gh issue edit[7]
2026-01 (fixed 2.0.65)Claude Code, CVE-2026-21852Repository settings fileANTHROPIC_BASE_URL pointed at an attacker endpoint, so requests carrying the API key were sent before the trust prompt[4][5]
2026-02Anthropic internal red teamPhished employee sessionAgent asked to read ~/.aws/credentials and POST it out: “Across 25 retries of that prompt, Claude completed the exfiltration 24 times”[13]
2026-04Claude Code Security Review action, Copilot coding agent, Gemini CLI action (“Comment and Control”)Pull-request title, hidden HTML comment, issue commentps auxeww output containing API keys and tokens posted to a PR comment, committed as base64, or posted in an issue comment[8][9]

Four patterns recur.

  • The environment is the first thing harvested. Four of the ten rows took environment variables [3][6][7][8], and two used ps or /proc to read a process other than the injected command’s own [3][8].
  • Model refusal is not a control. In s1ngularity, Wiz found that about a quarter of Claude invocations refused, and that refusals varied with prompt wording [2]. Anthropic’s own test succeeded 24 times in 25 [13].
  • The allowed destination is the exfiltration channel. The data left through github.com (a commit, a comment, an issue edit), an image proxy, DNS, and the model vendor’s API [3][7][8][11][12]. Anthropic’s summary: “Every function reachable through any domain on an allowlist is now an attack surface” [13].
  • Vendors often classify the finding as architecture. GitHub described the Copilot result as a known architectural limitation and Anthropic said its review action “is not designed to be hardened against prompt injection”; both statements are reported by the researcher [8]. Plan for the class, not for the patched instance.

3. Environment inheritance: no surveyed CLI narrows it by default

Claude Code. Subprocess environments are “inherited from Claude Code, including any secrets in its environment”, and “There is no built-in credential deny list, so only the files and variables you list are restricted” [18]. Experiment 1 shows the starting point for this corpus’s own headless research run: the agent’s shell saw 45 variables, four with credential-like names. The documented controls:

SettingEffectLimit
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1Strips credentials, recognised by variable name or value shape, from Bash commands, hooks and stdio MCP servers; on Linux also runs Bash subprocesses in an isolated PID namespace “so they can’t read host process environments through /proc” [19]Leaves GITHUB_TOKEN, GH_TOKEN, HTTP_PROXY/HTTPS_PROXY (including credentials in the URL) and GIT_CONFIG_*; leaves any secret whose name and value do not look like one; before v2.1.251 removed only ANTHROPIC_API_KEY and AWS_SECRET_ACCESS_KEY of the documented examples [19]
CLAUDE_CODE_MCP_ALLOWLIST_ENV=1Stdio MCP servers start “with only a safe baseline environment plus the server’s configured env, instead of inheriting your shell environment” [19]Off by default, so the default is full inheritance [19]
sandbox.credentials.envVars with "mode": "deny"Unsets the named variable before each sandboxed command [18]Applies to sandboxed commands only; you must list each name [18]
sandbox.credentials with "mode": "mask"The command sees a placeholder and the sandbox proxy substitutes the real value for allowed hosts [18]Needs the experimental network.tlsTerminate; honoured only from user, managed or --settings scope, never from repository settings [18]

Codex CLI. populate_env builds the child environment in a fixed order: start from inherit (all, core or none); apply the default excludes unless ignore_default_excludes is set; apply exclude; apply set; apply include_only if non-empty [15]. The default excludes are the case-insensitive globs *KEY*, *SECRET* and *TOKEN*, and the Unix core set is PATH, SHELL, TMPDIR, TEMP, TMP, HOME, LANG, LC_ALL, LC_CTYPE, LOGNAME, USER [15]. The important default is the reverse of what the name suggests: “ignore_default_excludes defaults to true, so Codex doesn’t automatically remove variable names containing KEY, SECRET, or TOKEN” [17][16]. Codex does always strip a short list of its own internal variables from model-reachable children; a user’s OPENAI_API_KEY is not on that list [15]. The documented narrowing is:

# ~/.codex/config.toml, from the Codex advanced-configuration page [17]; not run here.
[shell_environment_policy]
inherit = "core"
ignore_default_excludes = false
[shell_environment_policy.filters]
"AWS_*" = "exclude"
"AZURE_*" = "exclude"

The filters map is the current form; exclude and include_only are labelled legacy and the two styles cannot be mixed in one configuration layer. An include pattern turns the map into an allowlist, and includes “can’t restore excluded values” [16][17]. The default of inherit is not stated on the pages read.

Gemini CLI. The configuration reference says the CLI “automatically redacts potential secrets from environment variables when executing tools” on a best-effort basis, and the same page lists security.environmentVariableRedaction.enabled with default false [21]. The two statements conflict, so verify the effective behaviour on the version you run.

Hosted agents separate setup from the agent phase. In Codex cloud, “Secrets configured for cloud environments are available only during setup and are removed before the agent phase starts”, while plain environment variables persist for the whole task [23]. In Claude Code cloud environments, “Anyone who uses the environment can read its environment variables and setup script” [24].

Why filtering the child is not enough. /proc/<pid>/environ “contains the initial environment that was set when the currently executing program was started via execve(2)”; later changes made with putenv are not reflected [49]. Experiment 3 shows a same-uid process reading it, a different uid refused, and the file mode -r--------. On macOS, experiment 2 shows ps eww printing the environment of a same-user Homebrew python3 process and nothing for /bin/sleep. So an agent or MCP server that holds the secret exposes it to any command it spawns, whatever that command’s own environment contains. This is what happened to the Copilot coding agent: the researcher reports that filtering applied to the bash child while the parent Node and MCP processes kept the full environment, and ps auxeww read them [8]. Claude Code’s scrub pairs the filter with a PID namespace on Linux for this reason [19]. CWE-214 and CWE-526 name the two underlying weaknesses: sensitive values visible in process arguments or environment, and environment variables used to store them [47][48].

Building the child environment yourself. An orchestrator should construct the environment from an allowlist instead of deleting known-bad names. The routine below compiled with rustc 1.93.0 and, run with two fake secrets exported, gave the child eight variables and neither secret (experiment 4). env -i NAME=value ... command is the shell equivalent.

use std::process::Command;
/// Spawn `program` with an allowlisted environment: nothing is inherited
/// unless it is named here.
fn spawn_allowlisted(program: &str, args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
const ALLOW: &[&str] = &["PATH", "HOME", "USER", "TERM", "LANG", "TMPDIR"];
let mut cmd = Command::new(program);
cmd.args(args).env_clear();
for name in ALLOW {
if let Some(value) = std::env::var_os(name) {
cmd.env(name, value);
}
}
cmd.status()
}

Arguments need the same care. /proc/<pid>/cmdline “holds the complete command line for the process” [50], and in experiment 3 a different uid could read it while being refused the environment. Never pass a secret or a prompt containing one in argv.

4. Files and the sandbox

Permission deny rules are narrower than they look. In Claude Code, Read(./.env) blocks the built-in file tools and recognised Bash file commands, but such rules “don’t apply to a command that reads files without naming them, such as grep -r pattern .”, nor to arbitrary subprocesses such as a Python or Node script that opens files itself [20].

The sandbox is the control for subprocess reads, with documented gaps.

  • It is off by default and covers Bash-spawned processes only: “A denyRead entry doesn’t stop the Read tool, and allowedDomains doesn’t limit WebFetch”, and hooks, local MCP servers, LSP servers and helper commands “run with your full access” [18].
  • Its default read scope is most of the machine, “including credential files such as ~/.ssh and ~/.aws/credentials” [18].
  • It fails open: without sandbox.failIfUnavailable: true a missing dependency means commands run unsandboxed, and a failed command can be retried outside the sandbox unless allowUnsandboxedCommands is false [18].
  • The documentation’s own caution: “Don’t rely on any of the sandbox’s restrictions, including protected paths and credentials.files entries, to stop a malicious command” [18].

A sandbox restricts files and network, not the environment. In experiment 5 a sandbox-exec profile denied a file read with “Operation not permitted” while the sandboxed shell still printed an inherited variable. The documented tightening for Claude Code, combining three examples from the sandboxing page [18] (not run here):

{
"sandbox": {
"enabled": true,
"failIfUnavailable": true,
"allowUnsandboxedCommands": false,
"filesystem": { "denyRead": ["~/"], "allowRead": ["."] },
"credentials": {
"envVars": [
{ "name": "GITHUB_TOKEN", "mode": "deny" },
{ "name": "NPM_TOKEN", "mode": "deny" }
]
}
}
}

The relative . resolves against the settings file’s location, so this belongs in the project’s .claude/settings.json [18].

Codex. Version-controlled folders default to workspace-write with on-request approvals, and that mode “keeps network access turned off unless you enable it” [23]. Permission profiles accept deny entries for paths and globs such as "**/*.env" [16]. The default read scope outside the workspace was not found in the pages read.

Containers are a boundary around what you mount. With permission prompts bypassed, “dev containers do not prevent a malicious project from exfiltrating anything accessible inside the container, including the Claude Code credentials stored in ~/.claude”, and the guidance is to “Avoid mounting host secrets such as ~/.ssh or cloud credential files” [27]. Codex’s documentation says the same of devcontainers: they “do not prevent every attack” [23].

The agent’s own credential is a file on Linux. Claude Code stores it in the macOS Keychain where available and in a mode-0600 file on Linux [28], so on Linux any process running as the user can read it unless the sandbox denies the path.

Both layers are needed. “Without network isolation, a compromised agent could exfiltrate sensitive files like SSH keys. Without filesystem isolation… a compromised agent could backdoor system resources to gain network access” [25].

5. Network egress

ProductWhat the egress control coversDocumented gap
Claude Code sandbox proxyAllowlist by client-supplied hostname; allowedDomains starts empty; refuses hostnames resolving to link-local addresses including 169.254.169.254 [18]“does not terminate or inspect TLS”; “Allowing broad domains such as github.com can create paths for data exfiltration” [18]
Copilot coding agent firewall“processes started by the agent through its Bash tool” [29]Not MCP servers or setup steps; “Sophisticated attacks may bypass the firewall” [29]
Codex cloudInternet off in the agent phase by default; allowlist presets; optional restriction to GET, HEAD, OPTIONS [30]The “Common dependencies” preset includes github.com, npmjs.com and pypi.org [30]
Codex local network proxyShell commands“does not filter web search, app or connector calls, MCP connections, browser activity, or the client’s model requests” [23]
Claude Code cloud sessionsAllowlisted egressGitHub traffic, MCP connector traffic and requests to network-secret hosts “don’t go through this allowlist” [24]

Experiment 6 shows the basic mechanism working on macOS: under a (deny network*) profile curl failed at name resolution, and the same request succeeded outside it. The mechanism is not the weak point. The allowlist contents are: in the incident table, an agent with a legitimate reason to reach github.com used git push, gh issue edit and a PR comment as the upload path [7][8], and an agent allowed to reach its own vendor’s API uploaded files to another account there [12]. Anthropic’s sandbox-runtime guidance states the consequence: “If the agent has permissive credentials for an allowed domain, ensure it cannot use that domain to… exfiltrate data” [26].

6. MCP servers

Stdio MCP servers are ordinary child processes and, by default in Claude Code, inherit the shell environment [19]. The MCP authorization specification is OAuth-2.1-based and optional; for stdio transports implementations “SHOULD NOT follow this specification, and instead retrieve credentials from the environment” [37]. So the specification itself directs stdio servers to the environment, which is the surface section 3 narrows. For HTTP servers, the MCP server “MUST NOT pass through the token it received from the MCP client” [37], and servers “MUST NOT accept any tokens that were not explicitly issued for the MCP server” [38].

Give each MCP server its own configured env with only its own credential, turn on the allowlist switch, and remember that in Claude Code MCP servers run outside the Bash sandbox [18][19].

7. Brokering: the agent never holds the secret

Anthropic’s statement of the principle: “if credentials never enter the sandbox, they can’t be exfiltrated, regardless of whether the cause is a user, a model finding a ‘creative’ path, or an attacker” [13].

PatternHow it worksWhat it leaves
Credential-injecting proxy“run a proxy outside the agent’s security boundary that injects credentials into outgoing requests… The agent never sees the actual credentials” [26]For HTTPS an HTTP_PROXY “only sees an opaque TLS tunnel and can’t inject credentials”, so injection needs TLS termination with the proxy’s CA trusted inside, or a tool outside the boundary that makes the call; not every program honours HTTP_PROXY [26]
Hosted git proxy“the git client inside the VM uses a scoped credential, which the proxy verifies and swaps for your actual GitHub token”; inside, GH_TOKEN reads as the placeholder proxy-injected [24]Whatever the proxy permits on the repository
Sealed tokens (Fly.io Tokenizer)The application holds only secrets encrypted to the proxy’s public key; the proxy decrypts and injects, and a sealed secret can be pinned to allowed hosts [33]The proxy is a high-value component to run and protect
Short-lived federated tokensGitHub Actions OIDC yields “a short-lived access token that is only valid for a single job” with no long-lived cloud secret stored [34]; Nx moved to npm Trusted Publishers after its incident [1]Use within the job
op run and similar launchersRuns a command “in a subprocess with the secrets made available as environment variables”, masking them in stdout and stderr by default [36]The secret is an ordinary environment variable of the child

Scope remains the companion control. The Amazon Q extension incident began with an “inappropriately scoped” GitHub token [14], and GitHub’s guidance is that GITHUB_TOKEN should have “the minimum required permissions” [35]. OWASP’s LLM06 puts the general rule as: “Implement authorization in downstream systems rather than relying on an LLM to decide if an action is allowed or not” [52].

8. Redaction, scanners and transcripts

CI log masking is documented as best-effort by every vendor read.

  • GitHub Actions: “Because there are multiple ways a secret value can be transformed, automatic redaction is not guaranteed”; do not use structured data as a secret; register derived values separately [35][39].
  • GitLab: “Masking a CI/CD variable is not a guaranteed way to prevent malicious users from accessing variable values” [40].
  • Buildkite: redaction keys off variable-name patterns, “Values shorter than six bytes are not redacted”, and “tee saves output before job-log redaction” [41].

Scanners find formats they know, in encodings they decode. A 2023 benchmark of nine tools found best precision of 75% (GitHub Secret Scanner) and best recall of 88% (Gitleaks), with false negatives traced to “faulty regular expressions, skipping specific file types, and insufficient rulesets” [42]. TruffleHog adds verification by logging in to the provider [43]. GitHub push protection can by default be bypassed by anyone with write access who gives a reason [44]. Experiment 7 ran gitleaks 8.30.1 [55] over one fake GitHub token in ten forms:

Form of the valueDefault (--max-decode-depth 5)Depth 0
Plain ghp_ token; AWS access key ID; password = "..." assignmentfoundfound
Base64; hexfoundmissed
Base64 applied twicefoundmissed
Split across two assignments; reversed; a space between each charactermissedmissed
Password embedded in a Postgres connection URL (the user:password@ part before the host)missedmissed

The Copilot coding agent’s pre-push scan was defeated by base64 in the field, per the researcher [8]. Masking and scanning therefore reduce accidental exposure and do not constrain an agent that has been told to hide a value.

Transcripts are plaintext copies of everything a tool returned. For Claude Code: “Anything that passes through a tool is written to a transcript on disk: file contents, command output, pasted text”, and “Transcripts and history are not encrypted at rest… If a tool reads a .env file or a command prints a credential, that value is written to projects/<project>/<session>.jsonl” [45]. Experiment 8 confirms it: a marker string that existed only in a command’s output was present in this run’s session file, which had mode -rw------- inside world-listable ~/.claude and ~/.claude/projects directories. Default retention is 30 days via cleanupPeriodDays; CLAUDE_CODE_SKIP_PROMPT_HISTORY=1, or --no-session-persistence with -p, turns writing off [45]. Redaction of known key patterns happens when a transcript is uploaded for sharing or feedback, not locally [46]. Codex saves history under CODEX_HOME unless history.persistence = "none" [16].

Telemetry. Claude Code’s OTEL_LOG_USER_PROMPTS, OTEL_LOG_TOOL_DETAILS, OTEL_LOG_TOOL_CONTENT and OTEL_LOG_RAW_API_BODIES are off by default and are the switches that put prompt and tool content into telemetry [19].

9. Agents in CI on untrusted text

The PromptPwnd and Comment and Control findings share one shape: issue or pull-request text is interpolated into the prompt of an agent whose job holds a write-scoped token or a cloud key [7][8]. Aikido names the settings that open it to anyone: allowed_non_write_users: "*" in the Claude Code action and allow-users: "*" in the Codex action [7]. claude-code-action turns the environment scrub on automatically when allowed_non_write_users is configured, and the scrub leaves GITHUB_TOKEN in place, so the job’s permissions block is what bounds the damage [19]. The Comment and Control author argues that removing individual tools after each report is “whack-a-mole” and that tool allowlists plus removing secrets from the agent’s reach are the durable fix [8].

10. Worked example from our repositories

a2a, which dispatches Codex workers from a Claude Code session, applies several of these controls, as described in its repository profile [56]:

  • Briefs and context files are scanned for secrets on ingress, and a hit fails the spawn.
  • Events are redacted at append time so the write-ahead log is clean, and every printed stream is redacted on egress.
  • OPENAI_API_KEY, AWS_* and DEPOT_TOKEN are scrubbed from every worker environment, and the broker’s app-server child gets an allowlist of PATH, HOME, USER, TERM, LANG, TMPDIR and CODEX_HOME.
  • No brief or message text appears in argv; it travels through a 0600 prompt file on the child’s stdin.

11. Checklist for a headless run

  1. List what the launcher exports. Start the agent from env -i or an equivalent allowlist, not from a login shell.
  2. Claude Code: set CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 and CLAUDE_CODE_MCP_ALLOWLIST_ENV=1; add sandbox.credentials deny entries for GITHUB_TOKEN and any name the scrub would not recognise [19][18].
  3. Codex: set ignore_default_excludes = false, inherit = "core", and add filters for provider prefixes [17].
  4. Enable the sandbox with home denied for reads, failIfUnavailable: true and allowUnsandboxedCommands: false [18].
  5. Keep the egress allowlist to the hosts the task needs, and treat each one as a place data can be sent [18][13].
  6. Replace long-lived tokens with OIDC or per-job tokens, and set the narrowest permissions [34][35].
  7. Do not let an agent that reads untrusted issue or PR text hold a write token or a cloud key [7][8].
  8. Set a short cleanupPeriodDays or disable session persistence for unattended runs; leave the OTEL content switches off [45][19].
  9. Keep masking and scanning on for accidents, and do not count them as a boundary [35][8].

12. Common misconceptions

ClaimStatusEvidence
“Codex strips variables named *KEY*, *SECRET*, *TOKEN* by default”False as documented on 2026-11-30: ignore_default_excludes defaults to true[16][17]
“A Read(.env) deny rule keeps the file from the agent”Only from the file tools and recognised file commands[20]
“Removing the variable from the child’s environment hides it”Not while a same-user parent still holds it and /proc or ps is reachable[8][49], experiments 2 and 3
“The sandbox is on, so MCP servers and hooks are contained”They run with full access in Claude Code[18]
“An egress allowlist prevents exfiltration”It prevents exfiltration to hosts not on it[12][13][18]
“CI masking will catch a leaked secret”Not after any transformation[35][40][41]
“The model will refuse to hunt for credentials”Sometimes; 24 of 25 attempts succeeded in one vendor test[13][2]
“Environment variables are the recommended place for secrets”Twelve-factor says so for deployed services [53]; CWE-526 lists it as a weakness [48]; for an agent the inheritance path decidessection 3

13. Standards

OWASP’s LLM02:2025 (Sensitive Information Disclosure) lists credentials among the data at risk and recommends least-privilege access, restricted data sources and pattern-based redaction [51]. LLM06:2025 (Excessive Agency) names excessive functionality, permissions and autonomy as root causes [52]. The OWASP Top 10 for Agentic Applications (2025-12-09) adds agent-specific entries including ASI01 Agent Goal Hijack, ASI02 Tool Misuse and ASI03 Identity and Privilege Abuse [54]. Vendors state the limits of their own layers: Anthropic that “protection in the model layer will never be 100% effective” [13], GitHub that its firewall may be bypassed [29], and GitHub’s published agent principles limit the agent to information that is “absolutely necessary” [22].

14. Synthesis (inferred)

These are our conclusions from the sources and experiments above, not claims any single source makes.

  • Ask where the secret is, not who is allowed to read it. Every control in sections 3 to 5 is a rule about access to a secret that is present. Each has a documented exception: the unrecognised variable name, the subprocess that opens the file itself, the tool outside the sandbox, the allowed host. Only step 1 of the ladder has no exception list, because there is nothing to read.
  • An environment allowlist is worth doing even though it is not a boundary. It will not stop an injected command from reading the parent, but most real exposure in an unattended run is mundane: a build script, a test runner or an MCP server receiving credentials it never needed. For our weekly research run that means having scripts/research-weekly.sh start claude -p from an explicit environment instead of the inherited one (45 variables in experiment 1). We have not made that change.
  • Redaction on ingress is more valuable than on egress. Scanning a brief or context file before a worker starts catches the honest mistake at the only point where nothing adversarial has run yet. On egress, experiment 7 shows the redactor loses to a reversed string. a2a does both; the ingress scan is the one doing the security work.
  • A GET-only egress rule is weaker than it sounds. The DNS and image-URL incidents moved data in the request name, not the body [3][11], so a method restriction does not stop them. No vendor page read says this directly.
  • Brokering moves the problem to scope. A proxy that injects a GitHub token still lets the agent do anything that token allows on the allowed host, including the git push and issue-edit uploads in section 2. The pairing that makes sense is a broker plus a token that can only touch one repository and cannot publish outside it.
  • Verification-by-login scanners should not be used as inline redactors. TruffleHog’s verification sends the candidate to the provider [43]; that is fine for a repository audit and is itself an outbound call carrying the secret if placed in an agent’s output path.
  • Practitioner tooling is forming around the broker pattern. Hacker News “Show HN” threads in 2026 include Infisical’s Agent Vault (156 points) [57], OneCLI (110 points) [58] and yolo-cage (60 points) [59], all described by their authors as keeping credentials out of the agent. We did not evaluate any of them; the cluster is a signal of where practice is heading, not a recommendation.
  • The transcript directory deserves the same handling as ~/.ssh. Experiment 8 found the session file itself owner-only but its parent directories listable by other users, and the retention default is 30 days. On a shared or backed-up machine, session files are the longest-lived copy of anything an agent ever printed.

Appendix A: experiments run for this document (2026-11-30)

macOS 26.6.2 with System Integrity Protection enabled; Linux 7.2.12 in a debian:stable-slim container under Docker 29.8.2; Claude Code 2.1.326. All secret values were made-up strings generated for the test.

  1. Agent shell environment. In this headless Claude Code run, env in the Bash tool listed 45 variables, 4 with names matching key|token|secret|passw|credential. Names only were inspected.
  2. macOS ps. A same-user /opt/homebrew/bin/python3 process started with FAKE_TOKEN set: ps eww -p and ps -E -p both printed the variable. The same test on /bin/sleep printed nothing. A value placed in argv was shown by ps -o args=.
  3. Linux /proc. Process owned by user a: /proc/<pid>/environ is mode -r--------, cmdline is -r--r--r--. User a read the variable from environ; user b got “Permission denied” on environ and read cmdline; root in the default container (no CAP_SYS_PTRACE) was also denied environ.
  4. Allowlisted spawn. With FAKE_TOKEN and AWS_SECRET_ACCESS_KEY exported, a plain child saw both; under env -i PATH HOME TERM LANG it saw neither and had 7 variables. The Rust routine in section 3 (rustc 1.93.0) gave its child 8 variables and neither secret.
  5. Sandbox does not scrub the environment. sandbox-exec with a deny file-read* rule on a directory: cat of a file inside failed with “Operation not permitted”; the same sandboxed shell printed the inherited FAKE_TOKEN.
  6. Network deny. sandbox-exec with (deny network*): curl https://example.com exited 6 (could not resolve host); outside the sandbox it returned HTTP 200.
  7. gitleaks 8.30.1 on ten forms of fake secrets, gitleaks dir at --max-decode-depth 0, 1 and 5 (5 is the default): results in the section 8 table. Depth 1 found single base64 and hex; double base64 needed depth 2 or more.
  8. Transcript storage. A marker string produced by a command, and absent from the command text, was found by grep in this session’s ~/.claude/projects/<project>/<session>.jsonl. The file was mode -rw-------; ~/.claude and ~/.claude/projects were drwxr-xr-x.

Not tested: any agent CLI’s scrub or sandbox settings in operation (sections 3 and 4 rest on the cited documentation and source), Codex CLI at all (not installed on the test machine), bubblewrap, proxies with TLS termination, CI masking, and Gemini CLI’s redaction default.

Sources

  1. Nx, “s1ngularity postmortem”: https://nx.dev/blog/s1ngularity-postmortem
  2. Wiz, “s1ngularity’s aftermath”: https://www.wiz.io/blog/s1ngularitys-aftermath
  3. Embrace The Red, “Claude Code: Data Exfiltration with DNS (CVE-2025-55284)”: https://embracethered.com/blog/posts/2025/claude-code-exfiltration-via-dns-requests/
  4. GitHub Advisory GHSA-jh7p-qr78-84p7 (CVE-2026-21852): https://github.com/advisories/GHSA-jh7p-qr78-84p7
  5. Check Point Research, “RCE and API token exfiltration through Claude Code project files”: https://research.checkpoint.com/2026/rce-and-api-token-exfiltration-through-claude-code-project-files-cve-2025-59536/
  6. Tracebit, “Code execution through deception: Gemini AI CLI hijack”: https://tracebit.com/blog/code-exec-deception-gemini-ai-cli-hijack
  7. Aikido, “PromptPwnd”: https://aikido.dev/blog/promptpwnd-github-actions-ai-agents
  8. Aonan Guan, “Comment and Control”: https://oddguan.com/blog/comment-and-control-prompt-injection-credential-theft-claude-code-gemini-cli-github-copilot/
  9. SecurityWeek coverage of Comment and Control: https://www.securityweek.com/claude-code-gemini-cli-github-copilot-agents-vulnerable-to-prompt-injection-via-comments/
  10. Invariant Labs, “GitHub MCP exploited”: https://invariantlabs.ai/blog/mcp-github-vulnerability
  11. Legit Security, “CamoLeak”: https://www.legitsecurity.com/blog/camoleak-critical-github-copilot-vulnerability-leaks-private-source-code
  12. Embrace The Red, “Claude Pirate”: https://embracethered.com/blog/posts/2025/claude-abusing-network-access-and-anthropic-api-for-data-exfiltration/
  13. Anthropic, “How we contain Claude”: https://www.anthropic.com/engineering/how-we-contain-claude
  14. AWS Security Bulletin AWS-2025-015: https://aws.amazon.com/security/security-bulletins/AWS-2025-015/
  15. Codex source, shell_environment.rs: https://raw.githubusercontent.com/openai/codex/main/codex-rs/protocol/src/shell_environment.rs
  16. Codex configuration reference: https://learn.chatgpt.com/docs/config-file/config-reference
  17. Codex advanced configuration: https://learn.chatgpt.com/docs/config-file/config-advanced
  18. Claude Code docs, Sandboxing: https://code.claude.com/docs/en/sandboxing.md
  19. Claude Code docs, Environment variables: https://code.claude.com/docs/en/env-vars.md
  20. Claude Code docs, Permissions: https://code.claude.com/docs/en/permissions.md
  21. Gemini CLI configuration reference: https://geminicli.com/docs/reference/configuration.md
  22. GitHub, “How GitHub’s agentic security principles make our AI agents as secure as possible”: https://github.blog/security/how-githubs-agentic-security-principles-make-our-ai-agents-as-secure-as-possible/
  23. Codex docs, Agent approvals and security: https://learn.chatgpt.com/docs/agent-approvals-security.md
  24. Claude Code docs, Cloud environments: https://code.claude.com/docs/en/cloud-environments.md
  25. Anthropic, “Claude Code sandboxing”: https://www.anthropic.com/engineering/claude-code-sandboxing
  26. Claude Agent SDK docs, Secure deployment: https://code.claude.com/docs/en/agent-sdk/secure-deployment.md
  27. Claude Code docs, Dev containers: https://code.claude.com/docs/en/devcontainer.md
  28. Claude Code docs, Security: https://code.claude.com/docs/en/security.md
  29. GitHub docs, Customizing the agent firewall: https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/customize-the-agent-firewall
  30. Codex docs, Cloud internet access: https://learn.chatgpt.com/docs/cloud/internet-access
  31. Simon Willison, “The lethal trifecta for AI agents”: https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/
  32. Meta, “Agents Rule of Two”: https://ai.meta.com/blog/practical-ai-agent-security/
  33. Fly.io, “Tokenized Tokens”: https://fly.io/blog/tokenized-tokens/
  34. GitHub docs, OpenID Connect: https://docs.github.com/en/actions/concepts/security/openid-connect
  35. GitHub docs, Secure use reference: https://docs.github.com/en/actions/reference/security/secure-use
  36. 1Password CLI, op run: https://www.1password.dev/cli/reference/commands/run/
  37. MCP specification 2025-06-18, Authorization: https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization
  38. MCP specification 2025-06-18, Security best practices: https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices
  39. GitHub docs, Workflow commands: https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands
  40. GitLab docs, CI/CD variables: https://docs.gitlab.com/ci/variables/
  41. Buildkite docs, Managing log output: https://buildkite.com/docs/pipelines/configure/managing-log-output
  42. Basak et al., “A Comparative Study of Software Secrets Reporting by Secret Detection Tools” (2023): https://arxiv.org/abs/2307.00714
  43. TruffleHog README: https://github.com/trufflesecurity/trufflehog
  44. GitHub docs, About push protection: https://docs.github.com/en/code-security/secret-scanning/introduction/about-push-protection
  45. Claude Code docs, The .claude directory: https://code.claude.com/docs/en/claude-directory.md
  46. Claude Code docs, Data usage: https://code.claude.com/docs/en/data-usage.md
  47. CWE-214: https://cwe.mitre.org/data/definitions/214.html
  48. CWE-526: https://cwe.mitre.org/data/definitions/526.html
  49. proc_pid_environ(5): https://man7.org/linux/man-pages/man5/proc_pid_environ.5.html
  50. proc_pid_cmdline(5): https://man7.org/linux/man-pages/man5/proc_pid_cmdline.5.html
  51. OWASP LLM02:2025: https://genai.owasp.org/llmrisk/llm022025-sensitive-information-disclosure/
  52. OWASP LLM06:2025: https://genai.owasp.org/llmrisk/llm062025-excessive-agency/
  53. The Twelve-Factor App, Config: https://12factor.net/config
  54. OWASP Top 10 for Agentic Applications: https://genai.owasp.org/2025/12/09/owasp-top-10-for-agentic-applications-the-benchmark-for-agentic-security-in-the-age-of-autonomous-ai/
  55. gitleaks (tool used in experiment 7): https://github.com/gitleaks/gitleaks
  56. a2a repository profile in this corpus: repos/a2a.md
  57. Hacker News, “Show HN: Agent Vault”: https://news.ycombinator.com/item?id=47865822
  58. Hacker News, “Show HN: OneCLI”: https://news.ycombinator.com/item?id=49023427
  59. Hacker News, “Show HN: yolo-cage”: https://news.ycombinator.com/item?id=46706796