Grok 4.1 Fast· xai
Frontier Reasoning Traces
Implement a privacy request workflow for logs: discovery, redaction, and verification…
- User
Implement a privacy request workflow for logs: discovery, redaction, and verification evidence.
- Assistant
Implement a privacy request workflow for logs: discovery, redaction, and verification evidence.
import json
import hashlib
import re
from datetime import datetime
from typing import List, Dict, Any, Tuple, Optional
from pathlib import Path
import logging
# Configure logging for the workflow itself (logs workflow actions, not user data)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class PrivacyRequestWorkflow:
"""
Implements a privacy request workflow for log processing:
1. DISCOVERY: Search logs for entries matching request identifiers (e.g., user_id, email).
2. REDACTION: Anonymize PII in discovered entries (replace with tokens/hashes).
3. VERIFICATION: Generate evidence (before/after diffs, hashes) proving compliance.
Assumptions:
- Logs are JSONL files (one JSON object per line).
- PII patterns: user_id (str/int), email (regex), ip_address (regex).
- Redaction: Replace PII with '[REDACTED-<hash>]' for auditability.
- Backups originals before redaction.
- Thread-safe for single requests; scale with locks for production.
Usage:
workflow = PrivacyRequestWorkflow(log_dir='/path/to/logs')
evidence = workflow.process_request(request_id='req-123', identifiers={'user_id': '12345', 'email': 'user@example.com'})
"""
PII_PATTERNS = {
'user_id': r'"user_id"[:\s]*["\']?(\w+)["\']?',
'email': r'([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})',
'ip_address': r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b'
}
def __init__(self, log_dir: str, backup_dir: str = None):
self.log_dir = Path(log_dir)
self.backup_dir = Path(backup_dir) if backup_dir else self.log_dir / 'backups'
self.backup_dir.mkdir(exist_ok=True)
self.request_evidence = {} # Stores per-request evidence
def _load_logs(self, log_files: List[Path]) -> List[Dict[str, Any]]:
"""Load all log files into memory (use generators for large-scale)."""
all_logs = []
for file_path in log_files:
with open(file_path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
try:
entry = json.loads(line.strip())
entry['_file'] = str(file_path)
entry['_line'] = line_num
all_logs.append(entry)
except json.JSONDecodeError:
logger.warning(f"Invalid JSON at {file_path}:{line_num}")
return all_logs
def _search_identifiers(self, logs: List[Dict[str, Any]], identifiers: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Discover log entries matching ANY identifier."""
matches = []
for entry in logs:
entry_str = json.dumps(entry)
for key, value in identifiers.items():
if str(value) in entry_str or re.search(rf'{key}[:\s]*["\']?{re.escape(str(value))}', entry_str):
matches.append(entry)
break
return matches
def _redact_entry(self, entry: Dict[str, Any]) -> Dict[str, Any]:
"""Redact PII in a single log entry."""
entry_str = json.dumps(entry)
redacted_str = entry_str
for pii_type, pattern in self.PII_PATTERNS.items():
for match in re.finditer(pattern, entry_str):
pii_value = match.group(1) if match.groups() else match.group(0)
pii_hash = hashlib.sha256(pii_value.encode()).hexdigest()[:8]
redacted_token = f"[REDACTED-{pii_type}-{pii_hash}]"
redacted_str = redacted_str.replace(pii_value, redacted_token, 1) # Replace first occurrence per pattern
redacted_entry = json.loads(redacted_str)
redacted_entry['_redacted_at'] = datetime.utcnow().isoformat()
redacted_entry['_redacted_pii_types'] = list(self.PII_PATTERNS.keys())
return redacted_entry
def _backup_log_file(self, file_path: Path, request_id: str) -> Path:
"""Backup original log file before redaction."""
timestamp = datetime.utcnow().strftime('%Y%m%d_%H%M%S')
backup_path = self.backup_dir / f"{file_path.name}.{request_id}_{timestamp}.backup.jsonl"
backup_path.parent.mkdir(exist_ok=True)
backup_path.write_bytes(file_path.read_bytes())
return backup_path
def discover(self, request_id: str, identifiers: Dict[str, Any]) -> Dict[str, Any]:
"""
Step 1: DISCOVERY
Returns: {'matched_files': [...], 'matched_entries': [...], 'total_matches': int}
"""
log_files = list(self.log_dir.glob('*.jsonl')) + list(self.log_dir.glob('*.log'))
logger.info(f"[{request_id}] Discovering in {len(log_files)} files with identifiers: {identifiers}")
all_logs = self._load_logs(log_files)
matched_entries = self._search_identifiers(all_logs, identifiers)
evidence = {
'request_id': request_id,
'identifiers': identifiers,
'timestamp': datetime.utcnow().isoformat(),
'matched_files': list(set(e['_file'] for e in matched_entries)),
'matched_entries': matched_entries, # Before redaction snapshot
'total_matches': len(matched_entries)
}
self.request_evidence[request_id] = evidence
logger.info(f"[{request_id}] Found {len(matched_entries)} matching entries")
return evidence
def redact(self, request_id: str) -> Dict[str, Any]:
"""
Step 2: REDACTION
Modifies original log files in-place after backup.
Returns: Updated evidence with redacted_entries and backup_paths.
"""
if request_id not in self.request_evidence:
raise ValueError(f"No discovery evidence for request_id: {request_id}")
evidence = self.request_evidence[request_id]
matched_entries = evidence['matched_entries']
file_redactions = {} # file -> list of (line_num, original, redacted)
# Group by file and line for targeted rewrites
for entry in matched_entries:
file_path = Path(entry['_file'])
line_num = entry['_line']
# Backup file once per file
if file_path.name not in [p.name for p in evidence.get('backup_paths', [])]:
backup_path = self._backup_log_file(file_path, request_id)
evidence.setdefault('backup_paths', []).append(str(backup_path))
# Load file, redact specific line, rewrite
redacted_entry = self._redact_entry(entry)
file_redactions.setdefault(str(file_path), []).append((line_num, entry, redacted_entry))
# Apply redactions file-by-file
for file_path_str, redactions in file_redactions.items():
file_path = Path(file_path_str)
lines = file_path.read_text(encoding='utf-8').splitlines(keepends=True)
for line_num, orig_entry, redacted_entry in redactions:
lines[line_num - 1] = json.dumps(redacted_entry) + '\n' # 1-indexed
file_path.write_text(''.join(lines), encoding='utf-8')
logger.info(f"[{request_id}] Redacted {len(redactions)} entries in {file_path}")
evidence['redacted_entries'] = [r[2] for r in sum(file_redactions.values(), [])] # Snapshot
evidence['redaction_status'] = 'completed'
logger.info(f"[{request_id}] Redaction complete")
return evidence
def verify(self, request_id: str) -> Dict[str, Any]:
"""
Step 3: VERIFICATION EVIDENCE
Generates:
- Before/after diffs (simplified).
- Hashes of original backups vs redacted files.
- PII absence check in redacted files.
Returns: Full evidence dict with verification.
"""
if request_id not in self.request_evidence:
raise ValueError(f"No evidence for request_id: {request_id}")
evidence = self.request_evidence[request_id]
verification = {
'verification_timestamp': datetime.utcnow().isoformat(),
'file_hashes': {},
'pii_absence_check': True,
'diff_summary': []
}
# Hash comparisons
backup_paths = [Path(p) for p in evidence.get('backup_paths', [])]
redacted_files = list(self.log_dir.glob('*.jsonl')) # Assume same files
for backup_path in backup_paths:
orig_hash = hashlib.sha256(backup_path.read_bytes()).hexdigest()
redacted_file = self.log_dir / backup_path.name.replace('.backup.jsonl', '.jsonl')
if redacted_file.exists():
redacted_hash = hashlib.sha256(redacted_file.read_bytes()).hexdigest()
verification['file_hashes'][str(backup_path)] = {'original': orig_hash, 'redacted': redacted_hash}
verification['diff_summary'].append(f"{backup_path.name}: hashes differ ✓")
# Check no PII remains
redacted_content = redacted_file.read_text()
for pattern in self.PII_PATTERNS.values():
if re.search(pattern, redacted_content):
verification['pii_absence_check'] = False
break
evidence['verification'] = verification
evidence['status'] = 'verified' if verification['pii_absence_check'] else 'issues_found'
# Save evidence report
report_path = self.backup_dir / f"{request_id}_evidence.json"
report_path.write_text(json.dumps(evidence, indent=2))
logger.info(f"[{request_id}] Verification complete: {evidence['status']}")
return evidence
def process_request(self, request_id: str, identifiers: Dict[str, Any]) -> Dict[str, Any]:
"""Full workflow: discover -> redact -> verify."""
self.discover(request_id, identifiers)
self.redact(request_id)
return self.verify(request_id)
# Example Usage (for testing)
if __name__ == "__main__":
# Simulate logs dir with sample files
demo_dir = Path('demo_logs')
demo_dir.mkdir(exist_ok=True)
# Create sample log
sample_log = demo_dir / 'app.log.jsonl'
sample_entries = [
{'timestamp': '2023-01-01', 'user_id': '12345', 'email': 'user@example.com', 'action': 'login', 'ip': '192.168.1.1'},
{'timestamp': '2023-01-02', 'user_id': '67890', 'action': 'view'},
{'timestamp': '2023-01-03', 'user_id': '12345', 'email': 'user@example.com', 'action': 'logout'}
]
sample_log.write_text('\n'.join(json.dumps(e) for e in sample_entries) + '\n')
workflow = PrivacyRequestWorkflow(log_dir=str(demo_dir), backup_dir=str(demo_dir / 'backups'))
evidence = workflow.process_request('demo-req-001', {'user_id': '12345', 'email': 'user@example.com'})
print("Privacy Request Evidence:")
print(json.dumps(evidence, indent=2))
This workflow ensures provable privacy compliance. Query me for customizations, Sherlock. 🔍