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 05 · 50 minutes

Find the weak points of embeddings and vector stores

After this lesson you can
  • Show what an index file leaks and keep secret words out of the files that others can read
  • Use a similarity score as a side channel, then remove the score from the reply
  • Measure a keyword-stuffed chunk and limit it with a cap per document and a stuffing check
Lab files of this lesson (28)

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

Your lead has read that a vector store is "just numbers", and asks: "So the index file is harmless, and a score in the reply is only a debug field?" You test both claims on your own service, and a third weak point, keyword stuffing. Then you fix each one.

Recall

Lesson 4: why does the filter run before the ranking and not after it?

The prompt then holds only chunks that the user may read, and the best allowed chunks fill the slots.

Lesson 3: what does `INSTRUCTION` do, and why is it not the control?

A short list of phrases that talk to the assistant. A careful attack avoids them, so the control is the approval of a person.

The idea

An embedding is a list of numbers that stands for a text, so that texts with a similar meaning get similar numbers. This course uses TF-IDF vectors, the simple kind: one weight for each word. Real services use learned embeddings from a model. The attack surface is similar in kind, not in detail: a TF-IDF file stores the words themselves, and a dense index stores vectors with no words in them. OWASP names the area LLM08:2025 Vector and Embedding Weaknesses.

Weak pointWhat happensDefence of this lesson
The index fileA person with the file reads the words of every chunk, including secret ones.A separate index file for each level, shown here for the public level.
A dense vector storeThe store often keeps the text of each chunk beside its vector. The vectors can be partly inverted, as OWASP notes, though this takes effort. A nearest-neighbour search that filters after the search can return too few results.Not built in this lab. Protect the store like the documents, and filter before the search.
The scoreA score in the reply lets a visitor test a guess against hidden chunks.Never show a score.
Ranking tricksA chunk full of keywords ranks first for many questions.A check for stuffing, and a cap per document.
What an attacker uses at each weak point
OutsideYour serviceSourcesAttackerSearch APIIndex fileWiki1234OutsideYour serviceSourcesAttackerSearch APIIndex fileWiki1234
  1. Attacker → Index file: steals it and reads the words
  2. Attacker → Search API: sends guesses, reads the score
  3. Attacker → Wiki: adds a page of repeated keywords
  4. Wiki → Index file: the stuffed page wins the top slots

Worked example

1. Save the index and read it as a thief

Save peek.py. It writes the vectors of lesson 1 to index.json, as a real service does. Then it plays the thief: from the marked line on it reads only index.json, never kb.json, and prints the eight heaviest words of each finance chunk.

peek.py

"""peek.py: save the index to a file, then read it as someone who steals only index.json."""
import json
from rag import Index, load

index = Index(load())
json.dump({"idf": index.idf, "vec": index.vec}, open("index.json", "w"))
print("index.json:", len(index.vec), "chunks,", len(index.idf), "words")

data = json.load(open("index.json"))        # the thief starts here: kb.json stays closed
for cid, vec in data["vec"].items():
    if cid.startswith("fin-"):
        top = sorted(vec, key=vec.get, reverse=True)[:8]
        print(cid, "->", " ".join(top))
python3 peek.py
index.json: 12 chunks, 180 words
fin-salary -> 000 earns eur salary bands store assistant 31
fin-q3 -> was 12 eur q3 results revenue million profit
fin-supplier -> eur each supplier prices norrland textiles charges jacket
fin-payroll -> payroll salaries 25th month main account file goes

No sentence is stored, and still the thief reads "salary bands store assistant 31 000" and "payroll salaries main account".

2. Give a level its own file

Save partition.py. It builds an index of the public chunks only and writes it to its own file, index-public.json. Then it counts, for the full index.json and for the public file, the words that only finance documents use. A service that loaded only the public file for a visitor would never hold a finance vector for that visitor. This course shows the file and the count and does not build the loader: partition.py is shown for the measure, not for the service.

partition.py

"""partition.py: an index file for the public level only, then the finance-only words that each file holds."""
import json
from rag import Index, load, words

kb = load()
only = {w for c in kb if c["level"] == "finance" for w in words(c["text"])} - \
       {w for c in kb if c["level"] != "finance" for w in words(c["text"])}
public = Index([c for c in kb if c["level"] == "public"])
json.dump({"idf": public.idf, "vec": public.vec}, open("index-public.json", "w"))
for path in ("index.json", "index-public.json"):
    have = set(json.load(open(path))["idf"])
    print(path.ljust(18), len(have), "words,", len(only & have), "of", len(only), "finance-only")
python3 partition.py
index.json         180 words, 63 of 63 finance-only
index-public.json  66 words, 0 of 63 finance-only

