Aller au contenu principal

EMTB Brownfield Enhancement PRD

Intro Project Analysis and Context​

This PRD is designed for SIGNIFICANT enhancements to existing projects that require comprehensive planning and multiple stories.

Analysis Source​

IDE-based fresh analysis - Comprehensive review of project files, documentation, and monorepo structure

Current Project State​

Project: EMTB Tax Claim Management System

Primary Purpose: Multi-tenant tax claim management platform where EMTB firm employees manage tax claims (TF/CFE) on behalf of business clients, with role-based access ensuring clients only see their own data.

Current Technical Architecture:

  • Monorepo Structure: Independent apps (apps/api, apps/frontend) with separate deployment cycles
  • Backend: NestJS API with TypeScript, Prisma ORM, PostgreSQL database, Swagger documentation
  • Frontend: Next.js 14 with App Router, React 18, Material-UI (MUI), JWT-based authentication
  • Infrastructure: Cloud infrastructure for independent deployment of API and frontend services
  • Migration Status: Mid-migration from Strapi CMS to custom NestJS API (partially complete)

Available Documentation Analysis​

Available Documentation ✓:

  • ✓ Complete Project Brief (32-page comprehensive analysis in docs/brief.md)
  • ✓ Tech Stack Documentation (evident from package.json analysis)
  • ✓ Source Tree/Architecture (monorepo with apps/api and apps/frontend structure)
  • ✓ API Documentation (Swagger integration in NestJS)
  • ✓ Deployment Documentation (RENDER_DEPLOYMENT.md, RENDER_TROUBLESHOOTING.md)
  • ✓ Technical Migration Context (CLI tools for data import, validation scripts)

Documentation Quality: Excellent - comprehensive project brief covers all major aspects including business requirements, technical constraints, migration status, and user personas.

Enhancement Scope Definition​

Enhancement Type:

  • ✓ Integration with New Systems (implementing comprehensive RBAC system)
  • ✓ Major Feature Modification (adding data isolation to existing workflows)
  • ✓ Performance/Scalability Improvements (optimizing multi-tenant architecture)

Enhancement Description: Implementation of comprehensive role-based authentication and multi-tenant data siloing system for the EMTB Tax Claim Management platform. This enhancement will ensure that EMTB staff have appropriate access levels based on their roles (admin, account manager, tax specialist) while maintaining strict data isolation where clients can only access their own tax claim data, documents, and related information.

Impact Assessment:

  • ✓ Major Impact (architectural changes required) - This enhancement requires:
    • Database schema modifications for tenant isolation
    • API-level authorization middleware implementation
    • Frontend UI adjustments for role-specific interfaces
    • Authentication system integration with existing Auth0 setup
    • Comprehensive testing of data isolation boundaries

Goals and Background Context​

Goals:

  • Implement granular role-based access control for EMTB staff with different permission levels
  • Ensure complete data isolation between clients (tenant-based data siloing)
  • Maintain security compliance with French data protection regulations
  • Enable scalable multi-tenant architecture supporting client growth
  • Preserve existing functionality while adding security layers

Background Context: Based on your project brief, the current EMTB system handles sensitive tax claim data for multiple business clients. The ongoing Strapi→NestJS migration presents the perfect opportunity to implement proper multi-tenant security architecture. Your current Auth0 integration provides the authentication foundation, but you need comprehensive authorization and data isolation to ensure clients never see each other's data and EMTB staff have appropriate access levels for their roles.

Requirements​

Functional Requirements​

FR1: The system shall implement role-based authentication supporting EMTB Staff roles (Admin, Account Manager, Tax Specialist) and Client roles with appropriate access levels to existing tax claim functionality.

FR2: The system shall enforce tenant-based data isolation ensuring clients can only access their own sites, tax claims, documents, and related data with no cross-client data visibility.

FR3: The system shall implement JWT-based authentication with NestJS authorization middleware to control access to API endpoints based on user roles and tenant ownership.

