LightRAG/docs/action_plan/multitenant-audit/scripts/test_api_isolation.py
Raphael MANSUY fe9b8ec02a
tests: stabilize integration tests + skip external services; fix multi-tenant API behavior and idempotency (#4)
* 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
2025-12-04 16:04:21 +08:00

379 lines
14 KiB
Python

#!/usr/bin/env python3
"""
Multi-Tenant API Test Script
This script tests the multi-tenant REST API endpoints without needing
the Web UI or Docker for the API server.
Requirements:
- PostgreSQL running on localhost:5433
- Redis running on localhost:6380
- API server to be started separately
Usage:
python test_api_isolation.py
"""
import httpx
import asyncio
import json
from typing import Optional
from dataclasses import dataclass
import sys
# Configuration
API_BASE_URL = "http://localhost:9621"
ADMIN_USERNAME = "admin"
ADMIN_PASSWORD = "admin123" # Default admin password
@dataclass
class TestResult:
test_name: str
passed: bool
message: str
details: Optional[dict] = None
class MultiTenantAPITest:
def __init__(self, base_url: str = API_BASE_URL):
self.base_url = base_url
self.results: list[TestResult] = []
self.tenant_a_id: Optional[str] = None
self.tenant_b_id: Optional[str] = None
self.kb_a_id: Optional[str] = None
self.kb_b_id: Optional[str] = None
def get_auth_header(self, username: str = ADMIN_USERNAME) -> dict:
"""Get authorization header."""
return {
"Authorization": f"Basic {username}:password",
"Content-Type": "application/json"
}
def get_tenant_headers(self, tenant_id: str, kb_id: str) -> dict:
"""Get headers with tenant context."""
headers = self.get_auth_header()
headers["X-Tenant-ID"] = tenant_id
headers["X-KB-ID"] = kb_id
return headers
async def check_api_health(self) -> bool:
"""Check if API is running."""
try:
async with httpx.AsyncClient() as client:
response = await client.get(f"{self.base_url}/health", timeout=5.0)
return response.status_code == 200
except Exception as e:
print(f"API not reachable: {e}")
return False
async def test_list_tenants(self) -> TestResult:
"""Test listing tenants (public endpoint)."""
async with httpx.AsyncClient() as client:
try:
response = await client.get(
f"{self.base_url}/tenants",
timeout=10.0
)
if response.status_code == 200:
tenants = response.json()
return TestResult(
test_name="List Tenants",
passed=True,
message=f"Found {len(tenants)} tenants",
details={"tenants": tenants}
)
else:
return TestResult(
test_name="List Tenants",
passed=False,
message=f"Status {response.status_code}: {response.text}"
)
except Exception as e:
return TestResult(
test_name="List Tenants",
passed=False,
message=str(e)
)
async def test_create_tenant(self, name: str, description: str) -> TestResult:
"""Test creating a tenant."""
async with httpx.AsyncClient() as client:
try:
response = await client.post(
f"{self.base_url}/tenants",
headers=self.get_auth_header(),
json={
"name": name,
"description": description,
"config": {}
},
timeout=10.0
)
if response.status_code in [200, 201]:
tenant = response.json()
return TestResult(
test_name=f"Create Tenant: {name}",
passed=True,
message=f"Created tenant: {tenant.get('tenant_id')}",
details=tenant
)
else:
return TestResult(
test_name=f"Create Tenant: {name}",
passed=False,
message=f"Status {response.status_code}: {response.text}"
)
except Exception as e:
return TestResult(
test_name=f"Create Tenant: {name}",
passed=False,
message=str(e)
)
async def test_create_kb(self, tenant_id: str, kb_name: str) -> TestResult:
"""Test creating a knowledge base for a tenant."""
async with httpx.AsyncClient() as client:
try:
headers = self.get_auth_header()
headers["X-Tenant-ID"] = tenant_id
response = await client.post(
f"{self.base_url}/knowledge-bases",
headers=headers,
json={
"name": kb_name,
"description": f"Test KB for {tenant_id}"
},
timeout=10.0
)
if response.status_code in [200, 201]:
kb = response.json()
return TestResult(
test_name=f"Create KB: {kb_name}",
passed=True,
message=f"Created KB: {kb.get('kb_id')}",
details=kb
)
else:
return TestResult(
test_name=f"Create KB: {kb_name}",
passed=False,
message=f"Status {response.status_code}: {response.text}"
)
except Exception as e:
return TestResult(
test_name=f"Create KB: {kb_name}",
passed=False,
message=str(e)
)
async def test_document_isolation(self) -> TestResult:
"""Test that documents are isolated between tenants."""
if not all([self.tenant_a_id, self.tenant_b_id, self.kb_a_id, self.kb_b_id]):
return TestResult(
test_name="Document Isolation",
passed=False,
message="Tenants/KBs not set up yet"
)
async with httpx.AsyncClient() as client:
try:
# Upload document to Tenant A
headers_a = self.get_tenant_headers(self.tenant_a_id, self.kb_a_id)
response_a = await client.post(
f"{self.base_url}/documents/text",
headers=headers_a,
json={
"text": "This is a secret document for Tenant A only.",
"description": "Tenant A Secret Doc"
},
timeout=30.0
)
if response_a.status_code not in [200, 201]:
return TestResult(
test_name="Document Isolation",
passed=False,
message=f"Failed to upload doc to Tenant A: {response_a.text}"
)
# List documents from Tenant A - should see the document
list_a = await client.get(
f"{self.base_url}/documents",
headers=headers_a,
timeout=10.0
)
docs_a = list_a.json() if list_a.status_code == 200 else []
# List documents from Tenant B - should NOT see the document
headers_b = self.get_tenant_headers(self.tenant_b_id, self.kb_b_id)
list_b = await client.get(
f"{self.base_url}/documents",
headers=headers_b,
timeout=10.0
)
docs_b = list_b.json() if list_b.status_code == 200 else []
# Check isolation
tenant_a_has_doc = isinstance(docs_a, dict) and docs_a.get("total_count", 0) > 0
tenant_b_has_doc = isinstance(docs_b, dict) and docs_b.get("total_count", 0) > 0
if tenant_a_has_doc and not tenant_b_has_doc:
return TestResult(
test_name="Document Isolation",
passed=True,
message="✅ Tenant A can see its doc, Tenant B cannot",
details={
"tenant_a_docs": docs_a.get("total_count", 0) if isinstance(docs_a, dict) else 0,
"tenant_b_docs": docs_b.get("total_count", 0) if isinstance(docs_b, dict) else 0
}
)
else:
return TestResult(
test_name="Document Isolation",
passed=False,
message=f"Isolation failed: A has {tenant_a_has_doc}, B has {tenant_b_has_doc}",
details={
"docs_a": docs_a,
"docs_b": docs_b
}
)
except Exception as e:
return TestResult(
test_name="Document Isolation",
passed=False,
message=str(e)
)
async def test_missing_tenant_header(self) -> TestResult:
"""Test behavior when tenant header is missing."""
async with httpx.AsyncClient() as client:
try:
# Try to list documents without tenant headers
response = await client.get(
f"{self.base_url}/documents",
headers=self.get_auth_header(),
timeout=10.0
)
# Should either fail with 400/401 or return empty/global data
if response.status_code in [400, 401, 403]:
return TestResult(
test_name="Missing Tenant Header",
passed=True,
message=f"Correctly rejected: {response.status_code}"
)
elif response.status_code == 200:
return TestResult(
test_name="Missing Tenant Header",
passed=False,
message="⚠️ Request succeeded without tenant header - potential security issue",
details={"response": response.json()}
)
else:
return TestResult(
test_name="Missing Tenant Header",
passed=False,
message=f"Unexpected status: {response.status_code}"
)
except Exception as e:
return TestResult(
test_name="Missing Tenant Header",
passed=False,
message=str(e)
)
async def run_all_tests(self):
"""Run all tests."""
print("=" * 60)
print("Multi-Tenant API Isolation Tests")
print("=" * 60)
# Check API health
print("\n🔍 Checking API health...")
if not await self.check_api_health():
print("❌ API is not running. Please start the API server first.")
print(f" Expected at: {self.base_url}")
return
print("✅ API is healthy")
# Run tests
print("\n📝 Running tests...\n")
# Test 1: List tenants
result = await self.test_list_tenants()
self.results.append(result)
self.print_result(result)
# Test 2: Create tenant A
result = await self.test_create_tenant("Test Tenant A", "First test tenant")
self.results.append(result)
self.print_result(result)
if result.passed and result.details:
self.tenant_a_id = result.details.get("tenant_id")
# Test 3: Create tenant B
result = await self.test_create_tenant("Test Tenant B", "Second test tenant")
self.results.append(result)
self.print_result(result)
if result.passed and result.details:
self.tenant_b_id = result.details.get("tenant_id")
# Test 4: Create KB for tenant A
if self.tenant_a_id:
result = await self.test_create_kb(self.tenant_a_id, "Tenant A KB")
self.results.append(result)
self.print_result(result)
if result.passed and result.details:
self.kb_a_id = result.details.get("kb_id")
# Test 5: Create KB for tenant B
if self.tenant_b_id:
result = await self.test_create_kb(self.tenant_b_id, "Tenant B KB")
self.results.append(result)
self.print_result(result)
if result.passed and result.details:
self.kb_b_id = result.details.get("kb_id")
# Test 6: Document isolation
result = await self.test_document_isolation()
self.results.append(result)
self.print_result(result)
# Test 7: Missing tenant header
result = await self.test_missing_tenant_header()
self.results.append(result)
self.print_result(result)
# Summary
print("\n" + "=" * 60)
print("Test Summary")
print("=" * 60)
passed = sum(1 for r in self.results if r.passed)
failed = len(self.results) - passed
print(f"✅ Passed: {passed}")
print(f"❌ Failed: {failed}")
print(f"📊 Total: {len(self.results)}")
def print_result(self, result: TestResult):
"""Print a single test result."""
status = "" if result.passed else ""
print(f"{status} {result.test_name}")
print(f" {result.message}")
if result.details and not result.passed:
print(f" Details: {json.dumps(result.details, indent=2)[:200]}")
async def main():
tester = MultiTenantAPITest()
await tester.run_all_tests()
# Exit with error code if any tests failed
if any(not r.passed for r in tester.results):
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())