Block 3: Security
13:15 - 14:45 90 minutes 3 Quests
🎯 Learning Goals
เมื่อจบบล็อกนี้ คุณจะ:
- ระบุ security vulnerabilities ใน AI-generated code
- แก้ไขปัญหาความปลอดภัยที่พบบ่อย
- ออกแบบระบบ architecture ที่ปลอดภัย
📖 Concept: Security in AI-Generated Code (30 min)
Why AI Code Can Be Insecure
AI models ถูกฝึกบนข้อมูลจำนวนมาก ซึ่งรวมถึง code ที่มี vulnerability:
- Training data: มีทั้ง good และ bad patterns
- No security context: AI ไม่รู้ว่า code นี้จะถูกใช้ที่ไหน
- Pattern matching: AI อาจเลือก pattern ที่ไม่ปลอดภัย
OWASP Top 10 (Most Critical)
warning 1. Injection
SQL, NoSQL, OS command injection
lock 2. Broken Auth
Weak passwords, session fixation
document 3. Sensitive Data
Hardcoded secrets, weak encryption
code 4. XSS
Cross-site scripting
Common Vulnerabilities in AI Code
1. SQL Injection
Bad (AI might generate):
const query = 'SELECT * FROM users WHERE id = ' + userId; Good (What you should use):
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId]); 2. Hardcoded Secrets
Bad:
const apiKey = 'sk-1234567890abcdef';
const dbPassword = 'admin123'; Good:
const apiKey = process.env.API_KEY;
const dbPassword = process.env.DB_PASSWORD; 3. Weak Password Hashing
Bad:
const hash = crypto.createHash('md5').update(password).digest('hex'); Good:
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 12); 4. No Input Validation
Bad:
function processPayment(amount) {
return charge(amount); // No validation!
} Good:
function processPayment(amount) {
if (typeof amount !== 'number' || amount <= 0) {
throw new Error('Invalid amount');
}
return charge(amount);
} 5. Path Traversal
Bad:
const filePath = path.join('/uploads', filename);
const content = fs.readFileSync(filePath); Good:
const safePath = path.normalize(filename).replace(/^(\.\.(\/|\\|$))+/, '');
const filePath = path.join('/uploads', safePath);
if (filePath.startsWith('/uploads')) {
const content = fs.readFileSync(filePath);
} 6. XSS (Cross-Site Scripting)
Bad:
function renderUserInput(userInput) {
return userInput;
} Good:
function sanitize(str) {
return str.replace(/[<>&"']/g, c => ({
'<': '<', '>': '>', '&': '&',
'"': '"', "'": "'"
}[c]));
}
function renderUserContent(userInput) {
return '<div>' + sanitize(userInput) + '</div>';
} 🛠️ Security Checklist
Before Running AI-Generated Code
- ☐ Check for hardcoded secrets
- ☐ Validate all inputs
- ☐ Use parameterized queries
- ☐ Hash passwords properly
- ☐ Sanitize file paths
- ☐ Escape HTML output
- ☐ Use HTTPS
- ☐ Implement rate limiting
Security Testing
# Run security linter
npm audit
# Check for vulnerabilities
npx snyk test
# Static analysis
npx eslint --plugin security 🎮 Code Quests
🟢 Quest 3.1: Spot the Vulnerability
Goal: Find security issues in AI-generated code
- Review the vulnerable code in
vulnerable.js - Identify ALL vulnerabilities
- SQL Injection
- Hardcoded Secrets
- Weak Hashing
- No Input Validation
- Path Traversal
- XSS
- Document each vulnerability
## Vulnerability 1: SQL Injection - Line: 10 - Severity: Critical - Description: User input concatenated into SQL - Fix: Use parameterized queries - Run the test suite to verify findings
Deliverable: Vulnerability report with all issues identified
🟡 Quest 3.2: Fix and Harden
Goal: Fix security vulnerabilities
- Fix each vulnerability from Quest 3.1
- Apply security hardening
- Add input validation
- Use environment variables
- Implement proper hashing
- Test your fixes
npm test - Document changes
- What you fixed
- Why it was vulnerable
- How you fixed it
Deliverable: Secure code with all tests passing
🔴 Quest 3.3: Security Architecture
Goal: Design a secure system
- Choose a system: Chatbot, API, or Web App
- Identify threats
- What attacks are possible?
- What's the impact?
- Design controls
- Authentication mechanism
- Authorization model
- Encryption strategy
- Document architecture
# Security Architecture: [System Name] ## Threat Model - Threat 1: [description] ## Controls - Control 1: [implementation]
Deliverable: Security architecture document
✅ Block 3 Checklist
- ☐ Understand common vulnerabilities
- ☐ Quest 3.1 completed
- ☐ Quest 3.2 completed
- ☐ Quest 3.3 completed
🚀 Next Block
Block 4: Agentic Workflows → Learn to create automated development loops and multi-agent systems.