Agent credential leakage is the moment an AI agent puts a secret it legitimately holds into an outbound request that should never carry it. Because the agent decides the destination at runtime, the only reliable place to catch it is the egress boundary: inspect every outbound request body, header, and query string for credential patterns, then block, redact, or escalate before the bytes leave.
Why agent credential leakage is different from ordinary secret sprawl
Traditional secret leakage is a static problem. A key gets committed to a repo, a scanner finds it, you rotate it. Agent credential leakage is dynamic. The secret is not misplaced at all: it is correctly injected into the agent process as an environment variable or fetched from a secret manager at boot. The failure happens later, when the model composes a tool call and decides that the value of AWS_SECRET_ACCESS_KEY belongs in a Slack message, a debugging webhook, a pastebin POST, or an error report to a third party.
Three mechanics make this common in practice:
- Agents read their own environment. Coding agents with shell access run
env,cat .env, orprintenvas a normal debugging step, then include the output in a summary that gets posted somewhere. - Agents echo request context. When a tool call fails, many frameworks feed the full request (including the
Authorizationheader) back into the model as an observation. The model then quotes it in a status update or an issue comment. - Untrusted content steers the destination. Indirect prompt injection in a retrieved document, a README, or an HTML page can instruct the agent to send configuration details to an attacker-controlled endpoint. The agent does not need to be compromised, only obedient.
None of this requires a vulnerability in your code. It requires only that an agent with credentials also has network reach.
API key exposure in LLM systems: what the control points actually see
Most teams already run several layers that sound like they should catch this. They do not, because each one inspects a different artifact. Here is the honest breakdown.
| Control | What it inspects | Catches runtime credential egress? |
|---|---|---|
| Repo secret scanning | Committed source and history | No. The secret was never committed. |
| Secret manager plus rotation | Issuance and lifetime | No. It scopes the blast radius but does not see the outbound call. |
| NHI governance and identity tooling | Which identities exist and what they can access | No. It knows the token is valid, not where it just went. |
| In-process guardrail library | Prompt and completion strings inside the app | Partially. It misses shell output, subprocess traffic, SDK calls that bypass the wrapper. |
| Cloud firewall or security group | IP, port, protocol | No. A leak to a legitimate SaaS domain looks identical to normal traffic. |
| Egress proxy with payload inspection | Full request line, headers, body, query string per agent identity | Yes. This is the only layer that sees the credential and the destination together. |
The gap is structural, not a tooling oversight. Prompt-layer filters live inside the trust boundary the agent controls; L3/L4 firewalls live below the layer where the secret is visible. An inspecting egress proxy sits exactly where the credential and its destination coexist. That is the same reasoning behind a default-deny egress allowlist: constrain the destination set first, then inspect what crosses it.
How to stop secrets exfiltration from an AI agent at egress: six steps
- Enumerate the credentials your agents actually hold. Walk each agent runtime and list every secret reachable from the process: environment variables, mounted files, cached OAuth tokens, CI variables, cloud instance role credentials. Tag each one with an issuer prefix and a criticality tier. You cannot write detectors for secrets you have not inventoried.
- Route all agent traffic through one inspecting egress path. Set
HTTP_PROXY,HTTPS_PROXY, andNO_PROXYin the agent runtime, or force traffic with iptables redirection or a sidecar so the SDKs cannot dodge it. Terminate TLS at the proxy with a trusted internal CA so bodies are inspectable rather than opaque. - Write high-precision structural detectors first. Provider prefixes give you near zero false positives:
sk-andsk-proj-for OpenAI,sk-ant-for Anthropic,ghp_andgho_andgithub_pat_for GitHub,glpat-for GitLab,xoxb-andxoxp-for Slack,AKIAandASIAfor AWS access key IDs,ya29.for Google OAuth access tokens,eyJfollowed by two more base64url segments for JWTs, and-----BEGINfor private keys. Add checksum validation where the provider defines one. - Add entropy and context heuristics second. For unprefixed secrets, score candidate strings on Shannon entropy, character class mix, and length, then require a contextual anchor nearby: a key name like
api_key,secret,token,password, orbearerin the same JSON object, form field, or header. Entropy alone flags UUIDs, hashes, and image data; entropy plus context is workable. - Normalize before you match. Run the payload through URL decoding, base64 and base64url decoding, gzip and deflate inflation, JSON string unescaping, multipart part extraction, and whitespace and homoglyph folding, then re-scan each decoded layer. A raw regex sweep of the original bytes misses a key that was base64 wrapped inside a JSON field inside a gzipped body. Cap recursion depth so a hostile payload cannot turn normalization into a decompression bomb.
- Bind the verdict to a policy tier per agent identity. Same detector, different outcome depending on who is calling and where the request is going. A GitHub token in a request to
api.github.comis normal. The same token in a POST to an unapproved webhook host is an incident.
Stop token leakage from an agent without breaking legitimate calls
The hard part of a credential egress control is not detection, it is disposition. Blocking every request containing a bearer token would break every authenticated tool call your agents make. Policy has to distinguish between a credential used as authentication and a credential carried as data.
The distinguishing signals are all available at the proxy:
- Position. A token in the
Authorizationheader of a request to its own issuer domain is authentication. The same token in a JSON body field, a query parameter, a Markdown code fence, or a multipart file upload is data in transit. - Issuer to destination binding. Maintain a map: keys with the
sk-ant-prefix may only appear in requests to Anthropic API hosts;xoxb-only to Slack; AWS SigV4 material only to AWS service endpoints. Any credential appearing outside its bound destination set is a violation regardless of position. - Count and shape. One credential in a header is routine. Nine distinct secrets in a single POST body is an
envdump, and it should be blocked and paged, not redacted quietly.
Practical dispositions, in increasing severity: log and fingerprint (store a salted hash of the secret, never the plaintext, so you can prove which key moved without creating a new secret store); redact inline and forward the modified request; hold the request for human approval; hard block with a synthetic 403 and a machine-readable reason the agent can read and act on; and finally trip a per-agent kill switch when repeated attempts indicate injection or a runaway loop.
Inline redaction deserves a warning. Silently stripping a secret from a request that the destination requires will produce confusing downstream failures. Reserve redaction for low-stakes destinations such as logging and analytics endpoints, and prefer explicit denial with a clear error for everything else. Coding agents in particular need deterministic failures they can reason about, which is why egress control for AI coding agents pairs blocking with an explanatory response body.
Instrument it so leakage becomes evidence, not a mystery
Every credential verdict should emit a structured record containing: timestamp, agent identity and workload, destination host and path, detector name and match confidence, credential type and issuer, secret fingerprint, position (header, body, query, multipart), normalization layers traversed before the match, and the action taken. That record is what turns a vague concern into a rotation ticket with scope, and it is what an auditor accepts as proof the control fired. Ship it to your SIEM alongside the rest of your egress telemetry so detections can correlate across sessions, as described in the guide to streaming agent egress logs to Splunk, Datadog, and Sentinel.
Then test the control adversarially. Plant a canary token with no privileges in the agent environment and prompt the agent, directly and through poisoned retrieved content, to send its configuration to an external endpoint. Repeat with base64 encoding, gzip, chunked bodies, a multipart upload, a Markdown image URL, and a messaging tool. Any variant that succeeds is a missing normalization pass, and the messaging and webhook channels are usually the leakiest, which is why exfiltration through email, Slack, and webhooks deserves dedicated policy.
Where Agent G fits
Agent G is a zero-trust egress proxy that sits between your agents and the internet. It terminates and inspects outbound traffic, normalizes encoded payloads, matches credential detectors against every layer, and applies per-agent policy: allow, redact, hold for human approval, or block. Because it runs outside the agent process, its verdicts and logs survive prompt injection, tool misuse, and framework changes. Explore the platform overview, the MCP gateway for tool-call inspection, or how it compares to other approaches.
Frequently Asked Questions
Can I prevent agent credential leakage without TLS interception?
Only partially. Without decryption you can enforce destination allowlists and see SNI hostnames, which blocks unknown endpoints. You cannot detect a secret sent to an approved host. Full agent credential leakage detection requires terminating TLS at the proxy with an internal CA the agent runtime trusts.
Does inspecting request bodies add meaningful latency?
Structural prefix matching and entropy scoring run in microseconds on typical JSON payloads. Cost concentrates in normalization of large compressed or multipart bodies. Bound it with a maximum inspected body size, a recursion depth limit, and streaming inspection so the first bytes forward while later chunks are still being scanned.
How do I avoid false positives on high-entropy data?
Require two independent signals. Use provider prefixes and checksums as the primary detector, and gate entropy heuristics behind a contextual anchor such as a nearby field name containing token, secret, key, or password. Exclude known high-entropy content types like images, binary uploads, and content hashes.
Should a detected secret be rotated automatically?
Rotate on any confirmed egress to an unapproved destination, since you cannot prove the value was not observed. Automate rotation for tokens with clean rotation APIs, and use the logged secret fingerprint to identify exactly which credential moved so you rotate one key rather than every key the agent held.
Close the loop on credentials leaving your network
Agent credential leakage is not a code review problem or an identity hygiene problem. It is a runtime egress problem, and it is solved by inspecting outbound requests at a boundary the agent cannot talk around. Inventory the secrets, force traffic through an inspecting proxy, layer structural detectors over normalization passes, and bind every verdict to an agent identity and destination.
Want that enforced by default, with signed logs and human-in-the-loop approval on the risky calls? Request access to the Agent G private beta and put a default-deny, secret-aware egress boundary in front of your agents.