Detect Secrets
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
- breaking Support for Python 3.6 and 3.7 was dropped in v1.5.0. Python 3.8 support will also be removed in a future release (likely after its EOL in October 2024).
- gotcha The ML-based `gibberish-detector` (introduced in v1.1.0) is not included in the default installation. It requires an 'extra' package.
- gotcha For effective use, especially with `pre-commit` hooks, `detect-secrets` heavily relies on configuration files (`.detect-secrets.yaml`) and a baseline file (`.secrets.baseline`). Skipping these can lead to excessive false positives or missed secrets.
Install
-
pip install detect-secrets -
pip install 'detect-secrets[ml]'
Imports
- run_as_library
from detect_secrets.core.usage import run_as_library
- TransientSettings
from detect_secrets.settings import TransientSettings
- Baseline
from detect_secrets.core.baseline import Baseline
Quickstart
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()