Hardcoded Secrets: How to Find, Fix, and Prevent Them [2026]

Superblocks Team
+2

Multiple authors

October 27, 2026

0 min read

Copied
0:00

Public GitHub commits added 28.65 million new hardcoded secrets in 2025. I'll cover how they end up in code (AI-assisted code included), how to detect them, and how to fix and prevent them. The short version is to rotate first and rewrite history only if rotation can't cover the exposure.

What are hardcoded secrets?

Hardcoded secrets are credentials such as API keys, passwords, tokens, and certificates that are written directly into source code or configuration files.

MITRE tracks the weakness as CWE-798 and splits it into two types. With inbound credentials, the product itself contains a login it checks users against, such as a default admin password. With outbound credentials, your code contains the login it uses to reach another system, such as a database.

OWASP also rates hardcoded passwords as High severity, with a very high likelihood of exploit.

To see how the fix looks in code, here is the same API call before and after.

Before the fix

import requests
API_KEY = "sk_live_9f2c1e7a4b"  # committed with the file
resp = requests.get(
    "https://api.example.com/v1/orders",
    headers={"Authorization": f"Bearer {API_KEY}"},
)

After the fix

import os
import requests
API_KEY = os.environ["ORDERS_API_KEY"]  # set outside the repo
resp = requests.get(
    "https://api.example.com/v1/orders",
    headers={"Authorization": f"Bearer {API_KEY}"},
)
# .env
ORDERS_API_KEY=sk_live_9f2c1e7a4b
# .gitignore
.env

In the first version, every clone of the repo includes the key. In the second, the value is stored in a .env file, and .gitignore keeps that file out of Git.

The API key in that snippet is one common type. Others include passwords, database connection strings, access tokens, and private keys. Codacy's list runs to 12 types. It also names SSH keys and service account keys, plus JWT signing keys.

Why hardcoded secrets happen

Apiiro's write-up says hardcoded secrets persist because they reduce friction in the short term. Three patterns stand out in these sources.

  • Prototype shortcuts, debug values left in code after a commit, copied snippets, and deadline pressure. Codacy lists all four.
  • Personal keys that are already set up in the builder's terminal, which prototypes use by default (Superblocks).
  • AI-generated code, where Superblocks' vibe coding security guide ranks hardcoded secrets as risk 2 of 7.

The third pattern shows up in the data. GitGuardian measured a 3.2% secret-leak rate on Claude Code-assisted commits, against a 1.5% baseline across all public GitHub commits.

The wider data points the same way. Leaked secrets tied to AI services rose 81% year over year, to 1,275,105 (GitGuardian, 2026).

The same report also found 24,008 unique secrets on public GitHub in configuration files for MCP, the protocol AI tools use to connect to other systems, and 2,117 of them were valid.

Why hardcoded secrets stay exposed after you delete them

Git keeps every commit. A "fix" commit that removes the line leaves the original in history, where Apiiro says secrets remain.

Old secrets often keep working. GitGuardian retested its 2022 dataset in January 2026 and found that more than 64% of the secrets were still valid. Internal repos hold more of them, too, and GitGuardian reports they are roughly 6x more likely than public repos to contain hardcoded secrets.

Toyota's October 7, 2022 notice (in Japanese) shows how long an exposure can last. A development subcontractor uploaded part of the T-Connect user site's source code to GitHub with public visibility, and it remained exposed from December 2017 to September 15, 2022.

The code included an access key for a data server. Toyota said 296,019 email addresses and customer management numbers may have been exposed, and it changed the keys on September 17.

The damage depends on what the key opens. Snyk's lesson lists three cases. An API key can be used to send thousands of premium requests billed to you, database or cloud storage credentials can expose sensitive data, and SSH keys or cloud tokens can give an attacker control of servers.

Rotating late costs more, because an exposed secret stays usable until you revoke it (GitHub docs).

How to detect hardcoded secrets

Use these checks together, because each one finds what the one before it missed.

Step 1. Stop secrets at commit time

A pre-commit hook scans staged changes and blocks the commit when it detects a match. Gitleaks provides one. Add this to .pre-commit-config.yaml and replace rev with the latest release tag. Then run pre-commit install:

repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.24.2
    hooks:
      - id: gitleaks

IDE plugins for VS Code and JetBrains catch it even earlier, flagging a secret as you type it, per Apiiro.

Step 2. Scan the history you already have

A hook only sees new commits, so scan the existing history as well:

