Calendar Icon White
December 5, 2026
Clock Icon
9
 min read

Hardcoded Secrets: A Secrets Detection and Prevention Guide

Where hardcoded secrets hide (.env, notebooks, Kubernetes, Terraform state, CI), how secrets detection finds them, and how to stop new ones for good.

Hardcoded Secrets: A Secrets Detection and Prevention Guide
ChatGPT
Perplexity
Grok
Google AI
Claude
Summarize and analyze this article with:

TL;DR

Hardcoded secrets are API keys, passwords and tokens written directly into code, config or infrastructure files, and they stay in git history even after you delete them. Stopping them takes two things: secrets detection across files and full history to find the ones you already have, and pre-commit and pull request checks plus a secrets manager so new ones never land.

This guide covers where hardcoded secrets actually hide, how secrets detection works, the commands to set up blocking today, and what to do with a key once you find it. It is written by Strac, a Y Combinator-backed data security company trusted by enterprises, which has spent five years finding sensitive data, credentials included, across SaaS apps, endpoints and cloud.

✨ Secrets detection: what it finds and why it matters

Secrets detection scans code, configuration and history for credentials: cloud keys, database URLs with passwords, payment and AI provider keys, private keys and tokens. It matters because a working key skips every other control you have. Verizon's Data Breach Investigations Report has listed stolen credentials among the top ways attackers get in year after year. Here is what a good finding looks like:

Strac secret finding: an active AWS access key committed eight months ago in .env, deleted from the file but still in git history, with a Rotation steps button
Deleted from the file, still in history, and still working.

Three details make that finding useful: it found the key in history, not just the current file; it checked that the key still works; and it tells you how to rotate it. Most scanners stop at the first.

✨ Where hardcoded secrets hide

Hardcoded secrets rarely sit in obvious places like config.py. They hide in files people do not think of as code:

Six places hardcoded secrets hide: .env files, notebooks, Kubernetes manifests, Terraform state, CI files, and images or bundles

Two of these deserve a closer look because teams assume they are safe. Kubernetes Secret values are only base64-encoded, and the Kubernetes documentation warns they are stored unencrypted in etcd by default. Anyone can decode one:

# a "secret" from a committed manifest is one command from plain text
echo 'cG9zdGdyZXM6Ly9hZG1pbjpodW50ZXIyQGRiLmludGVybmFsOjU0MzIvYXBw' | base64 -d
# -> postgres://admin:hunter2@db.internal:5432/app

Terraform state is the other. HashiCorp's documentation on sensitive data in state is explicit that state can contain secrets in plain text, including generated database passwords, even when variables are marked sensitive. A committed terraform.tfstate is a credential dump. Keep state in a remote, encrypted, access-controlled backend and add *.tfstate* to .gitignore.

Why hardcoded secrets happen

Nobody hardcodes a production key on purpose. It happens through ordinary shortcuts:

  • "Just to test it." A key goes into code to try an API, and the commit includes it.
  • Sample files with real values. .env.example gets copied from .env instead of written by hand.
  • Notebooks. Data and ML work happens in notebooks, where keys get pasted into cells and printed into saved output.
  • AI coding tools. Coding agents read your environment and helpfully write the key into the config file they are editing, and copy-paste from chat moves keys around too.
  • Debugging CI. A token is echoed into logs while fixing a pipeline, and the log is kept.

None of these is solved by telling people to be careful. They are solved by tooling that catches the mistake at the moment it happens. Our guide on how to stop AI agents reading secrets covers the coding-agent case in more depth.

How secrets detection works

Scanners combine three techniques. Pattern rules match known formats, such as the AKIA prefix of an AWS access key or the ghp_ prefix of a GitHub token. Entropy checks flag long random-looking strings in places like assignments named password or token. Validation then asks the provider whether the key works.

TechniqueCatchesWeakness
Pattern rulesKnown key formats with fixed prefixesMisses custom and generic passwords
Entropy checksRandom strings in suspicious placesNoisy: hashes and IDs look random too
Validity checksWhether a found key still worksNeeds a safe, read-only call per provider
History scanningKeys deleted from current filesSlower on the first scan of large repos

