RBAC, ABAC and Row-Level Security for RAG

Role-based, attribute-based and row-level access control for retrieval, with PostgreSQL examples.

Last Updated:

Module 21 · Lesson 4 of 7 · Advanced

RBAC, ABAC and Row-Level Security for RAG

Role-based, attribute-based and row-level access control for retrieval, with PostgreSQL examples.

The previous lesson showed the core rule of RAG access control: filter retrieval by the user's permissions before anything reaches the model. This lesson goes further. It compares the main access-control models, RBAC (role-based), ABAC (attribute-based) and row-level security (RLS), and builds a PostgreSQL + pgvector store where the database itself enforces tenant, group and clearance rules on every vector search. Even a buggy query in the application cannot return a row the user may not see.

What you will learn

  • The difference between RBAC, ABAC and row-level security, and when to use each
  • How to express access rules as PostgreSQL RLS policies on a pgvector table
  • How to pass the authenticated user's identity to the database safely
  • How to test that the rules work, and the pitfalls that silently disable them

Prerequisites

The three models

ModelRule looks likeStrengthsWeaknesses
RBAC"Members of hr may read HR documents"Simple, maps to identity-provider groups, easy to auditRole explosion when rules depend on many factors
ABAC"Users may read documents whose classification is at or below their clearance, in their own region"Fine-grained, context-aware (department, region, project, time)Harder to reason about and audit; needs reliable attributes
Row-level securityA database policy that hides rows not matching the session's identityEnforced by the database for every query, even buggy onesTied to a database that supports it; needs careful session handling

These are not alternatives so much as layers. RBAC and ABAC describe what the rules are; RLS is one place to enforce them. The other common enforcement point is a metadata filter built by your application on every vector search, as in the previous lesson. Most real systems combine RBAC (groups from the source system) with a few ABAC attributes (tenant, classification, region).

Step 1: Design the metadata

Every chunk needs the attributes your rules use, copied from the source document at ingestion:

  • tenant_id: the customer or business unit that owns the document (for multi-tenant systems)
  • allowed_groups: groups allowed to read it (RBAC), from the source system's permissions
  • classification: public, internal or confidential (ABAC)

The user side comes from authentication: tenant, groups and clearance level from your identity provider's token or directory, never from the request body.

Step 2: Create the table and policies

Run this as the database owner (for example with psql):

rls_schema.sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS secure_chunks (
    id              bigserial PRIMARY KEY,
    tenant_id       text   NOT NULL,
    source          text   NOT NULL,
    content         text   NOT NULL,
    allowed_groups  text[] NOT NULL,
    classification  text   NOT NULL CHECK (classification IN ('public', 'internal', 'confidential')),
    embedding       vector(384) NOT NULL
);
CREATE INDEX IF NOT EXISTS secure_chunks_embedding_idx
    ON secure_chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX IF NOT EXISTS secure_chunks_groups_idx ON secure_chunks USING gin (allowed_groups);

-- Turn RLS on. FORCE makes it apply to the table owner too.
ALTER TABLE secure_chunks ENABLE ROW LEVEL SECURITY;
ALTER TABLE secure_chunks FORCE ROW LEVEL SECURITY;

-- Permissive policy: rows of the session's tenant are candidates.
CREATE POLICY tenant_isolation ON secure_chunks
    USING (tenant_id = current_setting('app.tenant_id', true));

-- Restrictive policies are ANDed with the permissive one.
-- RBAC: the row's groups must overlap the user's groups.
CREATE POLICY group_access ON secure_chunks AS RESTRICTIVE
    USING (allowed_groups && string_to_array(current_setting('app.user_groups', true), ','));

-- ABAC: the row's classification must not exceed the user's clearance.
CREATE POLICY clearance_access ON secure_chunks AS RESTRICTIVE
    USING (
        CASE classification WHEN 'public' THEN 0 WHEN 'internal' THEN 1 ELSE 2 END
        <= coalesce(nullif(current_setting('app.clearance', true), '')::int, 0)
    );

-- The application connects as a separate, non-owner role with read-only access.
-- Create the role with your usual tooling and keep its password in a secrets manager.
GRANT SELECT ON secure_chunks TO rag_app;

How the policies combine: PostgreSQL ORs all permissive policies together and ANDs every restrictive policy on top, so a row is visible only if it is in the user's tenant and shares a group and is within their clearance. The true argument to current_setting returns NULL instead of an error when a setting is missing, and the nullif handles an empty value, so a session that forgot to set its identity sees no rows: the policies fail closed.

Step 3: Set the identity for each request

The application authenticates the user, then sets the identity as transaction-local settings before searching. set_config(..., true) scopes the values to the current transaction, so they cannot leak to the next request that reuses the pooled connection.

secure_search.py
import os
from dataclasses import dataclass

import psycopg
from pgvector.psycopg import register_vector
from rag_helpers import embed

@dataclass(frozen=True)
class User:
    """Built from the verified identity token, never from request parameters."""
    user_id: str
    tenant_id: str
    groups: tuple[str, ...]
    clearance: int            # 0 = public, 1 = internal, 2 = confidential

