Skip to content
PremityPublic

About

Enterprise RAG knowledge platform with 7-tier RBAC — LangGraph agents route queries across PostgreSQL and Qdrant, scoping every answer to the user's clearance and department.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

RoleGate

Enterprise RAG platform with multi-dimensional role-based access control. Users query structured company data and unstructured documents through an AI chat interface that enforces a seven-tier permission hierarchy — the same question asked by a CEO, a Manager, and a Contractor returns different answers, each scoped to what that role can see.


Architecture

React 18 + Vite  ──▶  FastAPI (Python 3.12)
                           │
                    LangGraph pipeline
                    ┌──────────────────────┐
                    │  auth → cleaner →    │
                    │  router              │
                    │    ├─ sql     ──────▶│──▶ PostgreSQL
                    │    ├─ vector  ──────▶│──▶ Qdrant (HyDE + rerank)
                    │    ├─ hybrid  ──────▶│──▶ both, parallel
                    │    ├─ general ──────▶│──▶ synthesis only
                    │    ├─ reject  ──────▶│──▶ canned response
                    │    └─ admin   ──────▶│──▶ Qdrant (admin_docs)
                    │                      │
                    │  Cross-Encoder rerank│
                    │  Synthesis (LiteLLM) │
                    └──────────────────────┘

Services

Service Image Port Purpose
frontend Custom (Nginx + React build) 3000 React SPA
backend Custom (Python 3.12) 8000 FastAPI + LangGraph
db postgres:16-alpine 5432 Users, RBAC, CSV tables
qdrant qdrant/qdrant:latest 6333 / 6334 Document vector store

Tech Stack

Layer Technology
Frontend React 18, Vite, TypeScript, Tailwind CSS, shadcn/ui, Zustand, TanStack Query
Backend Python 3.12, FastAPI, LangGraph
AI Gateway LiteLLM — swap models via LLM_MODEL env var, no code changes
Generation Gemini gemini-2.0-flash (default) or Groq llama-3.3-70b-versatile
Embeddings all-mpnet-base-v2 locally, or Cloudflare Workers AI bge-base-en-v1.5 — both 768-dim
Reranker ms-marco-MiniLM-L-6-v2 locally, or Cohere rerank-v3.5 via LiteLLM
Vector Store Qdrant — company_docs and admin_docs collections
Relational DB PostgreSQL 16 + Alembic migrations
Deployment Docker Engine + Docker Compose

RBAC Hierarchy

Seven roles across two access dimensions: clearance level (0–4) and scope.

Role Level Scope Data Access
Super Admin 0 system User/role management only. Chat routes to admin_docs, never company data.
C-Suite 4 global All departments, all document levels
Auditor 3 global Read-only across all departments
Director 3 multi_dept Assigned departments only (junction table)
Manager 2 department Own department only
Employee 1 department Own department, level 1 docs only
Contractor 1 project Explicitly assigned projects only (junction table)

RBAC is enforced in two places simultaneously:

  • PostgreSQL: WHERE department_id IN (...) and WHERE min_level <= ? on every query
  • Qdrant: hard payload filter {dept_id: ..., min_level: ≤ level} on every vector search

Getting Started

Prerequisites

  • Docker Engine 25+ and Docker Compose v2
  • Gemini API key (free tier works)
  • Groq API key (optional — faster inference)

Setup

# 1. Clone
git clone https://github.com/Premity/RoleGate.git
cd RoleGate

# 2. Configure
cp .env.example .env
# Edit .env — add GEMINI_API_KEY and a strong JWT_SECRET_KEY:
#   python -c "import secrets; print(secrets.token_hex(32))"

# 3. Start all services
docker compose up --build

# 4. Run migrations (first run only)
docker compose exec backend alembic upgrade head

# 5. Seed demo users, roles, departments, and projects
docker compose exec backend python scripts/seed.py

The app is now running:

URL What
http://localhost:3000 React frontend
http://localhost:8000/docs FastAPI interactive docs
http://localhost:6333/dashboard Qdrant dashboard

Demo Users

Username Password Role What they can see
superadmin admin123 Super Admin Admin docs only; no company data
ceo_jane pass123 C-Suite Everything
auditor_bob pass123 Auditor All departments, read-only
vp_sara pass123 Director Engineering + HR departments
sales_mgr_tom pass123 Manager Sales department only
eng_alice pass123 Employee Engineering, level 1 docs only
contractor_dave pass123 Contractor Q4 Launch project only

Ingest Demo Data

After seeding users, load the demo datasets so queries return real data:

# Get a token for a manager (Sales)
TOKEN=$(curl -s -X POST http://localhost:8000/auth/token \
  -d "username=sales_mgr_tom&password=pass123" | jq -r .access_token)

