Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 01 · 40 minutes

Build a RAG service and map its trust boundaries

After this lesson you can
  • Build a small RAG service over twelve documents of three sensitivity levels
  • Draw the data flow and name who can write to each part of it
  • Show that a service without a user check gives every document to every asker
Lab files of this lesson (6)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Marlowe Outdoor is an invented company that sells camping gear. Its web team wants an assistant that answers from the company's own documents: returns, shipping, staff rules and finance papers. Your lead says: "Before anyone adds a real document, draw where data enters, and tell me who can change each part." You build the small service first, on twelve invented documents, and then you map it.

The idea

You know retrieval-augmented generation (RAG) from lesson 6 of "How LLMs and agents work": the service searches the documents, puts the best ones in the prompt, and the model writes an answer from them. This course asks who can feed that service and who can read from it. As "Securing LLM applications" showed, a model cannot tell a rule from data, so every text that reaches the prompt is a possible attack.

A chunk is the piece of a document that the service indexes and retrieves. Here each document is short, so one document is one chunk. A trust boundary is a line in the data flow where data passes from a party that you trust less to a part that you trust more. Checks belong on those lines.

Who can write to the RAG service, and who can read
OutsideYour serviceProviderUserAttackerRetrieverIndexDocumentsModel123456OutsideYour serviceProviderUserAttackerRetrieverIndexDocumentsModel123456
  1. Attacker → Documents: edits a wiki page
  2. Documents → Index: the index build copies every page
  3. User → Retriever: asks a question
  4. Retriever → Index: search with the question
  5. Retriever → Model: rules, chunks and question
  6. Retriever → User: the answer and its sources

Each part has writers, the people or programs that can change it. The writers decide what the model reads.

PartWhat it holdsWho can write to it
Knowledge basethe documents (kb.json)everyone who can edit the wiki or the share it comes from
Indexone vector for each chunkthe build code: it copies whatever the knowledge base holds
Questionthe text of the useranyone who can reach the service
Prompt templatethe rules (RULES)the developers
Modelthe weightsthe provider that you took the file from
Logsquestions and answersthe service, and so the users through their questions

The model sees a chunk only after the index returns it, and the index returns what the knowledge base holds. So whoever can write to the knowledge base can write to the prompt. The weak point of this course is that path, not the model.

Worked example

1. Make the knowledge base

The twelve documents carry three levels: public (anyone), staff (employees) and finance (the finance team only). Each one also has a source (where it came from), an owner (who answers for it) and a date. Save the file kb.json. JSON is a text format for data, and every document is one object with named fields.

One document of kb.json
pub-returnsidpubliclevelshop-wikisourceweb-teamowner2026-03-10dateReturns: unused gear can be...text that is indexedpub-returnsidpubliclevelshop-wikisourceweb-teamowner2026-03-10dateReturns: unused gear can be...text that is indexed

kb.json

[
  {"id": "pub-returns", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-03-10",
   "text": "Returns: unused gear can be returned within 30 days of delivery. The customer sends the order number. Marlowe Outdoor refunds the money to the original payment method within 5 working days."},
  {"id": "pub-shipping", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-02-02",
   "text": "Shipping: orders placed before 14:00 ship the same day. Delivery takes 2 to 4 working days and costs 6 EUR. Delivery is free for orders of 80 EUR or more."},
  {"id": "pub-warranty", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-01-15",
   "text": "Warranty: tents and backpacks have a warranty of 24 months. The warranty covers faults in material and sewing. It does not cover damage from misuse or wear."},
  {"id": "pub-hours", "level": "public", "source": "shop-wiki", "owner": "web-team", "date": "2026-04-01",
   "text": "Opening hours: the Bergen shop is open Monday to Friday from 10:00 to 18:00 and on Saturday from 10:00 to 16:00. The shop is closed on Sunday."},
  {"id": "stf-holiday", "level": "staff", "source": "hr-share", "owner": "hr", "date": "2026-01-20",
   "text": "Holiday: staff have 25 days of paid holiday each year. Send the request to your manager at least 14 days before the first day. Holiday in July needs approval by the end of April."},
  {"id": "stf-expenses", "level": "staff", "source": "hr-share", "owner": "hr", "date": "2026-05-12",
   "text": "Expenses: claim travel and supplies in the expense tool within 30 days. A claim above 200 EUR needs the approval of your manager. Keep every receipt for one year."},
  {"id": "stf-vpn", "level": "staff", "source": "shop-wiki", "owner": "it", "date": "2026-06-03",
   "text": "VPN: staff connect to the company VPN with the Marlowe client and a one-time code from the phone app. Write to the IT desk when the code fails."},
  {"id": "stf-discount", "level": "staff", "source": "hr-share", "owner": "hr", "date": "2026-02-18",
   "text": "Staff discount: staff pay 30 percent less for gear in the shop and online. The discount applies to two items for each order. Sale items are not reduced further."},
  {"id": "fin-salary", "level": "finance", "source": "finance-share", "owner": "finance", "date": "2026-03-01",
   "text": "Salary bands: a store assistant earns 31,000 to 36,000 EUR a year. A team lead earns 40,000 to 47,000 EUR. Band changes are decided each March by the finance director."},
  {"id": "fin-q3", "level": "finance", "source": "finance-share", "owner": "finance", "date": "2026-10-28",
   "text": "Q3 results: revenue was 4.2 million EUR and profit was 310,000 EUR. Tent sales rose by 12 percent. The board meets on 12 December to plan the budget."},
  {"id": "fin-supplier", "level": "finance", "source": "finance-share", "owner": "finance", "date": "2026-04-22",
   "text": "Supplier prices: Norrland Textiles charges 18 EUR for each jacket shell and 9 EUR for each tent pole set. The contract runs until June and the price cannot change before then."},
  {"id": "fin-payroll", "level": "finance", "source": "finance-share", "owner": "finance", "date": "2026-02-27",
   "text": "Payroll: salaries are paid on the 25th of each month from the main company account. The payroll file goes to the bank by 12:00 two working days before. Only the finance team may open it."}
]

