devsecops

Implementing Secrets Scanning in CI/CD

Integrate gitleaks and trufflehog into CI/CD pipelines to detect leaked secrets before deployment

ci-cdgitleakssecrets-scanningtrufflehog
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

This skill covers implementing automated secrets scanning in CI/CD pipelines using gitleaks and trufflehog. It enables security teams to detect API keys, tokens, passwords, and other credentials that have been accidentally committed to source code repositories, providing a CI gate that blocks deployments containing high-severity findings.

Gitleaks scans git repositories and directories for hardcoded secrets using regex patterns and entropy analysis. TruffleHog performs filesystem and git history scans with optional secret verification against live services. Together they provide comprehensive coverage for secrets detection.

When to Use

  • When deploying or configuring implementing secrets scanning in ci cd capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Python 3.9 or later
  • gitleaks v8.x installed and available on PATH
  • trufflehog v3.x installed and available on PATH
  • A git repository or directory to scan
  • Access to CI/CD platform (GitHub Actions, GitLab CI, Jenkins)

Steps

  1. Install scanning tools: Install gitleaks via package manager or binary download. Install trufflehog via brew install trufflehog or download from GitHub releases.

  2. Configure gitleaks: Create a .gitleaks.toml configuration file in the repository root to define custom rules, allowlists, and path exclusions. Use --config flag to point to custom configs.

  3. Run gitleaks directory scan: Execute gitleaks dir --source . --report-format json --report-path gitleaks-report.json to scan the working directory and generate a JSON report.

  4. Run trufflehog filesystem scan: Execute trufflehog filesystem /path/to/repo --json > trufflehog-report.json to scan files and output JSON findings to a report file.

  5. Parse and filter findings: Use the agent script to parse both JSON reports, filter findings by severity (critical, high, medium, low), and determine whether the CI pipeline should pass or fail.

  6. Integrate into CI pipeline: Add the scanning step to your GitHub Actions workflow, GitLab CI config, or Jenkins pipeline as a pre-deployment gate. Use --exit-code flag in gitleaks to control pipeline behavior.

  7. Configure pre-commit hooks: Set up gitleaks as a pre-commit hook using gitleaks protect --staged to catch secrets before they are committed.

  8. Review and triage findings: Examine the JSON output for false positives, add legitimate entries to .gitleaksignore, and rotate any confirmed leaked credentials immediately.

Expected Output

The agent script produces a JSON report containing:

  • Total findings count from each scanner
  • Findings grouped by severity level
  • Individual finding details including file path, line number, rule ID, and redacted secret
  • A CI gate verdict (pass/fail) based on the configured severity threshold
  • Execution metadata including scan duration and tool versions
{
  "scan_summary": {
    "tool": "both",
    "total_findings": 3,
    "critical": 1,
    "high": 1,
    "medium": 1,
    "low": 0,
    "ci_gate": "FAIL",
    "fail_reason": "Found 1 critical and 1 high severity findings"
  },
  "findings": [...]
}
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 1

api-reference.md3.0 KB

Secrets Scanning API Reference

Gitleaks CLI

Subcommands

gitleaks git    # Scan git repositories
gitleaks dir    # Scan directories or files
gitleaks stdin  # Detect secrets from stdin

Key Flags

Flag Description
--source, -s Path to source directory or repository
--config, -c Path to .gitleaks.toml config file
--report-format, -f Output format: json, csv, junit, sarif, template
--report-path, -r File path to write report
--exit-code Exit code when leaks found (default: 1)
--redact Redact secrets from output (0-100%, default: 100)
--baseline-path, -b Path to baseline report to ignore known findings
--no-banner Suppress banner output
--verbose, -v Show verbose scan details
--log-level, -l Log level: trace, debug, info, warn, error, fatal
--max-target-megabytes Skip files larger than specified MB
--enable-rule Only enable specific rule IDs
--gitleaks-ignore-path, -i Path to .gitleaksignore file

Pre-commit Hook

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.21.2
    hooks:
      - id: gitleaks

Protect Staged Files

gitleaks protect --staged --report-format json --report-path staged-report.json

TruffleHog CLI

Subcommands

trufflehog git <repo-url>            # Scan git repository
trufflehog filesystem <path>         # Scan local filesystem
trufflehog github --org=<org>        # Scan GitHub org
trufflehog gitlab --token=<token>    # Scan GitLab instance
trufflehog s3 --bucket=<name>        # Scan S3 bucket
trufflehog docker --image=<img>      # Scan Docker image

Key Flags

Flag Description
--json, -j Output in JSON format (one object per line)
--no-verification Skip live secret verification
--concurrency Number of concurrent workers (default: 20)
--results Filter: verified, unknown, unverified, filtered_unverified
--force-skip-binaries Skip binary files during scan
--force-skip-archives Skip archive files during scan
--include-paths Path to file with include path patterns
--exclude-paths Path to file with exclude path patterns
--log-level Verbosity: 0 (info) to 5 (trace)

GitHub Secret Scanning API

List Alerts

curl -H "Authorization: Bearer $TOKEN" \
  https://api.github.com/repos/{owner}/{repo}/secret-scanning/alerts

Update Alert State

curl -X PATCH \
  -H "Authorization: Bearer $TOKEN" \
  https://api.github.com/repos/{owner}/{repo}/secret-scanning/alerts/{alert_number} \
  -d '{"state": "resolved", "resolution": "revoked"}'

GitHub Actions Integration

- name: Gitleaks Scan
  uses: gitleaks/gitleaks-action@v2
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
 
- name: TruffleHog Scan
  uses: trufflesecurity/trufflehog@main
  with:
    extra_args: --results verified,unknown

