Multi-Tenancy & User Data Isolation
Relevant source files
The following files were used as context for generating this wiki page:
NEXUS implements a multi-tenant architecture designed to provide secure, isolated environments for digital account and trial tracking. The system ensures that user data—including account credentials, email management, and trial schedules—remains strictly private and accessible only to the authenticated owner. This isolation is achieved through a combination of JWT-based authentication, unique identifier (UUID) association, and server-side filtering at the database layer.
The core of this system revolves around the user_id attribute, which acts as the primary foreign key across all data collections (Accounts, Emails, and Trials). Every API request targeting a specific resource is validated against the active user's session, preventing cross-tenant data leakage.
Authentication & Identity Management
The identity system is the foundation of data isolation in NEXUS. It utilizes JSON Web Tokens (JWT) to maintain stateless authentication sessions. When a user registers or logs in, the backend generates a signed token containing the user's identity, which the frontend must include in the Authorization header for all subsequent requests.
Authentication Flow
The following sequence diagram illustrates the process of establishing an isolated session through JWT issuance and verification.
Key Auth Components
| Component | Implementation | Description |
|---|---|---|
| Password Hashing | bcrypt | Uses salt-based hashing to ensure password security at rest. |
| Token Generation | PyJWT | Creates HS256 signed tokens with a 30-minute expiration. |
| Identity Context | get_current_user | Dependency that extracts sub from JWT and fetches the user object. |
Sources: backend/server.py:155-173
Server-Side Data Isolation
Isolation is enforced programmatically in the backend API routes. Rather than relying on the client to specify a user context, the backend derives the user_id directly from the authenticated JWT payload. This ensures that even if a user attempts to access a resource ID belonging to another tenant, the query will return a 404 or empty result because it includes a strict user_id filter.
Data Ownership Logic
When resources are created, the current_user.id is automatically injected into the data model. When resources are retrieved, updated, or deleted, the query filter always includes the user_id.
# Example of isolation in Account Routes
@api_router.get("/accounts", response_model=List[Account])
async def get_accounts(current_user: User = Depends(get_current_user)):
# Strict filter on user_id prevents seeing other tenants' data
accounts = await db.accounts.find({"user_id": current_user.id}).to_list(1000)
return [Account(**account) for account in accounts]
@api_router.delete("/accounts/{account_id}")
async def delete_account(account_id: str, current_user: User = Depends(get_current_user)):
# Requires both ID and the correct user_id ownership
result = await db.accounts.delete_one({"id": account_id, "user_id": current_user.id})
if result.deleted_count == 0:
raise HTTPException(status_code=404, detail="Account not found")
return {"message": "Account deleted successfully"}
Sources: backend/server.py:252-255, backend/server.py:273-277
Data Models & Relationships
The NEXUS schema is built using Pydantic models that enforce the presence of a user_id for every record. This relationship ensures that all entities—Accounts, Emails, and Trials—are "owned" by a specific user instance.
Sources: backend/server.py:84-142
Summary of Isolated Models
| Entity | Isolation Key | Description |
|---|---|---|
user_id | Private email addresses used for trial registrations. | |
| Account | user_id | Credentials and subscription details for various platforms. |
| Trial | user_id | Tracking data for active trials and cancellation deadlines. |
Sources: backend/server.py:100, backend/server.py:112, backend/server.py:146
Security Center and Statistics
The Dashboard and Security Center provide aggregated views of a user's data. Even at the aggregation level, isolation is maintained by performing count_documents and sum operations only on records matching the authenticated user_id.
Statistical Isolation Logic
The get_dashboard_stats endpoint calculates metrics such as monthly_spend and security_score by iterating only through the current tenant's account list. This prevents cross-user statistical leakage.
@api_router.get("/dashboard/stats", response_model=DashboardStats)
async def get_dashboard_stats(current_user: User = Depends(get_current_user)):
total_accounts = await db.accounts.count_documents({"user_id": current_user.id})
accounts = await db.accounts.find({"user_id": current_user.id}).to_list(1000)
monthly_spend = sum(account.get("monthly_cost", 0) or 0 for account in accounts)
# ...
Sources: backend/server.py:322-330
Validation and Testing
The effectiveness of the user data isolation was verified through a dedicated testing suite. The backend_test.py validates that:
- Protected routes reject requests without a valid JWT.
- CRUD operations correctly associate resources with the active user.
- User isolation is maintained during concurrent operations.
Testing results confirmed 100% success across 20/20 backend tests, specifically validating "read all accounts with proper user isolation."
Sources: backend_test.py:106-118, test_result.md:92-98
NEXUS provides a robust multi-tenant environment where data isolation is enforced at the API gateway via JWT and at the database layer via mandatory user_id filtering, ensuring a secure and private experience for every digital commander.