SOC 2 Compliance

🔥 Vibe Prompt

"Prepare for SOC 2 Type II audit: controls for Security, Availability, Confidentiality."

SOC 2 Trust Services Criteria

| Criteria | Description | Example Controls |
|----------|-------------|------------------|
| Security  | Protected against unauthorized access | Firewall, IAM, MFA, IDS |
| Availability | System available for operation | HA, backup, DR, monitoring |
| Confidentiality | Data classified and protected | Encryption, access control |
| Processing Integrity | Processing complete, accurate | Logging, validation, reconciliation |
| Privacy | PII collected, used, retained properly | Consent, GDPR, data lifecycle |

Key Controls (Security)

# Control: Access Review - quarterly review of all users
@app.route('/api/access/review', methods=['POST'])
@admin_required
def access_review():
    # Generate access report
    users = db.execute("SELECT id, email, role, last_login, created_at FROM users ORDER BY role, email")
    
    # Mark inactive users (>90 days no login)
    inactive = [u for u in users if u.last_login and (datetime.now() - u.last_login).days > 90]
    
    # Send to security team
    send_email(
        to="security@company.com",
        subject=f"Quarterly Access Review - {date.today().strftime('%Y-Q%m')}",
        body=generate_access_report(users, inactive)
    )
    
    return jsonify({"users": len(users), "inactive": len(inactive)})

SOC 2 Evidence Collection

# Automated evidence collection
class SOC2Evidence:
    def __init__(self):
        self.evidence = []
    
    def collect_security(self):
        # Firewall rules
        fw_rules = subprocess.run(["iptables", "-L", "-n"], capture_output=True, text=True).stdout
        
        # Failed logins
        failed = db.execute("SELECT COUNT(*) FROM auth_log WHERE success=false AND timestamp > NOW() - INTERVAL '24 hours'").fetchone()[0]
        
        # MFA usage
        mfa_users = db.execute("SELECT COUNT(*) FROM users WHERE mfa_enabled=true").fetchone()[0]
        total_users = db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
        
        self.evidence.append({"type": "firewall_rules", "data": fw_rules, "timestamp": datetime.now()})
        self.evidence.append({"type": "failed_logins_24h", "data": failed, "timestamp": datetime.now()})
        self.evidence.append({"type": "mfa_adoption", "data": f"{mfa_users}/{total_users}", "timestamp": datetime.now()})
    
    def collect_availability(self):
        # Uptime
        uptime = subprocess.run(["uptime"], capture_output=True, text=True).stdout
        
        # Backup success
        backup = db.execute("SELECT COUNT(*) FROM backup_log WHERE success=true AND timestamp > NOW() - INTERVAL '7 days'").fetchone()[0]
        
        self.evidence.append({"type": "uptime", "data": uptime, "timestamp": datetime.now()})
        self.evidence.append({"type": "backup_success_7d", "data": backup, "timestamp": datetime.now()})
    
    def export(self):
        return {
            "company": "MyApp Inc.",
            "period": f"{date.today() - timedelta(days=180)} to {date.today()}",
            "evidence_count": len(self.evidence),
            "items": self.evidence
        }

Control Matrix Example

| Control ID | Control Name | Frequency | Owner | Evidence |
|------------|-------------|-----------|-------|----------|
| CC6.1 | Firewall rules review | Quarterly | Engineering | Firewall config backup |
| CC6.2 | Access termination | Within 24h | HR+IT | HR ticket → IAM deprovision |
| CC6.3 | MFA for admin | Always | Security | IAM MFA report |
| CC7.1 | Vulnerability scan | Weekly | Security | Nessus report |
| CC7.2 | IDS/IPS monitoring | 24/7 | Security | SIEM alerts |
| CC8.1 | Change management | Per change | Engineering | PR + approval in Jira |
| A1.1 | Backup monitoring | Daily | Engineering | Backup success report |
| A1.2 | DR test | Annually | Engineering | DR test report |

SOC 2 vs SOC 1 vs SOC 3

| Aspect | SOC 1 | SOC 2 | SOC 3 | |--------|-------|-------|-------| | Focus | Financial controls | Trust Services | Same as SOC 2 | | Audience | User auditor | Management, customers | General public | | Distribution | Restricted | Restricted | Public | | Report Type | Type I/II | Type I/II | Type II only |

Type I vs Type II

| Aspect | Type I | Type II | |--------|--------|---------| | Point in time | Controls designed properly | ✅ | ❌ | | Over period | Controls operating effectively | ❌ | ✅ | | Effort | 1-2 months | 6-12 months | | Cost | Lower | Higher | | Customer preference | Sometimes | Usually required |

Best Practices

  • Start with SOC 2 Type I (design), then Type II (operating)
  • Use automated evidence collection (saves months)
  • Map controls to TSC criteria clearly
  • Run control tests quarterly (not just at audit)
  • Remediate findings within SLA (30/60/90 days)
  • Use a GRC tool (Vanta, Drata, Secureframe)
  • Involve engineering early in control design


為什麼要學SOC 2 合規?

SOC 2 合規 是 security-compliance 課程的核心章節之一。

在真實世界中

SOC 2 合規 並不是課本上的理論——它在真實的軟體開發中頻繁出現。無論你是正在接案、準備面試,還是想要提升自己的技術深度,理解這個主題都能讓你直接受益。

你將從本章獲得

  • 🎯 完整的知識體系:從核心原理到實作細節,條理分明
  • 💻 可運行的程式碼:每段程式碼都是完整的,可直接執行
  • 🔍 除錯技巧:常見錯誤的分析與解決方案
  • 🚀 下一步指引:學完後該往哪個方向繼續深入

銜接下一章

本章為你建立了 SOC 2 合規 的完整知識基礎。下一章將在此基礎上,帶你探索更進階的真實世界應用場景——你將學會如何將本章所學應用到更複雜的問題中。

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!