This lesson covers credential handling for agent systems: the kinds of credentials involved, every place a secret can surface in an agent runtime, and the patterns that keep secrets usable but invisible to the model, namely injecting proxies, per-task token exchange, audience binding, sender-constrained tokens, and short-lived dynamic credentials. Tested reference code for a placeholder-injecting proxy and an output redactor is included. By the end you should be able to audit an agent deployment for credential exposure and redesign it so that a fully compromised model context yields nothing reusable.
Credential types
| Type | Typical lifetime | Bound to holder? | Notes |
|---|---|---|---|
| Static API key | Until revoked | No (bearer) | Often coarse scope; the most common leak |
| Personal access token (PAT) | Configurable | No | GitHub’s fine-grained PATs can be limited to specific repositories and given an expiry; GitHub removes tokens unused for a year [4] |
| OAuth access token | Minutes to hours | No by default (RFC 6750) | Scope and audience set at issuance |
| OAuth refresh token | Long | Should be | RFC 9700: refresh tokens for public clients “MUST be sender-constrained or use refresh token rotation” [7] |
| Sender-constrained token | Short | Yes: DPoP key (RFC 9449) or mTLS certificate (RFC 8705) | Stolen copy is useless without the private key |
| Cloud temporary credentials | Minutes to hours | No, but expire | AWS: after expiry “AWS no longer recognizes them” [8] |
| Workload identity (OIDC federation) | Minutes | Issued to a verified workload | Removes static bootstrap secrets; OWASP recommends it for CI/CD [5] |
RFC 6750’s definition is the root of the problem: “Any party in possession of a bearer token (a ‘bearer’) can use it to get access to the associated resources (without demonstrating possession of a cryptographic key)” [6].
Where secrets surface in an agent runtime
Audit each of these. In practice most leaks come from the first four.
- Prompts and system instructions. Keys pasted into instructions or stored in agent “memory”.
- Tool results. A tool that reads
.env, prints configuration, or returns HTTP response headers. OWASP LLM02 explicitly includes security credentials among the sensitive data LLM applications can disclose [13]. - Process environment. If an agent has a shell tool
and secrets are in environment variables of that process,
envorprintenvis a one-step reveal. Environment variables are a deployment convenience, not an isolation boundary. - Files the agent writes. Coding agents generate configs and scripts; secrets copied into them reach version control. Meli et al. found leakage in over 100,000 public repositories and “thousands of new, unique secrets” leaked daily [1]. GitGuardian’s industry telemetry counted 23,770,171 new secrets in public GitHub commits in 2024, a 25% year-on-year increase [2].
- Logs and traces. Request logs that capture headers, agent traces that capture tool I/O, evaluation datasets built from transcripts.
- URLs. Tokens in query strings end up in proxy, server and browser history logs. The MCP authorisation spec states that access tokens “MUST NOT be included in the URI query string” [10].
- Downstream forwarding. An MCP server or tool that passes the client’s token through to another API. MCP forbids this: servers “MUST NOT accept or transit any other tokens” than those issued for them [10].
Threat model
Assume the worst plausible case: an attacker controls text in the model’s context (via indirect prompt injection) and the model follows it. The question is what that attacker can obtain or do.
- If any secret is in the context or readable by a tool: the attacker can exfiltrate it through any egress channel [12]. Damage outlives the session.
- If secrets are outside the context but usable by tools: the attacker can misuse them through those tools, within scope and lifetime, for the duration of the session. Damage is bounded and attributable.
- If tool use is also policy-gated (destination allowlists, Ask on consequential calls): misuse is further limited to what policy permits.
The design goal is to move every credential from the first category to the second or third.
Pattern 1: placeholder-injecting proxy
The agent sends requests containing placeholders; an egress component outside the agent’s process substitutes the real secret, only for bound destinations. Anthropic’s cloud coding sandbox uses this shape for git: credentials are never inside the sandbox; a proxy authenticates a scoped credential from the sandbox, “verifies this credential and the contents of the git interaction (e.g. ensuring it is only pushing to the configured branch), then attaches the right authentication token” [14].
# Illustrative, tested. Runs in the egress proxy, never in the agent process.
import re
SECRETS = {"supplier_api": "sk_live_example_not_real"} # from a secrets manager
BINDINGS = {"supplier_api": {"hosts": {"api.supplier.example"}, "header": "Authorization",
"format": "Bearer {}"}}
PLACEHOLDER = re.compile(r"\{\{secret:([a-z0-9_]+)\}\}")
def inject(host: str, headers: dict) -> dict:
out = {}
for name, value in headers.items():
m = PLACEHOLDER.fullmatch(value.strip())
if not m:
if PLACEHOLDER.search(value):
raise PermissionError("placeholder must be the whole header value")
out[name] = value
continue
key = m.group(1)
b = BINDINGS.get(key)
if not b or host not in b["hosts"] or name != b["header"]:
raise PermissionError(f"secret {key!r} not bound to {host}/{name}")
out[name] = b["format"].format(SECRETS[key])
return out
# inject("api.supplier.example", {"Authorization": "{{secret:supplier_api}}"}) -> Bearer ...
# inject("evil.example", {"Authorization": "{{secret:supplier_api}}"}) -> PermissionError
# inject("api.supplier.example", {"X-Debug": "{{secret:supplier_api}}"}) -> PermissionErrorDesign notes. Bind each secret to host and header, so a hijacked agent cannot reflect the secret into a body or a debug header that the server echoes back. Refuse placeholders embedded in larger strings. Strip credential-bearing headers from responses before returning them to the agent. Do not follow redirects to other hosts with credentials attached.
Pattern 2: per-task, downscoped tokens
Rather than giving an agent a standing credential, mint one per task.
- Token exchange. RFC 8693 defines how a client
presents one token to a security token service and receives another,
potentially for a different audience and narrower scope, with the
act(actor) claim recording who is acting for whom [15]. An orchestrator can hold the user’s broad token and hand each agent run a token for one API, one scope, fifteen minutes. - Audience binding. Request the token with an RFC
8707
resourceparameter [11]; RFC 9700 says access tokens “SHOULD be audience-restricted to a specific resource server” and that resource servers MUST refuse tokens not meant for them [7]. MCP servers must validate this audience binding [10]. - Dynamic secrets. For databases and internal services, OWASP recommends generating credentials per session with “a short lease duration”, revoked when no longer needed, and notes that restarting the application “does not itself revoke stolen credentials” [5].
Pattern 3: sender-constrained tokens
DPoP (RFC 9449) binds tokens to a key pair: each request carries a signed proof that the presenter holds the private key, so the resource server can check “that the client presenting the token also possesses the private key” [18]. Mutual-TLS certificate-bound tokens (RFC 8705) achieve the same at the transport layer [16].
Be precise about what this buys in an agent setting. If the DPoP private key lives in the agent runtime (ideally in non-extractable storage), exfiltrating the access token alone is useless: copying a transcript or log line yields nothing replayable. It does not stop a hijacked agent from using the token through its own legitimate tools during the session. Sender-constraining defeats theft; it does not defeat the confused deputy. Pair it with policy gating.
Pattern 4: detection and redaction
Defence in depth for when the other patterns fail.
# Illustrative output filter applied to tool results and model output before logging or display.
import re
REDACT = [re.compile(p) for p in (
r"gh[pousr]_[A-Za-z0-9]{36,}", # GitHub token prefixes (illustrative)
r"github_pat_[A-Za-z0-9_]{20,}",
r"AKIA[0-9A-Z]{16}", # AWS access key ID format (illustrative)
)]
def redact(text: str, known_secrets: list[str]) -> str:
for p in REDACT + [re.compile(re.escape(v)) for v in known_secrets]:
text = p.sub("[REDACTED]", text)
return textRedaction is a filter, not a boundary: encoding, splitting or paraphrasing defeats pattern matching, and an injected instruction can ask for exactly that. Its job is to keep accidental disclosure out of logs. At the repository boundary, GitHub push protection blocks pushes containing provider-pattern, generic or custom-pattern secrets and explains why [3]. Use it, and route every alert to revocation first.
Rotation and revocation
NIST SP 800-57 defines a cryptoperiod as “the time span during which a specific key is authorized for use”, and lists among its benefits that it “limits the amount of exposure if a single key is compromised” [9]. OWASP recommends automated rotation of static secrets, expiry set at the secrets manager, and phased or dual-credential rotation to avoid outages; it also lists what to record for each secret: when and by whom or what it was created, consumed, rotated or deleted [5].
For agents specifically:
- One credential per agent per integration. Shared keys make revocation a breaking change and attribution impossible.
- Expiry by default. Every credential issued to an agent has an expiry. Renewal is an explicit act tied to a review.
- Revocation drills. Measure time from revoke to refusal. Cached authorisation, long JWT lifetimes and refresh tokens all extend it.
- JWT hygiene. If your tokens are JWTs, follow RFC 8725: perform algorithm verification, validate issuer, subject and audience, and treat its section 3.10, “Do Not Trust Received Claims”, as a rule for every claim you act on [17].
Worked example: auditing a reporting agent
A design studio runs an agent that writes weekly status reports from its project management tool and emails them to clients.
| Finding | Category | Fix |
|---|---|---|
| Admin API key in the agent’s system prompt | In context | Remove; rotate immediately |
| Same key in a cron script and a spreadsheet | Shared, static | One credential per consumer |
| Agent has shell tool; key also in process env | Readable by tool | Move secret to egress proxy; remove from env |
| Report tool returns raw API responses including headers | Tool result leak | Return parsed fields only |
| Agent reads inbound client email and sends email | Trifecta | Send becomes Ask; recipients restricted to the project’s client contacts |
| Key never expires | Lifetime | OAuth integration with read-only scope; tokens expire hourly; refresh token held by orchestrator, not agent |
| No leak detection | Detection | Push protection on the studio’s repos; redaction on agent logs |
After the changes, a successful injection can at worst cause the agent to read project data it is already allowed to read and request approval to send a report. No credential can be extracted from any transcript.
Key takeaways
Most credentials agents handle are bearer secrets, and secret leakage through code, logs and documents is measured in the millions per year, so any design that places a secret in a model’s context should be treated as already leaked. The core pattern is to keep secrets outside the agent process and let a proxy or broker attach them only for bound destinations and headers, so a compromised context can misuse access within policy but cannot exfiltrate anything reusable. Per-task token exchange, audience binding and dynamic secrets shrink what any credential can do and for how long, while sender-constrained tokens defeat theft but not in-session misuse, which still needs policy gating. Rotation with defined cryptoperiods, one credential per agent and integration, rehearsed revocation and leak detection at the repository and log boundaries turn the inevitable leak into a short, attributable incident.
Sources and further reading
- Meli, M., McNiece, M. R., & Reaves, B. (2019). How Bad Can It Git? Characterizing Secret Leakage in Public GitHub Repositories. NDSS 2019. https://www.ndss-symposium.org/ndss-paper/how-bad-can-it-git-characterizing-secret-leakage-in-public-github-repositories/
- GitGuardian. (2025). The State of Secrets Sprawl 2025. https://www.gitguardian.com/state-of-secrets-sprawl-report-2025
- GitHub. (n.d.). About push protection. GitHub Docs. https://docs.github.com/en/code-security/secret-scanning/introduction/about-push-protection
- GitHub. (n.d.). Managing your personal access tokens. GitHub Docs. https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens
- OWASP Cheat Sheet Series. (n.d.). Secrets Management Cheat Sheet. https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
- Jones, M., & Hardt, D. (2012). The OAuth 2.0 Authorization Framework: Bearer Token Usage (RFC 6750). IETF. https://www.rfc-editor.org/rfc/rfc6750
- Lodderstedt, T., Bradley, J., Labunets, A., & Fett, D. (2025). Best Current Practice for OAuth 2.0 Security (RFC 9700, BCP 240). IETF. https://www.rfc-editor.org/rfc/rfc9700
- Amazon Web Services. (n.d.). Temporary security credentials in IAM. https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html
- Barker, E. (2020). Recommendation for Key Management: Part 1 – General (NIST SP 800-57 Part 1 Rev. 5), Section 5.3. NIST. https://csrc.nist.gov/pubs/sp/800/57/pt1/r5/final
- Model Context Protocol. (2025). Specification 2025-06-18: Authorization. https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization
- Campbell, B., Bradley, J., & Tschofenig, H. (2020). Resource Indicators for OAuth 2.0 (RFC 8707). IETF. https://www.rfc-editor.org/rfc/rfc8707
- Willison, S. (2025, 16 June). The lethal trifecta for AI agents. https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/
- OWASP Gen AI Security Project. (2025). LLM02:2025 Sensitive Information Disclosure. https://genai.owasp.org/llmrisk/llm022025-sensitive-information-disclosure/
- Dworken, D., & Weller-Davies, O. (2025, 20 October). Beyond permission prompts: making Claude Code more secure and autonomous. Anthropic Engineering. https://www.anthropic.com/engineering/claude-code-sandboxing
- Jones, M., Nadalin, A., Campbell, B. (Ed.), Bradley, J., & Mortimore, C. (2020). OAuth 2.0 Token Exchange (RFC 8693). IETF. https://www.rfc-editor.org/rfc/rfc8693
- Campbell, B., Bradley, J., Sakimura, N., & Lodderstedt, T. (2020). OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens (RFC 8705). IETF. https://www.rfc-editor.org/rfc/rfc8705
- Sheffer, Y., Hardt, D., & Jones, M. (2020). JSON Web Token Best Current Practices (RFC 8725, BCP 225). IETF. https://www.rfc-editor.org/rfc/rfc8725
- Fett, D., Campbell, B., Bradley, J., Lodderstedt, T., Jones, M., & Waite, D. (2023). OAuth 2.0 Demonstrating Proof of Possession (DPoP) (RFC 9449). IETF. https://www.rfc-editor.org/rfc/rfc9449