Validation is what turns a noisy list into a short one. Strac makes a harmless read-only "who am I" call to the provider with your permission, never writing, sending or charging anything, so live keys go to the top and dead test values drop out. It covers cloud keys (AWS, Google Cloud, Azure), code and package tokens (GitHub, GitLab, npm, PyPI, Docker Hub), AI provider keys (OpenAI, Anthropic, Gemini, Hugging Face), payment and SaaS keys (Stripe, Twilio, SendGrid, Slack, Shopify, Datadog and more), private keys and database URLs. Strac stores only a one-way hash and a masked preview, never the secret itself. See how Strac's secret scanning works.

How many of the keys in your git history still work?

Book a demo of Strac secrets detection  ·  Run a free security scan

✨ Stop new hardcoded secrets: four layers

Prevention works in layers, from the developer's laptop to places git never reaches:

Four layers of secrets detection: pre-commit, pull request, full history and beyond git

Layer 1: pre-commit. A hook that scans staged changes stops the key before it exists in history. The open-source Gitleaks project ships a ready-made hook for the pre-commit framework:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.24.2        # pin a release tag you have reviewed
    hooks:
      - id: gitleaks

# then, once per clone:
pip install pre-commit && pre-commit install

Pre-commit hooks are optional by nature, since anyone can skip them with --no-verify, so treat them as a convenience for developers, not a control. Layer 2: the pull request. A required check that fails when a new secret appears is the real gate. GitHub's push protection blocks known token formats at push time on GitHub, and Strac fails pull request checks on GitHub and GitLab when a new secret is added.

Layer 3: scan the full git history

Prevention does nothing for the keys already committed. A history scan reads every commit on every branch, which is where most live findings come from on a first run. You can try it locally:

# scan the full history of the current repo
gitleaks git -v .

# list every commit that ever touched a .env file
git log --all --full-history --oneline -- '*.env' '.env*'

At company scale you want this across every repo, re-run on every new commit, with findings tied to the commit and author. Strac does exactly that, and includes notebooks, decoded Kubernetes secrets and committed Terraform state. Our guide to secret scanning in code and git history goes deeper on history scanning.

Layer 4: secrets beyond git

Git is not the only place keys leak. Developers paste them into Slack to unblock a teammate, drop them in a Google Doc runbook, attach them to a Jira ticket, or share them with an AI assistant while debugging. A git-only scanner cannot follow them there. Strac's data loss prevention product, which is where the company started, finds the same credentials in Slack, Google Workspace and AI tools, so one platform covers both the repo and the chat thread where the key was shared.

Hardcoded secrets in the AI coding era

AI coding assistants changed how secrets leak. An agent asked to "get the Stripe integration working" will happily paste a test key into a config file to make the tests pass, and a developer accepting a large diff is less likely to notice one line. Agents also read local files, including .env, and can echo their contents into a chat transcript, a commit message or a generated README. The same developer who would never commit a key by hand may paste one into an AI chat while debugging.

The answer is not to ban the tools; it is to make the four layers above cover them. Pre-commit hooks and PR checks catch keys an agent writes into code, whoever typed them. Keep .env files out of the directories agents can read where your tooling allows it, and give agents scoped, short-lived test credentials rather than production keys. Strac's DLP covers the other half, finding credentials pasted into AI tools like ChatGPT and Claude before they leave the browser.

✨ Replace hardcoded secrets with a secrets manager

Detection finds the problem. Removing it means moving every credential somewhere designed to hold it:

Hardcoded secrets versus a secrets manager: where they live, who can read them, rotation and logging
Where you runSecrets managerBetter still
AWSAWS Secrets ManagerIAM roles for compute, no keys at all
AzureAzure Key VaultManaged identities
Google CloudSecret ManagerWorkload Identity Federation
KubernetesExternal secrets pulled from your cloud managerPod identity mapped to cloud roles
CI/CDEncrypted CI secretsOIDC federation from CI to your cloud
Multi-cloud / on-premHashiCorp VaultShort-lived dynamic credentials

The right-hand column matters most. The safest secret is the one that does not exist: workload identity and OIDC federation let services and CI jobs get short-lived credentials on demand, so there is no long-lived key to leak in the first place.

Cutting false positives without missing real keys

