TL;DR
AI coding assistants read your whole repo — including the keys in it. Four layers of defence, from exclusion rules to rotation, that keep secrets out of prompts, logs, and commits.
The old rule was simple: never commit a secret. The new rule is harder: never let a secret be seen by anything that might repeat it. An AI coding assistant is not a linter. It reads your repository, runs your commands, and sends what it finds to a model provider — and it does that on your machine, in your repo, with your keys sitting a directory away. A .env file that never reaches git can still reach a prompt, a transcript, a log file, or a commit the agent makes on your behalf.
The short version: treat every AI assistant as a new person on the team with broad read access and no memory of what is secret. Four layers keep you safe: keep secrets out of the project, tell each assistant what not to read, scan every commit before it leaves, and assume a leak will happen anyway — so rotate fast. No single layer holds. Together they cover the paths a key actually travels.
Why the old rules stopped being enough
Three things changed at once. First, the reader changed. A coding assistant does not read the file you open; it reads the project. Cursor indexes the whole directory for codebase search, GitHub Copilot reads open files and visible tabs, and an agentic tool like Claude Code can run cat, grep, and printenv and feed the output straight into its context. A key in a .env file, a config file, or your shell environment can end up in a prompt sent to a provider, in a session log, or in a commit an agent pushes — without you typing it anywhere.
Second, the scale of the leak changed. GitGuardian's State of Secrets Sprawl 2026 report counted 28.6 million new hardcoded secrets in public GitHub commits during 2025, up 34% on the year before. The tooling got better and the numbers still went up — because the number of things that can read a secret went up faster than the number of things that block one.
Third, the evidence that "it can't happen to us" keeps failing in public. In March 2023, Samsung engineers pasted confidential semiconductor source code into ChatGPT three times in three weeks — once to fix a bug, once to optimise a test sequence, once as a meeting transcript for minutes — and Samsung capped prompts at 1,024 bytes, then banned generative AI tools outright on 1 May 2023. In November 2026, Cursor disclosed that an attacker had copied stored coding-agent traces after obtaining an access key Cursor had issued to its inference provider, Fireworks AI — and some of those traces held API keys in plain text, because an agent had read them or a person had pasted them in. Cursor said fewer than 0.05% of users had traces exposed and fewer than 0.01% had API credentials exposed; sessions in Privacy Mode were not affected. The lesson is not that Cursor is unsafe. It is that a key an agent can read is a key that can end up in a stored trace, on someone else's infrastructure, outside your control.
The options
Option 1: Keep secrets out of the project
The strongest control is not a scanner or a setting — it is not having the secret on the machine at all. Load keys at runtime from a secrets manager or the OS keychain, not from a file in the repository. Tools like 1Password's op run, Doppler, and Infisical inject secrets into the process that needs them, so there is no .env file for an assistant to read. The running process — and any agent that can run it — still sees the values, so this is a narrowing, not a cure.
If you must use a .env file, three habits matter: list it in .gitignore before the first commit, commit a .env.example with every variable name and a dummy value so nobody pastes a real one into Slack to "help" a teammate, and keep production keys off the machine where the agent runs — give the agent development keys with low limits, test-mode payment keys, and a non-production database, so a leaked key costs little and is easy to rotate. OWASP's Secrets Management Cheat Sheet makes the same point about environment variables generally: they are accessible to every process on the machine and can turn up in logs and system dumps, so treat them as exposed by default.
Pick this first, always. It is the only option that protects against an assistant you have not configured yet, and it is the only one that works when the assistant is a tool you have never heard of.
Option 2: Tell each assistant what not to read
Every major assistant now ships an exclusion mechanism — and every one of them has gaps, which the vendors document themselves. A checklist that checked the documentation of Claude Code, Cursor, GitHub Copilot, and Gemini CLI in October 2026 found the same pattern in all four: the exclusion covers the assistant's file tools, not everything the assistant can run.
Read(./.env), Read(./.env.), and Read(./secrets/) to permissions.deny in .claude/settings.json. A .claudeignore file has no effect. The deny rules do not cover scripts that open files by themselves — grep -r or a Python script the agent writes can still read the file. Claude Code's sandbox can enforce this at OS level with sandbox.filesystem.denyRead paths (for example ~//.env), so a sandboxed command and its child processes cannot read the file either; by default the sandbox still lets commands read most of the machine, so list the secret paths explicitly. Our guide to securing AI agents with sandboxing covers the sandboxing decision in depth..env files are ignored by default, and a .cursorignore file in gitignore syntax adds more paths — commit it, so the whole team benefits. But Cursor says complete protection "isn't guaranteed due to LLM unpredictability", and the terminal and MCP tools its agent uses run outside its file-access controls, so a key the agent reaches through a command is not covered..copilotignore file. And it is not supported in the Edit and Agent modes of Copilot Chat in VS Code and other editors, which is exactly where an agent reads the most.Pick this as your second layer, and configure it in the repo, not on one laptop: .cursorignore and .claude/settings.json are committable, so the protection travels with the clone. But do not treat an exclusion as a guarantee. The vendors do not, and neither should you.
Option 3: Catch leaks before they leave
Exclusions fail, so scan at every exit. Three checkpoints, each catching what the previous one missed:
repo: https://github.com/gitleaks/gitleaks and the gitleaks hook, or into husky with gitleaks git --pre-commit --redact --staged --verbose. The --staged flag scans only what you are about to commit, so it stays fast, and --redact keeps the secret out of your terminal scrollback. (Older guides use gitleaks protect --staged; that command was deprecated in v8.19.0.) Hooks are per-clone and git commit --no-verify skips them, so a hook is a safety net, not a gate.gitleaks/gitleaks-action with fetch-depth: 0 so it sees full history — and add TruffleHog, which goes a step further: it classifies over 800 secret types and verifies* each candidate by calling the provider's API (an AWS key is checked against GetCallerIdentity), so --results=verified shows only credentials confirmed live. That verification is what turns a noisy scanner into a triage list. Our guide to securing CI/CD pipelines covers the pipeline side of this in detail.Pick all three checkpoints. The hook is fastest, CI is the one nobody can skip, and push protection is the last line before the secret is on someone else's server.
Option 4: Assume a leak and respond
Sooner or later a key escapes — through a prompt, a trace, a commit, or a screenshot. The response order matters, and GitHub's own documentation states it plainly: rotate first, rewrite history second.
git filter-repo (the tool Git's own docs now recommend; version 2.47 or later for the --sensitive-data-removal flag), for example git filter-repo --sensitive-data-removal --invert-paths --path .env, or BFG Repo-Cleaner for very large repos. Then force-push, and tell every collaborator to re-clone or hard-reset — if someone merges an old local branch, the secret comes right back.Pick this as a runbook, written down before you need it. The teams that recover in minutes are the ones that rehearsed the rotation; the ones that take days are the ones discovering, mid-incident, who owns the key and where it is used.
The comparison
| Option | What it stops | What it misses | Effort | When it fails |
|---|---|---|---|---|
| Keep secrets out of the project | Keys in files, prompts, and commits | Keys the running process needs | Low — a secrets manager CLI | A secret someone pastes "just this once" |
| Tell the assistant what not to read | The assistant's file tools reading .env | Commands, scripts, terminal, MCP tools | Low — committable config | A new tool with no exclusion setting |
| Catch leaks before they leave | Secrets in commits, at three checkpoints | Unknown formats, bypassed hooks, --no-verify | Medium — hooks + CI + push protection | A secret format no scanner recognises |
| Assume a leak and respond | The damage after a leak | Nothing — it is damage control, not prevention | Low to write, high under pressure | A leak nobody notices for months |
Trade-offs
The trade-off nobody puts in the demo is convenience against blast radius. The most productive setup — production keys on the dev laptop, the agent free to read and run anything — is also the most exposed. Short-lived, scoped credentials (a read-only token, one repo, an hour of life) are the honest middle ground, and they pair naturally with zero-trust thinking: identity and scope per workload, not a standing master key. Every credential the agent holds should be one you could rotate in a minute without a meeting.
The second trade-off is false positives against coverage. A scanner that flags test fixtures and example keys will be disabled within a week; a scanner tuned to silence will miss the real leak. Budget the tuning time: gitleaks:allow comments and a .gitleaksignore baseline for known-safe findings, and TruffleHog's --results=verified in CI so the gate only blocks on credentials confirmed live. A gate the team trusts is a gate that stays on.
The third trade-off is where the secret lives vs. who can read it. A secrets manager removes the file but not the access: any agent that can run the process can read the injected values, and any agent that can read the process's environment can exfiltrate them through a tool call. Runtime injection plus a sandbox is the combination that actually narrows the hole — injection removes the file, the sandbox removes the reach.
And the trade-off teams forget: your assistant's memory is also a leak surface. A key pasted into a chat stays in the transcript, the session log, and possibly the provider's stored traces — deleting it from the file afterwards removes nothing. If a key was exposed to the assistant, rotate it. Deleting the message is not rotation.
Recommendation
For most teams using AI coding tools this quarter: do all four layers, in order, and start with the cheapest. Keep production secrets off the agent's machine and give it development keys. Commit the exclusion config (.cursorignore, Claude Code deny rules) so it travels with the repo. Add a gitleaks pre-commit hook and the same scan in CI, turn on push protection, and write the rotation runbook before you need it. That stack costs an afternoon to set up and covers the paths keys actually travel.
Add TruffleHog verification when the team is triaging too many unverified findings, or when you need to know — not guess — whether a leaked credential is still live. Add OS-level sandboxing when the agent runs commands you did not write, which is to say, whenever the agent is genuinely agentic rather than a fancy autocomplete.
When not to build this
Do not build a four-layer secrets programme for a solo hobby project with no production keys and no collaborators. .gitignore plus push protection is enough there, and the rest is ceremony.
Do not buy an enterprise secrets platform because an AI tool scared you. The free layers — runtime injection from a manager you already pay for, committable exclusion config, open-source scanners, GitHub's own push protection — cover the realistic threat. Spend the money when you have many repos, many developers, and a compliance requirement, not before.
Do not chase a scanner that promises zero false positives. It is either missing real secrets or it has not run yet. Tune the allowlist, gate CI on verified findings only, and accept that a human still triages the rest.
What to do next
This week, pick one repository where an AI coding assistant is already in daily use and do the four checks in order: is there a .env or credential file the assistant can read — and does the assistant actually need production keys, or will development keys do? Is the exclusion config committed (.cursorignore, Claude Code deny rules)? Is there a pre-commit scan and a CI scan, and is push protection on? And if a key leaked today, who rotates it, and how long would that take? If any answer is "we don't know", that is the gap to close first — and it is almost always the rotation runbook, which costs an hour to write and saves a weekend when it matters.
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.