RAG Authorization: Filter Forbidden Evidence Before It Reaches the LLM

It’s 3:00 AM. Your company's new AI assistant, built on a state-of-the-art Retrieval-Augmented Generation (RAG) architecture, is live in production. An enterprising product manager decides to test its boundaries. They type a simple, innocuous query into the chat interface: “Show me the executive compensation review from last quarter.”

Your vector database, optimized entirely for semantic similarity rather than security, immediately returns the top five chunks from an internal HR storage bucket. The dense embedding model calculated a high cosine similarity between the query and the restricted document. Without skipping a beat, your orchestration framework injects those sensitive salary brackets into the context window and passes the prompt to your LLM.

The model responds with polite, highly detailed bullet points outlining what the CEO and VP of Engineering make.

Your vector search engine did its job. Your RAG pipeline did its job. But your system just leaked confidential data because of a fundamental architectural flaw: you trusted your retrieval layer with your security policy.

In production AI systems, RAG authorization is the missing link that separates secure enterprise software from expensive compliance nightmares. Too many developers treat access control as an afterthought, relying on post-generation guardrails, system prompts (“Please don’t share things users shouldn’t see”), or naive metadata filtering that breaks down under complex organizational hierarchies.

To build RAG applications that survive real-world security audits, you need to filter forbidden evidence before it ever touches the LLM context window.


📋 Table of Contents


The Illusion of Prompt-Level Security

Let’s address the elephant in the room. Many engineering teams believe they can solve authorization by writing strict instructions into their system prompts.

They write something like this:

You are an enterprise HR assistant. You will be provided with context chunks retrieved from internal storage. 
CRITICAL RULE: If the user does not have permission to view a document, refuse to answer. Do not repeat information marked with `classification: confidential`.

This approach fails for two reasons: adversarial prompt injection and attention dilution.

Even if your users aren't malicious, LLMs are probabilistic completion engines, not deterministic access control enforcers. If you pass a classified document into the context window alongside the prompt, the model already possesses the data.

Once the data enters the GPU memory and populates the context window, you have already leaked it at the infrastructure layer.

┌──────────────┐     1. Query     ┌─────────────────┐
│              │─────────────────>│ Vector Database │
│              │                  └─────────────────┘
│              │                           │
│              │     2. Leaks Docs         │ (Returns forbidden chunks
│    Client    │     (Bypasses ACLs)       │  because vector search
│              │<──────────────────────────┘  only cares about semantics)
│              │
│              │     3. Injects into Context
│              │     ┌────────────────────────────────────────┐
│              │     │ [PROMPT] Here is the secret data: ...  │
│              │     └────────────────────────────────────────┘
│              │                           │
│              │                           v
│              │                  ┌─────────────────┐
│              │                  │       LLM       │
│              │                  └─────────────────┘
└──────────────┘                           │
                                           │ 4. "Here is the CEO's salary..."
                                           v

Furthermore, sending unauthorized chunks to the LLM increases token costs, dilutes the attention mechanism over irrelevant data, and increases latency. True RAG authorization requires intercepting the retrieval phase before the vector distance search executes or immediately upon its raw output—never after the prompt has been assembled.


1. Post-Retrieval Filtering: The Naive Approach That Burns Tokens

Scenario: You build a standard RAG pipeline using LangChain or LlamaIndex. You query your vector database for the top 20 most similar chunks, iterate over them in Python, check the user's permissions against a relational database, and discard the unauthorized chunks before sending the remaining 5 to the LLM.

Why it matters: While this technically prevents the LLM from seeing unauthorized data, it introduces severe operational bottlenecks. If a low-privilege user queries a topic dominated by restricted documents, your vector search might return 20 chunks, all of which get filtered out. You end up with zero context to send to the LLM, or worse, you retrieve 20 chunks, pay for the embedding lookup and vector distance calculation, query your PostgreSQL database 20 times for ACL verification, and then throw away 90% of your results.

Solution: If you must use post-retrieval filtering, you must over-fetch by a safety factor, apply asynchronous permission checks, and handle empty context gracefully without failing the request.

import asyncio
from typing import List, Dict, Any

async def verify_document_acl(user_id: str, document_ids: List[str]) -> Set[str]:
    """
    Simulates an asynchronous check against an external authorization service (e.g., OpenFGA, SpiceDB)
    """
    # In production, batch this query to your auth engine
    allowed_docs = set()
    for doc_id in document_ids:
        # Mock check: assume user_id 'admin' has access to everything, 
        # others only to docs they own or share.
        if user_id == "admin" or doc_id.startswith(f"public-{user_id}"):
            allowed_docs.add(doc_id)
    return allowed_docs

