By clicking “Accept”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.
18px_cookie
e-remove
Blog

Secrets in AI-Generated Code: How Coding Agents Leak Credentials

Learn how secrets in ai code leak through agents, repos, configs, and git history—and how to detect and stop credential exposure fast
Published on
September 2, 2026
Updated on
September 2, 2026

Rotating keys, purging commits and force-pushing the clean history doesn't guarantee your credential isn't still sitting somewhere it shouldn't. Not all your secrets are truly cleaned up

What are secrets in AI-generated code?

Secrets in AI-generated code are credentials that an AI coding assistant writes into code, copies out of your project, or exposes through the systems it touches while working. A secret is any private credential: an application programming interface (API) key, a database password, an access token, a private key. A hardcoded secret sits in plain text inside the source code, where anyone with the code can read it.

The weakness itself is old. MITRE tracks it as CWE-798, Use of Hard-coded Credentials: "The product contains hard-coded credentials, such as a password or cryptographic key." It has appeared in the CWE Top 25 Most Dangerous Software Weaknesses every year from 2019 through 2024, and MITRE rates its likelihood of exploit as high.

What changed is the number of places a credential can end up, and how fast it gets there. A developer leaks a secret by committing it. An agent can leak the same secret four ways in a single task, and only one of them leaves a trace in your repository.

Why AI coding assistants hardcode and leak secrets

AI did not invent this mistake. It scaled it. Secrets in AI code come from two habits: what the models learned, and how the tools read your project.

At Endor Labs, we studied where AI-written code goes wrong, as we cover in our review of the common AI code security risks. A 2025 study of eight leading models found they generate vulnerable code at rates of 9.8% to 42.1%, with some models topping 40% on security benchmarks.

It learned from code that hardcoded secrets

Large language models (LLMs) learn by studying huge amounts of public code. Much of that code hardcoded secrets, so the models learned the same habit.

These systems also optimize for code that runs, not code that is secure. To keep an example working, a model will often paste a key straight into the code.

Many models even reuse the same placeholder secrets across many apps. When a placeholder happens to match a real key, that guess becomes a live leak.

It ingests your whole workspace

Assistants read your full project to understand it, including .env and config files. A .env file stores environment variables, which often hold real secrets.

That means an assistant can copy a live token into new code. It can do this even when a .gitignore or .npmignore file was meant to keep that token out.

Check Point research put the pattern plainly: "They ingest the entire workspace to build context… regurgitating sensitive tokens into the production code."

Where secrets leak in AI-assisted workflows

Secrets in AI code do not leak in only one place. They show up across the many files and tools that AI-assisted work touches.

One common spot is MCP configuration. MCP (Model Context Protocol) is the standard that lets AI assistants connect to outside tools and data. Another is git history, the full record of every past commit in a repository.

The MCP layer is worth extra attention. In our State of Dependency Management 2025 research, we found that 75% of MCP servers are built by individuals and 82% use sensitive APIs.

Location Why it's risky
Inline source code A secret in plain code is visible to everyone with repo access and ships to every environment.
.env files These hold real environment secrets, and assistants can read and copy them into generated code.
mcp.json / MCP configuration files Tool connections often store API keys in plain text that agents can expose.
Notebooks (.ipynb) Data notebooks save output and keys inline, and are often shared or committed by mistake.
Client-side/frontend bundles Anything shipped to the browser is public, so a secret there is exposed to every visitor.
Infrastructure-as-code Config files that define cloud setup often embed credentials that reach version control.
git history A secret removed from current code still lives in older commits.
AI agent config files Local agent settings can store credentials that get committed with the project.

For security leaders, this spread is a coverage problem. A scanner that reads only the default branch will miss secrets in notebooks, configs, and history.

The scale of these config-file leaks is easy to underrate. Lakera's review of AI assistant config files found this: "Across approximately 46,500 packages monitored, 428 contained a .claude/settings.local.json. Of those, 33 files across 30 packages contained credentials."

How big the problem really is

The volume of secrets in AI code is large and growing. The point is scope, not alarm. Clear evidence helps security leaders size the risk and plan coverage.

GitGuardian's State of Secrets Sprawl 2026 reports the trend directly: "28.65 million new hardcoded secrets were added to public GitHub commits in 2025 alone, a 34% increase year over year and the largest single-year jump we've recorded."

The same report ties part of this rise to AI. It found that Claude Code-assisted commits showed a 3.2% secret-leak rate, versus a 1.5% baseline. That is more than double the rate of other commits.

Two more figures from the same report stand out. AI service secrets reached 1,275,105, up 81% year over year. And 24,008 unique secrets were found in MCP-related configuration files.

The mix of leaked secrets is shifting toward AI, too. Wiz's AI-related secrets research found that "Three of the top five, and half of the top ten most common validated secrets [are] in some way tied to AI."

The real cost of a leaked secret

The cost of secrets in AI code is rarely limited to one app. One leaked credential can grant access far beyond the app it belonged to. An exposed cloud key, for example, can open storage, databases, and other services at once.