FR4: The system shall provide EMTB Admin users with full system access including user management, all client data visibility, and system configuration capabilities.

FR5: The system shall restrict EMTB Account Managers to view and manage only clients assigned to them, with read/write access to those clients' tax claims, sites, and documents.

FR6: The system shall allow EMTB Tax Specialists to access client data as assigned by Account Managers, with read/write access to tax claim processing but limited client management capabilities.

FR7: The system shall ensure Client users can only view and interact with their own company's data including their tax claims, sites, documents, and invoices.

FR8: The system shall maintain all existing tax claim workflow functionality (client management, site management, document upload, invoicing) while adding role-based restrictions to each operation.

FR9: The system shall implement database-level tenant isolation using tenant_id fields across all relevant tables (clients, sites, reclamations, factures, documents).

FR10: The system shall provide role-based UI rendering showing/hiding interface elements based on user permissions without exposing unauthorized functionality.

FR11: The system shall provide secure, email-based password reset functionality for all user roles (ADMIN, MANAGER, CLIENT) with cryptographically secure tokens, 15-minute expiry, single-use enforcement, and rate limiting (3 requests per email per hour) to prevent abuse.

Non-Functional Requirements​

NFR1: Role-based authorization checks must add less than 50ms to existing API response times to maintain current performance characteristics.

NFR2: Data isolation implementation must prevent any possibility of cross-tenant data leakage with 100% reliability across all API endpoints.

NFR3: The enhanced authentication system must support the existing user load (100+ concurrent users) without degradation in system performance.

NFR4: Role and permission changes must take effect immediately without requiring user re-authentication or system restart.

NFR5: The system must maintain 99.5% uptime during RBAC implementation with no data loss during the enhancement deployment.

NFR6: All role-based access control decisions must be logged for audit compliance with French data protection regulations.

NFR7: The authentication enhancement must be completed without requiring users to re-register accounts or disrupting existing authentication flows.

NFR8: Password reset tokens must expire within 15 minutes of generation and be single-use only to maintain security compliance and prevent replay attacks.

NFR9: Password reset functionality must implement rate limiting of maximum 3 requests per email address per hour to prevent abuse and protect against denial-of-service attacks.

Compatibility Requirements​

CR1: All existing API endpoints must maintain backward compatibility while adding role-based authorization layers without changing request/response formats.

CR2: Current database schema must be enhanced with tenant isolation fields without requiring data migration or breaking existing data relationships.

CR3: Existing Next.js frontend components must continue to function while adding role-based UI rendering and navigation restrictions.

CR4: Current JWT authentication flow must remain unchanged while extending with NestJS-based authorization for seamless user experience.

Technical Constraints and Integration Requirements​

Existing Technology Stack​

Languages: TypeScript (both frontend and backend) Frameworks: NestJS API with Prisma ORM, Next.js 14 with App Router, React 18, Material-UI Database: PostgreSQL with Prisma for type-safe operations Infrastructure: Cloud deployment for independent API and frontend services External Dependencies: JWT-based authentication, Swagger for API docs

Integration Approach​

Database Integration Strategy:

  • Implement tenant_id columns across existing tables (clients, sites, reclamations, factures, documents)
  • Create role-based authorization tables (users, roles, permissions) integrated with Prisma schema
  • Use database-level constraints and indexes to enforce tenant isolation
  • Leverage Prisma middleware for automatic tenant filtering on all queries

API Integration Strategy:

  • Extend existing NestJS guards and interceptors for role-based authorization
  • Implement tenant context injection from JWT tokens into NestJS request pipeline
  • Add role validation decorators to existing controllers without changing method signatures
  • Maintain existing Swagger documentation while adding security schema definitions

Frontend Integration Strategy:

  • Implement authentication provider with role and tenant information from JWT tokens
  • Implement role-based route protection using Next.js middleware and JWT validation
  • Create role-aware components that conditionally render UI elements based on permissions
  • Extend existing MUI layouts with role-based navigation and menu systems

