docs: add Core SaaS, Multi-Tenancy, RBAC, and Audit Logging master architectural documentation

This commit is contained in:
Inamul-hasan-tec
2026-08-19 17:46:01 +05:30
parent 891b8157bc
commit 189fe338f5
6 changed files with 382 additions and 0 deletions
@@ -0,0 +1,59 @@
# 🏢 Core Multi-Tenant Architecture & Data Isolation Manual
## 1. Executive Summary
The PIM platform is designed as an Enterprise Multi-Tenant Software-as-a-Service (SaaS) application. It enforces strict logical isolation across tenants while sharing a unified application and database instance, maximizing resource efficiency, maintainability, and scalability.
---
## 2. Multi-Tenant Topology & Request Context Lifecycle
```mermaid
sequenceDiagram
autonumber
actor Client as Web Browser / API Consumer
participant Gate as API Gateway / Reverse Proxy
participant Auth as Auth & Context Middleware
participant TenantSvc as Tenant Context Engine
participant DB as PostgreSQL Multi-Tenant DB
Client->>Gate: HTTP Request (Authorization: Bearer <JWT>, x-tenant-id)
Gate->>Auth: Forward with Headers
Auth->>Auth: Verify JWT Token & Signature
Auth->>TenantSvc: buildContext(req)
alt Platform SuperAdmin with Impersonation
TenantSvc->>TenantSvc: Detect x-impersonated-tenant-id
TenantSvc->>TenantSvc: Set context.tenantId = Impersonated ID
TenantSvc->>TenantSvc: Set context.isImpersonating = true
else Standard Tenant User
TenantSvc->>TenantSvc: Set context.tenantId = jwt.user.tenant_id
TenantSvc->>TenantSvc: Set context.isImpersonating = false
end
TenantSvc-->>Auth: req.context populated
Auth->>DB: Execute Query WHERE tenant_id = req.context.tenantId
DB-->>Client: Scoped Data Response (Zero Cross-Tenant Leakage)
```
---
## 3. Core Multi-Tenant Tenets & Invariants
1. **Context Guarantee**: Every authenticated request populates `req.context`:
```javascript
req.context = {
tenantId: 19,
userId: "3c847d01-e23a-4a22-9218-192a514d2847",
roleIds: ["role-tenant-admin-uuid"],
userType: "tenant", // 'platform' or 'tenant'
isImpersonating: false
};
```
2. **Repository Layer Scoping**: All Sequelize queries MUST include `where: { tenant_id: req.context.tenantId }` (unless executed by a platform administrator in global management view).
3. **Tenant Provisioning Lifecycle**:
- Provisioning a new tenant creates:
- The `tenants` record.
- Default system roles (`TENANT_ADMIN`, `CATALOG_MANAGER`, `VIEWER`).
- Default permission bindings for all available `permission_nodes`.
- An initial root administrative user.
- Default taxonomy seeds (base units of measure, default attribute groups).
@@ -0,0 +1,44 @@
# 🔐 Authentication & User Identity Management
## 1. Overview
The Authentication Subsystem provides JWT-based session management, password hashing via bcrypt (10 rounds), token refresh rotations, and multi-tier user classification (`platform` vs `tenant`).
---
## 2. User Types & Security Realms
| User Type | Scope | Access Capabilities | Impersonation Allowed |
| :--- | :--- | :--- | :--- |
| **`platform`** | Global SaaS Operator | Full cross-tenant access, tenant provisioning, system nodes management, global billing and quotas | **YES** (via `x-impersonated-tenant-id`) |
| **`tenant`** | Specific Workspace | Restricted strictly to records where `tenant_id === user.tenant_id`. Governed by assigned RBAC roles | **NO** |
---
## 3. JWT Payload Structure & Token Lifecycle
### Token Structure
```json
{
"user_id": "3c847d01-e23a-4a22-9218-192a514d2847",
"email": "admin@maskantech.com",
"first_name": "Inam",
"last_name": "Admin",
"tenant_id": 19,
"user_type": "tenant",
"role_ids": ["fd9c2e97-9576-437d-aae9-939327efaf7e"],
"iat": 1787123456,
"exp": 1787209856
}
```
### Security Workflows
1. **Login (`POST /api/v1/auth/login`)**:
- Validates email and bcrypt password hash.
- Verifies `status === 'active'`.
- Eager-loads assigned `roles` and extracts `role_ids`.
- Returns Access Token (JWT) and User Profile payload.
2. **Password Updates**:
- Requires previous password verification.
- Enforces minimum 8-character complexity with letter, number, and special character requirements.
3. **Session Revocation**:
- Changing a user's status to `inactive` or deleting a user immediately halts subsequent requests as token validation checks against active DB records on critical operations.
@@ -0,0 +1,64 @@
# 🛡️ RBAC Permissions Matrix & Security Engine
## 1. Overview
The Role-Based Access Control (RBAC) engine enforces fine-grained authorization across all platform resources. It decouples functional permission definitions (**Permission Nodes**) from business identities (**Roles**), allowing dynamic, tenant-level customization of user access privileges.
---
## 2. Permission Action Matrix (7-Point Granularity)
Every permission node in the system supports 7 distinct operational flags:
```mermaid
graph LR
Node[Permission Node e.g. 'products'] --> View[can_view: Read & List]
Node --> Create[can_create: POST New]
Node --> Edit[can_edit: PUT/PATCH]
Node --> Delete[can_delete: Soft Delete]
Node --> Alter[can_alter: Schema/Publish]
Node --> Import[can_import: Batch Import]
Node --> Export[can_export: CSV/JSON Export]
```
---
## 3. Core System Permission Nodes Registry
| Module | Node Code | Node Name | Description |
| :--- | :--- | :--- | :--- |
| **Products** | `products` | Product Catalog Management | Core SKU and product entity lifecycle management |
| **Variants** | `variants` | Product Variants Management | Variant matrix generation and child SKU overrides |
| **Families** | `families` | Product Families (Catalogs) | Catalog blueprints, variant axes, and asset rules |
| **Categories** | `categories` | Categories Taxonomy | Hierarchical taxonomy tree and category assignments |
| **Attributes** | `attributes` | Attribute Management | Attribute definitions, sets, and attribute groups |
| **Brands** | `brands` | Brand Management | Brand registry and allowed brand constraints |
| **Units** | `units` | Units of Measure (UOM) | Unit registry and conversion factors |
| **Media (DAM)** | `assets` | Digital Asset Management | Media library uploads, asset types, and asset families |
| **Channels** | `channels` | Channel Syndication | Channel endpoints, transformations, and feeds |
| **Users & Roles** | `users` | User & RBAC Management | User provisioning, custom roles, and permission assignments |
| **Audit Logs** | `audit_logs` | Security & Compliance Logs | Read-only audit trail inspection |
| **Settings** | `settings` | Tenant Settings | Theme, white-labeling, and integration configurations |
---
## 4. Authorization Middleware Flow
```mermaid
flowchart TD
Req[Incoming Request] --> AuthCheck{Is req.user present?}
AuthCheck -- No --> 401[HTTP 401 Unauthorized]
AuthCheck -- Yes --> SuperCheck{Is user_type == 'platform'?}
SuperCheck -- Yes --> Pass[Pass: Next Middleware]
SuperCheck -- No --> AdminCheck{Has SUPER_ADMIN or TENANT_ADMIN role?}
AdminCheck -- Yes --> Pass
AdminCheck -- No --> RoleCheck{Inspect RolePermissions for node_code}
RoleCheck -- Action matches flag --> Pass
RoleCheck -- Missing flag --> 403[HTTP 403 Forbidden: Insufficient Permissions]
```
### Action Resolution Map
If no specific action is passed into `authorize('products')`, the middleware automatically infers the required flag from the HTTP Method:
- `GET` $\rightarrow$ `can_view`
- `POST` $\rightarrow$ `can_create`
- `PUT` / `PATCH` $\rightarrow$ `can_edit`
- `DELETE` $\rightarrow$ `can_delete`
@@ -0,0 +1,115 @@
# 🗄️ Core SaaS & Security Database Schema Dictionary
## 1. Overview
This document specifies all database tables, columns, data types, constraints, and relations powering Multi-Tenancy, Users, Roles, Permissions, and Auditing.
---
## 2. Table-by-Table Data Dictionary
### 2.1. `tenants` (Multi-Tenant Organization Accounts)
| Column Name | PostgreSQL Type | Nullable | Default | Description & Constraints |
| :--- | :--- | :--- | :--- | :--- |
| `id` | `SERIAL` (INTEGER) | NO | Auto-increment | Primary Key |
| `name` | `VARCHAR(255)` | NO | — | Legal Organization Name |
| `code` | `VARCHAR(100)` | NO | — | Unique organization code |
| `domain` | `VARCHAR(255)` | YES | `NULL` | Custom domain / CNAME mapping |
| `status` | `VARCHAR(50)` | NO | `'active'` | `active`, `suspended`, `pending_verification` |
| `plan_id` | `VARCHAR(50)` | YES | `'enterprise'`| Subscription tier plan |
| `settings` | `JSONB` | YES | `{}` | White-label branding, quotas, feature toggles |
| `created_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `updated_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `deleted_at` | `TIMESTAMP WITH TZ`| YES | `NULL` | Soft delete marker |
---
### 2.2. `users` (User Identity Master)
| Column Name | PostgreSQL Type | Nullable | Default | Description & Constraints |
| :--- | :--- | :--- | :--- | :--- |
| `id` | `UUID` | NO | `gen_random_uuid()` | Primary Key |
| `tenant_id` | `INTEGER` | YES | `NULL` | FK -> `tenants.id` (NULL for global platform users) |
| `first_name` | `VARCHAR(100)` | NO | — | User First Name |
| `last_name` | `VARCHAR(100)` | NO | — | User Last Name |
| `email` | `VARCHAR(255)` | NO | — | Unique email address across tenant realm |
| `password_hash` | `VARCHAR(255)` | NO | — | Bcrypt salted password hash |
| `user_type` | `VARCHAR(50)` | NO | `'tenant'` | `platform` (SaaS Admin) or `tenant` (Workspace Member) |
| `status` | `VARCHAR(50)` | NO | `'active'` | `active`, `inactive`, `locked` |
| `last_login_at` | `TIMESTAMP WITH TZ` | YES | `NULL` | Last session authentication timestamp |
| `created_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `updated_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `deleted_at` | `TIMESTAMP WITH TZ`| YES | `NULL` | Soft delete marker |
---
### 2.3. `roles` (RBAC Security Roles)
| Column Name | PostgreSQL Type | Nullable | Default | Description & Constraints |
| :--- | :--- | :--- | :--- | :--- |
| `id` | `UUID` | NO | `gen_random_uuid()` | Primary Key |
| `tenant_id` | `INTEGER` | YES | `NULL` | FK -> `tenants.id` |
| `role_name` | `VARCHAR(100)` | NO | — | Display Role Name (e.g. Catalog Manager) |
| `role_code` | `VARCHAR(50)` | NO | — | Unique Role Code (e.g. `CATALOG_MANAGER`) |
| `description`| `TEXT` | YES | `NULL` | Functional scope of the role |
| `status` | `BOOLEAN` | NO | `TRUE` | Active flag |
| `is_system` | `BOOLEAN` | NO | `FALSE` | Protected system role flag (prevents deletion) |
| `created_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `updated_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `deleted_at` | `TIMESTAMP WITH TZ`| YES | `NULL` | Soft delete marker |
---
### 2.4. `permission_nodes` (Functional Security Nodes)
| Column Name | PostgreSQL Type | Nullable | Default | Description & Constraints |
| :--- | :--- | :--- | :--- | :--- |
| `id` | `UUID` | NO | `gen_random_uuid()` | Primary Key |
| `node_code` | `VARCHAR(50)` | NO | — | Unique node code (e.g. `products`, `channels`) |
| `node_name` | `VARCHAR(100)` | NO | — | Display name (e.g. `Product Catalog`) |
| `module` | `VARCHAR(50)` | NO | — | UI/API Module categorization |
| `description`| `TEXT` | YES | `NULL` | Description of guarded operations |
| `is_system` | `BOOLEAN` | NO | `TRUE` | System managed node |
| `created_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `updated_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
---
### 2.5. `role_permissions` (Role to Permission Junction & Flags)
| Column Name | PostgreSQL Type | Nullable | Default | Description & Constraints |
| :--- | :--- | :--- | :--- | :--- |
| `id` | `UUID` | NO | `gen_random_uuid()` | Primary Key |
| `role_id` | `UUID` | NO | — | FK -> `roles.id` (Cascade delete) |
| `permission_node_id` | `UUID` | NO | — | FK -> `permission_nodes.id` |
| `can_view` | `BOOLEAN` | NO | `FALSE` | Read / List access |
| `can_create` | `BOOLEAN` | NO | `FALSE` | Create access |
| `can_edit` | `BOOLEAN` | NO | `FALSE` | Update / Edit access |
| `can_delete` | `BOOLEAN` | NO | `FALSE` | Soft delete access |
| `can_alter` | `BOOLEAN` | NO | `FALSE` | Lifecycle transition / publish access |
| `can_import` | `BOOLEAN` | NO | `FALSE` | Bulk import access |
| `can_export` | `BOOLEAN` | NO | `FALSE` | Bulk export access |
| `created_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `updated_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
---
### 2.6. `user_roles` (User to Role Junction)
| Column Name | PostgreSQL Type | Nullable | Default | Description & Constraints |
| :--- | :--- | :--- | :--- | :--- |
| `id` | `UUID` | NO | `gen_random_uuid()` | Primary Key |
| `user_id` | `UUID` | NO | — | FK -> `users.id` (Cascade delete) |
| `role_id` | `UUID` | NO | — | FK -> `roles.id` (Cascade delete) |
| `created_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
| `updated_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Timestamp |
---
### 2.7. `audit_logs` (Security & Operations Audit Trail)
| Column Name | PostgreSQL Type | Nullable | Default | Description & Constraints |
| :--- | :--- | :--- | :--- | :--- |
| `id` | `UUID` | NO | `gen_random_uuid()` | Primary Key |
| `tenant_id` | `INTEGER` | YES | `NULL` | FK -> `tenants.id` |
| `user_id` | `UUID` | YES | `NULL` | FK -> `users.id` (Executor) |
| `action` | `VARCHAR(50)` | NO | — | `CREATE`, `UPDATE`, `DELETE`, `PUBLISH`, `LOGIN` |
| `entity` | `VARCHAR(100)` | NO | — | Target entity name (`Product`, `Category`, `Role`) |
| `entity_id` | `VARCHAR(100)` | YES | `NULL` | Target record UUID/ID |
| `details` | `JSONB` | YES | `{}` | Before/After JSON diff snapshot |
| `ip_address` | `VARCHAR(45)` | YES | `NULL` | IPv4 or IPv6 client address |
| `user_agent` | `TEXT` | YES | `NULL` | Browser / Client User-Agent string |
| `created_at` | `TIMESTAMP WITH TZ`| NO | `NOW()` | Audit event timestamp |
@@ -0,0 +1,73 @@
# 📜 Audit Logging, Security Interceptors & Compliance
## 1. Overview
The Audit Logging system provides an immutable, append-only historical record of all state-mutating actions across the PIM platform. It guarantees enterprise compliance (SOC 2, ISO 27001, GDPR) by recording *who* performed *what* action on *which* entity, along with chronological before-and-after JSON snapshots, IP addresses, and user-agent metadata.
---
## 2. Audit Event Interceptor Architecture
```mermaid
sequenceDiagram
autonumber
actor User as Authenticated User
participant Route as Express API Endpoint
participant Svc as Feature Service Layer
participant DB as PostgreSQL DB
participant Audit as AuditLogService
participant WS as Real-Time Notification Broadcaster
User->>Route: PUT /api/v1/products/:id (Change Price / Status)
Route->>Svc: updateProduct(id, changes, context)
Svc->>DB: Fetch original record (Before Snapshot)
Svc->>DB: Apply update (After Snapshot)
rect rgb(245, 255, 245)
Note over Svc,Audit: Automated Audit Capture
Svc->>Audit: recordLog({ tenant_id, user_id, action: 'UPDATE', entity: 'Product', entity_id, diff, ip, ua })
Audit->>DB: INSERT INTO audit_logs (...)
end
opt High-Priority Mutation (e.g. Product Publish, Role Alteration)
Svc->>WS: Broadcast security event to tenant administrators
end
Svc-->>Route: Updated Result
Route-->>User: HTTP 200 OK
```
---
## 3. Audit Log Schema & Diff Structure
```json
{
"id": "7b049d11-4fec-411a-9a8b-3d84950e1234",
"tenant_id": 19,
"user_id": "3c847d01-e23a-4a22-9218-192a514d2847",
"action": "UPDATE",
"entity": "Product",
"entity_id": "80c68220-9d0b-485b-a1df-c96f883b5e6b",
"details": {
"status": {
"previous": "draft",
"current": "active"
},
"price": {
"previous": 199.99,
"current": 249.99
},
"modified_fields": ["status", "price"]
},
"ip_address": "192.168.1.49",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/128.0.0.0",
"created_at": "2026-08-19T17:45:00.000Z"
}
```
---
## 4. Compliance & Security Guarantees
1. **Append-Only Immutability**: `audit_logs` has NO `update` or `delete` API endpoints. Once an audit record is written, it cannot be modified or truncated through standard application routes.
2. **Tenant Scoping**: Audit log queries are strictly isolated to `tenant_id = req.context.tenantId`.
3. **Session Context Association**: Every audit record links the originating authenticated JWT user ID and client network location.
+27
View File
@@ -0,0 +1,27 @@
# 📚 Core SaaS & RBAC Security Engine Master Documentation
Welcome to the architectural and operational knowledge base for the **Core Multi-Tenant SaaS, Authentication, RBAC, and Audit Logging** subsystems.
---
## 📑 Manuals & Reference Guides
| File | Scope & Contents |
| :--- | :--- |
| **[`01_MULTI_TENANT_ARCHITECTURE_AND_ISOLATION.md`](file:///Users/maskantech/Desktop/PIM/docs/core_saas_and_rbac_engine/01_MULTI_TENANT_ARCHITECTURE_AND_ISOLATION.md)** | Multi-tenant logical topology, request context builder, support impersonation mode, and tenant provisioning lifecycle. |
| **[`02_AUTHENTICATION_AND_USER_MANAGEMENT.md`](file:///Users/maskantech/Desktop/PIM/docs/core_saas_and_rbac_engine/02_AUTHENTICATION_AND_USER_MANAGEMENT.md)** | User identity models, JWT payload tokens, bcrypt password encryption, platform vs tenant realms, and session management. |
| **[`03_RBAC_PERMISSIONS_MATRIX_AND_SECURITY_ENGINE.md`](file:///Users/maskantech/Desktop/PIM/docs/core_saas_and_rbac_engine/03_RBAC_PERMISSIONS_MATRIX_AND_SECURITY_ENGINE.md)** | 7-point permission action matrix (`can_view`, `can_create`, `can_edit`, `can_delete`, `can_alter`, `can_import`, `can_export`), system roles, and authorization middleware logic. |
| **[`04_DATABASE_SCHEMA_AND_SECURITY_DICTIONARY.md`](file:///Users/maskantech/Desktop/PIM/docs/core_saas_and_rbac_engine/04_DATABASE_SCHEMA_AND_SECURITY_DICTIONARY.md)** | Detailed table dictionary for `tenants`, `users`, `roles`, `permission_nodes`, `role_permissions`, `user_roles`, and `audit_logs`. |
| **[`05_AUDIT_LOGGING_AND_ENTERPRISE_COMPLIANCE.md`](file:///Users/maskantech/Desktop/PIM/docs/core_saas_and_rbac_engine/05_AUDIT_LOGGING_AND_ENTERPRISE_COMPLIANCE.md)** | Append-only audit interceptors, before/after JSON diff captures, IP/User-Agent tracking, and compliance architecture. |
---
## 🎯 Quick Verification Commands
```bash
# Verify backend server health
curl -sI http://localhost:5002/api/v1/categories
# Verify frontend build & dev server
curl -sI http://localhost:5173
cd productcatalogue_frontend && npx tsc --noEmit
```