# Upload a CSV (becomes a queryable PostgreSQL table)
curl -X POST http://localhost:8000/documents/upload \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@data/seed/sales_orders.csv" \
  -F "department_id=3" -F "min_level=1"

# Upload a document (goes into Qdrant with RBAC payload)
curl -X POST http://localhost:8000/documents/upload \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@data/docs/sales_strategy_2025.md" \
  -F "department_id=3" -F "min_level=1"

Seed files available in data/:

  • data/seed/ — sales_orders.csv, hr_employees.csv, inventory.csv
  • data/docs/ — engineering_onboarding.md, hr_restructuring_plan.md, q4_launch_specs.md, sales_strategy_2025.md
  • data/admin_docs/ — system_admin_guide.md (Super Admin only)

Project Structure

RoleGate/
├── backend/
│   ├── app/
│   │   ├── api/              Route handlers
│   │   │   ├── auth.py       POST /auth/token — JWT issuance
│   │   │   ├── chat.py       WebSocket /chat — streaming chat (unused in current UI)
│   │   │   ├── documents.py  POST /documents/upload — CSV + markdown ingestion
│   │   │   ├── query.py      POST /query — main query endpoint (invokes LangGraph)
│   │   │   └── users.py      GET/POST /users — user management (Super Admin only)
│   │   ├── core/
│   │   │   ├── auth_deps.py  FastAPI dependency — validates JWT, loads User from DB
│   │   │   ├── config.py     Pydantic Settings — reads from .env
│   │   │   ├── database.py   SQLAlchemy engine, SessionLocal, get_db_session() context manager
│   │   │   ├── logging_config.py  Rotating file + stderr logging setup
│   │   │   ├── rbac.py       build_user_rbac(), apply_sql_rbac(), build_qdrant_filter()
│   │   │   └── security.py   hash_password(), verify_password(), create_access_token()
│   │   ├── models/
│   │   │   ├── db_models.py  SQLAlchemy ORM — UserRole, User, Department, Project, DataTableRegistry
│   │   │   └── schemas.py    Pydantic request/response schemas
│   │   ├── agent/
│   │   │   ├── state.py      AgentState TypedDict, UserRBAC, SQLResult, VectorResult, VALID_ROUTES
│   │   │   ├── graph.py      LangGraph graph — all 6 edges wired, compile-time edge/route sync check
│   │   │   └── nodes/
│   │   │       ├── auth_node.py      Gates Super Admin to admin route before any data access
│   │   │       ├── cleaner_node.py   LLM pass — normalizes abbreviations, dates, typos; no intent rewrite
│   │   │       ├── router_node.py    LLM classifies query into one of 6 route labels
│   │   │       ├── sql_agent.py      Schema introspection → NL-to-SQL → RBAC-filtered execution
│   │   │       ├── vector_agent.py   HyDE → Qdrant filtered search → cross-encoder rerank → top 5
│   │   │       └── synthesis_node.py Assembles SQL + vector context, calls LLM for Markdown answer
│   │   └── services/
│   │       ├── llm.py           LiteLLM text generation + local sentence-transformers embeddings
│   │       ├── qdrant_service.py  ensure_collections(), search_company_docs(), search_admin_docs()
│   │       ├── reranker.py      cross-encoder/ms-marco-MiniLM-L-6-v2 loaded once, rerank() function
│   │       └── ingestion.py     CSV → PostgreSQL table + DataTableRegistry; MD → hierarchical chunks → Qdrant
│   ├── migrations/             Alembic migrations (env.py + versions/)
│   ├── scripts/seed.py         Idempotent seed — roles, departments, projects, demo users + junction rows
│   ├── main.py                 FastAPI app factory — mounts routers, runs ensure_collections() on startup
│   ├── requirements.txt
│   └── Dockerfile
├── frontend/
│   └── src/
│       ├── pages/
│       │   ├── LoginPage.tsx        Auth form, ripple theme toggle
│       │   ├── ChatPage.tsx         Chat interface with message history, Markdown rendering
│       │   ├── DataExplorerPage.tsx Browse accessible SQL tables + document registry
│       │   ├── DocsPage.tsx         Document viewer
│       │   └── AdminPage.tsx        Super Admin panel — user management, role assignment
│       ├── components/
│       │   └── layout/
│       │       ├── AppLayout.tsx    Shell — sidebar toggle, theme toggle, route guard
│       │       └── Sidebar.tsx      Navigation links, user badge, logout
│       ├── store/
│       │   ├── authStore.ts   Zustand — JWT token + decoded user claims, persisted to localStorage
│       │   ├── chatStore.ts   Zustand — message history per session
│       │   └── themeStore.ts  Zustand — dark/light with View Transitions API ripple effect
│       ├── api/client.ts      Axios instance — base URL, Authorization header injected from authStore
│       └── types/index.ts     Shared TypeScript types
├── data/
│   ├── seed/                  Demo CSVs — sales_orders, hr_employees, inventory
│   ├── docs/                  Demo markdown docs at access levels 1–3
│   └── admin_docs/            system_admin_guide.md — Super Admin only (admin_docs Qdrant collection)
├── logs/
│   ├── backend/               app.log (rotating, 10 MB × 5 files)
│   └── nginx/                 access.log, error.log
├── docker-compose.yml
├── .env.example               Copy to .env and fill in keys
└── CLAUDE.md                  AI assistant context for development sessions