Testing Integration Strategy:

  • Extend existing Jest test suites with role-based test scenarios for all API endpoints
  • Add tenant isolation tests to ensure no cross-tenant data access
  • Create role-based UI testing scenarios using existing testing framework
  • Implement security-focused integration tests for authentication flows

Code Organization and Standards​

File Structure Approach: Follow existing monorepo structure with security enhancements in:

  • apps/api/src/auth/ - Role and tenant management modules
  • apps/api/src/guards/ - Authorization guards and decorators
  • apps/frontend/src/contexts/auth/ - Enhanced Auth0 context with roles
  • apps/frontend/src/components/rbac/ - Role-based UI components

Naming Conventions: Maintain existing TypeScript/NestJS naming patterns:

  • Role-based decorators: @RequireRoles(), @RequireTenant()
  • Guard classes: RoleBasedAuthGuard, TenantIsolationGuard
  • Service classes: RoleService, TenantService

Coding Standards: Follow existing ESLint and Prettier configurations with additional security-focused rules:

  • Mandatory authorization checks on all new API endpoints
  • Explicit tenant context validation in all database operations
  • Type-safe role definitions using TypeScript enums and interfaces

Deployment and Operations​

Build Process Integration: Enhance existing build scripts with:

  • Database migration scripts for adding tenant_id columns and RBAC tables
  • Environment variable validation for JWT secret and role configuration
  • Security testing as part of existing CI/CD pipeline

Deployment Strategy: Leverage existing cloud infrastructure with:

  • Zero-downtime deployment using existing independent service architecture
  • Database migrations executed during maintenance windows
  • Feature flags for gradual rollout of RBAC functionality

Monitoring and Logging: Extend existing logging with:

  • Security audit logs for all authorization decisions
  • Performance monitoring of authorization overhead
  • Tenant isolation verification alerts

Configuration Management: Enhance existing environment configuration:

  • Role definitions managed via environment variables
  • JWT secret and token validation settings
  • Tenant isolation settings and feature flags

Risk Assessment and Mitigation​

Technical Risks:

  • Database migration complexity for adding tenant isolation to existing data
  • Performance impact of authorization middleware on existing API endpoints
  • JWT token validation complexity for role claim extraction and validation

Integration Risks:

  • Breaking existing JWT authentication flow during role enhancement
  • Frontend component compatibility with new role-based rendering logic
  • Database constraint conflicts during tenant_id column addition

Deployment Risks:

  • Data isolation failures during migration leading to cross-tenant access
  • Authorization bypass vulnerabilities in existing API endpoints
  • User access disruption during role-based authentication rollout

Mitigation Strategies:

  • Comprehensive database backup and rollback procedures before migration
  • Feature flag implementation allowing gradual RBAC rollout per user segment
  • Extensive security testing including penetration testing of tenant isolation
  • Staging environment replication of production data for migration validation

Epic and Story Structure​

Epic Approach​

Epic Structure Decision: Single Epic - "Implement Role-Based Authentication and Multi-Tenant Data Siloing"

Rationale: For brownfield RBAC implementation, all components (database isolation, API authorization, frontend role-based UI) must work together seamlessly. Splitting into multiple epics would create intermediate states where security is partially implemented, creating vulnerabilities. A single epic ensures complete end-to-end security implementation with proper rollback capabilities.

Epic 1: Implement Role-Based Authentication and Multi-Tenant Data Siloing​

Epic Goal: Transform the EMTB Tax Claim Management System into a secure, multi-tenant platform with comprehensive role-based access control, ensuring EMTB staff have appropriate access levels while maintaining complete data isolation between clients.

Integration Requirements:

  • Seamless integration with existing Auth0 authentication
  • Zero disruption to existing tax claim workflows during implementation
  • Database-level tenant isolation across all existing entities
  • Role-based UI rendering that preserves existing user experience patterns

Story 1.1: Implement Database Schema Enhancement for Tenant Isolation​

