# _MAP: MGN-007 - Audit

**Modulo:** MGN-007
**Nombre:** Auditoria y Logs
**Fase:** 02 - Core Business
**Story Points:** 30 SP
**Estado:** Implementado
**Sprint:** 7
**Ultima actualizacion:** 2026-01-07

---

## Resumen

Sistema completo de auditoria con Audit Trail automatico (TypeORM Subscriber), Access Logs, Security Events con deteccion de brute force y anomalias.

---

## Metricas

| Metrica | Valor |
|---------|-------|
| Story Points | 30 SP |
| Requerimientos (RF) | 4 |
| Especificaciones (ET) | 3 |
| User Stories (US) | 4 |
| Tablas DB | 3 |
| Endpoints API | 15 |
| Tests | - |

---

## Requerimientos Funcionales

| ID | Titulo | Prioridad | SP |
|----|--------|-----------|---:|
| [RF-AUDIT-001](./requerimientos/RF-AUDIT-001.md) | Audit Trail | P0 | 10 |
| [RF-AUDIT-002](./requerimientos/RF-AUDIT-002.md) | Access Logs | P0 | 8 |
| [RF-AUDIT-003](./requerimientos/RF-AUDIT-003.md) | Security Events | P0 | 8 |
| [RF-AUDIT-004](./requerimientos/RF-AUDIT-004.md) | Consultas y Reportes | P1 | 5 |

**Indice completo:** [INDICE-RF-AUDIT.md](./requerimientos/INDICE-RF-AUDIT.md)

---

## Especificaciones Tecnicas

| ID | Archivo | Titulo |
|----|---------|--------|
| ET-AUDIT-backend | [ET-AUDIT-backend.md](./especificaciones/ET-AUDIT-backend.md) | Backend Services |
| ET-AUDIT-frontend | [ET-AUDIT-frontend.md](./especificaciones/ET-AUDIT-frontend.md) | Frontend Components |
| ET-AUDIT-database | [ET-AUDIT-database.md](./especificaciones/ET-AUDIT-database.md) | Database Schema |

---

## Historias de Usuario

| ID | Titulo | Estado |
|----|--------|--------|
| US-MGN007-001 | Audit Trail | Implementado |
| US-MGN007-002 | Access Logs | Implementado |
| US-MGN007-003 | Security Events | Implementado |
| US-MGN007-004 | Consultas y Dashboard | Implementado |

---

## Implementacion

### Database (DDL: 13-audit.sql)

| Objeto | Tipo | Schema |
|--------|------|--------|
| audit_logs | Tabla | audit |
| access_logs | Tabla | audit |
| security_events | Tabla | audit |

### Enums y Types

| Enum | Valores |
|------|---------|
| audit_action | INSERT, UPDATE, DELETE |
| access_event_type | LOGIN_SUCCESS, LOGIN_FAILED, LOGOUT, TOKEN_REFRESH, PASSWORD_CHANGE, PASSWORD_RESET, API_ACCESS |
| security_severity | LOW, MEDIUM, HIGH, CRITICAL |

### Backend (src/modules/audit/)

| Objeto | Tipo | Path |
|--------|------|------|
| AuditService | Service | src/modules/audit/audit.service.ts |
| AccessLogsService | Service | src/modules/audit/access-logs.service.ts |
| SecurityEventsService | Service | src/modules/audit/security-events.service.ts |
| AuditController | Controller | src/modules/audit/audit.controller.ts |
| AccessLogsController | Controller | src/modules/audit/access-logs.controller.ts |
| SecurityEventsController | Controller | src/modules/audit/security-events.controller.ts |
| AuditSubscriber | Subscriber | src/modules/audit/audit.subscriber.ts |
| AuditContext | Context | src/modules/audit/audit-context.ts |

### Entities

| Entity | Path |
|--------|------|
| AuditLog | src/modules/audit/entities/audit-log.entity.ts |
| AccessLog | src/modules/audit/entities/access-log.entity.ts |
| SecurityEvent | src/modules/audit/entities/security-event.entity.ts |

### Utilities

| Utility | Path | Proposito |
|---------|------|-----------|
| BruteForceDetector | src/modules/audit/utils/brute-force-detector.ts | Detecta ataques de fuerza bruta |
| AnomalyDetector | src/modules/audit/utils/anomaly-detector.ts | Detecta patrones anomalos |

### Routes

| Route | Method | Endpoint |
|-------|--------|----------|
| AuditRoutes | GET | /api/audit/logs |
| AccessLogsRoutes | GET | /api/audit/access-logs |
| SecurityEventsRoutes | GET/PATCH | /api/audit/security-events |

### Caracteristicas Implementadas

- **TypeORM Subscriber:** Captura automatica de INSERT/UPDATE/DELETE
- **AsyncLocalStorage:** Propagacion de contexto (tenant, user, IP)
- **Brute Force Detection:** Detecta intentos fallidos de login
- **Anomaly Detection:** Detecta IPs nuevas, cambios de ubicacion
- **Cleanup Functions:** Limpieza automatica de logs antiguos
- **RLS Policies:** Aislamiento por tenant

---

## Dependencias

**Depende de:** MGN-001 (Auth), MGN-002 (Users), MGN-004 (Tenants)

**Requerido por:** Ninguno (transversal)

---

## Trazabilidad

Ver: [TRACEABILITY.yml](./implementacion/TRACEABILITY.yml)

---

## Changelog

| Fecha | Sprint | Cambios |
|-------|--------|---------|
| 2026-01-07 | Sprint 7 | Implementacion completa: Audit Trail, Access Logs, Security Events |
| 2025-12-05 | - | Documentacion RF inicial |

---

**Generado por:** Requirements-Analyst
**Implementado por:** Backend-Agent (Sprint 7)
**Fecha:** 2026-01-07