def connect() -> psycopg.Connection:
    conn = psycopg.connect(os.environ["RAG_APP_DATABASE_URL"])   # connects as rag_app
    register_vector(conn)
    return conn

def secure_search(conn: psycopg.Connection, user: User, question: str, k: int = 5) -> list[tuple]:
    if any("," in g for g in user.groups):
        raise ValueError("group names must not contain commas")
    query_vector = embed(question, query=True)[0]
    with conn.transaction():
        conn.execute(
            "SELECT set_config('app.tenant_id', %s, true), "
            "       set_config('app.user_groups', %s, true), "
            "       set_config('app.clearance', %s, true)",
            (user.tenant_id, ",".join(user.groups), str(user.clearance)),
        )
        return conn.execute(
            "SELECT source, classification, content FROM secure_chunks "
            "ORDER BY embedding <=> %s LIMIT %s",
            (query_vector, k),
        ).fetchall()

Notice that the search query has no WHERE clause at all. The database adds the policies to every query on the table, so even a developer who forgets the filter cannot leak rows.

Step 4: Load sample data and test

Insert test rows as the owner (RLS is forced, so the owner must also satisfy the policies; a simple approach for loading is a separate ingestion role with an INSERT policy, or a role with the BYPASSRLS attribute used only by the ingestion job). Then check the behaviour for different users:

test_rls.py
from secure_search import User, connect, secure_search

conn = connect()
question = "What are the salary bands?"

alice = User("alice", "acme", ("hr", "staff"), clearance=2)     # HR, confidential clearance
bob = User("bob", "acme", ("staff",), clearance=1)              # ordinary employee
eve = User("eve", "globex", ("hr",), clearance=2)               # HR, but another tenant

for user in (alice, bob, eve):
    rows = secure_search(conn, user, question, k=3)
    print(user.user_id, [(source, level) for source, level, _ in rows])
alice [('hr/salary-bands-2026.pdf', 'confidential'), ('handbook/pay.md', 'internal'), ('handbook/benefits.md', 'internal')]
bob [('handbook/pay.md', 'internal'), ('handbook/benefits.md', 'internal'), ('handbook/holidays.md', 'public')]
eve []

Turn these into automated tests: for each role, assert that restricted sources never appear. Add a test that runs a search without setting the identity and expects zero rows, to prove the policies fail closed.

Filtering and recall

With an HNSW index, PostgreSQL finds nearest neighbours first and then applies the policy filter, so a restrictive filter can return fewer than k rows. pgvector 0.8 and later can keep scanning the index until enough rows pass the filter: enable it with SET hnsw.iterative_scan = relaxed_order; (check the pgvector documentation for your version). For very selective filters, such as small tenants in a large table, partitioning by tenant or a partial index per tenant also helps.

ABAC in the application layer

If your vector database has no row-level security, apply the same attribute rules as a filter on every search, built by one function that every query path must use:

LEVELS = {"public": 0, "internal": 1, "confidential": 2}

def allowed_filter(user: User) -> dict:
    """One place that turns a user into a retrieval filter (adapt to your vector DB's syntax)."""
    return {
        "tenant_id": user.tenant_id,
        "allowed_groups": {"any_of": list(user.groups)},
        "classification": {"in": [name for name, level in LEVELS.items() if level <= user.clearance]},
    }

Keep this function small, reviewed and covered by tests; it is your security boundary.

Common errors and pitfalls

  • Everyone sees every row: the application connects as a superuser or a role with BYPASSRLS, both of which ignore policies. Use a dedicated, non-owner role.
  • The owner sees everything: you enabled RLS but did not FORCE it; table owners bypass policies unless forced.
  • Identity leaks between requests: you used session-level SET on a pooled connection. Use set_config(..., true) inside a transaction.
  • No rows for anyone: you created only restrictive policies. At least one permissive policy must allow the row.
  • Stale permissions: allowed_groups must be re-synced when a document's permissions change in the source system.
  • Caches bypass the rules: a semantic cache shared across users can return another user's answer. Include the permission scope in cache keys.

Key takeaways

  • RBAC uses roles and groups; ABAC adds attributes such as tenant, classification and region.
  • PostgreSQL row-level security enforces the rules inside the database for every vector search.
  • Set the user's identity per transaction with set_config(..., true), from the verified token.
  • Use a non-owner role, force RLS, fail closed, and test every role automatically.

Frequently asked questions

Does row-level security slow down vector search?

It adds a filter to every query. The group overlap check is cheap, and a GIN index on the array helps when it is used for filtering. Measure with EXPLAIN ANALYZE on realistic data, and use iterative scans or partitioning when filters are very selective.

Can I use RLS with other vector databases?

RLS is a PostgreSQL feature. Most dedicated vector databases instead offer namespaces, collections or tenants for isolation plus metadata filters, which your application must apply on every query.

Practice exercises

  1. Add a region attribute and a restrictive policy so that users only see documents for their own region or for "global".
  2. Write a pytest suite that creates three users and asserts which sources each can and cannot retrieve.

Related tutorials