Permission-Aware Retrieval and Redaction
Fix a retriever that trusts a client-supplied workspace filter: label chunks at ingestion, build the filter from the server-verified identity before ranking, prove isolation with tests, and redact secrets and personal data from prompts and logs while sending the model only the fields a task needs.
Contentsand lesson path
On this page
- The problem
- Step 1: Label chunks at ingestion, decide identity on the server
- Step 2: Reproduce the leak
- Step 3: Filter on the verified identity, before ranking
- Step 4: Prove it with tests
- Step 5: Redact secrets and personal data, and send less
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of AI Security
- Threat Modeling an LLM Application Concept · 20 min
- Lab: Injecting Your Own RAG Assistant Lab · 25 min
- Layered Defenses, Moderation and Their Limits Concept · 15 min
- Permission-Aware Retrieval and Redaction Worked example · 20 min
- Untrusted Output and Content Moderation Worked example · 25 min
- Check: Spot the Vulnerability Knowledge check · 10 questions
What you will learn
- Prevent sensitive data leakage by enforcing per-user authorization in retrieval and redacting secrets and personal data from prompts and logs.
01. The problem
The Lumen assistant has grown. Besides the public help centre, it now answers from each customer's own workspace documents, and some of those are private notes that only their author may read. One index holds all of it.
A security review finds two problems. First, the search endpoint takes the workspace to search from the JSON body that the browser sends, so anyone who edits the request can read another company's plans. Second, the application log records every user message in full, including the API keys, email addresses and card numbers that customers paste into the chat.
Both are cases of sensitive information disclosure (OWASP LLM02:2026), and the first is also a vector and embedding weakness (LLM09:2026). Neither can be fixed in the prompt. A model told "only use documents from the user's workspace" cannot check who the user is, and it has already seen the other documents by the time it reads the rule. Authorisation has to happen in the retrieval code, before any text reaches the prompt. In this worked example you fix both problems, and write the tests that prove the first one stays fixed.
02. Step 1: Label chunks at ingestion, decide identity on the server
Every chunk carries the access labels of its source document, copied at ingestion: a visibility (public, workspace or private), the workspace and the owner. Without labels on the chunks, retrieval has nothing to filter on.
Identity comes from the auth layer. verify() turns a session token into a Principal: the user ID and the workspaces the user belongs to right now, looked up from the membership table, which is the source of truth. In a real app it checks the signature and expiry of a session cookie or token; here a dictionary stands in for that.
"""Chunks with access labels, copied from the source system at ingestion."""
def chunk(id, text, visibility, workspace=None, owner=None) -> dict:
return {"id": id, "text": text, "visibility": visibility,
"workspace": workspace, "owner": owner}
CHUNKS = [
chunk("kb-1", "Export a project as CSV from the project settings.", "public"),
chunk("acme-1", "Acme plan: the Orion release ships on 3 March.",
"workspace", "acme", "u-ada"),
chunk("acme-2", "Private note: Orion will cost 40 EUR per seat.",
"private", "acme", "u-ada"),
chunk("globex-1", "Globex plan: the Atlas release ships on 9 May.",
"workspace", "globex", "u-bob"),
]"""Stand-in for your auth layer: the server decides who the caller is."""
from dataclasses import dataclass
class Unauthorised(Exception):
pass
@dataclass(frozen=True)
class Principal:
user_id: str
workspaces: frozenset[str]
SESSIONS = {"tok-ada": "u-ada", "tok-cy": "u-cy", "tok-bob": "u-bob"}
MEMBERSHIPS = {"u-ada": {"acme"}, "u-cy": {"acme"}, "u-bob": {"globex"}}
def verify(token: str) -> Principal:
"""In a real app: check the session cookie or token signature and expiry."""
user_id = SESSIONS.get(token)
if user_id is None:
raise Unauthorised("unknown or expired session")
return Principal(user_id, frozenset(MEMBERSHIPS.get(user_id, ())))03. Step 2: Reproduce the leak
Here is the vulnerable endpoint. It filters before ranking, which is right, but it builds the filter from body["workspace_id"], a value the client controls, and it ignores private notes altogether. rank() is a word-overlap stand-in for vector search.
"""Retrieval for the assistant: a vulnerable version and a fixed one."""
import re
from auth import Principal, verify
from index import CHUNKS
class Forbidden(Exception):
pass
def words(text: str) -> set[str]:
return set(re.findall(r"[a-z0-9]{4,}", text.lower()))
def rank(query: str, chunks: list[dict], k: int) -> list[dict]:
"""Stand-in for vector search: rank by shared words."""
scored = [(len(words(query) & words(c["text"])), c) for c in chunks]
return [c for s, c in sorted(scored, key=lambda x: -x[0]) if s > 0][:k]
def search_v1(body: dict, k: int = 3) -> list[dict]:
"""VULNERABLE: the workspace filter comes from the request body."""
allowed = [c for c in CHUNKS
if c["visibility"] == "public" or c["workspace"] == body["workspace_id"]]
return rank(body["query"], allowed, k)from search import search_v1
# Bob belongs to Globex, but he edits the request body in his browser.
body = {"query": "When does the Orion release ship?", "workspace_id": "acme"}
print([c["id"] for c in search_v1(body)])
# Cy is in Acme, so the filter is right, yet Ada's private note comes back.
body = {"query": "What will Orion cost per seat?", "workspace_id": "acme"}
print([c["id"] for c in search_v1(body)])python try_v1.py['acme-1', 'acme-2']
['acme-2', 'acme-1']Bob, who works for Globex, gets Acme's release plan and Ada's private pricing note by changing one field. Cy is a legitimate Acme member and still sees Ada's private note. Neither needed any prompt injection: the model would have answered from these chunks politely and with correct citations.
04. Step 3: Filter on the verified identity, before ranking
The fix has three parts. The identity comes from verify(), never from the body. can_read() states the rule in one place: public chunks for everyone, workspace chunks for members, private chunks for members who own them. And the client may still narrow the search to one workspace, but only to one it belongs to; asking for another is refused rather than silently ignored, so the attempt shows up in your logs. Add this to search.py:
def can_read(p: Principal, c: dict) -> bool:
if c["visibility"] == "public":
return True
if c["workspace"] not in p.workspaces:
return False
return c["visibility"] == "workspace" or c["owner"] == p.user_id
def search(token: str, query: str, workspace: str | None = None,
k: int = 3) -> list[dict]:
p = verify(token) # identity from the session, not from the body
if workspace is not None and workspace not in p.workspaces:
raise Forbidden(f"{p.user_id} is not a member of {workspace}")
allowed = [c for c in CHUNKS if can_read(p, c)
and (workspace is None or c["workspace"] in (None, workspace))]
return rank(query, allowed, k) # filter first, then rankfrom search import Forbidden, search
print([c["id"] for c in search("tok-bob", "When does the Orion release ship?")])
print([c["id"] for c in search("tok-cy", "What will Orion cost per seat?")])
print([c["id"] for c in search("tok-ada", "What will Orion cost per seat?")])
try:
search("tok-bob", "Orion release", workspace="acme")
except Forbidden as error:
print("Forbidden:", error)python try_v2.py['globex-1']
['acme-1']
['acme-2', 'acme-1']
Forbidden: u-bob is not a member of acmeFiltering comes first and ranking second. With a real vector database, pass the same rule as a metadata filter in the query itself, so the index only ever considers chunks the user may read. Dropping forbidden chunks from the top-k results afterwards looks equivalent but is not, as the common mistakes below explain.
05. Step 4: Prove it with tests
A fix you have not tested is a fix you will lose in the next refactor. The strongest isolation test does not guess at queries: it searches as Bob with every chunk's own text as the query, which is the best possible match for that chunk, and asserts that no Acme chunk ever comes back. The other tests cover private notes, a tampered workspace and a forged session.
import pytest
from auth import Unauthorised
from index import CHUNKS
from search import Forbidden, search
def test_bob_cannot_retrieve_acme_chunks():
for chunk in CHUNKS: # each chunk's own text is the strongest possible query
found = search("tok-bob", chunk["text"], k=len(CHUNKS))
assert all(c["workspace"] != "acme" for c in found), chunk["id"]
def test_private_note_stays_with_its_owner():
query = "What will Orion cost per seat?"
assert "acme-2" in [c["id"] for c in search("tok-ada", query)]
assert "acme-2" not in [c["id"] for c in search("tok-cy", query, k=10)]
def test_tampered_workspace_is_refused():
with pytest.raises(Forbidden):
search("tok-bob", "Orion release", workspace="acme")
def test_unknown_session_is_refused():
with pytest.raises(Unauthorised):
search("tok-forged", "Orion release")python -m pytest -q test_isolation.py.... [100%]
4 passed in 0.84sCheck that the tests can fail: make can_read() return True and run them again. The first two fail, which shows they really exercise the rule. Run this suite in CI, and add a case whenever you add a new kind of visibility or a new data source.
06. Step 5: Redact secrets and personal data, and send less
Now the second finding. Whatever a customer types goes to the model provider and, through the log, to everyone who can read logs, for as long as logs are kept. Redact it on the way in. redact() replaces each match with a typed placeholder such as [API_KEY_1]: the sentence still makes sense to the model, which can tell the customer that a key was shared and should be rotated. Within one call to redact(), the same value gets the same placeholder; the numbering starts again for the next message. Patterns run in order, so card numbers are matched before the looser phone pattern.
Attach the filter to the log handler, not to one logger: a filter on a logger does not see records from its child loggers, while a handler filter sees every record it writes, including those from libraries.
"""Replace secrets and personal data with typed placeholders."""
import logging
import re
PATTERNS = [ # order matters: card numbers before phone numbers
("API_KEY", re.compile(r"\blm_(?:live|test)_[A-Za-z0-9]{16,}\b")),
("AWS_KEY_ID", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
("EMAIL", re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")),
("CARD", re.compile(r"\b(?:\d[ -]?){12,18}\d\b")),
("PHONE", re.compile(r"\+?\d[\d ()-]{7,}\d")),
]
def redact(text: str) -> str:
seen: dict[str, str] = {} # the same value gets the same placeholder
for label, pattern in PATTERNS:
def swap(match: re.Match) -> str:
value = match.group(0)
if value not in seen:
n = sum(p.startswith(f"[{label}_") for p in seen.values()) + 1
seen[value] = f"[{label}_{n}]"
return seen[value]
text = pattern.sub(swap, text)
return text
class RedactingFilter(logging.Filter):
"""Redacts every record before any handler formats or writes it."""
def filter(self, record: logging.LogRecord) -> bool:
record.msg, record.args = redact(record.getMessage()), None
return Trueimport logging
import sys
from redact import RedactingFilter, redact
MESSAGES = [
"Key lm_live_9fA3kQ2xZp7RtY6wB4 fails. Mail me at [email protected].",
"Call +44 20 7946 0958. Card 4111 1111 1111 1111 was charged twice.",
]
for message in MESSAGES:
print(redact(message))
logging.basicConfig(stream=sys.stdout, format="%(levelname)s %(name)s %(message)s",
level=logging.INFO)
for handler in logging.getLogger().handlers: # on the handler: covers every logger
handler.addFilter(RedactingFilter())
logging.getLogger("assistant").info("user message: %s", MESSAGES[0])python try_redact.pyKey [API_KEY_1] fails. Mail me at [EMAIL_1].
Call [PHONE_1]. Card [CARD_1] was charged twice.
INFO assistant user message: Key [API_KEY_1] fails. Mail me at [EMAIL_1].Redaction catches what the customer typed. Data minimisation controls what your own code adds. When the assistant answers a billing question, it needs the plan, the seat count and the last invoice; it does not need the customer's name, email or billing address. Choose the fields per task with an allow-list, so that a new column in the account table is never sent by default.
"""Send the model the account fields the task needs, nothing else."""
ACCOUNT = {
"user_id": "u-dana", "name": "Dana Reyes", "email": "[email protected]",
"billing_address": "1 High Street, Leeds", "plan": "Team", "seats": 12,
"last_invoice": "2026-10-01: 2 charges of 96 EUR",
}
FOR_BILLING_QUESTIONS = ("plan", "seats", "last_invoice")
def account_context(account: dict, fields: tuple[str, ...]) -> str:
return "\n".join(f"{name}: {account[name]}" for name in fields)
print(account_context(ACCOUNT, FOR_BILLING_QUESTIONS))python minimise.pyplan: Team
seats: 12
last_invoice: 2026-10-01: 2 charges of 96 EURPattern-based redaction finds secrets with a known format and well-formed contact details. It misses names, street addresses and secrets without a recognisable shape. Entity-recognition tools catch more but still miss some, so treat redaction as one layer: minimise first, redact what remains, and keep log retention short.
07. Common mistakes
08. Check your understanding
09. Apply it
In your own RAG assistant:
- Add access labels to every chunk at ingestion and build the retrieval filter from the verified session, inside the vector store query.
- Write the practice-project test: as one user, search with every other user's chunk text as the query and assert that none of their chunks come back. Make it fail once on purpose.
- Put a redacting filter on your log handlers, and on any trace or analytics exporter, with tests for each pattern you rely on.
- List the fields each prompt template sends, and remove any the task does not need.
10. Review prompt
Without looking back:
- Why can a system-prompt rule not keep one customer's documents away from another?
- What may the client still choose in a search request, and how does the server constrain it?
- Describe the strongest test for cross-user isolation in one sentence.
- Name three places besides the prompt where personal data from a chat can end up, and one limit of pattern-based redaction.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.