The public file holds none of the 63 finance-only words. A service that used only that file for a visitor would survive a bug in the filter of lesson 4: the index cannot return what it does not hold. It would remove a second leak too: an index over every document computes its word weights from hidden text, so the order of the replies for a visitor can depend on pages that the visitor may not read.

3. Probe a hidden chunk through the score

A developer adds a field best_score to the reply "for debugging". It is the best score over all chunks, hidden ones included. Save leaky_api.py, with the leaky api and the fixed safe_api.

leaky_api.py

"""leaky_api.py: a search API that a developer 'improved' with a score field, and the fixed version."""
from access import allowed_ids
from rag import Index, load

kb = load()
index = Index(kb)


def api(user, question):
    """The ids that the user may read, and the best score 'for debugging'."""
    mine = index.search(question, 3, allowed_ids(user, kb))
    best = index.search(question, 1)                      # the best chunk over ALL chunks
    return {"ids": [cid for _, cid in mine], "best_score": best[0][0] if best else 0.0}


def safe_api(user, question):
    """The fix: only the ids that the user may read. No score, and no trace of other chunks."""
    return {"ids": [cid for _, cid in index.search(question, 3, allowed_ids(user, kb))]}

Save probe.py. The visitor gus may read nothing secret. He sends four guesses of what a hidden page might say and reads the score. This is a side channel: a way to learn a secret from a reply that does not carry it.

probe.py

"""probe.py: a visitor who may read nothing secret tests guesses against the score.   python3 probe.py [safe]"""
import sys
import leaky_api

GUESSES = {
    "A": "Q3 results: revenue was 9.9 million EUR and profit was 700,000 EUR.",
    "B": "Q3 results: revenue was 4.2 million EUR and profit was 310,000 EUR.",
    "C": "The company has a cafeteria with free coffee for all staff.",
    "D": "Supplier prices: Norrland Textiles charges 18 EUR for each jacket shell.",
}
call = leaky_api.safe_api if sys.argv[1:] == ["safe"] else leaky_api.api
for name, guess in GUESSES.items():
    reply = call("gus", guess)
    print(name, reply.get("best_score", "no score"), reply["ids"], guess[:40])
python3 probe.py
python3 probe.py safe
A 0.57 ['pub-shipping'] Q3 results: revenue was 9.9 million EUR 
B 0.74 ['pub-shipping'] Q3 results: revenue was 4.2 million EUR 
C 0.2 ['pub-shipping'] The company has a cafeteria with free co
D 0.67 ['pub-hours', 'pub-shipping'] Supplier prices: Norrland Textiles charg
A no score ['pub-shipping'] Q3 results: revenue was 9.9 million EUR 
B no score ['pub-shipping'] Q3 results: revenue was 4.2 million EUR 
C no score ['pub-shipping'] The company has a cafeteria with free co
D no score ['pub-hours', 'pub-shipping'] Supplier prices: Norrland Textiles charg
Best score for each guess, leaky API
B right figures0.74D supplier prices0.67A wrong figures0.57C cafeteria page0.2B right figures0.74D supplier prices0.67A wrong figures0.57C cafeteria page0.2

Every reply holds only public ids, and still the scores tell the story: the cafeteria page scores 0.2, and pages like the hidden ones score 0.57 and above. The guess with the right figures (B) beats the one with wrong figures (A), so a patient visitor can confirm a secret value without reading the chunk. With safe_api the four guesses look the same.

4. Stuff a page with keywords

Save safeindex.py. It has three parts.

  • distinct_ratio is the share of the words of a text that are different. Normal prose is above 0.7.
  • looks_stuffed flags a text of 20 words or more where the share is below limit. A shorter text is never flagged, so a short stuffed chunk passes. Only the approval of lesson 3 stops it.
  • SafeIndex is an Index with two defences. It leaves out stuffed chunks and records their ids. Its search returns at most one chunk of each document: the cap. An id such as doc#2 is the second chunk of doc; only the stuffed pages use that form here.

safeindex.py

"""safeindex.py: an index with two defences against ranking tricks."""
from rag import Index, words


def distinct_ratio(text):
    """The share of the words of a text that are different. Normal prose is above 0.7."""
    ws = words(text)
    return len(set(ws)) / len(ws) if ws else 1.0


def looks_stuffed(text, limit=0.6):
    """True when a long text repeats the same words, so that fewer than `limit` of its words are different."""
    return len(words(text)) >= 20 and distinct_ratio(text) < limit