gitleaks git -v path_to_repo
trufflehog git <repo-url> --results=verified

The --results=verified flag makes TruffleHog report only credentials it confirmed as valid and active through API testing. Those are the first ones to rotate.

Step 3. Turn on platform scanning

GitHub secret scanning checks the entire Git history on all branches. It also scans issues and pull requests, as well as discussions and wikis.

Availability depends on the repository. It runs for free on public repositories, while private and internal repositories in an organization need GitHub Secret Protection on Team or Enterprise Cloud.

Step 4. Fail the build in CI

A pre-commit hook runs on the developer's machine, and git commit --no-verify bypasses it (git docs). A CI scan that fails the build still checks those commits.

Code review adds a final human check. Reviewers should treat any literal that looks like a credential as a reason to block the merge until someone confirms it's a placeholder.

The steps above all read code, and a repository scanner can't see leaks that happen in tools such as Slack, Jira, and Confluence.

The size of that blind spot shows in GitGuardian's data. About 28% of incidents originate entirely outside repositories, and those are 13 percentage points more likely to be rated critical than secrets found only in code. Add your chat and ticketing tools to the scan scope.

The table below compares the three tools.

Tool Scans License / availability
Gitleaks Staged changes, history MIT
TruffleHog Git history (can filter to verified secrets) AGPL-3.0
GitHub secret scanning Full history, issues, PRs Free on public repos

How to fix hardcoded secrets (4 solutions)

Start with rotation. A revoked credential can no longer be used for access, even while it remains in the repo. Solutions 1 and 2 deal with a secret that is already in the repo, and Solutions 3 and 4 change where your code reads its values from.

Solution 1. Rotate the secret

Use it when a secret has ever been committed, even once. Snyk's lesson advises assuming it's compromised.

How to do it

  1. Revoke or rotate the credential at the provider.
  2. Update every service that depends on it.
  3. Check the provider's access logs for activity you don't recognize.

A revoked or rotated secret can no longer be used for access, which may be enough without rewriting any history (GitHub docs).

Solution 2. Rewrite Git history

Use it when rotation can't mitigate the risk, for example when the secret can't be revoked. Rewriting history also requires coordinating with everyone who has cloned the repository (GitHub docs).

How to do it

1. Remove the file from every commit, using its full path:

git-filter-repo --sensitive-data-removal --invert-paths --path path/to/file

2. Or replace matching text across history, with the values listed in a file:

git-filter-repo --sensitive-data-removal --replace-text ../passwords.txt

3. Force-push every ref:

git push --force --mirror origin

The force-push fails for refs under refs/pull/, which GitHub marks read-only. Those refs go through GitHub Support.

The rewrite changes every commit that contained the secret. Use git filter-repo for it, since the git project now recommends it over filter-branch and its README says BFG Repo-Cleaner is limited to a few kinds of rewrites.

Solution 3. Move secrets to environment variables

Use it for local development and single-service apps.

How to do it

  1. Replace the literal with a read from the environment, as in the "after" snippet above.
  2. Put the value in a .env file. Superblocks' deployment guide advises adding .env to .gitignore before the first commit.
  3. On a host, set the variable in its dashboard or CLI. Snyk notes that Heroku, Vercel, Netlify, Render, and AWS Elastic Beanstalk don't use your .env file directly.

Because the secret is stored outside the repo, new clones don't include it. A secret that is already in history still needs Solutions 1 and 2.

Solution 4. Use a secrets manager and managed connections

Use it for production systems and apps that more than one builder works on.

How to do it

  1. Store the credential in AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault and read it at runtime.
  2. Issue short-lived, narrowly scoped credentials where the platform supports them. Apiiro points to OIDC federation for this.
  3. For internal tools, replace personal API keys with a centrally managed Superblocks integration that uses a secrets store, as Superblocks' prototype-to-production guide describes.

A secret is stored once in the manager, so a rotation means one update, and builders reference it instead of keeping their own copies.

How to prevent hardcoded secrets in the future

These habits cut the chance that new secrets reach your repos:

  • Put the pre-commit hook in your repo template, so new projects start with it.
  • Add a CI job that fails the build on pull requests. Check AI-generated code at each commit too, since commits assisted by Claude Code leaked secrets at 3.2%, against a 1.5% baseline across public GitHub commits (GitGuardian).
  • Keep keys out of frontend code. Anyone who opens the app can read them in the browser's developer tools, per Superblocks' deployment guide.
  • Schedule recurring scans across all repos, branches, and pull requests, including commit history, and keep a written response plan for secret exposure (Apiiro recommends both).
  • For inbound credentials such as a default admin login, force a unique password at first login, as MITRE recommends.

