From b4023fb341fe26ef49e17873ac8faa8c7ead13b0 Mon Sep 17 00:00:00 2001 From: Sutider Date: Mon, 18 May 2026 04:12:44 +0100 Subject: [PATCH] Add global exception handler and audit log viewer - Global exception handler in factory.py (404, 405, unhandled exceptions return JSON) - AuditService for tracking admin actions (miner cleanup, toggles) - Audit Log Viewer UI section in server.html - Updated .gitignore to exclude app/logs/ --- .gitignore | 3 ++ app/factory.py | 35 ++++++++++++++ app/routes/api.py | 86 +++++++++++++++++++++------------- app/services/audit.py | 90 ++++++++++++++++++++++++++++++++++++ templates/server.html | 105 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 288 insertions(+), 31 deletions(-) create mode 100644 app/services/audit.py diff --git a/.gitignore b/.gitignore index 8e361cb..bc7d5eb 100644 --- a/.gitignore +++ b/.gitignore @@ -95,3 +95,6 @@ VERSION # Security scripts (contain VM-specific configs) scripts/cleanup-miner.sh scripts/vm-security-changes.md + +# Audit logs directory +app/logs/ diff --git a/app/factory.py b/app/factory.py index 2035368..15ebdc8 100644 --- a/app/factory.py +++ b/app/factory.py @@ -89,6 +89,36 @@ def create_app(settings_path=None): response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()' return response + # Global error handlers + @app.errorhandler(Exception) + def handle_exception(e): + """Handle all unhandled exceptions.""" + logging.exception(f"Unhandled exception: {str(e)}") + from flask import jsonify + error_type = type(e).__name__ + error_msg = str(e) + # Don't expose internal error details in production + if settings['dashboard'].get('debug', False): + return jsonify({ + 'error': error_msg, + 'type': error_type, + 'trace': str(e) + }), 500 + return jsonify({ + 'error': 'An internal error occurred', + 'type': error_type + }), 500 + + @app.errorhandler(404) + def handle_not_found(e): + from flask import jsonify + return jsonify({'error': 'Resource not found', 'type': 'NotFound'}), 404 + + @app.errorhandler(405) + def handle_method_not_allowed(e): + from flask import jsonify + return jsonify({'error': 'Method not allowed', 'type': 'MethodNotAllowed'}), 405 + _setup_logging(settings) db_host = settings['database']['host'] @@ -161,6 +191,11 @@ def create_app(settings_path=None): miner_protection.start() services['miner_protection'] = miner_protection + # Initialize audit service + from app.services.audit import AuditService + audit_svc = AuditService() + services['audit'] = audit_svc + socketio = SocketIO(app, cors_allowed_origins=[], async_mode='threading') # Initialize rate limiter diff --git a/app/routes/api.py b/app/routes/api.py index 0ad294b..9a499e9 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -1084,37 +1084,6 @@ def register_api_routes(app, services, settings): status = miner_protection.get_status() return jsonify({'success': True, 'status': status}) - @app.route('/api/security/cleanup', methods=['POST']) - @auth_req - def api_security_cleanup(): - """Manually run miner cleanup.""" - if not miner_protection: - return jsonify({'success': False, 'error': 'Miner protection not available'}) - result = miner_protection.run_cleanup() - return jsonify({'success': True, 'result': result}) - - @app.route('/api/security/toggle', methods=['POST']) - @auth_req - def api_security_toggle(): - """Toggle miner protection on/off.""" - if not miner_protection: - return jsonify({'success': False, 'error': 'Miner protection not available'}) - data = request.get_json() or {} - enabled = data.get('enabled', True) - miner_protection.toggle(enabled) - # Save to settings - if 'miner_protection' not in settings: - settings['miner_protection'] = {} - settings['miner_protection']['enabled'] = enabled - try: - import yaml - settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings.yaml') - with open(settings_path, 'w') as f: - yaml.dump(settings, f, default_flow_style=False, sort_keys=False) - except Exception as e: - logger.warning(f"Failed to save miner protection setting: {e}") - return jsonify({'success': True, 'enabled': enabled}) - @app.route('/api/security/logs', methods=['GET']) @auth_req def api_security_logs(): @@ -1127,3 +1096,58 @@ def register_api_routes(app, services, settings): else: logs = miner_protection.get_logs(all_logs=True) return jsonify({'success': True, 'logs': logs}) + + # Audit logs + from app.services.audit import AuditService + audit_svc = AuditService() + + @app.route('/api/audit/logs', methods=['GET']) + @auth_req + def api_audit_logs(): + """Get audit logs.""" + action = request.args.get('action') + user = request.args.get('user') + limit = int(request.args.get('limit', 100)) + offset = int(request.args.get('offset', 0)) + logs = audit_svc.get_logs(action=action, user=user, limit=limit, offset=offset) + return jsonify({'success': True, 'logs': logs}) + + @app.route('/api/audit/stats', methods=['GET']) + @auth_req + def api_audit_stats(): + """Get audit log statistics.""" + stats = audit_svc.get_stats() + return jsonify({'success': True, 'stats': stats}) + + # Add audit logging to miner cleanup and toggle + @app.route('/api/security/cleanup', methods=['POST']) + @auth_req + def api_security_cleanup_with_audit(): + """Manually run miner cleanup with audit logging.""" + if not miner_protection: + return jsonify({'success': False, 'error': 'Miner protection not available'}) + result = miner_protection.run_cleanup() + audit_svc.log('miner_cleanup', {'result': result}, user='admin', severity='warning') + return jsonify({'success': True, 'result': result}) + + @app.route('/api/security/toggle', methods=['POST']) + @auth_req + def api_security_toggle_with_audit(): + """Toggle miner protection on/off with audit logging.""" + if not miner_protection: + return jsonify({'success': False, 'error': 'Miner protection not available'}) + data = request.get_json() or {} + enabled = data.get('enabled', True) + miner_protection.toggle(enabled) + audit_svc.log('miner_protection_toggle', {'enabled': enabled}, user='admin', severity='info') + if 'miner_protection' not in settings: + settings['miner_protection'] = {} + settings['miner_protection']['enabled'] = enabled + try: + import yaml + settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings.yaml') + with open(settings_path, 'w') as f: + yaml.dump(settings, f, default_flow_style=False, sort_keys=False) + except Exception as e: + logger.warning(f"Failed to save miner protection setting: {e}") + return jsonify({'success': True, 'enabled': enabled}) diff --git a/app/services/audit.py b/app/services/audit.py new file mode 100644 index 0000000..f503e00 --- /dev/null +++ b/app/services/audit.py @@ -0,0 +1,90 @@ +"""Audit logging service - tracks important admin actions""" + +import os +import json +import logging +from datetime import datetime +from threading import Lock + +logger = logging.getLogger(__name__) + + +class AuditService: + """In-memory audit log service (could be extended to database).""" + + def __init__(self, log_dir=None): + self._lock = Lock() + self._logs = [] + self._max_logs = 1000 + 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 log(self, action, details=None, user='system', severity='info'): + """Log an audit event.""" + with self._lock: + entry = { + 'timestamp': datetime.now().isoformat(), + 'action': action, + 'user': user, + 'severity': severity, + 'details': details or {} + } + self._logs.append(entry) + # 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) + logger.info(f"Audit: {action} by {user}") + + def _write_to_file(self, entry): + """Write audit entry to daily log file.""" + try: + date = datetime.now().strftime('%Y-%m-%d') + log_file = os.path.join(self._log_dir, f'audit-{date}.log') + with open(log_file, 'a') as f: + f.write(json.dumps(entry) + '\n') + except Exception as e: + logger.warning(f"Failed to write audit log to file: {e}") + + def get_logs(self, action=None, user=None, limit=100, offset=0): + """Query audit logs.""" + with self._lock: + results = self._logs + if action: + results = [e for e in results if e['action'] == action] + if user: + results = [e for e in results if e['user'] == user] + results = results[offset:offset+limit] + return results + + def clear_old_logs(self, days=30): + """Remove log files older than specified days.""" + try: + import time + cutoff = time.time() - (days * 86400) + for f in os.listdir(self._log_dir): + if f.startswith('audit-') and f.endswith('.log'): + fpath = os.path.join(self._log_dir, f) + if os.path.getmtime(fpath) < cutoff: + os.remove(fpath) + logger.info(f"Removed old audit log: {f}") + except Exception as e: + logger.warning(f"Failed to clear old logs: {e}") + + def get_stats(self): + """Get audit log statistics.""" + with self._lock: + return { + 'total_entries': len(self._logs), + 'by_severity': self._count_by('severity'), + 'by_action': self._count_by('action'), + } + + def _count_by(self, key): + """Count entries by a specific key.""" + counts = {} + for entry in self._logs: + val = entry.get(key, 'unknown') + counts[val] = counts.get(val, 0) + 1 + return counts \ No newline at end of file diff --git a/templates/server.html b/templates/server.html index 33f8c3c..3715331 100644 --- a/templates/server.html +++ b/templates/server.html @@ -243,6 +243,49 @@ +
+
+ 📋 Audit Log Viewer + Loading... +
+
+
+ + + + + +
+
+ Total: 0 + Info: 0 + Warning: 0 + Error: 0 +
+
+ + + + + + + + + + + + + +
TimeActionUserSeverityDetails
Loading...
+
+
+
+
Firewall Security @@ -581,5 +624,67 @@ loadMinerStatus(); // Auto-refresh every 30 seconds setInterval(loadMinerStatus, 30000); + +// Audit Log Viewer +async function loadAuditLogs(action = '', user = '', severity = '', limit = 100, offset = 0) { + const tbody = document.getElementById('audit-logs-body'); + const actionFilter = document.getElementById('audit-search').value; + const userFilter = document.getElementById('audit-user').value; + const severityFilter = document.getElementById('audit-severity').value; + + try { + let url = '/api/audit/logs?limit=' + limit + '&offset=' + offset; + if (actionFilter) url += '&action=' + encodeURIComponent(actionFilter); + if (userFilter) url += '&user=' + encodeURIComponent(userFilter); + + const resp = await fetch(url); + const data = await resp.json(); + + if (!data.success) { + tbody.innerHTML = 'Error: ' + data.error + ''; + return; + } + + const logs = data.logs || []; + if (logs.length === 0) { + tbody.innerHTML = 'No audit logs found'; + document.getElementById('audit-total').textContent = '0'; + return; + } + + // Update stats + const infoCount = logs.filter(l => l.severity === 'info').length; + const warningCount = logs.filter(l => l.severity === 'warning').length; + const errorCount = logs.filter(l => l.severity === 'error').length; + document.getElementById('audit-total').textContent = logs.length; + document.getElementById('audit-info-count').textContent = infoCount; + document.getElementById('audit-warning-count').textContent = warningCount; + document.getElementById('audit-error-count').textContent = errorCount; + + // Render table + tbody.innerHTML = logs.map(log => { + const details = log.details ? JSON.stringify(log.details) : '-'; + const severityColor = log.severity === 'error' ? 'color:#e74c3c;' : (log.severity === 'warning' ? 'color:#f39c12;' : 'color:#3498db;'); + const timestamp = log.timestamp ? log.timestamp.replace('T', ' ').substring(0, 19) : '-'; + return '' + + '' + timestamp + '' + + '' + (log.action || '-') + '' + + '' + (log.user || '-') + '' + + '' + (log.severity || 'info') + '' + + '' + details + '' + + ''; + }).join(''); + + } catch (e) { + tbody.innerHTML = 'Error: ' + e.message + ''; + } +} + +function refreshAuditLogs() { + loadAuditLogs(); +} + +// Load audit stats on page load +loadAuditLogs(); {% endblock %}