import argparse
import asyncio
import json
import re
import time
from pathlib import Path
from typing import Any, Dict, Optional
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from prometheus_client import Counter, Histogram, make_asgi_app
import uvicorn
from faker import Faker
fake = Faker()
# Metrics
mirror_requests = Counter(
'traffic_mirror_requests_total', 'Total requests mirrored', ['method', 'status']
)
mirror_latency = Histogram('traffic_mirror_latency_seconds', 'Mirror latency')
recorded_requests = Counter('traffic_recorded_requests_total', 'Recorded requests')
replayed_requests = Counter('traffic_replay_requests_total', 'Replayed requests', ['status'])
# Globals
MIRROR_HOST: str = "http://mirror.example.com:8080"
record_file: Optional[Path] = None
# PII scrubbing config
PII_KEYS = [
"email", "phone", "phonenumber", "phoneNumber", "ssn", "name", "firstname", "lastname",
"address", "creditcard", "creditCard", "ip", "ipaddress", "userId", "ssn"
]
PII_PATTERNS = [
(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', lambda: fake.email()),
(r'\b\d{3}[-.]?\d{2}[-.]?\d{4}\b', lambda: fake.ssn()),
(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', lambda: fake.phone_number()),
(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b', lambda: fake.ipv4()),
]
def scrub_json(data: Any, path: str) -> Any:
"""Scrub PII in JSON by key names and apply transforms."""
if isinstance(data, dict):
new_data = {}
for k, v in data.items():
scrubbed_k = k
if any(pii.lower() in k.lower() for pii in PII_KEYS):
scrubbed_k = f"[PII_REDACTED_{k.upper()}]"
new_data[scrubbed_k] = scrub_json(v, path)
data = new_data
elif isinstance(data, list):
data = [scrub_json(item, path) for item in data]
# Payload transforms (example: configurable per path)
if isinstance(data, dict):
if "/users" in path:
data["age"] = 18 # Transform example
if "amount" in data:
data["amount"] = 0.01 # Another transform
return data
def scrub_text(text: str) -> str:
"""Regex-based PII scrubbing for non-JSON."""
for pattern, repl_func in PII_PATTERNS:
def replacer(match):
return repl_func()
text = re.sub(pattern, replacer, text, flags=re.IGNORECASE)
return text
def scrub_body(body: bytes, content_type: str, path: str) -> bytes:
if not body:
return body
text = body.decode('utf-8', errors='ignore')
try:
if 'application/json' in content_type.lower():
data = json.loads(text)
scrubbed_data = scrub_json(data, path)
return json.dumps(scrubbed_data, ensure_ascii=False).encode('utf-8')
except json.JSONDecodeError:
pass
# Fallback to text scrubbing
scrubbed_text = scrub_text(text)
return scrubbed_text.encode('utf-8')
# FastAPI Proxy App
proxy_app = FastAPI(title="Traffic Mirroring Harness Proxy")
proxy_app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
# Prometheus metrics endpoint
prometheus_app = make_asgi_app()
proxy_app.mount("/metrics", prometheus_app)
@proxy_app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
async def mirror_proxy(request: Request, full_path: str):
host = request.headers.get("host", "localhost")
orig_url = f"http://{host}{request.url.path}"
if request.url.query:
orig_url += f"?{request.url.query}"
# Prepare headers (remove proxy-specific)
headers = {k: v for k, v in request.headers.items() if k.lower() not in ("host", "content-length")}
content_type = headers.get("content-type", "")
body = await request.body()
scrubbed_body = scrub_body(body, content_type, str(request.url.path))
# Mirror URL
mirror_url = f"{MIRROR_HOST.rstrip('/')}{request.url.path}"
if request.url.query:
mirror_url += f"?{request.url.query}"
mirror_headers = headers.copy()
mirror_headers["X-Mirrored-By"] = "traffic-harness"
async with httpx.AsyncClient(timeout=httpx.Timeout(30.0)) as client:
# Forward to original (stream response)
orig_req = client.build_request(
request.method, orig_url, headers=headers, content=body
)
orig_resp = await client.send(orig_req, stream=True)
# Fire-and-forget mirror in background
async def background_mirror():
mirror_start = time.time()
try:
mirror_req = client.build_request(
request.method, mirror_url, headers=mirror_headers, content=scrubbed_body
)
mresp = await client.send(mirror_req)
latency = time.time() - mirror_start
mirror_latency.observe(latency)
mirror_requests.labels(method=request.method, status=mresp.status_code).inc()
# Record scrubbed flow
if record_file:
flow = {
"timestamp": time.time(),
"method": request.method,
"path": request.url.path,
"query": request.url.query or "",
"headers": {k: v for k, v in mirror_headers.items() if k.lower() not in ("host", "authorization")},
"body": scrubbed_body.decode('utf-8', errors='ignore'),
"content_type": content_type,
}
with record_file.open("a", encoding="utf-8") as f:
f.write(json.dumps(flow) + "\n")
recorded_requests.inc()
except Exception:
mirror_requests.labels(method=request.method, status="error").inc()
asyncio.create_task(background_mirror())
# Stream original response back
return StreamingResponse(
orig_resp.aiter_bytes(),
status_code=orig_resp.status_code,
headers=dict(orig_resp.headers),
)
async def replay_record(record_path: Path, replay_target: str, dry_run: bool, limit: Optional[int], concurrency: int, yes: bool):
"""Replay recorded traffic safely."""
if not yes:
confirm = input(f"Are you sure you want to replay {record_path.read_text().count('\n')} flows to {replay_target} (y/N)? ")
if confirm.lower() != 'y':
print("Replay aborted for safety.")
return
if dry_run:
print("=== DRY-RUN MODE: No requests will be sent ===")
flows = []
with open(record_path, encoding="utf-8") as f:
for line_num, line in enumerate(f, 1):
if line.strip():
try:
flows.append(json.loads(line))
except json.JSONDecodeError:
print(f"Skipping invalid JSON at line {line_num}")
continue
if limit and len(flows) >= limit:
break
print(f"Loaded {len(flows)} flows for replay.")
semaphore = asyncio.Semaphore(concurrency)
async def send_one(flow: Dict[str, Any]):
async with semaphore:
replay_url = f"{replay_target.rstrip('/')}{flow['path']}"
if flow['query']:
replay_url += f"?{flow['query']}"
body_bytes = flow['body'].encode('utf-8') if flow['body'] else None
if dry_run:
print(f"DRY-RUN: {flow['method']} {replay_url}")
return
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(10.0)) as client:
resp = await client.send(
flow['method'],
replay_url,
headers=flow['headers'],
content=body_bytes,
)
print(f"Replayed [{flow['method']}] {replay_url} -> {resp.status_code}")
replayed_requests.labels(status=resp.status_code).inc()
except Exception as e:
print(f"Replay error [{flow['method']}] {replay_url}: {e}")
replayed_requests.labels(status="error").inc()
start = time.time()
await asyncio.gather(*(send_one(flow) for flow in flows))
print(f"Replay complete: {len(flows)} requests in {time.time() - start:.2f}s")
def main():
global MIRROR_HOST, record_file
parser = argparse.ArgumentParser(description="Traffic Mirroring Harness with PII Scrubbing")
parser.add_argument("--mirror-host", default="http://localhost:9000", help="Mirror service base URL")
subparsers = parser.add_subparsers(dest="mode", required=True)
# Proxy mode
proxy_parser = subparsers.add_parser("proxy", help="Run HTTP proxy with mirroring")
proxy_parser.add_argument("--port", type=int, default=8000, help="Proxy listen port")
proxy_parser.add_argument("--record-to", type=Path, help="Record scrubbed flows to JSONL file")
# Replay mode
replay_parser = subparsers.add_parser("replay", help="Replay recorded traffic")
replay_parser.add_argument("record_file", type=Path, help="JSONL record file")
replay_parser.add_argument("--target", required=True, help="Target base URL for replay")
replay_parser.add_argument("--dry-run", action="store_true", help="Dry-run (print without sending)")
replay_parser.add_argument("--limit", type=int, default=0, help="Max flows to replay (0=all)")
replay_parser.add_argument("--concurrency", type=int, default=10, help="Concurrent replays")
replay_parser.add_argument("--yes", action="store_true", help="Skip confirmation (unsafe!)")
args = parser.parse_args()
MIRROR_HOST = args.mirror_host
if args.mode == "proxy":
if args.record_to:
args.record_to.parent.mkdir(parents=True, exist_ok=True)
record_file = args.record_to
print(f"Recording scrubbed traffic to {record_file}")
print(f"Starting proxy on :{args.port} | Original from Host header | Mirror: {MIRROR_HOST}")
print("Set your client proxy to http://localhost:{args.port}")
uvicorn.run(proxy_app, host="0.0.0.0", port=args.port, log_level="info")
elif args.mode == "replay":
asyncio.run(replay_record(
args.record_file, args.target, args.dry_run, args.limit, args.concurrency, args.yes
))
if __name__ == "__main__":
main()
Usage Instructions
-
Install dependencies:
pip install fastapi uvicorn httpx faker prometheus-client
-
Proxy/Mirroring Mode (live traffic capture, scrub, mirror, optional record):
python traffic_harness.py proxy --port 8000 --mirror-host http://mirror-api:8080 --record-to traffic.jsonl
- Configure your client/app to use proxy
http://localhost:8000.
- Requests go to original (via
Host header), scrubbed/transformed mirrored async to --mirror-host.
- PII scrubbed (JSON keys + regex), payloads transformed (e.g., age=18, amount=0.01).
- Metrics at
http://localhost:8000/metrics.
- Records scrubbed requests to JSONL if
--record-to.
-
Replay Mode (safe replay of recorded traffic):
python traffic_harness.py replay traffic.jsonl --target http://test-api:8080 --dry-run
# or with confirmation
python traffic_harness.py replay traffic.jsonl --target http://test-api:8080 --limit 100 --yes
- Safety: Confirmation prompt unless
--yes. --dry-run previews without sending.
- Replays scrubbed/transformed payloads to
--target.
- Concurrency-controlled, timeouts, error-resilient.
- Prints stats; Prometheus counters updated.
Features
- PII Scrubbing: Key-based (JSON) + regex (text/HTML/etc.) with Faker anonymization.
- Payload Transforms: Path/key-based mutations (extensible in
apply_transforms).
- Replay Safety: Dry-run, confirmation, limits, concurrency control.
- Metrics: Prometheus-ready (requests, latency, errors, recorded/replayed).
- Production-Ready: Async, streaming responses (no blocking), configurable, fault-tolerant.
Extend PII_KEYS, PII_PATTERNS, scrub_json transforms as needed. Self-contained!