async def secure_rag_post_filter(
    query: str, 
    user_id: str, 
    vector_store: Any, 
    k: int = 5, 
    over_fetch_factor: int = 4
) -> List[Dict[str, Any]]:
    
    # 1. Over-fetch from the vector database to account for dropped chunks
    raw_results = await vector_store.asimilarity_search_with_score(
        query, k=k * over_fetch_factor
    )
    
    # Extract document IDs and map them back to chunks
    doc_id_to_chunk = {res.metadata["document_id"]: res for res, score in raw_results}
    all_candidate_doc_ids = list(doc_id_to_chunk.keys())
    
    # 2. Perform batched authorization check
    authorized_doc_ids = await verify_document_acl(user_id, all_candidate_doc_ids)
    
    # 3. Filter and truncate to the requested top-k limit
    secured_chunks = [
        doc_id_to_chunk[doc_id] 
        for doc_id in all_candidate_doc_ids 
        if doc_id in authorized_doc_ids
    ]
    
    return secured_chunks[:k]

Why this works: By over-fetching by a factor of 4, you statistically guarantee that you will still have enough valid chunks to fill your context window even if the user lacks access to a large portion of the semantic neighborhood.

⚠️ Gotcha: If an enterprise user belongs to zero accessible documents matching a query, over-fetching will still result in zero valid chunks. Your application logic must explicitly handle empty context scenarios to prevent the LLM from hallucinating an answer based on its pre-trained weights while pretending it used internal documents.


2. Metadata Filtering in Vector Databases: When Exact Match Fails Context

Scenario: Your vector database (such as Pinecone, Qdrant, Milvus, or pgvector) supports metadata filtering. You tag every vector chunk with JSON metadata like {"department": "engineering", "clearance_level": 2, "project_id": "alpha"}. When a user executes a query, you dynamically attach a pre-filter expression to the vector search.

Why it matters: Metadata filtering is vastly superior to post-retrieval filtering because it pushes the security boundary down into the database storage engine. The vector similarity search is performed only across vectors that match the security predicate. However, metadata schemas are notoriously rigid. What happens when a document is shared with a specific list of user IDs rather than an entire department?

Solution: Store array-based access control lists (ACLs) or role tokens inside the vector metadata, and use array-intersection query operators during the vector search execution.

from qdrant_client import QdrantClient
from qdrant_client.http import models

def search_with_qdrant_acls(
    client: QdrantClient, 
    collection_name: str, 
    query_vector: List[float], 
    user_id: str, 
    user_groups: List[str], 
    top_k: int = 5
) -> List[models.ScoredPoint]:
    
    # Construct a filter that checks if the user's ID is in the document's 
    # allowed_users array OR any of the user's groups match the document's allowed_groups array.
    security_filter = models.Filter(
        should=[
            models.FieldCondition(
                key="allowed_users",
                match=models.MatchValue(value=user_id)
            ),
            models.FieldCondition(
                key="allowed_groups",
                match=models.MatchAny(any=user_groups)
            )
        ]
    )
    
    search_result = client.search(
        collection_name=collection_name,
        query_vector=query_vector,
        query_filter=security_filter,
        limit=top_k
    )
    
    return search_result

Why this works: Qdrant, Milvus, and Pinecone evaluate these metadata filters as part of the indexing or pre-filtering phase (depending on the index configuration, such as HNSW graph traversal with bitset masking). This ensures that forbidden evidence is never even evaluated for vector distance similarity, reducing compute overhead and eliminating leakage paths.

💡 Practical note: Be careful with high-cardinality array filters in large vector stores. If your allowed_users array contains thousands of user IDs for a globally shared document, vector database index performance can degrade significantly during filter evaluation.


3. Pre-Retrieval Document ACLs and Sparse Index Sharding

Scenario: Your organization has strict compliance mandates (such as HIPAA or SOC2 Type II) requiring physical or logical separation of data partitions. Storing everything in a single massive vector collection with metadata tags isn't enough; an auditor wants proof that unauthorized embeddings cannot even be queried.

Why it matters: Shared collections rely on software-level filter enforcement. If a developer accidentally writes a query without the query_filter parameter, the entire index is exposed. You need an architecture where security is baked into the storage topology.

Solution: Implement Namespace Sharding or Tenant-Specific Indices. Instead of filtering large collections by metadata, partition your vector store into isolated indices or namespaces where each namespace corresponds strictly to a security clearance tier or tenant ID.