2. Build the service

Save rag.py. It is the retrieval of lesson 6, grouped in one place. A class groups data and the functions that use it. Index turns every chunk into a vector with vector: one weight for each word, the number of times the word occurs times how rare the word is (this is TF-IDF), scaled to length 1, so that a dot product of two vectors is their cosine similarity. search returns the best k chunks as (score, id). The sort key (-r[0], r[1]) puts the highest score first and breaks ties by id, so every machine gives the same order. The argument allow is a set of ids that may be searched (None: all of them). Lesson 4 uses it.

answer takes the model as an argument, so that a test can pass a fake model and let the code decide the result.

rag.py

"""rag.py: a small RAG service for the invented company Marlowe Outdoor. Standard library only."""
import json
import math
import re
from collections import Counter

from llm import chat

STOP = set("a an the of to in is are for and or do does can i my it at on how what when which who with from by be "
           "if after before get you we our this that".split())

RULES = ("You answer questions for Marlowe Outdoor. Use only the sources below. "
         "If the sources do not contain the answer, reply: I do not know. Answer in at most 30 words.")


def words(text):
    """Lower-case words and numbers, without the common words."""
    return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP]


class Index:
    """TF-IDF vectors of the chunks, and a cosine-similarity search."""

    def __init__(self, chunks):
        self.chunks = {c["id"]: c for c in chunks}
        df = Counter(w for c in chunks for w in set(words(c["text"])))
        self.idf = {w: math.log((1 + len(chunks)) / (1 + n)) + 1 for w, n in df.items()}
        self.vec = {c["id"]: self.vector(words(c["text"])) for c in chunks}

    def vector(self, ws):
        """One weight for each word: how often it occurs, times how rare it is. Length 1."""
        vec = {w: n * self.idf[w] for w, n in Counter(ws).items() if w in self.idf}
        norm = math.sqrt(sum(x * x for x in vec.values())) or 1.0
        return {w: x / norm for w, x in vec.items()}

    def search(self, question, k=3, allow=None):
        """The k best chunks as (score, id). `allow` is a set of ids that may be searched; None means all."""
        q = self.vector(words(question))
        ranked = [(round(sum(x * v.get(w, 0) for w, x in q.items()), 2), cid)
                  for cid, v in self.vec.items() if allow is None or cid in allow]
        return sorted([r for r in ranked if r[0] > 0], key=lambda r: (-r[0], r[1]))[:k]


def build_prompt(question, chunks):
    """The two messages for the model: the rules with the sources, and the question."""
    sources = "\n\n".join(f"[{c['id']}]\n{c['text']}" for c in chunks)
    return [{"role": "system", "content": RULES + "\n\nSOURCES\n\n" + sources},
            {"role": "user", "content": question}]


def load(path="kb.json"):
    return json.load(open(path))


def answer(index, question, k=3, seed=0, allow=None, model=chat):
    """One question in; the answer and the ids of the chunks that it was written from."""
    hits = index.search(question, k, allow)
    messages = build_prompt(question, [index.chunks[cid] for _, cid in hits])
    return model(messages, temperature=0.7, seed=seed, max_tokens=80).strip(), [cid for _, cid in hits]


if __name__ == "__main__":
    index = Index(load())
    print(len(index.chunks), "chunks,", len(index.idf), "different words")
    for q in ["How many days do I have to return unused gear?", "When is delivery free?",
              "How much does a store assistant earn?"]:
        print(q, "->", index.search(q))