A secret in git history is also durable. It stays in old commits after you delete it from the current code. So cleanup takes more than one step, and a rushed fix can leave the real risk in place.

The blast radius of secrets in AI code is the real concern here. A single service token can expose customer data, internal systems, and other linked accounts.

There is a second exposure path that security leaders should track. Developers now paste source code into external AI tools every day, and that code carries secrets with it.

The Verizon 2026 DBIR found that source code is the most common data type submitted to external GenAI tools "by a significant margin." The same report found that shadow-AI data-loss events rose roughly 400% year over year.

For security leaders, this changes the math on coverage and compliance. It also matters for frameworks with tight remediation timelines, such as FedRAMP and the EU Cyber Resilience Act (CRA). Reviewing the cost of AI-generated code helps you justify the controls that keep coverage high.

Auditors increasingly ask for proof that AI-generated code is scanned, not just human-written code.

How to keep secrets out of AI-generated code

Preventing secrets in AI code is a layered job. Treat AI-generated code with the same rigor as human-written code, from the first prompt to production.

Detect secrets across the whole SDLC

Scan for secrets at every stage of the SDLC (software development lifecycle), not only at the end. Each stage catches leaks the earlier one missed.

  • Pre-commit hooks: Scan code before each commit is saved, so a secret never enters the repository.
  • IDE and code-review warnings: Flag secrets inside the integrated development environment (IDE) as developers write and review.
  • CI/CD scanning: Check every build in your continuous integration and continuous delivery (CI/CD) pipeline, so nothing leaks downstream.
  • Full git history scanning: Scan every past commit, not just the default branch, since deleted secrets stay in old commits.

Open-source tools like Gitleaks and TruffleHog cover parts of this work. For a wider view of what strong coverage looks like, see this guide to evaluating secret detection tools.

Validate which secrets are actually active

Regex-only scanners, which match any text shaped like a key, flag far too much. That noise buries the findings that matter and slows triage.

Validating whether an exposed credential is still live lets teams focus on real risk. Endor Labs Secrets Detection validates active credentials and supports custom rules for internal secret formats.

For security leaders, active validation cuts false-positive triage and lowers MTTR (mean time to remediate). It also gives clearer coverage reporting, so you know what was scanned and what was found.

Secure AI coding agents at the source

The earliest fix is a better instruction. Give assistants secure prompt patterns and rules so they avoid hardcoding from the start.

You can also let AI agents scan and fix secrets before code lands. The Endor Labs MCP Server helps both developers and AI coding agents fix secrets at the source.

Rules that travel with the repository keep every assistant consistent. New developers and new agents inherit the same guardrails without extra setup.

Start with a library of secure vibe coding prompts. You can also apply a safer prompt pattern that guides cleaner output. In a 2025 study, prompting the model to avoid specific weaknesses cut weakness density by 59% for GPT-4 — more than half — versus a plain prompt.

What to do when a secret has already leaked

Even with strong controls, some secrets in AI code will slip through. Here is the order of operations when that happens.

  1. Rotate the credential first. Replace the exposed secret with a new one before you investigate, so the old one stops working.
  2. Investigate second. Once the key is rotated, review what it could reach and whether it was used.
  3. Remember that deleting code is not enough. The secret still lives in git history, so it must be purged there too.
  4. Revoke exposed credentials. Fully disable the old secret at the provider, not just in your source code.
  5. Re-scan to confirm. Run a fresh scan across code and history to verify the secret is gone.

Frequently Asked Questions

Why do AI coding assistants hardcode secrets?

They learned from public code where hardcoding was common, and they optimize for code that runs rather than code that is secure.

Can I just use environment variables instead of hardcoding secrets?

Environment variables are safer than hardcoded values, but the .env files that hold them can still be read by AI assistants and leaked.

Does deleting a secret from my code remove it from git history?

No, the secret stays in older commits, so you must purge it from git history and rotate the credential.

Why isn't traditional secret scanning enough for AI-generated code?

Regex-only scanners flag anything shaped like a key, which creates noise, and they often miss secrets spread across configs, notebooks, and history.

Can AI assistants read my existing .env secrets?

Yes, many assistants read the whole workspace for context, so they can copy real secrets from .env and config files into new code.

What tools catch leaked secrets?

Open-source tools like Gitleaks and TruffleHog help, and platforms such as Endor Labs Secrets Detection add active credential validation and custom rules.

Secure AI code without slowing developers down

AI keeps writing more code every day. So secret prevention has to move to the moment code is generated, not just to a check before release. That keeps developers fast while coverage stays high.

The goal is full coverage across the SDLC without adding developer friction. Catch secrets at the prompt, in the IDE, in review, and in the pipeline, so real risks surface fast and false positives stay low.

A simple starting sequence works well:

  1. Scan your current repositories and full git history.
  2. Add pre-commit and CI/CD secret scanning to every pipeline.
  3. Validate which exposed secrets are active, so you fix the real ones first.

Want to see how Endor Labs keeps secrets in AI code out of production? Book a Demo.

Description goes here