A repository is more than source code. It's the input to your builds, the trigger for your deployments, and often the place where credentials leak first. Someone who can push to it, or who can read a secret committed to it, can often reach production. This lesson protects the repository itself: who can access it and how, how to keep secrets out and what to do when one gets in, how to sign commits and tags so others can verify who made them, and which repository settings defend your software supply chain.
Before you start
You should be comfortable with remotes and authentication from lesson 5, protected branches from lesson 7, and CI from CI/CD with Git: GitHub Actions, GitLab CI/CD, and Open-Source Alternatives. Practice history rewriting only on throwaway repositories.
Access: who can do what
Start with least privilege: everyone and everything gets the minimum access their work needs.
- People: give read access broadly, write access to those who contribute, and admin access to very few. Use teams or groups rather than individual grants, so access follows roles and ends when someone leaves the team.
- Multi-factor authentication: require it for everyone in the organization. Most platforms can enforce it.
- Automation: give each CI job, bot, or server its own narrowly scoped credential. A deploy server that only pulls code needs a read-only deploy key for one repository, not a person's account.
- Tokens: prefer fine-grained, repository-limited, short-lived tokens. Review and remove unused tokens, keys, and integrations regularly.
- Offboarding: when someone leaves, remove their access the same day, and rotate any shared secrets they could have seen.
Protect the branches and tags that matter
Branch protection (lesson 7) is a security control, not only a workflow one. For the main and release branches:
- require pull requests with at least one approval, and dismiss approvals when new commits are pushed;
- require passing status checks;
- block force pushes and deletion;
- include administrators in the rules, so a compromised admin account can't bypass them silently;
- protect release tags (for example
v*), so they can't be moved or deleted.
Require review from code owners for sensitive paths, especially CI configuration. Whoever can change a workflow file can usually make CI run any command with its secrets.
Keeping secrets out
Anything committed becomes part of history and is copied to every clone, fork, and CI cache. A secret in an old commit is just as exposed as one in the current files. Prevention is far cheaper than cleanup:
- Never put secrets in tracked files. Load them from environment variables or a secrets manager; keep
.envfiles in.gitignoreand commit a.env.examplewith placeholder values. - Scan before commit. A pre-commit hook with a scanner such as Gitleaks stops a commit containing something that looks like a key.
- Scan on push. Platform features such as GitHub's push protection and secret scanning, or GitLab's secret detection, catch what slips past local hooks.
- Scan history once. When adopting a scanner, scan the whole history, not only new commits.
# Scan the full history of the current repository
gitleaks git -v .When a secret is committed
Follow this order; the order matters.
- Revoke or rotate the secret immediately. Assume it's compromised the moment it was pushed: bots scan public repositories for keys within minutes. Revoking makes the leaked value useless; nothing else does.
- Check for misuse in the provider's logs (API calls, sign-ins, billing).
- Remove it from the current code and load it from a proper secret store.
- Optionally, rewrite history to remove it from old commits, which reduces exposure but can't undo it.
To rewrite history, the Git project recommends git filter-repo (a separate tool) over the older git filter-branch:
# Work on a fresh mirror clone, never on your only copy
git clone --mirror git@code.your-company.test:team/app.git
cd app.git
# Replace the leaked value everywhere in history
printf 'AKIAEXAMPLELEAKEDKEY==>REMOVED\n' > ../replacements.txt
git filter-repo --replace-text ../replacements.txt
git push --force --mirrorRewriting history has costs and limits: every commit ID after the change is different, so everyone must re-clone; open pull requests break; and copies outside your control (forks, other clones, CI caches, pull request references on the platform, search engine caches) may still hold the secret. Some platforms require contacting support to purge cached references. That's why step 1 always comes first.
Signing commits and tags
Git records an author name and email on each commit, but anyone can type any name and email into their configuration. A signature proves that the commit was made by someone holding a particular private key. Git supports three formats: GPG (OpenPGP), SSH keys (since Git 2.34), and X.509 certificates (S/MIME). SSH signing is the simplest if you already use SSH keys.
Signing with an SSH key
# Use a dedicated signing key, or your existing SSH key
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519_signing.pub
git config --global commit.gpgsign true
git config --global tag.gpgSign trueTo verify signatures locally, Git needs to know which keys belong to whom. List them in an allowed signers file:
echo "ada@example.test $(cat ~/.ssh/id_ed25519_signing.pub)" >> ~/.config/git/allowed_signers
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signersNow commits are signed automatically, and verification shows who signed:
$ git verify-commit HEAD
Good "git" signature for ada@example.test with ED25519 key SHA256:hfAGqwJA0RIWntO1FgGD9xYVOvB11w/qj86U6IgYk0I
$ git log --format='%h %G? %s' -2
586490f N Unsigned
db9f9c2 G Signed commitIn %G?, G means a good, trusted signature and N means no signature. Add the same public key to your hosting account as a signing key, and the platform marks your commits as verified.
What signing does and doesn't prove
A valid signature proves that the holder of that key created the commit, and that it hasn't been altered since. It doesn't prove the code is correct or safe, that the key wasn't stolen, or that the person behind the key is who they claim to be outside your organization. Signing is most valuable combined with rules: some platforms can require signed commits on protected branches, and release tags signed by known maintainers let users verify releases (git verify-tag v1.2.0).
Protect signing keys like any credential: a passphrase, or a hardware security key.
Repository supply chain protection
The repository feeds everything downstream, so protect what goes into it and what comes out:
- Review dependency changes: treat lockfile changes in pull requests as code. Automated update tools (Dependabot, Renovate) keep dependencies current through reviewable PRs.
- Guard CI configuration: require code owner review for workflow files, pin third-party actions to commit SHAs, and set minimal token permissions.
- Don't run untrusted code with secrets: pull requests from forks shouldn't trigger workflows that have access to secrets.
- Protect releases: tag protection, signed tags, and build provenance so users can trace an artifact back to a commit.
The Software Supply Chain Security lesson in our security series covers lockfiles, SBOMs, pinned actions, and provenance in depth.
Auditing what happened
Controls need checking. Platforms keep audit logs of security-relevant events: permission changes, new deploy keys and tokens, changes to branch protection, repository visibility changes, and force pushes. Review them regularly, and forward them to your logging system if you can, so a quiet change to a protection rule doesn't go unnoticed.
Git itself can help audit history. To list recent commits on the main branch that aren't signed by a known key:
git log --format='%h %G? %an %s' origin/main -50 | awk '$2 != "G"'Also review, every quarter or so, which people, teams, deploy keys, tokens, and installed apps have access to each repository, and remove anything nobody can explain.
Security hygiene checklist
- MFA required for all members.
- Access granted through teams; admins are few; access reviewed quarterly.
- Deploy keys and tokens are scoped, read-only where possible, and expire.
- Main and release branches protected, including from admins; release tags protected.
- Code owners required for CI configuration and sensitive code.
- Secret scanning in pre-commit hooks and on push; history scanned once.
- A written plan for leaked secrets: revoke first.
- Signed commits or at least signed release tags.
- Dependency updates arrive as reviewed pull requests.
Common mistakes and troubleshooting
- Deleting the file and thinking the secret is gone. It's in history and every clone. Revoke it.
- Rewriting history before revoking. The secret stays valid in all the copies you can't reach.
- Personal tokens in CI. If the person leaves, CI breaks, and the token usually has far more access than CI needs.
- Admins exempt from branch protection. A single compromised admin account bypasses every rule.
- Signing without verification. Signatures help only if someone checks them: platform rules,
verify-commit, orverify-tag. - "error: Load key ... invalid format" when signing.
user.signingkeymust point to the key file (often the.pub) or contain the key itself, andgpg.formatmust bessh.
Practical exercise: harden a test repository
- On a test repository, require MFA for the organization (if you can), protect
main(including admins), and protectv*tags. - Create a read-only deploy key and clone with it.
- Install a secret scanner as a pre-commit hook and confirm it blocks a commit containing a fake key such as
AKIAEXAMPLE.... - In a throwaway repository, commit a fake secret, then remove it from history with
git filter-repo --replace-text, and confirm withgit log -p --allthat it's gone. - Set up SSH commit signing with an allowed signers file, sign a commit and a tag, and verify both.
- Add your signing key to your hosting account and check that commits show as verified.
Key takeaways
- Apply least privilege to people, bots, and tokens; require MFA; protect main, release branches, and tags, including from admins.
- Keep secrets out with ignore rules and scanners; a committed secret is a leaked secret.
- When a secret leaks: revoke first, check for misuse, then clean history with
git filter-repoif needed. - Sign commits and tags with SSH, GPG, or X.509, and verify signatures; signing proves key ownership and integrity, not code quality.
- Guard CI configuration and dependency changes as part of the supply chain.
References
- Pro Git: Signing Your Work (opens in a new tab)
- Git documentation: git config (gpg.format, gpg.ssh.allowedSignersFile) (opens in a new tab)
- GitHub Docs: About commit signature verification (opens in a new tab)
- git-filter-repo (opens in a new tab)
- Gitleaks (opens in a new tab)
- GitLab Docs: Protected branches (opens in a new tab)
- OWASP Secrets Management Cheat Sheet (opens in a new tab)
What's next
To reason confidently about signatures, history rewriting, and recovery, it helps to know how Git stores data. Understanding Git Internals: Objects, References, Packfiles, and History looks inside.

