Marcio Cunha

Secrets exposed in code? How to audit with Gitleaks

Learn how to find forgotten passwords and API keys in your source code using Gitleaks integrated into githooks and CI pipelines.

Marcio Cunha•5 min
Also available in:PortuguêsEspañol
Summary
  • Passwords and API keys left in source code represent a critical attack vector automatically exploited by malicious bots on the internet.
  • Gitleaks acts as a highly efficient static scanner that locates suspicious credential patterns before they reach public environments.
  • Coupling security checks to local githooks prevents developers from committing compromised files right at the moment of the first commit.
  • Automating full scans within continuous integration pipelines ensures legacy changes or hidden files undergo constant auditing.
  • Keeping secrets out of the repository requires clear credential rotation policies and the use of specialized digital vaults for secure storage.

The silent danger of access keys in source code

Imagine leaving your front door key under the doormat outside your house. That is precisely what happens when developers insert database passwords, access tokens, or API keys directly into a system's text files. In practice, this means anyone with access to the project repository, whether public or private, gets a free pass to explore internal systems. Automated bots scour the internet twenty-four hours a day looking for these lost credentials to commit fraud, mine cryptocurrency, or hijack servers.

Discovering that a secret leaked usually happens too late, often through an astronomical cloud bill or a security breach notice. To prevent this operational nightmare, modern engineering relies on static scanning tools that analyze code text for known password patterns before damage occurs. A routine similar to how we clear temporary files and free up disk space, much like when a pipeline fails due to low disk space and you need to clean Docker to get the workflow running safely again.

What is Gitleaks and how it protects your repository

Gitleaks is an open-source tool designed to hunt for secrets, passwords, and forgotten keys in a project's commit history or local files. In practice, it acts as an automated detective reading your code line by line, comparing content against hundreds of regular expressions and statistical entropies that identify secret-like key sequences. Unlike a simple keyword search, it understands the token structures generated by major cloud providers and third-party services.

Adopting this type of inspection in your development routine prevents security from depending exclusively on human memory or tiring manual reviews. When we combine this verification with other robust infrastructure practices, such as automated credential management in dedicated services or secret rotation via how to automate SSL certificates with Vault, we build an impenetrable barrier against accidental leaks and unauthorized access.

Installing and running your first manual scan

Before automating the process, it is worth understanding how the tool behaves by running a direct scan in the project directory. Installation is easily done through common package managers in modern operating systems, allowing any team member to run quick audits on their local machine. The basic command scans the entire history of the current git repository and generates a detailed report if it finds any anomaly.

# Installing Gitleaks on Linux via Homebrew or direct binary
brew install gitleaks

# Running static scan on the current repository
gitleaks detect --source . --verbose

In practice, the command above reads every commit already made in the project and points out exactly which file, which line, and which user introduced the vulnerable credential. This immediate visibility helps understand the scale of the problem and serves as a starting point for cleaning history, which often requires rewriting commits if the secret has already been pushed to a remote server.

Stopping errors at the source with Git Hooks

Waiting for code to reach the remote server to discover a password was exposed is an unnecessary risk. The best defense strategy is intercepting the issue right on the developer's machine before the push command even completes. For this, we use githooks, which are scripts automatically executed by the version control system whenever we perform specific actions, such as a commit or push.

Setting up a pre-commit hook ensures Gitleaks analyzes only the changes about to be saved. If any key is detected, the commit is immediately rejected, stopping problematic code from advancing in the workflow. Below is a sample configuration using the pre-commit tool in a yaml configuration file:

repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.2
    hooks:
      - id: gitleaks

With this setup integrated into the local environment, the developer receives instant feedback in the terminal screen. If a test key or real token is accidentally pasted into code, the tool itself interrupts the action, educates the professional, and keeps the repository clean from the very first written line.

Automating audits in CI/CD pipelines

Even with rigorous local blocks, there is always a chance some adjustment slips by or external contributions arrive via pull requests without configured githooks. This is where continuous integration pipelines come in, running on automated servers every time new code is pushed. Ensuring centralized checks happen is the digital equivalent of maintaining scattered cluster logs and centralizing with Fluent Bit, guaranteeing full visibility into application health.

Inserting verification into the pipeline prevents any vulnerable version from merging into the main production branch. Below is a practical example of a GitHub Actions configuration file that runs Gitleaks automatically on every new code push:

name: Security
on: [pull_request, push]
jobs:
  gitleaks:
    runs-on: ubuntu-latest
    steps:
      - name: 'Checkout source code'
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: 'Run Gitleaks'
        uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

This workflow runs fully autonomously, blocking code integration if it finds any unprotected API key or password. Thus, the development team gains peace of mind and maintains rigorous security standards without constant manual effort.

What to do when a secret is accidentally exposed

Finding a leaked credential through static scanning requires a rapid and coordinated response to prevent intrusions. The immediate first step is revoking the compromised key directly in the service provider dashboard, generating a new access token to replace the old one. Never rely solely on deleting the file from the current commit, as git history preserves all previous file versions unless completely rewritten.

After revoking access, you must clean the repository history using advanced rewrite commands or deep cleaning tools like Gitleaks in remediation mode. Communicating the incident to the security team and monitoring access logs of the affected service helps ensure no malicious actor took advantage of the exposure window to extract confidential data.

Final Considerations

Protecting source code against accidental credential leakage is no longer a luxury but a baseline requirement of any modern engineering operation. By combining local scans via git hooks with automated validations in CI/CD pipelines, we build a solid security culture that protects both the company and end users against avoidable intrusions. The technology is widely available and its adoption brings immediate returns to the stability and reputation of any digital project.

Maintaining the discipline of regular code audits and educating the team about the silent danger of hardcoded keys ensures innovation happens without opening doors to chaos. Adopt these routines in your repositories today, keep your secrets in secure vaults, and sleep with the peace of mind that your infrastructure is shielded against everyday development slip-ups.