* 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
235 lines
8.4 KiB
Python
235 lines
8.4 KiB
Python
# Graph Database Multi-Tenant Support Module
|
|
# Supports: Neo4j, Memgraph, NetworkX
|
|
|
|
from typing import Any, Dict, List, Optional, Tuple
|
|
|
|
|
|
class GraphTenantHelper:
|
|
"""Helper class for graph DB multi-tenant operations"""
|
|
|
|
# Node labels and properties for tenant isolation
|
|
TENANT_NODE_LABEL = "Tenant"
|
|
KB_NODE_LABEL = "KnowledgeBase"
|
|
TENANT_PROPERTY = "tenant_id"
|
|
KB_PROPERTY = "kb_id"
|
|
|
|
@staticmethod
|
|
def create_tenant_node_id(tenant_id: str) -> str:
|
|
"""Create a node ID for tenant root node"""
|
|
return f"tenant_{tenant_id}"
|
|
|
|
@staticmethod
|
|
def create_kb_node_id(tenant_id: str, kb_id: str) -> str:
|
|
"""Create a node ID for knowledge base node"""
|
|
return f"kb_{tenant_id}_{kb_id}"
|
|
|
|
@staticmethod
|
|
def build_tenant_filter_cypher(tenant_id: str, kb_id: str, node_var: str = "n") -> str:
|
|
"""Build a Cypher WHERE clause for tenant isolation"""
|
|
return f"({node_var}:{GraphTenantHelper.TENANT_NODE_LABEL} {{tenant_id: '{tenant_id}'}}) OR EXISTS(({node_var})<-[:IN_KB]-(:KnowledgeBase {{tenant_id: '{tenant_id}', kb_id: '{kb_id}'}}))"
|
|
|
|
@staticmethod
|
|
def add_tenant_properties(
|
|
node_data: Dict[str, Any],
|
|
tenant_id: str,
|
|
kb_id: str
|
|
) -> Dict[str, Any]:
|
|
"""Add tenant properties to a node"""
|
|
node_data[GraphTenantHelper.TENANT_PROPERTY] = tenant_id
|
|
node_data[GraphTenantHelper.KB_PROPERTY] = kb_id
|
|
return node_data
|
|
|
|
|
|
class Neo4jTenantHelper(GraphTenantHelper):
|
|
"""Neo4j-specific tenant helper"""
|
|
|
|
@staticmethod
|
|
def build_tenant_constraint_cypher(tenant_id: str) -> str:
|
|
"""Build Cypher to create tenant node with constraints"""
|
|
return f"""
|
|
CREATE (t:{GraphTenantHelper.TENANT_NODE_LABEL} {{
|
|
id: '{GraphTenantHelper.create_tenant_node_id(tenant_id)}',
|
|
tenant_id: '{tenant_id}',
|
|
created_at: datetime()
|
|
}})
|
|
"""
|
|
|
|
@staticmethod
|
|
def build_kb_node_cypher(tenant_id: str, kb_id: str) -> str:
|
|
cypher_query = f"MATCH (t:Tenant {{tenant_id: '{tenant_id}'}}) CREATE (kb:KnowledgeBase {{id: 'kb_{tenant_id}_{kb_id}', tenant_id: '{tenant_id}', kb_id: '{kb_id}', created_at: datetime()}}) CREATE (kb)-[:BELONGS_TO]->(t)"
|
|
return cypher_query
|
|
|
|
@staticmethod
|
|
def build_tenant_aware_query(
|
|
base_query: str,
|
|
tenant_id: str,
|
|
kb_id: str,
|
|
node_var: str = "n"
|
|
) -> Tuple[str, Dict[str, Any]]:
|
|
"""Add tenant filtering to a Cypher query"""
|
|
params = {
|
|
"tenant_id": tenant_id,
|
|
"kb_id": kb_id
|
|
}
|
|
|
|
# Inject tenant filter into WHERE clause
|
|
where_clause = f"""
|
|
WHERE EXISTS((({node_var})-[:HAS_ENTITY]->(:Entity))-[:BELONGS_TO]->(:KnowledgeBase {{tenant_id: $tenant_id, kb_id: $kb_id}}))
|
|
OR ({node_var}.tenant_id = $tenant_id AND {node_var}.kb_id = $kb_id)
|
|
"""
|
|
|
|
if "WHERE" in base_query:
|
|
modified_query = base_query.replace("WHERE", "WHERE", 1)
|
|
modified_query = modified_query.replace("WHERE", where_clause, 1)
|
|
else:
|
|
modified_query = base_query + "\n" + where_clause
|
|
|
|
return modified_query, params
|
|
|
|
@staticmethod
|
|
def delete_tenant_graph(tenant_id: str, kb_id: str) -> str:
|
|
"""Create Cypher to delete all data for a tenant/KB"""
|
|
return f"""
|
|
MATCH (kb:KnowledgeBase {{tenant_id: '{tenant_id}', kb_id: '{kb_id}'}})
|
|
MATCH (kb)<-[r1]-(n)
|
|
DETACH DELETE kb, n, r1
|
|
WITH * MATCH (n) WHERE n.tenant_id = '{tenant_id}' AND n.kb_id = '{kb_id}'
|
|
DETACH DELETE n
|
|
"""
|
|
|
|
|
|
class MemgraphTenantHelper(GraphTenantHelper):
|
|
"""Memgraph-specific tenant helper"""
|
|
|
|
@staticmethod
|
|
def build_tenant_openCypher(tenant_id: str) -> str:
|
|
"""Build openCypher to create tenant node in Memgraph"""
|
|
return f"""
|
|
CREATE (t:{GraphTenantHelper.TENANT_NODE_LABEL} {{
|
|
id: '{GraphTenantHelper.create_tenant_node_id(tenant_id)}',
|
|
tenant_id: '{tenant_id}'
|
|
}})
|
|
"""
|
|
|
|
@staticmethod
|
|
def build_tenant_index_cypher(property_name: str) -> str:
|
|
"""Build openCypher to create index for tenant filtering"""
|
|
return f"CREATE INDEX ON :{GraphTenantHelper.TENANT_NODE_LABEL}({property_name})"
|
|
|
|
@staticmethod
|
|
def build_tenant_aware_query(
|
|
base_query: str,
|
|
tenant_id: str,
|
|
kb_id: str,
|
|
node_var: str = "n"
|
|
) -> Tuple[str, Dict[str, Any]]:
|
|
"""Add tenant filtering to an openCypher query"""
|
|
params = {
|
|
"tenant_id": tenant_id,
|
|
"kb_id": kb_id
|
|
}
|
|
|
|
# For Memgraph, similar to Neo4j but using openCypher syntax
|
|
where_clause = f"WHERE {node_var}.tenant_id = $tenant_id AND {node_var}.kb_id = $kb_id"
|
|
|
|
if "WHERE" in base_query:
|
|
parts = base_query.split("WHERE", 1)
|
|
modified_query = parts[0] + "WHERE " + where_clause + " AND (" + parts[1] + ")"
|
|
else:
|
|
modified_query = base_query + " " + where_clause
|
|
|
|
return modified_query, params
|
|
|
|
|
|
class NetworkXTenantHelper(GraphTenantHelper):
|
|
"""NetworkX-specific tenant helper"""
|
|
|
|
@staticmethod
|
|
def create_tenant_subgraph(G, tenant_id: str, kb_id: str):
|
|
"""Extract a subgraph for a specific tenant/KB from NetworkX graph"""
|
|
tenant_nodes = [
|
|
node for node, attr in G.nodes(data=True)
|
|
if attr.get(GraphTenantHelper.TENANT_PROPERTY) == tenant_id and
|
|
attr.get(GraphTenantHelper.KB_PROPERTY) == kb_id
|
|
]
|
|
|
|
return G.subgraph(tenant_nodes).copy()
|
|
|
|
@staticmethod
|
|
def filter_edges_by_tenant(
|
|
edges: List[Tuple],
|
|
G,
|
|
tenant_id: str,
|
|
kb_id: str
|
|
) -> List[Tuple]:
|
|
"""Filter edges to include only those in tenant's KB"""
|
|
filtered = []
|
|
for src, tgt in edges:
|
|
src_attrs = G.nodes[src]
|
|
tgt_attrs = G.nodes[tgt]
|
|
|
|
if (src_attrs.get(GraphTenantHelper.TENANT_PROPERTY) == tenant_id and
|
|
src_attrs.get(GraphTenantHelper.KB_PROPERTY) == kb_id and
|
|
tgt_attrs.get(GraphTenantHelper.TENANT_PROPERTY) == tenant_id and
|
|
tgt_attrs.get(GraphTenantHelper.KB_PROPERTY) == kb_id):
|
|
filtered.append((src, tgt))
|
|
|
|
return filtered
|
|
|
|
@staticmethod
|
|
def add_tenant_node(
|
|
G,
|
|
node_id: str,
|
|
tenant_id: str,
|
|
kb_id: str,
|
|
**attrs
|
|
):
|
|
"""Add a node with tenant properties to NetworkX graph"""
|
|
attrs[GraphTenantHelper.TENANT_PROPERTY] = tenant_id
|
|
attrs[GraphTenantHelper.KB_PROPERTY] = kb_id
|
|
G.add_node(node_id, **attrs)
|
|
|
|
@staticmethod
|
|
def delete_tenant_subgraph(G, tenant_id: str, kb_id: str):
|
|
"""Delete all nodes/edges for a tenant/KB"""
|
|
nodes_to_delete = [
|
|
node for node, attr in G.nodes(data=True)
|
|
if attr.get(GraphTenantHelper.TENANT_PROPERTY) == tenant_id and
|
|
attr.get(GraphTenantHelper.KB_PROPERTY) == kb_id
|
|
]
|
|
|
|
G.remove_nodes_from(nodes_to_delete)
|
|
return len(nodes_to_delete)
|
|
|
|
|
|
# ============================================================================
|
|
# TRANSACTION HELPER FOR MULTI-TENANT OPERATIONS
|
|
# ============================================================================
|
|
|
|
class GraphTenantTransaction:
|
|
"""Helper for managing tenant-aware graph transactions"""
|
|
|
|
def __init__(self, driver, tenant_id: str, kb_id: str):
|
|
self.driver = driver
|
|
self.tenant_id = tenant_id
|
|
self.kb_id = kb_id
|
|
|
|
async def create_tenant_structure(self):
|
|
"""Create tenant and KB nodes in graph"""
|
|
async with self.driver.session() as session:
|
|
# Create tenant node
|
|
await session.run(
|
|
Neo4jTenantHelper.build_tenant_constraint_cypher(self.tenant_id)
|
|
)
|
|
|
|
# Create KB node linked to tenant
|
|
await session.run(
|
|
Neo4jTenantHelper.build_kb_node_cypher(self.tenant_id, self.kb_id)
|
|
)
|
|
|
|
async def delete_tenant_data(self):
|
|
"""Delete all data for this tenant/KB"""
|
|
async with self.driver.session() as session:
|
|
await session.run(
|
|
Neo4jTenantHelper.delete_tenant_graph(self.tenant_id, self.kb_id)
|
|
)
|