Compare commits

..

11 Commits

Author SHA1 Message Date
6af80f1960 Feature: Sistema de Análisis de Seguridad y Detección de Vulnerabilidades v1.6.0
Nuevas funcionalidades:
- Sistema completo de análisis de seguridad con detección de amenazas
- Detección de patrones: fuerza bruta, escalada de privilegios, eliminaciones masivas, cuentas comprometidas
- Panel de vulnerabilidades con visualización detallada
- Acciones de seguridad: bloqueo de IPs, notificaciones, reset de contraseñas
- Análisis configurable (24h, 48h, 7 días)

Backend (/audit/security/):
- GET /analysis: Análisis completo de seguridad con amenazas detectadas
- POST /action: Ejecutar acciones de seguridad (solo ADMIN/SUPPORT_MANAGER)
- Schemas nuevos: SecurityAnalysisResponse, SecurityThreatPattern, SecurityActionRequest

Frontend (/audit/security):
- Panel completo de análisis con nivel de riesgo general
- Visualización de amenazas con severidad (critical, high, medium, low)
- Estadísticas: amenazas, intentos fallidos, IPs sospechosas, acciones críticas
- Opciones de acción por amenaza: bloquear IP, resetear contraseña, notificar admin
- Modal de ejecución de acciones de seguridad

Mejoras:
- Sidebar actualizado con enlace 'Seguridad'
- Permisos: Solo ADMIN/SUPPORT_MANAGER/AUDITOR pueden ver análisis
- Solo ADMIN/SUPPORT_MANAGER pueden ejecutar acciones
- Audit log de todas las acciones de seguridad ejecutadas
2026-02-16 10:09:36 -07:00
57944b364c Configure v1.6.0 display across application
- backend/app/core/config.py: Add APP_VERSION = '1.6.0' setting
- backend/app/main.py: Update health and root endpoints to show APP_VERSION
- frontend-internal/Sidebar.svelte: Add version display in sidebar footer
- frontend-client/+layout.svelte: Add version in page footer
- All endpoints now return both app_version (1.6.0) and api_version (v1)
2026-02-16 09:56:02 -07:00
3a061a005c Release v1.6.0 - Audit System Cross-Tenant Viewing
Features:
-  Cross-tenant audit log viewing for ADMIN/SUPPORT_MANAGER
-  New 'all_tenants' parameter in audit endpoints
-  Frontend toggle to view all clients' logs
-  Multi-tenant stats support in /audit/stats
-  Fixed timezone issue with date filters (UTC consistency)
-  Fixed date_to filter overlap causing duplicate records

Changes:
- backend/app/api/v1/endpoints/audit.py:
  * Added tenant_id and all_tenants query parameters
  * Permission checks for cross-tenant viewing
  * Dynamic tenant filtering based on user role
  * Fixed date_to filter (removed +1 day overlap)
  * Updated all stats queries for multi-tenant support

- frontend-internal/src/routes/audit/+page.svelte:
  * Import auth store for role detection
  * Added 'Ver todos los clientes' toggle for admins
  * Pass all_tenants parameter to API calls
  * UI badge indicating multi-tenant mode

- Version bump: 1.5.1.2 → 1.6.0 across all packages
2026-02-16 09:50:30 -07:00
d9b783107f fix: Corregir filtro de fechas en auditoría por zona horaria
- El filtro usaba hora local que se convertía incorrectamente a UTC
- Los registros de 'hoy' aparecían en 'ayer' por desfase horario
- Ahora trabaja directamente en UTC para consistencia
- Afecta todos los filtros: today, yesterday, last7days, last30days
- Custom dates también parseados correctamente como UTC
2026-02-16 09:26:43 -07:00
5a292daa0b feat: Script para crear usuario de prueba con contraseña conocida
- Permite crear/actualizar usuario admin@aduanasoft.com
- Password: admin123
- Facilita testing del sistema de auditoría
- Genera hash correcto con Argon2
2026-02-16 09:21:06 -07:00
87e094b668 feat: Integrar AuditService en todos los endpoints críticos
- Auth: login, logout, login_failed con registro automático
- Tickets: create, update, delete, assign con old/new values
- Users: create, update, delete con sanitización de passwords
- Stats: implementar top_users con JOIN a tabla users
- Schema: agregar índices compuestos para mejor performance
- Frontend: limpiar logs de debug en viewDetail
- Manejo de errores: audit logs no afectan flujo principal
2026-02-16 09:08:03 -07:00
2cb8b58808 Fix: Corregir funcionalidad del botón Ver en auditoría
- Eliminar click en fila completa que causaba conflicto
- Eliminar stopPropagation innecesario de botones
- Agregar type='button' a todos los botones Ver
- Mejorar hover states y transiciones
- Agregar títulos para accesibilidad
- Simplificar lógica de eventos de click
- Botones Ver ahora funcionan correctamente en tabla y tarjetas
- Tarjeta de vulnerabilidad: solo botón Ver es clickeable
2026-02-16 08:43:03 -07:00
9f973464b9 Implementar tarjeta de Vulnerabilidad y mejorar interactividad
- Reemplazar tarjeta 'Más Común' por 'Vulnerabilidad'
- Backend: Agregar campo critical_actions_today al schema de stats
- Backend: Calcular acciones críticas (delete, update sensibles, logout)
- Frontend: Mostrar contador de acciones críticas con código de color
- Frontend: Click en tarjeta filtra por acciones críticas del día
- Frontend: Botón 'Ver' funcional con icono
- Color rojo si >10 críticas, ámbar si >5, verde si <=5
- Función filterCriticalActions() para búsqueda rápida
- UX mejorada con hover effects y transiciones
2026-02-16 08:38:39 -07:00
90f9c9c6e6 Modernizar UI de registros de auditoría (UX mejorada)
- Diseño responsivo: tabla en desktop, tarjetas en móvil/tablet
- Altura máxima con scroll interno (evita scroll de página completa)
- Avatares circulares con iniciales del usuario
- Filas/tarjetas más compactas y eficientes
- Paginación sticky (siempre visible al fondo)
- Botones primera/última página para navegación rápida
- Página actual resaltada en color primary
- Click en toda la fila para ver detalles
- Diseño más moderno y limpio
- Mejor uso del espacio vertical
2026-02-16 08:31:07 -07:00
51a8515b40 Fix: Corregir formato de fechas en auditoría
- Enviar datetime ISO completo en lugar de solo fecha (YYYY-MM-DD)
- Backend requiere formato datetime ISO 8601
- Agregar hora 00:00:00 para fecha inicio y 23:59:59 para fecha fin
- Manejar correctamente fechas custom vacías
- Soluciona error 422 (Unprocessable Entity)
2026-02-16 08:24:14 -07:00
ff9a8998b2 Mejora UI de página de auditoría
- Por defecto muestra solo logs del día actual
- Agregado selector de período rápido (Hoy, Ayer, 7 días, 30 días, Personalizado)
- Filtros avanzados colapsables para mejor UX
- Interfaz más limpia y organizada
- Formato de fechas mejorado (hora corta para hoy)
- Estadísticas visuales mejoradas
- Tabla simplificada con información esencial
- Modal de detalles mantiene toda la información completa
2026-02-16 08:17:39 -07:00
17 changed files with 1996 additions and 419 deletions

View File

