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 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 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:

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.
Hardcoded secrets rarely sit in obvious places like config.py. They hide in files people do not think of as code:

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/appTerraform 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.
Nobody hardcodes a production key on purpose. It happens through ordinary shortcuts:
.env.example gets copied from .env instead of written by hand.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.
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.
| Technique | Catches | Weakness |
|---|---|---|
| Pattern rules | Known key formats with fixed prefixes | Misses custom and generic passwords |
| Entropy checks | Random strings in suspicious places | Noisy: hashes and IDs look random too |
| Validity checks | Whether a found key still works | Needs a safe, read-only call per provider |
| History scanning | Keys deleted from current files | Slower 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
Prevention works in layers, from the developer's laptop to places git never reaches:

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 installPre-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.
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.
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.
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.
Detection finds the problem. Removing it means moving every credential somewhere designed to hold it:

| Where you run | Secrets manager | Better still |
|---|---|---|
| AWS | AWS Secrets Manager | IAM roles for compute, no keys at all |
| Azure | Azure Key Vault | Managed identities |
| Google Cloud | Secret Manager | Workload Identity Federation |
| Kubernetes | External secrets pulled from your cloud manager | Pod identity mapped to cloud roles |
| CI/CD | Encrypted CI secrets | OIDC federation from CI to your cloud |
| Multi-cloud / on-prem | HashiCorp Vault | Short-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.
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.
Work in this order, and do not skip step one because the repo is private:
For a provider-by-provider playbook, see our guide to what to do in the first hour after an API key leak.
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.

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
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.
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.
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.
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.
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.
.avif)
.avif)
.avif)
.avif)
.avif)


.gif)

