Lý thuyết
25 phút
Bài 7/12

Code Review với Copilot

Sử dụng Copilot để review code quality, security vulnerabilities, và best practices

Code Review với Copilot

1. Tại sao Review Code với AI?

Lợi ích của AI Code Review

AspectHuman ReviewAI Review
SpeedSlow (hours/days)Instant
ConsistencyVariableConsistent
AvailabilityLimited24/7
CoverageMay missComprehensive
LearningFrom experienceFrom patterns

AI Review bổ sung cho Human Review

  • ✅ Catch obvious issues trước
  • ✅ Consistent style checking
  • ✅ Security vulnerability scan
  • ✅ Human reviewer focus vào logic phức tạp

2. Review Methods với Copilot

2.1 Using /explain

Hiểu code trước khi review:

TypeScript
1// Select code, then:
2/explain this function in detail, including potential issues

2.2 Using Inline Chat

Select code và ask trực tiếp:

Text
1Ctrl+I
2> Review this code for:
3> - Security vulnerabilities
4> - Performance issues
5> - Best practices violations

2.3 Using @workspace

Review trong context của project:

Text
1@workspace review src/auth/login.ts considering the overall architecture

3. Security Review

Common Vulnerabilities

Security Checklist

Security Review
Injection Attacks
SQL Injection
XSS
Command Injection
Authentication
Weak Passwords
Session Issues
JWT Vulnerabilities
Data Security
Sensitive Data Exposure
Missing Encryption

Prompt Template cho Security Review

Text
1Review this code for security vulnerabilities:
2
3Check for:
41. SQL Injection
52. XSS (Cross-Site Scripting)
63. CSRF vulnerabilities
74. Hardcoded secrets/credentials
85. Insecure random number generation
96. Path traversal
107. Unvalidated redirects
118. Missing input validation
12
13For each issue found:
14- Describe the vulnerability
15- Show the vulnerable code
16- Provide the fix

Example: SQL Injection Check

Original Code:

Python
1def get_user(username):
2 query = f"SELECT * FROM users WHERE username = '{username}'"
3 return db.execute(query)

Prompt:

Text
1Review this for SQL injection

Copilot Response:

Text
1🚨 SQL INJECTION VULNERABILITY FOUND
2
3The code concatenates user input directly into SQL query.
4
5Attack Example:
6username = "'; DROP TABLE users; --"
7
8Fix:
9```python
10def get_user(username):
11 query = "SELECT * FROM users WHERE username = ?"
12 return db.execute(query, (username,))

Or use ORM:

Python
1def get_user(username):
2 return User.query.filter_by(username=username).first()
Text
1---
2
3## 4. Performance Review
4
5### Performance Checklist

Review this code for performance issues:

Check for:

  1. N+1 query problems
  2. Unnecessary loops
  3. Missing indexes
  4. Memory leaks
  5. Blocking operations
  6. Inefficient algorithms (O(n²) when O(n) possible)
  7. Redundant computations
  8. Large data in memory
Text
1### Example: N+1 Query Problem
2
3**Original Code:**
4```python
5def get_orders_with_items():
6 orders = Order.query.all() # 1 query
7 result = []
8 for order in orders:
9 items = order.items # N queries!
10 result.append({
11 'order': order,
12 'items': items
13 })
14 return result

Copilot Review:

Text
1🔴 N+1 QUERY PROBLEM
2
3Current: 1 + N queries (N = number of orders)
4
5Fix: Use eager loading
6```python
7def get_orders_with_items():
8 orders = Order.query.options(
9 joinedload(Order.items)
10 ).all() # 1 query with JOIN
11
12 return [{'order': o, 'items': o.items} for o in orders]
Text
1---
2
3## 5. Code Quality Review
4
5### Clean Code Checklist

Review this code for clean code principles:

Check for:

  1. Single Responsibility violations
  2. Long functions (>20 lines)
  3. Deep nesting (>3 levels)
  4. Magic numbers
  5. Unclear naming
  6. Code duplication
  7. Missing error handling
  8. Incomplete documentation
Text
1### Example Review
2
3**Original Code:**
4```javascript
5function p(d) {
6 let t = 0;
7 for (let i = 0; i < d.length; i++) {
8 if (d[i].s === 1) {
9 if (d[i].a > 100) {
10 t += d[i].a * 0.9;
11 } else {
12 t += d[i].a;
13 }
14 }
15 }
16 return t;
17}

Copilot Review:

