What the Spring AI, Auth0 and pgEdge advisories teach us about tenant isolation in RAG systems, and how to design it so an assistant never answers with someone else's documents.
Almost every B2B AI product ends up with the same component: a RAG that answers from each customer's documents. Contracts, tickets, meeting notes, internal manuals. And almost all of them start the same way: a demo with a single customer, a vector index with no tenant field and a prompt that says "only answer with this customer's information". When the second customer arrives, their documents go into the same index and someone adds a metadata filter. It works in testing, so it stays.
The problem is that this filter is, for all practical purposes, your access control. And the last few weeks have given us several examples of how fragile it is when treated as an implementation detail:
- Spring AI published several high-severity advisories on November 19 for the converters that translate its metadata filters into each vector store's query language. In Redis and Typesense, a crafted value could change the structure of the query and bypass a tenant or permission filter; in Typesense, parenthesised groups were also translated incorrectly; in Coherence, certain filter keys were interpreted as operations instead of field names [1][2][3][4]. The same day it warned that its Redis-backed semantic cache shared answers across every user of an application [5]. Versions 2.1.0 and 2.0.3, released November 20, fix 13 CVEs in total [6].
- Auth0 disclosed on November 10 that its FGA (fine-grained authorization) retriever for LangChain and LlamaIndex could reuse a permission check across documents mapped to the same object, so denied documents ended up in the model's context and in the answer [7].
- pgEdge RAG Server fixed in version 2.0.0 a flaw where its keyword index (BM25) was a single object shared by every request: under normal concurrent traffic, with no injection of any kind, a search could run against a corpus filtered by a different request [8].
- And on November 25 Lamplit Labs published an experiment that measures what many teams take for granted: what happens when permissions are enforced in the prompt, after search, inside the query, or forgotten in the cache [9].
OWASP already covers this in its Top 10 for LLM applications (LLM08:2025): where several groups of users share the same vector database, there is a risk of context leaking between them, and the mitigation it proposes is a permission-aware store with strict logical and access partitioning [14].
None of these cases needs a compromised model or a sophisticated attacker. This post is about designing isolation between customers (and between users with different permissions) in a RAG so it doesn't depend on everything going right.
This is the seventh post in our series on best practices for AI products. The previous one covered when you really need an LLM; today we look at tenant isolation in RAG.
1. Three ideas worth getting straight
The prompt is not access control. If a chunk from another customer reaches the context, you've already lost: every later control is a probability, not a guarantee. In the Lamplit Labs experiment, tagging disallowed documents as RESTRICTED and telling the model not to use them barely moved the result: a low-privilege user got the answer to 107 of 545 questions it shouldn't have been able to answer, against 122 with no check at all [9]. The author deliberately used a very small model and notes that a larger one would leak less often; but "less often" is still a rate, and access control needs a zero.
The tenant filter is a security query, and it has to fail closed. The question isn't whether you have a filter, but what happens when it doesn't apply: a value with odd characters, a mistranslated group, an empty condition, two requests at once. That is exactly what the Spring AI and pgEdge advisories describe [1][2][3][8]. If the default behaviour on error is "return unfiltered results", isolation depends on there never being errors.
Everything derived from a document inherits its permissions. Answer caches, semantic caches, conversation memory, summaries, embeddings. The Spring AI cache case [5] and the cache part of the Lamplit experiment [9] show the same thing: you can filter search perfectly and still hand one customer an answer built from another customer's documents.
2. What happened, in a bit more detail
Spring AI: the filter converter as a boundary
Spring AI offers a common filter language (Filter.Expression) that each integration translates into its database's syntax. It's a convenient abstraction, and that's exactly why it's easy to forget that underneath there's a query string being built from values.
- In Redis (CVE-2026-59361), the converter escaped only some of the characters RediSearch treats as syntax, and compound expressions were emitted without grouping, so operator precedence could change what the filter meant. The result: broader searches than intended, returning documents and embeddings from other tenants [2].
- In Typesense (CVE-2026-59369), values were escaped as JSON strings, but Typesense's filter tokenizer doesn't treat those as literals, so a crafted value could close the clause and add conditions of its own [1]. A second flaw (CVE-2026-59442) mistranslated parenthesised groups, so some conditions might not apply; if you can't upgrade, Spring recommends enforcing tenant constraints separately from the filter expression [3].
- In Coherence (CVE-2026-59344), certain quoted keys were interpreted as operations on the metadata object instead of field names. The advisory explicitly mentions applications that pass externally influenced or model-generated filter expressions to the vector store [4].
The pattern is familiar to anyone who has worked with SQL: building queries by concatenating values. What's new is where it shows up, and that the value may come from an LLM.
The semantic cache everyone shared
Advisory CVE-2026-59417, rated critical, describes a semantic cache where responses were separated only by the hash of the system prompt, with no user, session or tenant dimension. A response containing one user's data could be served to another who asked a similar question, and an attacker could prime a cache entry with their own content to be served to later users. Entries written through the advisor also never expired [5]. It's a residual gap from an earlier advisory (CVE-2026-59308) that had only addressed isolation by system prompt.
The fix is interesting because of how it changes the design: patched versions require a SemanticCacheScopeResolver that determines the scope in which responses are shared, and Spring asks for it to be derived from a trusted source, such as the authenticated principal, not from a value the user can choose. Without that component, auto-configuration no longer registers the cache [5][6].
Auth0 FGA: a reused check
The Auth0 flaw (CVE-2026-108167, CVSS 6.5) is subtler. The retriever checked permissions with Auth0 FGA, but when a single retrieval included several documents mapped to the same FGA object with different users, relations or contexts, it didn't distinguish between those checks. Denied documents ended up in the model's context. It's fixed in auth0-ai-langchain 1.0.2 and auth0-ai-llamaindex 1.0.3 [7]. Having a serious authorization system isn't enough if the piece that wires it into retrieval groups the questions wrongly.
pgEdge: isolation broken by concurrency
In pgEdge RAG Server (CVE-2026-125325), each request cleared the shared BM25 index, refilled it with its own filtered corpus and searched it, taking a separate lock for each step. Under concurrent requests, the steps interleaved [8]. Two details in the advisory are worth reading twice. First, normal load is enough. Second, upgrading doesn't tell you whether you were affected: affected responses can't be identified from the server's logs, so there's no retrospective check [8].
What Lamplit Labs measured
The Lamplit Labs experiment (about 20,000 documents, six access groups, five users and a small model, with code and data published) compares four strategies [9]:
- Prompt rule: the one above, 107 of 545 improper answers.
- Post-filter (search everything, then drop what isn't allowed) and pre-filter (permissions inside the query): no restricted document reached the prompt in 5,950 retrievals.
- But a shallow post-filter starves the lowest-privilege user: fetching 4 and filtering afterwards left that user with fewer than 4 documents on 95.9% of their questions. Fetching 100 matched the pre-filter, which needs no such tuning.
- Answer cache keyed on the question alone: 35 replies, across three runs, gave a user information its own pipeline couldn't have produced. Adding the user's group set to the key brought that to zero, at the cost of the cache hit rate dropping from 75% to 57.7%.
It's a lab experiment and the author is explicit about its limits, but it puts numbers on the three ideas in the previous section.
3. How we'd build it
3.1 Choose the isolation level before you choose the filter
Not every customer needs the same thing. The options, from most to least isolated:
- One index, collection or database per customer. Isolation comes from the infrastructure, not from a condition in the query. This is what we ask for when a customer has particularly sensitive data or contractual requirements. It has a cost: Qdrant, for example, warns that each collection carries its own overhead and recommends separate collections only for a limited number of tenants that need strict isolation [10].
- A partition or shard per customer. For multitenancy, pgvector recommends list partitioning or separate tables [11]; Qdrant offers user-defined sharding and a tiered mode where small tenants share a shard and large ones get their own [10].
- A shared collection with a tenant field. The most efficient option for many small customers, and the one that demands the most discipline: everything depends on the filter always being applied.
A useful rule: the isolation level is a product and contract decision, not just a performance one. Document it per customer or per plan, and have the code read it from configuration, not from assumptions.
3.2 The tenant comes from the token, never from the model or the request
The tenant identifier and the user's groups come from the authenticated session on the server. Not from a field in the request body, not from a header the client can set and, above all, not from anything the LLM generates. The model can help narrow a search (by date, by document type), but the security filter is set by your code, always, and combined with AND.
The safest way to get there is to make sure the rest of the code can't call the vector store directly: only a retriever that requires a security context and always applies it. An example with Qdrant and FastAPI:
from dataclasses import dataclass
from qdrant_client import QdrantClient, models
@dataclass(frozen=True)
class SecurityContext:
tenant_id: str # from the verified token, never from the body
groups: frozenset[str] # user's groups/roles, from the IdP
acl_version: int # bumped when the tenant's permissions change
class TenantScopedRetriever:
"""The only entry point to the vector store. Exposes no unscoped search."""
def __init__(self, client: QdrantClient, collection: str):
self._client = client
self._collection = collection
def search(self, ctx: SecurityContext, vector: list[float],
extra: models.Filter | None = None, limit: int = 8):
if not ctx.tenant_id or not ctx.groups:
# Fail closed: no scope, no results (and no swallowed exception)
raise PermissionError("missing security context")
must = [
models.FieldCondition(key="tenant_id",
match=models.MatchValue(value=ctx.tenant_id)),
models.FieldCondition(key="allowed_groups",
match=models.MatchAny(any=sorted(ctx.groups))),
]
# "Business" filters (proposed by the model or the UI) can only narrow:
# they're nested inside the must, never replace it.
if extra is not None:
must.append(extra)
hits = self._client.query_points(
collection_name=self._collection,
query=vector,
query_filter=models.Filter(must=must),
limit=limit,
).points
# Defence in depth: check every hit before it reaches the prompt.
for h in hits:
if h.payload.get("tenant_id") != ctx.tenant_id:
raise RuntimeError("cross-tenant hit") # alert, don't hide it
return hitsThree details matter more than the exact code. The security filter goes inside the query (pre-filter), not after it. A missing context is an error, not "no filter". And the final check on each hit isn't redundant: it's the one that would have warned you in a case like pgEdge or Auth0, where the filter believed it was working.
In Qdrant, if you use a shared collection, the tenant field should have a payload index; the docs also recommend flagging it with is_tenant so each tenant's data is co-located [10].
3.3 If you use pgvector, let Postgres be the gatekeeper
With pgvector you have an advantage: PostgreSQL row-level security (RLS). With RLS enabled, every normal query on the table only sees the rows the policy allows, and if there's no policy, the default is to see nothing [12]. That turns isolation into a property of the database rather than of every query someone on the team writes.
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
tenant_id uuid NOT NULL,
doc_id uuid NOT NULL,
content text NOT NULL,
embedding vector(1024) NOT NULL
);
ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
-- The table owner bypasses RLS unless you force it:
ALTER TABLE chunks FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON chunks
USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);
-- The app connects with a role that has no BYPASSRLS and doesn't own the table.
CREATE ROLE rag_app LOGIN; -- NOSUPERUSER NOBYPASSRLS by default
GRANT SELECT, INSERT, UPDATE, DELETE ON chunks TO rag_app;And in the application, the tenant is set per transaction, from the verified session:
async def search_chunks(conn, ctx: SecurityContext, query_vec, k: int = 8):
async with conn.transaction():
# is_local = true: the value dies with the transaction (matters with pools)
await conn.execute("SELECT set_config('app.tenant_id', $1, true)", ctx.tenant_id)
return await conn.fetch(
"SELECT id, doc_id, content FROM chunks "
"ORDER BY embedding <=> $1 LIMIT $2",
query_vec, k,
)If someone forgets to set app.tenant_id, current_setting(..., true) returns NULL, the comparison isn't true and the query returns no rows: it fails closed. The traps to know about are all in the PostgreSQL docs: superusers and roles with BYPASSRLS always bypass policies, and so does the table owner unless you use FORCE ROW LEVEL SECURITY [12]. Ingestion and migration jobs often run with exactly those roles, so check which role each process uses.
A performance warning that is also a correctness one: pgvector explains that with approximate indexes like HNSW, filtering is applied after the index is scanned, so selective conditions can return fewer results than requested; since 0.8.0 it offers iterative index scans (hnsw.iterative_scan) to mitigate this, and for multitenancy it recommends partitioning or separate tables [11]. A small customer in a huge table can get answers with little or no context, and the model will fill the gap. It isn't a leak, but it is a quality bug that only small customers will see.
3.4 Filters as data, never as strings
The Spring AI flaws are, at heart, injection into the vector store's query language [1][2][4]. The rules are the usual ones:
- Use your client's structured filter API (objects, not strings) and keep the libraries that do the translation up to date. If you use Spring AI, that means 2.0.3 or 2.1.0 [6].
- Allow-list keys and types. If the model or the UI can propose filters ("self-query retrievers"), check they only use permitted fields (
date,document_type) with values of the expected type, and reject everything else. Never accept a filter from the model ontenant_idorallowed_groups. - Keep the security filter separate from the business filter. That's literally the mitigation Spring proposes for the Typesense grouping flaw: enforce tenant constraints separately from the filter expression [3]. In the example in 3.2, the business filter is nested inside the security
must. - Deletes filter too. In the same batch, Spring fixed an injection in Typesense delete-by-ID that allowed unintended document deletion [6]. A delete with a broken filter hits another customer just as a read does.
3.5 Caches, memory and summaries: scoped and versioned
Every time you store something derived from a customer's documents, the key has to include its scope:
import hashlib, json
def cache_key(ctx: SecurityContext, normalized_question: str, prompt_version: str) -> str:
scope = {
"tenant": ctx.tenant_id,
"groups": sorted(ctx.groups), # users with different permissions don't share
"acl": ctx.acl_version, # revoking a permission invalidates entries
"prompt": prompt_version,
}
raw = json.dumps(scope, sort_keys=True) + "\n" + normalized_question
return hashlib.sha256(raw.encode()).hexdigest()- Answer cache and semantic cache: tenant, group set and permissions version in the key, as both Lamplit Labs and the Spring AI fix recommend [5][9]. And with expiry: an entry in a cache that never expires outlives a revoked permission.
- Conversation memory: loaded by a session identifier verified on the server and bound to the tenant; an unknown session is an error, not a default conversation.
- Summaries, embeddings and generated records: inherit the source document's permissions and are deleted with it. Lamplit flags this as one of the gaps its experiment doesn't cover [9].
The price is a lower cache hit rate (in the Lamplit experiment, from 75% to 57.7%) [9]. That's the price of the cache being correct: if two users can see different documents, they can't share an answer built from them.
3.6 Per-document permissions: sync is part of the control
As soon as you move from "each customer sees their own data" to "each user sees what they see in SharePoint, Drive or Confluence", two new problems appear:
- Permission lag. Between someone losing access to a folder in the source tool and your index finding out, there's a leak window. Measure it, set a target and, for sensitive sources, consider checking the permission at the source at query time for the retrieved documents.
- Who decides. If you delegate to an authorization system (such as FGA), the integration with the retriever is security code: the Auth0 flaw wasn't in the authorization engine, but in how checks were grouped during retrieval [7]. Review how each chunk maps to an authorization object and test documents that share an object but have different permissions.
3.7 Test it like access control, in CI
If isolation is a security control, it deserves security tests, not just a manual check with the admin account (which, as Lamplit points out, will never see the problem [9]):
# tests/test_tenant_isolation.py
import asyncio, pytest
CANARY = "zx-canary-7f3a" # unique string seeded only in tenant B's documents
@pytest.mark.asyncio
async def test_tenant_a_never_sees_tenant_b(rag, ctx_tenant_a):
ans = await rag.answer(ctx_tenant_a, f"What does document {CANARY} say?")
assert CANARY not in ans.text
assert all(d.tenant_id == ctx_tenant_a.tenant_id for d in ans.retrieved)
@pytest.mark.asyncio
async def test_isolation_under_concurrency(rag, ctx_tenant_a, ctx_tenant_b):
# The pgEdge bug only showed up with simultaneous requests
ctxs = [ctx_tenant_a if i % 2 else ctx_tenant_b for i in range(200)]
answers = await asyncio.gather(*(rag.answer(c, "summarise the contract") for c in ctxs))
for ctx, ans in zip(ctxs, answers):
assert all(d.tenant_id == ctx.tenant_id for d in ans.retrieved)
@pytest.mark.parametrize("evil", ['x" || tenant_id:*', "a) OR (1=1", "`", "\\", "*"])
def test_hostile_filter_values_fail_closed(retriever, ctx_tenant_a, evil):
hits = retriever.search(ctx_tenant_a, VEC, extra=business_filter(doc_type=evil))
assert all(h.payload["tenant_id"] == ctx_tenant_a.tenant_id for h in hits)What we always cover: a least-privilege user for each role, canary documents with unique strings in other tenants, the cache included in the path (not just the retriever), concurrent load and hostile values in every field that ends up in a filter.
And in production, log the IDs of the retrieved documents on every request (IDs, not content, as we covered in the post on traces). The pgEdge advisory says affected responses couldn't be identified from the logs [8]. With the doc_ids and the tenant of each request, you could answer "did any customer receive another customer's documents?" with a query instead of a guess. And the check in 3.2 can become a metric with an alert: any hit from another tenant reaching the retriever is an incident.
4. And if it has already happened
If a customer writes in because the assistant answered with someone else's data:
- Switch the feature off for the tenants you can't separate with certainty, until you have a trace showing the filter holds.
- Preserve the evidence: request ID, retrieved documents, cache entries involved, tool calls.
- Find the layer that crossed the boundary: index, cache, memory or tool. The user being authenticated tells you nothing; what matters is whether that identity reached the query.
- Purge derived data: cache entries, memories and summaries generated during the affected window.
- Assess notification. If another customer's personal data was exposed, it's a personal data breach under the GDPR, and the controller must notify the supervisory authority without undue delay and, where feasible, within 72 hours (Art. 33) [13]. In a B2B product your customer is usually the controller and you the processor, and Art. 33(2) requires you to inform them without undue delay. This isn't a substitute for legal advice on your case.
Checklist: tenant isolation in RAG
Design
- [ ] There's a decided, documented isolation level per customer or plan (own index, partition or shared collection).
- [ ] Customers with sensitive data or contractual requirements get their own index, collection or partition.
- [ ] No permission is enforced only in the prompt.
Query
- [ ] Tenant and groups come from the session verified on the server, never from the request body or the model.
- [ ] There's a single retriever with mandatory scope; code can't call the vector store without it.
- [ ] The security filter is part of the query (pre-filter) and a missing context is an error.
- [ ] Every hit is checked before it enters the prompt, and a hit from another tenant triggers an alert.
- [ ] With pgvector: RLS enabled and forced, an app role without
BYPASSRLSthat doesn't own the table, tenant set per transaction.
Filters
- [ ] Filters are built with the structured API, never by concatenating strings.
- [ ] Filters proposed by the model or the UI go through an allow-list of fields and types and can only narrow the search.
- [ ] Deletes apply the same scope as reads.
- [ ] RAG and vector store libraries are up to date (e.g. Spring AI 2.0.3/2.1.0,
auth0-ai-langchain≥ 1.0.2,auth0-ai-llamaindex≥ 1.0.3, pgEdge RAG Server ≥ 2.0.0).
Derived data
- [ ] Cache keys (answer, semantic and retrieval caches) include tenant, group set and permissions version.
- [ ] Cache entries expire.
- [ ] Memory, summaries and embeddings inherit the source document's permissions and are deleted with it.
Permissions and sync
- [ ] We measure the lag between a permission change at the source and its reflection in the index.
- [ ] The integration with the authorization system has tests with documents that share an object but have different permissions.
Testing and operations
- [ ] CI tests isolation with least-privilege users, canary documents, concurrent load and hostile filter values, cache included.
- [ ] We log the retrieved document IDs and the tenant of every request.
- [ ] We have a procedure to switch the feature off per tenant, purge derived data and decide on notification.
Conclusion
A multi-tenant RAG is an access control problem before it's a relevance problem. The advisories of the last few weeks show it from several angles: a filter that can be rewritten with a crafted value, a cache that doesn't know who's asking, a permission check reused where it shouldn't be, a shared index that gets trampled by concurrency. None of them is fixed with a better prompt.
What works is boring and well known: the tenant comes from identity, is applied in the query, fails closed, is checked before the prompt and travels with everything derived from the document. And it's tested like any other security control, with the least-privileged user and real load, not with the admin account in a demo.
If you'd like a second pair of eyes on how your RAG keeps customers apart (where the filter is applied, what's in your caches and what would happen with two requests at once), we'd be happy to have that conversation. No pitch: a 30-minute call with one of our engineers. Let's talk.