basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    A secret got into a commit — change the secret first, clean the history second

    A password, token or key in a commit stays in history even after the file is deleted. If the commit went to GitHub, treat the secret as leaked: change it first, clean the history second — cleaning doesn’t undo what’s already been downloaded.

    Why the secret comes first

    A deleted file lives on in old commits: git show HEAD~1:.env prints it whole. After a push, a copy of the history is on GitHub, with everyone who ran clone or fetch, in forks, and in the pull request cache. Bots scan public repositories for tokens within minutes. Rewritten history only protects future clones.

    So the order is:

    1. Change the secret where it was issued: a new database password, a revoked Cloudflare token, a new key. The old value stops working, and the leak no longer opens anything (Secrets in Docker stacks).
    2. Remove the file from the repository and add it to .gitignore (.gitignore and a tracked file).
    3. If needed, clean the history.

    How to clean

    The commit isn’t pushed yet — rewrite your own history without affecting anyone:

    git rm --cached .env
    echo ".env" >> .gitignore
    git add .gitignore
    git commit --amend --no-edit      # if the secret is in the last commit

    If it’s deeper — git rebase -i back to the commit with the secret.

    Already on GitHub — git filter-repo (a separate program: pip install git-filter-repo, or the git-filter-repo package on Ubuntu) rewrites the whole history:

    git filter-repo --invert-paths --path .env          # remove the file from every commit
    git filter-repo --replace-text <(echo 'Kx9…==>***REMOVED***')   # replace a string everywhere
    git push --force --all

    After cleaning, every commit has a new hash: everyone else needs a fresh clone. GitHub keeps serving the old commits by direct hash for a while — GitHub support removes them completely on request.

    So it doesn’t happen again

    • .gitignore before the first commit (Git from scratch), and an allowlist in server repositories (Server configs in git).
    • git diff --staged before every commit.
    • GitHub push protection — on for public repositories, it rejects a push containing tokens of known services. The rejection gives the secret type, the commit and the file line: —— GitHub Personal Access Token ——, commit: 8728dbe67, path: README.md:4.