Git Security Best Practices
In this page:
Keeping Secrets Out of Git
A password or API key committed to Git is effectively public the moment it's pushed, since Git preserves full history — anyone who clones the repo can dig it out of an old commit even after you "remove" it later. Keep secrets in an untracked .env file (listed in .gitignore) and load them at runtime instead.
Example: Keeping Secrets Out of Git
echo ".env" >> .gitignore
Scrubbing History for Comitted Secrets
Deleting a secret in a new commit leaves it fully intact in every earlier commit — history isn't overwritten by default. Actually removing it requires rewriting history with a tool like git filter-repo or BFG Repo-Cleaner, and even then you should treat the leaked credential as compromised and rotate it, since old clones may still have it.
Example: Scrubbing History for Comitted Secrets
git filter-repo --path secrets.env --invert-paths
Signing Commits with GPG
A GPG-signed commit carries a cryptographic signature tied to your key, which Git (and hosting platforms) can verify to prove the commit really came from you and wasn't tampered with — protection a plain commit, which only records a name and email you could type in yourself, doesn't offer.
Example: Signing Commits with GPG
git commit -S -m "Signed commit"
Auditing Remote Access Keys
SSH keys and personal access tokens don't expire on their own by default, so a key from a laptop you no longer use, or a token generated for a one-off script years ago, can sit around as a live, forgotten access point. Reviewing and revoking unused ones regularly closes that gap.
Example: Auditing Remote Access Keys
ssh-add -l
git config --global --get user.signingkey
Restricting Branch Access
Branch protection rules (available on GitHub, GitLab, etc.) can require passing CI checks and at least one approving review before a push to a branch like main is even allowed, turning code review from a social convention into something the platform actually enforces.
Example: Restricting Branch Access
# Configured on the hosting platform: require CI checks and reviews before merging to main
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: