Sub topic 2
Where Sensitive Data Hides in LLM Traffic
This chapter assumes you can call an LLM API from Python and know how application logging and log levels work. It also assumes you can read a basic regular expression. Redaction and policy come in later chapters. Here the goal is to find the data, because you can't protect a field you haven't noticed.
Why LLM traffic needs its own inventory
In a typical web API, you know which fields are sensitive: a password field, a card number, an email column. An LLM call is different. The main payload is free text, and free text has no schema. A user can paste anything into a prompt, and a model can say anything in a response.
Logging a whole request to an LLM is therefore like logging a whole support inbox. Most of it is harmless, and some of it is not. You can't tell which part is which without reading it.
The anatomy of one call
A single call has several places where data enters, and several places where copies end up.
Three kinds of data matter: what you send in the body, what comes back in the response, and what travels alongside in headers and URLs. The sections below take each in turn.
Sensitive data in prompts
A prompt is rarely just what the user typed. Your application assembles it from several sources, and each source brings its own risks.
- User messages. People paste emails, contracts, stack traces, medical details, and customer records into chat boxes. They also paste credentials, often by accident, such as a
.envfile shared to ask why an app won't start. - System prompts. Your instructions may contain business rules, internal URLs, pricing logic, or sometimes an API key that a developer embedded for convenience. A system prompt is often the most valuable text in the request, and it is repeated in every call. A single logging mistake multiplies it.
- Retrieved context. In retrieval-augmented generation (RAG), your application fetches documents and inserts them into the prompt. Those documents may come from internal wikis, ticket systems, or shared drives. They carry whatever access controls those systems have, and the controls do not follow the text into your logs.
- Tool and function results. When a model calls a tool, the result goes back into the conversation. A database lookup can return a full customer row. A file read can return a config file.
- Conversation history. Many applications resend the whole conversation on every turn. If you log every request, one piece of sensitive text gets logged once per turn, not once.
Repeated history makes log volume and exposure grow together. A ten-turn chat that includes one pasted password logs that password ten times.
Sensitive data in responses
Responses look safer because you did not write them, but they carry risk too.
- Echoes. Models often repeat input. A request to summarize a document returns pieces of that document, including its personal data.
- Derived data. A model can infer and state things the user never typed outright, such as a likely diagnosis from a list of symptoms. A derived fact about a person can be as sensitive as a stated one.
- Generated lookalikes. A model may produce text shaped like an email address, a phone number, or an API key. Most are invented, but a log scanner cannot tell. You also cannot assume the data is fake, because training data and your own context can both supply real values.
- Hostile text. The response can contain newlines, markup, or instructions planted by an attacker through a retrieved document. This is a log-safety issue rather than a privacy issue, and a later chapter covers it.
Sensitive data outside the body
Developers tend to focus on prompt text and forget the rest of the request.
| Location | What it can hold | Why it leaks |
|---|---|---|
| `Authorization` header | The provider API key as a bearer token | Debug logging of "the request" often includes all headers |
| Other auth headers | Organization or project IDs, custom keys such as `x-api-key` | Proxies and gateways add them, so they differ by environment |
| `Cookie` and session headers | Session tokens, if calls pass through an internal gateway | The gateway may forward the end user's cookies |
| URL and query string | Keys on APIs that accept `?key=...`, user IDs, filenames | URLs are logged by default in proxies and HTTP libraries |
| Custom metadata fields | User IDs, emails, tenant names that you attach for tracking | Teams add them for convenience and rarely review them |
| Provider error messages | Partial keys, request fragments | Exceptions get logged without being read |
A provider's authentication error, for example, may echo part of the key you sent. The message then lands in your logs through an ordinary logger.exception(...) call, where nobody expected a secret.
An allowlist beats a denylist
Suppose you want to log request headers for debugging. A denylist ("drop Authorization") fails the first time a gateway adds X-Api-Key or Proxy-Authorization. An allowlist fails safe: an unknown header is dropped.
ALLOWED_HEADERS = {"content-type", "x-request-id", "user-agent"}
def safe_headers(headers: dict) -> dict:
"""Keep only headers that are known to be harmless."""
return {k: v for k, v in headers.items() if k.lower() in ALLOWED_HEADERS}
raw = {
"Authorization": "Bearer sk-abcdefghijklmnop1234",
"Content-Type": "application/json",
"X-Request-Id": "r-42",
"Cookie": "session=abc123",
}
print(safe_headers(raw))
# {'Content-Type': 'application/json', 'X-Request-Id': 'r-42'}The comparison is lowercase because HTTP header names are case-insensitive. A check that compares exact case will miss authorization.
Places where copies appear without your code asking
You can write a careful logging wrapper and still leak, because other components log too.
- HTTP library debug modes. Python's
http.clientprints request headers when itsdebuglevelis raised, and some SDKs expose a debug flag that logs full requests. These are easy to switch on during an incident and easy to forget. - Exception messages and tracebacks. An exception raised deep in a client library can carry request details. Logging the exception object logs those details.
- Error trackers and APM tools. Many capture local variables, request bodies, or breadcrumbs automatically. A variable named
promptin a stack frame can be uploaded to a third party. - Tracing and observability integrations. Some LLM tracing tools record the full prompt and response as span attributes by default. Check their settings before you enable them.
- Gateways and proxies. A load balancer or API gateway in front of your service may log bodies or query strings on its own schedule and in its own storage.
- Retries and queues. A failed request pushed to a retry queue or dead-letter queue stores the whole body, often with a longer retention than your logs.
Sorting what you find
Once you have found the data, place it in a class. The class decides the handling in the next chapter.
| Class | Examples | Typical handling |
|---|---|---|
| Credentials | API keys, bearer tokens, passwords, cookies | Never log, in any environment |
| Personal data | Names, emails, phone numbers, addresses, IDs | Log only under policy, redacted or hashed |
| Special-category data | Health, finances, beliefs, minors' data | Strictest handling, and often legal duties |
| Proprietary text | System prompts, source code, contracts | Treat as confidential, restrict access |
| Operational metadata | Model name, token counts, latency, status | Safe to log by default |
The last row matters. Token counts, latency, and status codes carry no user text, which is why a metadata-first policy still gives you useful data for debugging and cost tracking.
Edge cases to keep in mind
- Partial secrets. A log line that shows the first eight characters of a key still helps an attacker, and it makes the key easier to find in a leak.
- Encoded data. Base64 images, file attachments, and embedded documents in a request body are opaque to a text scanner. Skip logging attachments entirely, and record only their size and type.
- Non-English and unusual formats. Name and address patterns differ by country. A scanner tuned for US phone numbers misses others.
- Prompts that were never typed by a person. Automated pipelines process scraped pages and inbound emails. The sender of that content never agreed to anything, which can matter for legal reasons.
- Test data that turns out to be real. Developers often debug with a real customer's record "just once." Logs from that session persist.
What to take into the policy chapter
Sensitive data appears in at least four places: the prompt, the response, the headers and URL, and the side channels that copy requests without your knowledge. Free text cannot be fully classified in advance. This is why the safest default is to log facts about the call and not the text of the call.
Exercise
Your wrapper logs the prompt and response, with redaction, but you use a denylist for headers that drops only "Authorization". A gateway team adds an "X-Api-Key" header on the way to the provider. Name two separate problems with this setup and one fix for each.
Show answer
First, the denylist fails open. The new X-Api-Key header is logged because nobody added it to the list. Fix: switch to an allowlist of known-safe headers, so unknown headers are dropped. Second, logging the prompt and response by default exposes anything users paste, including data that redaction patterns do not recognize. Fix: log only metadata by default (sizes, model, status, latency) and log redacted content only under an explicit, gated setting.
Exercise
A user pastes a 2,000-word contract into a chat, and the conversation lasts ten turns. The app resends the full history each turn and logs every request body. Roughly how many times is the contract logged, and why does that matter?
Show answer
About ten times, once per turn, because the whole history is resent in each request. Every copy is another place the data can be read, retained, or leaked, and deleting it later means finding all ten. Logging metadata, or hashing the prompt, avoids storing the text at all.