Committed Your .env to GitHub? Rotate First, Then Fix It

· 7 min read ·

A man in a green sweater stares at his laptop in alarm while a small white robot holds up a folder with a warning symbol, and a trail of paper sheets flies out the window into the night sky

If you committed a .env file to GitHub, rotate every key in it first, then stop tracking the file. Deleting it, or rewriting history, does not undo the exposure: anything that was ever in a public repo should be treated as copied. If you just pushed it, go rotate now and come back.

How it happens

Three ordinary paths:

  • The scaffold never ignores it. Your first git add . commits everything in the folder, .env included, if .gitignore does not list it.
  • The AI creates it mid-session. You ask for Supabase or Stripe wiring, the tool writes a .env, and your next commit sweeps it up without anyone mentioning it.
  • The “just for a second” commit. You commit .env to sync two machines, intending to remove it later.

Do I have this problem? One minute

Terminal window
git log --all --oneline --name-only -- '*.env*'
git log --all --oneline -G"$(cat ../canary.txt)"

The first lists every commit that touched any env file, variants like .env.production included, and names the file per commit. The second matches the diff text itself, so it also catches a key swapped in place on the same line, which a count-based -S search stays silent on (verified in a scratch repo: -S found only the commit that added the key, -G found that and the in-place rotation). Put the first 12 characters of the key in ../canary.txt first, as in the test below, and reading it from a file keeps the key out of your shell history. Keep the fragment to letters and digits, because -G reads it as a regular expression. If the first command prints anything, a key was committed. Also run git ls-files | grep env; you want to see only .env.example, or nothing.

Does deleting .env from GitHub remove the secret?

Git keeps every version of every committed file, so the old commit still holds your .env. A force-push does not close it either. GitHub’s sensitive-data guide lists where rewritten commits stay reachable: cached views by commit hash, any pull request that references them, and any fork, which GitHub says you must coordinate with the fork’s owner to clean. Every clone someone already made keeps its copy too.

For scale, a related mistake: in May 2024 Cybernews reported over a million secrets in .env files exposed on the web servers of more than 58,000 sites, including 140 valid Stripe API keys. That is files served by websites, not files in git, but it is the same file leaking by another route.

The fix, in order

1. Rotate first. GitHub’s guide says it plainly: if the data is a credential, revoke or rotate it first, and once it can no longer be used you generally do not need to rewrite history. Create the replacement key, deploy the server side with it, then revoke the old one (the rotation post walks a real rotation). Scrubbing history without rotating is cosmetic, because the old key still works everywhere it went.

2. Stop tracking it. Add .env to .gitignore, run git rm --cached .env, commit, and add a .env.example with variable names and empty values. New developers get setup instructions from the example file, not from a real key.

3. Skip the history rewrite if you rotated. GitHub recommends rewriting history only for data that cannot be rotated, such as personal data. If you need it anyway, work on a fresh copy of the repo (a rewrite is hard to undo) and install the tool first, because git filter-repo is a separate program:

Terminal window
pip install git-filter-repo
git filter-repo --path .env --invert-paths --force
git remote -v

That last command prints nothing, and that is the gotcha: filter-repo removes your origin remote on purpose, so a plain git push --force fails with “No configured push destination” (confirmed in a scratch repo). Add the remote back, then push every branch and every tag, because a plain push sends only the current branch:

Terminal window
git remote add origin YOUR_REPO_URL
git push --force --all origin
git push --force --tags origin

Run as two pushes against a local bare repo (by URL instead of a named remote), the secret was gone from every branch and tag. Then every collaborator re-clones. Open and merged pull requests will show broken diffs, so merge or close the open ones first.

