Mental model
A large language model is an untrusted, probabilistic compute layer that mixes governing instructions and raw data inside a single shared token window. Production security and privacy therefore cannot rely on prompting the model to behave safely; they require NIST Zero Trust per-request authorization, pre-embedding PII redaction, pinned artifact supply chains, zero-data-retention (ZDR) inference contracts, and deterministic egress firewalls.
Learning outcomes
- Map critical OWASP Top 10 for LLM Applications risks (prompt injection, sensitive disclosure, excessive agency, supply-chain compromise) to deterministic system controls.
- Explain why PII and credential redaction must occur before chunking, vector embedding, prompt assembly, and trace logging.
- Configure zero-data-retention (ZDR) inference endpoints, VPC private links, and tenant-scoped encryption keys to prevent cross-tenant leakage and unintended training retention.
- Build a Python egress PII and secret firewall that blocks leaked API keys, SSNs, or cross-tenant identifiers before responses or tool arguments leave the trust boundary.
Theory
Traditional web security separates executable code from user data via parameterized SQL queries, DOM sanitization, and OS process isolation. In an LLM pipeline, user text, retrieved documents, and system directives all become token embeddings inside the same transformer context. Under the NIST AI Risk Management Framework (AI RMF) and NIST SP 800-207 Zero Trust Architecture, every inference call, vector lookup, and tool invocation must assume breach at the model layer and verify identity, data classification, and authorization at deterministic enforcement points.
OWASP LLM Top 10 Operational Boundaries
Four high-severity OWASP LLM threat classes dominate production architectures:
- LLM01 Prompt Injection & LLM06 Excessive Agency: Untrusted text retrieved via RAG or web search attempts to hijack tool calls. Mitigation pairs structural role isolation with strict least-privilege tool scopes and out-of-band human confirmation for mutating operations.
- LLM02 Sensitive Information Disclosure: Models leak secrets memorized during fine-tuning, cached across shared prompts, or retrieved from unsegregated vector namespaces. Mitigation strips PII before ingestion, disables training retention, and partitions retrieval indexes by verified tenant ACLs.
- LLM03 Supply Chain Vulnerabilities: Downloading unverified open-weight checkpoints serialized in Python
pickleformat (.ptor.bin) can execute arbitrary OS shell payloads duringtorch.load(). Production clusters pin SHA-256 weight digests and mandate memory-safesafetensorsserialization. - LLM05 Improper Output Handling: Rendering unescaped model-generated Markdown, HTML, or SQL directly in browsers or databases causes Cross-Site Scripting (XSS) and SQL injection—requiring strict HTML escaping and parameterized queries downstream.
Quantitative Exposure & Pre-Ingestion Redaction
Why must PII scrubbing happen before vector embedding and prompt assembly rather than only on final output? Once an email, SSN, or AWS secret key enters a vector store or OpenTelemetry trace, it persists in disk snapshots, dense embedding vectors (which remain partially invertible), and log aggregators even if a final output regex catches it later.
Consider an enterprise support platform indexing 500,000 customer tickets averaging 300 tokens each (150 million tokens), where 1.2% of tickets contain unmasked payment tokens or government IDs (6,000 sensitive records). If retrieval queries hit an average top- chunks per turn across monthly queries with probability per chunk, naive unredacted indexing exposes sensitive records to prompt context windows up to:
Even if an output filter catches 95% of leaked strings before reaching the UI, 5% of 4,602 (~230 monthly responses)—plus all 4,602 upstream API requests and debug traces—still handle raw sensitive secrets. Running deterministic NER and regex PII pseudonymization prior to vector embedding and enforcing tenant metadata filters collapses upstream secret exposure toward zero.
Tenant Encryption and Zero Data Retention (ZDR)
Provider data controls distinguish standard API retention (where prompts/outputs may be stored 30 days for abuse monitoring or optional evaluation) from Zero Data Retention (ZDR) agreements and VPC-private endpoints (Azure Private Link, AWS PrivateLink, or self-hosted vLLM). High-assurance workloads pair ZDR contracts with per-tenant envelope encryption keys (KMS CMKs) so tenant A's stored history and vector payloads remain cryptographically unreadable to tenant B even on shared storage.
Trade-offs
Defense-in-depth layers trade false-positive blocking, latency overhead, and operational complexity against breach blast radius.
| Security Control | Protected Threat Class | Latency / UX Overhead | Residual Risk / Operational Trade-off |
|---|---|---|---|
Pre-Embedding PII Pseudonymization (<PERSON_1>) | Sensitive disclosure (LLM02), trace leakage | +5–20 ms on ingestion & query | Over-aggressive regexes can mask benign product codes (ID-123) |
Mandatory safetensors + SHA-256 Weight Pinning | Supply-chain RCE (LLM03) | Zero inference overhead; CI/CD digest checks | Requires mirroring and re-verifying Hugging Face weight releases |
| ZDR + VPC Private Inference Routing | Third-party data retention & transit snooping | Minimal after PrivateLink setup; higher fixed cost | Disables provider-managed web playground debugging & stateful storage |
| Deterministic Egress Secret Firewall | Credential exfiltration via Markdown images/URLs | < 1ms streaming buffer check | Can clip legitimate masked examples unless allowlisted by context |
Failure modes and misconceptions
- Scrubbing PII only in the final HTTP response: Logging unredacted user prompts to observability pipelines, caching raw prompts in Redis, or indexing raw PII into pgvector already violates data-minimization policies before the model responds.
- Exfiltrating secrets via rendered Markdown image tags: Even if an application strips
<script>tags, an indirect prompt injection can coerce the model into emitting, causing the user's browser to transmit secrets via an automatic HTTP GET fetch. Enforce strict Content Security Policy (img-src 'self') and strip external image URLs in Markdown renderers. - Loading unverified
pickle.bincheckpoints withweights_only=False: Arbitrarypickleopcodes execute immediately during deserialization on GPU hosts, compromising cluster credentials. - Global shared vector namespaces without verified ACL filters: Relying on the model prompt "Only cite docs belonging to user Bob" fails trivially under adversarial queries; always inject
WHERE tenant_id = :verified_jwt_tenantat the database query boundary. - Misinterpreting ZDR as local storage hygiene: Provider ZDR stops retention on the inference vendor's servers, yet your own reverse proxies, Kubernetes stdout logs, and evaluation buckets still retain raw payloads unless explicitly scrubbed.
Decision scenario
A healthcare fintech builds an internal claims-triage copilot querying claims documents and calling a settlement status API. Compliance flags three gaps: raw SSNs and bank routing numbers enter pgvector embeddings, debug logs capture unredacted prompts, and Markdown links in model answers can trigger external fetches. Remediate the pipeline by deploying a deterministic pre-ingestion PII scrubber (SSN, IBAN, bearer tokens) before chunking or embedding, routing inference over a ZDR-enabled VPC endpoint, enforcing JWT-derived tenant_id filters in Postgres SQL rather than prompts, disabling remote Markdown image rendering via CSP, and gating every outbound model reply and tool call through an egress secret firewall.
Implementation example
This Python egress and pre-ingestion PII/secret firewall detects and redacts high-risk tokens (SSNs, AWS keys, JWTs, private keys, and unapproved Markdown exfiltration URLs) deterministically before storage or delivery.
pythonimport refrom dataclasses import dataclassSECRET_PATTERNS: dict[str, re.Pattern[str]] = {"AWS_KEY": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),"BEARER_JWT": re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"),"SSN": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),"PRIVATE_KEY": re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),}MD_EXFIL_RE = re.compile(r"!\[[^\]]*\]\((https?://[^)\s]+)\)", re.I)@dataclass(frozen=True)class FirewallVerdict:sanitized_text: str; findings: list[str]; blocked_exfil: booldef inspect_and_redact(text: str, allowed_hosts: set[str] | None = None) -> FirewallVerdict:findings, redacted, allowed = [], text, allowed_hosts or set()for label, pattern in SECRET_PATTERNS.items():if matches := pattern.findall(redacted):findings.append(f"{label}:{len(matches)}")redacted = pattern.sub(f"[REDACTED_{label}]", redacted)blocked = Falsedef _strip_img(match: re.Match[str]) -> str:nonlocal blockedhost = match.group(1).split("/")[2].lower() if len(match.group(1).split("/")) > 2 else ""if host not in allowed:blocked = True; findings.append(f"BLOCKED_IMG:{host}"); return "[BLOCKED_EXTERNAL_IMAGE]"return match.group(0)return FirewallVerdict(MD_EXFIL_RE.sub(_strip_img, redacted), findings, blocked)
Knowledge check
Why must PII redaction and Zero-Trust tenant filtering execute prior to vector embedding and log emission rather than relying solely on output filters or ZDR contracts?