Text
1Code Quality Issues:
2
31. 📛 Unclear Naming
4 - `p` → `calculateTotalActiveAmount`
5 - `d` → `dataItems`
6 - `s` → `status`
7 - `a` → `amount`
8 - `t` → `total`
9
102. 🔢 Magic Numbers
11 - `1` → `STATUS_ACTIVE`
12 - `100` → `DISCOUNT_THRESHOLD`
13 - `0.9` → `DISCOUNT_RATE`
14
153. 📚 Missing Documentation
16
17Fixed Version:
18```javascript
19const STATUS_ACTIVE = 1;
20const DISCOUNT_THRESHOLD = 100;
21const DISCOUNT_RATE = 0.9;
22
23/**
24 * Calculates total amount for active items with bulk discount
25 * @param {Array} items - List of items with status and amount
26 * @returns {number} Total amount after discounts
27 */
28function calculateTotalActiveAmount(items) {
29 return items
30 .filter(item => item.status === STATUS_ACTIVE)
31 .reduce((total, item) => {
32 const amount = item.amount > DISCOUNT_THRESHOLD
33 ? item.amount * DISCOUNT_RATE
34 : item.amount;
35 return total + amount;
36 }, 0);
37}
Text
1---
2
3## 6. Review Specific Patterns
4
5### 6.1 Error Handling Review

Review error handling in this code:

  • Are all errors caught?
  • Are errors logged properly?
  • Are user-facing messages safe (no sensitive data)?
  • Is there proper cleanup on error?
Text
1### 6.2 API Design Review

Review this API for:

  • RESTful conventions
  • Proper status codes
  • Input validation
  • Response format consistency
  • Error response format
Text
1### 6.3 Database Code Review

Review this database code for:

  • Transaction handling
  • Connection management
  • Query efficiency
  • Data integrity
  • Race conditions
Text
1### 6.4 Frontend Code Review

Review this React component for:

  • Unnecessary re-renders
  • Memory leaks (missing cleanup)
  • Accessibility (a11y)
  • State management
  • Props validation
Text
1---
2
3## 7. Review Workflow
4
5### Step-by-step Review Process
6
7```markdown
8## Code Review Checklist
9
10### 1. Functionality
11- [ ] Does it work as expected?
12- [ ] Edge cases handled?
13- [ ] Error states handled?
14
15### 2. Security
16- [ ] Input validation?
17- [ ] No sensitive data exposed?
18- [ ] Proper authentication/authorization?
19
20### 3. Performance
21- [ ] Efficient algorithms?
22- [ ] No unnecessary operations?
23- [ ] Proper caching?
24
25### 4. Maintainability
26- [ ] Clear naming?
27- [ ] Proper documentation?
28- [ ] No code duplication?
29
30### 5. Testing
31- [ ] Tests exist?
32- [ ] Tests pass?
33- [ ] Edge cases tested?

Quick Review Command

Tạo command tổng hợp:

Text
1@workspace Review the staged changes:
2
31. Security check
42. Performance check
53. Code quality check
64. Test coverage check
7
8Format:
9- 🔴 Critical: Must fix
10- 🟡 Warning: Should fix
11- 🟢 Suggestion: Nice to have

8. Automated Review Integration

Pre-commit Review

Tạo script để review trước khi commit:

Python
1# pre_commit_review.py
2import subprocess
3import sys
4
5def get_staged_files():
6 result = subprocess.run(
7 ['git', 'diff', '--staged', '--name-only'],
8 capture_output=True, text=True
9 )
10 return result.stdout.strip().split('\n')
11
12def review_file(filepath):
13 # Use Copilot CLI or API for automated review
14 print(f"Reviewing: {filepath}")
15 # Integration code here
16
17if __name__ == "__main__":
18 files = get_staged_files()
19 issues = []
20
21 for f in files:
22 if f.endswith(('.py', '.js', '.ts')):
23 issues.extend(review_file(f))
24
25 if any(i['severity'] == 'critical' for i in issues):
26 print("❌ Critical issues found. Fix before committing.")
27 sys.exit(1)
28
29 print("✅ Review passed")

GitHub Actions Integration

yaml
1# .github/workflows/code-review.yml
2name: AI Code Review
3
4on:
5 pull_request:
6 branches: [main]
7
8jobs:
9 review:
10 runs-on: ubuntu-latest
11 steps:
12 - uses: actions/checkout@v4
13
14 - name: AI Code Review
15 uses: github/copilot-code-review-action@v1
16 with:
17 github-token: ${{ secrets.GITHUB_TOKEN }}

9. Review Response Patterns

Constructive Feedback Format

Khi nhận review từ Copilot, reformat để share với team:

markdown
1## Code Review: feature/user-auth
2
3### Summary
4Overall: 🟡 Needs minor fixes
5
6### Issues Found
7
8#### 🔴 Critical (1)
91. **SQL Injection in login.py:45**
10 - Issue: User input concatenated in query
11 - Fix: Use parameterized queries
12
13#### 🟡 Warning (2)
141. **Missing error handling in auth_service.py:78**
152. **Hardcoded timeout value in config.py:12**
16
17#### 🟢 Suggestions (3)
181. Consider adding docstrings to public methods
192. Could simplify the conditional at line 89
203. Unit test coverage could be improved
21
22### Recommended Actions
231. Fix SQL injection immediately
242. Add error handling before merge
253. Address suggestions in follow-up PR

10. Hands-on Exercise

Challenge: Security Review

Review đoạn code sau và tìm tất cả security issues:

JavaScript
1const express = require('express');
2const app = express();
3
4app.post('/login', (req, res) => {
5 const { username, password } = req.body;
6
7 // Check credentials
8 const query = `SELECT * FROM users
9 WHERE username='${username}'
10 AND password='${password}'`;
11
12 db.query(query, (err, results) => {
13 if (results.length > 0) {
14 const token = username + Date.now();
15 res.cookie('auth', token);
16 res.redirect('/dashboard?user=' + username);
17 } else {
18 res.send('Invalid credentials for ' + username);
19 }
20 });
21});
22
23app.get('/profile/:id', (req, res) => {
24 const userId = req.params.id;
25 const userData = fs.readFileSync('./users/' + userId + '.json');
26 res.json(JSON.parse(userData));
27});

Task:

  1. Sử dụng Copilot để identify tất cả vulnerabilities
  2. List các issues theo severity
  3. Provide fixed version cho từng issue

Expected Issues:

  • SQL Injection
  • Plain text password storage
  • Weak session token
  • XSS in error message
  • Open redirect
  • Path traversal
  • Missing input validation

Tiếp theo

Bài tiếp theo: Refactoring với Copilot - cải thiện code structure, clean up tech debt, và modernize codebase!