1. AI生成程式碼的安全現狀
2025-2026 年,Vibe Coding 將會蓬勃發展,但隨之而來的是嚴重的安全問題:
| 研究 | 結果 |
|---|---|
| 維拉代碼 (2026) | 72% 使用 AI 程式碼的應用程式有安全缺陷 |
| 史丹佛大學 (2025) | 使用人工智慧的開發人員編寫的程式碼安全性較低,但對安全性更有信心 |
| GitHub (2026) | 與 AI 產生的程式碼一起使用時,AI 程式碼掃描擷取的問題數量增加了 3 倍 |
核心問題:人工智慧接受公共程式碼的訓練-包括存在安全漏洞的程式碼。人工智慧沒有歧視 範例程式碼 (教程,StackOverflow) 生產程式碼。
2. OWASP Top 10 和 Vibe 編碼
2.1.注射 (A03:2021)
AI經常產生不安全的SQL查詢:
// ❌ 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.身份驗證被破壞 (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.敏感資料暴露 (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.不安全的直接物件參考 (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. AI程式碼常見漏洞
| 漏洞 | 人工智慧的頻率 | 範例 |
|---|---|---|
| 硬編碼的秘密 | 非常高 | API 金鑰、程式碼中的密碼 |
| 缺少輸入驗證 | 高 | 不驗證使用者輸入 |
| 弱加密 | 高 | MD5 代替 bcrypt、SHA-256 |
| 缺少身份驗證檢查 | 平均 | 端點不驗證用戶 |
| SQL注入 | 平均 | 字串連接查詢 |
| 跨站腳本攻擊 | 平均 | 直接 HTML 渲染 |
| 路徑遍歷 | 低 | 未清理的檔案路徑 |
4. 及時注射風險
使用 MCP 伺服器或透過 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
預防:
- 切勿將使用者輸入直接傳遞到 AI 提示中
- 在將輸入傳送給 AI 之前對其進行清理
- 執行前驗證 AI 輸出
- 使用允許列表而不是拒絕列表
5. 安全提示模式
5.1.自訂安全說明
## 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.安全第一提示
// 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.安全掃描工具
6.1. GitHub 高階安全性
GitHub Secret Scanning: phát hiện secrets trong code
CodeQL: static analysis cho security vulnerabilities
Dependabot: scan dependencies cho known vulnerabilities
6.2.在 CI/CD 管道中
# .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級掃描
// 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. Vibe 編碼的安全編碼模式
模式 1:驗證優先中間件
// 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();
};
};
模式二:授權守衛
// Resource-level authorization:
const canAccessProject = async (userId: string, projectId: string) => {
const member = await prisma.projectMember.findUnique({
where: {
userId_projectId: { userId, projectId },
},
});
return member !== null;
};
模式 3:輸出清理
// 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. Vibe 編碼的安全檢查表
| # | 檢查 | 當 |
|---|---|---|
| 1 | 沒有硬編碼的秘密 | 每次提交 |
| 2 | 所有端點的輸入驗證 | 每個新端點 |
| 3 | 受保護路由中的身份驗證中間件 | 每條新航線 |
| 4 | 參數化查詢 | 每個資料庫查詢 |
| 5 | 日誌/回應中沒有敏感數據 | 每個API回應 |
| 6 | 依賴項沒有 CVE | 每週 |
| 7 | 配置的安全標頭 | 一次+驗證 |
| 8 | 身份驗證端點的速率限制 | 一次+驗證 |
9. 總結
Vibe 編碼的安全性要求 不同的心態:
- 信任但驗證:AI代碼總是需要安全審查
- 縱深防禦:多層安全檢查
- 自動掃描:CI/CD 必須迫使 AI 問題產生
- 預設安全:自訂指令強制執行安全模式
- 保持更新:人工智慧模型得到改進,但威脅情勢也發生了變化
下一篇: 技術債和可維護性 — 使用 Vibe Coding 時管理技術債。