AI Hints
Home›RAG Tutorial›Trust and Safety
RAG · Lesson 98 of 120

Access Control

Who can see what.

⏱ 2 min read▶ Video at 1:36:36🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Northwind's staff have internal pages too, like supplier discounts. Customers must never see them. If RAG searches everything, it can leak private text into an answer. Access control filters before search.

Access Control
From the video: Access Control
  • Staff-only pages
  • Customers must not see
  • Filter before search

Filtering by role

Each chunk has an audience, public or staff. Allowed returns only the chunks a role may see. We search the same question as a customer, then as staff. Run it. The customer never sees the staff page. Staff see both.

access.pypython
from rag_kit import Index

chunks = [
    {"source": "returns.md", "audience": "public",
     "text": "You can return any unused item within 30 days."},
    {"source": "staff_returns.md", "audience": "staff",
     "text": "Staff may approve returns up to 60 days for loyal customers."},
]

def allowed(role):
    return [c for c in chunks if c["audience"] == "public" or role == "staff"]

for role in ["customer", "staff"]:
    hits = Index(allowed(role)).search("How long do returns last?", k=2)
    print(role, "sees:", [c["source"] for s, c in hits])
Output
customer sees: ['returns.md']
staff sees: ['staff_returns.md', 'returns.md']
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

Access control rules

Filter before search, never after the answer is written. Store permissions on every chunk. Check the user's role on the server, not in the browser. And test it, with a question only staff should answer.

keyvalue
Filterbefore search
Permissionson every chunk
Checkon the server
Testwith staff questions

Summary

Store who may see each chunk, and filter by the user's role before searching. Next, prompt injection hidden in documents.

Key takeaways
  • Audience per chunk
  • Filter first
  • Test leaks
Next up: Prompt Injection in Documents — untrusted text