ATS Global

An assistant that knows who's asking: building a permission-aware RAG service

Learn how to build a permission-aware AI assistant using Retrieval-Augmented Generation (RAG). This article explains role-based document access, secure hybrid search, live permission verification, automated document ingestion, expert-approved knowledge updates, and grounded AI responses using Python, FastAPI, and OpenSearch.

AI ENGINEERINGPublished: NOV 30, 202610 min readBy Mohammed Izhaar Haq Share
An assistant that knows who's asking: building a permission-aware RAG service

How we added an AI assistant to a role-based enterprise portal without leaking restricted documents, and made the knowledge base improve every time an expert approves a fix.

  • Ordinary RAG ranks by relevance only, so it will happily feed a restricted document to the model.
  • We filter by the user's roles inside the search query, then re-check live permissions before the model sees anything.
  • Roles are looked up server-side from the user's token and never taken from the request.
  • Documents and expert-approved fixes are indexed automatically from the portal's own webhooks, with no re-indexing jobs.

ChallengeAdd an AI assistant to a portal where different roles see different content, without leaking restricted documents
ApproachPermission filtering in the search query, a live re-check before answering, hybrid retrieval
OutcomeGrounded, cited answers that respect the portal's own permissions; approved knowledge searchable within seconds
StackPython, FastAPI, OpenSearch, a local embedding model, any OpenAI-compatible LLM

The problem with ordinary RAG

Retrieval-augmented generation (RAG) is now the standard way to put an assistant on top of company documents. It searches an index for the passages most relevant to a question, then asks a language model to write an answer from them.

The catch is that ordinary RAG ranks by relevance alone. It has no idea who is asking. In a portal where field staff, managers and external partners log into the same site and see different content, that causes three problems.

Data leakage. If a restricted procedure is the best match for a partner's question, a standard pipeline hands it to the model, and the model uses it. A system prompt saying "don't reveal confidential information" doesn't fix this. Once the model has read a passage, assume the user can get it out.

One answer for everyone. A senior engineer and a first-week employee get the same wording. It's too shallow for one and too dense for the other.

Stale knowledge. The most useful answers often come from fixes experts worked out last week, not from the manual. If adding them requires a manual re-indexing job, they never get added.

Constraints we designed around

  • The portal owns identity and permissions. The assistant must reuse the portal's roles, not keep a parallel user list that drifts out of sync.
  • Roles can't come from the request. A caller who can name their own roles can name any role. Roles have to be looked up server-side from the user's token.
  • Webhooks carry only metadata. The portal's workflow events can call a URL with a JSON payload, but never with a file attached.
  • Data stays in-house. Embeddings and the index run on-premises, and the language model must be replaceable, including with a local one.

These four constraints drive almost every decision below.

Architecture

The assistant is a separate Python service that sits next to the portal. The portal is both the front door, through a chat widget, and the source of truth for who can see what. The service talks to three backing components: an embedding model, a combined vector and keyword index, and a language model.

System architecture: portal, RAG service, and models & storage

The portal is the source of truth for permissions. The RAG service keeps no user list of its own. On every query it asks the portal who the caller is, and before answering it checks again that they can still view each source.

The service is split into API routes (answer, search, knowledge entries, documents, access control, health) and the services behind them (embedding client, hybrid retrieval, ingestion pipeline, live permission check, answer generation, auth guards). The search route runs the retrieval half of the pipeline without calling the LLM, which makes it useful for debugging and for building evaluation sets.

Ingestion: labelling every passage with who may see it

Content enters through two paths. Both are triggered by the portal's own workflow events, so nobody has to run an indexing job.

Documents (manuals, reference PDFs). The webhook can't carry the file, so the service receives the document's id and downloads the file through the portal's API using a service account. A layout-aware parser converts it to text and keeps tables intact, which matters for spec sheets and wiring tables. A token-aware chunker then splits it into overlapping passages sized for the embedding model.

Expert-approved knowledge entries. When an expert approves a fix (problem, cause, resolution), the approval event pushes it to the service as a single passage. A rejection uses the same webhook and removes the passage.

Both paths then read the roles that can view the source entry and store them on every passage. That label is what the search query filters on later.

Ingestion flow: documents and approved knowledge entries

Both paths end in the same steps: tag permissions, embed with the local model, index. New content is searchable at once.

One detail worth copying: re-ingesting a document deletes all of its old passages first. Overwriting by id alone would leave the tail of a longer previous version searchable, which is stale content you thought you had removed.

Answering: two permission checks

When a user asks a question, the widget sends it with the user's own token. The service resolves that token to a role list through the portal. The list never comes from the request body.

Question to answer: the nine-step sequence

Nine steps from question to streamed answer. If any check fails, the request stops. A missing or rejected token returns 401, and a source the user has lost access to is dropped, not replaced.

Check 1: a hard filter inside the search query

The role filter is part of the search query itself, not a re-ranking step afterwards. A restricted passage never becomes a candidate, so it can't reach the model.

This choice matters. If you retrieve the top 10 and then filter, a user with narrow access can end up with zero usable results, because all ten were restricted. Filtering inside the query means the top results are the best matches among what this user may see.

python

