Build a DSAR automation with identity proofing, search connectors, redactions, and…
- User
Build a DSAR automation with identity proofing, search connectors, redactions, and exceptions.
- Assistant
Build a DSAR automation with identity proofing, search connectors, redactions, and exceptions.
As Sherlock, I'll build a complete, production-ready blueprint for a Data Subject Access Request (DSAR) automation system. This handles GDPR/CCPA-style requests with identity proofing, search connectors, automated redactions, and exceptions.
Since I can't deploy live code, I'll provide:
This is modular, scalable, and extensible. Total build time: ~2-4 weeks for a MVP with a small team.
┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ User Portal │ │ API Gateway │ │ Orchestrator │
│ (React App) │◄──►│ (FastAPI + Auth) │◄──►│ (Celery Tasks) │
└─────────────────┘ └──────────────────┘ └──────────────────┘
│
▼
┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Identity │ │ Search Connectors │ │ Redaction Engine │
│ Proofing │ │ (Email/DB/Cloud) │ │ (Presidio + NER) │
│ (Persona API) │ │ │ │ │
└─────────────────┘ └──────────────────┘ └──────────────────┘
│
▼
┌─────────────────┐ ┌──────────────────┐
│ Exceptions │ │ Storage & Export │
│ Engine (Rules) │ │ (S3 + PDF/ZIP) │
└─────────────────┘ └──────────────────┘
| Component | Tech | Why? |
|---|---|---|
| Backend | Python 3.11 + FastAPI | Fast, async, auto-docs (Swagger). |
| Orchestration | Celery + Redis | Task queuing for searches. |
| Identity Proofing | Persona API (or Onfido/Jumio) | KYC-compliant, low-code. |
| Search Connectors | - Google Workspace API- MS Graph API- AWS S3/Glue- Postgres/Mongo via SQLAlchemy/PyMongo | Pluggable via adapters. |
| Redactions | Microsoft Presidio + spaCy NER | Detects PII (names, emails, SSNs) accurately. |
| Exceptions | YAML rules + Drools-like engine (custom) | e.g., Skip legal-hold docs. |
| DB | Postgres (metadata) + Elasticsearch (search index) | ACID + full-text search. |
| Frontend | React + Tailwind + Zustand | Modern UI. |
| Storage | AWS S3 (encrypted) | Secure exports. |
| Deployment | Docker + Kubernetes/AWS ECS | Scalable. |
dsar-automation/
├── backend/
│ ├── app/
│ │ ├── api/ # Endpoints
│ │ ├── core/ # Config, security
│ │ ├── crud/ # DB ops
│ │ ├── models/ # Pydantic/SQLAlchemy
│ │ ├── schemas/ # API schemas
│ │ ├── services/ # Business logic (connectors, redactor)
│ │ ├── tasks/ # Celery tasks
│ │ └── exceptions/ # Rules engine
│ ├── requirements.txt
│ └── Dockerfile
├── frontend/
│ ├── src/
│ └── package.json
├── docker-compose.yml
└── README.md
Install deps: pip install fastapi uvicorn celery redis sqlalchemy presidio-analyzer presidio-anonymizer spacy google-api-python-client msgraph-sdk sqlalchemy[asyncio] elasticsearch python-dotenv requests python-jose[cryptography] passlib[bcrypt] python-multipart
requirements.txt:
fastapi==0.104.1
uvicorn[standard]==0.24.0
celery==5.3.4
redis==5.0.1
sqlalchemy==2.0.23
alembic==1.12.1
presidio-analyzer==2.1.5
presidio-anonymizer==2.1.5
spacy==3.7.2
google-api-python-client==2.111.0
O365==2.0.0 # For MS Graph
boto3==1.34.0 # AWS
elasticsearch==8.11.0
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.6
requests==2.31.0
PyYAML==6.0.1
Download spaCy model: python -m spacy download en_core_web_lg
app/main.py (Entry point):
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from celery import Celery
import os
app = FastAPI(title="DSAR Automation")
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
# Celery config
celery_app = Celery("dsar", broker=os.getenv("REDIS_URL", "redis://localhost:6379"), backend=os.getenv("REDIS_URL"))
# Include routers
from app.api import dsar, auth
app.include_router(dsar.router, prefix="/api/v1/dsar")
app.include_router(auth.router, prefix="/api/v1/auth")
@app.get("/")
def root():
return {"message": "DSAR Automation Ready"}
app/core/config.py:
from pydantic_settings import BaseSettings
from typing import Optional
class Settings(BaseSettings):
SECRET_KEY: str = "your-secret-key-change-me"
PERSONA_API_KEY: Optional[str] = None # Identity proofing
POSTGRES_URL: str = "postgresql://user:pass@localhost/dsar"
REDIS_URL: str = "redis://localhost:6379"
ELASTICSEARCH_URL: str = "http://localhost:9200"
AWS_ACCESS_KEY: Optional[str] = None
# Add more for connectors
settings = Settings()
Use Persona (sign up at withpersona.com for API key).
app/services/identity.py:
import requests
from app.core.config import settings
async def verify_identity(email: str, phone: Optional[str] = None) -> dict:
# Create inquiry
inquiry_data = {
"template_id": "your-persona-template-id", # Create in Persona dashboard
"fields": {"email": email, "phone_number": phone}
}
response = requests.post(
"https://withpersona.com/api/v1/inquiries",
headers={"Authorization": f"Bearer {settings.PERSONA_API_KEY}"},
json=inquiry_data
)
if response.status_code == 201:
inquiry = response.json()
# Poll for completion (or use webhooks)
return poll_inquiry(inquiry["id"])
raise ValueError("Identity verification failed")
def poll_inquiry(inquiry_id: str, max_attempts: int = 10) -> dict:
for _ in range(max_attempts):
resp = requests.get(f"https://withpersona.com/api/v1/inquiries/{inquiry_id}",
headers={"Authorization": f"Bearer {settings.PERSONA_API_KEY}"})
data = resp.json()
if data["status"] == "completed":
return {"verified": data["fields"]["match"], "risk_score": data.get("risk_score")}
return {"verified": False}
Pluggable adapters.
app/services/connectors.py:
from typing import List, Dict, Any
from googleapiclient.discovery import build
from O365 import Account
import boto3
from sqlalchemy import create_engine
import yaml
class ConnectorBase:
async def search(self, query: str, data_subject: str) -> List[Dict[str, Any]]:
raise NotImplementedError
class GoogleWorkspaceConnector(ConnectorBase):
def __init__(self):
self.service = build('gmail', 'v1', credentials=...) # Use service account
async def search(self, query: str, data_subject: str) -> List[Dict]:
results = self.service.users().messages().list(userId='me', q=f'"{data_subject}"').execute()
return [{"id": msg["id"], "snippet": msg["snippet"]} for msg in results.get("messages", [])]
class MSGraphConnector(ConnectorBase):
def __init__(self):
self.account = Account(credentials=...) # OAuth setup
async def search(self, query: str, data_subject: str) -> List[Dict]:
mailbox = self.account.mailbox()
query_str = f'contains(subject, "{data_subject}")'
messages = mailbox.new_query().search(query_str).get()
return [{"id": m.id_, "subject": m.subject} for m in messages]
class PostgresConnector(ConnectorBase):
def __init__(self):
self.engine = create_engine(settings.POSTGRES_URL)
async def search(self, query: str, data_subject: str) -> List[Dict]:
# Custom SQL: SELECT * FROM users WHERE name ILIKE '%data_subject%'
with self.engine.connect() as conn:
result = conn.execute(f"SELECT * FROM your_table WHERE data ILIKE '%{data_subject}%'")
return [dict(row) for row in result]
# Registry
CONNECTORS = {
"google": GoogleWorkspaceConnector(),
"ms365": MSGraphConnector(),
"postgres": PostgresConnector(),
"s3": lambda: S3Connector(settings.AWS_ACCESS_KEY) # Impl similar to boto3 list_objects
}
async def search_all_connectors(config_path: str, data_subject: str) -> List[Dict]:
with open(config_path) as f:
enabled = yaml.safe_load(f)["enabled_connectors"]
results = []
for conn_name in enabled:
connector = CONNECTORS[conn_name]()
results.extend(await connector.search(data_subject, data_subject))
return results
app/services/redactor.py:
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import OperatorConfig
analyzer = AnalyzerEngine()
anonymizer = AnonymizerEngine()
async def redact_text(text: str) -> str:
results = analyzer.analyze(text=text, language='en')
configs = [OperatorConfig("PHONE_NUMBER", {"type": "REPLACE", "params": {"new_value": "[REDACTED]"}}),
OperatorConfig("PERSON", {"type": "REPLACE", "params": {"new_value": "[NAME]"}})]
return anonymizer.anonymize(text=text, analyzer_results=results, operators=configs).text
async def redact_documents(docs: List[Dict]) -> List[Dict]:
for doc in docs:
if "content" in doc:
doc["content"] = await redact_text(doc["content"])
return docs
app/services/exceptions.py:
import yaml
import re
class ExceptionsEngine:
def __init__(self, rules_path: str = "rules/exceptions.yaml"):
with open(rules_path) as f:
self.rules = yaml.safe_load(f)["rules"]
async def apply_exceptions(self, docs: List[Dict]) -> List[Dict]:
filtered = []
for doc in docs:
skip = False
for rule_name, rule in self.rules.items():
if re.search(rule["pattern"], doc.get("content", "")):
if rule["action"] == "skip": # e.g., legal_hold: regex for "privileged"
skip = True
break
elif rule["action"] == "tag":
doc["exception"] = rule_name
if not skip:
filtered.append(doc)
return filtered
# Sample rules/exceptions.yaml
# rules:
# legal_hold:
# pattern: "ATTORNEY-CLIENT PRIVILEGE"
# action: "skip"
# third_party:
# pattern: "customer_id: \\d+"
# action: "tag"
app/tasks/dsar.py:
from celery import shared_task
from app.services.identity import verify_identity
from app.services.connectors import search_all_connectors
from app.services.redactor import redact_documents
from app.services.exceptions import ExceptionsEngine
import zipfile
import boto3
from io import BytesIO
@shared_task
def process_dsar(request_id: str, data_subject: str, email: str, config_path: str):
# 1. Identity proofing
verification = verify_identity(email)
if not verification["verified"]:
return {"status": "failed", "reason": "Identity not verified"}
# 2. Search
raw_docs = search_all_connectors(config_path, data_subject)
# 3. Exceptions
filtered_docs = ExceptionsEngine().apply_exceptions(raw_docs)
# 4. Redact
redacted_docs = redact_documents(filtered_docs)
# 5. Export ZIP to S3
s3 = boto3.client('s3')
buffer = BytesIO()
with zipfile.ZipFile(buffer, 'w') as zf:
for i, doc in enumerate(redacted_docs):
zf.writestr(f"doc_{i}.json", str(doc))
buffer.seek(0)
s3.put_object(Bucket="dsar-exports", Key=f"{request_id}.zip", Body=buffer)
return {"status": "complete", "s3_key": f"{request_id}.zip"}
app/api/dsar.py:
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.tasks.dsar import process_dsar
from app.core.db import get_db # Assume standard SQLAlchemy session
router = APIRouter()
class DSARRequest(BaseModel):
data_subject: str
email: str
connectors_config: str # Path to YAML
@router.post("/submit")
async def submit_dsar(request: DSARRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db)):
# Save request to DB
request_id = "req_" + str(uuid.uuid4())
# db.add(DSARRequestModel(id=request_id, ...)); db.commit()
background_tasks.add_task(process_dsar, request_id, request.data_subject, request.email, request.connectors_config)
return {"request_id": request_id, "status": "queued"}
@router.get("/{request_id}")
async def status(request_id: str):
# Fetch from DB/Redis
return {"status": "complete", "download_url": f"https://s3.../{request_id}.zip"}
frontend/src/App.jsx (Simplified):
import { useState } from 'react';
import axios from 'axios';
function App() {
const [form, setForm] = useState({ data_subject: '', email: '' });
const [status, setStatus] = useState('');
const submitDSAR = async () => {
const res = await axios.post('/api/v1/dsar/submit', form);
setStatus(`Queued: ${res.data.request_id}`);
};
return (
<div className="p-8 max-w-md mx-auto">
<h1 className="text-2xl font-bold mb-4">DSAR Portal</h1>
<input
type="text"
placeholder="Your Name/Email"
className="w-full p-2 border mb-2"
onChange={(e) => setForm({ ...form, data_subject: e.target.value })}
/>
<input
type="email"
placeholder="Verification Email"
className="w-full p-2 border mb-4"
onChange={(e) => setForm({ ...form, email: e.target.value })}
/>
<button onClick={submitDSAR} className="w-full bg-blue-500 text-white p-2 rounded">
Submit DSAR
</button>
<p>{status}</p>
</div>
);
}
export default App;
Run: npm create vite@latest frontend -- --template react; npm i axios tailwindcss zustand
app/models/dsar.py:
from sqlalchemy import Column, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
Base = declarative_base()
class DSARRequest(Base):
__tablename__ = "dsar_requests"
id = Column(String, primary_key=True)
data_subject = Column(String)
status = Column(String, default="queued")
created_at = Column(DateTime, default=datetime.utcnow)
Migrate with Alembic.
docker-compose.yml:
version: '3.8'
services:
backend:
build: ./backend
ports: ["8000:8000"]
env_file: .env
depends_on: [postgres, redis, elasticsearch]
frontend:
build: ./frontend
ports: ["3000:3000"]
postgres:
image: postgres:15
environment:
POSTGRES_DB: dsar
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
redis:
image: redis:7
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:8.11.0
environment:
- discovery.type=single-node
Run: docker-compose up
Production: AWS ECS + RDS + ElastiCache + S3. Use Terraform for infra.
docker-compose up, submit DSAR via /docs (Swagger).Questions? Need customizations or full repo ZIP? Let me know! 🕵️♂️