@@ -51,6 +51,55 @@ class AuditLogResponse(AuditLogBase):
from_attributes = True
# ===================================
# SECURITY ANALYSIS SCHEMAS
# ===================================
class SecurityThreatPattern(BaseModel):
"""Patrón de amenaza detectado."""
type: str = Field(description="Tipo de amenaza (brute_force, privilege_escalation, etc.)")
severity: str = Field(description="Severidad: low, medium, high, critical")
description: str = Field(description="Descripción de la amenaza")
occurrences: int = Field(description="Número de ocurrencias")
affected_ips: list[str] = Field(default=[], description="IPs involucradas")
affected_users: list[str] = Field(default=[], description="Usuarios afectados")
first_seen: datetime = Field(description="Primera ocurrencia")
last_seen: datetime = Field(description="Última ocurrencia")
recommendations: list[str] = Field(default=[], description="Recomendaciones de acción")
class SecurityAnalysisResponse(BaseModel):
"""Análisis completo de seguridad."""
overall_risk_level: str = Field(description="Nivel de riesgo general: safe, low, medium, high, critical")
total_threats_detected: int = Field(description="Total de amenazas detectadas")
threats: list[SecurityThreatPattern] = Field(description="Lista de amenazas detectadas")
analysis_period_hours: int = Field(description="Período de análisis en horas")
generated_at: datetime = Field(description="Timestamp del análisis")
# Estadísticas de seguridad
failed_login_attempts: int = Field(description="Intentos fallidos de login")
suspicious_ips_count: int = Field(description="IPs sospechosas detectadas")
critical_actions_count: int = Field(description="Acciones críticas realizadas")
# Opciones de acción
recommended_actions: list[str] = Field(default=[], description="Acciones recomendadas")
class SecurityActionRequest(BaseModel):
"""Solicitud de acción de seguridad."""
action_type: str = Field(description="Tipo de acción: block_ip, notify_admin, reset_password, etc.")
target: str = Field(description="Objetivo de la acción (IP, email, etc.)")
reason: str = Field(description="Razón de la acción")
duration_minutes: Optional[int] = Field(None, description="Duración del bloqueo en minutos")
class SecurityActionResponse(BaseModel):
"""Respuesta de acción de seguridad."""
success: bool = Field(description="Si la acción fue exitosa")
message: str = Field(description="Mensaje descriptivo")
action_id: Optional[UUID4] = Field(None, description="ID de la acción registrada")
class AuditLogFilters(BaseModel):
"""
Filtros para consulta de audit logs.
@@ -84,6 +133,7 @@ class AuditLogStats(BaseModel):
total_actions: int = Field(description="Total de acciones registradas")
actions_today: int = Field(description="Acciones en las ├║ltimas 24 horas")
actions_this_week: int = Field(description="Acciones en los últimos 7 días")
critical_actions_today: int = Field(description="Acciones críticas hoy (delete, cambios sensibles)")
# Top acciones
top_actions: Dict[str, int] = Field(description="Acciones más frecuentes")

View File

@@ -19,11 +19,16 @@ from app.api.deps import get_current_user, get_current_tenant
from app.models.user import User, UserRole
from app.models.tenant import Tenant
from app.models.audit import AuditLog
from app.services.audit_service import AuditService
from app.api.schemas.audit import (
AuditLogResponse,
AuditLogListResponse,
AuditLogFilters,
AuditLogStats
AuditLogStats,
SecurityAnalysisResponse,
SecurityThreatPattern,
SecurityActionRequest,
SecurityActionResponse
)
router = APIRouter()
@@ -61,8 +66,10 @@ async def get_audit_logs(
date_from: Optional[datetime] = Query(None, description="Fecha desde"),
date_to: Optional[datetime] = Query(None, description="Fecha hasta"),
search: Optional[str] = Query(None, description="B├║squeda en acci├│n o email"),
# Dependencies
# Multi-tenant filters (solo ADMIN/SUPPORT_MANAGER)
tenant_id: Optional[uuid.UUID] = Query(None, description="Ver logs de un tenant específico"),
all_tenants: bool = Query(False, description="Ver logs de todos los tenants"),
# Dependencies
current_user: User = Depends(require_auditor_role),
current_tenant: Tenant = Depends(get_current_tenant),
db: AsyncSession = Depends(get_db)
@@ -90,17 +97,28 @@ async def get_audit_logs(
"user_id": str(user_id) if user_id else None,
"action": action,
"resource_type": resource_type,
"page": page
"page": page,
"tenant_filter": str(tenant_id) if tenant_id else None,
"all_tenants": all_tenants
}
)
# Query base - solo logs del tenant actual
# Usar selectinload para cargar la relaci├│n user (eager loading para async)
query = (
select(AuditLog)
.where(AuditLog.tenant_id == current_tenant.id)
.options(selectinload(AuditLog.user))
)
# Determinar el filtro de tenant
# Solo ADMIN y SUPPORT_MANAGER pueden ver otros tenants o todos los tenants
can_see_all_tenants = current_user.role in [UserRole.ADMIN, UserRole.SUPPORT_MANAGER]
# Query base con filtro de tenant dinámico
query = select(AuditLog).options(selectinload(AuditLog.user))
if all_tenants and can_see_all_tenants:
# Ver todos los tenants (no agregar filtro de tenant)
pass
elif tenant_id and can_see_all_tenants:
# Ver un tenant específico
query = query.where(AuditLog.tenant_id == tenant_id)
else:
# Ver solo el tenant actual (comportamiento default)
query = query.where(AuditLog.tenant_id == current_tenant.id)
# Aplicar filtros
if user_id:
@@ -119,9 +137,8 @@ async def get_audit_logs(
query = query.where(AuditLog.created_at >= date_from)
if date_to:
# Agregar 1 día para incluir todo el día
date_to_end = date_to + timedelta(days=1)
query = query.where(AuditLog.created_at < date_to_end)
# El frontend ya envía el timestamp correcto
query = query.where(AuditLog.created_at < date_to)
if search:
# B├║squeda en action
@@ -188,51 +205,57 @@ async def get_audit_logs(
@router.get("/stats", response_model=AuditLogStats)
async def get_audit_stats(
all_tenants: bool = Query(False, description="Ver stats de todos los tenants"),
current_user: User = Depends(require_auditor_role),
current_tenant: Tenant = Depends(get_current_tenant),
db: AsyncSession = Depends(get_db)
):
"""
Obtener estadísticas de auditoría del tenant.
Obtener estadísticas de auditoría del tenant (o todos los tenants si es ADMIN).
**Permisos**: ADMIN, SUPPORT_MANAGER, AUDITOR
**Retorna**: Estadísticas de actividad
**Retorna**: Estadísticas de actividad
"""
can_see_all_tenants = current_user.role in [UserRole.ADMIN, UserRole.SUPPORT_MANAGER]
logger.info(
"Fetching audit stats",
user_id=str(current_user.id),
tenant_id=str(current_tenant.id)
tenant_id=str(current_tenant.id),
all_tenants=all_tenants,
can_see_all=can_see_all_tenants
)
now = datetime.utcnow()
# Determinar si aplicar filtro de tenant
apply_tenant_filter = not (all_tenants and can_see_all_tenants)
# Total de acciones
total_query = select(func.count()).select_from(AuditLog).where(
AuditLog.tenant_id == current_tenant.id
)
total_query = select(func.count()).select_from(AuditLog)
if apply_tenant_filter:
total_query = total_query.where(AuditLog.tenant_id == current_tenant.id)
total_result = await db.execute(total_query)
total_actions = total_result.scalar() or 0
# Acciones hoy (├║ltimas 24 horas)
today_start = now - timedelta(days=1)
today_query = select(func.count()).select_from(AuditLog).where(
and_(
AuditLog.tenant_id == current_tenant.id,
AuditLog.created_at >= today_start
)
AuditLog.created_at >= today_start
)
if apply_tenant_filter:
today_query = today_query.where(AuditLog.tenant_id == current_tenant.id)
today_result = await db.execute(today_query)
actions_today = today_result.scalar() or 0
# Acciones esta semana (últimos 7 días)
week_start = now - timedelta(days=7)
week_query = select(func.count()).select_from(AuditLog).where(
and_(
AuditLog.tenant_id == current_tenant.id,
AuditLog.created_at >= week_start
)
AuditLog.created_at >= week_start
)
if apply_tenant_filter:
week_query = week_query.where(AuditLog.tenant_id == current_tenant.id)
week_result = await db.execute(week_query)
actions_this_week = week_result.scalar() or 0
@@ -240,9 +263,10 @@ async def get_audit_stats(
top_actions_query = select(
AuditLog.action,
func.count(AuditLog.id).label('count')
).where(
AuditLog.tenant_id == current_tenant.id
).group_by(
)
if apply_tenant_filter:
top_actions_query = top_actions_query.where(AuditLog.tenant_id == current_tenant.id)
top_actions_query = top_actions_query.group_by(
AuditLog.action
).order_by(
desc('count')
@@ -255,9 +279,10 @@ async def get_audit_stats(
by_resource_query = select(
AuditLog.resource_type,
func.count(AuditLog.id).label('count')
).where(
AuditLog.tenant_id == current_tenant.id
).group_by(
)
if apply_tenant_filter:
by_resource_query = by_resource_query.where(AuditLog.tenant_id == current_tenant.id)
by_resource_query = by_resource_query.group_by(
AuditLog.resource_type
).order_by(
desc('count')
@@ -266,14 +291,48 @@ async def get_audit_stats(
by_resource_result = await db.execute(by_resource_query)
by_resource_type = {row.resource_type: row.count for row in by_resource_result}
# Top usuarios (necesitamos hacer join - simplificado por ahora)
# En producción podrías hacer un join con users para obtener nombres
top_users = {} # Placeholder - implementar con join si es necesario
# Top usuarios (con join a users para obtener nombres)
top_users_query = select(
User.email,
func.count(AuditLog.id).label('count')
).join(
User, AuditLog.user_id == User.id
)
if apply_tenant_filter:
top_users_query = top_users_query.where(AuditLog.tenant_id == current_tenant.id)
top_users_query = top_users_query.group_by(
User.email
).order_by(
desc('count')
).limit(5)
top_users_result = await db.execute(top_users_query)
top_users = {row.email: row.count for row in top_users_result}
# Acciones críticas hoy (delete, update sensibles, etc.)
critical_conditions = [
AuditLog.created_at >= today_start,
or_(
AuditLog.action.like('%.delete'),
AuditLog.action.like('user.update'),
AuditLog.action.like('%.assign'),
AuditLog.action.in_(['user.login_failed', 'user.logout'])
)
]
if apply_tenant_filter:
critical_conditions.append(AuditLog.tenant_id == current_tenant.id)
critical_actions_query = select(func.count()).select_from(AuditLog).where(
and_(*critical_conditions)
)
critical_result = await db.execute(critical_actions_query)
critical_actions_today = critical_result.scalar() or 0
return AuditLogStats(
total_actions=total_actions,
actions_today=actions_today,
actions_this_week=actions_this_week,
critical_actions_today=critical_actions_today,
top_actions=top_actions,
top_users=top_users,
by_resource_type=by_resource_type
@@ -336,3 +395,321 @@ async def get_audit_log_detail(
log_dict["user_name"] = log.user.full_name
return AuditLogResponse(**log_dict)
# ===================================
# SECURITY ANALYSIS ENDPOINTS
# ===================================
@router.get("/security/analysis", response_model=SecurityAnalysisResponse)
async def get_security_analysis(
hours: int = Query(default=24, ge=1, le=168, description="Período de análisis en horas"),
current_user: User = Depends(require_auditor_role),
current_tenant: Tenant = Depends(get_current_tenant),
db: AsyncSession = Depends(get_db)
):
"""
Análisis de seguridad y detección de amenazas.
**Permisos**: ADMIN, SUPPORT_MANAGER, AUDITOR
**Detecta**:
- Intentos de fuerza bruta (login_failed)
- Escalada de privilegios
- Eliminaciones masivas
- Accesos desde IPs sospechosas
- Patrones anómalos de actividad
**Retorna**: Análisis completo con amenazas y recomendaciones
"""
logger.info(
"Security analysis requested",
user_id=str(current_user.id),
tenant_id=str(current_tenant.id),
hours=hours
)
now = datetime.utcnow()
analysis_start = now - timedelta(hours=hours)
threats = []
failed_login_attempts = 0
suspicious_ips = set()
critical_actions_count = 0
# 1. DETECCIÓN DE FUERZA BRUTA
brute_force_query = select(
AuditLog.ip_address,
func.count(AuditLog.id).label('attempts'),
func.min(AuditLog.created_at).label('first_seen'),
func.max(AuditLog.created_at).label('last_seen')
).where(
and_(
AuditLog.tenant_id == current_tenant.id,
AuditLog.action == 'user.login_failed',
AuditLog.created_at >= analysis_start
)
).group_by(AuditLog.ip_address).having(func.count(AuditLog.id) >= 5)
brute_force_result = await db.execute(brute_force_query)
brute_force_ips = brute_force_result.all()
for ip_data in brute_force_ips:
if ip_data.ip_address:
suspicious_ips.add(str(ip_data.ip_address))
failed_login_attempts += ip_data.attempts
severity = "high" if ip_data.attempts > 20 else "medium" if ip_data.attempts > 10 else "low"
threats.append(SecurityThreatPattern(
type="brute_force_attack",
severity=severity,
description=f"Ataque de fuerza bruta detectado desde {ip_data.ip_address}",
occurrences=ip_data.attempts,
affected_ips=[str(ip_data.ip_address)],
affected_users=[],
first_seen=ip_data.first_seen,
last_seen=ip_data.last_seen,
recommendations=[
f"Bloquear IP {ip_data.ip_address} temporalmente",
"Revisar logs de firewall",
"Considerar implementar CAPTCHA",
"Notificar al equipo de seguridad"
]
))
# 2. ESCALADA DE PRIVILEGIOS
privilege_query = select(
User.email,
func.count(AuditLog.id).label('changes'),
func.min(AuditLog.created_at).label('first_seen'),
func.max(AuditLog.created_at).label('last_seen')
).join(
User, AuditLog.user_id == User.id
).where(
and_(
AuditLog.tenant_id == current_tenant.id,
AuditLog.action == 'user.update',
AuditLog.created_at >= analysis_start,
AuditLog.new_values.contains('"role"')
)
).group_by(User.email).having(func.count(AuditLog.id) >= 3)
privilege_result = await db.execute(privilege_query)
privilege_changes = privilege_result.all()
for priv_data in privilege_changes:
threats.append(SecurityThreatPattern(
type="privilege_escalation",
severity="critical",
description=f"Posible escalada de privilegios - {priv_data.email} ha modificado roles {priv_data.changes} veces",
occurrences=priv_data.changes,
affected_ips=[],
affected_users=[priv_data.email],
first_seen=priv_data.first_seen,
last_seen=priv_data.last_seen,
recommendations=[
f"Revisar permisos del usuario {priv_data.email}",
"Auditar todos los cambios de roles realizados",
"Verificar si los cambios fueron autorizados",
"Considerar revertir cambios no autorizados"
]
))
# 3. ELIMINACIONES MASIVAS
deletion_query = select(
User.email,
func.count(AuditLog.id).label('deletions'),
func.min(AuditLog.created_at).label('first_seen'),
func.max(AuditLog.created_at).label('last_seen')
).join(
User, AuditLog.user_id == User.id
).where(
and_(
AuditLog.tenant_id == current_tenant.id,
AuditLog.action.like('%.delete'),
AuditLog.created_at >= analysis_start
)
).group_by(User.email).having(func.count(AuditLog.id) >= 10)
deletion_result = await db.execute(deletion_query)
mass_deletions = deletion_result.all()
for del_data in mass_deletions:
critical_actions_count += del_data.deletions
threats.append(SecurityThreatPattern(
type="mass_deletion",
severity="high",
description=f"Eliminaciones masivas detectadas - {del_data.email} ha eliminado {del_data.deletions} recursos",
occurrences=del_data.deletions,
affected_ips=[],
affected_users=[del_data.email],
first_seen=del_data.first_seen,
last_seen=del_data.last_seen,
recommendations=[
f"Verificar urgentemente las eliminaciones de {del_data.email}",
"Comprobar si hay backups disponibles",
"Contactar al usuario para verificar la acción",
"Revisar sistema de permisos"
]
))
# 4. ACCESOS DESDE MÚLTIPLES IPS (Cuenta comprometida)
multi_ip_query = select(
User.email,
func.count(func.distinct(AuditLog.ip_address)).label('ip_count'),
func.min(AuditLog.created_at).label('first_seen'),
func.max(AuditLog.created_at).label('last_seen')
).join(
User, AuditLog.user_id == User.id
).where(
and_(
AuditLog.tenant_id == current_tenant.id,
AuditLog.action.in_(['user.login', 'user.logout']),
AuditLog.created_at >= analysis_start
)
).group_by(User.email).having(func.count(func.distinct(AuditLog.ip_address)) >= 5)
multi_ip_result = await db.execute(multi_ip_query)
multi_ip_users = multi_ip_result.all()
for ip_data in multi_ip_users:
threats.append(SecurityThreatPattern(
type="account_compromise",
severity="medium",
description=f"Posible cuenta comprometida - {ip_data.email} accedió desde {ip_data.ip_count} IPs diferentes",
occurrences=ip_data.ip_count,
affected_ips=[],
affected_users=[ip_data.email],
first_seen=ip_data.first_seen,
last_seen=ip_data.last_seen,
recommendations=[
f"Contactar a {ip_data.email} para verificar actividad",
"Forzar cambio de contraseña",
"Revisar ubicaciones de acceso",
"Considerar habilitar 2FA obligatorio"
]
))
# Calcular nivel de riesgo general
critical_count = sum(1 for t in threats if t.severity == "critical")
high_count = sum(1 for t in threats if t.severity == "high")
medium_count = sum(1 for t in threats if t.severity == "medium")
if critical_count > 0:
overall_risk = "critical"
elif high_count >= 3:
overall_risk = "high"
elif high_count > 0 or medium_count >= 3:
overall_risk = "medium"
elif medium_count > 0 or len(threats) > 0:
overall_risk = "low"
else:
overall_risk = "safe"
# Recomendaciones generales
recommended_actions = []
if failed_login_attempts > 20:
recommended_actions.append("Implementar límite de intentos de login por IP")
if len(suspicious_ips) > 0:
recommended_actions.append(f"Bloquear {len(suspicious_ips)} IPs sospechosas identificadas")
if critical_actions_count > 50:
recommended_actions.append("Revisar políticas de permisos - demasiadas acciones críticas")
if len(threats) == 0:
recommended_actions.append("Sistema seguro - continuar monitoreando")
return SecurityAnalysisResponse(
overall_risk_level=overall_risk,
total_threats_detected=len(threats),
threats=threats,
analysis_period_hours=hours,
generated_at=now,
failed_login_attempts=failed_login_attempts,
suspicious_ips_count=len(suspicious_ips),
critical_actions_count=critical_actions_count,
recommended_actions=recommended_actions
)
@router.post("/security/action", response_model=SecurityActionResponse)
async def execute_security_action(
action: SecurityActionRequest,
current_user: User = Depends(require_auditor_role),
current_tenant: Tenant = Depends(get_current_tenant),
db: AsyncSession = Depends(get_db)
):
"""
Ejecutar acción de seguridad.
**Permisos**: ADMIN, SUPPORT_MANAGER (solo ellos pueden ejecutar acciones)
**Acciones disponibles**:
- `block_ip`: Bloquear IP temporalmente
- `notify_admin`: Notificar administradores
- `force_password_reset`: Forzar cambio de contraseña
- `disable_user`: Desactivar usuario temporalmente
**Retorna**: Resultado de la acción
"""
# Verificar que solo ADMIN y SUPPORT_MANAGER puedan ejecutar acciones
if current_user.role not in [UserRole.ADMIN, UserRole.SUPPORT_MANAGER]:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Solo administradores pueden ejecutar acciones de seguridad"
)
logger.info(
"Security action requested",
user_id=str(current_user.id),
action_type=action.action_type,
target=action.target
)
# Registrar la acción en auditoría
try:
await AuditService.log(
db=db,
tenant_id=current_tenant.id,
user_id=current_user.id,
action=f"security.{action.action_type}",
resource_type="security",
resource_id=None,
metadata={
"target": action.target,
"reason": action.reason,
"duration_minutes": action.duration_minutes
}
)
await db.commit()
except Exception as e:
logger.error("Failed to log security action", error=str(e))
# Por ahora, simular la ejecución (en producción conectar con firewall, email, etc.)
message = ""
success = True
if action.action_type == "block_ip":
message = f"IP {action.target} bloqueada por {action.duration_minutes or 60} minutos. Razón: {action.reason}"
# TODO: Integrar con firewall/WAF
elif action.action_type == "notify_admin":
message = f"Notificación enviada a administradores sobre: {action.reason}"
# TODO: Enviar email/Slack notification
elif action.action_type == "force_password_reset":
message = f"Se forzará cambio de contraseña para {action.target}. Razón: {action.reason}"
# TODO: Marcar usuario para reset password
elif action.action_type == "disable_user":
message = f"Usuario {action.target} desactivado temporalmente. Razón: {action.reason}"
# TODO: Desactivar usuario en BD
else:
success = False
message = f"Tipo de acción no reconocida: {action.action_type}"
return SecurityActionResponse(
success=success,
message=message,
action_id=None # TODO: Retornar ID del audit log creado
)

View File

@@ -18,6 +18,7 @@ from app.core.security import security
from app.core.config import get_settings
from app.models.user import User
from app.models.tenant import Tenant
from app.services.audit_service import AuditService
router = APIRouter()
logger = structlog.get_logger(__name__)
@@ -99,6 +100,23 @@ async def login(
"Login failed - invalid credentials",
email=login_data.email
)
# Registrar intento fallido en auditoría (si el usuario existe)
if user:
try:
await AuditService.log(
db=db,
tenant_id=user.tenant_id,
user_id=None, # Login fallido = sin user_id
action="user.login_failed",
resource_type="user",
resource_id=user.id,
metadata={"email": login_data.email, "reason": "invalid_password"}
)
await db.commit()
except Exception as e:
logger.warning("Failed to log audit entry", error=str(e))
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Credenciales inválidas"
@@ -126,6 +144,21 @@ async def login(
access_token = security.create_access_token(token_data)
refresh_token = security.create_refresh_token(token_data)
# Registrar login exitoso en auditoría
try:
await AuditService.log(
db=db,
tenant_id=user.tenant_id,
user_id=user.id,
action="user.login",
resource_type="user",
resource_id=user.id,
metadata={"email": user.email, "success": True}
)
await db.commit()
except Exception as e:
logger.warning("Failed to log audit entry", error=str(e))
logger.info(
"Login successful",
email=login_data.email,
@@ -227,6 +260,25 @@ async def logout(
# TODO: Revoke refresh token in database
# Registrar logout en auditoría
try:
import uuid
user_id = uuid.UUID(payload["sub"])
tenant_id = uuid.UUID(payload["tenant_id"])
await AuditService.log(
db=db,
tenant_id=tenant_id,
user_id=user_id,
action="user.logout",
resource_type="user",
resource_id=user_id,
metadata={"email": payload.get("email")}
)
await db.commit()
except Exception as e:
logger.warning("Failed to log audit entry", error=str(e))
logger.info("Logout successful", user_id=payload["sub"])
return {"message": "Successfully logged out"}

View File

@@ -21,6 +21,7 @@ from app.models.comment import TicketComment
from app.models.attachment import TicketAttachment
from app.api.schemas.attachment import AttachmentResponse
from app.core.file_handler import file_handler
from app.services.audit_service import AuditService
import uuid
router = APIRouter()
@@ -143,6 +144,27 @@ async def create_ticket(
await db.commit()
await db.refresh(db_ticket)
# Registrar creación en auditoría
try:
await AuditService.log(
db=db,
tenant_id=current_user.tenant_id,
user_id=current_user.id,
action="ticket.create",
resource_type="ticket",
resource_id=db_ticket.id,
new_values={
"ticket_number": db_ticket.ticket_number,
"subject": db_ticket.subject,
"priority": db_ticket.priority.value,
"status": db_ticket.status.value
}
)
await db.commit()
except Exception as e:
# No fallar si falla el audit log
pass
# ✅ Éxito - retornar ticket creado
return {
"id": str(db_ticket.id),
@@ -501,6 +523,15 @@ async def update_ticket(
detail=f"Ticket {ticket_id} not found"
)
# Guardar valores anteriores para audit
old_values = {
"subject": db_ticket.subject,
"description": db_ticket.description,
"status": db_ticket.status.value,
"priority": db_ticket.priority.value,
"assigned_to": str(db_ticket.assigned_to) if db_ticket.assigned_to else None
}
try:
update_data = ticket_update.dict(exclude_unset=True)
@@ -519,6 +550,34 @@ async def update_ticket(
await db.commit()
await db.refresh(db_ticket)
# Registrar actualización en auditoría
try:
new_values = {
"subject": db_ticket.subject,
"description": db_ticket.description,
"status": db_ticket.status.value,
"priority": db_ticket.priority.value,
"assigned_to": str(db_ticket.assigned_to) if db_ticket.assigned_to else None
}
# Si cambió assigned_to, registrar como acción de asignación
action = "ticket.assign" if old_values["assigned_to"] != new_values["assigned_to"] else "ticket.update"
await AuditService.log(
db=db,
tenant_id=current_user.tenant_id,
user_id=current_user.id,
action=action,
resource_type="ticket",
resource_id=db_ticket.id,
old_values=old_values,
new_values=new_values
)
await db.commit()
except Exception as e:
# No fallar si falla el audit log
pass
# ✅ CORREGIDO: Usar affected_system_id
return {
"id": str(db_ticket.id),
@@ -787,9 +846,33 @@ async def delete_ticket(
detail=f"Ticket {ticket_id} not found"
)
# Guardar datos del ticket antes de eliminar para audit
old_values = {
"ticket_number": db_ticket.ticket_number,
"subject": db_ticket.subject,
"status": db_ticket.status.value,
"priority": db_ticket.priority.value
}
await db.delete(db_ticket)
await db.commit()
# Registrar eliminación en auditoría
try:
await AuditService.log(
db=db,
tenant_id=current_user.tenant_id,
user_id=current_user.id,
action="ticket.delete",
resource_type="ticket",
resource_id=ticket_uuid,
old_values=old_values
)
await db.commit()
except Exception as e:
# No fallar si falla el audit log
pass
return {"message": "Ticket deleted successfully"}
# ===================================

View File

@@ -9,6 +9,7 @@ import uuid
from app.core.database import get_db
from app.core.security import security
from app.models.user import User, UserRole
from app.services.audit_service import AuditService
from app.api import deps
router = APIRouter()
@@ -147,6 +148,28 @@ async def create_user(
db.add(db_user)
await db.commit()
await db.refresh(db_user)
# Registrar creación en auditoría
try:
await AuditService.log(
db=db,
tenant_id=current_user.tenant_id,
user_id=current_user.id,
action="user.create",
resource_type="user",
resource_id=db_user.id,
new_values=AuditService.sanitize_values({
"email": db_user.email,
"first_name": db_user.first_name,
"last_name": db_user.last_name,
"role": db_user.role.value
})
)
await db.commit()
except Exception as e:
# No fallar si falla el audit log
pass
return db_user
@@ -214,6 +237,15 @@ async def update_user(
detail="User not found"
)
# Guardar valores anteriores para audit
old_values = {
"email": db_user.email,
"first_name": db_user.first_name,
"last_name": db_user.last_name,
"role": db_user.role.value,
"is_active": db_user.is_active
}
# Verificar email único si se está cambiando
update_data = user_update.model_dump(exclude_unset=True)
if "email" in update_data and update_data["email"] != db_user.email:
@@ -239,6 +271,32 @@ async def update_user(
await db.commit()
await db.refresh(db_user)
# Registrar actualización en auditoría
try:
new_values = {
"email": db_user.email,
"first_name": db_user.first_name,
"last_name": db_user.last_name,
"role": db_user.role.value,
"is_active": db_user.is_active
}
await AuditService.log(
db=db,
tenant_id=current_user.tenant_id,
user_id=current_user.id,
action="user.update",
resource_type="user",
resource_id=db_user.id,
old_values=AuditService.sanitize_values(old_values),
new_values=AuditService.sanitize_values(new_values)
)
await db.commit()
except Exception as e:
# No fallar si falla el audit log
pass
return db_user
@@ -306,6 +364,28 @@ async def delete_user(
# Soft delete
db_user.is_active = False
await db.commit()
# Registrar eliminación en auditoría
try:
await AuditService.log(
db=db,
tenant_id=current_user.tenant_id,
user_id=current_user.id,
action="user.delete",
resource_type="user",
resource_id=db_user.id,
old_values={
"email": db_user.email,
"role": db_user.role.value,
"was_active": True
},
metadata={"action_type": "soft_delete"}
)
await db.commit()
except Exception as e:
# No fallar si falla el audit log
pass
return None

View File

@@ -27,6 +27,7 @@ class Settings(BaseSettings):
DEBUG: bool = Field(default=False)
SECRET_KEY: str = Field(...)
API_VERSION: str = Field(default="v1")
APP_VERSION: str = Field(default="1.6.0")
# ===================================
# DATABASE

View File

@@ -56,7 +56,7 @@ async def lifespan(app: FastAPI):
app = FastAPI(
title="ServiceManagerWeb API",
description="Mesa de Ayuda B2B multi-tenant para Aduanasoft",
version=settings.API_VERSION,
version=settings.APP_VERSION,
lifespan=lifespan,
docs_url=f"/{settings.API_VERSION}/docs" if settings.ENVIRONMENT == "development" else None,
redoc_url=f"/{settings.API_VERSION}/redoc" if settings.ENVIRONMENT == "development" else None,
@@ -163,7 +163,8 @@ async def health_check():
return {
"status": "healthy",
"service": "ServiceManagerWeb API",
"version": settings.API_VERSION,
"version": settings.APP_VERSION,
"api_version": settings.API_VERSION,
"environment": settings.ENVIRONMENT
}
@@ -174,7 +175,8 @@ async def root():
"""Endpoint raíz con información básica."""
return {
"service": "ServiceManagerWeb API",
"version": settings.API_VERSION,
"version": settings.APP_VERSION,
"api_version": settings.API_VERSION,
"docs": f"/{settings.API_VERSION}/docs",
"environment": settings.ENVIRONMENT
}

View File

@@ -0,0 +1,67 @@
"""
Script para crear/actualizar usuario de prueba con contraseña conocida
"""
import asyncio
from sqlalchemy import select, update
from app.core.database import AsyncSessionLocal
from app.core.security import security
from app.models.user import User, UserRole
from app.models.tenant import Tenant
import uuid
async def create_test_user():
async with AsyncSessionLocal() as db:
# Buscar tenant
tenant_query = select(Tenant).where(Tenant.slug.like('%aduanasoft%')).limit(1)
result = await db.execute(tenant_query)
tenant = result.scalar_one_or_none()
if not tenant:
print("❌ No se encontró tenant")
return
print(f"✅ Tenant encontrado: {tenant.name} ({tenant.slug})")
# Buscar o crear usuario admin
user_query = select(User).where(
User.email == "admin@aduanasoft.com",
User.tenant_id == tenant.id
)
result = await db.execute(user_query)
user = result.scalar_one_or_none()
# Hash de la contraseña "admin123"
password_hash = security.hash_password("admin123")
if user:
# Actualizar contraseña
user.password_hash = password_hash
user.is_active = True
user.email_verified = True
await db.commit()
print(f"✅ Usuario actualizado: {user.email}")
else:
# Crear usuario nuevo
user = User(
id=uuid.uuid4(),
tenant_id=tenant.id,
email="admin@aduanasoft.com",
first_name="Admin",
last_name="Sistema",
password_hash=password_hash,
role=UserRole.ADMIN,
is_active=True,
email_verified=True
)
db.add(user)
await db.commit()
print(f"✅ Usuario creado: {user.email}")
print(f"\n📋 Credenciales de prueba:")
print(f" Email: admin@aduanasoft.com")
print(f" Password: admin123")
print(f" Tenant: {tenant.slug}")
print(f" Role: ADMIN")
if __name__ == "__main__":
asyncio.run(create_test_user())

View File

@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "servicemanager-backend"
version = "1.5.1.2"
version = "1.6.0"
description = "ServiceManagerWeb Backend - Mesa de Ayuda B2B"
authors = [
{name = "Aduanasoft", email = "dev@aduanasoft.com"}

View File

@@ -369,10 +369,14 @@ CREATE TABLE audit_logs (
CREATE INDEX idx_audit_logs_tenant_id ON audit_logs(tenant_id);
CREATE INDEX idx_audit_logs_user_id ON audit_logs(user_id);
CREATE INDEX idx_audit_logs_action ON audit_logs(action);
CREATE INDEX idx_audit_logs_resource ON audit_logs(resource_type, resource_id);
CREATE INDEX idx_audit_logs_correlation_id ON audit_logs(correlation_id);
CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at);
-- Índices compuestos para queries comunes de auditoría
CREATE INDEX idx_audit_logs_tenant_action ON audit_logs(tenant_id, action);
CREATE INDEX idx_audit_logs_resource ON audit_logs(resource_type, resource_id);
CREATE INDEX idx_audit_logs_user_created ON audit_logs(user_id, created_at);
-- ===================================
-- FUNCIONES Y TRIGGERS
-- ===================================

View File

@@ -1,6 +1,6 @@
{
"name": "@servicemanager/client-frontend",
"version": "1.5.1.2",
"version": "1.6.0",
"private": true,
"type": "module",
"scripts": {

View File

@@ -23,6 +23,11 @@
<slot />
</main>
<!-- Footer with version -->
<footer class="py-4 text-center border-t border-gray-200 bg-white">
<p class="text-xs text-gray-400">ServiceManagerWeb v1.6.0 · © 2026 Aduanasoft</p>
</footer>
<!-- Toast notifications -->
{#each $toast.toasts as toastMessage (toastMessage.id)}
<Toast

View File

@@ -1,6 +1,6 @@
{
"name": "@servicemanager/internal-frontend",
"version": "1.5.1.2",
"version": "1.6.0",
"private": true,
"type": "module",
"scripts": {

View File

@@ -1,8 +1,9 @@
<script>
import { createEventDispatcher, onMount, onDestroy } from 'svelte';
import { createEventDispatcher } from 'svelte';
export let open = false;
export let title = '';
export let size = 'lg'; // sm, md, lg, xl, 2xl
const dispatch = createEventDispatcher();
@@ -15,6 +16,20 @@
close();
}
}
function handleBackdropClick(e) {
if (e.target === e.currentTarget) {
close();
}
}
const sizeClasses = {
sm: 'sm:max-w-sm',
md: 'sm:max-w-md',
lg: 'sm:max-w-lg',
xl: 'sm:max-w-xl',
'2xl': 'sm:max-w-2xl'
};
</script>
<svelte:window on:keydown={handleKeydown}/>
@@ -23,21 +38,45 @@
<div class="fixed inset-0 z-50 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
<div class="flex items-end justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
<div class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75" aria-hidden="true" on:click={close}></div>
<!-- Backdrop -->
<div
class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
aria-hidden="true"
on:click={handleBackdropClick}
></div>
<!-- Center trick -->
<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
<div class="inline-block px-4 pt-5 pb-4 overflow-hidden text-left align-bottom transition-all transform bg-white rounded-lg shadow-xl sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
<div class="sm:flex sm:items-start">
<div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
<h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
{title}
</h3>
<div class="mt-2 text-sm text-gray-500">
<slot />
</div>
</div>
<!-- Modal panel -->
<div class="inline-block w-full align-bottom bg-white rounded-lg shadow-xl transform transition-all sm:my-8 sm:align-middle {sizeClasses[size]} sm:w-full">
<!-- Header -->
<div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
<h3 class="text-lg font-semibold text-gray-900" id="modal-title">
{title}
</h3>
<button
type="button"
on:click={close}
class="text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-500 rounded-lg p-1"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<!-- Body -->
<div class="px-6 py-4 max-h-[70vh] overflow-y-auto">
<slot />
</div>
<!-- Footer (optional) -->
{#if $$slots.footer}
<div class="px-6 py-4 bg-gray-50 border-t border-gray-200 rounded-b-lg">
<slot name="footer" />
</div>
{/if}
</div>
</div>
</div>

View File

@@ -62,6 +62,11 @@
name: 'Auditoría',
href: '/audit',
icon: 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z'
},
{
name: 'Seguridad',
href: '/audit/security',
icon: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z'
}
);
}
@@ -178,5 +183,10 @@
</div>
</div>
</div>
<!-- Version info -->
<div class="px-4 py-2 border-t border-gray-100">
<p class="text-xs text-gray-400 text-center">v1.6.0</p>
</div>
</div>
</div>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,532 @@
<script lang="ts">
import { onMount } from 'svelte';
import { api } from '$lib/utils/api';
import { toast } from '$lib/stores/toast';
import { auth } from '$lib/stores/auth';
import Modal from '$lib/components/Modal.svelte';
// Estado
let isLoading = false;
let analysis = null;
let analysisHours = 24;
let selectedThreat = null;
let showActionModal = false;
let actionType = '';
let actionTarget = '';
let actionReason = '';
let actionDuration = 60;
// Usuario actual
$: currentUser = $auth.user;
$: canExecuteActions = currentUser && (currentUser.role === 'ADMIN' || currentUser.role === 'SUPPORT_MANAGER');
/**
* Cargar análisis de seguridad
*/
async function loadSecurityAnalysis() {
isLoading = true;
try {
analysis = await api.get('/audit/security/analysis', { hours: analysisHours });
console.log('Security analysis loaded:', analysis);
} catch (e: any) {
toast.error('Error cargando análisis de seguridad: ' + (e.message || 'Error desconocido'));
} finally {
isLoading = false;
}
}
/**
* Cambiar período de análisis
*/
function changeAnalysisPeriod(hours: number) {
analysisHours = hours;
loadSecurityAnalysis();
}
/**
* Obtener color según nivel de riesgo
*/
function getRiskColor(level: string) {
const colors: any = {
safe: 'bg-green-100 text-green-800 border-green-300',
low: 'bg-blue-100 text-blue-800 border-blue-300',
medium: 'bg-yellow-100 text-yellow-800 border-yellow-300',
high: 'bg-orange-100 text-orange-800 border-orange-300',
critical: 'bg-red-100 text-red-800 border-red-300'
};
return colors[level] || colors.low;
}
/**
* Obtener color de severidad de amenaza
*/
function getSeverityColor(severity: string) {
const colors: any = {
low: 'bg-blue-100 text-blue-800',
medium: 'bg-yellow-100 text-yellow-800',
high: 'bg-orange-100 text-orange-800',
critical: 'bg-red-100 text-red-800'
};
return colors[severity] || colors.low;
}
/**
* Obtener icono de tipo de amenaza
*/
function getThreatIcon(type: string) {
const icons: any = {
brute_force_attack: 'M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z',
privilege_escalation: 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z',
mass_deletion: 'M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16',
account_compromise: 'M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z'
};
return icons[type] || icons.account_compromise;
}
/**
* Obtener texto legible del tipo de amenaza
*/
function getThreatTypeText(type: string) {
const texts: any = {
brute_force_attack: 'Ataque de Fuerza Bruta',
privilege_escalation: 'Escalada de Privilegios',
mass_deletion: 'Eliminación Masiva',
account_compromise: 'Cuenta Comprometida'
};
return texts[type] || type;
}
/**
* Abrir modal para acción de seguridad
*/
function openActionModal(threat: any, action: string) {
if (!canExecuteActions) {
toast.error('No tienes permisos para ejecutar acciones de seguridad');
return;
}
selectedThreat = threat;
actionType = action;
// Pre-llenar campos según el tipo de acción
if (action === 'block_ip' && threat.affected_ips.length > 0) {
actionTarget = threat.affected_ips[0];
actionReason = `Bloqueo automático: ${threat.description}`;
} else if (action === 'force_password_reset' && threat.affected_users.length > 0) {
actionTarget = threat.affected_users[0];
actionReason = `Reseteo de seguridad: ${threat.description}`;
} else {
actionTarget = '';
actionReason = threat.description;
}
showActionModal = true;
}
/**
* Ejecutar acción de seguridad
*/
async function executeSecurityAction() {
if (!actionTarget || !actionReason) {
toast.error('Completa todos los campos requeridos');
return;
}
try {
const response = await api.post('/audit/security/action', {
action_type: actionType,
target: actionTarget,
reason: actionReason,
duration_minutes: actionDuration
});
if (response.success) {
toast.success(response.message);
showActionModal = false;
loadSecurityAnalysis(); // Recargar análisis
} else {
toast.error(response.message);
}
} catch (e: any) {
toast.error('Error ejecutando acción: ' + (e.message || 'Error desconocido'));
}
}
/**
* Formatear fecha
*/
function formatDate(dateString: string) {
const date = new Date(dateString);
return new Intl.DateTimeFormat('es-MX', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
timeZone: 'UTC',
timeZoneName: 'short'
}).format(date);
}
onMount(() => {
loadSecurityAnalysis();
});
</script>
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
<!-- Header -->
<div class="mb-6">
<div class="flex items-center justify-between">
<div>
<h1 class="text-2xl font-bold text-gray-900 flex items-center gap-2">
<svg class="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
Análisis de Seguridad
</h1>
<p class="mt-1 text-sm text-gray-500">
Detección de amenazas y análisis de vulnerabilidades
</p>
</div>
<button
on:click={() => loadSecurityAnalysis()}
class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-primary-500 flex items-center gap-2"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
Actualizar
</button>
</div>
</div>
<!-- Selector de Período -->
<div class="bg-white shadow rounded-lg p-4 mb-6">
<div class="flex items-center gap-2 mb-2">
<svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span class="text-sm font-medium text-gray-700">Período de Análisis</span>
</div>
<div class="flex flex-wrap gap-2">
<button
on:click={() => changeAnalysisPeriod(24)}
class="px-4 py-2 rounded-lg text-sm font-medium transition-colors {analysisHours === 24 ? 'bg-primary-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}"
>
Últimas 24 horas
</button>
<button
on:click={() => changeAnalysisPeriod(48)}
class="px-4 py-2 rounded-lg text-sm font-medium transition-colors {analysisHours === 48 ? 'bg-primary-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}"
>
Últimas 48 horas
</button>
<button
on:click={() => changeAnalysisPeriod(168)}
class="px-4 py-2 rounded-lg text-sm font-medium transition-colors {analysisHours === 168 ? 'bg-primary-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}"
>
Última semana
</button>
</div>
</div>
{#if isLoading}
<div class="flex justify-center items-center py-12">
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
</div>
{:else if analysis}
<!-- Resumen de Riesgo -->
<div class="bg-white shadow rounded-lg p-6 mb-6 border-l-4 {getRiskColor(analysis.overall_risk_level)}">
<div class="flex items-center justify-between">
<div>
<h3 class="text-lg font-semibold text-gray-900">Nivel de Riesgo General</h3>
<p class="text-sm text-gray-600 mt-1">Análisis de {analysis.analysis_period_hours} horas</p>
</div>
<div class="text-right">
<span class="inline-block px-4 py-2 text-2xl font-bold rounded-lg {getRiskColor(analysis.overall_risk_level)}">
{analysis.overall_risk_level.toUpperCase()}
</span>
<p class="text-xs text-gray-500 mt-1">Generado: {formatDate(analysis.generated_at)}</p>
</div>
</div>
</div>
<!-- Estadísticas Rápidas -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<div class="bg-white rounded-lg shadow p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-gray-500">Amenazas Detectadas</p>
<p class="text-2xl font-bold text-red-600">{analysis.total_threats_detected}</p>
</div>
<svg class="w-10 h-10 text-red-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
</div>
</div>
<div class="bg-white rounded-lg shadow p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-gray-500">Intentos Fallidos</p>
<p class="text-2xl font-bold text-orange-600">{analysis.failed_login_attempts}</p>
</div>
<svg class="w-10 h-10 text-orange-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
</div>
</div>
<div class="bg-white rounded-lg shadow p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-gray-500">IPs Sospechosas</p>
<p class="text-2xl font-bold text-purple-600">{analysis.suspicious_ips_count}</p>
</div>
<svg class="w-10 h-10 text-purple-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
</svg>
</div>
</div>
<div class="bg-white rounded-lg shadow p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm text-gray-500">Acciones Críticas</p>
<p class="text-2xl font-bold text-amber-600">{analysis.critical_actions_count}</p>
</div>
<svg class="w-10 h-10 text-amber-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
</svg>
</div>
</div>
</div>
<!-- Recomendaciones Generales -->
{#if analysis.recommended_actions && analysis.recommended_actions.length > 0}
<div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
<div class="flex items-start gap-3">
<svg class="w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<div class="flex-1">
<h4 class="text-sm font-semibold text-blue-900 mb-2">Acciones Recomendadas</h4>
<ul class="space-y-1">
{#each analysis.recommended_actions as action}
<li class="text-sm text-blue-800 flex items-start gap-2">
<svg class="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
{action}
</li>
{/each}
</ul>
</div>
</div>
</div>
{/if}
<!-- Lista de Amenazas -->
{#if analysis.threats && analysis.threats.length > 0}
<div class="space-y-4">
<h3 class="text-lg font-semibold text-gray-900">Amenazas Detectadas</h3>
{#each analysis.threats as threat}
<div class="bg-white shadow rounded-lg p-6 border-l-4 {threat.severity === 'critical' ? 'border-red-500' : threat.severity === 'high' ? 'border-orange-500' : threat.severity === 'medium' ? 'border-yellow-500' : 'border-blue-500'}">
<!-- Header de Amenaza -->
<div class="flex items-start justify-between mb-4">
<div class="flex items-start gap-3 flex-1">
<div class="p-2 rounded-lg {threat.severity === 'critical' ? 'bg-red-100' : threat.severity === 'high' ? 'bg-orange-100' : threat.severity === 'medium' ? 'bg-yellow-100' : 'bg-blue-100'}">
<svg class="w-6 h-6 {threat.severity === 'critical' ? 'text-red-600' : threat.severity === 'high' ? 'text-orange-600' : threat.severity === 'medium' ? 'text-yellow-600' : 'text-blue-600'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d={getThreatIcon(threat.type)} />
</svg>
</div>
<div class="flex-1">
<div class="flex items-center gap-2 mb-1">
<h4 class="text-lg font-semibold text-gray-900">{getThreatTypeText(threat.type)}</h4>
<span class="px-2 py-1 text-xs font-semibold rounded-full {getSeverityColor(threat.severity)}">
{threat.severity.toUpperCase()}
</span>
</div>
<p class="text-sm text-gray-700">{threat.description}</p>
</div>
</div>
</div>
<!-- Detalles -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4 text-sm">
<div>
<span class="font-medium text-gray-600">Ocurrencias:</span>
<span class="ml-2 text-gray-900 font-semibold">{threat.occurrences}</span>
</div>
<div>
<span class="font-medium text-gray-600">Primera detección:</span>
<span class="ml-2 text-gray-900">{formatDate(threat.first_seen)}</span>
</div>
<div>
<span class="font-medium text-gray-600">Última detección:</span>
<span class="ml-2 text-gray-900">{formatDate(threat.last_seen)}</span>
</div>
</div>
<!-- IPs y Usuarios Afectados -->
{#if threat.affected_ips.length > 0 || threat.affected_users.length > 0}
<div class="mb-4 text-sm">
{#if threat.affected_ips.length > 0}
<div class="mb-2">
<span class="font-medium text-gray-600">IPs involucradas:</span>
<div class="mt-1 flex flex-wrap gap-1">
{#each threat.affected_ips as ip}
<code class="px-2 py-1 bg-gray-100 rounded text-xs font-mono">{ip}</code>
{/each}
</div>
</div>
{/if}
{#if threat.affected_users.length > 0}
<div>
<span class="font-medium text-gray-600">Usuarios afectados:</span>
<div class="mt-1 flex flex-wrap gap-1">
{#each threat.affected_users as user}
<span class="px-2 py-1 bg-gray-100 rounded text-xs">{user}</span>
{/each}
</div>
</div>
{/if}
</div>
{/if}
<!-- Recomendaciones -->
{#if threat.recommendations && threat.recommendations.length > 0}
<div class="bg-gray-50 rounded-lg p-3 mb-4">
<p class="text-xs font-semibold text-gray-700 mb-2">Recomendaciones:</p>
<ul class="space-y-1">
{#each threat.recommendations as rec}
<li class="text-xs text-gray-600 flex items-start gap-2">
<svg class="w-3 h-3 text-gray-400 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
{rec}
</li>
{/each}
</ul>
</div>
{/if}
<!-- Acciones -->
{#if canExecuteActions}
<div class="flex flex-wrap gap-2">
{#if threat.affected_ips.length > 0}
<button
on:click={() => openActionModal(threat, 'block_ip')}
class="px-3 py-1.5 bg-red-600 text-white text-sm rounded hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 flex items-center gap-1"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
</svg>
Bloquear IP
</button>
{/if}
{#if threat.affected_users.length > 0}
<button
on:click={() => openActionModal(threat, 'force_password_reset')}
class="px-3 py-1.5 bg-orange-600 text-white text-sm rounded hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-orange-500 flex items-center gap-1"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
</svg>
Resetear Contraseña
</button>
{/if}
<button
on:click={() => openActionModal(threat, 'notify_admin')}
class="px-3 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center gap-1"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
</svg>
Notificar Admin
</button>
</div>
{/if}
</div>
{/each}
</div>
{:else}
<!-- No hay amenazas -->
<div class="bg-green-50 border border-green-200 rounded-lg p-8 text-center">
<svg class="w-16 h-16 text-green-600 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
</svg>
<h3 class="text-lg font-semibold text-green-900 mb-2">Sistema Seguro</h3>
<p class="text-sm text-green-700">No se detectaron amenazas en el período analizado</p>
</div>
{/if}
{/if}
</div>
<!-- Modal de Acción de Seguridad -->
{#if showActionModal}
<Modal open={showActionModal} size="lg" title="Ejecutar Acción de Seguridad" on:close={() => showActionModal = false}>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Tipo de Acción</label>
<input
type="text"
bind:value={actionType}
readonly
class="block w-full rounded-md border-gray-300 bg-gray-50 shadow-sm sm:text-sm"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
Objetivo {#if actionType === 'block_ip'}(IP){:else if actionType === 'force_password_reset'}(Email){/if}
</label>
<input
type="text"
bind:value={actionTarget}
placeholder="IP o email del usuario"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Razón</label>
<textarea
bind:value={actionReason}
rows="3"
placeholder="Razón de la acción de seguridad"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
></textarea>
</div>
{#if actionType === 'block_ip'}
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Duración del Bloqueo (minutos)</label>
<input
type="number"
bind:value={actionDuration}
min="1"
max="10080"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
/>
</div>
{/if}
<div class="flex justify-end gap-3 pt-4 border-t">
<button
on:click={() => showActionModal = false}
class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-primary-500"
>
Cancelar
</button>
<button
on:click={executeSecurityAction}
class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500"
>
Ejecutar Acción
</button>
</div>
</div>
</Modal>
{/if}