* feat: Implement multi-tenant architecture with tenant and knowledge base models - Added data models for tenants, knowledge bases, and related configurations. - Introduced role and permission management for users in the multi-tenant system. - Created a service layer for managing tenants and knowledge bases, including CRUD operations. - Developed a tenant-aware instance manager for LightRAG with caching and isolation features. - Added a migration script to transition existing workspace-based deployments to the new multi-tenant architecture. * chore: ignore lightrag/api/webui/assets/ directory * chore: stop tracking lightrag/api/webui/assets (ignore in .gitignore) * feat: Initialize LightRAG Multi-Tenant Stack with PostgreSQL - Added README.md for project overview, setup instructions, and architecture details. - Created docker-compose.yml to define services: PostgreSQL, Redis, LightRAG API, and Web UI. - Introduced env.example for environment variable configuration. - Implemented init-postgres.sql for PostgreSQL schema initialization with multi-tenant support. - Added reproduce_issue.py for testing default tenant access via API. * feat: Enhance TenantSelector and update related components for improved multi-tenant support * feat: Enhance testing capabilities and update documentation - Updated Makefile to include new test commands for various modes (compatibility, isolation, multi-tenant, security, coverage, and dry-run). - Modified API health check endpoint in Makefile to reflect new port configuration. - Updated QUICK_START.md and README.md to reflect changes in service URLs and ports. - Added environment variables for testing modes in env.example. - Introduced run_all_tests.sh script to automate testing across different modes. - Created conftest.py for pytest configuration, including database fixtures and mock services. - Implemented database helper functions for streamlined database operations in tests. - Added test collection hooks to skip tests based on the current MULTITENANT_MODE. * feat: Implement multi-tenant support with demo mode enabled by default - Added multi-tenant configuration to the environment and Docker setup. - Created pre-configured demo tenants (acme-corp and techstart) for testing. - Updated API endpoints to support tenant-specific data access. - Enhanced Makefile commands for better service management and database operations. - Introduced user-tenant membership system with role-based access control. - Added comprehensive documentation for multi-tenant setup and usage. - Fixed issues with document visibility in multi-tenant environments. - Implemented necessary database migrations for user memberships and legacy support. * feat(audit): Add final audit report for multi-tenant implementation - Documented overall assessment, architecture overview, test results, security findings, and recommendations. - Included detailed findings on critical security issues and architectural concerns. fix(security): Implement security fixes based on audit findings - Removed global RAG fallback and enforced strict tenant context. - Configured super-admin access and required user authentication for tenant access. - Cleared localStorage on logout and improved error handling in WebUI. chore(logs): Create task logs for audit and security fixes implementation - Documented actions, decisions, and next steps for both audit and security fixes. - Summarized test results and remaining recommendations. chore(scripts): Enhance development stack management scripts - Added scripts for cleaning, starting, and stopping the development stack. - Improved output messages and ensured graceful shutdown of services. feat(starter): Initialize PostgreSQL with AGE extension support - Created initialization scripts for PostgreSQL extensions including uuid-ossp, vector, and AGE. - Ensured successful installation and verification of extensions. * feat: Implement auto-select for first tenant and KB on initial load in WebUI - Removed WEBUI_INITIAL_STATE_FIX.md as the issue is resolved. - Added useTenantInitialization hook to automatically select the first available tenant and KB on app load. - Integrated the new hook into the Root component of the WebUI. - Updated RetrievalTesting component to ensure a KB is selected before allowing user interaction. - Created end-to-end tests for multi-tenant isolation and real service interactions. - Added scripts for starting, stopping, and cleaning the development stack. - Enhanced API and tenant routes to support tenant-specific pipeline status initialization. - Updated constants for backend URL to reflect the correct port. - Improved error handling and logging in various components. * feat: Add multi-tenant support with enhanced E2E testing scripts and client functionality * update client * Add integration and unit tests for multi-tenant API, models, security, and storage - Implement integration tests for tenant and knowledge base management endpoints in `test_tenant_api_routes.py`. - Create unit tests for tenant isolation, model validation, and role permissions in `test_tenant_models.py`. - Add security tests to enforce role-based permissions and context validation in `test_tenant_security.py`. - Develop tests for tenant-aware storage operations and context isolation in `test_tenant_storage_phase3.py`. * feat(e2e): Implement OpenAI model support and database reset functionality * Add comprehensive test suite for gpt-5-nano compatibility - Introduced tests for parameter normalization, embeddings, and entity extraction. - Implemented direct API testing for gpt-5-nano. - Validated .env configuration loading and OpenAI API connectivity. - Analyzed reasoning token overhead with various token limits. - Documented test procedures and expected outcomes in README files. - Ensured all tests pass for production readiness. * kg(postgres_impl): ensure AGE extension is loaded in session and configure graph initialization * dev: add hybrid dev helper scripts, Makefile, docker-compose.dev-db and local development docs * feat(dev): add dev helper scripts and local development documentation for hybrid setup * feat(multi-tenant): add detailed specifications and logs for multi-tenant improvements, including UX, backend handling, and ingestion pipeline * feat(migration): add generated tenant/kb columns, indexes, triggers; drop unused tables; update schema and docs * test(backward-compat): adapt tests to new StorageNameSpace/TenantService APIs (use concrete dummy storages) * chore: multi-tenant and UX updates — docs, webui, storage, tenant service adjustments * tests: stabilize integration tests + skip external services; fix multi-tenant API behavior and idempotency - gpt5_nano_compatibility: add pytest-asyncio markers, skip when OPENAI key missing, prevent module-level asyncio.run collection, add conftest - Ollama tests: add server availability check and skip markers; avoid pytest collection warnings by renaming helper classes - Graph storage tests: rename interactive test functions to avoid pytest collection - Document & Tenant routes: support external_ids for idempotency; ensure HTTPExceptions are re-raised - LightRAG core: support external_ids in apipeline_enqueue_documents and idempotent logic - Tests updated to match API changes (tenant routes & document routes) - Add logs and scripts for inspection and audit
7.6 KiB
7.6 KiB
Multi-Tenant Query Context Fix
Problem
The Retrieval/Query page was not respecting the selected tenant and knowledge base context. While documents were properly isolated by tenant on the backend, the query interface was not sending tenant context headers for streaming queries.
Root Cause
The queryTextStream function in lightrag_webui/src/api/lightrag.ts was using the raw fetch() API instead of axiosInstance, which meant:
- It wasn't benefiting from the axios interceptor that adds
X-Tenant-IDandX-KB-IDheaders - It was manually constructing headers but missing the tenant/KB context
- This caused queries to default to the global RAG instance instead of the tenant-specific one
Solution
Frontend Fix: lightrag_webui/src/api/lightrag.ts
Updated the queryTextStream function to read and include tenant context from localStorage:
export const queryTextStream = async (
request: QueryRequest,
onChunk: (chunk: string) => void,
onError?: (error: string) => void
) => {
const apiKey = useSettingsStore.getState().apiKey;
const token = localStorage.getItem('LIGHTRAG-API-TOKEN');
// Get tenant context from localStorage
const selectedTenantJson = localStorage.getItem('SELECTED_TENANT');
const selectedKBJson = localStorage.getItem('SELECTED_KB');
const headers: HeadersInit = {
'Content-Type': 'application/json',
'Accept': 'application/x-ndjson',
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
if (apiKey) {
headers['X-API-Key'] = apiKey;
}
// Add tenant context headers
if (selectedTenantJson) {
try {
const selectedTenant = JSON.parse(selectedTenantJson);
if (selectedTenant?.tenant_id) {
headers['X-Tenant-ID'] = selectedTenant.tenant_id;
}
} catch (e) {
console.error('[queryTextStream] Failed to parse selected tenant:', e);
}
}
if (selectedKBJson) {
try {
const selectedKB = JSON.parse(selectedKBJson);
if (selectedKB?.kb_id) {
headers['X-KB-ID'] = selectedKB.kb_id;
}
} catch (e) {
console.error('[queryTextStream] Failed to parse selected KB:', e);
}
}
try {
const response = await fetch(`${backendBaseUrl}/query/stream`, {
method: 'POST',
headers: headers,
body: JSON.stringify(request),
});
// ... rest of the function
}
};
Key Changes:
- Added
selectedTenantJsonandselectedKBJsonextraction from localStorage - Parsed JSON safely with try-catch error handling
- Added
X-Tenant-IDandX-KB-IDheaders to the fetch request if tenant/KB context is available - Logs errors but doesn't fail - allows queries to proceed even if headers are missing
Backend Verification
The backend was already correctly configured:
lightrag/api/dependencies.py
get_tenant_context_optional: Extracts tenant context fromX-Tenant-IDandX-KB-IDheaders- Propagates authentication errors instead of silently falling back to global RAG
lightrag/api/routers/query_routes.py
All query endpoints use the get_tenant_rag dependency:
async def get_tenant_rag(tenant_context: Optional[TenantContext] = Depends(get_tenant_context_optional)) -> LightRAG:
"""Dependency to get tenant-specific RAG instance for query operations"""
if rag_manager and tenant_context and tenant_context.tenant_id and tenant_context.kb_id:
return await rag_manager.get_rag_instance(
tenant_context.tenant_id,
tenant_context.kb_id,
tenant_context.user_id # Pass user_id for security validation
)
return rag
This ensures:
/queryendpoint uses tenant-specific RAG/query/streamendpoint uses tenant-specific RAG/query/dataendpoint uses tenant-specific RAG
How Tenant Context Flows
For Axios-based calls (e.g., queryText):
- Request is made via
axiosInstance.post('/query', request) - Axios interceptor in
client.tsautomatically readsSELECTED_TENANTandSELECTED_KBfrom localStorage - Interceptor adds
X-Tenant-IDandX-KB-IDheaders - Backend receives headers and routes to tenant-specific RAG
For Fetch-based calls (e.g., queryTextStream):
- Request is made via
fetch()to/query/stream - NEW: Function now reads
SELECTED_TENANTandSELECTED_KBfrom localStorage - NEW: Function manually adds
X-Tenant-IDandX-KB-IDheaders to fetch request - Backend receives headers and routes to tenant-specific RAG
Testing the Fix
Prerequisites:
- User must be authenticated and have an active tenant/KB selected
- Documents must exist in the selected tenant/KB
Test Steps:
- Select a tenant from the tenant dropdown
- Select a knowledge base from the KB dropdown
- Navigate to the Retrieval tab
- Enter a query that should match documents in the selected KB
- Verify the query returns results from that tenant/KB only
Expected Behavior:
- Query respects the selected tenant/KB context
- Results are filtered to the selected tenant/KB
- No data from other tenants appears in results
- "No relevant context found" only appears if no matching documents in selected KB
Multi-Tenant Architecture Summary
Data Isolation Layers:
- HTTP Headers:
X-Tenant-IDandX-KB-IDsent by frontend - Dependency Injection:
get_tenant_context_optionalextracts and validates headers - RAG Instance Selection:
get_tenant_ragreturns tenant-specific RAG instance - Query Execution: Tenant-specific RAG only searches that tenant's knowledge graph
Frontend Storage:
SELECTED_TENANT: JSON object withtenant_idstored in localStorageSELECTED_KB: JSON object withkb_idstored in localStorage- Updated whenever user changes tenant/KB selection
Query Endpoints:
/query: Non-streaming query, uses axios (automatically includes headers)/query/stream: Streaming query, uses fetch (now manually includes headers)/query/data: Structured data retrieval, uses axios (automatically includes headers)
Files Modified
lightrag_webui/src/api/lightrag.ts- Modified
queryTextStreamfunction (lines 317-365+) - Added tenant context extraction from localStorage
- Added
X-Tenant-IDandX-KB-IDheaders to fetch request
- Modified
Verification Checklist
- Frontend code compiles without errors
- Backend query endpoints properly use
get_tenant_ragdependency - Tenant context is extracted from
X-Tenant-IDheader - KB context is extracted from
X-KB-IDheader queryTextStreamnow includes tenant/KB headers- Error handling includes proper logging
- Build succeeds with no TypeScript errors
Backward Compatibility
This fix maintains backward compatibility:
- Non-authenticated requests (no tenant headers) still work with global RAG
- Existing API clients that don't send headers still function
- Multi-tenant isolation is optional based on header presence
- No breaking changes to API contracts
Performance Impact
- Minimal: Only adds header reading from localStorage during query
- localStorage.getItem() and JSON.parse() are fast operations
- Negligible impact on query latency
Security Implications
✅ Improved Security
- Query operations now respect tenant isolation
- Headers are validated on backend
- Each query is scoped to selected tenant/KB
- Prevents accidental cross-tenant data leakage
Related Documentation
See also:
docs/0001-multi-tenant-architecture.md- Overall multi-tenant designdocs/0002-multi-tenant-visual-reference.md- Visual architecture guidelightrag/api/dependencies.py- Tenant context injectionlightrag/tenant_rag_manager.py- Tenant RAG instance management