Scan ML Projects for Exposed Secrets Before Sharing
Before you share a machine learning project—on GitHub, with a colleague, or as part of a submission—you need to make sure no API keys, database passwords, or private tokens are hiding in your files. This guide walks you through a practical, step-by-step scan that catches common secret leaks, so you can share your work with confidence.
What You’ll Need
- A terminal or command-line interface (on Windows, use PowerShell or Command Prompt; on macOS/Linux, use Terminal).
- Git installed on your machine (to check commit history).
- Access to the project directory you plan to share.
- Optional: Python installed (for some scanning tools) and a GitHub account (if you want to use GitHub’s secret scanning).
Step-by-Step
- Create a clean copy of your project. Before scanning, copy your project folder to a temporary location. This ensures you don’t accidentally modify or delete files during the scan. Use
cp -r /path/to/project /tmp/scan-copyon macOS/Linux, orrobocopyon Windows. - Search for obvious secret patterns. Use a recursive grep to find common secret keywords. On macOS/Linux:
grep -rniE "(api[_-]?key|secret|password|token|auth|bearer)" --include="*.py" --include="*.env" --include="*.json" --include="*.yaml" .On Windows PowerShell:Get-ChildItem -Recurse -Include *.py,*.env,*.json,*.yaml | Select-String -Pattern "api[_-]?key|secret|password|token|auth|bearer". Review each match—many will be false positives (like a variable namedpasswordthat stores a hashed value), but flag anything that looks like a real credential. - Check all file types, not just code. Secrets often hide in configuration files, Jupyter notebooks, and even images or PDFs. Search for files with extensions like
.env,.ini,.cfg,.toml,.pem,.key,.p12, and.pfx. Usefind . -type f \( -name "*.env" -o -name "*.pem" -o -name "*.key" \)to list them. Open each file and inspect its contents. - Scan Jupyter notebooks. Notebooks (
.ipynb) store output cells as JSON, which can contain printed secrets. Use a tool likenbconvertto strip outputs:jupyter nbconvert --clear-output --inplace *.ipynb. Then search the notebook JSON for secrets:grep -rniE "(api[_-]?key|secret|password)" *.ipynb. - Look for hardcoded strings in code. Search for long, high-entropy strings that might be keys or tokens. A simple heuristic is to search for strings of 20+ alphanumeric characters. On macOS/Linux:
grep -rnoE '[A-Za-z0-9]{20,}' --include="*.py" --include="*.js" --include="*.java" .Review each match—if it looks like a random string, it could be a secret. - Check Git history. Even if you remove a secret in your latest commit, it may still exist in earlier commits. Use
git log --onelineto see your commit history. Then search all commits for secrets:git grep -iE "(api[_-]?key|secret|password)" $(git rev-list --all). If you find a secret, you’ll need to rewrite history (usegit filter-branchor BFG Repo-Cleaner) or, better, rotate the secret and remove it from history. - Use a dedicated secret scanning tool. Tools like
trufflehogorgitleaksare designed to find secrets in files and Git history. Install one (e.g.,brew install gitleakson macOS, orpip install trufflehog), then run it on your project directory. For example:gitleaks detect --source . --report-path report.json. Review the report carefully. - Scan for common ML-specific files. Machine learning projects often contain model files (
.h5,.pkl,.joblib) that may have embedded metadata or even training data with secrets. Usestrings model.pkl | grep -iE "(api|secret|password)"to check for readable strings. Also checkrequirements.txtandDockerfilefor hardcoded credentials. - Check environment variable files. The
.envfile is a common place for secrets. If you have one, ensure it’s in your.gitignoreand not committed. Runcat .gitignoreto confirm. If you don’t have a.gitignore, create one with entries like.env,*.pem,*.key, andsecrets.*. - Do a final manual review of every file you plan to share. Open each file in your clean copy and skim for anything that looks like a credential. Pay special attention to comments, docstrings, and example code—people often leave dummy keys that are actually real.
- Test your scan with a fake secret. Add a dummy string like
sk-test-1234567890abcdefto a temporary file, run your scanning tools again, and confirm they catch it. If they don’t, your scan is incomplete—adjust your patterns or tools. - Remove or rotate any found secrets. If you find a real secret, delete it from the code and replace it with a reference to an environment variable. If the secret was ever committed, rotate it immediately (e.g., regenerate an API key) because it may already be compromised. Then re-run the scan to confirm it’s gone.
Common Mistakes
- Only scanning the current directory. Secrets can hide in subdirectories, hidden files, and build artifacts. Always scan recursively and include hidden files (use
--hiddenwith grep orfind). - Ignoring Git history. Removing a secret from the latest commit is not enough. Anyone can see the history. Always scan all commits.
- Assuming .env files are automatically ignored. If you don’t have a
.gitignore, or if you force-add files, secrets can be committed. Always check your.gitignore. - Overlooking Jupyter notebook outputs. Notebooks store printed output, and if you printed a key during development, it’s in the JSON. Clear outputs before sharing.
- Using weak search patterns. Searching only for
passwordmisses tokens likeghp_...orsk-.... Use broad patterns and entropy checks. - Not rotating secrets after a leak. Even if you remove a secret from code, if it was ever exposed, assume it’s compromised and rotate it.
Tips
- Use a pre-commit hook. Tools like
pre-commitwithgitleaksordetect-secretscan automatically scan before every commit, preventing secrets from entering history in the first place. - Store secrets in environment variables. Never hardcode credentials. Use
os.getenv("API_KEY")in Python, or a secrets manager like AWS Secrets Manager or HashiCorp Vault. - Use a .gitignore template. GitHub offers templates for Python, Jupyter, and other languages. Include entries for
.env,*.pem,*.key, andsecrets.*. - Regularly rotate secrets. Even if you never share your project, rotating keys periodically reduces risk.
- Use a secret scanning service. If you host on GitHub, enable GitHub’s secret scanning (free for public repos) to automatically detect known secret patterns.
- Test your scan on a dummy secret. This confirms your tools are working before you trust them.
Troubleshooting
- The scan finds too many false positives. Refine your search patterns—exclude common words like “password” in comments, and focus on high-entropy strings or known prefixes (e.g.,
sk-,ghp_). Use a tool likedetect-secretsthat uses heuristics. - Git history scan fails with “fatal: bad revision” This happens when you have no commits yet or your repo is shallow. Make sure you have at least one commit, or run
git fetch --unshallowto get full history. - Gitleaks reports a secret in a binary file. Binary files like model weights can contain strings that look like secrets but are actually random data. Verify by extracting the string and checking if it’s a valid key (e.g., try the API key format). If unsure, treat it as a secret and remove it.
- You accidentally committed a secret and pushed to a public repo. Immediately rotate the secret, then remove it from history using
git filter-branchor BFG. Also consider making the repo private temporarily. Note that even after removal, the secret is in the public history—rotation is essential. - Your scan tool isn’t finding a secret you know exists. Try a different tool or use a broader regex. Sometimes secrets are split across lines or encoded (base64). Run a base64 decode on suspicious strings.
- Jupyter notebook clear-output doesn’t work. Ensure you have
nbconvertinstalled (pip install nbconvert). If it fails, manually edit the notebook JSON and remove theoutputsandexecution_countfields.
Frequently Asked Questions
What is the most common place for secrets to leak in ML projects?
The most common is the .env file being committed to version control. Also common are Jupyter notebook output cells that print API keys during debugging.
Can I just delete the secret from the latest commit?
No. The secret remains in Git history. You must either rewrite history (using tools like BFG) or, more importantly, rotate the secret because it’s already exposed.
Is it safe to share a model file that was trained with secret data?
Not necessarily. Model files can contain embedded metadata or even memorized training data. Use strings to check for readable secrets, and consider using a tool like git-lfs to manage large files separately.
Do I need to scan if I’m only sharing with a colleague privately?
Yes. Even private sharing can lead to leaks if the colleague forwards the project or if the repository is later made public. Always scan before any external sharing.
What should I do if I find a secret that was already pushed to a public repo?
Rotate the secret immediately (generate a new key, revoke the old one). Then remove it from the repo history. Even after removal, assume the secret is compromised and monitor for misuse.
Are there any built-in tools in GitHub to detect secrets?
Yes, GitHub has secret scanning for public repositories and for private repos with GitHub Advanced Security. It automatically detects known patterns like AWS keys and GitHub tokens, but it’s not a substitute for a thorough scan before sharing.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.