## Documentation - Align MCH-029 to MCH-032 with template-saas modules (SAAS-008 to SAAS-015) - Create MCH-034 (Analytics) and MCH-035 (Reports) from SAAS-016/017 - Update PLAN-DESARROLLO.md with Phase 7 and 8 - Update _MAP.md indexes (35 total epics) ## Database (5 new schemas, 14 tables) - Add storage schema: buckets, files, signed_urls - Add webhooks schema: endpoints, deliveries - Add audit schema: logs, retention_policies - Add features schema: flags, tenant_flags (14 seeds) - Add analytics schema: metrics, events, reports, report_schedules - Add auth.oauth_connections for MCH-030 - Add timestamptz_to_date() IMMUTABLE function - Update EXPECTED_SCHEMAS in recreate-database.sh ## Analysis Reports - ANALISIS-INTEGRACION-TEMPLATE-SAAS-2026-01-13.md - VALIDACION-COHERENCIA-2026-01-13.md - GAP-ANALYSIS-BD-2026-01-13.md - REPORTE-EJECUCION-2026-01-13.md Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
337 lines
11 KiB
Markdown
337 lines
11 KiB
Markdown
---
|
|
id: EPIC-MCH-031
|
|
type: Epic
|
|
title: "MCH-031: Auditoria Empresarial"
|
|
code: MCH-031
|
|
status: Planificado
|
|
phase: 7
|
|
priority: P1
|
|
created_at: 2026-01-10
|
|
updated_at: 2026-01-10
|
|
simco_version: "4.0.1"
|
|
dependencies:
|
|
blocks: []
|
|
depends_on: []
|
|
---
|
|
|
|
# MCH-031: Auditoria Empresarial
|
|
|
|
## Metadata
|
|
- **Codigo:** MCH-031
|
|
- **Fase:** 7 - Expansion
|
|
- **Prioridad:** P1
|
|
- **Estado:** Planificado
|
|
- **Story Points:** 5
|
|
- **Sprint Objetivo:** Sprint 7
|
|
|
|
## Descripcion
|
|
|
|
Implementar sistema de auditoria completo con registro de todas las acciones CRUD, politica de retencion configurable y capacidad de exportacion para compliance. Permite trazabilidad completa de operaciones y deteccion de actividades sospechosas.
|
|
|
|
## Objetivos
|
|
|
|
1. Registrar todas las acciones de usuarios en el sistema
|
|
2. Mantener historial de cambios con valores antes/despues
|
|
3. Configurar politicas de retencion por tenant
|
|
4. Exportar logs para auditorias externas
|
|
5. Visualizar actividad en dashboard admin
|
|
|
|
## Alcance
|
|
|
|
### Incluido
|
|
- Audit logs para CREATE, UPDATE, DELETE
|
|
- Activity logs para acciones de usuario (login, logout, view)
|
|
- Interceptor global NestJS
|
|
- Politica de retencion (30, 90, 365 dias)
|
|
- Exportacion CSV
|
|
- Visor de logs en admin
|
|
|
|
### Excluido
|
|
- SIEM integration (futuro)
|
|
- Real-time alerting (ver notificaciones)
|
|
- Forensic analysis tools
|
|
|
|
## Arquitectura
|
|
|
|
```
|
|
┌─────────────────────────────────────┐
|
|
│ MCH-031: Auditoria │
|
|
└─────────────────────────────────────┘
|
|
│
|
|
┌───────────────────────┴───────────────────────┐
|
|
▼ ▼
|
|
┌─────────────────────┐ ┌─────────────────────┐
|
|
│ Audit Logs │ │ Activity Logs │
|
|
│ (data changes) │ │ (user actions) │
|
|
└──────────┬──────────┘ └──────────┬──────────┘
|
|
│ │
|
|
└──────────────────┬─────────────────────────┘
|
|
▼
|
|
┌─────────────────────────────────────────┐
|
|
│ AuditInterceptor │
|
|
│ (NestJS Global Interceptor) │
|
|
└─────────────────────────────────────────┘
|
|
│
|
|
┌──────────────────┼──────────────────┐
|
|
▼ ▼ ▼
|
|
┌──────────┐ ┌──────────┐ ┌──────────┐
|
|
│ schema │ │ Retencion│ │ Export │
|
|
│ audit │ │ Policy │ │ CSV │
|
|
└──────────┘ └──────────┘ └──────────┘
|
|
```
|
|
|
|
## Entregables
|
|
|
|
| Entregable | Estado | Sprint | Ubicacion |
|
|
|------------|--------|--------|-----------|
|
|
| Schema audit (DDL) | Planificado | 7 | `database/schemas/14-audit.sql` |
|
|
| AuditInterceptor | Planificado | 7 | `apps/backend/src/common/interceptors/` |
|
|
| AuditService | Planificado | 7 | `apps/backend/src/modules/audit/` |
|
|
| AuditController | Planificado | 7 | `apps/backend/src/modules/audit/` |
|
|
| Retention Job | Planificado | 7 | `apps/backend/src/jobs/` |
|
|
| UI Visor logs | Planificado | 7 | `apps/web/src/pages/admin/audit/` |
|
|
|
|
## Dependencias
|
|
|
|
### Depende de
|
|
- Ninguna (puede ejecutarse en paralelo con MCH-029)
|
|
|
|
### Bloquea a
|
|
- Ninguna
|
|
|
|
---
|
|
|
|
## Historias de Usuario
|
|
|
|
### MCH-US-107: Registro de Acciones
|
|
|
|
**Como** administrador
|
|
**Quiero** ver un registro de todas las acciones realizadas en el sistema
|
|
**Para** tener trazabilidad y detectar actividades sospechosas
|
|
|
|
**Story Points:** 3
|
|
|
|
**Criterios de Aceptacion:**
|
|
- [CA-107-1] Registra CREATE, UPDATE, DELETE automaticamente
|
|
- [CA-107-2] Incluye: usuario, timestamp, IP, user-agent
|
|
- [CA-107-3] Guarda valor anterior y nuevo en cambios (old_value, new_value)
|
|
- [CA-107-4] Filtrable por usuario, accion, entidad, rango de fechas
|
|
- [CA-107-5] Exportable a CSV con columnas seleccionables
|
|
|
|
**Tareas:**
|
|
| ID | Tarea | Tipo | SP |
|
|
|----|-------|------|-----|
|
|
| MCH-TT-107-01 | DDL schema audit (audit_logs, activity_logs) | DDL | 0.5 |
|
|
| MCH-TT-107-02 | AuditInterceptor global | Backend | 0.5 |
|
|
| MCH-TT-107-03 | AuditService con metodos log/query | Backend | 0.5 |
|
|
| MCH-TT-107-04 | AuditController (GET /audit/logs) | Backend | 0.25 |
|
|
| MCH-TT-107-05 | UI visor de logs con filtros | Frontend | 0.5 |
|
|
| MCH-TT-107-06 | Exportacion CSV | Backend | 0.25 |
|
|
| MCH-TT-107-07 | Tests | Test | 0.25 |
|
|
| MCH-TT-107-08 | Documentacion | Docs | 0.25 |
|
|
|
|
---
|
|
|
|
### MCH-US-108: Politica de Retencion
|
|
|
|
**Como** administrador
|
|
**Quiero** configurar cuanto tiempo se guardan los logs
|
|
**Para** cumplir con politicas de retencion y optimizar almacenamiento
|
|
|
|
**Story Points:** 2
|
|
|
|
**Criterios de Aceptacion:**
|
|
- [CA-108-1] Configuracion de dias de retencion: 30, 90, 180, 365
|
|
- [CA-108-2] Job automatico de limpieza (cron diario)
|
|
- [CA-108-3] Opcion de archivar a storage antes de eliminar
|
|
- [CA-108-4] Notificacion por email antes de purga (7 dias antes)
|
|
|
|
**Tareas:**
|
|
| ID | Tarea | Tipo | SP |
|
|
|----|-------|------|-----|
|
|
| MCH-TT-108-01 | Configuracion de retencion en tenant_settings | Backend | 0.25 |
|
|
| MCH-TT-108-02 | Job de limpieza con BullMQ (cron) | Backend | 0.5 |
|
|
| MCH-TT-108-03 | Archivado opcional a storage (S3) | Backend | 0.5 |
|
|
| MCH-TT-108-04 | Tests | Test | 0.25 |
|
|
| MCH-TT-108-05 | Documentacion de politica de retencion | Docs | 0.5 |
|
|
|
|
---
|
|
|
|
## Resumen de Story Points
|
|
|
|
| Historia | SP | Sprint |
|
|
|----------|-----|--------|
|
|
| MCH-US-107: Registro de Acciones | 3 | 7 |
|
|
| MCH-US-108: Politica de Retencion | 2 | 7 |
|
|
| **TOTAL** | **5** | 7 |
|
|
|
|
---
|
|
|
|
## Criterios de Aceptacion de Epica
|
|
|
|
- [ ] Todas las acciones CRUD se registran automaticamente
|
|
- [ ] Logs visibles en dashboard admin
|
|
- [ ] Exportacion CSV funcional
|
|
- [ ] Job de limpieza ejecutandose diariamente
|
|
- [ ] Cobertura de tests >80%
|
|
|
|
## Notas Tecnicas
|
|
|
|
### Schema audit
|
|
|
|
```sql
|
|
CREATE SCHEMA IF NOT EXISTS audit;
|
|
|
|
CREATE TABLE audit.audit_logs (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
tenant_id UUID NOT NULL,
|
|
user_id UUID,
|
|
action VARCHAR(20) NOT NULL, -- CREATE, UPDATE, DELETE
|
|
entity_type VARCHAR(100) NOT NULL, -- Product, Order, User
|
|
entity_id UUID NOT NULL,
|
|
old_value JSONB,
|
|
new_value JSONB,
|
|
ip_address INET,
|
|
user_agent TEXT,
|
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
|
);
|
|
|
|
CREATE INDEX idx_audit_logs_tenant_date ON audit.audit_logs(tenant_id, created_at DESC);
|
|
CREATE INDEX idx_audit_logs_entity ON audit.audit_logs(entity_type, entity_id);
|
|
```
|
|
|
|
### Configuracion de Retencion
|
|
```typescript
|
|
// En tenant_settings
|
|
{
|
|
"audit": {
|
|
"retention_days": 90,
|
|
"archive_before_delete": true,
|
|
"notify_before_purge": true
|
|
}
|
|
}
|
|
```
|
|
|
|
## ADRs Relacionados
|
|
|
|
- [ADR-0008: Audit Log Retention](../97-adr/ADR-0008-audit-log-retention.md)
|
|
|
|
---
|
|
|
|
## Especificaciones Tecnicas Detalladas (Ref: SAAS-008)
|
|
|
|
Esta seccion documenta las especificaciones del modulo de auditoria segun template-saas para garantizar alineacion arquitectonica.
|
|
|
|
### Estructura de Tabla audit_logs
|
|
|
|
| Campo | Tipo | Descripcion |
|
|
|-------|------|-------------|
|
|
| id | UUID | Identificador unico |
|
|
| tenant_id | UUID | Tenant al que pertenece |
|
|
| user_id | UUID | Usuario que realizo la accion |
|
|
| action | VARCHAR | Tipo de accion (create/update/delete/read/auth) |
|
|
| entity_type | VARCHAR | Tipo de entidad afectada |
|
|
| entity_id | UUID | ID de la entidad afectada |
|
|
| changes | JSONB | Objeto con {before, after, diff} |
|
|
| ip_address | INET | Direccion IP del cliente |
|
|
| user_agent | TEXT | User agent del navegador |
|
|
| metadata | JSONB | Datos adicionales (requestId, location) |
|
|
| created_at | TIMESTAMP | Fecha de creacion |
|
|
|
|
### Tabla Adicional: auth_logs
|
|
|
|
| Campo | Tipo | Descripcion |
|
|
|-------|------|-------------|
|
|
| id | UUID | Identificador unico |
|
|
| tenant_id | UUID | Tenant al que pertenece |
|
|
| user_id | UUID | Usuario relacionado |
|
|
| action | VARCHAR | Tipo (login/logout/failed/mfa) |
|
|
| ip_address | INET | Direccion IP |
|
|
| user_agent | TEXT | User agent |
|
|
| location | JSONB | {country, city} |
|
|
| success | BOOLEAN | Si fue exitoso |
|
|
| failure_reason | TEXT | Razon de fallo si aplica |
|
|
| created_at | TIMESTAMP | Fecha de creacion |
|
|
|
|
### Endpoints API del Modulo
|
|
|
|
| Metodo | Endpoint | Descripcion |
|
|
|--------|----------|-------------|
|
|
| GET | /audit/logs | Listar logs con paginacion y filtros |
|
|
| GET | /audit/logs/:id | Detalle de un log especifico |
|
|
| GET | /audit/entity/:type/:id | Logs de una entidad especifica |
|
|
| GET | /audit/user/:id | Logs de un usuario especifico |
|
|
| GET | /audit/auth | Logs de autenticacion |
|
|
| GET | /audit/export | Exportar logs (CSV/JSON) |
|
|
| GET | /audit/stats | Estadisticas de auditoria |
|
|
|
|
### Tipos de Acciones Soportadas
|
|
|
|
#### Acciones de Datos
|
|
| Accion | Descripcion |
|
|
|--------|-------------|
|
|
| entity.created | Registro creado |
|
|
| entity.updated | Registro modificado |
|
|
| entity.deleted | Registro eliminado |
|
|
| entity.viewed | Registro consultado |
|
|
| bulk.import | Importacion masiva |
|
|
| bulk.export | Exportacion masiva |
|
|
|
|
#### Acciones de Autenticacion
|
|
| Accion | Descripcion |
|
|
|--------|-------------|
|
|
| auth.login | Login exitoso |
|
|
| auth.logout | Logout |
|
|
| auth.failed | Login fallido |
|
|
| auth.mfa | MFA verificado |
|
|
| auth.password_change | Password cambiado |
|
|
| auth.session_revoked | Sesion revocada |
|
|
|
|
### Politica de Retencion por Plan
|
|
|
|
| Plan | Retencion |
|
|
|------|-----------|
|
|
| Free | 7 dias |
|
|
| Starter | 30 dias |
|
|
| Pro | 90 dias |
|
|
| Enterprise | 1 año (configurable) |
|
|
|
|
### Estructura de Log Completa
|
|
|
|
```typescript
|
|
interface AuditLog {
|
|
id: string;
|
|
tenantId: string;
|
|
userId: string;
|
|
userName: string;
|
|
action: string;
|
|
entityType: string;
|
|
entityId: string;
|
|
changes: {
|
|
before: object | null;
|
|
after: object | null;
|
|
diff: object; // solo campos cambiados
|
|
};
|
|
metadata: {
|
|
ip: string;
|
|
userAgent: string;
|
|
location?: {
|
|
country: string;
|
|
city: string;
|
|
};
|
|
requestId: string;
|
|
};
|
|
createdAt: Date;
|
|
}
|
|
```
|
|
|
|
### Referencia
|
|
|
|
> Documentacion fuente: `/projects/template-saas/docs/01-modulos/SAAS-008-audit-logs.md`
|
|
> Version: 1.0.0
|
|
|
|
---
|
|
|
|
**Ultima actualizacion:** 2026-01-13
|
|
**Autor:** Architecture Team
|