Aller au contenu principal

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:

  1. Add tenant_id columns to all relevant tables (clients, sites, reclamations, factures, contacts, cadastres)
  2. Create NOT NULL constraints on tenant_id for all tenant-scoped tables
  3. Implement database migration that preserves all existing data integrity
  4. Add composite indexes (tenant_id + primary key) for optimal query performance
  5. 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:

  1. Implement Prisma middleware that automatically injects tenant_id filters
  2. Create tenant context service that extracts tenant from authenticated user
  3. Add automatic tenant validation for all CUD operations
  4. Implement query interception for all find operations
  5. 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:

  1. Apply tenant context injection to all existing controllers
  2. Update all service methods to use tenant-aware queries
  3. Add tenant validation decorators for endpoint protection
  4. Implement cross-tenant access logging for audit
  5. 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:

  1. Implement @BypassTenantFilter decorator for admin operations
  2. Create cross-tenant query capabilities with proper authorization
  3. Add comprehensive audit logging for all admin cross-tenant access
  4. Implement tenant switching mechanism for admin users
  5. 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:

  1. Create data migration scripts that assign proper tenant_id values
  2. Implement validation scripts to verify tenant data integrity
  3. Add rollback procedures for migration failures
  4. Create post-migration verification reports
  5. 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​

  1. Data Migration Risk: Potential data loss or corruption during tenant_id addition
  2. Performance Risk: Query performance degradation with tenant filtering
  3. Security Risk: Incomplete tenant isolation allowing data leakage

Mitigation Strategies​

  1. Comprehensive Testing: Full E2E tenant isolation testing before production
  2. Incremental Rollout: Feature flags for gradual tenant enforcement
  3. Performance Monitoring: Real-time query performance tracking
  4. Audit Logging: Complete tenant access audit trail
  5. 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