AI security
RAG: when the assistant cites documents the user must not see
A RAG without authorization at retrieval time is a data leak with a chat interface. Token-derived filter, Bedrock metadata, post-retrieval check and a cross-tenant test in CI.
The scenario shows up in almost every RAG platform audit: SharePoint, Confluence and the shared drive are indexed into a single vector store, an assistant is plugged on top, and it answers beautifully. Including « what is the CFO’s salary? », because the compensation PDF was indexed like everything else. The model leaked nothing: it did exactly what it was asked, with the data it was given.
The problem is architectural. A vector store knows nothing about your users. If authorization isn’t enforced at search time, it doesn’t exist. OWASP files this risk in the 2025 LLM Top 10 under LLM02 (Sensitive Information Disclosure) and LLM08 (Vector and Embedding Weaknesses), which explicitly mentions insufficient access control and cross-tenant data mixing in vector databases.
This article follows threat → control → evidence, using Amazon Bedrock Knowledge Bases as the thread. The principle applies as-is to OpenSearch or pgvector used directly.
The threat: retrieval doesn’t know who is asking
Three failures come up repeatedly in engagements.
- Single index, no filter. Everything is retrievable by everyone. Semantic similarity does the rest: the user doesn’t need to know the document’s name.
- Filter chosen by the client or the model. The
tenant_idarrives in the HTTP body, or an agent builds the filter itself. A user who edits the request, or a prompt injection (LLM01), switches tenant. - Direct access to the retrieval API. Users or an application hold
bedrock:Retrieveon the Knowledge Base: the app may filter, but nothing prevents calling the API without a filter.
One more point is often forgotten: source ACLs (SharePoint, Drive) change, the index doesn’t. A document whose access was revoked stays retrievable until its metadata is resynced.
Control 1: authorization metadata at ingestion
Every document carries its authorization attributes. With Bedrock Knowledge Bases on S3, you drop a contract-acme.pdf.metadata.json file next to contract-acme.pdf (documentation):
{
"metadataAttributes": {
"tenant_id": "acme",
"acl_groups": ["finance", "management"],
"classification": "confidential"
}
}
This metadata must be generated by the ingestion pipeline from the source ACLs, never typed by hand. Schedule a regular resync (daily at least) and treat revoking a permission as an event that triggers re-indexing of the affected document.
Design rule: a document without tenant_id is not indexed. A loud rejection at ingestion beats a « public by default » document.
Control 2: the filter is derived from the token, server-side
The backend extracts tenant_id and groups from the validated JWT (signature, iss, aud, expiry) and builds the filter. It never accepts these values from the client or the model. The Retrieve API takes a filter in retrievalConfiguration.vectorSearchConfiguration.filter (reference):
import boto3
bedrock = boto3.client("bedrock-agent-runtime", region_name="eu-west-3")
KB_ID = "KBXXXXXXXX"
class AuthorizationError(Exception):
pass
def build_filter(claims: dict) -> dict:
tenant = claims.get("custom:tenant_id")
groups = claims.get("cognito:groups", [])
if not tenant:
raise AuthorizationError("token without tenant")
return {
"andAll": [
{"equals": {"key": "tenant_id", "value": tenant}},
# readable if one of the doc's ACL groups is among the user's groups
{"orAll": [
{"in": {"key": "acl_groups", "value": groups}},
{"equals": {"key": "classification", "value": "public"}},
]},
]
}
def retrieve(query: str, claims: dict, top_k: int = 6) -> list[dict]:
tenant = claims["custom:tenant_id"]
resp = bedrock.retrieve(
knowledgeBaseId=KB_ID,
retrievalQuery={"text": query},
retrievalConfiguration={"vectorSearchConfiguration": {
"numberOfResults": top_k,
"filter": build_filter(claims),
}},
)
results = resp["retrievalResults"]
# barrier 2: never trust the filter alone
for r in results:
if r.get("metadata", {}).get("tenant_id") != tenant:
raise AuthorizationError(f"out-of-tenant chunk: {r['location']}")
return results
Two details to validate on your version and vector store: how an in filter behaves on a list attribute (test it, don’t assume), and whether metadata is actually returned in retrievalResults[].metadata. That is precisely what the test in control 4 checks.
The same logic applies to RetrieveAndGenerate, which accepts the same filter block: the filter is always built by the backend. If you go through a Bedrock agent, the retrieval tool must receive the user’s identity outside the model’s context (see least privilege for agents).
Control 3: close the back door with IAM
The filter is only worth something if retrieval can’t be called any other way. Only the RAG backend role may invoke Retrieve; human roles, including admins of dev accounts, may not:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "OnlyRagBackendCanRetrieve",
"Effect": "Deny",
"Action": ["bedrock:Retrieve", "bedrock:RetrieveAndGenerate"],
"Resource": "*",
"Condition": {
"ArnNotLike": {
"aws:PrincipalArn": "arn:aws:iam::*:role/rag-backend-prod"
}
}
}
]
}
Apply as an SCP on the production OU, after checking that no other legitimate role (an evaluation pipeline, for instance) needs it; add it to the list if so. Apply the same logic to source buckets and the underlying vector store (OpenSearch Serverless, Aurora pgvector): the Knowledge Base role and data administrators, nobody else.
For richer rules (per department, role, project), an alternative is to externalise the decision to Amazon Verified Permissions with Cedar policies, as described in an AWS article on multi-tenant RAG (see sources). The upside: versioned, auditable rules, changeable without redeploying. The cost: one more dependency on the critical path. For an SMB with two authorization dimensions (tenant, group), the filter above is enough.
Control 4: the evidence, a cross-tenant test in CI
An auditor or a B2B customer will ask: « how do you demonstrate that customer A cannot see customer B’s documents? » The answer is an automated test, not an architecture diagram. Index canary documents per tenant, each containing a unique string, and try to retrieve them from the wrong account:
from rag import retrieve
CLAIMS_A = {"custom:tenant_id": "acme", "cognito:groups": ["finance"]}
CLAIMS_B = {"custom:tenant_id": "globex", "cognito:groups": ["finance"]}
def texts(results):
return " ".join(r["content"]["text"] for r in results)
def test_tenant_a_cannot_see_canary_b():
assert "CANARY-GLOBEX-7f3a" not in texts(retrieve("CANARY-GLOBEX-7f3a", CLAIMS_A))
def test_tenant_b_cannot_see_canary_a():
assert "CANARY-ACME-91c2" not in texts(retrieve("CANARY-ACME-91c2", CLAIMS_B))
def test_finance_group_cannot_see_hr_document():
assert "CANARY-ACME-HR-44d0" not in texts(retrieve("CANARY-ACME-HR-44d0", CLAIMS_A))
def test_tenant_a_sees_its_own_canary():
assert "CANARY-ACME-91c2" in texts(retrieve("CANARY-ACME-91c2", CLAIMS_A))
The last test matters as much as the others: it guarantees the filter doesn’t return « nothing » to everyone, which would pass the negative tests for the wrong reasons. Run the suite in GitHub Actions on every change to the ingestion pipeline or KB configuration, and archive the report: it is dated, replayable evidence.
Add detection. Enable Bedrock invocation logging (while controlling what it contains, a topic for a separate article) and alert on the AuthorizationError from the post-retrieval check: an out-of-tenant chunk surfacing despite the filter is either a misconfiguration or an attempt, and either way you want to know.
Common pitfalls
- Caches: a response or embedding cache keyed on the question alone serves tenant A’s answer to tenant B. Include tenant and groups in the key.
- Conversation summaries and titles stored without isolation: they contain document excerpts.
- Cited sources: never display a link to a document the user can’t access, even if the text is filtered.
- pgvector: if you run the database yourself, PostgreSQL Row Level Security on the chunks table, with
tenant_idset per session, gives a barrier independent of application code. On OpenSearch, prefer one index per tenant when contractual requirements are strong; metadata filtering remains logical isolation.
Conclusion
A safe RAG comes down to four elements: authorization metadata derived from source ACLs, a server-side filter built from the token, retrieval access reserved to the backend, and a cross-tenant test replayed in CI. If your internal assistant or RAG product is already in production and nobody has tried to make it quote another tenant’s document, the AI & Bedrock Security Audit includes exactly that test.
Sources: OWASP LLM02:2025 Sensitive Information Disclosure, OWASP LLM08:2025 Vector and Embedding Weaknesses, AWS — Knowledge Base metadata and filtering, AWS — Configure and customize queries, AWS ML Blog — Multi-tenancy in RAG applications in a single Amazon Bedrock knowledge base with metadata filtering, Amazon Verified Permissions.
Found this useful? Share it.
Go further
A topic, a project, a question?
Distribuée supports demanding SMBs on cloud security, CI/CD supply chain and AI security.
Book 15 min