Perform thorough code reviews with security, performance, and maintainability analysis. Use when user asks to review code, check for bugs, or audit a codebase.
git clone https://github.com/shareAI-lab/learn-claude-code.git--- name: code-review description: Perform thorough code reviews with security, performance, and maintainability analysis. Use when user asks to review code, check for bugs, or audit a codebase. --- # Code Review Skill You now have expertise in conducting comprehensive code reviews. Follow this structured approach: ## Review Checklist ### 1. Security (Critical) Check for: - [ ] **Injection vulnerabilities**: SQL, command, XSS, template injection - [ ] **Authentication issues**: Hardcoded credentials, weak auth - [ ] **Authorization flaws**: Missing access controls, IDOR - [ ] **Data exposure**: Sensitive data in logs, error messages - [ ] **Cryptography**: Weak algorithms, improper key management - [ ] **Dependencies**: Known vulnerabilities (check with `npm audit`, `pip-audit`) ```bash # Quick security scans npm audit # Node.js pip-audit # Python cargo audit # Rust grep -r "password\|secret\|api_key" --include="*.py" --include="*.js" ``` ### 2. Correctness Check for: - [ ] **Logic errors**: Off-by-one, null handling, edge cases - [ ] **Race conditions**: Concurrent access without synchronization - [ ] **Resource leaks**: Unclosed files, connections, memory - [ ] **Error handling**: Swallowed exceptions, missing error paths - [ ] **Type safety**: Implicit conversions, any types ### 3. Performance Check for: - [ ] **N+1 queries**: Database calls in loops - [ ] **Memory issues**: Large allocations, retained references - [ ] **Blocking operations**: Sync I/O in async code - [ ] **Inefficient algorithms**: O(n^2) when O(n) possible - [ ] **Missing caching**: Repeated expensive computations ### 4. Maintainability Check for: - [ ] **Naming**: Clear, consistent, descriptive - [ ] **Complexity**: Functions > 50 lines, deep nesting > 3 levels - [ ] **Duplication**: Copy-pasted code blocks - [ ] **Dead code**: Unused imports, unreachable branches - [ ] **Comments**: Outdated, redundant, or missing where needed ### 5. Testing Check for: - [ ] **Coverage**: Critical paths tested - [ ] **Edge cases**: Null, empty, boundary values - [ ] **Mocking**: External dependencies isolated - [ ] **Assertions**: Meaningful, specific checks ## Review Output Format ```markdown ## Code Review: [file/component name] ### Summary [1-2 sentence overview] ### Critical Issues 1. **[Issue]** (line X): [Description] - Impact: [What could go wrong] - Fix: [Suggested solution] ### Improvements 1. **[Suggestion]** (line X): [Description] ### Positive Notes - [What was done well] ### Verdict [ ] Ready to merge [ ] Needs minor changes [ ] Needs major revision ``` ## Common Patterns to Flag ### Python ```python # Bad: SQL injection cursor.execute(f"SELECT * FROM users WHERE id = {user_id}") # Good: cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) # Bad: Command injection os.system(f"ls {user_input}") # Good: subprocess.run(["ls", user_input], check=True) # Bad: Mutable default argument def append(item, lst=[]): # Bug: shared mutable default # Good: def append(item, lst=None): lst = lst or [] ``` ### JavaScript/TypeScript ```javascript // Bad: Prototype pollution Object.assign(target, userInput) // Good: Object.assign(target, sanitize(userInput)) // Bad: eval usage eval(userCode) // Good: Never use eval with user input // Bad: Callback hell getData(x => process(x, y => save(y, z => done(z)))) // Good: const data = await getData(); const processed = await process(data); await save(processed); ``` ## Review Commands ```bash # Show recent changes git diff HEAD~5 --stat git log --oneline -10 # Find potential issues grep -rn "TODO\|FIXME\|HACK\|XXX" . grep -rn "password\|secret\|token" . --include="*.py" # Check complexity (Python) pip install radon && radon cc . -a # Check dependencies npm outdated # Node pip list --outdated # Python ``` ## Review Workflow 1. **Understand context**: Read PR description, linked issues 2. **Run the code**: Build, test, run locally if possible 3. **Read top-down**: Start with main entry points 4. **Check tests**: Are changes tested? Do tests pass? 5. **Security scan**: Run automated tools 6. **Manual review**: Use checklist above 7. **Write feedback**: Be specific, suggest fixes, be kind
[{"step":"Prepare the code for review","action":"Copy the relevant code snippet or upload the file to your AI tool. Include context such as the programming language, framework, and purpose of the code (e.g., 'This is a React component for a user dashboard').","tip":"For large codebases, focus on specific files or modules rather than the entire repository. Mention any known issues or areas of concern to get targeted feedback."},{"step":"Specify review priorities","action":"Tell the AI what aspects to focus on. For example: 'Check for security vulnerabilities in this API endpoint' or 'Review this database query for performance issues'.","tip":"Use terms like 'security', 'performance', 'maintainability', or 'bug risks' to guide the review. The more specific you are, the more actionable the feedback will be."},{"step":"Request actionable feedback","action":"Ask for code examples, explanations, and prioritized suggestions. For example: 'Provide fixes for the SQL injection vulnerability with code examples' or 'Suggest optimizations for this loop'.","tip":"Ask for 'before and after' comparisons to make it easier to implement changes. Highlight the most critical issues first."},{"step":"Iterate and refine","action":"After receiving feedback, address the issues and request a follow-up review. For example: 'I’ve fixed the SQL injection issue. Can you review the updated code for any remaining vulnerabilities?'","tip":"Use version control (e.g., Git) to track changes and compare them with the original code. This helps in identifying what was fixed."},{"step":"Automate where possible","action":"Use tools like SonarQube, ESLint, or Pylint alongside the AI review for continuous integration. Integrate the AI review into your pull request workflow.","tip":"Combine AI feedback with static analysis tools to catch issues early in the development cycle. Set up automated checks in your CI/CD pipeline."}]
No install command available. Check the GitHub repository for manual installation instructions.
git clone https://github.com/shareAI-lab/learn-claude-code/tree/main/skills/code-reviewCopy the install command above and run it in your terminal.
Launch Claude Code, Cursor, or your preferred AI coding agent.
Use the prompt template or examples below to test the skill.
Adapt the skill to your specific use case and workflow.
Perform a comprehensive code review of the following [LANGUAGE] code snippet: [CODE_SNIPPET]. Evaluate it for: 1) Security vulnerabilities (e.g., SQL injection, XSS, hardcoded secrets), 2) Performance bottlenecks (e.g., inefficient loops, memory leaks), 3) Maintainability issues (e.g., code duplication, poor naming, lack of comments), and 4) Bug risks (e.g., edge cases, race conditions). Provide specific suggestions for improvements with code examples where applicable. Focus on actionable feedback that a developer can implement immediately.
### Code Review: User Authentication Module (Python)
**Reviewed Code:**
```python
import sqlite3
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
username = data['username']
password = data['password']
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute(f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'")
user = cursor.fetchone()
conn.close()
if user:
return jsonify({'status': 'success'})
else:
return jsonify({'status': 'error'}), 401
```
### Findings:
**1. Critical Security Vulnerabilities:**
- **SQL Injection Risk:** The query uses string formatting (`f"SELECT ... '{username}' ... '{password}'"`), which is vulnerable to SQL injection. An attacker could input `' OR '1'='1` as the username to bypass authentication.
- **Password Storage:** Passwords are stored in plaintext. This is a major security risk. Use bcrypt or Argon2 for hashing.
- **Hardcoded Database Connection:** The database path (`users.db`) is hardcoded. This makes it difficult to change environments or test locally.
**2. Performance Issues:**
- **Database Connection Handling:** The connection is opened and closed for every request. This is inefficient. Use connection pooling (e.g., `with sqlite3.connect(...) as conn`).
- **No Indexing:** The `users` table likely lacks an index on `username`, leading to slow queries as the table grows.
**3. Maintainability Issues:**
- **No Input Validation:** The code assumes the request body contains `username` and `password` keys. Missing keys will cause a `KeyError`. Validate the input first.
- **No Error Handling:** The code doesn’t handle database errors (e.g., connection failures, table not found). This could crash the application.
- **Poor Naming:** The function name `login` is too generic. Consider `authenticate_user` for clarity.
**4. Bug Risks:**
- **Case Sensitivity:** The query is case-sensitive for both username and password. This may cause issues if the application expects case-insensitive matching.
- **No Rate Limiting:** The endpoint is vulnerable to brute-force attacks. Implement rate limiting (e.g., using Flask-Limiter).
### Suggested Improvements:
**Security Fixes:**
```python
from werkzeug.security import generate_password_hash, check_password_hash
import bcrypt
# Use parameterized queries to prevent SQL injection
cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password))
# Hash passwords before storing them (do this during user registration)
password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
```
**Performance Fixes:**
```python
# Use connection pooling
with sqlite3.connect('users.db') as conn:
cursor = conn.cursor()
...
```
**Maintainability Fixes:**
```python
@app.route('/login', methods=['POST'])
def authenticate_user():
data = request.get_json()
if not data or 'username' not in data or 'password' not in data:
return jsonify({'status': 'error', 'message': 'Invalid input'}), 400
username = data['username'].strip()
password = data['password']
...
```
**Additional Recommendations:**
- Add logging for failed login attempts.
- Use environment variables for database paths and secrets.
- Implement JWT for stateless authentication after login.
### Summary:
This code is **high-risk** due to SQL injection and plaintext password storage. Prioritize the security fixes before deploying to production. The performance and maintainability issues are secondary but should be addressed to ensure long-term scalability.skills-collection
Take a free 3-minute scan and get personalized AI skill recommendations.
Take free scan