class SafeIndex(Index):
    def __init__(self, chunks, limit=0.6):
        self.rejected = [c["id"] for c in chunks if looks_stuffed(c["text"], limit)]
        super().__init__([c for c in chunks if c["id"] not in self.rejected])

    def search(self, question, k=3, allow=None):
        """Like Index.search, but one chunk for each document: 'doc#2' and 'doc#3' count as 'doc'."""
        seen, out = set(), []
        for hit in super().search(question, len(self.chunks), allow):
            doc = hit[1].split("#")[0]
            if doc not in seen:
                seen.add(doc)
                out.append(hit)
        return out[:k]

Save stuff.py. It builds three chunks of one document that repeat ten keywords six times, and writes them to promo.json (you use that file in lesson 7). measure counts, over six questions, in how many the stuffed chunk ranks first and how many top-3 slots it takes. With limit=0 the stuffing check never fires, so you see the cap alone.

stuff.py

"""stuff.py: three chunks stuffed with keywords, and what they do to the ranking."""
import json
from rag import Index, load
from safeindex import SafeIndex, distinct_ratio

BAIT = "refund returns delivery shipping warranty price tent jacket free days"
promo = [{"id": f"pub-promo#{n}", "level": "public", "source": "shop-wiki", "owner": "anon-edit",
          "date": "2026-11-20", "text": "Marlowe offers a coupon. " + (BAIT + " ") * 6} for n in (1, 2, 3)]
json.dump(promo, open("promo.json", "w"), indent=1)

QUESTIONS = ["How many days do I have to return unused gear?", "When is delivery free?",
             "How long is the warranty on a tent?", "When is the shop open on Saturday?",
             "Can I get a refund for a jacket?", "How much does shipping cost?"]


def measure(index):
    """(questions where a promo chunk is first, promo chunks in the top 3 over all questions)"""
    hits = [index.search(q, 3) for q in QUESTIONS]
    first = sum(bool(h) and h[0][1].startswith("pub-promo") for h in hits)
    return first, sum(cid.startswith("pub-promo") for h in hits for _, cid in h)


chunks = load() + promo
print("different words, promo chunk:", round(distinct_ratio(promo[0]["text"]), 2), " shipping chunk:", round(distinct_ratio(load()[1]["text"]), 2))
print("plain index          ", measure(Index(chunks)))
print("cap per document only", measure(SafeIndex(chunks, limit=0)))
safe = SafeIndex(chunks)
print("cap and detection    ", measure(safe), "rejected:", safe.rejected)
python3 stuff.py
different words, promo chunk: 0.21  shipping chunk: 0.87
plain index           (4, 12)
cap per document only (4, 4)
cap and detection     (0, 0) rejected: ['pub-promo#1', 'pub-promo#2', 'pub-promo#3']

Without a defence the stuffed chunks rank first for four of six questions and take 12 of the top-3 slots. The cap cuts the slots to 4, but the chunk still ranks first for four questions. The stuffing check removes the chunks: a normal page has a ratio of 0.87, and the stuffed one 0.21.

Your turn

Needs: the files of steps 1 to 4. A reader who starts here runs bash catchup.sh from the set-up lesson (00) first.

Your lead wants proof for all three weak points.

  1. Run probe.py and probe.py safe again, and for each guess write down whether the score is 0.50 or more.
  2. Read the last column of partition.py for the two index files, and note which of them holds finance-only words.
  3. Run stuff.py and read the three lines of numbers. Then change the bait text so that it holds only three keywords, repeated six times, and run again. Try five repeats too. Write in notes-05.txt whether the stuffing check still catches each one, and why.

Check yourself

The index file holds numbers and no sentences. Why is it still sensitive?

The numbers are weights of words, and the words are in the file. A reader sees which words each chunk uses, so the topic and often the figures. Treat the index like its documents.

The reply holds only public ids. How can the score still leak?

The score is computed from the hidden chunk, so the reply tells the visitor something about it. Many guesses can confirm that a page exists and even what it says.

The cap per document did not stop the stuffed chunk from ranking first. What did it do?

It limited the damage: one chunk of the document, not three, in the prompt. The chunk still ranks first, because it holds the question's words. Only the stuffing check and, in the end, the approval of lesson 3 keep the page out.

Field notes

  • Use file permissions, disk encryption and access control on every index, cache and backup, as for the documents. Give the service account of a vector database the smallest role.
  • Do not return similarity scores, ranks or counts of hidden chunks to a user. Timing is a second side channel: a reply that is slower when a hidden chunk matches tells the same story. Add a rate limit.
  • A separate index for each level, loaded by level, is a strong defence in depth: the filter of lesson 4 can fail and the data is still absent. The cost is a copy of the shared documents in each file, so use levels or groups, not one index for each user.
  • Do not share one vector store between customers with only a metadata field to tell them apart, unless you have tested the filter. A partition for each tenant is safer. OWASP LLM08:2025 lists context leaks in shared stores.