llm-shield-proxy 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
app/__init__.py ADDED
@@ -0,0 +1 @@
1
+ # LLM-Shield Package
app/audit.py ADDED
@@ -0,0 +1,64 @@
1
+ import json
2
+ import logging
3
+ import sys
4
+ from datetime import datetime, timezone
5
+ from typing import Dict, List, Optional, Any
6
+
7
+ # Configure structured audit logger for enterprise SOC 2 / HIPAA compliance
8
+ audit_logger = logging.getLogger("llm_shield.audit")
9
+ audit_logger.setLevel(logging.INFO)
10
+
11
+ if not audit_logger.handlers:
12
+ handler = logging.StreamHandler(sys.stdout)
13
+ handler.setFormatter(logging.Formatter('%(message)s'))
14
+ audit_logger.addHandler(handler)
15
+
16
+
17
+ class AuditLogger:
18
+ """
19
+ Enterprise Structured Audit Logger for SOC 2 / HIPAA Compliance.
20
+ Logs metadata about redaction events without ever leaking raw PII.
21
+ """
22
+
23
+ @staticmethod
24
+ def log_redaction_event(
25
+ session_id: Optional[str],
26
+ entity_counts: Dict[str, int],
27
+ path: str,
28
+ status_code: int = 200
29
+ ):
30
+ """
31
+ Emits a structured JSON audit log event recording entity redaction counts.
32
+ """
33
+ log_entry: Dict[str, Any] = {
34
+ "timestamp": datetime.now(timezone.utc).isoformat(),
35
+ "event": "PII_REDACTION_EVENT",
36
+ "service": "LLM-Shield",
37
+ "session_id": session_id or "ephemeral",
38
+ "path": path,
39
+ "status_code": status_code,
40
+ "total_entities_redacted": sum(entity_counts.values()),
41
+ "entity_breakdown": entity_counts,
42
+ }
43
+ audit_logger.info(json.dumps(log_entry))
44
+
45
+ @staticmethod
46
+ def log_proxy_event(
47
+ session_id: Optional[str],
48
+ path: str,
49
+ method: str,
50
+ status_code: int = 200
51
+ ):
52
+ """
53
+ Emits a structured JSON audit log event for incoming proxy traffic.
54
+ """
55
+ log_entry: Dict[str, Any] = {
56
+ "timestamp": datetime.now(timezone.utc).isoformat(),
57
+ "event": "PROXY_TRAFFIC_EVENT",
58
+ "service": "LLM-Shield",
59
+ "session_id": session_id or "ephemeral",
60
+ "path": path,
61
+ "method": method,
62
+ "status_code": status_code
63
+ }
64
+ audit_logger.info(json.dumps(log_entry))
app/config.py ADDED
@@ -0,0 +1,24 @@
1
+ import os
2
+ from typing import Optional
3
+ from pydantic_settings import BaseSettings, SettingsConfigDict
4
+
5
+
6
+ class Settings(BaseSettings):
7
+ UPSTREAM_BASE_URL: str = "https://api.openai.com"
8
+ OPENAI_API_KEY: Optional[str] = None
9
+ REDIS_URL: Optional[str] = None
10
+ SESSION_TTL_SECONDS: int = 3600
11
+
12
+ # Telemetry: Strictly Opt-In (Bring Your Own Database)
13
+ TELEMETRY_ENABLED: bool = False
14
+ TELEMETRY_ENDPOINT_URL: Optional[str] = None
15
+ TELEMETRY_API_KEY: Optional[str] = None
16
+
17
+ model_config = SettingsConfigDict(
18
+ env_file=".env",
19
+ env_file_encoding="utf-8",
20
+ extra="ignore"
21
+ )
22
+
23
+
24
+ settings = Settings()
app/main.py ADDED
@@ -0,0 +1,176 @@
1
+ import json
2
+ from contextlib import asynccontextmanager
3
+ from typing import Optional
4
+
5
+ import httpx
6
+ from fastapi import FastAPI, Request, Response, Header
7
+ from fastapi.responses import StreamingResponse, JSONResponse
8
+
9
+ from app.config import settings
10
+ from app.vault import vault_store
11
+ from app.pii_engine import pii_engine
12
+ from app.streaming import rehydrate_sse_stream
13
+ from app.telemetry import telemetry_tracker
14
+ from app.audit import AuditLogger
15
+
16
+
17
+ @asynccontextmanager
18
+ async def lifespan(app: FastAPI):
19
+ app.state.http_client = httpx.AsyncClient(timeout=120.0)
20
+ telemetry_tracker.start()
21
+ yield
22
+ telemetry_tracker.stop()
23
+ await app.state.http_client.aclose()
24
+
25
+
26
+ app = FastAPI(
27
+ title="LLM-Shield Proxy",
28
+ description="Enterprise Zero-Egress Privacy Redaction Middleware Proxy",
29
+ version="1.0.0",
30
+ lifespan=lifespan
31
+ )
32
+
33
+
34
+ def get_http_client(request: Request) -> httpx.AsyncClient:
35
+ if not hasattr(request.app.state, "http_client") or request.app.state.http_client is None:
36
+ request.app.state.http_client = httpx.AsyncClient(timeout=120.0)
37
+ return request.app.state.http_client
38
+
39
+
40
+ def build_target_url(upstream_base: str, path: str) -> str:
41
+ base = upstream_base.rstrip("/")
42
+ p = path.lstrip("/")
43
+ if base.endswith("/v1") and p.startswith("v1/"):
44
+ p = p[3:]
45
+ return f"{base}/{p}"
46
+
47
+
48
+ @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
49
+ async def proxy_catch_all(
50
+ request: Request,
51
+ path: str,
52
+ x_session_id: Optional[str] = Header(None, alias="X-Session-ID"),
53
+ x_upstream_base_url: Optional[str] = Header(None, alias="X-Upstream-Base-Url")
54
+ ):
55
+ upstream_base = x_upstream_base_url or settings.UPSTREAM_BASE_URL
56
+ target_url = build_target_url(upstream_base, path)
57
+
58
+
59
+ # Prepare forwarding headers (strip hop-by-hop and compression headers)
60
+ headers = dict(request.headers)
61
+ headers.pop("host", None)
62
+ headers.pop("content-length", None)
63
+ headers.pop("accept-encoding", None)
64
+
65
+ if settings.OPENAI_API_KEY:
66
+ headers["authorization"] = f"Bearer {settings.OPENAI_API_KEY}"
67
+
68
+ vault = vault_store.get_vault(x_session_id)
69
+ http_client: httpx.AsyncClient = get_http_client(request)
70
+
71
+ telemetry_tracker.increment_active()
72
+ try:
73
+ if request.method == "POST":
74
+ try:
75
+ body_bytes = await request.body()
76
+ payload = json.loads(body_bytes.decode("utf-8")) if body_bytes else {}
77
+ except Exception:
78
+ payload = {}
79
+
80
+ if isinstance(payload, dict):
81
+ is_streaming = payload.get("stream", False)
82
+ redacted_payload = pii_engine.redact_payload(payload, vault)
83
+ redacted_bytes = json.dumps(redacted_payload).encode("utf-8")
84
+
85
+ redaction_count = sum(vault.type_counters.values())
86
+ telemetry_tracker.record_request(redaction_count)
87
+ AuditLogger.log_redaction_event(x_session_id, vault.type_counters, path)
88
+
89
+ if is_streaming:
90
+ req = http_client.build_request(
91
+ method=request.method,
92
+ url=target_url,
93
+ headers=headers,
94
+ content=redacted_bytes
95
+ )
96
+ upstream_res = await http_client.send(req, stream=True)
97
+
98
+ res_headers = dict(upstream_res.headers)
99
+ res_headers.pop("content-encoding", None)
100
+ res_headers.pop("content-length", None)
101
+ res_headers.pop("transfer-encoding", None)
102
+
103
+ if upstream_res.status_code >= 400:
104
+ err_content = await upstream_res.aread()
105
+ await upstream_res.aclose()
106
+ return Response(
107
+ content=err_content,
108
+ status_code=upstream_res.status_code,
109
+ headers=res_headers,
110
+ media_type=res_headers.get("content-type", "application/json")
111
+ )
112
+
113
+ return StreamingResponse(
114
+ rehydrate_sse_stream(upstream_res.aiter_bytes(), vault),
115
+ status_code=upstream_res.status_code,
116
+ headers=res_headers,
117
+ media_type="text/event-stream"
118
+ )
119
+ else:
120
+ upstream_res = await http_client.request(
121
+ method=request.method,
122
+ url=target_url,
123
+ headers=headers,
124
+ content=redacted_bytes
125
+ )
126
+ res_headers = dict(upstream_res.headers)
127
+ res_headers.pop("content-encoding", None)
128
+ res_headers.pop("content-length", None)
129
+ res_headers.pop("transfer-encoding", None)
130
+
131
+ try:
132
+ res_json = upstream_res.json()
133
+ rehydrated_res = _rehydrate_json_response(res_json, vault)
134
+ return JSONResponse(content=rehydrated_res, status_code=upstream_res.status_code, headers=res_headers)
135
+ except Exception:
136
+ return Response(
137
+ content=vault.rehydrate(upstream_res.text),
138
+ status_code=upstream_res.status_code,
139
+ headers=res_headers
140
+ )
141
+
142
+
143
+ # For non-POST or pass-through requests
144
+ AuditLogger.log_proxy_event(x_session_id, path, request.method)
145
+ body_bytes = await request.body()
146
+ upstream_res = await http_client.request(
147
+ method=request.method,
148
+ url=target_url,
149
+ headers=headers,
150
+ content=body_bytes
151
+ )
152
+ return Response(
153
+ content=upstream_res.content,
154
+ status_code=upstream_res.status_code,
155
+ headers=dict(upstream_res.headers)
156
+ )
157
+ finally:
158
+ telemetry_tracker.decrement_active()
159
+
160
+
161
+ def _rehydrate_json_response(res_json: dict, vault) -> dict:
162
+ if not isinstance(res_json, dict):
163
+ return res_json
164
+
165
+ res_copy = res_json.copy()
166
+ if "choices" in res_copy and isinstance(res_copy["choices"], list):
167
+ for choice in res_copy["choices"]:
168
+ if isinstance(choice, dict):
169
+ message = choice.get("message", {})
170
+ if isinstance(message, dict) and "content" in message and isinstance(message["content"], str):
171
+ message["content"] = vault.rehydrate(message["content"])
172
+ delta = choice.get("delta", {})
173
+ if isinstance(delta, dict) and "content" in delta and isinstance(delta["content"], str):
174
+ delta["content"] = vault.rehydrate(delta["content"])
175
+
176
+ return res_copy
app/pii_engine.py ADDED
@@ -0,0 +1,129 @@
1
+ import re
2
+ from typing import List, Tuple, Optional
3
+ from app.vault import Vault
4
+
5
+ # Tier 1 Compiled Regex Patterns
6
+ TIER1_PATTERNS = [
7
+ ("EMAIL", re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b')),
8
+ ("SSN", re.compile(r'\b\d{3}-\d{2}-\d{4}\b')),
9
+ ("PHONE", re.compile(r'\b(?:\+?\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?(?:\d{3}[-.\s]?)?\d{4}\b')),
10
+
11
+ ("CREDIT_CARD", re.compile(r'\b(?:\d[ -]*?){13,16}\b')),
12
+ ("IP_ADDRESS", re.compile(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b')),
13
+ ("API_KEY", re.compile(r'\b(?:sk-[a-zA-Z0-9]{32,48}|AKIA[0-9A-Z]{16})\b')),
14
+ ]
15
+
16
+ # Tier 2 NER Pattern Rules (Names, Titles, Locations)
17
+ TIER2_PATTERNS = [
18
+ ("PERSON", re.compile(r'\b(?:Mr\.|Mrs\.|Ms\.|Dr\.|Prof\.)?\s*[A-Z][a-z]+\s+[A-Z][a-z]+\b')),
19
+ ]
20
+
21
+
22
+
23
+ class PIIEngine:
24
+ """
25
+ Two-Tier Cascade PII Redaction Engine:
26
+ - Tier 1: Microsecond compiled regex for structured secrets & numbers.
27
+ - Tier 2: Millisecond NER rules / ONNX model for unstructured names/orgs.
28
+ """
29
+ def __init__(self, enable_tier2: bool = True):
30
+ self.enable_tier2 = enable_tier2
31
+ self._onnx_session = None
32
+ self._init_onnx_model()
33
+
34
+ def _init_onnx_model(self):
35
+ """
36
+ Attempts to load an ONNX runtime session if model file is present.
37
+ Falls back gracefully to rule-based Tier 2 NER if ONNX runtime model is not loaded.
38
+ """
39
+ try:
40
+ import onnxruntime as ort
41
+ # Optional ONNX INT8 BERT-NER model path initialization can go here
42
+ self._onnx_session = None
43
+ except Exception:
44
+ self._onnx_session = None
45
+
46
+ def detect_spans(self, text: str) -> List[Tuple[int, int, str, str]]:
47
+ """
48
+ Detects all PII spans in the input text.
49
+ Returns a list of tuples: (start_index, end_index, entity_type, matched_text)
50
+ """
51
+ spans: List[Tuple[int, int, str, str]] = []
52
+
53
+ # Tier 1 Regex Scanning
54
+ for entity_type, pattern in TIER1_PATTERNS:
55
+ for match in pattern.finditer(text):
56
+ spans.append((match.start(), match.end(), entity_type, match.group(0)))
57
+
58
+ # Tier 2 NER Scanning
59
+ if self.enable_tier2:
60
+ for entity_type, pattern in TIER2_PATTERNS:
61
+ for match in pattern.finditer(text):
62
+ spans.append((match.start(), match.end(), entity_type, match.group(0)))
63
+
64
+ # Remove overlapping spans (prioritizing longer/earlier spans)
65
+ spans.sort(key=lambda s: (s[0], -(s[1] - s[0])))
66
+ non_overlapping: List[Tuple[int, int, str, str]] = []
67
+ last_end = -1
68
+
69
+ for span in spans:
70
+ start, end, entity_type, matched_text = span
71
+ if start >= last_end:
72
+ non_overlapping.append(span)
73
+ last_end = end
74
+
75
+ return non_overlapping
76
+
77
+ def redact_text(self, text: str, vault: Vault) -> str:
78
+ """
79
+ Redacts PII spans in text and registers deterministic tokens in the Vault.
80
+ """
81
+ if not text:
82
+ return text
83
+
84
+ spans = self.detect_spans(text)
85
+ if not spans:
86
+ return text
87
+
88
+ # Rebuild string from right to left to keep indices accurate
89
+ result = list(text)
90
+ for start, end, entity_type, matched_text in reversed(spans):
91
+ token = vault.get_or_create_token(matched_text, entity_type)
92
+ result[start:end] = list(token)
93
+
94
+ return "".join(result)
95
+
96
+ def redact_payload(self, payload: dict, vault: Vault) -> dict:
97
+ """
98
+ Recursively traverses OpenAI payload structure (e.g. messages array)
99
+ and redacts PII in string content fields.
100
+ """
101
+ if not isinstance(payload, dict):
102
+ return payload
103
+
104
+ new_payload = payload.copy()
105
+ if "messages" in new_payload and isinstance(new_payload["messages"], list):
106
+ redacted_messages = []
107
+ for msg in new_payload["messages"]:
108
+ if isinstance(msg, dict):
109
+ msg_copy = msg.copy()
110
+ if "content" in msg_copy and isinstance(msg_copy["content"], str):
111
+ msg_copy["content"] = self.redact_text(msg_copy["content"], vault)
112
+ redacted_messages.append(msg_copy)
113
+ else:
114
+ redacted_messages.append(msg)
115
+ new_payload["messages"] = redacted_messages
116
+
117
+ if "prompt" in new_payload:
118
+ if isinstance(new_payload["prompt"], str):
119
+ new_payload["prompt"] = self.redact_text(new_payload["prompt"], vault)
120
+ elif isinstance(new_payload["prompt"], list):
121
+ new_payload["prompt"] = [
122
+ self.redact_text(p, vault) if isinstance(p, str) else p
123
+ for p in new_payload["prompt"]
124
+ ]
125
+
126
+ return new_payload
127
+
128
+
129
+ pii_engine = PIIEngine()
app/streaming.py ADDED
@@ -0,0 +1,97 @@
1
+ import json
2
+ from typing import AsyncGenerator, Optional
3
+ from app.vault import Vault
4
+
5
+
6
+ class SSERehydrationBuffer:
7
+ """
8
+ Sliding window buffer that prevents partial tag leakage across SSE chunks.
9
+ Holds back partial token tags (e.g. '[PER' ... 'SON_1]') until completed across deltas.
10
+ """
11
+ MAX_TAG_LENGTH = 64 # Maximum expected length for tokens like [PERSON_999]
12
+
13
+ def __init__(self, vault: Vault):
14
+ self.vault = vault
15
+ self.content_buffer = ""
16
+
17
+ def process_delta_text(self, delta_text: str, is_final: bool = False) -> str:
18
+ """
19
+ Appends incoming delta_text to buffer, checks for unclosed tag brackets '[' near the tail,
20
+ re-hydrates the safe portion, and returns the text ready to emit.
21
+ """
22
+ self.content_buffer += delta_text
23
+
24
+ if is_final or not self.content_buffer:
25
+ res = self.vault.rehydrate(self.content_buffer)
26
+ self.content_buffer = ""
27
+ return res
28
+
29
+ last_bracket_idx = self.content_buffer.rfind('[')
30
+ if last_bracket_idx != -1:
31
+ # Check if matching closing bracket exists after the last open bracket
32
+ matching_close = self.content_buffer.find(']', last_bracket_idx)
33
+ if matching_close == -1:
34
+ # Unclosed bracket at tail. Verify length threshold.
35
+ tail_length = len(self.content_buffer) - last_bracket_idx
36
+ if tail_length <= self.MAX_TAG_LENGTH:
37
+ # Hold tail from last_bracket_idx onward
38
+ safe_part = self.content_buffer[:last_bracket_idx]
39
+ self.content_buffer = self.content_buffer[last_bracket_idx:]
40
+ return self.vault.rehydrate(safe_part) if safe_part else ""
41
+
42
+ # Buffer is safe
43
+ safe_part = self.content_buffer
44
+ self.content_buffer = ""
45
+ return self.vault.rehydrate(safe_part)
46
+
47
+
48
+ async def rehydrate_sse_stream(
49
+ raw_stream: AsyncGenerator[bytes, None],
50
+ vault: Vault
51
+ ) -> AsyncGenerator[bytes, None]:
52
+ """
53
+ Async generator that processes raw SSE stream bytes from upstream LLM,
54
+ parses SSE data lines, re-hydrates content deltas through SSERehydrationBuffer,
55
+ and yields transformed SSE bytes.
56
+ """
57
+ buffer = SSERehydrationBuffer(vault)
58
+ line_accumulator = ""
59
+
60
+ async for chunk in raw_stream:
61
+ chunk_text = chunk.decode("utf-8", errors="replace")
62
+ line_accumulator += chunk_text
63
+
64
+ while "\n" in line_accumulator:
65
+ line, line_accumulator = line_accumulator.split("\n", 1)
66
+ stripped = line.strip()
67
+
68
+ if stripped.startswith("data: ") and stripped != "data: [DONE]":
69
+ raw_json = stripped[6:]
70
+ try:
71
+ data_obj = json.loads(raw_json)
72
+ choices = data_obj.get("choices", [])
73
+ if choices and isinstance(choices, list):
74
+ delta = choices[0].get("delta", {})
75
+ if "content" in delta and isinstance(delta["content"], str):
76
+ raw_content = delta["content"]
77
+ rehydrated_content = buffer.process_delta_text(raw_content)
78
+ delta["content"] = rehydrated_content
79
+ data_obj["choices"][0]["delta"] = delta
80
+ line = f"data: {json.dumps(data_obj)}"
81
+ except json.JSONDecodeError:
82
+ # If line is not valid JSON, fallback to buffer text processing
83
+ pass
84
+
85
+ yield (line + "\n").encode("utf-8")
86
+
87
+ # Flush remaining buffer at stream end
88
+ remaining = buffer.process_delta_text("", is_final=True)
89
+ if remaining:
90
+ # Emit remaining flushed text if any left
91
+ flush_obj = {
92
+ "choices": [{"delta": {"content": remaining}}]
93
+ }
94
+ yield f"data: {json.dumps(flush_obj)}\n\n".encode("utf-8")
95
+
96
+ if line_accumulator:
97
+ yield line_accumulator.encode("utf-8")
app/telemetry.py ADDED
@@ -0,0 +1,144 @@
1
+ """
2
+ Anonymous Volumetric Telemetry System for LLM-Shield.
3
+
4
+ PRIVACY & ZERO-EGRESS GUARANTEE:
5
+ Telemetry in LLM-Shield is strictly OPT-IN ('Bring Your Own Database').
6
+ By default, TELEMETRY_ENABLED=false and no data egress occurs.
7
+
8
+ When explicitly enabled by enterprise operators via environment configuration,
9
+ this worker tracks ONLY purely anonymous, aggregated volumetric metrics
10
+ (such as total requests processed, redaction counts, active proxy connections, and timestamp).
11
+ NO Personally Identifiable Information (PII), prompts, responses, payload contents,
12
+ or IP addresses are EVER collected, logged, or transmitted.
13
+ """
14
+
15
+ import asyncio
16
+ import logging
17
+ import uuid
18
+ from datetime import datetime, timezone
19
+ from typing import Dict, Any, Optional
20
+
21
+ import httpx
22
+ from app.config import settings
23
+
24
+ logger = logging.getLogger("llm_shield.telemetry")
25
+
26
+
27
+ class TelemetryTracker:
28
+ """
29
+ Background worker tracking anonymous volumetric metrics for LLM-Shield instances
30
+ and periodically sending aggregated metrics to an enterprise-configured telemetry REST API.
31
+ """
32
+
33
+ def __init__(self):
34
+ self.instance_id: str = str(uuid.uuid4())
35
+ self.total_requests: int = 0
36
+ self.total_redactions: int = 0
37
+ self.active_connections: int = 0
38
+ self._background_task: Optional[asyncio.Task] = None
39
+
40
+ @property
41
+ def is_enabled(self) -> bool:
42
+ """
43
+ Returns True ONLY if telemetry is explicitly enabled AND endpoint & keys are configured.
44
+ """
45
+ return bool(
46
+ settings.TELEMETRY_ENABLED
47
+ and settings.TELEMETRY_ENDPOINT_URL
48
+ and settings.TELEMETRY_API_KEY
49
+ )
50
+
51
+ def record_request(self, redactions_count: int = 0):
52
+ """
53
+ Increments anonymous volumetric request and redaction counters if telemetry is enabled.
54
+ """
55
+ if not self.is_enabled:
56
+ return
57
+ self.total_requests += 1
58
+ self.total_redactions += redactions_count
59
+
60
+ def increment_active(self):
61
+ if not self.is_enabled:
62
+ return
63
+ self.active_connections += 1
64
+
65
+ def decrement_active(self):
66
+ if not self.is_enabled:
67
+ return
68
+ self.active_connections = max(0, self.active_connections - 1)
69
+
70
+ def get_metrics(self) -> Dict[str, Any]:
71
+ """
72
+ Returns snapshot of current anonymous volumetric metrics.
73
+ """
74
+ return {
75
+ "timestamp": datetime.now(timezone.utc).isoformat(),
76
+ "active_proxy_connections": self.active_connections,
77
+ "total_requests_processed": self.total_requests,
78
+ "total_pii_redactions": self.total_redactions,
79
+ "instance_id": self.instance_id,
80
+ "telemetry_enabled": self.is_enabled,
81
+ }
82
+
83
+ async def emit_telemetry(self):
84
+ """
85
+ Sends aggregated volumetric metrics to configured telemetry REST API endpoint.
86
+ Returns early if telemetry is disabled or unconfigured.
87
+ FAILS SILENTLY on any network error so main proxy traffic is NEVER impacted.
88
+ """
89
+ if not self.is_enabled:
90
+ return
91
+
92
+ payload = {
93
+ "timestamp": datetime.now(timezone.utc).isoformat(),
94
+ "active_proxy_connections": self.active_connections,
95
+ "total_requests_processed": self.total_requests,
96
+ "total_pii_redactions": self.total_redactions,
97
+ }
98
+
99
+ headers = {
100
+ "apikey": settings.TELEMETRY_API_KEY,
101
+ "Authorization": f"Bearer {settings.TELEMETRY_API_KEY}",
102
+ "Content-Type": "application/json",
103
+ }
104
+
105
+ try:
106
+ async with httpx.AsyncClient(timeout=5.0) as client:
107
+ res = await client.post(
108
+ settings.TELEMETRY_ENDPOINT_URL,
109
+ json=payload,
110
+ headers=headers
111
+ )
112
+ if res.status_code >= 400:
113
+ logger.error(f"Telemetry REST HTTP Error {res.status_code}: {res.text}")
114
+ except Exception as exc:
115
+ # Critical Safety: log error locally, fail silently, never crash main proxy pipeline
116
+ logger.error(f"Telemetry emission failed silently: {exc}")
117
+
118
+ async def _heartbeat_worker(self):
119
+ """
120
+ Periodic background task emitting aggregated telemetry.
121
+ """
122
+ while self.is_enabled:
123
+ try:
124
+ await asyncio.sleep(60) # Emission heartbeat interval
125
+ await self.emit_telemetry()
126
+ except asyncio.CancelledError:
127
+ break
128
+ except Exception as exc:
129
+ logger.error(f"Telemetry heartbeat loop error: {exc}")
130
+
131
+ def start(self):
132
+ if self.is_enabled and self._background_task is None:
133
+ try:
134
+ loop = asyncio.get_running_loop()
135
+ self._background_task = loop.create_task(self._heartbeat_worker())
136
+ except RuntimeError:
137
+ pass
138
+
139
+ def stop(self):
140
+ if self._background_task and not self._background_task.done():
141
+ self._background_task.cancel()
142
+
143
+
144
+ telemetry_tracker = TelemetryTracker()
app/vault.py ADDED
@@ -0,0 +1,70 @@
1
+ import re
2
+ from typing import Dict, Optional
3
+
4
+
5
+ class Vault:
6
+ """
7
+ Vault manages bidirectional deterministic mappings between original PII values
8
+ and session-bound tokens (e.g., "sarah@example.com" <-> "[EMAIL_1]").
9
+ """
10
+ def __init__(self):
11
+ self.original_to_token: Dict[str, str] = {}
12
+ self.token_to_original: Dict[str, str] = {}
13
+ self.type_counters: Dict[str, int] = {}
14
+
15
+ def get_or_create_token(self, original_val: str, entity_type: str) -> str:
16
+ """
17
+ Returns an existing token if original_val has already been registered,
18
+ otherwise generates a deterministic token like [PERSON_1].
19
+ """
20
+ if original_val in self.original_to_token:
21
+ return self.original_to_token[original_val]
22
+
23
+ current_count = self.type_counters.get(entity_type, 0) + 1
24
+ self.type_counters[entity_type] = current_count
25
+
26
+ token = f"[{entity_type}_{current_count}]"
27
+ self.original_to_token[original_val] = token
28
+ self.token_to_original[token] = original_val
29
+ return token
30
+
31
+ def rehydrate(self, text: str) -> str:
32
+ """
33
+ Replaces all tokens in the text with their corresponding original PII values.
34
+ """
35
+ if not text or not self.token_to_original:
36
+ return text
37
+
38
+ # Sort tokens by length descending to prevent partial token replacements
39
+ sorted_tokens = sorted(self.token_to_original.keys(), key=len, reverse=True)
40
+ result = text
41
+ for token in sorted_tokens:
42
+ original = self.token_to_original[token]
43
+ result = result.replace(token, original)
44
+
45
+ return result
46
+
47
+
48
+ class VaultStore:
49
+ """
50
+ Store holding session-scoped vaults.
51
+ If session_id is provided, vault persists across requests for that session_id.
52
+ Otherwise, an ephemeral Vault is returned for a single request.
53
+ """
54
+ def __init__(self):
55
+ self._sessions: Dict[str, Vault] = {}
56
+
57
+ def get_vault(self, session_id: Optional[str] = None) -> Vault:
58
+ if not session_id:
59
+ return Vault()
60
+
61
+ if session_id not in self._sessions:
62
+ self._sessions[session_id] = Vault()
63
+ return self._sessions[session_id]
64
+
65
+ def clear_session(self, session_id: str):
66
+ if session_id in self._sessions:
67
+ del self._sessions[session_id]
68
+
69
+
70
+ vault_store = VaultStore()
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: llm-shield-proxy
3
+ Version: 1.0.0
4
+ Summary: Enterprise Zero-Egress Privacy Redaction Proxy Engine for LLMs
5
+ Author-email: Ninad Phalak <ninad.phalak@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/ninadphalak/LLM-Shield
8
+ Project-URL: Repository, https://github.com/ninadphalak/LLM-Shield
9
+ Project-URL: Bug Tracker, https://github.com/ninadphalak/LLM-Shield/issues
10
+ Keywords: llm,pii,redaction,privacy,proxy,fastapi,streaming,soc2,hipaa
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Security
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: fastapi>=0.100.0
24
+ Requires-Dist: uvicorn>=0.22.0
25
+ Requires-Dist: httpx>=0.24.0
26
+ Requires-Dist: pydantic>=2.0.0
27
+ Requires-Dist: pydantic-settings>=2.0.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
30
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
31
+ Requires-Dist: pytest-httpx>=0.24.0; extra == "dev"
32
+ Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
33
+ Requires-Dist: openai>=1.0.0; extra == "dev"
34
+ Requires-Dist: build; extra == "dev"
35
+ Requires-Dist: twine; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # LLM-Shield - Enterprise Privacy Redaction Engine
39
+
40
+ [![PyPI Version](https://img.shields.io/pypi/v/llm-shield-proxy.svg)](https://pypi.org/project/llm-shield-proxy/)
41
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
42
+ [![Python Version](https://img.shields.io/badge/python-3.9%2B-blue)](https://www.python.org/)
43
+
44
+ **LLM-Shield** is an open-source, zero-egress middleware proxy that intercepts OpenAI-compatible LLM API requests, redacts Personally Identifiable Information (PII) before it leaves your local infrastructure, and deterministically re-hydrates real-time SSE streaming responses without breaking stream latency.
45
+
46
+ Designed for enterprise privacy compliance (**SOC 2 / HIPAA**).
47
+
48
+ Author & Core Maintainer: **Ninad Phalak** (`ninad.phalak@gmail.com`)
49
+
50
+ ---
51
+
52
+ ## ⚡ Core Features
53
+
54
+ - **Zero Latency Streaming:** Sliding-window tag-safety buffer intercepts SSE streams delta-by-delta without buffering full requests or responses.
55
+ - **Zero Cloud / Zero Egress:** 100% local processing. No external API calls for PII detection.
56
+ - **Two-Tier PII Cascade Engine:**
57
+ - **Tier 1 (Sub-millisecond Regex):** SSNs, Credit Cards, Email Addresses, Phone Numbers, IPv4/IPv6, API Keys.
58
+ - **Tier 2 (NER Engine):** Person Names and unstructured entities.
59
+ - **Deterministic Re-Hydration Vault:** Swaps PII with session-bound tokens (e.g., `Sarah` -> `[PERSON_1]`). Maps back deterministically when the LLM streams responses. Supports request-scoped and session-scoped (`X-Session-ID`) vaults.
60
+ - **SOC 2 Structured Audit Logging:** Emits JSON structured audit logs for compliance monitoring.
61
+ - **Opt-In Telemetry:** Strictly opt-in (`TELEMETRY_ENABLED=false` by default) telemetry worker collecting aggregated volumetric metrics with an explicit zero-PII guarantee.
62
+
63
+ ---
64
+
65
+ ## 📦 Installation
66
+
67
+ Install `llm-shield-proxy` directly from PyPI via `pip`:
68
+
69
+ ```bash
70
+ pip install llm-shield-proxy
71
+ ```
72
+
73
+
74
+ Or install locally in editable mode:
75
+
76
+ ```bash
77
+ pip install -e .
78
+ ```
79
+
80
+ ---
81
+
82
+ ## 🚀 Quickstart
83
+
84
+ ### Running via Python / Uvicorn
85
+
86
+ ```bash
87
+ uvicorn app.main:app --host 0.0.0.0 --port 8000
88
+ ```
89
+
90
+ ### Running via Docker Compose
91
+
92
+ ```bash
93
+ docker-compose up -d
94
+ ```
95
+
96
+ ### Usage with OpenAI Client
97
+
98
+ Point your base URL to LLM-Shield (`http://localhost:8000/v1`):
99
+
100
+ ```python
101
+ from openai import OpenAI
102
+
103
+ client = OpenAI(
104
+ base_url="http://localhost:8000/v1",
105
+ api_key="your-openai-api-key"
106
+ )
107
+
108
+ response = client.chat.completions.create(
109
+ model="gpt-4o-mini",
110
+ messages=[
111
+ {"role": "user", "content": "Contact Sarah Connor at sarah@example.com"}
112
+ ],
113
+ stream=True
114
+ )
115
+
116
+ for chunk in response:
117
+ print(chunk.choices[0].delta.content or "", end="")
118
+ ```
119
+
120
+ ---
121
+
122
+ ## 🧪 Testing
123
+
124
+ Run the full automated test suite:
125
+
126
+ ```bash
127
+ py -m pytest tests/
128
+ ```
129
+
130
+ ---
131
+
132
+ ## 🏢 Using LLM-Shield in Production?
133
+
134
+ We are actively working with enterprise security teams to map out advanced compliance features. If your startup or organization is using LLM-Shield to unblock LLM streaming or pass SOC 2/HIPAA audits, I would love to hear from you.
135
+
136
+ Email the core maintainer at ninad.phalak@gmail.com to share your feedback, request a feature, or feature your team as a case study.
@@ -0,0 +1,13 @@
1
+ app/__init__.py,sha256=yXolTGrhv8IFA0utVx_o0Wl2TLfNqQUhZg6z60boqC4,21
2
+ app/audit.py,sha256=xIKuSZpQPov9zF7bcJUAKxMKvXrmvd4QzL8tKRDocVo,2052
3
+ app/config.py,sha256=JORV2CzfaquIYBgQciocYva3NvV1Gi3P-rbfeO4-5f0,642
4
+ app/main.py,sha256=SN49A-Sr7Ievdpn5aw1SgStUylFQT4wsPXdVoIj3JCc,6907
5
+ app/pii_engine.py,sha256=u7jROfOidkcNpiHXinJCiFXwyIGX0DAdZ1PXfRilwdU,4900
6
+ app/streaming.py,sha256=e8BcayoYk4gvMCsVFHYmF0XFXv36afXvdQEUjMlSS6Q,4002
7
+ app/telemetry.py,sha256=zlOYrIvaRYFC4pXeRaX5oH45fXzUiztR_fHPZMSC5Q8,5097
8
+ app/vault.py,sha256=olWydC1jQoW7nd4LkZrS_BTOX1T4jATNOKnTdt4FakA,2377
9
+ llm_shield_proxy-1.0.0.dist-info/licenses/LICENSE,sha256=WpXfhhvQsp6XSoVLn7EXhpkA0QphuXeJuAQimuiSZ9I,10727
10
+ llm_shield_proxy-1.0.0.dist-info/METADATA,sha256=-mf1dRJOsxE9LqICAQu5Lfa4VOHa5B2Q7_QMz3w1vkU,4902
11
+ llm_shield_proxy-1.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
12
+ llm_shield_proxy-1.0.0.dist-info/top_level.txt,sha256=io9g7LCbfmTG1SFKgEOGXmCFB9uMP2H5lerm0HiHWQE,4
13
+ llm_shield_proxy-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Ninad Phalak
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ app