#Why this matters
Even input-validated code breaks down if a developer commits an API token to Git or ships an outdated library with a remote code execution flaw. Automated bots watch public repositories and container registries continuously, harvesting exposed credentials within seconds of a push. At the same time, modern Python projects rely on dozens of third-party packages, meaning a vulnerability in one indirect dependency becomes a weakness in your application.
Good secrets hygiene and dependency management keep credentials separate from code and keep external libraries visible and patchable.
#Why hardcoded secrets persist in Git
Writing API_TOKEN = "example-lab-token-1234" directly inside config.py creates secret sprawl. Even if you spot the mistake five minutes later and delete the line in a second commit, Git preserves every previous snapshot. Anyone who clones the repository or runs git log -p can still read the secret from the earlier commit.
Tools like git-secrets block accidental commits locally and scan existing history before a push:
$ git secrets --install
$ git secrets --register-aws
$ git secrets --add 'LAB_TOKEN_[A-Z0-9]{12}'
$ git secrets --scan-history
src/client.py:4:LAB_TOKEN_9F8E7D6C5B4A
[ERROR] Matched one or more prohibited patternsInstalling the hook into .git/hooks/ checks staged changes at commit time, while --scan-history inspects older commits that a normal file search misses.
#Managing configuration with environment variables
Code belongs in Git; configuration and secrets belong in the runtime environment. In Python, read required secrets from os.environ so the program fails closed at startup if a variable is missing, rather than falling back to an insecure default.
import os
API_TOKEN = os.environ["LAB_API_TOKEN"]
API_BASE_URL = os.environ.get("LAB_API_URL", "https://api.example.test")For local lab work, store values in an untracked .env file and commit only a .env.example template with empty placeholders. Always add .env to .gitignore before your first commit.
| Storage method | Suitable for | Key risk if misused |
|---|---|---|
Hardcoded string in .py |
Never | Exposed to anyone with repo or image access |
Local .env listed in .gitignore |
Local development only | Accidentally committed if .gitignore is missing |
| OS / container env vars or secret manager | Staging and production | Leaked if /proc or debug endpoints dump os.environ |
Never print os.environ in error handlers, startup banners, or diagnostic endpoints, because all injected tokens live in that dictionary.
#Auditing and pinning third-party dependencies
When you install one package such as requests, pip also installs transitive dependencies (urllib3, certifi, charset-normalizer, idna). Unpinned lines in requirements.txt (such as requests or requests>=2.28) pull newer releases unpredictably across builds, making security testing unreliable.
Pin exact versions in requirements.txt (for example requests==2.32.3), generate lockfiles from a clean virtual environment, and audit them regularly with pip-audit. pip-audit checks installed packages or requirements files against the Python Packaging Advisory Database (PyPI / OSV):
$ pip-audit -r requirements.txt
Found 2 known vulnerabilities in 1 package
Name Version ID Fix Versions
-------- ------- ------------------- ------------
examplepkg 1.2.0 PYSEC-2024-0000 1.2.4Review the Fix Versions column, update the pinned version in requirements.txt, run your test suite, and re-run pip-audit until it reports No known vulnerabilities found. Also verify package names carefully before installing to avoid typosquatting (malicious packages named similarly to popular libraries, such as reqeusts).
#Common mistakes
- Committing
.envfirst and adding.gitignorelater: Git continues tracking already-committed files even after they appear in.gitignore; you must rungit rm --cached .env, commit, and rotate the exposed values. - Providing hardcoded fallback secrets: Writing
os.getenv("SECRET_KEY", "dev-only-key")means a missing environment variable silently runs production with a guessable key. - Assuming
git commit --amendor a new commit fixes a pushed leak: Once pushed, others may have fetched the old commit object, so secret rotation is always required. - Auditing only direct imports: Skipping
pip-auditon transitive dependencies leaves hidden vulnerabilities in libraries pulled underneath your main packages.
#Summary
- Never store passwords or API tokens in source files; keep them in runtime environment variables or a secret manager, and fail closed when required variables are missing.
- Deleting a secret in a newer commit leaves it readable in Git history; use
git-secretsto prevent commits and rotate any exposed credential immediately. - Pin exact package versions in
requirements.txt, watch for typosquatted package names, and runpip-auditregularly to catch vulnerable direct and transitive dependencies.