class SegmentedVectorRouter:
    def __init__(self, client):
        self.client = client

    def get_collection_name(self, security_tier: int) -> str:
        return f"enterprise_docs_tier_{security_tier}"

    def secure_search(
        self, 
        query_vector: List[float], 
        user_clearance_tier: int, 
        top_k: int = 5
    ):
        # Users can only query collections matching their clearance level or lower
        accessible_tiers = [t for t in range(1, user_clearance_tier + 1)]
        
        all_results = []
        for tier in accessible_tiers:
            collection_name = self.get_collection_name(tier)
            results = self.client.search(
                collection_name=collection_name,
                query_vector=query_vector,
                limit=top_k
            )
            all_results.extend(results)
            
        # Sort combined results by similarity score and take top_k
        all_results.sort(key=lambda x: x.score, reverse=True)
        return all_results[:top_k]

Why this works: Physical separation eliminates the risk of missing filter clauses. If a user shouldn't have access to Tier 3 documents, the application code doesn't even construct a search call against the Tier 3 collection.


4. Graph-Based Authorization for Nested Team Hierarchies

Scenario: Your company uses complex organizational structures. Alice is the Director of Engineering. Engineering contains Backend, Frontend, and AI teams. The AI team has a sub-project called "Project Chimera." A document is tagged as accessible only to members of "Project Chimera" or higher management tiers.

Why it matters: Flat metadata lists (allowed_groups: ["ai-team"]) break down when hierarchical inheritance is required. If Alice is not explicitly listed in the allowed_users or allowed_groups array of a document chunk, simple string-matching metadata filters will deny her access, causing executive frustration and support tickets.

Solution: Integrate a Relationship-Based Access Control (ReBAC) engine like OpenFGA, SpiceDB, or Casbin into your RAG pipeline to resolve recursive group memberships before generating vector search filters.

import openfga_sdk
from openfga_sdk.client import OpenFGAClient
from openfga_sdk.models import ClientCheckRequest

async def user_has_document_access(
    fga_client: OpenFGAClient, 
    user_id: str, 
    document_id: str
) -> bool:
    """
    Checks if a user has access to a document via OpenFGA graph traversal.
    """
    body = ClientCheckRequest(
        user=f"user:{user_id}",
        relation="can_view",
        object=f"document:{document_id}"
    )
    
    response = await fga_client.check(body)
    return response.allowed
     [User: Alice]
           │
           v (member_of)
    [Group: Engineering]
           │
           v (child_group)
    [Group: AI Team]
           │
           v (parent_project)
    [Object: Project Chimera Doc]

Why this works: ReBAC engines evaluate graph traversals in milliseconds. By querying the authorization graph before retrieval, you can translate complex hierarchical relationships into an explicit list of permitted document IDs, which are then passed as an IN (...) filter directly to your vector search query.


5. Hybrid RAG Security: Combining Vector Embeddings with Policy Engines

Scenario: You are building an advanced RAG platform where permissions depend not just on who the user is, but contextual attributes—such as time of day, geographic location, device compliance, and document classification tags.

Why it matters: Static ACLs and basic role checks are insufficient for modern zero-trust enterprise architectures. You need Attribute-Based Access Control (ABAC) evaluated dynamically alongside semantic retrieval.

Solution: Adopt a hybrid architecture where the retrieval request passes through an external Policy Decision Point (PDP) such as OPA (Open Policy Agent) before hitting the vector database.

# Example OPA Policy (rego)
package ragger.authz

default allow = false

allow {
    input.user.clearance >= input.document.classification
    input.user.department == input.document.department
    input.context.is_work_hours == true
}
import requests

def evaluate_opa_policy(user_context: dict, document_metadata: dict) -> bool:
    """
    Sends user context and document metadata to Open Policy Agent for evaluation.
    """
    opa_url = "http://localhost:8181/v1/data/ragger/authz/allow"
    payload = {
        "input": {
            "user": user_context,
            "document": document_metadata,
            "context": {"is_work_hours": True}
        }
    }
    
    response = requests.post(opa_url, json=payload)
    return response.json().get("result", False)

Why this works: Decoupling authorization logic from your application code ensures that security policies remain centralized, testable, and auditable by security teams without requiring constant code deployments in your AI microservice.


6. Handling Multi-Tenant Embeddings Without Vector Bloat

Scenario: You run a multi-tenant SaaS application hosting data for hundreds of different companies. Each company's data must be strictly isolated. You could spin up a separate vector database collection for every tenant, but at 500 tenants, your cluster management overhead and connection pooling limits become unsustainable.

Why it matters: If you store all tenants in a single collection and rely entirely on metadata filters like tenant_id: "tenant_xyz", a single bug in your query builder could expose Tenant A's data to Tenant B. However, managing thousands of physical indices is an infrastructure nightmare.

