Permission-aware retrieval for two user scopes
Filter retrieval by the caller's permissions, prove a denied document never appears, and scope caches to identity and data.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.
In short
If a document the caller is not allowed to see reaches the model, it can leak into the answer, no matter what the prompt says. So permission filtering belongs inside the retrieval query, based on the caller's verified identity. You prove it with tests that run the same question under two scopes, and you include identity and data version in every cache key.
Think of it like this: Permission filtering at retrieval is the locked filing cabinet; telling the model not to mention secrets is a sticky note on an open drawer.
Explained simply
A knowledge assistant often holds documents that not everyone may read. At Contoso, support agents can read public and internal articles, but only the billing team may read billing procedures. The assistant must respect that, every time.
Telling the model not to reveal restricted text is not enough. If the text reaches the model, it can appear in the answer, be paraphrased, or be pulled out by a clever question. The only safe rule is that restricted text never reaches the model for a caller who may not see it.
So the permission check happens inside the search. The server works out the caller's scopes from their verified login, and every search query includes a filter that keeps only chunks whose visibility is in those scopes.
Then you prove it. A test runs the same question as a support agent and as a billing user and checks that a billing-only canary document appears for one and never for the other. Caches need the same care: a stored answer must only be reused for a caller with the same scopes.
Press Play on a diagram to walk through it one step at a time.
- Caller to API: Question plus signed token1Question plus signed token
- 2Verify token, derive scopesAPI to API: Verify token, derive scopes
- API to PostgreSQL: Search WHERE visibility = ANY(scopes)3Search WHERE visibility = ANY(scopes)
- PostgreSQL to API: Only permitted chunks4Only permitted chunks
- API to Model: Prompt with permitted evidence5Prompt with permitted evidence
- Model to API: Answer with citations6Answer with citations
- API to Caller: Answer, citations checked again7Answer, citations checked again
- Prompt says do not reveal billing text
- Filter results in Python after LIMIT
- Scopes read from the request body
- Cache keyed by question only
- Restricted text never retrieved
- Filter in SQL before LIMIT, plus RLS
- Scopes derived from a verified token
- Cache keyed by scopes and data version
In depth
Filtering by scope inside the query
The API verifies the caller's token, looks up their scopes on the server and passes them to the search function as a list, for example ['public', 'internal']. Each candidate query, keyword and vector, includes visibility = ANY($scopes) in its WHERE clause alongside status = 'active'. Because the filter runs before LIMIT, the top 20 are the top 20 the caller may see, and no restricted chunk is ever ranked, reranked or logged.
Never accept scopes from the request body or a query string. Never filter in Python after fetching results either: it leaves you with fewer results than intended, and restricted text has already passed through your process, where logs or traces may capture it.
- Scopes come from the verified identity only
- Filter in every candidate query, before LIMIT
- No restricted text in logs, traces or caches
- Re-check citations against visible evidence at answer time
Row-level security as a second guard
PostgreSQL row-level security (RLS) lets the database itself refuse rows. After ALTER TABLE chunks ENABLE ROW LEVEL SECURITY, a policy such as USING (visibility = ANY(string_to_array(current_setting('app.scopes', true), ','))) limits which rows a role can read. The API sets app.scopes per request with SET LOCAL inside a transaction, so the value cannot leak to the next request on a pooled connection.
Know the exceptions. Superusers and roles with BYPASSRLS skip policies, and so does the table owner unless you also run ALTER TABLE ... FORCE ROW LEVEL SECURITY. So the application should connect as a separate, non-owner role. RLS does not replace the WHERE filter; it catches the day someone writes a new query and forgets it.
- 1Answer check
Citations must be in the caller's visible evidence
- 2Query filter
visibility = ANY(scopes) before LIMIT
- 3Row-level security
Database policy for the app role
- 4Identity
Verified token mapped to scopes on the server
Testing with two scopes and a canary
A permission test needs a positive and a negative half. Put a unique phrase, such as canary-chargeback-77, in the billing-only document KB-9001. Run several questions that should find it as a billing user and assert it is found. Run the same questions as a support user and assert that neither the doc_id nor the phrase appears in results, the prompt sent to the model stub, the answer, or the logs.
Without the positive half, the negative test could pass simply because the document is never retrieved for anyone. Run the test in CI on every change to retrieval code, prompts or schema, and include an RLS test that queries the table directly as the app role with the support scopes.
Cache keys that respect identity and data
Caching retrieval results or answers saves time and money, but a cache is a shortcut around your permission filter. If the key is only the question text, a billing user's answer, built from billing documents, can be served to a support agent asking the same thing.
Build the key from everything that changes the result: the normalized question, the caller's sorted scopes, the index or data version, the embedding model, and the retrieval and prompt settings. Using scopes rather than user ID lets callers with identical permissions share entries. When ingest changes the data version, old entries simply stop matching. Hash the key so personal data does not sit in plain text in the cache.
- Key: question + sorted scopes + data version + model + settings
- Scopes, not user ID, allow safe sharing
- New ingest run = new data version
- Hash the key; set a time to live
Learn it in 4 short steps
About 55m each. Track them with a timer in your plan.
- 1Filter by caller scope in the query~55m
- 2Test a denied document with two scopes~55m
- 3Consider row-level security~55m
- 4Include identity and data version in cache keys~55m
Key points
- Derive scopes from a verified token on the server, never from a field the client can set.
- Apply the visibility filter inside each candidate query, before LIMIT and before reranking.
- Row-level security in PostgreSQL adds a second guard in the database itself.
- Test with a canary document: a billing-only chunk must never appear for a support-only caller.
- Cache keys must include the caller's scopes and the index version, or one user's answer can serve another.
Key terms
Tap a card to flip it. 0/5 known
Examples
def test_billing_doc_hidden_from_support(search):
q = "What is the chargeback fee for enterprise invoices?"
support = search(q, scopes=["public", "internal"])
billing = search(q, scopes=["public", "internal", "billing"])
assert "KB-9001" not in {r.doc_id for r in support}
assert "KB-9001" in {r.doc_id for r in billing}The second assertion matters too: it proves the canary is findable, so the first one is not passing by accident.
A row-level security policy for chunks
Prerequisites: a local PostgreSQL where you own the chunks table. Step 1: create a non-owner role kb_app and grant it SELECT. Step 2: enable RLS and add a policy that reads scopes from a setting. Step 3: in a transaction, SET LOCAL ROLE kb_app and SET LOCAL app.scopes. Expected evidence: with 'public,internal' the count of billing chunks is 0; with 'public,internal,billing' it is above 0. Rollback: DROP POLICY and DISABLE ROW LEVEL SECURITY.
CREATE ROLE kb_app LOGIN PASSWORD 'example-only';
GRANT SELECT ON chunks TO kb_app;
ALTER TABLE chunks ENABLE ROW LEVEL SECURITY;
CREATE POLICY chunks_by_scope ON chunks FOR SELECT TO kb_app
USING (visibility = ANY (string_to_array(current_setting('app.scopes', true), ',')));
BEGIN;
SET LOCAL ROLE kb_app;
SET LOCAL app.scopes = 'public,internal';
SELECT count(*) FROM chunks WHERE visibility = 'billing'; -- expect 0
COMMIT;A scope-aware cache key
Two support agents ask 'What is the refund window?' and should share one cache entry. A billing user asking the same must get a separate entry. After tonight's ingest, all entries must stop matching. Step 1: normalize the question. Step 2: sort the scopes. Step 3: include the data version and settings. Step 4: hash. Expected evidence: the two support keys are equal; the billing key differs; changing data_version changes every key.
import hashlib, json
def cache_key(question: str, scopes: list[str], data_version: str, cfg: dict) -> str:
payload = {
"q": " ".join(question.lower().split()),
"scopes": sorted(scopes),
"data": data_version,
"model": cfg["embedding_model"],
"settings": cfg["retrieval_version"],
}
raw = json.dumps(payload, sort_keys=True)
return "rag:" + hashlib.sha256(raw.encode()).hexdigest()Quick reference
- Restricted text must never reach the model; prompts are not access control
- Scopes come from a verified token, never from the request body
- WHERE visibility = ANY($scopes) in every candidate query, before LIMIT
- RLS: ENABLE ROW LEVEL SECURITY + CREATE POLICY; owner bypasses unless FORCE
- Set per-request scopes with SET LOCAL inside a transaction
- Permission tests need a positive and a negative case with a canary
- Cache key = question + sorted scopes + data version + model + settings
Common mistakes
- Retrieving everything and asking the model to ignore restricted text.
- Filtering in Python after fetching the top 10, which leaks timing and leaves too few results.
- Caching answers by question text alone, so a billing user's answer is served to a support user.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add a scopes parameter to your keyword and vector search functions and include visibility = ANY(%s) in both queries.
- Exercise 2medium
Write a pytest test that runs five billing questions under two scopes and checks the canary doc_id and phrase never appear for the support scope, in results or in the prompt sent to the model stub.
- Exercise 3hard
Add RLS as a second guard, connect the app as a non-owner role, and show that a deliberately unfiltered query still returns no billing rows for a support request.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is it enough to hide restricted citations in the answer?
- No. The model has already read the restricted text and may paraphrase it. Filter before retrieval so the text never reaches the model.
- Do I need row-level security if my queries already filter?
- It is not required, but it is a cheap second guard against a future query that forgets the filter.
- Should cache entries be per user?
- Per scope set is enough and allows sharing between users with identical permissions. Add the user ID only if results depend on more than scopes.