def acl_filter(user_role_ids: list[str]) -> dict:
   # Never skip this when the role list is empty. A terms filter on an
   # empty list matches nothing, which is the point: a caller whose roles
   # could not be established sees zero passages, not every passage.
   return {"terms": {"allowed_roles": user_role_ids}}

One detail is easy to get wrong. If the filter were added "only when the user has roles", an empty role list would mean no restrictions. Making it unconditional turns that failure into zero results instead of everything.

Check 2: a live re-check before the model reads anything

Permission labels are written at ingestion time, and the portal sends no event when permissions change later. So after ranking, the service re-reads the live permissions of each source in the final shortlist and drops any the user can no longer view.

Doing this after ranking keeps it cheap: one lookup per distinct source in the top results, not one per candidate. The result is that a revoked document stops appearing immediately, even though the index label is out of date.

Hybrid retrieval with rank fusion

Vector search finds passages by meaning ("the unit won't power on"). Keyword search finds exact identifiers such as error and part codes, which embeddings often blur. In technical content you need both.

The service runs both searches concurrently, both permission-filtered, and merges them with Reciprocal Rank Fusion. Their raw scores aren't on the same scale (cosine similarity is bounded, BM25 isn't), so the merge uses only rank positions.

python

def reciprocal_rank_fusion(result_lists, k=60):
   # Cosine similarity (0-1) and BM25 (unbounded) can't be added directly.
   # Use rank positions only: a passage ranked 1st by both strategies beats
   # one ranked 1st by a single strategy.
   scores, hits = {}, {}
   for results in result_lists:
       for rank, hit in enumerate(results, start=1):
           hits[hit["_id"]] = hit
           scores[hit["_id"]] = scores.get(hit["_id"], 0.0) + 1.0 / (k + rank)
   return sorted(((hits[i], s) for i, s in scores.items()),
                 key=lambda pair: pair[1], reverse=True)

A passage that both strategies rank highly rises to the top. That is usually the one you want.

Grounded generation, styled by role

The model receives the permitted passages as numbered sources. Its instructions are to use only those sources, cite them inline as [1], [2], and say plainly when the answer isn't there. Without an explicit way to say "not in the sources", a model will fill the gap from memory and produce something fluent and wrong.

The user's role also picks one of two writing styles. Specialists get precise wording with exact codes and values. Everyone else gets plain language with acronyms spelled out. Both styles end by restating the grounding rule, because "give exact part numbers" must never read as permission to invent one.

ScenarioWhat happens
Specialist asks a technical questionGets the exact procedure, codes and settings, each claim cited to its source
Partner asks for a restricted procedure"The sources I can use don't cover that." The model never saw the document, so there was nothing to withhold

The second row is the point of the whole design. We don't rely on the model to keep a secret. It never had the secret.

A knowledge base that improves with use

The feature users notice most isn't the search. It's the loop around it.

When the assistant has no good answer, the person who solves the problem records the fix as a draft entry. A subject-matter expert reviews it in the portal, and on approval it is indexed within seconds, so the next person with the same problem finds it. Drafts and rejected entries are never searchable. The expert's approval is the only quality gate, and the only way knowledge gets published.


The knowledge loop: ask, answer, record the fix, expert approves, indexed

No manual re-ingestion and no nightly batch. The expert's approval is what publishes knowledge.

Engineering decisions worth calling out

  • Fail closed everywhere. No token returns 401. An unset webhook secret rejects every write. Missing portal credentials return an error instead of quietly skipping the file fetch. An empty role list is a valid answer ("this user has no roles"), so the code never uses it to mean "we couldn't check".
  • Keep heavy work off the event loop. Document parsing is CPU-bound and synchronous, so it runs in a thread pool. Otherwise one large PDF would stall every other request, including health probes.
  • Searchable immediately. Writes refresh the index right away. Without that, a user who uploads a document and searches straight away finds nothing and assumes the system is broken.
  • Swappable models. The LLM is any OpenAI-compatible endpoint, set by configuration. Pointing it at a local model keeps all data on-premises with no code change.
  • Operable permissions. An access-control endpoint reports how many passages haven't had their permissions confirmed recently, and can re-sync one entry on demand.
  • Probes that don't hang. Readiness checks have short timeouts, so a stuck dependency reports "not ready" instead of holding the probe open.

Outcome

  • Restricted content can't reach the model. Permissions are enforced by the search query and re-verified live, not by asking the model to keep secrets.
  • One assistant for every audience. The same approved content produces expert-level or plain-language answers, depending on the user's role.
  • No re-indexing chores. Documents and approved fixes flow in from the portal's own workflow events and are searchable within seconds.
  • Every answer can be checked. Inline citations point to the exact sources, and the assistant says so when the sources don't contain the answer.

What's next

  • Write ingestion status back to the portal entry, so editors can see when a document was indexed and how many passages it produced.
  • Run scheduled permission reconciliation across the whole index, alongside the per-request live check.
  • Build an evaluation set of real questions with expected sources, to measure retrieval quality as content grows.

This pattern works on any platform that already manages users and permissions. The assistant reuses those rules instead of creating its own.

Working on something similar? See how ATS Global approaches AI development services, or browse our case studies.

Found this useful? Share it with your network.

Let’s work together

Ready to build something great?

Tell us about your project. We respond within one business day and can provide a customised quote for your requirements.