Security analyzer for AI-generated code
Project description
SafeAI 🔒
Security analyzer for AI-generated code
SafeAI is a Python library that analyzes source code for security vulnerabilities commonly found in AI-generated code. It helps developers identify and fix security issues before they reach production.
🚀 Features
- 11 Security Rules: Comprehensive detection of common vulnerabilities
- AI-Focused: Specifically designed for AI-generated code patterns
- Multiple Output Formats: Text, JSON, and table output
- CLI Interface: Easy-to-use command-line tool
- Severity Levels: HIGH, MEDIUM, LOW classification
- Extensible: Easy to add custom security rules
📦 Installation
pip install safeai-scanner
🎯 Quick Start
Basic Usage
# Scan a single file
safeai scan main.py
# Scan a directory
safeai scan ./myproject
# Get detailed output
safeai scan ./myproject --format table
# Export results to JSON
safeai scan ./myproject --format json --output report.json
Command Line Options
# Filter by severity
safeai scan ./myproject --severity HIGH,MEDIUM
# Ignore specific directories
safeai scan ./myproject --ignore tests,docs,venv
# Fail CI/CD pipeline if issues found
safeai scan ./myproject --fail-on-error
# List all available rules
safeai list-rules
# Show version
safeai version
🔍 Security Rules
SafeAI includes 11 security rules specifically designed for AI-generated code:
Critical (HIGH) Severity
- PY001:
eval()/exec()usage - Code injection risk - PY002: Hardcoded secrets - API keys, tokens, passwords
- PY003: SQL injection - String concatenation in SQL queries
- PY004: Command injection -
os.system(),subprocesswithshell=True - PY005: Unsafe deserialization -
pickle.loads(),yaml.load()without Loader
Medium (MEDIUM) Severity
- PY006: Path traversal - File operations without path validation
- PY007: Missing input validation - Functions without parameter validation
- PY008: Assert for security - Security checks using
assert(can be disabled) - PY009: Insecure HTTP -
requestswithverify=False
Low (LOW) Severity
- PY010: Weak cryptography - MD5, SHA1, DES usage
- PY011: Missing exception handling - Critical operations without try/except
📋 Example Output
$ safeai scan vulnerable_code.py
⚠️ Found 3 security issues in vulnerable_code.py:
🔴 [PY001] Using eval() or exec() can be unsafe
Line 3: result = eval(expr)
Recommendation: Avoid using eval() and exec(). Use safe alternatives or thoroughly validate input data.
🔴 [PY002] Hardcoded secrets or tokens detected in code
Line 6: api_key = "sk-1234567890abcdef"
Recommendation: Use environment variables or configuration files to store secrets.
🟡 [PY010] Using weak cryptographic algorithms
Line 15: hash_value = hashlib.md5(data).hexdigest()
Recommendation: Use modern cryptographic algorithms: SHA-256 instead of MD5/SHA1.
🐍 Python API
from safeai import CodeAnalyzer
# Initialize analyzer
analyzer = CodeAnalyzer()
# Analyze code string
code = "result = eval('1 + 1')"
issues = analyzer.analyze_code(code)
# Analyze file
issues = analyzer.analyze_file("main.py")
# Analyze directory
results = analyzer.analyze_directory("./myproject")
# Get rules information
rules = analyzer.get_rules_info()
🔧 Configuration
Ignore Patterns
SafeAI automatically ignores common directories:
__pycache__,.git,.pytest_cachevenv,env,.venv,.envnode_modules,.tox,.noxbuild,dist,*.egg-info
Custom Ignore Patterns
safeai scan ./myproject --ignore custom_dir,another_dir
🛠️ Development
Setup Development Environment
# Clone repository
git clone https://github.com/whickybravo388/safeai.git
cd safeai
# Install in development mode
pip install -e .
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run linting
ruff check .
# Run type checking
mypy safeai/
Adding Custom Rules
from safeai.rules.base import BaseRule
class CustomRule(BaseRule):
id = "CUSTOM001"
description = "Custom security rule"
severity = "MEDIUM"
recommendation = "Fix this issue"
def check(self, code: str, ast_tree=None):
# Your detection logic here
if "dangerous_pattern" in code:
return self._create_issue(
line=1,
column=0,
code_snippet="dangerous_pattern",
details="Custom issue detected"
)
return None
📊 CI/CD Integration
GitHub Actions
name: Security Scan
on: [push, pull_request]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.9"
- name: Install SafeAI
run: pip install safeai
- name: Run security scan
run: safeai scan . --fail-on-error
GitLab CI
security-scan:
stage: test
image: python:3.9
script:
- pip install safeai
- safeai scan . --fail-on-error
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Workflow
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run the test suite
- Submit a pull request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Inspired by tools like Bandit and Safety
- Built with Rich for beautiful terminal output
- Uses Python's built-in
astmodule for code analysis
📞 Support
- 📧 Email: whickybravo388@gmail.com
- 🐛 Issues: GitHub Issues
🔄 Changelog
v0.1.0 (2024-01-XX)
- Initial release
- 11 security rules for Python
- CLI interface with multiple output formats
- Comprehensive test suite
- Full documentation
Made with ❤️ by the SafeAI Team
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file safeai_scanner-0.1.1.tar.gz.
File metadata
- Download URL: safeai_scanner-0.1.1.tar.gz
- Upload date:
- Size: 31.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d4df1f37896938077e1bf5568a7b303662747af70dc046dbd9d883f7071ae0d4
|
|
| MD5 |
f3661eab46d5e1fd066c02d3d5384be2
|
|
| BLAKE2b-256 |
0f2258ea387036576a32e591032375c4234b7a92ea385ae71923b9c6d76ec5ca
|
File details
Details for the file safeai_scanner-0.1.1-py3-none-any.whl.
File metadata
- Download URL: safeai_scanner-0.1.1-py3-none-any.whl
- Upload date:
- Size: 20.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
45e8ed05f0706f191be31753c13a0b4b0e653309047a34fc436aa184e754f8e4
|
|
| MD5 |
8a4943b153828529d5e911e6c500a142
|
|
| BLAKE2b-256 |
43b3d8cbf23ff33d69cd375b37cd32c2bc964a62f144ed1014beef86cba29a51
|