# How RAG search gets fooled: cosine similarity, reranking and poisoned documents

> Embeddings, cosine similarity and cross-encoder reranking in plain words, then how RAG retrieval is poisoned, manipulated and reversed, and what to check.

- Published: 2026-11-23
- Topics: AI security, RAG, LLM security
- Canonical page: https://thesecguy.com/notes/rag-cosine-similarity-reranking-poisoning/
- Publisher: The Sec Guy (https://thesecguy.com)

**Short answer:** A RAG chatbot finds documents by turning text into coordinates and fetching whatever sits closest to your question. Closeness measures topic, so the search is easy to fool: on a negation benchmark, common embedding models scored 6.8% to 11.1% where random guessing scores 25%. Attackers use that too. In the PoisonedRAG study, 5 planted texts per targeted question steered that answer 90% of the time. Rerankers help accuracy but read attacker text too, and short stored embeddings can be turned back into text. Control what enters the index and filter by the user's permissions at search time.

---

Retrieval-augmented generation, or RAG, is how most company chatbots work: before answering, the bot searches your documents and hands the best matches to the model. The model then answers from whatever it was handed. So whoever controls the search results controls the answer.

The search has two stages worth understanding. The first uses cosine similarity. The second, when there is one, uses a cross-encoder to rerank.

## Embeddings and cosine similarity, in plain words

Imagine a huge map where every sentence ever written has an address. Sentences about cricket live in one district, sentences about home loans in another. An embedding model is the clerk who assigns each sentence its address.

To search, the clerk gives your question an address too, then fetches whatever lives nearest. Cosine similarity is the measure of nearness.

The trap is in what "near" means. "The customer is happy" and "the customer is not happy" are about the same thing, so they end up on the same street. The map knows what a sentence is about far better than it knows what the sentence says.

<figure class="fig">
<p class="fig-k">How close two sentences score (higher = closer in meaning)</p>
<div class="hbars">
<div class="hbar hot"><em>"The new movie is awesome" vs "The new movie is so great"</em><div class="track"><i style="width:89%"></i></div><b>0.89</b></div>
<div class="hbar"><em>"The new movie is awesome" vs "The dog plays in the garden"</em><div class="track"><i style="width:5%"></i></div><b>0.05</b></div>
</div>
<figcaption>Source: example scores in the Sentence Transformers documentation (0.8939 and 0.0543), rounded.</figcaption>
</figure>

## Embeddings and cosine similarity, technically

An embedding model turns text into a long list of numbers, a vector. The [Sentence Transformers documentation](https://sbert.net/examples/applications/semantic-search/README.html) describes the setup. You "embed all entries in your corpus, whether they be sentences, paragraphs, or documents, into a vector space". At search time, "the query is embedded into the same vector space and the closest embeddings from your corpus are found." Cosine similarity is that library's default way of scoring closeness. Texts on the same subject score high, and unrelated ones score much lower. Scores are only comparable within one embedding model. In the library's [own example](https://sbert.net/docs/usage/semantic_textual_similarity.html), two sentences praising a movie score 0.89 and a sentence about a dog in a garden scores 0.05 against the first.

A vector database stores these vectors and finds nearest neighbors quickly. The same documentation says comparing against everything suits small collections, "up to about 1 million entries". For larger collections, systems usually switch to approximate search, where "the results are not necessarily exact".

A Johns Hopkins team [measured](https://arxiv.org/abs/2305.07614) how badly these models handle negation, the "not" in a sentence, with a benchmark called NevIR, built from 2,556 pairs of documents that differ only by a negation. Each test has two questions and two documents, and a model must match both correctly. Guessing scores 25%. The paper's headline finding is that "nearly all models perform worse than randomly ranking."

<figure class="fig">
<p class="fig-k">Getting negation right: score on the NevIR benchmark</p>
<div class="hbars">
<div class="hbar hot"><em>Best embedding model tested (bi-encoder)</em><div class="track"><i style="width:11%"></i></div><b>11.1%</b></div>
<div class="hbar"><em>Random guessing</em><div class="track"><i style="width:25%"></i></div><b>25%</b></div>
<div class="hbar"><em>Best reranker tested (cross-encoder)</em><div class="track"><i style="width:51%"></i></div><b>50.6%</b></div>
<div class="hbar"><em>Humans</em><div class="track"><i style="width:100%"></i></div><b>100%</b></div>
</div>
<figcaption>Source: Weller, Lawrie and Van Durme, "NevIR: Negation in Neural Information Retrieval", Johns Hopkins University, EACL 2024.</figcaption>
</figure>

The embedding models in that study scored between 6.8% and 11.1%. They do worse than chance because they usually rank the same document first for both questions, which counts as a miss.

## Rerankers, in plain words

Think of two librarians. The first read every book once, long ago, and wrote one short index card for each. Ask a question and they compare it with the cards, never the books, and pull a hundred likely ones in a second. The second librarian takes those hundred, opens each one with your question in hand, and puts the ones that truly answer it on top. It's careful work and slow, so it's only practical on a short pile.

<figure class="fig">
<p class="fig-k">Two ways to compare a question with a document</p>
<div class="flow">
<div class="node"><b>Fast: bi-encoder</b><span>Question and document are each turned into coordinates on their own, then the coordinates are compared</span><div class="chips"><i class="chip">read separately</i><i class="chip">stored ahead of time</i></div></div>
<div class="node"><b>Careful: cross-encoder</b><span>Question and document are read together, word against word, and one score comes out</span><div class="chips"><i class="chip">read together</i><i class="chip">nothing stored</i></div></div>
<div class="node"><b>In practice</b><span>The fast one picks about 100 candidates, the careful one orders them</span><div class="chips"><i class="chip">retrieve</i><i class="chip">then rerank</i></div></div>
</div>
<figcaption>Our illustration of the two designs described in the Sentence Transformers documentation.</figcaption>
</figure>

## Bi-encoders and cross-encoders, technically

The fast librarian is a bi-encoder. It encodes the question and each document separately, so document vectors can be computed once and stored. The careful one is a cross-encoder: "we pass both sentences simultaneously to the Transformer network", so the model can compare the question and the document word by word. That is why it handles "not" better, though not well: the best one reached 50.6% and several scored near chance.

It costs time. A cross-encoder "does not produce a sentence embedding", so nothing can be precomputed. The Sentence Transformers documentation gives a sense of scale: comparing 10,000 sentences with each other takes a cross-encoder "about 65 hours", while a bi-encoder computes the embeddings in 5 seconds.

So real systems use both, a design called [retrieve and rerank](https://sbert.net/examples/applications/retrieve_rerank/README.html). The first stage fetches "a large list of e.g. 100 possible hits". Then a "re-ranker based on a CrossEncoder" scores those candidates and the top few go to the model. The idea dates from a [2019 paper](https://arxiv.org/abs/1901.04085) that reranked search results with a language model called BERT and beat the previous best "by 27% (relative)" on a standard benchmark.

A reranker is the standard fix for answers that are wrong even though "retrieval works". It's built for accuracy and was not designed as a security control, which is what Attack 2 below goes after.

<figure class="fig">
<p class="fig-k">The RAG pipeline and where each weakness and attack lands</p>
<div class="flow">
<div class="node"><b>1. Documents come in</b><span>Files, tickets, web pages, emails are embedded and stored</span><div class="chips"><i class="chip">poisoning</i></div></div>
<div class="node"><b>2. Vector store</b><span>Holds a vector for every chunk of text</span><div class="chips"><i class="chip">inversion</i></div></div>
<div class="node"><b>3. Retrieve</b><span>Nearest vectors to the question, about 100</span><div class="chips"><i class="chip">negation errors</i></div></div>
<div class="node"><b>4. Rerank</b><span>A cross-encoder or an LLM reads and reorders them</span><div class="chips"><i class="chip">rank manipulation</i></div></div>
<div class="node"><b>5. Model answers</b><span>From the top few, with the user's access</span><div class="chips"><i class="chip">prompt injection</i></div></div>
</div>
<figcaption>Our mapping of the attacks described in the research below onto a typical retrieve-and-rerank pipeline.</figcaption>
</figure>

## Attack 1: poison the index

If nearness decides what the model reads, an attacker only has to write text that lands nearest to a question they care about.

The reference study is [PoisonedRAG](https://arxiv.org/abs/2402.07867), from Pennsylvania State University and Illinois Institute of Technology, presented at USENIX Security 2025. For each target question the attackers wrote a handful of texts that both matched the question and carried a false answer. In the authors' words, "PoisonedRAG could achieve a 90% attack success rate when injecting five malicious texts for each target question into a knowledge database with millions of texts."

The attacker in that study has no special access, though they do choose the target questions in advance. They "cannot access texts in the knowledge database and cannot access/query the LLM in RAG." They only need a way to add content, and the paper's example is "maliciously editing Wikipedia pages". The defenses the authors tried, such as paraphrasing the question and filtering duplicates, were in their words "insufficient". It is a research benchmark on chosen questions, so read 90% as what's possible in a test. Nobody has measured it in the field.

<figure class="fig">
<p class="fig-k">Three results that changed how RAG is threat-modeled</p>
<div class="tiles">
<div class="tile hot"><b>5</b><span>planted texts per question were enough</span><small>90% success, PoisonedRAG</small></div>
<div class="tile"><b>92%</b><span>of short texts recovered exactly from their embeddings</span><small>32-token inputs, Cornell 2023</small></div>
<div class="tile"><b>2.5x</b><span>more likely to be recommended after hidden text was added</span><small>Bing test, ETH Zürich 2024</small></div>
</div>
<figcaption>Sources: Zou et al. 2024; Morris et al. 2023; Nestaas, Debenedetti and Tramèr 2024.</figcaption>
</figure>

## Attack 2: talk your way up the ranking

Rerankers read the document's text. So does an LLM that orders search results. Text inside a document can therefore argue for its own promotion.

ETH Zürich researchers [showed this](https://arxiv.org/abs/2406.18382) against production LLM search engines, Bing and Perplexity, using pages they controlled. Hidden instructions on a product page made "the targeted camera 2.5× more likely to be recommended by the LLM". They note that "all our attacks can be embedded as illegible text on a web page". A UC Berkeley team [reached the same conclusion](https://arxiv.org/abs/2406.03589) for shopping-style conversational search, with a method that "reliably promotes low-ranked products." Both studies targeted an LLM doing the ordering. Earlier research attacked rerankers directly. A [2022 paper](https://arxiv.org/abs/2209.06506) went after BERT-style passage rankers it could only query from outside, "adding 6-words triggers into the irrelevant passages" to push them up the list.

## Attack 3: turn the vectors back into text

Teams often treat embeddings as harmless numbers and give the vector store weaker protection than the documents. A Cornell paper titled ["Text Embeddings Reveal (Almost) As Much As Text"](https://arxiv.org/abs/2310.06816) shows the mistake. Their method could "recover 92% of 32-token text inputs exactly" from embeddings alone. A token is a word or a piece of one, so those are short texts. On clinical notes it recovered 89% of full names.

The limits matter too. Longer passages were much harder: 8.0% exact recovery on inputs up to 128 tokens. And the attacker needs both the stolen vectors and the ability to query the same embedding model.

## A real case

Researchers have shown injection through retrieved content in a shipped product. EchoLeak in Microsoft 365 Copilot is tracked as [CVE-2025-32711](https://db.gcve.eu/vuln/CVE-2025-32711), published on 11 June 2025. Microsoft describes it this way: "Ai command injection in M365 Copilot allows an unauthorized attacker to disclose information over a network." Microsoft's [advisory](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2025-32711) says the flaw "has already been fully mitigated by Microsoft" and that there is "no action for users of this service to take". It lists the flaw as not exploited. We covered it with five other cases in [Prompt injection: 6 real AI agent hijacks and the 5 fixes](https://thesecguy.com/notes/prompt-injection-6-real-ai-agent-hijacks/).

## What to check, with an example

OWASP's own scenario is a good one to hold in mind: a hiring assistant that searches submitted resumes, where an attacker "creates a resume that includes hidden text, such as white text on a white background". Anyone can submit a resume.

1. **Who can add to the index?** List every source: uploads, shared drives, tickets, inboxes, crawled pages. Each one that a stranger can write to is an injection point. OWASP's advice is to "Accept data only from trusted and verified sources."
2. **Is retrieval permission-aware?** The search should return only chunks the asking user is allowed to read, checked at query time. OWASP calls for "fine-grained access controls and permission-aware vector and embedding stores."
3. **Is hidden text stripped before embedding?** White-on-white text, tiny fonts, comments and metadata should be removed or flagged during ingestion.
4. **Is the vector store protected like the source documents?** Give it the same access rules, encryption and logging. The Cornell result is the reason.
5. **Does anything check negation-sensitive answers?** For policy, medical or legal content, "is allowed" and "is not allowed" retrieve the same passages. A reranker helps, but the best one tested still failed about half the pairs, so test with pairs of opposite questions and have a person review answers where a "not" matters.
6. **Are retrievals logged?** OWASP asks for "detailed immutable logs of retrieval activities". When an answer is wrong, you'll want to know which chunk caused it and who put it there.

Our [LLM security guide](https://thesecguy.com/notes/llm-security-guide/) says to enforce access where the data lives. In a RAG system that means the retrieval step, before the model has seen anything.

---

**Sources** (all checked 23 November 2026)
- Sentence Transformers documentation, "Semantic Search": [sbert.net](https://sbert.net/examples/applications/semantic-search/README.html), "Retrieve & Re-Rank": [sbert.net](https://sbert.net/examples/applications/retrieve_rerank/README.html), and "Cross-Encoders": [sbert.net](https://sbert.net/examples/cross_encoder/applications/), and "Semantic Textual Similarity": [sbert.net](https://sbert.net/docs/usage/semantic_textual_similarity.html)
- Weller, Lawrie, Van Durme (Johns Hopkins University), "NevIR: Negation in Neural Information Retrieval", EACL 2024: [arxiv.org/abs/2305.07614](https://arxiv.org/abs/2305.07614) and [aclanthology.org](https://aclanthology.org/2024.eacl-long.139)
- Nogueira, Cho, "Passage Re-ranking with BERT", 2019: [arxiv.org/abs/1901.04085](https://arxiv.org/abs/1901.04085)
- Zou, Geng, Wang, Jia, "PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models", USENIX Security 2025: [arxiv.org/abs/2402.07867](https://arxiv.org/abs/2402.07867) and [usenix.org](https://www.usenix.org/conference/usenixsecurity25/presentation/zou)
- Nestaas, Debenedetti, Tramèr (ETH Zürich), "Adversarial Search Engine Optimization for Large Language Models", 2024: [arxiv.org/abs/2406.18382](https://arxiv.org/abs/2406.18382)
- Pfrommer, Bai, Gautam, Sojoudi (UC Berkeley), "Ranking Manipulation for Conversational Search Engines", 2024: [arxiv.org/abs/2406.03589](https://arxiv.org/abs/2406.03589)
- Liu et al., "Order-Disorder: Imitation Adversarial Attacks for Black-box Neural Ranking Models", 2022: [arxiv.org/abs/2209.06506](https://arxiv.org/abs/2209.06506)
- Morris, Kuleshov, Shmatikov, Rush (Cornell University), "Text Embeddings Reveal (Almost) As Much As Text", 2023: [arxiv.org/abs/2310.06816](https://arxiv.org/abs/2310.06816)
- CVE-2025-32711 record (EchoLeak): [db.gcve.eu](https://db.gcve.eu/vuln/CVE-2025-32711), and Microsoft's advisory: [msrc.microsoft.com](https://msrc.microsoft.com/update-guide/vulnerability/CVE-2025-32711)
- OWASP GenAI Security Project, "LLM08:2025 Vector and Embedding Weaknesses": [genai.owasp.org](https://genai.owasp.org/llmrisk/llm082025-vector-and-embedding-weaknesses/)
