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

# Compliance - GDPR (Verbose)

Comprehensive GDPR compliance review for data protection and privacy.

> ⚠️ **DISCLAIMER:** This GDPR 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 GDPR compliance assessment. Requirements should be validated
> by qualified legal and data protection counsel before relying on them for regulatory
> compliance. You are solely responsible for ensuring GDPR compliance.

## GDPR Overview

GDPR (General Data Protection Regulation) is EU regulation governing personal data processing.

**Scope:** Applies if:
- Organization is in EU
- Organization offers goods/services to EU residents
- Organization monitors behavior of EU residents

**Personal Data:** Any information relating to an identified or identifiable person (name, email, IP address, cookie ID, etc.)

**Penalties:** Up to €20M or 4% of global annual revenue (whichever is higher)

---

## GDPR Principles (Art.5)

### 1. Lawfulness, Fairness, Transparency

**Legal Basis for Processing** (Art.6):
- Consent
- Contract
- Legal obligation
- Vital interests
- Public task
- Legitimate interests

❌ **Gap:**
No privacy notice explaining why data is collected.

✅ **Compliant:**
```html
<form>
  <p>We collect your email to send order confirmations (legal basis: contract performance).</p>
  <input type="email" name="email" />
  <button>Submit</button>
</form>
```

---

### 2. Purpose Limitation

Collect data only for specified, explicit, legitimate purposes.

❌ **Gap:**
```python
# Collects email for orders, then uses it for marketing without consent
user = User(email=email)
send_marketing_email(email)  # Violates purpose limitation
```

✅ **Compliant:**
```python
user = User(email=email)
if user.marketing_consent:
    send_marketing_email(email)  # Only if separate consent obtained
```

---

### 3. Data Minimization

Collect only what's necessary.

❌ **Gap:**
```python
class User:
    name: str
    email: str
    phone: str
    address: str
    date_of_birth: str  # Not needed for this app!
```

✅ **Compliant:**
```python
class User:
    name: str  # Needed for personalization
    email: str  # Needed for login
    # Only collect what's necessary
```

---

### 4. Accuracy

Keep data accurate and up-to-date.

**Technical Control:**
```python
@app.route("/api/users/me", methods=["PATCH"])
@login_required
def update_user():
    current_user.email = request.json["email"]
    current_user.name = request.json["name"]
    db.commit()
    return {"message": "Updated"}, 200
```

---

### 5. Storage Limitation

Retain data only as long as necessary.

❌ **Gap:**
No automatic deletion. Data retained forever.

✅ **Compliant:**
```python
# Automated deletion after 2 years of inactivity
from datetime import datetime, timedelta

def delete_inactive_users():
    cutoff = datetime.now() - timedelta(days=730)
    inactive_users = db.query(User).filter(User.last_login < cutoff)
    for user in inactive_users:
        delete_user_data(user.id)
        logger.info(f"Deleted inactive user {user.id} (GDPR Art.5 - storage limitation)")
```

**Schedule:** Run monthly

---

### 6. Integrity & Confidentiality

Secure data against unauthorized access.

**Technical Controls:**
- Encryption at rest (AES-256)
- Encryption in transit (TLS 1.2+)
- Access controls (least privilege)
- Logging and monitoring

---

### 7. Accountability

Demonstrate compliance.

**Evidence:**
- Data Protection Impact Assessment (DPIA)
- Records of Processing Activities (ROPA)
- Data Processing Agreements (DPAs) with processors
- Privacy Policy
- Consent records
- Logs of data subject requests

---

## Data Subject Rights

### Art.15 - Right to Access

Users can request copy of their data.

**Implementation:**
```python
@app.route("/api/users/me/export", methods=["GET"])
@login_required
def export_user_data():
    user_id = current_user.id
    
    data = {
        "user": db.query(User).get(user_id).to_dict(),
        "orders": [o.to_dict() for o in db.query(Order).filter_by(user_id=user_id)],
        "payments": [p.to_dict() for p in db.query(Payment).filter_by(user_id=user_id)],
    }
    
    return jsonify(data), 200
```

**Timeline:** Must respond within 30 days.

---

### Art.17 - Right to Erasure ("Right to be Forgotten")

Users can request deletion.

**Implementation:**
```python
@app.route("/api/users/me", methods=["DELETE"])
@login_required
def delete_user_data():
    user_id = current_user.id
    
    # Delete from all tables
    db.delete(User).filter_by(id=user_id)
    db.delete(Order).filter_by(user_id=user_id)
    db.delete(Payment).filter_by(user_id=user_id)
    # ... all tables
    
    db.commit()
    
    logger.info(f"User {user_id} data deleted (GDPR Art.17 request)")
    return {"message": "Your data has been deleted"}, 200
```

