๐Ÿ” Securing Your Git Repositories with Gitleaks and Pre-Commit Hooks

Rahul wathRahul wath
5 min read

In todayโ€™s software development landscape, securing your codebase is more critical than ever. One overlooked yet common threat is the accidental leakage of sensitive information โ€” like API keys, passwords, or cryptographic secrets โ€” through Git repositories.

To tackle this, two powerful defenses can work hand-in-hand:
โœ… Gitleaks โ€” an open-source tool that scans your repos for sensitive data.
โœ… Pre-commit hooks โ€” automated checks that prevent secrets from being committed in the first place.

Together, they help you maintain a secure, compliant, and trustworthy software supply chain.


๐Ÿšจ How Gitleaks Works

Gitleaks provides automated static analysis for your Git repos, catching secrets before they cause harm. Hereโ€™s how it works under the hood:

๐Ÿ” Scanning Process

  • Scans the entire Git repository, including commit history, staged files, or specific commit ranges.

  • Searches for patterns matching known sensitive data formats like API keys, passwords, and cryptographic tokens.

  • Uses regular expressions and rule-based detection to identify potential leaks.

๐Ÿ›ก๏ธ Rule-Based Detection

  • Relies on a robust set of predefined rules (signatures) for common secret patterns.

  • Supports custom rules, allowing you to adapt scanning for your specific use cases.

  • Continuously updated to catch new threats and credential formats.

๐Ÿ“„ Reporting

  • Generates clear reports showing file paths, line numbers, and types of detected secrets.

  • Supports output in multiple formats: JSON, CSV, SARIF, or plain text.

  • Reports can be integrated with your security dashboards or alerting systems.

โš™๏ธ Configuration & Customization

  • Define custom rules to catch organization-specific secrets.

  • Exclude files, directories, or paths that you know are safe.

  • Adjust verbosity and output to fit your CI/CD pipeline.


๐Ÿ”— Integrating Gitleaks into Your Workflow

Gitleaks is designed for flexibility. You can:

  • Run it locally before pushing code.

  • Integrate it in your CI/CD pipelines for automated scans.

  • Use it as a GitHub Action, pre-commit hook, or standalone CLI tool.


โšก Pre-Commit Hooks: Stop Leaks Before They Happen

Pre-commit hooks act as your first line of defense.
These are scripts that run automatically before a commit is finalized. If a hook fails, the commit is aborted โ€” ensuring vulnerabilities are caught early.

How pre-commit hooks work:

  • Configured in the .git/hooks directory or managed with the pre-commit framework.

  • Execute locally on each developerโ€™s machine, enforcing consistent security checks.

  • Can run linting, code formatting, secret scanning, or any custom script.


๐Ÿš€ Quick Setup Guide

โœ… Scan Your Repository

1. Scan current repo:

bashCopyEditgitleaks detect --source . --report-path gitleaks-report.json
cat gitleaks-report.json

2. Scan a specific commit range (last 10 commits):

bashCopyEditgitleaks detect --source . --log-opts "-n 10" --report-path gitleaks-report.json

3. Scan a remote repository:

bashCopyEditgitleaks detect --repo=https://github.com/your/repository.git --report-path gitleaks-report.json

โœ… Set Up Pre-Commit Hooks

Option 1: Using pre-commit framework

  1. Install pre-commit:
bashCopyEditpip install pre-commit
  1. Create a .pre-commit-config.yaml:
yamlCopyEditrepos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.1  # Replace with desired version
    hooks:
      - id: gitleaks
  1. Install the pre-commit hook:
bashCopyEditpre-commit install
  1. Run manually to test:
bashCopyEditpre-commit run --all-files

Option 2: Create a Custom Pre-Commit Hook

  1. Install Gitleaks on your local system.

  2. Create a pre-commit script in .git/hooks/pre-commit:

     bashCopyEdit#!/bin/sh
     echo "Running Gitleaks scan..."
     gitleaks detect --staged --report-path gitleaks-report.json
     if [ $? -ne 0 ]; then
       echo "Potential secrets detected! Fix before committing."
       exit 1
     fi
    
  3. Make the script executable:

     bashCopyEditchmod +x .git/hooks/pre-commit
    

๐Ÿš€ Example CI/CD Setup

โœ… GitHub Actions

yamlCopyEditname: Secrets Scan

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  gitleaks-scan:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Run Gitleaks
        uses: gitleaks/gitleaks-action@v2
        with:
          args: detect --source . --report-path=gitleaks-report.json

      - name: Upload scan report
        uses: actions/upload-artifact@v4
        with:
          name: gitleaks-report
          path: gitleaks-report.json

โœ… GitLab CI/CD

yamlCopyEditstages:
  - security

secrets_scan:
  image: zricethezav/gitleaks:latest
  stage: security
  script:
    - gitleaks detect --source . --report-path=gitleaks-report.json
  artifacts:
    paths:
      - gitleaks-report.json
  allow_failure: false

โœ… Jenkins Pipeline

groovyCopyEditpipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        stage('Gitleaks Scan') {
            steps {
                sh 'curl -sSL https://github.com/gitleaks/gitleaks/releases/latest/download/gitleaks-linux-amd64 -o gitleaks'
                sh 'chmod +x gitleaks'
                sh './gitleaks detect --source . --report-path=gitleaks-report.json'
            }
        }
    }
    post {
        always {
            archiveArtifacts artifacts: 'gitleaks-report.json'
        }
        failure {
            echo 'Secrets detected! Fix them before merging.'
        }
    }
}

โœ… Best Practices for CI/CD Integration

โœ”๏ธ Fail builds on leak detection: Configure your pipeline to fail if secrets are found.
โœ”๏ธ Store reports: Upload reports as pipeline artifacts for traceability.
โœ”๏ธ Combine with pre-commit hooks: This reduces the chance that secrets ever reach the pipeline.
โœ”๏ธ Rotate secrets regularly: If secrets are exposed, rotate them immediately.


๐Ÿ“‘ Recap: Your Multi-Layer Defense

LayerWhat it does
Gitleaks CLILocal or manual scans of repos & commits.
Pre-Commit HooksPrevents commits with secrets at the developer level.
CI/CD IntegrationEnforces continuous scanning on all pushes, PRs, and merges.

๐Ÿ”’ Final Thoughts

In a modern DevSecOps workflow, using Gitleaks, pre-commit hooks, and CI/CD integration is essential to keep your secrets safe. These proactive measures:
โœ… Reduce the risk of breaches.
โœ… Keep your stakeholdersโ€™ trust.
โœ… Save time and money by catching leaks early.

Start securing your Git repositories today โ€” because secrets belong in a vault, not your codebase.


๐Ÿ“š Reference

๐Ÿ‘‰ Gitleaks GitHub
๐Ÿ‘‰ Pre-commit Framework

0
Subscribe to my newsletter

Read articles from Rahul wath directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rahul wath
Rahul wath

An experienced DevOps Engineer understands the integration of operations and development in order to deliver code to customers quickly. Has Cloud and monitoring process experience, as well as DevOps development in Windows, Mac, and Linux systems.