Keeping Secrets Out of Source Code
Passwords, tokens and keys do not belong in a repository. See how secrets leak into code, how to prevent it, and what to do when one slips through.
On this page
A secret is any value that grants access: a database password, an API token, a private key, a signing certificate. Developers need these values to make software work, so they end up near the code. Sometimes they end up inside it. Once a secret is committed to a repository, it is copied to every clone, every fork and every backup. Removing it later is difficult, and assuming nobody saw it is dangerous.
This article covers how secrets leak, how to stop them leaking, and what to do when prevention fails.
How secrets end up in a repository
Almost nobody commits a password on purpose. It happens through ordinary shortcuts.
- Hardcoded values during testing. A developer pastes a token into a script to get something working and plans to remove it later.
- Configuration files added by accident. A file such as
.envorconfig.jsonsits in the project folder, and a broadgit add .sweeps it into the commit. - Copied examples. Sample code from documentation or a chat thread contains a real credential that someone forgot to replace.
- Debug output and logs. Log files or test fixtures saved in the repository sometimes record request headers that include tokens.
- Old history. A secret removed in a later commit still lives in earlier commits.
That last point is the one people underestimate. Git keeps history. Deleting a line in a new commit does not erase the line from the commits before it.
Why a leaked secret is such a problem
Automated scanners crawl public code constantly, looking for patterns that resemble keys and tokens. A credential pushed to a public repository can be found and tried by strangers very quickly. Private repositories are safer, but not safe: they can become public by mistake, be cloned to a laptop that is later stolen, or be read by a contractor who should only have seen part of the project.
The right assumption is simple. If a secret was ever committed, treat it as exposed.
Prevention: keep secrets outside the code
The core idea is to separate configuration from code. The program reads secrets at run time from somewhere that is not the repository.
Environment variables
The simplest approach is to pass secrets to the process as environment variables. The code asks for a name, and the deployment environment supplies the value.
import os
database_password = os.environ["DB_PASSWORD"]
This keeps the value out of the source file. For local development, many teams use a .env file that is listed in .gitignore, so it stays on the developer's machine.
A secrets manager
For production, a dedicated secrets manager is better than loose environment files. It stores values encrypted, controls who can read each one, records access, and supports rotation. Cloud providers and open-source projects both offer these. The point is not which product you pick, but that secrets live in a system built to protect them.
Short-lived credentials
Where possible, prefer credentials that expire. A token that works for an hour is far less valuable to an attacker than a password that has not changed in three years. Many platforms can issue temporary credentials to a running service so no long-term key needs to be stored at all.
Prevention: catch mistakes before they spread
People make mistakes, so add automatic guards.
- **Use a
.gitignorefrom the start.** List.env, key files and local configuration before the first commit. - Install a pre-commit hook. Tools that scan staged changes for secret-like patterns can block a commit before it is created. This is the cheapest place to catch a leak.
- Scan in your build pipeline. A second scan on every pull request catches anything the local hook missed, for instance when a contributor did not install it.
- Scan the full history once. Run a scanner across all past commits to find secrets that were committed long ago.
None of these checks is perfect, and scanners can produce false alarms. Together, they make a leak much less likely to survive.
What to do when a secret leaks
Speed matters, and the order of steps matters too.
- Revoke or rotate the secret first. Generate a new credential and disable the old one. This is the step that actually removes the risk. Rewriting history does nothing if the old key still works.
- Check the logs. Look at the access records of the affected service for activity you do not recognize, covering the time since the secret was first committed.
- Remove it from the repository. If needed, rewrite history with a tool designed for that purpose, then ask collaborators to re-clone. Remember that forks and caches may still hold the old data.
- Find the cause. Ask how it got in, and fix that gap, whether it was a missing ignore rule, a missing hook or a copied example.
- Write down what happened. A short note helps the team learn without blame.
Notice that cleaning the repository comes third. Many teams do it first because it feels productive, but the exposed credential is still active until it is rotated.
Habits that keep secrets safe over time
- Give each service its own credential with only the permissions it needs, so one leak has limited reach.
- Rotate secrets on a schedule, and whenever someone with access leaves the team.
- Keep example configuration files with placeholder values, such as
DB_PASSWORD=changeme, so new developers know what to set without seeing real data. - Avoid sharing secrets in chat messages or email, which are searchable and rarely deleted.
- Review who can read secrets in your manager at regular intervals.
Frequently Asked Questions
Is it safe to store secrets in a private repository?
It is safer than a public one, but it is still not recommended. Private repositories get cloned to many machines, shared with more people over time, and sometimes made public by accident. Storing secrets elsewhere means a repository leak does not also become a credentials leak.
If I delete the secret in a new commit, is the problem solved?
No. Git history still contains the earlier commit with the secret in it, and anyone who cloned the repository already has a copy. You must revoke or rotate the credential so the old value stops working, and then clean the history if you want to remove the traces.
Are environment variables completely secure?
They are a good basic practice but not a complete solution. Other processes running as the same user may be able to read them, and they can appear in crash reports or debugging output. For sensitive production systems, combine them with a secrets manager and strict access control.