In this lesson, you will learn how to proactively identify security risks in your project by using automated tools to scan your dependencies and source code for vulnerabilities.
Even with a comprehensive test suite, your application remains vulnerable if the third-party libraries you rely on contain known security flaws. Managing this risk requires two approaches: checking your dependencies for publicly disclosed vulnerabilities and auditing your own source code for common insecure coding patterns.
Scanning Dependencies with Safety
The safety tool checks your installed packages against a database of known vulnerabilities (the Safety DB). It ensures that none of your requirements are compromised. You can run it directly in your terminal:
# Check your current environment
pip install safety
safety check
If safety finds a package version with a known exploit (like a buffer overflow or an injection vulnerability), it will alert you immediately so you can upgrade to a secure version.
Auditing Code with Bandit
While safety looks at your external dependencies, bandit focuses on your own Python source code. It performs static analysis to find common security issues, such as the use of insecure cryptographic functions, improper shell command execution (os.system), or hardcoded credentials.
To scan your project directory, use:
# Install and run Bandit
pip install bandit
bandit -r your_project_folder/
Bandit will provide a report highlighting the severity (low, medium, or high) of the issues found and suggest how to remediate them.
Integrating into Development
These tools are most effective when integrated into your workflow. By running these scans before you deploy, you catch "low-hanging fruit" that attackers often look for. You don't need to manually check every line of code; these tools automate the discovery of security debt, allowing you to focus your energy on fixing high-priority vulnerabilities before they reach production.
Key Takeaway: Use safety to guard against compromised dependencies and bandit to identify insecure coding patterns, ensuring your application remains resilient against known security threats.