Git Security Best Practices: Protect Code & Credentials

Git powers modern software development—but a misstep in configuration, access, or workflow can expose your intellectual property, leak credentials, or compromise your supply chain. This comprehensive guide distills practical, battle-tested security practices you can apply today across local repos, remotes (GitHub/GitLab/Bitbucket), CI/CD, and teams.


1) Secure Identity & Commit Integrity

Sign your commits and tags

Signed commits make tampering and impersonation detectable.

With SSH (lazy & fast):

git config --global gpg.format ssh
git config --global user.signingkey "$(ssh-add -L | head -n1)"
git config --global commit.gpgsign true
git config --global tag.gpgSign true

With GPG (widely supported):

gpg --full-generate-key
gpg --list-secret-keys --keyid-format=long
git config --global user.signingkey <KEYID>
git config --global commit.gpgsign true
git config --global tag.gpgSign true

Best practices

  • Enforce “verified” signatures in branch protection rules.
  • Sign tags used for releases (git tag -s v1.2.3 -m "Release 1.2.3").
  • Rotate keys periodically and revoke lost ones.

2) Protect Credentials & Secrets

Never commit secrets

Add a pre-commit hook or use the pre-commit framework + scanners:

pre-commit config (.pre-commit-config.yaml):

repos:
  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.5.0
    hooks:
      - id: detect-secrets
  - repo: https://github.com/zricethezav/gitleaks
    rev: v8.18.0
    hooks:
      - id: gitleaks

pip install pre-commit
pre-commit install

Prevent past secrets from haunting you

  • If a secret slipped in: revoke it immediately (cloud/API provider).
  • Rotate the credential.
  • Remove it from history:
    • git filter-repo --path .env --invert-paths (recommended)
    • or BFG Repo-Cleaner for simple patterns.
  • Force-push only after coordinating with the team.

.gitignore must-haves

# Secrets / env
.env
.env.*
*.key
*.pem

# Build output / cache
dist/
build/
.cache/

Use short-lived tokens

  • Prefer fine-grained PATs or OIDC with cloud providers in CI.
  • Avoid long-lived deploy keys with broad scope.

3) Hardening Local Git

Safe directories & file safety

# Prevent Git from trusting arbitrary ownership (esp. in shared folders/CI)
git config --global --add safe.directory /path/to/repo

Restrict credential helpers

Use OS keychains and avoid plain-text storage.

# macOS Keychain
git config --global credential.helper osxkeychain
# Windows Credential Manager
git config --global credential.helper manager-core
# Linux (libsecret)
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret

Defend against malicious diffs

  • Use modern Git (auto-updated) to benefit from security fixes.
  • Avoid executing hooks you didn’t audit (see §8).

4) Repository Access & Governance

Least privilege

  • Read for viewers, Triage for issue triagers, Write for contributors, Maintain/Admin for a very small set of owners.
  • Use organization teams and CODEOWNERS for scoped reviews.

CODEOWNERS example