As an EMTB system administrator, I want the database schema enhanced with tenant isolation capabilities, so that all client data is properly segmented at the database level before implementing role-based access controls.

Acceptance Criteria:

  1. Add tenant_id columns to all relevant tables (clients, sites, reclamations, factures, documents)
  2. Create database constraints ensuring tenant_id cannot be null on tenant-scoped tables
  3. Update Prisma schema with tenant_id fields and appropriate relationships
  4. Create database migration scripts that preserve all existing data integrity
  5. Add database indexes on tenant_id columns for optimal query performance

Integration Verification:

  • IV1: Verify all existing client data retains proper relationships and referential integrity
  • IV2: Confirm existing API queries continue to return correct data sets
  • IV3: Validate database migration completes without data loss or corruption

Story 1.2: Create Role-Based Authorization Infrastructure in NestJS API​

As an EMTB developer, I want role-based authorization infrastructure built into the NestJS API, so that I can secure existing endpoints with role and tenant-based access controls.

Acceptance Criteria:

  1. Create Role and Permission entities with proper Prisma models
  2. Implement NestJS guards for role validation and tenant isolation
  3. Create custom decorators (@RequireRoles, @RequireTenant) for endpoint protection
  4. Build role service for managing user roles and permissions
  5. Integrate with JWT tokens to extract role and tenant information

Integration Verification:

  • IV1: Verify existing API endpoints continue to function without authorization enabled
  • IV2: Confirm role infrastructure doesn't impact existing performance benchmarks
  • IV3: Validate JWT authentication maintains current authentication flows

Story 1.3: Implement Tenant Context Injection and Data Filtering​

As an EMTB system architect, I want automatic tenant context injection throughout the API, so that all database queries are automatically scoped to the appropriate tenant without manual filtering.

Acceptance Criteria:

  1. Implement Prisma middleware for automatic tenant_id filtering on all queries
  2. Create request context service that extracts tenant information from authenticated user
  3. Add tenant validation to all existing service methods
  4. Implement tenant-aware query builders for complex operations
  5. Create comprehensive logging for all tenant-scoped operations

Integration Verification:

  • IV1: Verify existing business logic continues to return correct data for each client
  • IV2: Confirm no cross-tenant data leakage in any existing API endpoint
  • IV3: Validate existing unit tests pass with tenant context injection enabled

Story 1.4: Secure Existing API Endpoints with Role-Based Authorization​

As an EMTB security administrator, I want all existing API endpoints protected with appropriate role-based authorization, so that only authorized users can access specific client data and operations.

Acceptance Criteria:

  1. Apply role-based guards to all client management endpoints
  2. Implement tenant isolation on all site and tax claim endpoints
  3. Add role validation to document management and upload endpoints
  4. Secure invoice and billing endpoints with appropriate access controls
  5. Update API documentation with security requirements and examples

Integration Verification:

  • IV1: Verify EMTB staff can access assigned client data per their role definitions
  • IV2: Confirm clients can only access their own company's data and documents
  • IV3: Validate existing frontend functionality works correctly with secured endpoints

Story 1.5: Enhance Frontend with Role-Based Authentication and UI Controls​

As an EMTB user (staff or client), I want the frontend interface to reflect my role and tenant permissions, so that I only see and can interact with data and features appropriate to my access level.

Acceptance Criteria:

  1. Implement authentication context provider to include role and tenant information from JWT
  2. Implement role-based route protection and navigation restrictions
  3. Create role-aware components that conditionally render UI elements
  4. Update existing forms and tables to respect user permissions
  5. Add role-based menu systems and navigation controls

Integration Verification:

  • IV1: Verify existing user workflows remain intuitive and functional
  • IV2: Confirm unauthorized UI elements are properly hidden without breaking layouts
  • IV3: Validate role changes take effect immediately without requiring re-authentication

Story 1.6: Implement Security Testing and Validation Suite​

