Keeping Secrets Out of Git

Updated · 12 min read
mediumGit 2.53gitsecuritysecretsgitignoresafe-directoryinterview

A secret is any piece of information that gives access to something: a database password, an API key, a private SSH key, a cloud access token or a signing certificate. Keeping secrets out of Git means making sure they are never committed, because a committed secret is stored in history for good and copied into every clone. It is one of the most important habits in Git, because automated bots scan public repositories for leaked keys within minutes of a push.

Writing your bank PIN on a sticky note inside a library book is a close comparison. Taking the note out of your own copy later doesn't help: every copy that was printed has it.

Where Secrets Belong

Put it inExampleCommitted?
Environment variablesDB_PASSWORD set in your shell, IDE run settings or CINo
A local settings file listed in .gitignore.env, application-local.propertiesNo
A template with fake values.env.example with DB_PASSWORD=change-meYes
A secret managerAWS Secrets Manager, HashiCorp Vault, Azure Key VaultNo
CI/CD secret settingsGitHub Actions secrets, GitLab CI/CD variables, Bitbucket secured variablesNo

Example 1: A Local Settings File That Git Ignores

Navika keeps the database password for her own computer in .env, and commits only a template:

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
echo 'Term 1 fee: $12,000' > fees.txt
echo "DB_PASSWORD=Navika-local-2026" > .env
echo "DB_PASSWORD=change-me" > .env.example
printf "%s\n" ".env" "*.pem" "*.key" "application-local.properties" > .gitignore
git add .
git status --short
git check-ignore -v .env
Output
A  .env.example
A  .gitignore
A  fees.txt
.gitignore:1:.env	.env

Explanation: git add . staged everything except .env, because .gitignore lists it. git check-ignore -v confirms which rule ignores the file. The template .env.example is committed, so a new teammate knows which settings to create. Add the ignore rules before creating the secret file, so that it can never be staged by accident.

Terminal
git commit --quiet -m "Add the fees and a settings template"
Output
 

The Java code reads the value from the environment, never from a file in the repository:

DatabaseConfig.java
String password = System.getenv("DB_PASSWORD");
if (password == null) {
    throw new IllegalStateException("Set DB_PASSWORD first");
}

Example 2: Catching a Secret Before It Is Committed

.gitignore protects only the files it names. A password typed straight into a source file needs a check of the staged changes. Here is a small pre-commit hook, like those in "Git Hooks", that refuses commits adding lines that look like passwords or keys:

Terminal
cat > .git/hooks/pre-commit <<'EOF'
#!/bin/sh
if git diff --cached -U0 | grep -E -i "^\+.*(password|secret|api[_-]?key|token)[a-z_]*\s*[=:]" > /dev/null; then
  echo "pre-commit: this commit seems to add a secret:"
  git diff --cached -U0 | grep -E -i "^\+.*(password|secret|api[_-]?key|token)[a-z_]*\s*[=:]"
  echo "Move it to an environment variable, or commit with --no-verify if it is not a secret."
  exit 1
fi
EOF
chmod +x .git/hooks/pre-commit
echo 'String paymentApiKey = "pk_live_51Navika";' > Payments.java
git add Payments.java
git commit -m "Add payments"
Output
pre-commit: this commit seems to add a secret:
+String paymentApiKey = "pk_live_51Navika";
Move it to an environment variable, or commit with --no-verify if it is not a secret.

Explanation: the hook found the added line with ApiKey = and stopped the commit (git commit exits with code 1, and nothing is committed). Navika replaces the key with an environment variable and tries again:

Terminal
echo 'String paymentApiKey = System.getenv("PAYMENT_API_KEY");' > Payments.java
git add Payments.java
git commit --quiet -m "Add payments"
Output
pre-commit: this commit seems to add a secret:
+String paymentApiKey = System.getenv("PAYMENT_API_KEY");
Move it to an environment variable, or commit with --no-verify if it is not a secret.

Explanation: the hook blocked this commit too, although the line holds no secret: it still matches "a name containing ApiKey, then =". This is a false positive, and it shows the limits of simple patterns: they flag harmless lines and miss real secrets that don't look like name = value. Navika checks the line, is sure it is safe, and skips the hook for this one commit:

Terminal
git commit --quiet --no-verify -m "Add payments"
git log --oneline
Output
dd9a698 (HEAD -> main) Add payments
8df830e Add the fees and a settings template

Real projects use a dedicated scanner, which recognizes actual key formats instead of variable names.

Secret Scanners

Dedicated tools know hundreds of key formats (AWS, Google Cloud, Stripe, GitHub tokens, private keys) and check how random a string looks. They run in a pre-commit hook, in CI, or over the whole history. These are separate programs, so they are shown without output:

Terminal
# Scan the whole history of the repository in this folder
gitleaks git .
# Scan only what is staged, as a pre-commit hook does
gitleaks git --pre-commit --staged .
# Another scanner, also over the whole history
trufflehog git file://.

(Older gitleaks versions, before 8.19, used gitleaks detect and gitleaks protect --staged for the same two jobs.)

Hosting platforms scan too:

text
Secret scanning finds known key formats in repositories, and push protection blocks a push that
contains one, before it reaches the server. Both are free for public repositories; for private
repositories they are part of GitHub's paid security features. Find them under Settings, then
Code security.

Example 3: Searching History for a Secret

To find out whether a password was ever committed, search the changes in every commit (see "Searching History"):

Terminal
git log --all --oneline -S "pk_live"
git log --all --oneline -S "Navika-local-2026"
Output
 