*                 @org/leads
/frontend/**      @org/frontend
/infrastructure/** @org/devops

Branch & tag protection (must-have)

  • Require PR reviews (2+ for sensitive code).
  • Require commit signature verification.
  • Require status checks (build, tests, security scans).
  • Disallow force-push and deletion on protected branches.
  • Protect release tags from edits/deletions.

5) Secure PRs & Review Workflow

  • Use small, focused PRs—easier to review and audit.
  • Enable required reviewers via CODEOWNERS.
  • Block merges on failed checks (tests, linters, SAST, secret scan).
  • Require linear history or squash merges to reduce noise.
  • Add PR templates to enforce risk/impact and test evidence.

PR Template snippet

## Risks & Security
- Data exposure risk: Low/Med/High
- Secrets handled? ☐No ☐Yes (explain)
- Security tests added/updated? ☐


6) Supply Chain Security (Dependencies & Submodules)

Lock down dependencies

  • Commit lockfiles (package-lock.json, poetry.lock, Gemfile.lock).
  • Enable Dependabot/Snyk/GitLab Dependency Scanning.
  • Pin versions in Dockerfiles and CI images.

Be cautious with submodules

  • Pin submodule SHAs, not branches:
git submodule add -b main https://github.com/vendor/lib extern/lib
# then lock to a specific commit
cd extern/lib && git checkout <sha> && cd -
git add .gitmodules extern/lib

  • Review submodule updates like any third-party code.

7) CI/CD: Secrets, Tokens & Environments

Principles

  • No secrets in repo—store in CI secret manager or cloud KMS.
  • Mask secrets in logs; avoid echoing them.
  • Use OIDC to obtain cloud credentials at job time (short-lived).
  • Scope tokens to the minimum permissions (read-only if possible).
  • Separate build and deploy jobs; protect deploy with approvals.

GitHub Actions: principle of least privilege

permissions:
  contents: read
  pull-requests: read
  id-token: write   # only if using OIDC

Protected environments

  • Require manual approvals for prod.
  • Restrict who can deploy to prod.
  • Require up-to-date checks before deploy.

8) Hooks, Automation & Policy

Hooks are powerful—treat them like code

  • Store in repo and set a shared hooks path:
git config core.hooksPath .githooks

  • Review hook scripts (no curl | bash in critical paths).
  • Keep pre-commit fast; do heavier checks in CI.

Commit message policy (Conventional Commits)

# .githooks/commit-msg
#!/usr/bin/env bash
grep -E "^(feat|fix|chore|docs|test|refactor)(\(.+\))?: " "$1" || {
  echo "Use Conventional Commits, e.g., 'feat(ui): add search box'"
  exit 1
}


9) Incident Response: When a Secret Leaks

  1. Identify what leaked (token, key, password) and where (commit/tag/PR).
  2. Revoke the credential immediately (provider portal).
  3. Rotate and update usage (CI vars, apps).
  4. Purge history with git filter-repo or BFG if needed.
  5. Communicate impact and mitigation steps to the team.
  6. Add guardrails (scanners, hooks) to prevent recurrence.

Filter a file from history (example)

pip install git-filter-repo
git filter-repo --invert-paths --path secrets.yml
git push --force-with-lease origin main

Coordinate before rewriting shared history.


10) Monitoring, Auditing & Compliance

  • Enable organization audit logs and alerts.
  • Turn on secret scanning / push protection.
  • Track admin changes (new admins, SSO/2FA status).
  • Periodic access reviews: remove inactive users, rotate keys.
  • Keep a security policy (SECURITY.md) and an on-call contact.

11) Privacy & Metadata Hygiene

  • Avoid exposing real emails in commits:
    git config --global user.email "12345+you@users.noreply.github.com"
  • Use .mailmap to normalize/obfuscate author identities when needed.
  • Don’t commit PII; if needed, encrypt at rest and never in plain text.

12) Release & Artifact Integrity

  • Sign release tags and artifacts.
  • Generate and publish checksums (SHA256) with releases.
shasum -a 256 dist/app.tar.gz > dist/app.tar.gz.sha256

  • Prefer reproducible builds; pin toolchain versions.

13) Quick Start Checklist (Copy/Paste)

  • Enforce 2FA/SSO for org and users
  • Require signed commits + protected branches/tags
  • Enable secret scanning & push protection
  • Install pre-commit with gitleaks/detect-secrets
  • Use least privilege on repos, CI, cloud
  • Pin dependencies & enable Dependabot/SAST
  • Protect prod environment with approvals
  • Create incident runbook for leaked secrets
  • Rotate tokens/keys on schedule
  • Audit access quarterly

14) Example Team “Security Baseline” (Template)

# Git Security Baseline

**Identity & Signing**
- Commit signing required on main & release/*.
- Release tags signed by @release-engineers.

**Branch/Tag Protection**
- main, release/*: no force-push; 2 approvals; status checks required.

**Secrets**
- No secrets in repo. Gitleaks + detect-secrets in pre-commit & CI.
- OIDC for cloud creds; tokens scoped and short-lived.

**CI/CD**
- permissions: least; environments: staging/prod protected.
- Build artifacts signed; checksums published.

**Access**
- Teams-based permissions; quarterly reviews; 2FA enforced.

**Incident Response**
- Revoke, rotate, filter history, communicate, postmortem within 48h.


Conclusion

Security in Git is not one feature—it’s a layered approach across identity, repo governance, CI/CD, supply chain, and incident response. Start with the non-negotiables (2FA/SSO, protected branches, signed commits, secret scanning), then harden your pipelines and dependencies. Small changes today prevent big incidents tomorrow.

You Might Also Like

🛠️ Recommended Tools for Developers & Tech Pros

Save time, boost productivity, and work smarter with these AI-powered tools I personally use and recommend:

1️⃣ CopyOwl.ai – Research & Write Smarter
Write fully referenced reports, essays, or blogs in one click.
✅ 97% satisfaction • ✅ 10+ hrs saved/week • ✅ Academic citations

2️⃣ LoopCV.pro – Build a Job-Winning Resume
Create beautiful, ATS-friendly resumes in seconds — perfect for tech roles.
✅ One-click templates • ✅ PDF/DOCX export • ✅ Interview-boosting design

3️⃣ Speechify – Listen to Any Text
Turn articles, docs, or PDFs into natural-sounding audio — even while coding.
✅ 1,000+ voices • ✅ Works on all platforms • ✅ Used by 50M+ people