Scripts 1

agent.py5.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Secrets scanning CI/CD gate using gitleaks and trufflehog."""

import argparse
import json
import os
import subprocess
import sys
import tempfile
import time


SEVERITY_ORDER = {"critical": 4, "high": 3, "medium": 2, "low": 1, "info": 0}

GITLEAKS_SEVERITY_MAP = {
    "aws-access-key": "critical",
    "aws-secret-key": "critical",
    "github-pat": "critical",
    "private-key": "critical",
    "generic-api-key": "high",
    "slack-webhook": "high",
    "stripe-api-key": "critical",
    "twilio-api-key": "high",
    "sendgrid-api-key": "high",
    "npm-access-token": "high",
    "pypi-upload-token": "high",
    "gcp-api-key": "critical",
    "heroku-api-key": "high",
    "jwt": "medium",
    "password-in-url": "high",
    "generic-password": "medium",
}


def run_gitleaks(scan_path: str) -> list:
    report_file = tempfile.NamedTemporaryFile(suffix=".json", delete=False)
    report_path = report_file.name
    report_file.close()
    cmd = [
        "gitleaks", "dir",
        "--source", scan_path,
        "--report-format", "json",
        "--report-path", report_path,
        "--exit-code", "0",
        "--no-banner",
    ]
    proc = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
    findings = []
    if os.path.exists(report_path) and os.path.getsize(report_path) > 0:
        with open(report_path, "r") as f:
            raw = json.load(f)
        for item in raw:
            rule_id = item.get("RuleID", "unknown")
            severity = GITLEAKS_SEVERITY_MAP.get(rule_id, "medium")
            secret_val = item.get("Secret", "")
            redacted = secret_val[:4] + "****" if len(secret_val) > 4 else "****"
            findings.append({
                "tool": "gitleaks",
                "rule_id": rule_id,
                "description": item.get("Description", ""),
                "file": item.get("File", ""),
                "line": item.get("StartLine", 0),
                "severity": severity,
                "redacted_secret": redacted,
                "commit": item.get("Commit", ""),
                "author": item.get("Author", ""),
                "entropy": item.get("Entropy", 0.0),
            })
    os.unlink(report_path)
    return findings


def run_trufflehog(scan_path: str) -> list:
    cmd = [
        "trufflehog", "filesystem", scan_path,
        "--json",
        "--no-verification",
        "--concurrency", "10",
    ]
    proc = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
    findings = []
    for line in proc.stdout.strip().split("\n"):
        if not line.strip():
            continue
        item = json.loads(line)
        detector = item.get("DetectorName", item.get("DetectorType", "unknown"))
        source_meta = item.get("SourceMetadata", {})
        fs_data = source_meta.get("Data", {}).get("Filesystem", {})
        raw_secret = item.get("Raw", "")
        redacted = raw_secret[:4] + "****" if len(raw_secret) > 4 else "****"
        severity = "critical" if item.get("Verified", False) else "high"
        findings.append({
            "tool": "trufflehog",
            "rule_id": detector,
            "description": f"Detected {detector} secret",
            "file": fs_data.get("file", ""),
            "line": fs_data.get("line", 0),
            "severity": severity,
            "redacted_secret": redacted,
            "verified": item.get("Verified", False),
            "decoder_name": item.get("DecoderName", ""),
        })
    return findings


def evaluate_gate(findings: list, fail_on_severity: str) -> dict:
    threshold = SEVERITY_ORDER.get(fail_on_severity, 2)
    counts = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0}
    for f in findings:
        sev = f.get("severity", "medium")
        counts[sev] = counts.get(sev, 0) + 1
    gate_failed = False
    fail_reasons = []
    for sev, count in counts.items():
        if count > 0 and SEVERITY_ORDER.get(sev, 0) >= threshold:
            gate_failed = True
            fail_reasons.append(f"Found {count} {sev} severity findings")
    return {
        "ci_gate": "FAIL" if gate_failed else "PASS",
        "fail_reason": "; ".join(fail_reasons) if fail_reasons else None,
        "total_findings": len(findings),
        **counts,
    }


def main():
    parser = argparse.ArgumentParser(description="Secrets scanning CI/CD gate")
    parser.add_argument("--path", required=True, help="Path to scan for secrets")
    parser.add_argument("--tool", choices=["gitleaks", "trufflehog", "both"],
                        default="both", help="Scanner tool to use")
    parser.add_argument("--fail-on-severity", choices=["critical", "high", "medium", "low"],
                        default="high", help="Minimum severity to fail CI gate")
    parser.add_argument("--output", default=None, help="Output JSON file path")
    args = parser.parse_args()

    if not os.path.exists(args.path):
        print(json.dumps({"error": f"Path does not exist: {args.path}"}))
        sys.exit(1)

    start_time = time.time()
    all_findings = []

    if args.tool in ("gitleaks", "both"):
        all_findings.extend(run_gitleaks(args.path))
    if args.tool in ("trufflehog", "both"):
        all_findings.extend(run_trufflehog(args.path))

    gate_result = evaluate_gate(all_findings, args.fail_on_severity)
    elapsed = round(time.time() - start_time, 2)

    report = {
        "scan_summary": {
            "tool": args.tool,
            "scanned_path": args.path,
            "fail_on_severity": args.fail_on_severity,
            "scan_duration_seconds": elapsed,
            **gate_result,
        },
        "findings": all_findings,
    }

    output_json = json.dumps(report, indent=2)
    if args.output:
        with open(args.output, "w") as f:
            f.write(output_json)
    print(output_json)

    if gate_result["ci_gate"] == "FAIL":
        sys.exit(1)


if __name__ == "__main__":
    main()
Keep exploring