Solution: Use Tenant-Prefixed Vector Namespace Sharding combined with deterministic metadata partitioning, or leverage vector databases that natively support row-level security (RLS) policies at the storage layer (such as pgvector with PostgreSQL RLS enabled).

-- PostgreSQL + pgvector with Row Level Security (RLS)
CREATE TABLE enterprise_embeddings (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    document_id UUID NOT NULL,
    content TEXT,
    embedding vector(1536),
    acl_roles TEXT[]
);

-- Enable Row Level Security
ALTER TABLE enterprise_embeddings ENABLE ROW LEVEL SECURITY;

-- Create policy that automatically restricts vector search to the current tenant and user roles
CREATE POLICY tenant_isolation_policy ON enterprise_embeddings
    FOR SELECT
    USING (
        tenant_id = current_setting('app.current_tenant_id')::UUID
        AND (
            current_setting('app.current_user_id')::TEXT = ANY(acl_roles)
            OR 'admin' = ANY(string_to_array(current_setting('app.current_user_roles'), ','))
        )
    );

Why this works: By leveraging PostgreSQL’s native RLS, even if an engineer writes a raw SQL query against enterprise_embeddings without explicitly filtering by tenant_id, the database engine intercepts the query and automatically appends the security predicate. This provides a robust defense-in-depth barrier.

🧠 The important part: Storing embeddings in a relational database with vector extensions (like pgvector) allows you to leverage decades of mature transaction management, connection pooling, and enterprise access control primitives that dedicated vector databases are often still catching up on.


7. Auditing and Logging Blind Spots in Secure RAG Pipelines

Scenario: An internal security audit requests proof of why a specific piece of sensitive data was retrieved during an AI interaction last Tuesday. Your standard application logs show the user prompt and the final LLM response, but they lack visibility into the intermediate retrieval and filtering steps.

Why it matters: Without transparent audit trails for RAG pipelines, debugging false positives (over-filtering) and compliance breaches (data leakage) is nearly impossible. You cannot fix what you cannot inspect.

Solution: Implement structured telemetry and audit logging that captures the Retrieval Trace ID, the raw vector search query, the list of candidate document IDs returned by the vector store, the ACL verification results, and the final set of chunks injected into the context.

import structlog
import uuid

logger = structlog.get_logger()

async def audited_rag_pipeline(user_id: str, query: str, vector_store, auth_engine):
    trace_id = str(uuid.uuid4())
    
    # 1. Retrieval
    raw_chunks = await vector_store.asimilarity_search(query, k=20)
    candidate_doc_ids = [c.metadata["doc_id"] for c in raw_chunks]
    
    logger.info("rag.retrieval.executed", 
                trace_id=trace_id, 
                user_id=user_id, 
                candidate_count=len(candidate_doc_ids),
                candidate_ids=candidate_doc_ids)
    
    # 2. Authorization Filter
    authorized_chunks = []
    dropped_chunks = []
    for chunk in raw_chunks:
        is_allowed = await auth_engine.check(user_id, chunk.metadata["doc_id"])
        if is_allowed:
            authorized_chunks.append(chunk)
        else:
            dropped_chunks.append(chunk.metadata["doc_id"])
            
    logger.info("rag.authorization.filtered",
                trace_id=trace_id,
                user_id=user_id,
                allowed_count=len(authorized_chunks),
                dropped_count=len(dropped_chunks),
                dropped_ids=dropped_chunks)
    
    return authorized_chunks[:5], trace_id

Why this works: Structured logs with unique trace_id identifiers allow security operations teams to trace an incident from the initial user request all the way through the vector store and authorization layer, ensuring complete observability and compliance readiness.


Decision Guide: Choosing Your RAG Authorization Pattern

Pattern Complexity Scalability Security Level Best Use Case
Prompt-Level Rules Low High Critical Failure Prototyping only (never production)
Post-Retrieval Filtering Low to Medium Medium Moderate Small internal apps with low query volume
Metadata Filtering Medium High High Standard enterprise apps with uniform team ACLs
Database-Level RLS (pgvector) Medium High Very High Multi-tenant SaaS with relational user data
Graph / ReBAC Integration High High Maximum Complex enterprise org charts and nested sharing

Securing a RAG pipeline is not a feature you can bolt on after your model is deployed. If your embeddings are searchable, they are accessible—unless you actively enforce authorization before the similarity search executes. By moving your security boundary out of the prompt, away from the LLM, and directly into your vector storage and metadata layers, you ensure that forbidden evidence never sees the light of day.

Post a Comment

Previous Post Next Post