Просмотр исходного кода

feat: implement core real-time notification system

- Add Socket.IO integration for real-time notifications
- Create comprehensive notification service with multiple types
- Implement background notification monitor with health checks
- Add security monitoring functions (suspicious activity, auth attempts)
- Enhance API with notification endpoints and mark-as-read functionality
Yoelvis Mariné Ramos 1 год назад
Родитель
Сommit
bfd8bc3448
4 измененных файлов с 480 добавлено и 22 удалено
  1. 11 4
      app.py
  2. 21 1
      routes/api_routes.py
  3. 149 12
      services/auditoria_service.py
  4. 299 5
      services/notifications.py

+ 11 - 4
app.py

@@ -5,17 +5,18 @@ from flask import Flask
 from flask_apscheduler import APScheduler
 from flask_socketio import SocketIO
 from flask_wtf.csrf import CSRFProtect
-
 from config import Config, logger
 from database.database import migrate_database
 from parsers.log import process_logs
 from routes import register_routes
-from routes.main_routes import initialize_proxy_detection
+# from routes.main_routes import initialize_proxy_detection
 from routes.stats_routes import realtime_data_thread
 from services.metrics_service import MetricsService
 from services.notifications import (
     has_remote_commits_with_messages,
     set_commit_notifications,
+    set_socketio_instance,  # Nueva importación
+    start_notification_monitor,  # Nueva importación
 )
 from utils.filters import register_filters
 
@@ -51,7 +52,7 @@ def create_app():
     register_routes(app)
 
     # Initialize proxy detection
-    initialize_proxy_detection()
+#    initialize_proxy_detection()
 
     # Configure response headers
     @app.after_request
@@ -106,6 +107,12 @@ def main():
     # Initialize SocketIO
     socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
 
+    # Configurar Socket.IO en el módulo de notificaciones
+    set_socketio_instance(socketio)
+
+    # Iniciar el monitor de notificaciones
+    start_notification_monitor()
+
     # Start real-time data collection thread
     socketio.start_background_task(realtime_data_thread, socketio)
 
@@ -130,4 +137,4 @@ def main():
 
 
 if __name__ == "__main__":
-    main()
+    main()

+ 21 - 1
routes/api_routes.py

@@ -1,4 +1,5 @@
 from flask import Blueprint, current_app, jsonify, request
+from services.notifications import get_all_notifications, mark_notifications_read
 
 from config import logger
 from database.database import get_session
@@ -144,4 +145,23 @@ def api_run_audit():
 # API para notificaciones del sistema
 @api_bp.route("/notifications", methods=["GET"])
 def api_get_notifications():
-    return jsonify(get_commit_notifications())
+    try:
+        return jsonify(get_all_notifications(limit=10))
+    except Exception as e:
+        logger.error(f"Error getting notifications: {e}")
+        return jsonify({'unread_count': 0, 'notifications': []})
+
+
+@api_bp.route("/notifications/mark-read", methods=["POST"])
+def api_mark_notifications_read():
+    try:
+        data = request.get_json()
+        notification_ids = data.get('ids', [])
+        mark_notifications_read(notification_ids)
+        return jsonify({
+            'success': True, 
+            'unread_count': get_all_notifications()['unread_count']
+        })
+    except Exception as e:
+        logger.error(f"Error marking notifications as read: {e}")
+        return jsonify({'success': False}), 500

+ 149 - 12
services/auditoria_service.py

