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/
This commit is contained in:
1 parent
ab8d0d922a
commit
b4023fb341
5 files changed
+288
-31
No files matched your search
@@ -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/
|
||||
@@ -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
|
||||
|
||||
+55
-31
@@ -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})
|
||||
@@ -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
|
||||
@@ -243,6 +243,49 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header" style="cursor:pointer;" onclick="document.getElementById('audit-section').classList.toggle('hidden');">
|
||||
<span>📋 Audit Log Viewer</span>
|
||||
<span id="audit-stats" style="font-size:12px;color:var(--text-muted);">Loading...</span>
|
||||
</div>
|
||||
<div class="card-body" id="audit-section">
|
||||
<div style="margin-bottom:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
|
||||
<input type="text" id="audit-search" placeholder="Filter by action..." style="padding:8px 12px;background:#1a1a2e;border:1px solid #333;border-radius:6px;color:#e0d5c7;font-size:13px;width:180px;">
|
||||
<input type="text" id="audit-user" placeholder="Filter by user..." style="padding:8px 12px;background:#1a1a2e;border:1px solid #333;border-radius:6px;color:#e0d5c7;font-size:13px;width:140px;">
|
||||
<select id="audit-severity" style="padding:8px 12px;background:#1a1a2e;border:1px solid #333;border-radius:6px;color:#e0d5c7;font-size:13px;">
|
||||
<option value="">All Severities</option>
|
||||
<option value="info">Info</option>
|
||||
<option value="warning">Warning</option>
|
||||
<option value="error">Error</option>
|
||||
</select>
|
||||
<button onclick="loadAuditLogs()" style="padding:8px 16px;background:var(--primary);color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Filter</button>
|
||||
<button onclick="refreshAuditLogs()" style="padding:8px 16px;background:#333;color:#e0d5c7;border:none;border-radius:6px;cursor:pointer;font-size:13px;">Refresh</button>
|
||||
</div>
|
||||
<div style="margin-bottom:12px;display:flex;gap:16px;font-size:12px;color:var(--text-muted);">
|
||||
<span>Total: <strong id="audit-total">0</strong></span>
|
||||
<span>Info: <strong id="audit-info-count" style="color:#3498db;">0</strong></span>
|
||||
<span>Warning: <strong id="audit-warning-count" style="color:#f39c12;">0</strong></span>
|
||||
<span>Error: <strong id="audit-error-count" style="color:#e74c3c;">0</strong></span>
|
||||
</div>
|
||||
<div id="audit-logs-container" style="max-height:300px;overflow-y:auto;">
|
||||
<table style="width:100%;border-collapse:collapse;font-size:12px;">
|
||||
<thead style="position:sticky;top:0;background:#2a2a3e;">
|
||||
<tr style="text-align:left;color:var(--text-muted);">
|
||||
<th style="padding:8px;border-bottom:1px solid #333;">Time</th>
|
||||
<th style="padding:8px;border-bottom:1px solid #333;">Action</th>
|
||||
<th style="padding:8px;border-bottom:1px solid #333;">User</th>
|
||||
<th style="padding:8px;border-bottom:1px solid #333;">Severity</th>
|
||||
<th style="padding:8px;border-bottom:1px solid #333;">Details</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="audit-logs-body">
|
||||
<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--text-muted);">Loading...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<span>Firewall Security</span>
|
||||
@@ -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 = '<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--danger);">Error: ' + data.error + '</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
const logs = data.logs || [];
|
||||
if (logs.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--text-muted);">No audit logs found</td></tr>';
|
||||
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 '<tr style="border-bottom:1px solid #333;">' +
|
||||
'<td style="padding:8px;color:var(--text-muted);">' + timestamp + '</td>' +
|
||||
'<td style="padding:8px;font-weight:600;">' + (log.action || '-') + '</td>' +
|
||||
'<td style="padding:8px;">' + (log.user || '-') + '</td>' +
|
||||
'<td style="padding:8px;' + severityColor + '">' + (log.severity || 'info') + '</td>' +
|
||||
'<td style="padding:8px;color:var(--text-muted);font-size:11px;max-width:200px;overflow:hidden;text-overflow:ellipsis;">' + details + '</td>' +
|
||||
'</tr>';
|
||||
}).join('');
|
||||
|
||||
} catch (e) {
|
||||
tbody.innerHTML = '<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--danger);">Error: ' + e.message + '</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function refreshAuditLogs() {
|
||||
loadAuditLogs();
|
||||
}
|
||||
|
||||
// Load audit stats on page load
|
||||
loadAuditLogs();
|
||||
</script>
|
||||
{% endblock %}
|
||||
Reference in new issue
Block a user