From 3dc98c2fc35ed4beec092646bd8df904faaae569 Mon Sep 17 00:00:00 2001 From: Sutider Date: Mon, 18 May 2026 04:22:39 +0100 Subject: [PATCH] Add audit logging expansion, health endpoint, and request logging - Expand audit logging: server actions (restart, scale), login/logout with success/failure tracking - Add sensitive data filtering to audit logs before file writes (passwords, keys, tokens) - Add /api/health endpoint for monitoring (checks DB, SSH, K8s, miner protection, uptime) - Add request logging middleware with timing for API/server routes - Add X-Response-Time header to responses --- app/factory.py | 34 +++++++++++++++++++-- app/routes/api.py | 69 +++++++++++++++++++++++++++++++++++++++++++ app/routes/auth.py | 14 ++++++++- app/services/audit.py | 24 +++++++++++++-- 4 files changed, 136 insertions(+), 5 deletions(-) diff --git a/app/factory.py b/app/factory.py index 15ebdc8..d81b9f3 100644 --- a/app/factory.py +++ b/app/factory.py @@ -2,10 +2,11 @@ import os import sys +import time import logging import logging.handlers import threading -from flask import Flask, request +from flask import Flask, request, g from flask_socketio import SocketIO from flask_limiter import Limiter from flask_wtf.csrf import CSRFProtect @@ -119,6 +120,31 @@ def create_app(settings_path=None): from flask import jsonify return jsonify({'error': 'Method not allowed', 'type': 'MethodNotAllowed'}), 405 + # Request logging middleware + @app.before_request + def before_request_logging(): + from flask import request + from flask_login import current_user + import time + g._request_start_time = time.time() + user = current_user.id if current_user.is_authenticated else 'anonymous' + logging.debug(f"Request: {request.method} {request.path} from {user}") + + @app.after_request + def after_request_logging(response): + from flask import request, g + import time + duration = time.time() - g.get('_request_start_time', time.time()) + user = current_user.id if current_user.is_authenticated else 'anonymous' + + # Only log API requests to avoid noise + if request.path.startswith('/api') or request.path.startswith('/server'): + logging.info(f"{request.method} {request.path} {response.status_code} {duration:.3f}s user={user}") + + # Add timing header + response.headers['X-Response-Time'] = f"{duration:.3f}s" + return response + _setup_logging(settings) db_host = settings['database']['host'] @@ -196,6 +222,10 @@ def create_app(settings_path=None): audit_svc = AuditService() services['audit'] = audit_svc + # Track start time for uptime calculation + import time + app._start_time = time.time() + socketio = SocketIO(app, cors_allowed_origins=[], async_mode='threading') # Initialize rate limiter @@ -208,7 +238,7 @@ def create_app(settings_path=None): app.limiter = limiter if settings['auth']['enabled']: - init_auth(app, settings, limiter) + init_auth(app, settings, limiter, audit_svc) register_routes(app, services, settings) register_api_routes(app, services, settings) diff --git a/app/routes/api.py b/app/routes/api.py index 9a499e9..2645a15 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -5,6 +5,8 @@ import logging import os import re import shlex +import time +from datetime import datetime from flask import Blueprint, request, jsonify from flask_login import login_required from flask_limiter import Limiter @@ -36,6 +38,7 @@ def register_api_routes(app, services, settings): chat_svc = services['chat'] admin_svc = services['admin'] vehicle_svc = services['vehicle'] + audit_svc = services.get('audit') # Get or create rate limiter - use existing one from factory if available if not hasattr(app, 'limiter'): @@ -77,6 +80,12 @@ def register_api_routes(app, services, settings): return jsonify({'success': False, 'output': f'Unknown action: {action}'}) out, err, rc = k8s.run(cmd) + + # Audit logging for server actions + if audit_svc and action in ['restart', 'scale_0', 'scale_1']: + severity = 'warning' if action in ['restart', 'scale_0'] else 'info' + audit_svc.log(f'server_{action}', {'deployment': deployment, 'result': rc}, user='admin', severity=severity) + return jsonify({'success': rc == 0, 'output': out + '\n' + err}) @app.route('/server/pods') @@ -1151,3 +1160,63 @@ def register_api_routes(app, services, settings): except Exception as e: logger.warning(f"Failed to save miner protection setting: {e}") return jsonify({'success': True, 'enabled': enabled}) + + # Health check endpoint (no auth required for monitoring systems) + @app.route('/api/health') + def api_health(): + """Health check for monitoring systems.""" + health = { + 'status': 'healthy', + 'timestamp': datetime.now().isoformat(), + 'checks': {} + } + + # Check database + try: + db.execute('SELECT 1') + health['checks']['database'] = {'status': 'ok'} + except Exception as e: + health['checks']['database'] = {'status': 'error', 'message': str(e)} + health['status'] = 'degraded' + + # Check SSH + try: + out, err, rc = ssh.run('echo OK') + if rc == 0 and 'OK' in out: + health['checks']['ssh'] = {'status': 'ok'} + else: + health['checks']['ssh'] = {'status': 'error', 'message': 'SSH command failed'} + health['status'] = 'degraded' + except Exception as e: + health['checks']['ssh'] = {'status': 'error', 'message': str(e)} + health['status'] = 'degraded' + + # Check Kubernetes + try: + out, err, rc = k8s.run('get nodes') + if rc == 0: + health['checks']['kubernetes'] = {'status': 'ok'} + else: + health['checks']['kubernetes'] = {'status': 'error', 'message': 'kubectl failed'} + health['status'] = 'degraded' + except Exception as e: + health['checks']['kubernetes'] = {'status': 'error', 'message': str(e)} + health['status'] = 'degraded' + + # Check miner protection + if miner_protection: + mp_status = miner_protection.get_status() + health['checks']['miner_protection'] = { + 'status': 'ok' if mp_status.get('enabled') else 'disabled', + 'enabled': mp_status.get('enabled', False) + } + else: + health['checks']['miner_protection'] = {'status': 'not_configured'} + + # Add dashboard uptime + start_time = getattr(app, '_start_time', None) + if start_time: + health['uptime_seconds'] = int(time.time() - start_time) + + status_code = 200 if health['status'] == 'healthy' else 503 + return jsonify(health), status_code diff --git a/app/routes/auth.py b/app/routes/auth.py index 0583670..1952f1c 100644 --- a/app/routes/auth.py +++ b/app/routes/auth.py @@ -13,7 +13,7 @@ class AdminUser(UserMixin): def __init__(self, username): self.id = username -def init_auth(app, settings, limiter=None): +def init_auth(app, settings, limiter=None, audit_svc=None): login_manager.init_app(app) @login_manager.user_loader @@ -39,6 +39,8 @@ def init_auth(app, settings, limiter=None): # Verify username matches if u != cfg_u: + if audit_svc: + audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_username'}, user='unknown', severity='warning') flash('Invalid username or password') return render_template('login.html') @@ -49,8 +51,15 @@ def init_auth(app, settings, limiter=None): ph = PasswordHasher() if ph.verify(password_hash, p): login_user(AdminUser(u)) + if audit_svc: + audit_svc.log('login_success', {'username': u}, user=u, severity='info') return redirect(url_for('overview')) + else: + if audit_svc: + audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning') except exceptions.VerifyMismatchError: + if audit_svc: + audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning') pass except Exception: flash('Authentication error. Please try again.') @@ -66,5 +75,8 @@ def init_auth(app, settings, limiter=None): @app.route('/logout') @login_required def logout(): + user = current_user.id if current_user.is_authenticated else 'unknown' logout_user() + if audit_svc: + audit_svc.log('logout', {}, user=user, severity='info') return redirect(url_for('login')) diff --git a/app/services/audit.py b/app/services/audit.py index f503e00..76d62b9 100644 --- a/app/services/audit.py +++ b/app/services/audit.py @@ -12,6 +12,8 @@ logger = logging.getLogger(__name__) class AuditService: """In-memory audit log service (could be extended to database).""" + SENSITIVE_KEYS = {'password', 'password_hash', 'secret_key', 'token', 'ssh_key', 'key', 'cert', 'credentials'} + def __init__(self, log_dir=None): self._lock = Lock() self._logs = [] @@ -19,6 +21,22 @@ class AuditService: self._log_dir = log_dir or os.path.join(os.path.dirname(os.path.dirname(__file__)), 'logs') os.makedirs(self._log_dir, exist_ok=True) + def _filter_sensitive(self, data): + """Remove sensitive data from details before logging to file.""" + if not isinstance(data, dict): + return data + filtered = {} + for k, v in data.items(): + if any(s in k.lower() for s in self.SENSITIVE_KEYS): + filtered[k] = '[REDACTED]' + elif isinstance(v, dict): + filtered[k] = self._filter_sensitive(v) + elif isinstance(v, list): + filtered[k] = [self._filter_sensitive(i) if isinstance(i, dict) else i for i in v] + else: + filtered[k] = v + return filtered + def log(self, action, details=None, user='system', severity='info'): """Log an audit event.""" with self._lock: @@ -33,8 +51,10 @@ class AuditService: # Trim old logs if len(self._logs) > self._max_logs: self._logs = self._logs[-self._max_logs:] - # Also write to file - self._write_to_file(entry) + # Also write to file (with sensitive data filtered) + safe_entry = entry.copy() + safe_entry['details'] = self._filter_sensitive(entry.get('details', {})) + self._write_to_file(safe_entry) logger.info(f"Audit: {action} by {user}") def _write_to_file(self, entry):