**Exceptions:** Can refuse if data needed for:
- Legal obligation
- Legal claims
- Public interest

**Timeline:** Must respond within 30 days.

---

### Art.20 - Right to Data Portability

Users can export data in machine-readable format.

**Implementation:**
```python
@app.route("/api/users/me/export", methods=["GET"])
@login_required
def export_portable_data():
    user_id = current_user.id
    
    data = get_all_user_data(user_id)
    
    # Return as JSON (machine-readable)
    response = make_response(jsonify(data))
    response.headers["Content-Disposition"] = "attachment; filename=my_data.json"
    return response
```

---

## Consent (Art.7)

**Requirements:**
- Freely given
- Specific
- Informed
- Unambiguous
- Opt-in (not pre-checked boxes)
- Withdrawable (as easy to withdraw as to give)

❌ **Bad:**
```html
<!-- Pre-checked box -->
<input type="checkbox" name="marketing" checked />  
<label>I agree to marketing emails</label>
```

✅ **Good:**
```html
<input type="checkbox" name="marketing" />  <!-- Not pre-checked -->
<label>I consent to receiving marketing emails. You can withdraw consent at any time.</label>
```

**Record Consent:**
```python
class Consent(Base):
    user_id = Column(Integer)
    purpose = Column(String)  # "marketing", "analytics", etc.
    granted_at = Column(DateTime)
    ip_address = Column(String)
    user_agent = Column(String)
    privacy_policy_version = Column(String)  # Version user agreed to
```

---

## Breach Notification (Art.33)

**Timeline:** 72 hours from becoming aware of breach.

**Technical Controls:**
```python
# Detect breaches
if unauthorized_access_detected():
    send_alert("GDPR breach detected - unauthorized access to user data")
    log_breach({
        "detected_at": datetime.now(),
        "type": "unauthorized_access",
        "affected_users": get_affected_users(),
    })
```

**Process:**
1. Detect breach (technical controls + monitoring)
2. Assess severity (how many users? what data?)
3. Notify supervisory authority within 72 hours
4. Notify affected users if high risk

---

## Third-Party Processors (Art.28)

**Data Processing Agreement (DPA) Required** for any vendor that processes personal data.

**DPA Must Include:**
- What data is processed
- Purpose of processing
- Duration
- Security measures
- Sub-processor approval
- Data subject rights support
- Breach notification obligations

**Examples of Processors:**
- Email provider (e.g., SendGrid)
- Analytics (e.g., Google Analytics)
- CRM (e.g., Salesforce)
- Hosting (e.g., AWS)

**Action:** Maintain list of all processors with DPAs on file.

---

## Cross-Border Transfers (Chapter V)

If transferring personal data outside EU, must use:

1. **Adequacy Decision** (EU approves country as safe)
2. **Standard Contractual Clauses (SCCs)**
3. **Binding Corporate Rules (BCRs)**

**Example:**
If using AWS US region, execute SCCs with AWS.

---

## GDPR Compliance Checklist

```markdown
## GDPR Readiness Checklist

**Legal Basis:**
- [ ] Legal basis identified for all data processing
- [ ] Privacy notice published and accessible

**Data Subject Rights:**
- [ ] Right to access implemented (Art.15)
- [ ] Right to rectification implemented (Art.16)
- [ ] Right to erasure implemented (Art.17)
- [ ] Right to data portability implemented (Art.20)

**Consent:**
- [ ] Consent is opt-in (not pre-checked)
- [ ] Consent is recorded with timestamp and version
- [ ] Withdrawal process is as easy as giving consent

**Data Protection:**
- [ ] Encryption at rest and in transit
- [ ] Access controls (least privilege)
- [ ] Logging and monitoring

**Breach Notification:**
- [ ] Breach detection capability exists
- [ ] 72-hour notification process defined
- [ ] Breach log maintained

**Third-Party Processors:**
- [ ] All processors identified
- [ ] DPAs signed with all processors
- [ ] Sub-processors approved

**Cross-Border Transfers:**
- [ ] Transfers outside EU identified
- [ ] SCCs or other mechanism in place

**Documentation:**
- [ ] ROPA (Records of Processing Activities)
- [ ] DPIA (Data Protection Impact Assessment) if high-risk processing
- [ ] Privacy Policy published
```
