Epic 2: Complete Multi-Tenant Data Isolation
Epic Goal​
Complete the implementation of multi-tenant data isolation by adding tenant_id columns, implementing automatic tenant filtering, and ensuring comprehensive data separation while maintaining the performance and functionality of the existing EMTB Tax Claim Management System.
Epic Description​
Foundation Context:
- RBAC Infrastructure: Epic 1 successfully implemented JWT authentication, role-based guards, and comprehensive security testing
- Architecture: NestJS/Prisma/PostgreSQL with established authentication patterns
- Security: Role-based access control infrastructure operational and tested
- Current Gap: Tenant isolation at the database level needs completion
Epic Scope:
This epic focuses specifically on completing the tenant isolation infrastructure that was architected in Epic 1 but requires dedicated implementation effort to ensure data security and system integrity.
Stories​
Story 2.1: Database Tenant Schema Implementation​
Priority: Critical - Security Requirement
As an EMTB system administrator, I want all client data properly isolated at the database level with tenant_id columns, So that no client can accidentally access another client's sensitive tax information.
Acceptance Criteria:
- Add tenant_id columns to all relevant tables (clients, sites, reclamations, factures, contacts, cadastres)
- Create NOT NULL constraints on tenant_id for all tenant-scoped tables
- Implement database migration that preserves all existing data integrity
- Add composite indexes (tenant_id + primary key) for optimal query performance
- Create database-level checks to prevent cross-tenant data access
Security Requirements:
- Zero data loss during migration
- No cross-tenant data leakage possible at database level
- Performance impact < 5% for existing queries
Story 2.2: Prisma Middleware for Automatic Tenant Filtering​
Priority: Critical - Data Security
As an EMTB developer, I want all Prisma queries automatically filtered by tenant context, So that application code cannot accidentally access cross-tenant data.
Acceptance Criteria:
- Implement Prisma middleware that automatically injects tenant_id filters
- Create tenant context service that extracts tenant from authenticated user
- Add automatic tenant validation for all CUD operations
- Implement query interception for all find operations
- Create bypass mechanism for EMTB admin cross-tenant operations
Technical Implementation:
// Automatic tenant filtering
await prisma.client.findMany({
// where: { tenant_id: currentTenant.id } <- automatically injected
where: { status: "ACTIVE" },
});
// EMTB admin bypass
await prisma.client.findMany({
// @BypassTenantFilter decorator for admin operations
});
Story 2.3: Tenant-Aware API Endpoint Security​
Priority: High - Complete Security Implementation
As an EMTB security officer, I want all API endpoints to enforce tenant boundaries automatically, So that no API call can access data outside the user's tenant scope.
Acceptance Criteria:
- Apply tenant context injection to all existing controllers
- Update all service methods to use tenant-aware queries
- Add tenant validation decorators for endpoint protection
- Implement cross-tenant access logging for audit
- Create tenant boundary testing for all endpoints
Security Patterns:
@UseGuards(JwtAuthGuard, RolesGuard, TenantGuard)
@TenantAware()
export class ClientController {
// All operations automatically tenant-scoped
}
Story 2.4: EMTB Admin Cross-Tenant Access Controls​
Priority: Medium - Administrative Functionality
As an EMTB administrator, I want controlled access to cross-tenant data for administrative purposes, So that I can manage multiple clients while maintaining security boundaries.
Acceptance Criteria:
- Implement @BypassTenantFilter decorator for admin operations
- Create cross-tenant query capabilities with proper authorization
- Add comprehensive audit logging for all admin cross-tenant access
- Implement tenant switching mechanism for admin users
- Create admin dashboard with multi-tenant views
Admin Access Patterns:
- EMTB-ADMIN: Full cross-tenant access with audit logging
- EMTB-LIMITED: Restricted cross-tenant access to assigned clients only
- CLIENT-USER: Strict single-tenant access only
Story 2.5: Tenant Migration and Data Validation​
Priority: High - Data Integrity
As an EMTB data administrator, I want existing data properly migrated to the tenant model with full validation, So that all historical data remains accessible and properly isolated.
Acceptance Criteria:
- Create data migration scripts that assign proper tenant_id values
- Implement validation scripts to verify tenant data integrity
- Add rollback procedures for migration failures
- Create post-migration verification reports
- Implement ongoing tenant data consistency checks
Migration Safety:
- Pre-migration data backup
- Incremental migration with validation checkpoints
- Rollback scripts for each migration step
- Post-migration integrity verification
- Performance benchmark comparison
Technical Architecture​
Tenant Context Flow​
JWT Token → User Service → Tenant Context → Prisma Middleware → Database Query
Database Design​
-- Example tenant-aware table structure
CREATE TABLE clients (
id SERIAL PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES tenants(id),
nom VARCHAR(255) NOT NULL,
reference VARCHAR(50) UNIQUE NOT NULL,
-- ... other fields
INDEX idx_tenant_client (tenant_id, id),
INDEX idx_tenant_reference (tenant_id, reference)
);
Prisma Middleware Pattern​
prisma.$use(async (params, next) => {
if (tenantScopedModels.includes(params.model)) {
params.args.where = {
...params.args.where,
tenant_id: currentTenant.id,
};
}
return next(params);
});
Integration with Epic 1​
This epic directly completes the tenant isolation foundation laid in Epic 1:
- Epic 1 Achievement: Authentication, authorization, and security testing infrastructure
- Epic 2 Completion: Data isolation, tenant-aware queries, and complete security implementation
- Combined Result: Enterprise-grade multi-tenant tax claim management system
Risk Management​
Primary Risks​
- Data Migration Risk: Potential data loss or corruption during tenant_id addition
- Performance Risk: Query performance degradation with tenant filtering
- Security Risk: Incomplete tenant isolation allowing data leakage
Mitigation Strategies​
- Comprehensive Testing: Full E2E tenant isolation testing before production
- Incremental Rollout: Feature flags for gradual tenant enforcement
- Performance Monitoring: Real-time query performance tracking
- Audit Logging: Complete tenant access audit trail
- Rollback Procedures: Instant rollback capability for critical issues
Success Metrics​
Security Metrics​
- Zero cross-tenant data access: Verified through automated testing
- 100% tenant coverage: All relevant tables have tenant_id implementation
- Audit compliance: Complete logging of all tenant boundary crossings
Performance Metrics​
- Query performance: < 5% degradation from pre-tenant baseline
- Response times: Maintained within SLA bounds
- Database efficiency: Optimal indexing for tenant-scoped queries
Functional Metrics​
- Feature parity: All existing functionality maintained
- Admin efficiency: Cross-tenant admin operations streamlined
- Data integrity: Zero data inconsistencies post-migration
Definition of Done​
- All tenant_id columns added with proper constraints and indexes
- Prisma middleware operational for automatic tenant filtering
- All API endpoints enforce tenant boundaries with zero cross-tenant access
- EMTB admin cross-tenant access working with full audit logging
- Data migration completed with 100% integrity verification
- Comprehensive E2E testing covering all tenant isolation scenarios
- Performance benchmarks meet requirements (< 5% degradation)
- Security audit passed with zero critical findings
- Documentation updated for tenant-aware development patterns
Epic Owner: Security & Backend Team
Dependencies: Epic 1 (RBAC) completion
Target Timeline: 2-3 sprints
Critical Path: Database migration → Middleware implementation → API security → Admin tools