Blog/AI Security

How to keep API keys and secrets out of LLM prompts and context

Stop credentials, tokens and connection strings from entering prompts, context windows and model provider traffic, and know what to do if one does.

By Sagar Makker · 6 min read · October 2026
Concrete Wall
In short
Anything placed in a prompt can be repeated back, logged or sent to a third party.
Keep credentials server-side in tool code and a secrets manager, never in context.
Scan prompts and retrieved content for secrets, and rotate fast when one slips through.
The problem

This is for engineering managers and security leads whose teams build AI features and internal agents. Developers under deadline pressure paste API keys into system prompts, let agents read config files, or retrieve documents that happen to contain passwords. Once a secret is in the context window, it can appear in an answer, a log or a provider's request record. This post explains where secrets leak into prompts, how to keep them out by design, and how to respond when one gets in.

A developer builds an internal agent that calls the billing API. The quickest route is to put the API key in the system prompt and ask the model to include it in requests. It works. Months later, a user asks the agent to show its instructions for debugging, and the full key appears in a chat transcript that is shared in a team channel.

Other leaks are quieter. An agent with file access reads an environment file while answering a question. A knowledge base built from old wiki pages includes a page with database credentials, which retrieval then places into context for any user who asks a related question. None of this needs an attacker, only ordinary use of a system that treats context as private.

Why it happens
01Credentials are put in system prompts so the model can pass them to tools
02Agents with file or repo access can read config and environment files
03Knowledge bases ingest old documents that still contain passwords or tokens
04No secret scanning on prompts, retrieved chunks or model responses
05Teams assume system prompts are hidden, so nothing sensitive can surface
How to fix it
1
Move all credentials into tool code
Developers keep every key in a secrets manager and inject it only inside server-side tool functions at call time. The model sees the tool name and parameters, never the credential. The tech lead blocks any pull request that violates this.
2
Deny agents access to secret locations
The platform team blocks agent file and repo tools from reading environment files, key stores, CI configs and credential folders, using explicit deny paths. Agents should run in a workspace that contains no secrets in the first place.
3
Scan sources before they are indexed
The data owner runs a secret scanner over documents, wikis and tickets before ingestion into any knowledge base. Matches are removed or redacted at source, and the scan repeats on every re-index, not just the first load.
4
Scan prompts and responses at runtime
Engineering adds a lightweight secret-pattern check on the assembled prompt and on model output. If a key pattern is detected, the request is blocked or the value masked, and an alert goes to the security channel.
5
Write and rehearse a rotation runbook
Security documents how to revoke and rotate each credential type, who can do it, and how to check usage logs for misuse. Rehearse it so a leaked key can be replaced within a window your team defines.
Worked example
A SaaS team's support assistant clean-up

A B2B SaaS company in Bengaluru built a support assistant over its internal wiki and runbooks. During a pre-launch review, the security lead ran a secret scanner over the indexed content and found staging database passwords and an old payment sandbox key embedded in troubleshooting pages. The team removed them from the wiki, rotated every affected credential, moved the assistant's ticketing API key out of the system prompt into a server-side tool, and added a runtime check that masks key-like strings in responses. After launch, the assistant answered the same support questions, the wiki owners added scanning to their page review routine, and the security team had a tested rotation runbook ready.

Common mistakes
×
Believing system prompts stay hidden
System prompts can often be coaxed out or appear in logs and debugging output. Assume anything in context may become visible, and never place secrets there in the first place.
×
Scanning code but not documents
Repos often have secret scanning while wikis, tickets and shared drives do not. Extend scanning to every source that feeds an AI feature, because retrieval will surface whatever is indexed.
×
Deleting the leak without rotating
Removing a key from a page or log does not make it safe, since copies may exist elsewhere. Revoke and rotate the credential, then review its usage logs for unexpected activity.
Where an AI agent helps
Input
Prompt templates, indexed documents, agent tool configs and model responses
Agent does
Detects secrets in context sources and traffic, masks matches and opens rotation tasks
Human gate
Security owner approves rotations and any exception to the no-secrets rule
Outcome
Clean indexes, masked responses, and a rotation task list with owners
Checklist
Remove every credential from system prompts
Inject keys only inside server-side tool functions
Block agent access to env files and key stores
Scan documents for secrets before indexing
Add runtime secret checks on prompts and responses
Rehearse the credential rotation runbook
What to measure
Secrets found in indexed sources per scan
Runtime secret detections per month
Time from detection to key rotation
Prompt templates containing credentials
Questions
Is it safe to put a key in a prompt if the model provider does not train on our data?

No. Training is only one risk. The key can still be echoed in answers, stored in your own logs, or retained in provider request records under their terms. Keep keys in tool code where the model never sees them.

What patterns should a secret scanner look for?

Common key prefixes for your cloud, payment and messaging providers, private key blocks, connection strings, bearer tokens and high-entropy strings near words like password or secret. Tune it to the systems you actually use to reduce noise.

Our agent needs a credential to work. How does it authenticate?

The tool function authenticates on the server using a credential fetched from your secrets manager at call time, ideally a short-lived, narrowly scoped token. The model only requests the action; it never handles the credential itself.

Who should be alerted when a secret is detected?

Route alerts to the security owner and the owner of the affected system, with the source location and a request ID. The system owner rotates the credential; security confirms usage logs show no misuse.

Keep reading
All posts →
Cctv CameraAI Security
Prompt injection explained for business leaders, and how to reduce risk
5 min readRead →
Concrete WallAI Security
Keeping private documents private in RAG and AI search tools
5 min readRead →
Programming CodeAI Security
Least-privilege tool permissions for AI agents: a design guide
7 min readRead →
Next step

Want this fixed in your business?

Send the workflow. You get a scope and a fixed price within two working days — or a straight answer that it isn't a fit.

Secure by default · find → fix → verify · authorised scope only
Send a brief →enquiry@xdqlabs.com