1. Thực trạng bảo mật trong AI-Generated Code
Năm 2025-2026 chứng kiến sự bùng nổ của Vibe Coding, nhưng kèm theo là những lo ngại bảo mật nghiêm trọng:
| Nghiên cứu | Kết quả |
|---|---|
| VeraCode (2026) | 72% apps dùng AI code có security flaws |
| Stanford (2025) | Developers dùng AI viết code kém an toàn hơn và tự tin hơn about security |
| GitHub (2026) | AI code scanning catches 3x more issues khi dùng với AI-generated code |
Vấn đề cốt lõi: AI được train trên code công khai — bao gồm cả code có lỗ hổng bảo mật. AI không phân biệt code ví dụ (tutorial, StackOverflow) với production code.
2. OWASP Top 10 và Vibe Coding
2.1. Injection (A03:2021)
AI thường generate SQL queries không an toàn:
// ❌ AI có thể generate:
const users = await db.query(
`SELECT * FROM users WHERE email = '${email}'`
);
// ✅ Phải yêu cầu:
const users = await db.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
// Prompt an toàn:
Always use parameterized queries. Never concatenate user input
into SQL strings. Use ORM methods when available.
2.2. Broken Authentication (A07:2021)
// ❌ AI có thể generate weak JWT: jwt.sign(payload, 'secret123') // Hardcoded secret!
// ✅ Secure version: jwt.sign(payload, process.env.JWT_SECRET!, { expiresIn: '15m', algorithm: 'RS256', // Asymmetric })
2.3. Sensitive Data Exposure (A02:2021)
// ❌ AI có thể log sensitive data: console.log('User login:', { email, password }); res.json({ user: { ...user } }); // Includes password hash!
// ✅ Chỉ return cần thiết: const { password, ...safeUser } = user; res.json({ user: safeUser });
2.4. Insecure Direct Object Reference (A01:2021)
// ❌ AI thường bỏ auth check: app.get('/api/tasks/:id', async (req, res) => { const task = await prisma.task.findUnique({ where: { id: req.params.id }, }); res.json(task); // Any user can access any task! });
// ✅ Luôn check ownership: app.get('/api/tasks/:id', auth, async (req, res) => { const task = await prisma.task.findFirst({ where: { id: req.params.id, project: { members: { some: { userId: req.userId } }, }, }, }); if (!task) return res.status(404).json({ error: 'Not found' }); res.json(task); });
3. Lỗ hổng phổ biến trong AI Code
| Vulnerability | Tần suất AI mắc | Example |
|---|---|---|
| Hardcoded secrets | Rất cao | API keys, passwords trong code |
| Missing input validation | Cao | Không validate user input |
| Weak crypto | Cao | MD5 thay vì bcrypt, SHA-256 |
| Missing auth checks | Trung bình | Endpoint không verify user |
| SQL injection | Trung bình | String concatenation queries |
| XSS | Trung bình | Direct HTML rendering |
| Path traversal | Thấp | Unsanitized file paths |
4. Prompt Injection Risks
Khi sử dụng MCP servers hoặc xử lý user input qua AI:
// User nhập vào form:
"; DROP TABLE users; --
// Nếu AI xử lý raw input:
AI có thể generate code chứa malicious input
Phòng tránh:
- Không bao giờ pass user input trực tiếp vào AI prompt
- Sanitize input TRƯỚC khi chuyển đến AI
- Validate AI output trước khi execute
- Dùng allowlists thay vì denylists
5. Secure Prompting Patterns
5.1. Custom instructions cho security
## Security Requirements
- NEVER hardcode secrets, API keys, or passwords
- ALWAYS use parameterized queries, never string concatenation for SQL
- ALWAYS validate and sanitize user input at API boundaries
- ALWAYS check authorization before returning data
- NEVER log sensitive data (passwords, tokens, PII)
- Use bcrypt with cost factor >= 12 for password hashing
- Use HTTPS for all external API calls
- Set security headers (CORS, CSP, HSTS)
Implement rate limiting on auth endpoints
5.2. Security-first prompts
// Thay vì:
Create a login endpoint
// Dùng:
Create a secure login endpoint with:
- Rate limiting (5 attempts per minute per IP)
- Password hashing with bcrypt (cost 12)
- JWT with short expiry (15 min) + refresh token
- Account lockout after 10 failed attempts
- Audit logging for failed attempts
No password in response or logs
6. Security Scanning Tools
6.1. GitHub Advanced Security
GitHub Secret Scanning: phát hiện secrets trong code
CodeQL: static analysis cho security vulnerabilities
Dependabot: scan dependencies cho known vulnerabilities
6.2. Trong CI/CD pipeline
# .github/workflows/security.yml name: Security Scan on: [pull_request] jobs: security: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4# Dependency scan - run: npm audit --audit-level=high # Secret detection - uses: trufflesecurity/trufflehog@main with: path: ./ # SAST scan - uses: github/codeql-action/analyze@v3 with: languages: javascript-typescript # Container scan (if using Docker) - uses: aquasecurity/trivy-action@master with: scan-type: fs scan-ref: .
6.3. IDE-level scanning
// Copilot itself can help with security review:
@workspace /review Check all API endpoints for:
1. Missing authentication middleware
2. Missing input validation
3. SQL injection vulnerabilities
4. Hardcoded secrets
5. Sensitive data in responses
7. Secure Coding Patterns cho Vibe Coding
Pattern 1: Validate-first middleware
// Yêu cầu AI tạo validation middleware:
const validateRequest = (schema: z.ZodSchema) => {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({
error: 'Validation failed',
details: result.error.issues,
});
}
req.body = result.data; // Use validated data
next();
};
};
Pattern 2: Authorization guard
// Resource-level authorization:
const canAccessProject = async (userId: string, projectId: string) => {
const member = await prisma.projectMember.findUnique({
where: {
userId_projectId: { userId, projectId },
},
});
return member !== null;
};
Pattern 3: Output sanitization
// Chỉ return fields cần thiết:
const sanitizeUser = (user: User) => ({
id: user.id,
name: user.name,
email: user.email,
avatar: user.avatar,
// Exclude: password, resetToken, etc.
});
8. Security Checklist cho Vibe Coding
| # | Check | Khi nào |
|---|---|---|
| 1 | Không có hardcoded secrets | Mỗi commit |
| 2 | Input validation ở tất cả endpoints | Mỗi endpoint mới |
| 3 | Auth middleware ở protected routes | Mỗi route mới |
| 4 | Parameterized queries | Mỗi DB query |
| 5 | No sensitive data in logs/responses | Mỗi API response |
| 6 | Dependencies không có CVEs | Mỗi tuần |
| 7 | Security headers configured | Một lần + verify |
| 8 | Rate limiting on auth endpoints | Một lần + verify |
9. Tổng kết
Security trong Vibe Coding đòi hỏi mindset khác:
- Trust but verify: AI code luôn cần security review
- Defense in depth: Multiple layers of security checks
- Automate scanning: CI/CD phải bắt issues AI tạo ra
- Secure by default: Custom instructions enforce security patterns
- Stay updated: AI models cải thiện nhưng threat landscape cũng thay đổi
Bài tiếp theo: Technical Debt & Maintainability — quản lý nợ kỹ thuật khi dùng Vibe Coding.