As an EMTB security officer, I want comprehensive security testing to validate tenant isolation and role-based access, so that I can be confident no data leakage or unauthorized access is possible.

Acceptance Criteria:

  1. Create automated tests for all role-based access scenarios
  2. Implement tenant isolation validation tests across all API endpoints
  3. Add security-focused integration tests for authentication flows
  4. Create penetration testing scenarios for common attack vectors
  5. Build security monitoring and audit logging capabilities

Integration Verification:

  • IV1: Verify existing system performance remains within acceptable parameters
  • IV2: Confirm all security tests pass with 100% success rate
  • IV3: Validate audit logging captures all required security events without impacting user experience

Next Steps​

Story Manager Handoff​

For Story Manager Implementation: You now have a comprehensive brownfield PRD for implementing role-based authentication and multi-tenant data siloing in the EMTB Tax Claim Management System.

Key Integration Requirements Validated:

  • Database schema enhancement must preserve existing data relationships
  • NestJS authorization infrastructure must integrate seamlessly with current Auth0 setup
  • Frontend role-based UI must maintain existing user experience patterns
  • All security implementations must be thoroughly tested for tenant isolation

Existing System Constraints Based on Project Analysis:

  • Monorepo structure (apps/api, apps/frontend) requires coordinated deployment
  • PostgreSQL + Prisma ORM setup enables database-level tenant isolation
  • Current JWT-based authentication provides foundation for role enhancement
  • Next.js + MUI frontend allows for role-based component rendering

First Story to Implement: Story 1.1 - Database Schema Enhancement for Tenant Isolation

  • Critical Integration Checkpoint: Verify all existing data relationships remain intact
  • Risk Mitigation: Complete database backup before migration execution
  • Success Validation: All existing API queries return correct data sets post-migration

System Integrity Focus: Throughout implementation, maintain existing tax claim functionality while layering security controls incrementally.

Developer Handoff​

For Development Team Starting Implementation:

Reference Documents:

  • This comprehensive brownfield PRD defining role-based authentication requirements
  • Existing coding standards analyzed from NestJS + TypeScript + Prisma architecture
  • Project brief (docs/brief.md) containing full business context

Integration Requirements with Existing Codebase:

  • Database Integration: Add tenant_id columns using Prisma migrations while preserving existing relationships
  • API Integration: Implement NestJS guards and decorators that layer onto existing controllers without breaking signatures
  • Frontend Integration: Enhance Auth0 provider and create role-aware MUI components maintaining existing layouts
  • Testing Integration: Extend existing Jest test suites with role-based and tenant isolation test scenarios

Key Technical Decisions Based on Real Project Constraints:

  • Use Prisma middleware for automatic tenant filtering to minimize code changes
  • Leverage JWT token structure for role and tenant claim extraction
  • Implement database-level tenant isolation for maximum security with PostgreSQL constraints
  • Maintain existing Swagger API documentation while adding security schema definitions

Existing System Compatibility Requirements:

  • Zero API Breaking Changes: All existing endpoints must maintain request/response formats
  • Database Migration Safety: All tenant_id additions must preserve existing data integrity
  • Frontend Compatibility: Role-based UI rendering must not break existing component layouts
  • Authentication Flow Preservation: JWT authentication must remain unchanged for existing users

Implementation Sequencing for Risk Minimization:

  1. Database Foundation (Story 1.1) - Schema changes with full rollback capability
  2. Authorization Infrastructure (Story 1.2) - NestJS security components without enforcement
  3. Tenant Context (Story 1.3) - Automatic data filtering with comprehensive logging
  4. Endpoint Security (Story 1.4) - Gradual role enforcement with feature flags
  5. Frontend Enhancement (Story 1.5) - Role-based UI with existing experience preservation
  6. Security Validation (Story 1.6) - Comprehensive testing and monitoring
ChangeDateVersionDescriptionAuthor
Initial Creation2025-09-08v1.0Complete brownfield PRD for RBAC and data siloing implementationJohn (Product Manager)