Key Behaviours

LLM calls all go through LiteLLM. app/services/llm.py is the only place that touches any LLM SDK. Switching from Gemini to Groq is a one-line .env change (LLM_MODEL).

Embeddings run locally. all-mpnet-base-v2 via sentence-transformers — no API key needed, no network call per query. 768-dim vectors, loaded once at import time.

Chunking is hierarchical. Documents are split into parent chunks (~512 tokens, semantic boundaries) then child chunks (~128 tokens). Child chunks are embedded and stored in Qdrant with the parent text inline in the payload. Searches hit child chunks for precision; synthesis reads the parent text for context — no second Qdrant lookup.

HyDE before vector search. The vector agent generates a hypothetical answer paragraph, embeds that, and uses the resulting vector for Qdrant search. This improves recall for questions whose phrasing differs from how documents are written. Falls back to raw query embedding if HyDE fails.

RBAC is enforced at the data layer, not just the API. Every SQL query and every Qdrant search carries the user's access claims as hard filters. There is no code path that retrieves data and then filters it in Python — the databases do it.

Super Admin is hard-gated. auth_node.py sets route = "admin" for any is_system_admin = true user before the cleaner or router runs. Company data collections are never queried.

Router NameError protection. router_node.py validates the LLM's route label against VALID_ROUTES (imported from state.py). graph.py asserts at startup that its edge map keys match VALID_ROUTES exactly — a missing or extra route is a crash at boot, not a silent runtime error.


Environment Variables

See .env.example for the full list. Minimum required:

Variable Description
GEMINI_API_KEY Gemini API key for generation and (optionally) embeddings
JWT_SECRET_KEY Random hex string — python -c "import secrets; print(secrets.token_hex(32))"
POSTGRES_PASSWORD PostgreSQL password (any non-empty value)

LLM_MODEL defaults to gemini/gemini-2.0-flash. Set to groq/llama-3.3-70b-versatile and add GROQ_API_KEY to switch.

Providers

Embedding and reranking each run either in-process or against a hosted API:

Variable Values Default
EMBEDDING_PROVIDER local, cloudflare local
RERANKER_PROVIDER local, cohere local

Defaults keep everything on-device, so docker compose up needs no extra keys.

The hosted providers exist for deployment: sentence-transformers and torch account for roughly 1.8 GB of the container image, which is more than most free hosting tiers allow.

# Local models (default) — 2.54 GB image
docker build -t rolegate-backend ./backend

# Hosted providers — 731 MB image
docker build --build-arg REQUIREMENTS=requirements-deploy.txt -t rolegate-backend ./backend

The slim image has no torch, so local providers raise a clear error there.

Both embedding models output 768 dimensions and the Qdrant collection is unchanged — but vectors from different models are not comparable, so switching provider means re-ingesting documents.

Rate limiting

RATE_LIMIT_ENABLED=true caps per-user calls on the endpoints that spend third-party quota (RATE_LIMIT_QUERIES_PER_HOUR, RATE_LIMIT_UPLOADS_PER_HOUR). Intended for public demos where every visitor shares one set of API keys; leave it off locally. Counters are per-process, so multiple replicas would need shared storage to be exact.


Useful Commands

# View live backend logs
docker compose logs -f backend

# Re-run seed after DB wipe (idempotent — safe to run multiple times)
docker compose exec backend python scripts/seed.py

# Create a new Alembic migration after changing db_models.py
docker compose exec backend alembic revision --autogenerate -m "description"
docker compose exec backend alembic upgrade head

# Open a psql shell
docker compose exec db psql -U rolegate -d rolegate_db

# Hot-reload: backend syncs automatically via Docker watch (docker compose watch)
# Frontend: Vite HMR runs inside the container — changes reflect on save

Docs

Doc Contents
docs/pipeline.md LangGraph pipeline — every node, state shape, routing logic, how to add a new route
docs/rbac.md RBAC design — role table, apply_sql_rbac, build_qdrant_filter, JWT claims, DB schema
docs/services.md Backend services — LLM gateway, embeddings, reranker, Qdrant client, ingestion
docs/frontend.md Frontend — pages, Zustand stores, Axios client, routing, styling, design system

License

MIT

About

Enterprise RAG knowledge platform with 7-tier RBAC — LangGraph agents route queries across PostgreSQL and Qdrant, scoping every answer to the user's clearance and department.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Contributors

Languages