---
name: soc2
description: Compliance - soc2
mode: subagent
tools: [read]
workflows:
  - soc2-workflow
---

# Compliance - SOC 2 (Verbose)

Comprehensive SOC 2 Type II compliance review using Trust Service Criteria.

> ⚠️ **DISCLAIMER:** This SOC 2 analysis is generated by an AI assistant and is
> provided "as-is" without warranty of any kind. It is not legal advice and does not
> constitute a formal SOC 2 audit. Controls should be validated by qualified SOC 2
> auditors before relying on them for audit purposes.

## SOC 2 Overview

SOC 2 is an auditing standard for service organizations that store customer data. It focuses on five "Trust Service Criteria":

- **Security** (required for all SOC 2 audits)
- **Availability** (optional)
- **Processing Integrity** (optional)
- **Confidentiality** (optional)
- **Privacy** (optional)

**Type I:** Controls are designed appropriately (point-in-time)  
**Type II:** Controls operate effectively over time (6-12 months)

---

## Common Criteria (CC) - Security

### CC6 - Logical and Physical Access Controls

**CC6.1 - Access Controls**

Controls access to information assets based on least privilege.

❌ **Gap:**
```python
# All users have admin access
@app.route("/admin")
def admin_panel():
    return render_template("admin.html")  # No auth check!
```

✅ **Compliant:**
```python
@app.route("/admin")
@require_role("admin")
def admin_panel():
    return render_template("admin.html")
```

**Evidence:**
- Role-based access control (RBAC) implementation
- Access control matrix documenting who has what access
- Quarterly access reviews

---

**CC6.2 - Multi-Factor Authentication**

Requires MFA for privileged access.

❌ **Gap:**
```python
# Only password required
if user.password == hash(password):
    login(user)
```

✅ **Compliant:**
```python
if user.password == hash(password):
    if user.is_admin and not user.has_valid_mfa_token():
        return {"error": "MFA required"}, 401
    login(user)
```

**Evidence:**
- MFA implementation for admin accounts
- Screenshot of MFA enrollment process
- Logs showing MFA usage

---

**CC6.3 - Offboarding Process**

Access revoked when employee leaves.

**Technical Control:**
```python
def offboard_employee(employee_id):
    # Revoke all access immediately
    db.execute("UPDATE users SET active = false WHERE employee_id = ?", (employee_id,))
    # Disable API keys
    db.execute("DELETE FROM api_keys WHERE user_id IN (SELECT id FROM users WHERE employee_id = ?)", (employee_id,))
    # Log the action
    logger.info(f"Employee {employee_id} offboarded - all access revoked")
```

**Evidence:**
- Offboarding checklist
- Logs of access revocations
- HR termination date → access removal date (should be same day)

---

### CC7 - System Operations

**CC7.1 - Logging and Monitoring**

Logs security-relevant events and retains for ≥ 90 days.

❌ **Gap:**
No logging of authentication attempts or data access.

✅ **Compliant:**
```python
@app.before_request
def log_request():
    logger.info(f"User {current_user.id} accessed {request.path} from {request.remote_addr}")

@app.route("/api/users/<user_id>")
def get_user(user_id):
    user = db.query(User).get(user_id)
    logger.info(f"User {current_user.id} accessed user data for {user_id}")
    return jsonify(user)
```

**Evidence:**
- Log retention policy (90+ days)
- Screenshot of centralized logging system
- Example log entries showing who, what, when, where

---

**CC7.2 - Incident Response**

Detects and responds to security incidents.

**Technical Control:**
```python
# Alert on failed login attempts
if failed_login_count > 5:
    send_alert(f"Multiple failed logins for user {email} from {ip}")

# Alert on unusual access patterns
if access_time.hour < 6 or access_time.hour > 22:
    send_alert(f"Off-hours access by user {user_id}")
```

**Evidence:**
- Incident response plan document
- Logs of alerts sent
- Examples of incidents detected and resolved

---

### CC8 - Change Management

**CC8.1 - Change Approval**

All production changes reviewed and approved.

❌ **Gap:**
Developers can deploy directly to production without review.

✅ **Compliant:**
```yaml
# .github/workflows/deploy.yml
- name: Require approval
  uses: trstringer/manual-approval@v1
  with:
    approvers: tech-lead,cto
```

**Evidence:**
- Pull request logs showing approvals
- CI/CD pipeline configuration requiring reviews
- Deployment logs with approver names

---

**CC8.2 - Testing Before Deployment**

Changes tested before production deployment.

**Technical Control:**
```yaml
# .github/workflows/ci.yml
- name: Run tests
  run: pytest
- name: Block if tests fail
  if: failure()
  run: exit 1
```

**Evidence:**
- CI test results
- Test coverage reports (target: 80%+)
- Failed deployments blocked by failing tests

---

### CC9 / A1 - Availability

**CC9.1 - Backup and Recovery**

Data backed up and recovery tested.

**Technical Control:**
```bash
# Automated daily backups
0 2 * * * /usr/bin/pg_dump production_db | gzip > /backups/db_$(date +\%Y\%m\%d).sql.gz

# Retention: 30 days
find /backups -name "db_*.sql.gz" -mtime +30 -delete
```

**Evidence:**
- Backup logs showing daily execution
- Recovery test results (restore to test environment)
- RTO/RPO documentation (e.g., RTO: 4 hours, RPO: 24 hours)

---

**CC9.2 - Redundancy**

Critical systems have redundancy.

**Evidence:**
- Multi-AZ database deployment
- Load balancer configuration
- Auto-scaling group configuration

---

## Evidence Collection Checklist

For each control, auditor needs:

- [ ] **Policy:** Written policy or procedure document
- [ ] **Implementation:** Code, configuration, or system showing control in place
- [ ] **Operation:** Logs or reports proving control operated throughout audit period
- [ ] **Testing:** Evidence that control was tested (e.g., access review completed)

---

## Common SOC 2 Gaps

### 1. Logging Insufficient
- **Gap:** Logs don't capture who accessed what
- **Fix:** Add user ID, resource ID, timestamp, IP to all logs

### 2. No Access Reviews
- **Gap:** No quarterly review of who has access to what
- **Fix:** Generate access matrix quarterly, have manager review and sign off

### 3. No MFA for Admins
- **Gap:** Admins use password-only auth
- **Fix:** Implement TOTP MFA for all admin accounts

### 4. Backups Not Tested
- **Gap:** Backups run, but never tested restore
- **Fix:** Quarterly recovery drill: restore backup to test environment

### 5. No Change Approval Process
- **Gap:** Developers deploy directly to production
- **Fix:** Require PR approval + CI gates before merge

---

## SOC 2 Readiness Summary

```markdown
## SOC 2 Readiness Assessment

**Audit Period:** [Start] - [End] (6-12 months)

**Criteria in Scope:**
- [x] Security (required)
- [ ] Availability (optional)
- [ ] Confidentiality (optional)

**Controls Assessed:**
- CC6: N controls | N gaps
- CC7: N controls | N gaps
- CC8: N controls | N gaps
- CC9: N controls | N gaps

**Top Gaps:**
1. [Control ID] - [Gap description]
2. [Control ID] - [Gap description]

**Estimated Readiness:** [Ready | 1-2 months | 3-6 months | > 6 months]

**Recommended Actions:**
- [ ] Implement missing controls
- [ ] Collect evidence for 6-12 months
- [ ] Engage SOC 2 auditor
- [ ] Schedule pre-audit readiness assessment
```