A secrets detection tool that cries wolf gets ignored, and then the real key slips through with the noise. Most false positives come from four places: test fixtures with fake keys, example values in documentation, high-entropy strings that are not credentials (hashes, UUIDs, encoded images), and keys that were real once but are long dead.

Tune in this order. First, use provider-specific patterns before generic entropy rules; an AWS access key or a Stripe live key has a recognizable shape. Second, mark known test values in an allowlist kept in the repo, so the exception is reviewed like code. Third, and most useful, check validity. A read-only call to the provider tells you whether a key still works, which splits findings into the few that need action today and the many that are history. Strac runs that check on every finding, so the alert you see first is the live key, not the fixture from 2019. Track how long live keys stay open as a metric; it is the number your auditor and your board will care about.

You found a hardcoded secret. Now what?

Work in this order, and do not skip step one because the repo is private:

  1. Rotate it. Create a new key, deploy it, revoke the old one. Until the old key is revoked, it still works for anyone who copied it.
  2. Check the logs. Look at the provider's access logs for use of the old key since it was committed.
  3. Move it. Put the new key in a secrets manager and reference it from code.
  4. Clean history if needed. Rewriting history is optional once the key is dead, and disruptive, but some teams do it for hygiene.
  5. Record it. Note what leaked, when it was rotated and why. Your auditor will ask.

For a provider-by-provider playbook, see our guide to what to do in the first hour after an API key leak.

✨ Hardcoded secrets, SOC 2 and audit evidence

Auditors look for credential handling under SOC 2's logical access criteria (CC6.1) and vulnerability detection (CC7.1), and customers ask about it in every security questionnaire. With Strac, every leaked key found and rotated is saved as SOC 2, ISO 27001 and HIPAA evidence automatically, and secret scanning sits beside dependency scanning, cloud checks and the AI pen test in one platform at one price. Rotation deadlines belong in your vulnerability management policy, and the wider picture is in our guide to application security posture management. To see what is in your repos today, Strac's free scan checks up to 10 GitHub repos and their full history.

Strac free scan report: four leaked secrets, one still active, plus vulnerable and malicious package counts

Find every hardcoded secret in your code and history, and know which ones still work.

Book a demo of Strac secret scanning  ·  Run a free security scan

🌶️ Spicy FAQs about hardcoded secrets

What are hardcoded secrets?

Hardcoded secrets are credentials written directly into source code, configuration or infrastructure files: API keys, database passwords, tokens and private keys. Anyone who can read the file, or its git history, can use them.

Is it safe to store secrets in a .env file?

Only if the file never leaves the machine. A .env file is fine for local development when it is in .gitignore, but it is one of the most common sources of leaked keys because it is easy to commit by accident. Production secrets belong in a secrets manager.

Does deleting a secret from code remove it?

No. Git keeps every version of every file, so a deleted key is still in history for anyone with repository access, and in every clone and fork. The only real fix is to rotate the key, then optionally rewrite history.

How does secrets detection work?

Scanners match known key formats, such as the AKIA prefix of AWS access keys, and look for high-entropy strings in suspicious places. Good tools then check whether a found key still works, so you fix live credentials first instead of chasing test values.

Are Kubernetes secrets encrypted?

Not by default. Kubernetes Secret values are base64-encoded, which is an encoding, not encryption, and the Kubernetes documentation notes they are stored unencrypted in etcd unless you enable encryption at rest. A Secret manifest committed to git is a hardcoded secret.

Customer story

“Don’t just alert on problems, fix them.”

Scott Roberts, Chief Information Security Officer, UiPath

  • UiPath
  • Crypto.com
  • Inmar Intelligence
  • thredUP
  • Paymentology
  • Enveda
  • Genesis Molecular AI
  • MeridianLink
More customer stories →
What are hardcoded secrets?
Is it safe to store secrets in a .env file?
Does deleting a secret from code remove it?
How does secrets detection work?
Are Kubernetes secrets encrypted?
Discover & Protect Data on SaaS, AI, MCP, Endpoints & Cloud
Strac provides end-to-end data loss prevention for all SaaS and Cloud apps. Integrate in under 10 minutes and experience the benefits of live DLP scanning, live redaction, and a fortified SaaS environment.
Get compliant from $4,995

Latest articles

Browse all

Get Your Datasheet

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Close Icon