Detect Secrets

1.5.0 · active · verified Fri Apr 10

Detect-secrets is a tool designed to identify and prevent sensitive information, such as API keys, passwords, and other credentials, from being committed into source code repositories. It leverages various detectors, including regex, keyword, and optional machine learning-based algorithms. The current version is 1.5.0, with minor releases typically occurring every few months.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically scan a temporary directory containing a file with simulated secrets using `detect-secrets`. It initializes a temporary directory, creates a file with some fake credentials, and then uses `run_as_library` to perform the scan and print the detected secret types.

import os
import tempfile
from pathlib import Path
from detect_secrets.core.usage import run_as_library

def run_detect_secrets_scan():
    with tempfile.TemporaryDirectory() as tmpdir:
        repo_path = Path(tmpdir)
        
        # Create a dummy file with a fake secret
        (repo_path / "my_project").mkdir()
        (repo_path / "my_project" / "config.py").write_text(
            "API_KEY = 'AKIAIOSFODNN7EXAMPLE' # This is a fake AWS key, DO NOT USE
            DB_PASSWORD = 'supersecretpassword123'
            SECRET_PHRASE = 'NotARealSecret'
            ")
        
        print(f"Scanning directory: {repo_path}")
        
        # Run the scan
        # 'plugins_used': None lets detect-secrets use its default plugin set.
        # 'secret_type_mapping': None uses default mappings.
        # 'mount_paths': Specify the path to scan.
        scan_results = run_as_library(
            plugins_used=None,
            secret_type_mapping=None,
            mount_paths=[str(repo_path)]
        )
        
        # Process results
        if scan_results.data:
            print("\n--- Detected Secrets ---")
            for filepath, secrets in scan_results.data.items():
                print(f"File: {filepath}")
                for secret in secrets:
                    print(f"  - Type: {secret.type}, Hashed Secret: {secret.hashed_secret}")
        else:
            print("\nNo secrets detected.")

if __name__ == '__main__':
    run_detect_secrets_scan()

view raw JSON →