@@ -26,7 +26,6 @@ def _get_tables_in_range(
         current_date += timedelta(days=1)
     return log_tables_in_range
 
-
 def find_by_keyword(
     db: Session, start_str: str, end_str: str, keyword: str, username: str = None
 ) -> dict[str, Any]:
@@ -101,7 +100,6 @@ def find_by_keyword(
 
     return {"results": all_results}
 
-
 def find_social_media_activity(
     db: Session, start_str: str, end_str: str, sites: list[str], username: str = None
 ) -> dict[str, Any]:
@@ -197,7 +195,6 @@ def find_social_media_activity(
 
     return {"results": all_results}
 
-
 def find_by_ip(
     db: Session, start_str: str, end_str: str, ip_address: str
 ) -> dict[str, Any]:
@@ -268,7 +265,6 @@ def find_by_ip(
 
     return {"results": all_results}
 
-
 def find_by_response_code(
     db: Session, start_str: str, end_str: str, code: int, username: str = None
 ) -> dict[str, Any]:
@@ -346,7 +342,6 @@ def find_by_response_code(
 
     return {"results": all_results}
 
-
 def get_daily_activity(db: Session, date_str: str, username: str) -> dict[str, Any]:
     try:
         selected_date = datetime.strptime(date_str, "%Y-%m-%d")
@@ -402,7 +397,6 @@ def get_daily_activity(db: Session, date_str: str, username: str) -> dict[str, A
             "error": "An unexpected error occurred while calculating daily activity."
         }
 
-
 def get_all_usernames(db: Session) -> list[str]:
     engine = db.get_bind()
     inspector = inspect(engine)
@@ -441,7 +435,6 @@ def get_all_usernames(db: Session) -> list[str]:
 
     return sorted(all_usernames)
 
-
 def get_user_activity_summary(
     db: Session, username: str, start_str: str, end_str: str
 ) -> dict[str, Any]:
@@ -521,7 +514,6 @@ def get_user_activity_summary(
         ],
     }
 
-
 def get_top_users_by_data(
     db: Session, start_str: str, end_str: str, limit: int = 10
 ) -> dict[str, Any]:
@@ -568,7 +560,6 @@ def get_top_users_by_data(
 
     return {"top_users": top_users_list}
 
-
 def get_top_users_by_requests(
     db: Session, start_str: str, end_str: str, limit: int = 10
 ) -> dict[str, Any]:
@@ -612,7 +603,6 @@ def get_top_users_by_requests(
         ]
     }
 
-
 def get_top_urls_by_data(
     db: Session, start_str: str, end_str: str, limit: int = 15
 ) -> dict[str, Any]:
@@ -657,7 +647,6 @@ def get_top_urls_by_data(
 
     return {"top_urls": top_urls_list}
 
-
 def get_top_ips_by_data(
     db: Session, start_str: str, end_str: str, limit: int = 10
 ) -> dict[str, Any]:
@@ -703,7 +692,6 @@ def get_top_ips_by_data(
         ]
     }
 
-
 def find_denied_access(
     db: Session, start_str: str, end_str: str, username: str = None
 ) -> dict[str, Any]:
@@ -765,3 +753,152 @@ def find_denied_access(
     all_results.sort(key=lambda x: (x["log_date"], x["username"]), reverse=True)
 
     return {"results": all_results}
+
+def find_suspicious_activity(db, threshold=50, hours=1):
+    """
+    Encuentra IPs con actividad sospechosa (muchos requests en poco tiempo)
+    Retorna: lista de tuplas [(ip, count), ...]
+    """
+    from sqlalchemy import text
+    from datetime import datetime, timedelta
+    
+    try:
+        since_time = datetime.now() - timedelta(hours=hours)
+        
+        query = text("""
+            SELECT ip_address, COUNT(*) as request_count
+            FROM logs 
+            WHERE timestamp >= :since_time
+            GROUP BY ip_address
+            HAVING request_count > :threshold
+            ORDER BY request_count DESC
+            LIMIT 10
+        """)
+        
+        result = db.execute(query, {
+            'since_time': since_time,
+            'threshold': threshold
+        })
+        
+        return [(row[0], row[1]) for row in result]
+        
+    except Exception as e:
+        print(f"Error finding suspicious activity: {e}")
+        return []
+
+def get_active_users_count(db, hours=1):
+    """
+    Cuenta usuarios únicos activos en las últimas N horas
+    Retorna: número de usuarios únicos
+    """
+    from sqlalchemy import text
+    from datetime import datetime, timedelta
+    
+    try:
+        since_time = datetime.now() - timedelta(hours=hours)
+        
+        query = text("""
+            SELECT COUNT(DISTINCT username)
+            FROM logs
+            WHERE timestamp >= :since_time 
+            AND username IS NOT NULL 
+            AND username != ''
+        """)
+        
+        result = db.execute(query, {'since_time': since_time})
+        return result.scalar() or 0
+        
+    except Exception as e:
+        print(f"Error counting active users: {e}")
+        return 0
+
+def get_high_usage_users(db, hours=24, limit=5, threshold_mb=500):
+    """
+    Obtiene usuarios con mayor consumo de datos
+    Retorna: lista de tuplas [(username, usage_mb), ...]
+    """
+    from sqlalchemy import text
+    from datetime import datetime, timedelta
+    
+    try:
+        since_time = datetime.now() - timedelta(hours=hours)
+        
+        query = text("""
+            SELECT 
+                username,
+                SUM(bytes_sent) / (1024 * 1024) as usage_mb
+            FROM logs
+            WHERE timestamp >= :since_time
+            AND username IS NOT NULL 
+            AND username != ''
+            GROUP BY username
+            HAVING usage_mb > :threshold_mb
+            ORDER BY usage_mb DESC
+            LIMIT :limit
+        """)
+        
+        result = db.execute(query, {
+            'since_time': since_time,
+            'threshold_mb': threshold_mb,
+            'limit': limit
+        })
+        
+        return [(row[0], float(row[1])) for row in result]
+        
+    except Exception as e:
+        print(f"Error getting high usage users: {e}")
+        return []
+
+def get_failed_auth_attempts(db, hours=1, threshold=10):
+    """
+    Obtiene intentos de autenticación fallidos
+    Retorna: número de intentos fallidos
+    """
+    from sqlalchemy import text
+    from datetime import datetime, timedelta
+    
+    try:
+        since_time = datetime.now() - timedelta(hours=hours)
+        
+        query = text("""
+            SELECT COUNT(*) as failed_count
+            FROM logs
+            WHERE timestamp >= :since_time
+            AND response_code IN ('407', '401', '403')
+        """)
+        
+        result = db.execute(query, {'since_time': since_time})
+        count = result.scalar() or 0
+        
+        return count
+        
+    except Exception as e:
+        print(f"Error getting failed auth attempts: {e}")
+        return 0
+
+def get_denied_requests(db, hours=1, threshold=5):
+    """
+    Obtiene requests denegados
+    Retorna: número de requests denegados
+    """
+    from sqlalchemy import text
+    from datetime import datetime, timedelta
+    
+    try:
+        since_time = datetime.now() - timedelta(hours=hours)
+        
+        query = text("""
+            SELECT COUNT(*) as denied_count
+            FROM logs
+            WHERE timestamp >= :since_time
+            AND response_code = '403'
+        """)
+        
+        result = db.execute(query, {'since_time': since_time})
+        count = result.scalar() or 0
+        
+        return count
+        
+    except Exception as e:
+        print(f"Error getting denied requests: {e}")
+        return 0

+ 299 - 5
services/notifications.py

@@ -1,18 +1,170 @@
 import os
 import subprocess
+from datetime import datetime
+import threading
+import time
+from typing import List, Dict, Any
 
-notifications_data = {"commits": [], "has_updates": False}
+# Almacenamiento mejorado de notificaciones
+notifications_store = {
+    'notifications': [],
+    'unread_count': 0,
+    'last_check': None
+}
 
+# Variable global para Socket.IO
+socketio = None
 
-def set_commit_notifications(has_updates, messages):
-    notifications_data["has_updates"] = has_updates
-    notifications_data["commits"] = messages
+def set_socketio_instance(sio):
+    global socketio
+    socketio = sio
 
+def set_commit_notifications(has_updates, messages):
+    """Mantener por compatibilidad"""
+    # Convertir commits a notificaciones del sistema
+    if has_updates and messages:
+        for msg in messages:
+            add_notification('info', f"Commit: {msg}", 'fa-code-branch', 'git')
 
 def get_commit_notifications():
-    return notifications_data
+    """Mantener por compatibilidad con código existente"""
+    return {
+        'has_updates': len([n for n in notifications_store['notifications'] if n.get('source') == 'git']) > 0,
+        'commits': [n['message'].replace('Commit: ', '') for n in notifications_store['notifications'] if n.get('source') == 'git']
+    }
+
+def add_notification(notification_type: str, message: str, icon: str = None, source: str = "system"):
+    """Agrega una notificación al sistema y emite via Socket.IO si está configurado"""
+    notification = {
+        'id': len(notifications_store['notifications']) + 1,
+        'type': notification_type,  # 'info', 'warning', 'error', 'success'
+        'message': message,
+        'icon': icon or get_default_icon(notification_type),
+        'timestamp': datetime.now().isoformat(),
+        'time': 'Hace unos momentos',
+        'read': False,
+        'source': source
+    }
+    
+    # Agregar al inicio de la lista
+    notifications_store['notifications'].insert(0, notification)
+    
+    # Incrementar contador de no leídas
+    if not notification['read']:
+        notifications_store['unread_count'] += 1
+    
+    # Mantener máximo 50 notificaciones
+    if len(notifications_store['notifications']) > 50:
+        # Eliminar las más antiguas, pero mantener las no leídas si es posible
+        old_notifications = notifications_store['notifications'][50:]
+        for old_notif in old_notifications:
+            if not old_notif['read']:
+                notifications_store['unread_count'] -= 1
+        notifications_store['notifications'] = notifications_store['notifications'][:50]
+    
+    # Emitir via Socket.IO si está configurado
+    if socketio:
+        socketio.emit('new_notification', {
+            'notification': notification,
+            'unread_count': notifications_store['unread_count']
+        })
+    
+    return notification
+
+def get_default_icon(notification_type):
+    icons = {
+        'info': 'fa-info-circle',
+        'warning': 'fa-exclamation-triangle',
+        'error': 'fa-times-circle',
+        'success': 'fa-check-circle'
+    }
+    return icons.get(notification_type, 'fa-bell')
+
+def get_all_notifications(limit: int = 10) -> Dict[str, Any]:
+    """Obtiene todas las notificaciones del sistema"""
+    return {
+        'unread_count': notifications_store['unread_count'],
+        'notifications': notifications_store['notifications'][:limit]
+    }
+
+def mark_notifications_read(notification_ids: List[int]):
+    """Marca notificaciones como leídas"""
+    for notification in notifications_store['notifications']:
+        if notification['id'] in notification_ids and not notification['read']:
+            notification['read'] = True
+            notifications_store['unread_count'] -= 1
+
+def check_squid_service():
+    """Verifica el estado del servicio Squid y genera notificaciones"""
+    try:
+        # Verificar si Squid está corriendo
+        result = subprocess.run(
+            ['systemctl', 'is-active', 'squid'],
+            capture_output=True,
+            text=True,
+            timeout=10
+        )
+        
+        if result.returncode != 0:
+            add_notification('error', 'Servicio Squid no está corriendo', 'fa-exclamation-triangle', 'squid')
+        else:
+            # Verificar logs de errores recientes de Squid
+            log_check = subprocess.run(
+                ['journalctl', '-u', 'squid', '--since', '1 hour ago', '--no-pager'],
+                capture_output=True,
+                text=True,
+                timeout=10
+            )
+            
+            if 'error' in log_check.stdout.lower() or 'failed' in log_check.stdout.lower():
+                add_notification('warning', 'Errores detectados en logs de Squid', 'fa-exclamation-triangle', 'squid')
+                
+    except subprocess.TimeoutExpired:
+        add_notification('warning', 'Timeout al verificar estado de Squid', 'fa-clock', 'squid')
+    except Exception as e:
+        print(f"Error checking Squid service: {e}")
+
+def check_squid_log_health():
+    """Verifica la salud de los logs de Squid"""
+    try:
+        log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
+        
+        if os.path.exists(log_file):
+            # Verificar si el archivo de log está creciendo
+            stat_info = os.stat(log_file)
+            file_size_mb = stat_info.st_size / (1024 * 1024)
+            
+            if file_size_mb > 100:  # Más de 100MB
+                add_notification('warning', f'Log de Squid muy grande: {file_size_mb:.1f}MB', 'fa-file-alt', 'squid')
+            
+            # Verificar última modificación (no se actualiza en más de 5 minutos)
+            last_modified = datetime.fromtimestamp(stat_info.st_mtime)
+            time_diff = datetime.now() - last_modified
+            if time_diff.total_seconds() > 300:  # 5 minutos
+                add_notification('warning', 'Log de Squid no se actualiza hace más de 5 minutos', 'fa-clock', 'squid')
+                
+        else:
+            add_notification('error', f'Archivo de log de Squid no encontrado: {log_file}', 'fa-file-exclamation', 'squid')
+            
+    except Exception as e:
+        print(f"Error checking Squid log health: {e}")
 
+def check_system_health():
+    """Verifica la salud general del sistema"""
+    try:
+        # Verificar uso de disco
+        disk_usage = os.statvfs('/')
+        free_disk = (disk_usage.f_bavail * disk_usage.f_frsize) / (1024 ** 3)  # GB libres
+        
+        if free_disk < 1:  # Menos de 1GB libres
+            add_notification('error', f'Espacio en disco crítico: {free_disk:.1f}GB libres', 'fa-hdd', 'system')
+        elif free_disk < 5:  # Menos de 5GB libres
+            add_notification('warning', f'Espacio en disco bajo: {free_disk:.1f}GB libres', 'fa-hdd', 'system')
+            
+    except Exception as e:
+        print(f"Error checking system health: {e}")
 
+# Función para commits
 def has_remote_commits_with_messages(
     repo_path: str, branch: str = "main"
 ) -> tuple[bool, list[str]]:
@@ -72,3 +224,145 @@ def has_remote_commits_with_messages(
     except subprocess.CalledProcessError as e:
         print(f"Error al ejecutar comandos git: {e.stderr}")
         return False, []
+
+# Hilo para verificaciones periódicas
+def start_notification_monitor():
+    """Inicia el monitor de notificaciones en segundo plano"""
+    def monitor_loop():
+        check_count = 0
+        while True:
+            try:
+                # Verificar commits cada 30 minutos (cada 15 ciclos)
+                if check_count % 15 == 0:
+                    current_file_dir = os.path.dirname(os.path.abspath(__file__))
+                    repo_path = os.path.dirname(current_file_dir)  # Subir un nivel
+                    if os.path.exists(repo_path):
+                        has_updates, messages = has_remote_commits_with_messages(repo_path)
+                        set_commit_notifications(has_updates, messages)
+                
+                # Verificaciones CRÍTICAS cada 2 minutos (siempre)
+                check_squid_service()
+                check_squid_log_health()
+                check_system_health()
+                
+                # Verificaciones de SEGURIDAD cada 5 minutos (cada 2-3 ciclos)
+                if check_count % 3 == 0:
+                    check_security_events()
+                
+                # Verificaciones de USUARIOS cada 10 minutos (cada 5 ciclos)
+                if check_count % 5 == 0:
+                    check_user_activity()
+                
+                check_count += 1
+                if check_count > 1000:  # Prevenir overflow
+                    check_count = 0
+                
+            except Exception as e:
+                print(f"Error en monitor de notificaciones: {e}")
+            
+            time.sleep(120)  # Esperar 2 minutos entre ciclos
+    
+    thread = threading.Thread(target=monitor_loop, daemon=True)
+    thread.start()
+
+# Funciones específicas para Squid que pueden ser llamadas desde otras partes
+def notify_squid_restart_success():
+    """Notificar reinicio exitoso de Squid"""
+    add_notification('success', 'Squid reiniciado correctamente', 'fa-sync-alt', 'squid')
+
+def notify_squid_restart_failed(error_message: str = ""):
+    """Notificar fallo en reinicio de Squid"""
+    message = 'Error al reiniciar Squid'
+    if error_message:
+        message += f': {error_message}'
+    add_notification('error', message, 'fa-exclamation-triangle', 'squid')
+
+def notify_squid_config_error(error_message: str):
+    """Notificar error en configuración de Squid"""
+    add_notification('error', f'Error en configuración de Squid: {error_message}', 'fa-cog', 'squid')
+
+def notify_squid_high_usage(warning_message: str):
+    """Notificar uso alto de recursos de Squid"""
+    add_notification('warning', warning_message, 'fa-chart-line', 'squid')
+
+def check_security_events():
+    """Verifica eventos de seguridad desde la base de datos"""
+    try:
+        from database.database import get_session
+        from services.auditoria_service import (
+            find_suspicious_activity, 
+            get_failed_auth_attempts,
+            get_denied_requests
+        )
+        
+        db = get_session()
+        
+        # 1. Intentos de autenticación fallidos
+        failed_auth_count = get_failed_auth_attempts(db, hours=1)
+        if failed_auth_count > 15:
+            add_notification('warning', 
+                f'{failed_auth_count} intentos de autenticación fallidos en la última hora', 
+                'fa-shield-alt', 'security')
+        
+        # 2. Requests denegados
+        denied_count = get_denied_requests(db, hours=1)
+        if denied_count > 20:
+            add_notification('warning',
+                f'{denied_count} requests denegados en la última hora',
+                'fa-ban', 'security')
+        
+        # 3. IPs sospechosas (muchos requests en poco tiempo)
+        suspicious_ips = find_suspicious_activity(db, threshold=100, hours=1)
+        for ip, count in suspicious_ips:
+            if count > 200:  # Más de 200 requests en 1 hora
+                add_notification('warning',
+                    f'Actividad sospechosa desde IP {ip}: {count} requests/hora',
+                    'fa-user-secret', 'security')
+            elif count > 500:  # Más de 500 requests - crítico
+                add_notification('error',
+                    f'Actividad crítica desde IP {ip}: {count} requests/hora',
+                    'fa-exclamation-triangle', 'security')
+        
+        db.close()
+                
+    except Exception as e:
+        print(f"Error checking security events: {e}")
+
+def check_user_activity():
+    """Verifica actividad de usuarios desde la base de datos"""
+    try:
+        from database.database import get_session
+        from services.auditoria_service import get_active_users_count, get_high_usage_users
+        
+        db = get_session()
+        
+        # 1. Usuarios activos en la última hora
+        active_users = get_active_users_count(db, hours=1)
+        
+        if active_users > 50:
+            add_notification('info',
+                f'Alta actividad: {active_users} usuarios conectados en la última hora',
+                'fa-users', 'users')
+        
+        elif active_users == 0:
+            add_notification('warning',
+                'No hay usuarios activos en la última hora',
+                'fa-users', 'users')
+        
+        # 2. Usuarios con alto consumo de datos
+        high_usage_users = get_high_usage_users(db, hours=24, threshold_mb=100)
+        
+        for user, usage_mb in high_usage_users[:3]:  # Top 3
+            if usage_mb > 1000:  # Más de 1GB
+                add_notification('warning',
+                    f'Usuario {user} consumió {usage_mb:.0f}MB en 24h',
+                    'fa-chart-line', 'users')
+            elif usage_mb > 500:  # Más de 500MB
+                add_notification('info',
+                    f'Usuario {user} consumió {usage_mb:.0f}MB en 24h',
+                    'fa-user', 'users')
+        
+        db.close()
+                    
+    except Exception as e:
+        print(f"Error checking user activity: {e}")