Concepts · Level 2 · Note 5
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.
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.
Animated: why "not happy" lands next to "happy"
- An embedding model turns each sentence into an arrow. The direction stands for what the sentence is about.
- A sentence on another subject points somewhere else. A wide angle means unrelated.
- Now "the customer is NOT happy". It is about the same thing, so its arrow lands almost on top of the first one.
- A question becomes an arrow too. Search fetches the stored arrows that point the closest way.
- Both sentences come back as top matches, though they say opposite things, and the search can easily put the wrong one first. Closeness measures topic, and "not" barely moves the arrow.
- That is the trap, and it cuts both ways: an attacker can write text that points exactly where a question will, so it gets fetched first.
How close two sentences score (higher = closer in meaning)
Embeddings and cosine similarity, technically
An embedding model turns text into a long list of numbers, a vector. The Sentence Transformers documentation 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, 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 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.”
Getting negation right: score on the NevIR benchmark
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.
Animated: fast search first, careful reading second
About 100 candidates come back. Top of the list:
- Refund policy: refunds are allowed
- Old memo: refunds are NOT allowed
- Shipping times
- Refund policy: refunds are allowed
- Shipping times
- Old memo: refunds are NOT allowed
- Stage one is a fast librarian who compares your question with an index card written for each document ahead of time. It scans millions of cards in moments.
- It returns a rough shortlist. Rough means near-misses get in, including a document that says the opposite.
- Stage two is a careful reader, the cross-encoder. It reads your question and each shortlisted document together, word against word.
- It reorders the list. More often than before, the document that truly answers moves up and the misleading one drops.
- Careful reading is slow, which is why it only runs on the shortlist. In one documented example, comparing 10,000 sentences with each other takes about 65 hours this way, while the fast way works out all the coordinates in 5 seconds.
- A reranker improves accuracy. It still reads whatever is in the document, including text an attacker wrote to be ranked first.
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. 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 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.
The RAG pipeline and where each weakness and attack lands
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, 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.
Three results that changed how RAG is threat-modeled
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 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 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 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” 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, 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 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.
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.
- 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.”
- 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.”
- Is hidden text stripped before embedding? White-on-white text, tiny fonts, comments and metadata should be removed or flagged during ingestion.
- Is the vector store protected like the source documents? Give it the same access rules, encryption and logging. The Cornell result is the reason.
- 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.
- 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 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, “Retrieve & Re-Rank”: sbert.net, and “Cross-Encoders”: sbert.net, and “Semantic Textual Similarity”: sbert.net
- Weller, Lawrie, Van Durme (Johns Hopkins University), “NevIR: Negation in Neural Information Retrieval”, EACL 2024: arxiv.org/abs/2305.07614 and aclanthology.org
- Nogueira, Cho, “Passage Re-ranking with BERT”, 2019: 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 and usenix.org
- Nestaas, Debenedetti, Tramèr (ETH Zürich), “Adversarial Search Engine Optimization for Large Language Models”, 2024: arxiv.org/abs/2406.18382
- Pfrommer, Bai, Gautam, Sojoudi (UC Berkeley), “Ranking Manipulation for Conversational Search Engines”, 2024: 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
- Morris, Kuleshov, Shmatikov, Rush (Cornell University), “Text Embeddings Reveal (Almost) As Much As Text”, 2023: arxiv.org/abs/2310.06816
- CVE-2025-32711 record (EchoLeak): db.gcve.eu, and Microsoft’s advisory: msrc.microsoft.com
- OWASP GenAI Security Project, “LLM08:2025 Vector and Embedding Weaknesses”: genai.owasp.org