python3 rag.py
12 chunks, 180 different words
How many days do I have to return unused gear? -> [(0.32, 'pub-returns'), (0.17, 'stf-holiday'), (0.09, 'pub-warranty')]
When is delivery free? -> [(0.39, 'pub-shipping'), (0.12, 'pub-returns')]
How much does a store assistant earn? -> [(0.24, 'fin-salary')]

The right chunk ranks first each time.

3. Ask the model

Save ask.py. It takes the question from the command line (sys.argv[1]), builds the index, and prints the answer and its sources. The model call takes several seconds on a CPU.

ask.py

"""ask.py: ask the service one question.   python3 ask.py "When is delivery free?" """
import sys
from rag import Index, answer, load

reply, sources = answer(Index(load()), sys.argv[1])
print(reply)
print("sources:", sources)
python3 ask.py "When is delivery free?"
Delivery is free for orders of 80 EUR or more.
sources: ['pub-shipping', 'pub-returns']

4. See what the model receives

Print the prompt for the same question, with only the best chunk. python3 -c "text" runs the text as a small program, and ["content"] is the text of the first message.

python3 -c "
from rag import *
i = Index(load())
hits = i.search('When is delivery free?', 1)
print(build_prompt('When is delivery free?', [i.chunks[c] for _, c in hits])[0]['content'])
"
You answer questions for Marlowe Outdoor. Use only the sources below. If the sources do not contain the answer, reply: I do not know. Answer in at most 30 words.

SOURCES

[pub-shipping]
Shipping: orders placed before 14:00 ship the same day. Delivery takes 2 to 4 working days and costs 6 EUR. Delivery is free for orders of 80 EUR or more.

The rules of the developer and a text from the knowledge base sit in one block. Nothing in it marks the chunk as less trusted than the rules.

5. Ask who is asking

A service that gives each user their own documents must know who asks. Look at answer: it has no user. Ask a finance question, with no sign-in at all.

python3 ask.py "How much does a store assistant earn?"
A store assistant earns between 31,000 to 36,000 EUR per year.
sources: ['fin-salary']

Anyone who can reach this service reads the salary bands. The level field in kb.json is data that nothing checks. This is the first weakness that you will fix, in lesson 4.

6. Check who can write to the file

ls -l shows the owner, the group and the permissions of a file (the course "Linux", Part 1, lesson 10). Every account with write permission is a writer of the knowledge base.

How to read one line of ls -l
-rw-rw-r--file, owner rw, group rw, others ryouowneryougroup3442byteskb.jsonname-rw-rw-r--file, owner rw, group rw, others ryouowneryougroup3442byteskb.jsonname
ls -l kb.json
-rw-rw-r-- 1 you you 3442 Nov 21 12:45 kb.json

Your size and date differ. In a real company the knowledge base is a wiki or a share, and the list of writers is much longer.

Your turn

The lead asks: "What can a stranger read?" Use rag.py on the knowledge base and do these three things.

  1. For each of the questions "What was the profit in Q3?", "How do I connect to the VPN?", "How long is the warranty on a tent?" and "When is delivery free?", find the id and the level of the best chunk.
  2. Count the chunks of each level, and the different words in the index.
  3. Write boundaries.md, a table with one row for each of the six parts in the list of this lesson. Columns: the part, who writes to it in your own company or in your imagined one, and the check that you would put on that line. The page does not check this file. Keep it: it is the start of the design review in lesson 8.

Check yourself

The model is never changed in this course. Why is the knowledge base a better target for an attacker than the model?

The model belongs to a provider and is hard to reach. The knowledge base is edited by many people, and everything in it can reach the prompt. One changed document changes the answers without any change to the model or the code.

Where is the trust boundary between the index and the prompt?

Where the service writes the chunks that the index returns into the prompt. Before that point the text is data in a store. After it, the model reads the text as part of its instructions. Checks on the text, and on who may read it, must run before that point.

The `level` field says "finance", but `ask.py` still returned the salary. What does this tell you about a label in the data?

A label protects nothing until code enforces it. The service must read the label, know who asks, and refuse before the text is ranked or written into a prompt.

Field notes

  • Draw the data flow before you build controls. Every arrow across a trust boundary needs a decision: who may write, who may read, what you check.
  • The OWASP Top 10 for LLM Applications (2025 edition) holds three risks that this course covers: LLM02 Sensitive Information Disclosure, LLM04 Data and Model Poisoning and LLM08 Vector and Embedding Weaknesses.
  • Keep the list of writers short and name every source (lesson 9).
  • Give a chunk its provenance and its level on the day it enters, as kb.json does. Adding labels later is a large, error-prone job.