Chapter 1: Security and Compliance
Data Privacy Framework
from dataclasses import dataclass
from enum import Enum
class PIIType(Enum):
SSN = "social_security_number"
EMAIL = "email"
PHONE = "phone"
CREDIT_CARD = "credit_card"
ADDRESS = "address"
class PIIHandler:
def __init__(self):
self.patterns = {
PIIType.SSN: r"\b\d{3}-\d{2}-\d{4}\b",
PIIType.EMAIL: r"\b[\w.-]+@[\w.-]+\.\w+\b",
PIIType.PHONE: r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b",
PIIType.CREDIT_CARD: r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b",
}
def detect_pii(self, text: str) -> list[tuple[PIIType, str]]:
"""Detect PII in text."""
found = []
for pii_type, pattern in self.patterns.items():
matches = re.findall(pattern, text)
for match in matches:
found.append((pii_type, match))
return found
def redact(self, text: str) -> str:
"""Redact all PII from text."""
for pii_type, pattern in self.patterns.items():
text = re.sub(pattern, f"[{pii_type.value.upper()}_REDACTED]", text)
return text
Audit Trail
import json
from datetime import datetime
class AuditLogger:
def __init__(self, storage):
self.storage = storage
def log_request(self, request_id: str, user_id: str, prompt: str,
response: str, model: str, metadata: dict):
"""Log LLM interaction for audit."""
audit_record = {
"request_id": request_id,
"timestamp": datetime.utcnow().isoformat(),
"user_id": user_id,
"prompt_hash": hashlib.sha256(prompt.encode()).hexdigest(),
"response_hash": hashlib.sha256(response.encode()).hexdigest(),
"model": model,
"token_count": {
"input": count_tokens(prompt),
"output": count_tokens(response)
},
"metadata": metadata
}
# Store with retention policy
self.storage.store(audit_record, retention_days=365)
Compliance Checklist
| Framework | Requirements | Implementation |
|---|---|---|
| SOC2 | Access controls, encryption | IAM, TLS, KMS |
| HIPAA | PHI protection, audit logs | PII detection, logging |
| GDPR | Data minimization, consent | Purpose limitation, deletion |
| PCI-DSS | Card data protection | Tokenization, encryption |