Prevention

  • .gitignore with .env on day one, plus a tracked .env.example.
  • GitHub push protection. It blocks pushes that contain supported secret formats, including structured ones like private keys and database connection strings, and you can add custom patterns. GitHub enables it by default on new public repositories owned by personal accounts; on org-owned or older repositories, check Settings > Code security and analysis. It cannot know a key format it was never told about.
  • .dockerignore and deploy zips. A COPY . . in a Dockerfile copies your .env into the image unless .dockerignore lists it, and .dockerignore does nothing for an image you already pushed: anyone who pulls it has the file. Not tested here; it follows from how COPY works.
  • gitleaks in CI (optional, if you have CI; a solo Lovable project usually does not), so a scaffold that forgets .gitignore fails the build.

A test for your own machine

A gitleaks scan is the right tool for CI. The script below is for checking your own repo after the fix, from the point of view of someone who clones it. Put the first 12 characters of the old, already-rotated key in a file outside the repo (echo 'sb_secret_9f' > ../canary.txt, delete it afterward, so no live secret ever sits in a text file or your shell history) and run ./repo.test.sh ../canary.txt:

#!/bin/bash
# Behavior tests for the repo, from a fresh clone's perspective.
# Pass the first 12 characters of the old, rotated key in a file
# outside the repo: ./repo.test.sh ../canary.txt
canary=$(cat "${1:?usage: repo.test.sh CANARY_FILE}")
fail=0
say() { if [ "$1" -eq 0 ]; then echo "ok $2 - $3"; else echo "not ok $2 - $3"; fail=1; fi }
rm -rf /tmp/clone-check && git clone -q . /tmp/clone-check
if [ -z "$(ls -a /tmp/clone-check | grep -E '^\.env' | grep -vx '.env.example')" ]; then say 0 1 "a fresh clone contains no env file except .env.example"; else say 1 1 "a fresh clone contains no env file except .env.example"; fi
if git rev-list --all | xargs git grep -qF "$canary" 2>/dev/null; then say 1 2 "full history contains no secret"; else say 0 2 "full history contains no secret"; fi
ignored=0
for f in .env .env.local .env.production; do git check-ignore -q "$f" || ignored=1; done
if git ls-files --error-unmatch .env.example >/dev/null 2>&1 && [ "$ignored" -eq 0 ]; then say 0 3 ".env.example tracked and env files ignored"; else say 1 3 ".env.example tracked and env files ignored"; fi
exit $fail

Here is a run against a scratch repo with a committed .env. This is what you should see before the fix:

not ok 1 - a fresh clone contains no env file except .env.example
not ok 2 - full history contains no secret
not ok 3 - .env.example tracked and env files ignored

After rotate, stop tracking, and a git filter-repo scrub:

ok 1 - a fresh clone contains no env file except .env.example
ok 2 - full history contains no secret
ok 3 - .env.example tracked and env files ignored

Rotate-and-ignore without the scrub gives ok, not ok, ok. Read test 2 as a statement about that exact string: red means those characters are still in history, acceptable only because that specific key no longer works anywhere. Test 2 red on a key you have not rotated is a live leak, not a history problem. gitleaks agreed: leaks found: 1 before, no leaks found after the scrub.

A second scratch repo, one that ignores .env* and un-ignores .env.example and never had a key committed, passes all three. Test 3 checks git’s ignore behavior instead of grepping the text of .gitignore, so both ignore styles pass it. Test 2 searches branches and tags, not stashes, reflogs or GitHub’s pull request refs, and on a history too long for one command line it can miss a batch, so run gitleaks on very large repos. A green run is not a promise about every place a copy could live.

The assertions check what a cloner experiences, not how you fixed the repo, so a different fix passes the same tests, and a later change that breaks one of these behaviors turns a test red.

A prompt to start with

Check this repository for committed secrets: is any .env, .env.* or credentials file tracked now or anywhere in history, are any secrets behind VITE_ or NEXT_PUBLIC_ prefixes that ship to the browser, and does .gitignore cover every env file? List what you find and which keys need rotating. Do not rotate or delete anything yet.

If this turned up a live key, how to find and rotate leaked keys walks through the recovery, and the launch checklist has secrets as item one. Staging versus production is why your local .env should never hold production keys.

The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.

Comments