How Superblocks detects hardcoded secrets

The practices above work in any repository. Superblocks is an enterprise platform for building apps with AI, where business teams build the apps and IT controls integrations and policies.

Its secrets controls sit at the publish step, and on the Enterprise plan the checks run before an app reaches users. Apps connected to Git are the exception, covered below. Four features supply the checks and controls.

  • Static analysis checks source code and the artifacts your build produces for exposed credentials, using its Leaked secrets category. It runs after the build and before deployment.
  • The Security Agent's default review covers hardcoded secrets, API keys, tokens, and passwords, and each flagged issue shows the code with secrets redacted.
  • Credentials go into an integration once, and builders reference it.
  • On a Replit import, personal API keys are replaced with token exchange or service accounts.

Since the August 25, 2026 release, scans and agents can run in Advisory mode or in Blocking with Exceptions mode. In the second mode, a check that reports an issue halts the publish, and builders can choose Publish anyway for false positives.

Only critical and high severity issues can halt a publish. In Static analysis, issues in the build output can block a publish in that mode, while issues found only in source are reported.

Apps connected to Git currently skip pre-publish policy agents, which include the Security Agent. For those apps, run Gitleaks or TruffleHog in your own CI pipeline, as in Step 4 above.

When a leak does happen, audit logs help with the investigation. Launched in the April 13, 2026 release, they record who is building apps and running queries, along with which packages are in use. Which of these checks you get depends on the plan.

Teams starts at $125 per month, billed monthly, or $100 per month billed annually, with 1 hosted app included and more at $10 per app per month. The plan has a 14-day free trial. Security agents and scans, audit logs, and secrets management appear under Enterprise, which uses custom pricing.

To see the secrets checks on your own apps, read the Superblocks docs or book a demo.

Frequently asked questions

What are some examples of hardcoded secrets?

Examples include an API key assigned to a variable in a Python file, a database password in a config file committed to Git, a private key stored next to the code, or a connection string with credentials inline. CWE-798 also covers default admin passwords included with a product.

What tools can detect hardcoded secrets?

Gitleaks and TruffleHog work locally and in CI, while GitHub secret scanning is part of the platform, free on public repositories and available on private ones with GitHub Secret Protection. Pair one scanner with a pre-commit hook and a CI check.

What's the hardest part of fixing hardcoded secrets?

Rotation is the hardest part, because Apiiro notes that embedded secrets are difficult to track, rotate, or revoke. Services that still hold the old credential fail once you revoke it. List the dependents first.

What should you do if you committed a secret?

Rotate it first. Then update every service that used it and read the provider's access logs. Rewrite history with git filter-repo only if rotation doesn't cover the exposure.

Is a .env file safe for hardcoded secrets?

For local development, a .env file keeps secrets out of the repo as long as .gitignore excludes it. For production, put the values in the host's settings or a secrets manager, because hosts such as Heroku and Vercel take variables from their own dashboard or CLI (Snyk).

Can Superblocks catch hardcoded secrets in apps made with AI?

Yes, on the Enterprise plan, at publish. Static analysis and the Security Agent both look for leaked credentials, and the agent redacts raw values in what it reports. Blocking depends on the scan mode, and apps connected to Git skip the agent and need checks in CI.

Stay tuned for updates

Get the latest Superblocks news and internal tooling market insights.

You've successfully signed up

Request early access

Step 1 of 2

Request early access

Step 2 of 2

You’ve been added to the waitlist!

Book a demo to skip the waitlist

Thank you for your interest!

A member of our team will be in touch soon to schedule a demo.

8

production apps built

30

days to build them

10

semi-technical builders

0

traditional developers

8+

high-impact solutions shipped

2 days

training to get builders productive

0

SQL experience required

See full story →

See the full Virgin Voyages customer story, including the apps they built and how their teams use them.

Large cruise ship sailing in a harbor with a road lined with palm trees and cars in the foreground.
Why not Replit, Lovable, or Base44?

"Those tools are great for proof of concept. But they don't connect well to existing enterprise data sources, and they don't have the governance guardrails that IT requires for production use."

Superblocks Team
+2

Multiple authors

Oct 27, 2026