Explanation: both searches came back empty: the blocked key never reached a commit, and .env was never committed. On a real project, a scanner such as gitleaks git does the same search for every known key format at once.

A Secret Was Pushed: What to Do

Then, in order:

  1. Rotate the secret at its provider (database, cloud, payment service), and check its logs for use you don't recognize.
  2. Remove it from the code and commit the fix, reading the new secret from the environment.
  3. Rewrite history to remove it from every commit, on a fresh clone, with git filter-repo --replace-text or --path ... --invert-paths, as shown in "Removing Files from History".
  4. Force-push every rewritten branch and tag, and ask every teammate to clone again, because old clones still contain the secret.
  5. Ask the platform to clear cached views and pull request references if needed (GitHub and GitLab have support processes for this), and close or update open pull requests that include the old commits.

If the repository was never pushed, steps 4 and 5 aren't needed, and amending or rebasing the last commits (see "Git Amend" and "Interactive Rebase") is enough. Rotate anyway if anyone could have seen it.

What to do when a secret is pushed, in order

safe.directory and Repository Ownership

A repository can contain settings that run programs, such as hooks and core.fsmonitor. If you ran Git in a folder owned by someone else, their settings could run programs as you. Since Git 2.35.2, Git refuses to work in a repository owned by another user. This is what Git prints, for example in a shared folder /srv/fee-tracker owned by another account:

What Git prints
fatal: detected dubious ownership in repository at '/srv/fee-tracker'
To add an exception for this directory, call:
 
        git config --global --add safe.directory /srv/fee-tracker

Explanation: if you trust the repository's owner, add the exception, exactly as the message says. It is stored in your global config, so a repository can't add it for itself. You see this message most often in Docker containers and CI jobs, where the files belong to a different user than the one running Git, and on Windows with folders on other drives. Avoid safe.directory = *, which turns the check off for every folder.

Terminal
git config --global --add safe.directory /srv/fee-tracker
git config --global --get-all safe.directory
Output
/srv/fee-tracker

Common Mistakes

Committing first and adding .gitignore later. An ignore rule doesn't remove files already tracked. Use git rm --cached .env, commit, and rotate the secret if it was pushed.

Deleting the secret in a new commit and thinking it is gone. It is still in every earlier commit.

Cleaning history but not rotating. The secret has already been copied. Rotation is the only real fix.

Putting secrets in commit messages, branch names or tags. They are pushed and kept like everything else.

Turning off safe.directory for every folder. Add only the folders you trust.

Under the Hood

Once a secret is committed, it lives in a blob object, and that blob is reachable from every commit whose tree includes it. git rm creates a new tree without the file, but the old commits and their blobs stay in the object database and are sent with every clone and fetch. Even after a history rewrite, the old objects remain in your reflog until it expires, in other people's clones, and on the server until it runs its own garbage collection, which you don't control. Hosting platforms also keep pull request refs (refs/pull/<n>/head on GitHub) that point to the original commits. This is why every guide insists on rotating first: Git is built never to lose data, and that applies to your secrets too.

Interview Corner

You accidentally pushed an API key. What do you do?

First revoke or rotate the key at its provider, immediately. Then remove it from the code, rewrite history with git filter-repo to remove it from every commit, force-push, have teammates re-clone, and ask the platform to clear cached references if needed.

Is deleting the file in a new commit enough?

No. The secret is still in every earlier commit and in every clone. And once pushed, it must be treated as leaked even after a history rewrite.

How do you keep secrets out of a repository?

Ignore secret files with .gitignore, read secrets from environment variables or a secret manager, commit templates with fake values, and run a secret scanner in a pre-commit hook and in CI. Hosting platforms add push protection.

What is safe.directory?

A global setting listing repositories that Git may use even though another user owns them. Git refuses such repositories by default, because their config and hooks could run programs as you.

Practice

Challenge: stop tracking a settings file. Navika's config/local.properties was committed before it was ignored. Make Git stop tracking it, without deleting her copy, and ignore it from now on.

What does Git print? Before you open the solution, decide what git status --short shows after git rm --cached.

Show solution
Terminal
mkdir config
echo "db.password=local-only" > config/local.properties
git add config/local.properties
git commit --quiet --no-verify -m "Add local settings"
git rm --cached --quiet config/local.properties
echo "config/local.properties" >> .gitignore
git status --short
ls config
Output
 M .gitignore
D  config/local.properties
local.properties

D means the file is staged for deletion from the repository, while ls shows that Navika's copy is still on disk. .gitignore is modified, and the file doesn't appear as untracked, because it is now ignored. After committing this, the file is gone from new commits, but it is still in "Add local settings": if the value were a real secret that had been pushed, she would rotate it and clean the history. (--no-verify skipped the pre-commit hook, which would have caught password=.)

Checkpoint. Install a secret scanner such as gitleaks, run it over the full history of one of your projects, and add it as a pre-commit hook or a CI step.

Quick check: keeping secrets out of Git

4 questions
1You pushed a database password. What is the first thing to do?
2Where should a Java program get its database password?
3.env was committed before .gitignore listed it. What stops Git tracking it?
4Why does Git refuse to work in a repository owned by another user?

Key Takeaways

Quick reference

CommandIt is used to
git check-ignore -v <file>Show which rule ignores a file
git rm --cached <file>Stop tracking a file but keep it on disk
git log --all -S "<text>"Find commits that added or removed text
git filter-repo --replace-text <file>Remove secrets from all history
git config --global --add safe.directory <path>Trust a repository owned by another user

Was this tutorial helpful?

Lesson 92 of 106