SecurityIntermediate

Secrets Hygiene for AI Coding Tools: A Field Guide

DeveloperHat Team
14 min read

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.

.env file keys on disk AI assistant reads the repo Prompt sent to provider Logs + commits leak persists Exclude deny rules · .cursorignore Sandbox OS-level blocks Scan pre-commit + push Rotate when it leaks The secret's journey through an AI assistant A key the assistant can read can end up in a prompt, a trace, or a commit. Four gates sit between the key and the leak: exclude it, sandbox it, scan for it, rotate it.

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.

  • Claude Code. Add Read deny rules such as 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.
  • Cursor. .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.
  • GitHub Copilot. Content exclusion is configured by repository administrators or organization owners, on Copilot Business and Enterprise only — there is no .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:

  • Pre-commit hook, on the laptop. Gitleaks is the standard open-source scanner: fast, regex-and-entropy based, works offline, and ships with 150+ built-in detection rules. Wire it into the pre-commit framework with 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.
  • CI, on every push and pull request. Run the same scan in GitHub Actions — 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.
  • Push protection, on GitHub. GitHub's secret scanning push protection blocks pushes containing supported secrets before they land. It went generally available in May 2023 and has been on by default for pushes to public repositories since the February 2024 rollout, covering over 200 token types from more than 180 providers. Repository-level push protection for private repos needs GitHub Secret Protection (a paid add-on on Team or Enterprise) and is off by default — enable it explicitly. Know its limit: a developer can bypass the block, and it only recognises the token formats GitHub knows about. See GitHub's push protection docs for the current defaults.
  • 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.

  • Revoke or rotate the secret at its source — in the provider's dashboard, the database, the key store. The moment a secret touches a remote, assume it is compromised; bots scrape public GitHub for credentials within seconds. Rotation is the fix. Everything after this is cleanup.
  • Then scrub the history. Deleting the file in a new commit does not remove it — git keeps every version of every file, and the old commit still holds the secret byte for byte. Rewrite history with 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.
  • Treat the old value as public forever. Rewriting history changes commit hashes, but forks, clones, and cached views may still hold the old commits. That is exactly why rotation comes first: a scrubbed history with a still-valid key is a false sense of security.
  • 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

    OptionWhat it stopsWhat it missesEffortWhen it fails
    Keep secrets out of the projectKeys in files, prompts, and commitsKeys the running process needsLow — a secrets manager CLIA secret someone pastes "just this once"
    Tell the assistant what not to readThe assistant's file tools reading .envCommands, scripts, terminal, MCP toolsLow — committable configA new tool with no exclusion setting
    Catch leaks before they leaveSecrets in commits, at three checkpointsUnknown formats, bypassed hooks, --no-verifyMedium — hooks + CI + push protectionA secret format no scanner recognises
    Assume a leak and respondThe damage after a leakNothing — it is damage control, not preventionLow to write, high under pressureA 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.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.