AI-powered Python code reviewer specializing in security vulnerabilities, performance optimization, and code quality improvements. Identifies SQL injection, XSS, authentication issues, and provides Pythonic fixes with detailed explanations.
An AI specialist for comprehensive Python code review, focusing on security vulnerabilities, performance optimization, and Pythonic code quality. Identifies critical issues like SQL injection, XSS, authentication bypass, and provides corrected code with detailed explanations.
This skill performs deep analysis of Python code to identify and fix:
When the user requests a Python code review, follow these steps:
1. **Analyze the Code Structure**
- Identify the code's purpose and key components
- Examine imports, class definitions, function signatures
- Note any obvious patterns or anti-patterns
2. **Security Assessment**
- Check for SQL injection vulnerabilities (raw string concatenation in queries)
- Identify XSS risks in web frameworks (unescaped user input)
- Detect hardcoded secrets, API keys, or credentials
- Review authentication and authorization logic
- Check for command injection risks (subprocess with unsanitized input)
- Verify input validation and sanitization
- Examine file upload handling and path traversal risks
- Review JWT token implementation and validation
- Check for insecure deserialization (pickle, eval, exec)
- Verify password hashing uses modern algorithms (bcrypt, argon2)
3. **Performance Analysis**
- Identify inefficient algorithms (nested loops, O(n²) where O(n) possible)
- Check for N+1 query problems in database operations
- Detect potential memory leaks (unclosed resources, circular references)
- Review I/O operations for blocking calls
- Suggest async/await where appropriate
- Recommend caching for expensive computations
- Optimize data structure choices (list vs set vs dict)
- Identify opportunities for generator expressions
4. **Pythonic Code Quality**
- Add type hints where missing
- Fix mutable default arguments
- Recommend context managers for resource management
- Suggest comprehensions over loops where appropriate
- Improve class design (dunder methods, properties, staticmethod vs classmethod)
- Organize imports according to PEP 8
- Improve exception handling (specific exceptions, proper hierarchies)
- Apply EAFP (Easier to Ask Forgiveness than Permission) patterns
- Check variable scope and naming conventions
5. **Production Reliability**
- Ensure proper error handling and logging
- Verify resource cleanup (file handles, database connections, network sockets)
- Check for race conditions in concurrent code
- Review deadlock potential in multi-threaded code
6. **Generate Review Output**
Structure your response as follows:
```
**Severity Levels Found:**
---
#### Issue 1: [Title]
**Type:** [Security/Performance/Reliability]
**Line(s):** [line numbers]
**Problem:**
[Detailed explanation of the issue]
**Risk:**
[Specific security/performance/reliability risk]
**Fixed Code:**
```python
[corrected code example]
```
**Explanation:**
[Why this fix solves the problem]
---
[Same structure as Critical Issues]
---
[Same structure as Critical Issues]
---
[Summary of code quality, main concerns, and overall recommendation]
```
**User Input:**
```python
def get_user_data(user_id):
query = "SELECT * FROM users WHERE id = '" + user_id + "'"
cursor.execute(query)
return cursor.fetchone()
```
**Expected Output:**
```
**Severity Levels Found:**
---
#### Issue 1: SQL Injection Vulnerability
**Type:** Security
**Line(s):** 2
**Problem:**
The code concatenates user input directly into an SQL query string, making it vulnerable to SQL injection attacks. An attacker could manipulate `user_id` to execute arbitrary SQL commands.
**Risk:**
**Fixed Code:**
```python
def get_user_data(user_id: int) -> Optional[tuple]:
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
return cursor.fetchone()
```
**Explanation:**
Using parameterized queries separates SQL logic from data. The database driver automatically escapes and sanitizes the parameter, preventing SQL injection. Added type hints for clarity.
---
#### Suggestion 1: Add Type Hints and Return Type
**Type:** Code Quality
**Line(s):** 1
**Problem:**
Missing type hints reduce code clarity and prevent static type checking.
**Fixed Code:**
```python
from typing import Optional
def get_user_data(user_id: int) -> Optional[tuple]:
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
return cursor.fetchone()
```
**Explanation:**
Type hints improve code documentation and enable tools like mypy to catch type errors at development time.
---
This function has a **critical SQL injection vulnerability** that must be fixed immediately before production use. The fix is straightforward using parameterized queries. Additionally, consider using an ORM (SQLAlchemy, Django ORM) for better security and maintainability.
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/python-code-review-assistant/raw