diff --git a/.gitignore b/.gitignore index 38e0e2e8..de41feea 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /frontend/node_modules +nul diff --git a/backend/.env.example b/backend/.env.example index d9a71f57..1d5aef03 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,11 +1,16 @@ # Flask Configuration FLASK_ENV=development + +# IMPORTANT: Generate secure keys for production! +# Run: python -c "import secrets; print(secrets.token_hex(32))" SECRET_KEY=change-this-to-a-secure-random-string # Database DATABASE_URL=sqlite:///serverkit.db # JWT Configuration +# IMPORTANT: Generate a unique key for production! +# Run: python -c "import secrets; print(secrets.token_hex(32))" JWT_SECRET_KEY=change-this-to-another-secure-random-string # CORS - comma-separated list of allowed origins diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 00000000..60d27066 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,42 @@ +# Backend Dockerfile for ServerKit +FROM python:3.11-slim + +# Set environment variables +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + FLASK_ENV=production + +# Set working directory +WORKDIR /app + +# Install system dependencies +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc \ + libpq-dev \ + && rm -rf /var/lib/apt/lists/* + +# Copy requirements first for caching +COPY requirements.txt . + +# Install Python dependencies +RUN pip install --no-cache-dir -r requirements.txt \ + && pip install --no-cache-dir gunicorn gevent gevent-websocket + +# Copy application code +COPY . . + +# Create non-root user +RUN useradd --create-home appuser && chown -R appuser:appuser /app +USER appuser + +# Expose port +EXPOSE 5000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/api/v1/health')" || exit 1 + +# Run with gunicorn + gevent for WebSocket support +CMD ["gunicorn", "-k", "geventwebsocket.gunicorn.workers.GeventWebSocketWorker", \ + "-w", "1", "-b", "0.0.0.0:5000", "--access-logfile", "-", "--error-logfile", "-", \ + "run:app"] diff --git a/backend/app/__init__.py b/backend/app/__init__.py index c1713480..61b6f6a0 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -3,11 +3,14 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import JWTManager from flask_cors import CORS +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address from config import config db = SQLAlchemy() jwt = JWTManager() +limiter = Limiter(key_func=get_remote_address, default_limits=["100 per minute"]) socketio = None @@ -23,8 +26,13 @@ def create_app(config_name=None): # Initialize extensions db.init_app(app) jwt.init_app(app) + limiter.init_app(app) CORS(app, origins=app.config['CORS_ORIGINS'], supports_credentials=True) + # Register security headers middleware + from app.middleware.security import register_security_headers + register_security_headers(app) + # Initialize SocketIO from app.sockets import init_socketio socketio = init_socketio(app) @@ -71,6 +79,18 @@ def create_app(config_name=None): from app.api.databases import databases_bp app.register_blueprint(databases_bp, url_prefix='/api/v1/databases') + # Register blueprints - Monitoring & Alerts + from app.api.monitoring import monitoring_bp + app.register_blueprint(monitoring_bp, url_prefix='/api/v1/monitoring') + + # Register blueprints - Backups + from app.api.backups import backups_bp + app.register_blueprint(backups_bp, url_prefix='/api/v1/backups') + + # Register blueprints - Git Deployment + from app.api.deploy import deploy_bp + app.register_blueprint(deploy_bp, url_prefix='/api/v1/deploy') + # Create database tables with app.app_context(): db.create_all() diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py index 3cafa834..4503be0a 100644 --- a/backend/app/api/auth.py +++ b/backend/app/api/auth.py @@ -1,3 +1,4 @@ +from datetime import datetime from flask import Blueprint, request, jsonify from flask_jwt_extended import ( create_access_token, @@ -6,13 +7,14 @@ from flask_jwt_extended import ( get_jwt_identity, get_jwt ) -from app import db +from app import db, limiter from app.models import User auth_bp = Blueprint('auth', __name__) @auth_bp.route('/register', methods=['POST']) +@limiter.limit("3 per minute") def register(): data = request.get_json() @@ -60,6 +62,7 @@ def register(): @auth_bp.route('/login', methods=['POST']) +@limiter.limit("5 per minute") def login(): data = request.get_json() @@ -74,12 +77,27 @@ def login(): user = User.query.filter_by(email=email).first() + # Check if account is locked + if user and user.is_locked: + remaining = int((user.locked_until - datetime.utcnow()).total_seconds() / 60) + return jsonify({ + 'error': f'Account is locked. Try again in {remaining} minute(s).' + }), 429 + if not user or not user.check_password(password): + # Record failed login attempt + if user: + user.record_failed_login() + db.session.commit() return jsonify({'error': 'Invalid email or password'}), 401 if not user.is_active: return jsonify({'error': 'Account is deactivated'}), 403 + # Reset failed login count on successful login + user.reset_failed_login() + db.session.commit() + access_token = create_access_token(identity=user.id) refresh_token = create_refresh_token(identity=user.id) diff --git a/backend/app/api/backups.py b/backend/app/api/backups.py new file mode 100644 index 00000000..6d9c7f06 --- /dev/null +++ b/backend/app/api/backups.py @@ -0,0 +1,228 @@ +from flask import Blueprint, request, jsonify +from flask_jwt_extended import jwt_required, get_jwt_identity +from app.models import User, Application +from app.services.backup_service import BackupService + +backups_bp = Blueprint('backups', __name__) + + +def admin_required(fn): + """Decorator to require admin role.""" + from functools import wraps + + @wraps(fn) + def wrapper(*args, **kwargs): + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + if not user or user.role != 'admin': + return jsonify({'error': 'Admin access required'}), 403 + return fn(*args, **kwargs) + return wrapper + + +@backups_bp.route('', methods=['GET']) +@jwt_required() +def list_backups(): + """List all backups.""" + backup_type = request.args.get('type') + backups = BackupService.list_backups(backup_type) + return jsonify({'backups': backups}), 200 + + +@backups_bp.route('/stats', methods=['GET']) +@jwt_required() +def get_stats(): + """Get backup statistics.""" + stats = BackupService.get_backup_stats() + return jsonify(stats), 200 + + +@backups_bp.route('/config', methods=['GET']) +@jwt_required() +@admin_required +def get_config(): + """Get backup configuration.""" + config = BackupService.get_config() + return jsonify(config), 200 + + +@backups_bp.route('/config', methods=['PUT']) +@jwt_required() +@admin_required +def update_config(): + """Update backup configuration.""" + data = request.get_json() + if not data: + return jsonify({'error': 'No data provided'}), 400 + + current_config = BackupService.get_config() + current_config.update(data) + result = BackupService.save_config(current_config) + return jsonify(result), 200 if result['success'] else 400 + + +@backups_bp.route('/application', methods=['POST']) +@jwt_required() +@admin_required +def backup_application(): + """Backup an application.""" + data = request.get_json() + + if not data: + return jsonify({'error': 'No data provided'}), 400 + + app_id = data.get('application_id') + if not app_id: + return jsonify({'error': 'application_id is required'}), 400 + + app = Application.query.get(app_id) + if not app: + return jsonify({'error': 'Application not found'}), 404 + + result = BackupService.backup_application( + app_name=app.name, + app_path=app.path, + include_db=data.get('include_db', False), + db_config=data.get('db_config') + ) + + return jsonify(result), 201 if result['success'] else 400 + + +@backups_bp.route('/database', methods=['POST']) +@jwt_required() +@admin_required +def backup_database(): + """Backup a database.""" + data = request.get_json() + + if not data: + return jsonify({'error': 'No data provided'}), 400 + + required = ['db_type', 'db_name'] + missing = [f for f in required if f not in data] + if missing: + return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400 + + result = BackupService.backup_database( + db_type=data['db_type'], + db_name=data['db_name'], + user=data.get('user'), + password=data.get('password'), + host=data.get('host', 'localhost') + ) + + return jsonify(result), 201 if result['success'] else 400 + + +@backups_bp.route('/restore/application', methods=['POST']) +@jwt_required() +@admin_required +def restore_application(): + """Restore an application from backup.""" + data = request.get_json() + + if not data or 'backup_path' not in data: + return jsonify({'error': 'backup_path is required'}), 400 + + result = BackupService.restore_application( + backup_path=data['backup_path'], + restore_path=data.get('restore_path') + ) + + return jsonify(result), 200 if result['success'] else 400 + + +@backups_bp.route('/restore/database', methods=['POST']) +@jwt_required() +@admin_required +def restore_database(): + """Restore a database from backup.""" + data = request.get_json() + + if not data: + return jsonify({'error': 'No data provided'}), 400 + + required = ['backup_path', 'db_type', 'db_name'] + missing = [f for f in required if f not in data] + if missing: + return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400 + + result = BackupService.restore_database( + backup_path=data['backup_path'], + db_type=data['db_type'], + db_name=data['db_name'], + user=data.get('user'), + password=data.get('password'), + host=data.get('host', 'localhost') + ) + + return jsonify(result), 200 if result['success'] else 400 + + +@backups_bp.route('/', methods=['DELETE']) +@jwt_required() +@admin_required +def delete_backup(backup_path): + """Delete a backup.""" + # Ensure path is within backup directory + full_path = f"/var/backups/serverkit/{backup_path}" + result = BackupService.delete_backup(full_path) + return jsonify(result), 200 if result['success'] else 400 + + +@backups_bp.route('/cleanup', methods=['POST']) +@jwt_required() +@admin_required +def cleanup_backups(): + """Clean up old backups.""" + data = request.get_json() or {} + retention_days = data.get('retention_days') + + result = BackupService.cleanup_old_backups(retention_days) + return jsonify(result), 200 if result['success'] else 400 + + +# Schedules +@backups_bp.route('/schedules', methods=['GET']) +@jwt_required() +@admin_required +def list_schedules(): + """List backup schedules.""" + schedules = BackupService.get_schedules() + return jsonify({'schedules': schedules}), 200 + + +@backups_bp.route('/schedules', methods=['POST']) +@jwt_required() +@admin_required +def add_schedule(): + """Add a backup schedule.""" + data = request.get_json() + + if not data: + return jsonify({'error': 'No data provided'}), 400 + + required = ['name', 'backup_type', 'target', 'schedule_time'] + missing = [f for f in required if f not in data] + if missing: + return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400 + + result = BackupService.add_schedule( + name=data['name'], + backup_type=data['backup_type'], + target=data['target'], + schedule_time=data['schedule_time'], + days=data.get('days') + ) + + return jsonify(result), 201 if result['success'] else 400 + + +@backups_bp.route('/schedules/', methods=['DELETE']) +@jwt_required() +@admin_required +def remove_schedule(schedule_id): + """Remove a backup schedule.""" + result = BackupService.remove_schedule(schedule_id) + return jsonify(result), 200 if result['success'] else 400 diff --git a/backend/app/api/databases.py b/backend/app/api/databases.py index dd158f39..8c2166fb 100644 --- a/backend/app/api/databases.py +++ b/backend/app/api/databases.py @@ -35,8 +35,12 @@ def get_status(): @databases_bp.route('/mysql', methods=['GET']) @jwt_required() def list_mysql_databases(): - """List MySQL databases.""" - root_password = request.args.get('root_password') + """List MySQL databases. + + For security, root_password should be passed via X-DB-Password header, not query params. + """ + # Read root_password from header for security (not exposed in URL/logs) + root_password = request.headers.get('X-DB-Password') databases = DatabaseService.mysql_list_databases(root_password) return jsonify({'databases': databases}), 200 @@ -94,8 +98,11 @@ def drop_mysql_database(name): @databases_bp.route('/mysql//tables', methods=['GET']) @jwt_required() def get_mysql_tables(name): - """Get tables in a MySQL database.""" - root_password = request.args.get('root_password') + """Get tables in a MySQL database. + + For security, root_password should be passed via X-DB-Password header. + """ + root_password = request.headers.get('X-DB-Password') tables = DatabaseService.mysql_get_tables(name, root_password) return jsonify({'tables': tables}), 200 @@ -133,8 +140,11 @@ def restore_mysql_database(name): @databases_bp.route('/mysql/users', methods=['GET']) @jwt_required() def list_mysql_users(): - """List MySQL users.""" - root_password = request.args.get('root_password') + """List MySQL users. + + For security, root_password should be passed via X-DB-Password header. + """ + root_password = request.headers.get('X-DB-Password') users = DatabaseService.mysql_list_users(root_password) return jsonify({'users': users}), 200 @@ -188,9 +198,12 @@ def drop_mysql_user(username): @databases_bp.route('/mysql/users//privileges', methods=['GET']) @jwt_required() def get_mysql_user_privileges(username): - """Get privileges for a MySQL user.""" + """Get privileges for a MySQL user. + + For security, root_password should be passed via X-DB-Password header. + """ host = request.args.get('host', 'localhost') - root_password = request.args.get('root_password') + root_password = request.headers.get('X-DB-Password') privileges = DatabaseService.mysql_get_user_privileges(username, host, root_password) return jsonify({'privileges': privileges}), 200 diff --git a/backend/app/api/deploy.py b/backend/app/api/deploy.py new file mode 100644 index 00000000..7bdb1ce4 --- /dev/null +++ b/backend/app/api/deploy.py @@ -0,0 +1,218 @@ +from flask import Blueprint, request, jsonify +from flask_jwt_extended import jwt_required, get_jwt_identity +from app.models import User, Application +from app.services.git_service import GitService + +deploy_bp = Blueprint('deploy', __name__) + + +def admin_required(fn): + """Decorator to require admin role.""" + from functools import wraps + + @wraps(fn) + def wrapper(*args, **kwargs): + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + if not user or user.role != 'admin': + return jsonify({'error': 'Admin access required'}), 403 + return fn(*args, **kwargs) + return wrapper + + +@deploy_bp.route('/apps//config', methods=['GET']) +@jwt_required() +def get_deploy_config(app_id): + """Get deployment configuration for an app.""" + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + app = Application.query.get(app_id) + + if not app: + return jsonify({'error': 'Application not found'}), 404 + + if user.role != 'admin' and app.user_id != current_user_id: + return jsonify({'error': 'Access denied'}), 403 + + config = GitService.get_app_config(app_id) + if not config: + return jsonify({'configured': False}), 200 + + return jsonify({ + 'configured': True, + 'config': config + }), 200 + + +@deploy_bp.route('/apps//config', methods=['POST']) +@jwt_required() +@admin_required +def configure_deployment(app_id): + """Configure Git deployment for an app.""" + app = Application.query.get(app_id) + if not app: + return jsonify({'error': 'Application not found'}), 404 + + data = request.get_json() + if not data: + return jsonify({'error': 'No data provided'}), 400 + + if 'repo_url' not in data: + return jsonify({'error': 'repo_url is required'}), 400 + + result = GitService.configure_deployment( + app_id=app_id, + app_path=app.path, + repo_url=data['repo_url'], + branch=data.get('branch', 'main'), + auto_deploy=data.get('auto_deploy', True), + pre_deploy_script=data.get('pre_deploy_script'), + post_deploy_script=data.get('post_deploy_script') + ) + + return jsonify(result), 201 if result['success'] else 400 + + +@deploy_bp.route('/apps//config', methods=['DELETE']) +@jwt_required() +@admin_required +def remove_deployment(app_id): + """Remove deployment configuration.""" + result = GitService.remove_deployment(app_id) + return jsonify(result), 200 if result['success'] else 400 + + +@deploy_bp.route('/apps//deploy', methods=['POST']) +@jwt_required() +def trigger_deploy(app_id): + """Trigger a deployment.""" + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + app = Application.query.get(app_id) + + if not app: + return jsonify({'error': 'Application not found'}), 404 + + if user.role != 'admin' and app.user_id != current_user_id: + return jsonify({'error': 'Access denied'}), 403 + + data = request.get_json() or {} + result = GitService.deploy(app_id, force=data.get('force', False)) + + return jsonify(result), 200 if result['success'] else 400 + + +@deploy_bp.route('/apps//pull', methods=['POST']) +@jwt_required() +def pull_changes(app_id): + """Pull latest changes without running deploy scripts.""" + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + app = Application.query.get(app_id) + + if not app: + return jsonify({'error': 'Application not found'}), 404 + + if user.role != 'admin' and app.user_id != current_user_id: + return jsonify({'error': 'Access denied'}), 403 + + data = request.get_json() or {} + result = GitService.pull_changes(app.path, data.get('branch')) + + return jsonify(result), 200 if result['success'] else 400 + + +@deploy_bp.route('/apps//git-status', methods=['GET']) +@jwt_required() +def get_git_status(app_id): + """Get Git status for an app.""" + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + app = Application.query.get(app_id) + + if not app: + return jsonify({'error': 'Application not found'}), 404 + + if user.role != 'admin' and app.user_id != current_user_id: + return jsonify({'error': 'Access denied'}), 403 + + status = GitService.get_git_status(app.path) + return jsonify(status), 200 + + +@deploy_bp.route('/apps//commit', methods=['GET']) +@jwt_required() +def get_commit_info(app_id): + """Get current commit info for an app.""" + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + app = Application.query.get(app_id) + + if not app: + return jsonify({'error': 'Application not found'}), 404 + + if user.role != 'admin' and app.user_id != current_user_id: + return jsonify({'error': 'Access denied'}), 403 + + commit_info = GitService.get_commit_info(app.path) + if commit_info: + return jsonify({'commit': commit_info}), 200 + return jsonify({'error': 'Not a Git repository'}), 404 + + +@deploy_bp.route('/history', methods=['GET']) +@jwt_required() +def get_deployment_history(): + """Get deployment history.""" + app_id = request.args.get('app_id', type=int) + limit = request.args.get('limit', 50, type=int) + + history = GitService.get_deployment_history(app_id, limit) + return jsonify({'deployments': history}), 200 + + +@deploy_bp.route('/clone', methods=['POST']) +@jwt_required() +@admin_required +def clone_repository(): + """Clone a Git repository to a new location.""" + data = request.get_json() + + if not data: + return jsonify({'error': 'No data provided'}), 400 + + required = ['repo_url', 'app_path'] + missing = [f for f in required if f not in data] + if missing: + return jsonify({'error': f'Missing required fields: {", ".join(missing)}'}), 400 + + result = GitService.clone_repository( + app_path=data['app_path'], + repo_url=data['repo_url'], + branch=data.get('branch', 'main') + ) + + return jsonify(result), 201 if result['success'] else 400 + + +# Webhook endpoint (no auth required) +@deploy_bp.route('/webhook//', methods=['POST']) +def webhook(app_id, token): + """Handle incoming webhook from Git provider.""" + # Get signature if provided (GitHub style) + signature = request.headers.get('X-Hub-Signature-256') + + # Verify webhook + if not GitService.verify_webhook(app_id, token, signature, request.data): + return jsonify({'error': 'Invalid webhook'}), 403 + + # Parse payload + try: + payload = request.get_json() + except Exception: + return jsonify({'error': 'Invalid payload'}), 400 + + # Handle webhook + result = GitService.handle_webhook(app_id, payload) + + return jsonify(result), 200 if result.get('success') else 400 diff --git a/backend/app/api/domains.py b/backend/app/api/domains.py index a8574008..a84a55c1 100644 --- a/backend/app/api/domains.py +++ b/backend/app/api/domains.py @@ -2,10 +2,26 @@ from flask import Blueprint, request, jsonify from flask_jwt_extended import jwt_required, get_jwt_identity from app import db from app.models import Domain, Application, User +from app.services.nginx_service import NginxService +from app.services.ssl_service import SSLService domains_bp = Blueprint('domains', __name__) +def admin_required(fn): + """Decorator to require admin role.""" + from functools import wraps + + @wraps(fn) + def wrapper(*args, **kwargs): + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + if not user or user.role != 'admin': + return jsonify({'error': 'Admin access required'}), 403 + return fn(*args, **kwargs) + return wrapper + + @domains_bp.route('', methods=['GET']) @jwt_required() def get_domains(): @@ -160,11 +176,140 @@ def enable_ssl(domain_id): if user.role != 'admin' and app.user_id != current_user_id: return jsonify({'error': 'Access denied'}), 403 - # TODO: Actually request Let's Encrypt certificate + data = request.get_json() or {} + email = data.get('email') + + if not email: + return jsonify({'error': 'Email is required for SSL certificate'}), 400 + + # Request Let's Encrypt certificate + result = SSLService.obtain_certificate( + domains=[domain.name], + email=email, + use_nginx=True + ) + + if not result['success']: + return jsonify({'error': result.get('error', 'Failed to obtain certificate')}), 400 + + # Add SSL to Nginx site + nginx_result = NginxService.add_ssl_to_site( + app.name, + result['certificate_path'], + result['private_key_path'] + ) + + if not nginx_result['success']: + return jsonify({'error': nginx_result.get('error', 'Failed to configure Nginx')}), 400 + domain.ssl_enabled = True + domain.ssl_certificate_path = result['certificate_path'] + domain.ssl_private_key_path = result['private_key_path'] db.session.commit() return jsonify({ 'message': 'SSL enabled for domain', + 'domain': domain.to_dict(), + 'certificate': result + }), 200 + + +@domains_bp.route('//ssl/disable', methods=['POST']) +@jwt_required() +def disable_ssl(domain_id): + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + domain = Domain.query.get(domain_id) + + if not domain: + return jsonify({'error': 'Domain not found'}), 404 + + app = Application.query.get(domain.application_id) + if user.role != 'admin' and app.user_id != current_user_id: + return jsonify({'error': 'Access denied'}), 403 + + domain.ssl_enabled = False + db.session.commit() + + return jsonify({ + 'message': 'SSL disabled for domain', 'domain': domain.to_dict() }), 200 + + +@domains_bp.route('//ssl/renew', methods=['POST']) +@jwt_required() +def renew_ssl(domain_id): + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + domain = Domain.query.get(domain_id) + + if not domain: + return jsonify({'error': 'Domain not found'}), 404 + + app = Application.query.get(domain.application_id) + if user.role != 'admin' and app.user_id != current_user_id: + return jsonify({'error': 'Access denied'}), 403 + + if not domain.ssl_enabled: + return jsonify({'error': 'SSL is not enabled for this domain'}), 400 + + result = SSLService.renew_certificate(domain.name) + + if result['success']: + return jsonify({ + 'message': 'SSL certificate renewed', + 'domain': domain.to_dict() + }), 200 + + return jsonify({'error': result.get('error', 'Failed to renew certificate')}), 400 + + +@domains_bp.route('//verify', methods=['GET']) +@jwt_required() +def verify_domain(domain_id): + """Verify domain DNS configuration.""" + import socket + + domain = Domain.query.get(domain_id) + if not domain: + return jsonify({'error': 'Domain not found'}), 404 + + try: + # Try to resolve the domain + ip_address = socket.gethostbyname(domain.name) + return jsonify({ + 'verified': True, + 'domain': domain.name, + 'ip_address': ip_address + }), 200 + except socket.gaierror: + return jsonify({ + 'verified': False, + 'domain': domain.name, + 'error': 'Domain could not be resolved' + }), 200 + + +@domains_bp.route('/nginx/sites', methods=['GET']) +@jwt_required() +@admin_required +def list_nginx_sites(): + """List all Nginx site configurations.""" + sites = NginxService.list_sites() + return jsonify({'sites': sites}), 200 + + +@domains_bp.route('/ssl/status', methods=['GET']) +@jwt_required() +@admin_required +def get_ssl_status(): + """Get overall SSL status.""" + is_installed = SSLService.is_certbot_installed() + certificates = SSLService.list_certificates() + + return jsonify({ + 'certbot_installed': is_installed, + 'total_certificates': len(certificates), + 'certificates': certificates + }), 200 diff --git a/backend/app/api/monitoring.py b/backend/app/api/monitoring.py new file mode 100644 index 00000000..756d0edd --- /dev/null +++ b/backend/app/api/monitoring.py @@ -0,0 +1,180 @@ +from flask import Blueprint, request, jsonify +from flask_jwt_extended import jwt_required, get_jwt_identity +from app.models import User +from app.services.monitoring_service import MonitoringService + +monitoring_bp = Blueprint('monitoring', __name__) + + +def admin_required(fn): + """Decorator to require admin role.""" + from functools import wraps + + @wraps(fn) + def wrapper(*args, **kwargs): + current_user_id = get_jwt_identity() + user = User.query.get(current_user_id) + if not user or user.role != 'admin': + return jsonify({'error': 'Admin access required'}), 403 + return fn(*args, **kwargs) + return wrapper + + +@monitoring_bp.route('/status', methods=['GET']) +@jwt_required() +def get_status(): + """Get monitoring status and current metrics.""" + status = MonitoringService.get_status() + return jsonify(status), 200 + + +@monitoring_bp.route('/metrics', methods=['GET']) +@jwt_required() +def get_metrics(): + """Get current system metrics.""" + metrics = MonitoringService.get_current_metrics() + return jsonify(metrics), 200 + + +@monitoring_bp.route('/alerts/check', methods=['GET']) +@jwt_required() +def check_alerts(): + """Check current threshold violations.""" + alerts = MonitoringService.check_thresholds() + return jsonify({'alerts': alerts}), 200 + + +@monitoring_bp.route('/alerts/history', methods=['GET']) +@jwt_required() +def get_alert_history(): + """Get alert history.""" + limit = request.args.get('limit', 100, type=int) + alerts = MonitoringService.get_alert_history(limit) + return jsonify({'alerts': alerts}), 200 + + +@monitoring_bp.route('/alerts/history', methods=['DELETE']) +@jwt_required() +@admin_required +def clear_alert_history(): + """Clear alert history.""" + result = MonitoringService.clear_alert_history() + return jsonify(result), 200 if result['success'] else 400 + + +@monitoring_bp.route('/config', methods=['GET']) +@jwt_required() +@admin_required +def get_config(): + """Get monitoring configuration.""" + config = MonitoringService.get_config() + # Don't expose sensitive data + if 'email' in config and 'smtp_password' in config['email']: + config['email']['smtp_password'] = '***' if config['email']['smtp_password'] else '' + return jsonify(config), 200 + + +@monitoring_bp.route('/config', methods=['PUT']) +@jwt_required() +@admin_required +def update_config(): + """Update monitoring configuration.""" + data = request.get_json() + if not data: + return jsonify({'error': 'No data provided'}), 400 + + current_config = MonitoringService.get_config() + + # Update config with new values + if 'thresholds' in data: + current_config['thresholds'] = {**current_config.get('thresholds', {}), **data['thresholds']} + + if 'check_interval' in data: + current_config['check_interval'] = data['check_interval'] + + if 'email' in data: + email_config = current_config.get('email', {}) + new_email = data['email'] + + # Preserve password if not provided or masked + if new_email.get('smtp_password') in [None, '', '***']: + new_email['smtp_password'] = email_config.get('smtp_password', '') + + current_config['email'] = {**email_config, **new_email} + + if 'webhook' in data: + current_config['webhook'] = {**current_config.get('webhook', {}), **data['webhook']} + + result = MonitoringService.save_config(current_config) + return jsonify(result), 200 if result['success'] else 400 + + +@monitoring_bp.route('/thresholds', methods=['GET']) +@jwt_required() +def get_thresholds(): + """Get alert thresholds.""" + thresholds = MonitoringService.get_thresholds() + return jsonify({'thresholds': thresholds}), 200 + + +@monitoring_bp.route('/thresholds', methods=['PUT']) +@jwt_required() +@admin_required +def update_thresholds(): + """Update alert thresholds.""" + data = request.get_json() + if not data: + return jsonify({'error': 'No data provided'}), 400 + + result = MonitoringService.set_thresholds(data) + return jsonify(result), 200 if result['success'] else 400 + + +@monitoring_bp.route('/start', methods=['POST']) +@jwt_required() +@admin_required +def start_monitoring(): + """Start background monitoring.""" + result = MonitoringService.start_monitoring() + return jsonify(result), 200 if result['success'] else 400 + + +@monitoring_bp.route('/stop', methods=['POST']) +@jwt_required() +@admin_required +def stop_monitoring(): + """Stop background monitoring.""" + result = MonitoringService.stop_monitoring() + return jsonify(result), 200 if result['success'] else 400 + + +@monitoring_bp.route('/test/email', methods=['POST']) +@jwt_required() +@admin_required +def test_email_alert(): + """Send a test email alert.""" + test_alerts = [{ + 'type': 'test', + 'severity': 'info', + 'message': 'This is a test alert from ServerKit', + 'value': 0, + 'threshold': 0 + }] + result = MonitoringService.send_email_alert(test_alerts) + return jsonify(result), 200 if result['success'] else 400 + + +@monitoring_bp.route('/test/webhook', methods=['POST']) +@jwt_required() +@admin_required +def test_webhook_alert(): + """Send a test webhook alert.""" + test_alerts = [{ + 'type': 'test', + 'severity': 'info', + 'message': 'This is a test alert from ServerKit', + 'value': 0, + 'threshold': 0 + }] + result = MonitoringService.send_webhook_alert(test_alerts) + return jsonify(result), 200 if result['success'] else 400 diff --git a/backend/app/middleware/__init__.py b/backend/app/middleware/__init__.py new file mode 100644 index 00000000..93fa6f75 --- /dev/null +++ b/backend/app/middleware/__init__.py @@ -0,0 +1 @@ +# Middleware package diff --git a/backend/app/middleware/security.py b/backend/app/middleware/security.py new file mode 100644 index 00000000..44780d3b --- /dev/null +++ b/backend/app/middleware/security.py @@ -0,0 +1,42 @@ +"""Security middleware for adding security headers to responses.""" + +from flask import Flask + + +def register_security_headers(app: Flask): + """Register security headers as an after_request handler.""" + + @app.after_request + def add_security_headers(response): + # Prevent clickjacking + response.headers['X-Frame-Options'] = 'DENY' + + # Prevent MIME type sniffing + response.headers['X-Content-Type-Options'] = 'nosniff' + + # XSS Protection (legacy but still useful for older browsers) + response.headers['X-XSS-Protection'] = '1; mode=block' + + # Referrer Policy + response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin' + + # Content Security Policy + csp_directives = [ + "default-src 'self'", + "script-src 'self' 'unsafe-inline' 'unsafe-eval'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data: https:", + "font-src 'self'", + "connect-src 'self' ws: wss:", + "frame-ancestors 'none'", + ] + response.headers['Content-Security-Policy'] = '; '.join(csp_directives) + + # Permissions Policy (formerly Feature-Policy) + response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()' + + # HSTS - only in production and on HTTPS + if not app.debug: + response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' + + return response diff --git a/backend/app/models/user.py b/backend/app/models/user.py index 66be57be..75d5fd52 100644 --- a/backend/app/models/user.py +++ b/backend/app/models/user.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import datetime, timedelta from werkzeug.security import generate_password_hash, check_password_hash from app import db @@ -15,9 +15,41 @@ class User(db.Model): created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + # Account lockout fields + failed_login_count = db.Column(db.Integer, default=0) + locked_until = db.Column(db.DateTime, nullable=True) + # Relationships applications = db.relationship('Application', backref='owner', lazy='dynamic') + # Lockout durations (progressive: 5 min, 15 min, 1 hour) + LOCKOUT_DURATIONS = [5, 15, 60] + MAX_FAILED_ATTEMPTS = 5 + + @property + def is_locked(self): + """Check if account is currently locked.""" + if self.locked_until is None: + return False + return datetime.utcnow() < self.locked_until + + def record_failed_login(self): + """Record a failed login attempt and lock account if threshold reached.""" + self.failed_login_count += 1 + if self.failed_login_count >= self.MAX_FAILED_ATTEMPTS: + # Calculate lockout duration based on how many times they've been locked + lockout_index = min( + (self.failed_login_count - self.MAX_FAILED_ATTEMPTS) // self.MAX_FAILED_ATTEMPTS, + len(self.LOCKOUT_DURATIONS) - 1 + ) + lockout_minutes = self.LOCKOUT_DURATIONS[lockout_index] + self.locked_until = datetime.utcnow() + timedelta(minutes=lockout_minutes) + + def reset_failed_login(self): + """Reset failed login count after successful login.""" + self.failed_login_count = 0 + self.locked_until = None + def set_password(self, password): self.password_hash = generate_password_hash(password) diff --git a/backend/app/services/backup_service.py b/backend/app/services/backup_service.py new file mode 100644 index 00000000..7a403642 --- /dev/null +++ b/backend/app/services/backup_service.py @@ -0,0 +1,474 @@ +import os +import json +import subprocess +import shutil +import tarfile +import gzip +from datetime import datetime, timedelta +from typing import Dict, List, Optional +from pathlib import Path +import threading +import time +import schedule + + +class BackupService: + """Service for automated backups of applications and databases.""" + + BACKUP_BASE_DIR = '/var/backups/serverkit' + CONFIG_DIR = '/etc/serverkit' + BACKUP_CONFIG = os.path.join(CONFIG_DIR, 'backups.json') + + # Backup types + TYPE_APP = 'application' + TYPE_DATABASE = 'database' + TYPE_FULL = 'full' + + _scheduler_thread = None + _stop_scheduler = False + + @classmethod + def get_backup_dir(cls, backup_type: str = None) -> str: + """Get backup directory for type.""" + if backup_type: + return os.path.join(cls.BACKUP_BASE_DIR, backup_type) + return cls.BACKUP_BASE_DIR + + @classmethod + def ensure_backup_dirs(cls) -> None: + """Ensure backup directories exist.""" + for subdir in ['applications', 'databases', 'full', 'scheduled']: + path = os.path.join(cls.BACKUP_BASE_DIR, subdir) + os.makedirs(path, exist_ok=True) + + @classmethod + def get_config(cls) -> Dict: + """Get backup configuration.""" + if os.path.exists(cls.BACKUP_CONFIG): + try: + with open(cls.BACKUP_CONFIG, 'r') as f: + return json.load(f) + except Exception: + pass + + return { + 'enabled': False, + 'retention_days': 30, + 'schedules': [], + 'notifications': { + 'on_success': False, + 'on_failure': True, + 'email': '' + } + } + + @classmethod + def save_config(cls, config: Dict) -> Dict: + """Save backup configuration.""" + try: + os.makedirs(cls.CONFIG_DIR, exist_ok=True) + with open(cls.BACKUP_CONFIG, 'w') as f: + json.dump(config, f, indent=2) + return {'success': True, 'message': 'Configuration saved'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def backup_application(cls, app_name: str, app_path: str, + include_db: bool = False, db_config: Dict = None) -> Dict: + """Backup an application (files and optionally database).""" + cls.ensure_backup_dirs() + + timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') + backup_name = f"{app_name}_{timestamp}" + backup_dir = os.path.join(cls.BACKUP_BASE_DIR, 'applications', backup_name) + + try: + os.makedirs(backup_dir, exist_ok=True) + + # Backup files + files_backup = os.path.join(backup_dir, 'files.tar.gz') + with tarfile.open(files_backup, 'w:gz') as tar: + tar.add(app_path, arcname=os.path.basename(app_path)) + + backup_info = { + 'name': backup_name, + 'app_name': app_name, + 'timestamp': datetime.now().isoformat(), + 'type': cls.TYPE_APP, + 'files_backup': files_backup, + 'size': os.path.getsize(files_backup) + } + + # Backup database if requested + if include_db and db_config: + db_backup = cls._backup_database_internal( + db_config.get('type', 'mysql'), + db_config.get('name'), + backup_dir, + db_config + ) + if db_backup.get('success'): + backup_info['database_backup'] = db_backup['path'] + backup_info['database_type'] = db_config.get('type') + + # Save backup metadata + meta_path = os.path.join(backup_dir, 'backup.json') + with open(meta_path, 'w') as f: + json.dump(backup_info, f, indent=2) + + return { + 'success': True, + 'backup': backup_info, + 'path': backup_dir + } + + except Exception as e: + # Cleanup on failure + if os.path.exists(backup_dir): + shutil.rmtree(backup_dir, ignore_errors=True) + return {'success': False, 'error': str(e)} + + @classmethod + def _backup_database_internal(cls, db_type: str, db_name: str, + backup_dir: str, config: Dict) -> Dict: + """Internal database backup helper.""" + backup_file = os.path.join(backup_dir, f'{db_name}.sql.gz') + + try: + if db_type == 'mysql': + cmd = ['mysqldump'] + if config.get('user'): + cmd.extend(['-u', config['user']]) + if config.get('password'): + cmd.append(f"-p{config['password']}") + if config.get('host'): + cmd.extend(['-h', config['host']]) + cmd.append(db_name) + + with gzip.open(backup_file, 'wt') as f: + result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, text=True) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr} + + elif db_type == 'postgresql': + env = os.environ.copy() + if config.get('password'): + env['PGPASSWORD'] = config['password'] + + cmd = ['pg_dump'] + if config.get('user'): + cmd.extend(['-U', config['user']]) + if config.get('host'): + cmd.extend(['-h', config['host']]) + cmd.append(db_name) + + with gzip.open(backup_file, 'wt') as f: + result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, text=True, env=env) + + if result.returncode != 0: + return {'success': False, 'error': result.stderr} + + return {'success': True, 'path': backup_file} + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def backup_database(cls, db_type: str, db_name: str, + user: str = None, password: str = None, + host: str = 'localhost') -> Dict: + """Backup a database.""" + cls.ensure_backup_dirs() + + timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') + backup_name = f"{db_type}_{db_name}_{timestamp}.sql.gz" + backup_path = os.path.join(cls.BACKUP_BASE_DIR, 'databases', backup_name) + + config = { + 'type': db_type, + 'name': db_name, + 'user': user, + 'password': password, + 'host': host + } + + result = cls._backup_database_internal(db_type, db_name, + os.path.dirname(backup_path), config) + + if result.get('success'): + # Rename to final path + os.rename(result['path'], backup_path) + return { + 'success': True, + 'backup': { + 'name': backup_name, + 'path': backup_path, + 'timestamp': datetime.now().isoformat(), + 'type': cls.TYPE_DATABASE, + 'database_type': db_type, + 'database_name': db_name, + 'size': os.path.getsize(backup_path) + } + } + + return result + + @classmethod + def restore_application(cls, backup_path: str, restore_path: str = None) -> Dict: + """Restore an application from backup.""" + meta_path = os.path.join(backup_path, 'backup.json') + + if not os.path.exists(meta_path): + return {'success': False, 'error': 'Invalid backup: metadata not found'} + + try: + with open(meta_path, 'r') as f: + backup_info = json.load(f) + + files_backup = backup_info.get('files_backup') + if not files_backup or not os.path.exists(files_backup): + return {'success': False, 'error': 'Backup files not found'} + + # Determine restore path + if not restore_path: + restore_path = f"/var/www/{backup_info['app_name']}" + + # Backup existing if present + if os.path.exists(restore_path): + timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') + backup_existing = f"{restore_path}.backup_{timestamp}" + shutil.move(restore_path, backup_existing) + + # Extract backup + with tarfile.open(files_backup, 'r:gz') as tar: + tar.extractall(os.path.dirname(restore_path)) + + return { + 'success': True, + 'message': f'Application restored to {restore_path}', + 'restore_path': restore_path + } + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def restore_database(cls, backup_path: str, db_type: str, db_name: str, + user: str = None, password: str = None, + host: str = 'localhost') -> Dict: + """Restore a database from backup.""" + if not os.path.exists(backup_path): + return {'success': False, 'error': 'Backup file not found'} + + try: + if db_type == 'mysql': + cmd = ['mysql'] + if user: + cmd.extend(['-u', user]) + if password: + cmd.append(f"-p{password}") + if host: + cmd.extend(['-h', host]) + cmd.append(db_name) + + with gzip.open(backup_path, 'rt') as f: + result = subprocess.run(cmd, stdin=f, capture_output=True, text=True) + + elif db_type == 'postgresql': + env = os.environ.copy() + if password: + env['PGPASSWORD'] = password + + cmd = ['psql'] + if user: + cmd.extend(['-U', user]) + if host: + cmd.extend(['-h', host]) + cmd.extend(['-d', db_name]) + + with gzip.open(backup_path, 'rt') as f: + result = subprocess.run(cmd, stdin=f, capture_output=True, text=True, env=env) + + else: + return {'success': False, 'error': f'Unknown database type: {db_type}'} + + if result.returncode != 0: + return {'success': False, 'error': result.stderr} + + return {'success': True, 'message': f'Database {db_name} restored'} + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def list_backups(cls, backup_type: str = None) -> List[Dict]: + """List all backups.""" + backups = [] + cls.ensure_backup_dirs() + + search_dirs = [] + if backup_type == 'application': + search_dirs = [os.path.join(cls.BACKUP_BASE_DIR, 'applications')] + elif backup_type == 'database': + search_dirs = [os.path.join(cls.BACKUP_BASE_DIR, 'databases')] + else: + search_dirs = [ + os.path.join(cls.BACKUP_BASE_DIR, 'applications'), + os.path.join(cls.BACKUP_BASE_DIR, 'databases'), + os.path.join(cls.BACKUP_BASE_DIR, 'scheduled') + ] + + for search_dir in search_dirs: + if not os.path.exists(search_dir): + continue + + for item in os.listdir(search_dir): + item_path = os.path.join(search_dir, item) + + if os.path.isdir(item_path): + # Application backup (directory) + meta_path = os.path.join(item_path, 'backup.json') + if os.path.exists(meta_path): + try: + with open(meta_path, 'r') as f: + backup_info = json.load(f) + backup_info['path'] = item_path + backups.append(backup_info) + except Exception: + pass + elif item.endswith('.sql.gz'): + # Database backup (file) + stat = os.stat(item_path) + backups.append({ + 'name': item, + 'path': item_path, + 'type': cls.TYPE_DATABASE, + 'size': stat.st_size, + 'timestamp': datetime.fromtimestamp(stat.st_mtime).isoformat() + }) + + # Sort by timestamp (newest first) + backups.sort(key=lambda x: x.get('timestamp', ''), reverse=True) + + return backups + + @classmethod + def delete_backup(cls, backup_path: str) -> Dict: + """Delete a backup.""" + if not backup_path.startswith(cls.BACKUP_BASE_DIR): + return {'success': False, 'error': 'Invalid backup path'} + + try: + if os.path.isdir(backup_path): + shutil.rmtree(backup_path) + elif os.path.exists(backup_path): + os.remove(backup_path) + else: + return {'success': False, 'error': 'Backup not found'} + + return {'success': True, 'message': 'Backup deleted'} + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def cleanup_old_backups(cls, retention_days: int = None) -> Dict: + """Delete backups older than retention period.""" + config = cls.get_config() + if retention_days is None: + retention_days = config.get('retention_days', 30) + + cutoff = datetime.now() - timedelta(days=retention_days) + deleted = 0 + + try: + for backup in cls.list_backups(): + try: + backup_time = datetime.fromisoformat(backup.get('timestamp', '')) + if backup_time < cutoff: + result = cls.delete_backup(backup['path']) + if result.get('success'): + deleted += 1 + except Exception: + pass + + return { + 'success': True, + 'deleted_count': deleted, + 'message': f'Deleted {deleted} old backup(s)' + } + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def add_schedule(cls, name: str, backup_type: str, target: str, + schedule_time: str, days: List[str] = None) -> Dict: + """Add a backup schedule.""" + config = cls.get_config() + + schedule_entry = { + 'id': datetime.now().strftime('%Y%m%d%H%M%S'), + 'name': name, + 'backup_type': backup_type, + 'target': target, + 'schedule_time': schedule_time, + 'days': days or ['daily'], + 'enabled': True, + 'last_run': None + } + + config.setdefault('schedules', []).append(schedule_entry) + result = cls.save_config(config) + + if result.get('success'): + return {'success': True, 'schedule': schedule_entry} + return result + + @classmethod + def remove_schedule(cls, schedule_id: str) -> Dict: + """Remove a backup schedule.""" + config = cls.get_config() + schedules = config.get('schedules', []) + + new_schedules = [s for s in schedules if s.get('id') != schedule_id] + + if len(new_schedules) == len(schedules): + return {'success': False, 'error': 'Schedule not found'} + + config['schedules'] = new_schedules + return cls.save_config(config) + + @classmethod + def get_schedules(cls) -> List[Dict]: + """Get all backup schedules.""" + config = cls.get_config() + return config.get('schedules', []) + + @classmethod + def get_backup_stats(cls) -> Dict: + """Get backup statistics.""" + backups = cls.list_backups() + + total_size = sum(b.get('size', 0) for b in backups) + app_backups = [b for b in backups if b.get('type') == cls.TYPE_APP] + db_backups = [b for b in backups if b.get('type') == cls.TYPE_DATABASE] + + return { + 'total_backups': len(backups), + 'application_backups': len(app_backups), + 'database_backups': len(db_backups), + 'total_size': total_size, + 'total_size_human': cls._format_size(total_size) + } + + @staticmethod + def _format_size(size: int) -> str: + """Format size in human readable format.""" + for unit in ['B', 'KB', 'MB', 'GB', 'TB']: + if size < 1024: + return f"{size:.1f} {unit}" + size /= 1024 + return f"{size:.1f} PB" diff --git a/backend/app/services/git_service.py b/backend/app/services/git_service.py new file mode 100644 index 00000000..68fe1e5d --- /dev/null +++ b/backend/app/services/git_service.py @@ -0,0 +1,429 @@ +import os +import subprocess +import json +import hmac +import hashlib +from datetime import datetime +from typing import Dict, List, Optional +from pathlib import Path + + +class GitService: + """Service for Git deployment and webhooks.""" + + CONFIG_DIR = '/etc/serverkit' + DEPLOY_CONFIG = os.path.join(CONFIG_DIR, 'deployments.json') + DEPLOY_LOG = '/var/log/serverkit/deployments.log' + + @classmethod + def get_config(cls) -> Dict: + """Get deployment configuration.""" + if os.path.exists(cls.DEPLOY_CONFIG): + try: + with open(cls.DEPLOY_CONFIG, 'r') as f: + return json.load(f) + except Exception: + pass + + return { + 'apps': {}, # app_id -> deployment config + 'webhook_secret': cls._generate_secret() + } + + @classmethod + def save_config(cls, config: Dict) -> Dict: + """Save deployment configuration.""" + try: + os.makedirs(cls.CONFIG_DIR, exist_ok=True) + with open(cls.DEPLOY_CONFIG, 'w') as f: + json.dump(config, f, indent=2) + return {'success': True, 'message': 'Configuration saved'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @staticmethod + def _generate_secret() -> str: + """Generate a random webhook secret.""" + import secrets + return secrets.token_hex(32) + + @classmethod + def get_app_config(cls, app_id: int) -> Optional[Dict]: + """Get deployment config for an app.""" + config = cls.get_config() + return config.get('apps', {}).get(str(app_id)) + + @classmethod + def configure_deployment(cls, app_id: int, app_path: str, + repo_url: str, branch: str = 'main', + auto_deploy: bool = True, + pre_deploy_script: str = None, + post_deploy_script: str = None) -> Dict: + """Configure Git deployment for an application.""" + config = cls.get_config() + + app_config = { + 'app_id': app_id, + 'app_path': app_path, + 'repo_url': repo_url, + 'branch': branch, + 'auto_deploy': auto_deploy, + 'pre_deploy_script': pre_deploy_script, + 'post_deploy_script': post_deploy_script, + 'webhook_token': cls._generate_secret()[:16], + 'created_at': datetime.now().isoformat(), + 'last_deploy': None, + 'deploy_count': 0 + } + + config.setdefault('apps', {})[str(app_id)] = app_config + result = cls.save_config(config) + + if result.get('success'): + return { + 'success': True, + 'config': app_config, + 'webhook_url': f'/api/v1/deploy/webhook/{app_id}/{app_config["webhook_token"]}' + } + return result + + @classmethod + def remove_deployment(cls, app_id: int) -> Dict: + """Remove deployment configuration for an app.""" + config = cls.get_config() + + if str(app_id) not in config.get('apps', {}): + return {'success': False, 'error': 'Deployment not configured'} + + del config['apps'][str(app_id)] + return cls.save_config(config) + + @classmethod + def clone_repository(cls, app_path: str, repo_url: str, branch: str = 'main') -> Dict: + """Clone a Git repository.""" + try: + # Remove existing directory if exists + if os.path.exists(app_path): + return {'success': False, 'error': 'Directory already exists'} + + cmd = ['git', 'clone', '--branch', branch, '--single-branch', repo_url, app_path] + result = subprocess.run(cmd, capture_output=True, text=True, timeout=300) + + if result.returncode == 0: + return { + 'success': True, + 'message': f'Repository cloned to {app_path}', + 'path': app_path + } + return {'success': False, 'error': result.stderr} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Clone operation timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def pull_changes(cls, app_path: str, branch: str = None) -> Dict: + """Pull latest changes from remote.""" + if not os.path.exists(os.path.join(app_path, '.git')): + return {'success': False, 'error': 'Not a Git repository'} + + try: + # Fetch first + fetch_cmd = ['git', '-C', app_path, 'fetch', '--all'] + subprocess.run(fetch_cmd, capture_output=True, text=True, timeout=60) + + # Get current branch if not specified + if not branch: + branch_cmd = ['git', '-C', app_path, 'rev-parse', '--abbrev-ref', 'HEAD'] + result = subprocess.run(branch_cmd, capture_output=True, text=True) + branch = result.stdout.strip() if result.returncode == 0 else 'main' + + # Reset to remote branch (force pull) + reset_cmd = ['git', '-C', app_path, 'reset', '--hard', f'origin/{branch}'] + result = subprocess.run(reset_cmd, capture_output=True, text=True, timeout=60) + + if result.returncode == 0: + # Get new commit info + commit_info = cls.get_commit_info(app_path) + return { + 'success': True, + 'message': 'Changes pulled successfully', + 'commit': commit_info + } + return {'success': False, 'error': result.stderr} + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Pull operation timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def get_commit_info(cls, app_path: str) -> Optional[Dict]: + """Get current commit information.""" + if not os.path.exists(os.path.join(app_path, '.git')): + return None + + try: + # Get commit hash + cmd = ['git', '-C', app_path, 'rev-parse', 'HEAD'] + result = subprocess.run(cmd, capture_output=True, text=True) + commit_hash = result.stdout.strip() if result.returncode == 0 else None + + # Get commit message + cmd = ['git', '-C', app_path, 'log', '-1', '--pretty=%B'] + result = subprocess.run(cmd, capture_output=True, text=True) + commit_message = result.stdout.strip() if result.returncode == 0 else None + + # Get author + cmd = ['git', '-C', app_path, 'log', '-1', '--pretty=%an <%ae>'] + result = subprocess.run(cmd, capture_output=True, text=True) + author = result.stdout.strip() if result.returncode == 0 else None + + # Get timestamp + cmd = ['git', '-C', app_path, 'log', '-1', '--pretty=%ci'] + result = subprocess.run(cmd, capture_output=True, text=True) + timestamp = result.stdout.strip() if result.returncode == 0 else None + + # Get branch + cmd = ['git', '-C', app_path, 'rev-parse', '--abbrev-ref', 'HEAD'] + result = subprocess.run(cmd, capture_output=True, text=True) + branch = result.stdout.strip() if result.returncode == 0 else None + + return { + 'hash': commit_hash, + 'short_hash': commit_hash[:7] if commit_hash else None, + 'message': commit_message, + 'author': author, + 'timestamp': timestamp, + 'branch': branch + } + + except Exception: + return None + + @classmethod + def deploy(cls, app_id: int, force: bool = False) -> Dict: + """Deploy an application from Git.""" + app_config = cls.get_app_config(app_id) + if not app_config: + return {'success': False, 'error': 'Deployment not configured'} + + app_path = app_config['app_path'] + branch = app_config.get('branch', 'main') + + deploy_log = { + 'app_id': app_id, + 'started_at': datetime.now().isoformat(), + 'status': 'in_progress', + 'steps': [] + } + + try: + # Pre-deploy script + if app_config.get('pre_deploy_script'): + deploy_log['steps'].append({'step': 'pre_deploy', 'status': 'running'}) + result = cls._run_script(app_config['pre_deploy_script'], app_path) + deploy_log['steps'][-1].update({ + 'status': 'success' if result['success'] else 'failed', + 'output': result.get('output', result.get('error')) + }) + if not result['success']: + raise Exception(f"Pre-deploy script failed: {result['error']}") + + # Pull changes + deploy_log['steps'].append({'step': 'pull', 'status': 'running'}) + pull_result = cls.pull_changes(app_path, branch) + deploy_log['steps'][-1].update({ + 'status': 'success' if pull_result['success'] else 'failed', + 'commit': pull_result.get('commit') + }) + if not pull_result['success']: + raise Exception(f"Pull failed: {pull_result['error']}") + + # Post-deploy script + if app_config.get('post_deploy_script'): + deploy_log['steps'].append({'step': 'post_deploy', 'status': 'running'}) + result = cls._run_script(app_config['post_deploy_script'], app_path) + deploy_log['steps'][-1].update({ + 'status': 'success' if result['success'] else 'failed', + 'output': result.get('output', result.get('error')) + }) + if not result['success']: + raise Exception(f"Post-deploy script failed: {result['error']}") + + # Update config + config = cls.get_config() + config['apps'][str(app_id)]['last_deploy'] = datetime.now().isoformat() + config['apps'][str(app_id)]['deploy_count'] = config['apps'][str(app_id)].get('deploy_count', 0) + 1 + cls.save_config(config) + + deploy_log['status'] = 'success' + deploy_log['completed_at'] = datetime.now().isoformat() + + cls._log_deployment(deploy_log) + + return { + 'success': True, + 'message': 'Deployment completed successfully', + 'deploy_log': deploy_log + } + + except Exception as e: + deploy_log['status'] = 'failed' + deploy_log['error'] = str(e) + deploy_log['completed_at'] = datetime.now().isoformat() + + cls._log_deployment(deploy_log) + + return {'success': False, 'error': str(e), 'deploy_log': deploy_log} + + @classmethod + def _run_script(cls, script: str, working_dir: str) -> Dict: + """Run a deployment script.""" + try: + result = subprocess.run( + script, + shell=True, + cwd=working_dir, + capture_output=True, + text=True, + timeout=300 + ) + + return { + 'success': result.returncode == 0, + 'output': result.stdout, + 'error': result.stderr if result.returncode != 0 else None + } + + except subprocess.TimeoutExpired: + return {'success': False, 'error': 'Script timed out'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def verify_webhook(cls, app_id: int, token: str, + signature: str = None, payload: bytes = None) -> bool: + """Verify webhook authenticity.""" + app_config = cls.get_app_config(app_id) + if not app_config: + return False + + # Simple token verification + if token != app_config.get('webhook_token'): + return False + + # If signature provided (GitHub style), verify it + if signature and payload: + config = cls.get_config() + secret = config.get('webhook_secret', '').encode() + expected = 'sha256=' + hmac.new(secret, payload, hashlib.sha256).hexdigest() + return hmac.compare_digest(signature, expected) + + return True + + @classmethod + def handle_webhook(cls, app_id: int, payload: Dict) -> Dict: + """Handle incoming webhook.""" + app_config = cls.get_app_config(app_id) + if not app_config: + return {'success': False, 'error': 'App not configured'} + + if not app_config.get('auto_deploy', True): + return {'success': False, 'error': 'Auto-deploy disabled'} + + # Check if push is to configured branch + ref = payload.get('ref', '') + branch = app_config.get('branch', 'main') + + if ref != f'refs/heads/{branch}': + return { + 'success': True, + 'message': f'Ignoring push to {ref}, configured branch is {branch}' + } + + # Trigger deployment + return cls.deploy(app_id) + + @classmethod + def _log_deployment(cls, deploy_log: Dict) -> None: + """Log deployment to file.""" + try: + log_dir = os.path.dirname(cls.DEPLOY_LOG) + os.makedirs(log_dir, exist_ok=True) + + with open(cls.DEPLOY_LOG, 'a') as f: + f.write(json.dumps(deploy_log) + '\n') + except Exception: + pass + + @classmethod + def get_deployment_history(cls, app_id: int = None, limit: int = 50) -> List[Dict]: + """Get deployment history.""" + history = [] + + if not os.path.exists(cls.DEPLOY_LOG): + return history + + try: + with open(cls.DEPLOY_LOG, 'r') as f: + lines = f.readlines() + + for line in reversed(lines[-limit * 2:]): # Read more than needed for filtering + try: + entry = json.loads(line.strip()) + if app_id is None or entry.get('app_id') == app_id: + history.append(entry) + if len(history) >= limit: + break + except json.JSONDecodeError: + pass + + except Exception: + pass + + return history + + @classmethod + def get_git_status(cls, app_path: str) -> Dict: + """Get Git status for a repository.""" + if not os.path.exists(os.path.join(app_path, '.git')): + return {'error': 'Not a Git repository'} + + try: + # Status + cmd = ['git', '-C', app_path, 'status', '--porcelain'] + result = subprocess.run(cmd, capture_output=True, text=True) + changes = result.stdout.strip().split('\n') if result.stdout.strip() else [] + + # Remote URL + cmd = ['git', '-C', app_path, 'remote', 'get-url', 'origin'] + result = subprocess.run(cmd, capture_output=True, text=True) + remote_url = result.stdout.strip() if result.returncode == 0 else None + + # Behind/ahead of remote + cmd = ['git', '-C', app_path, 'rev-list', '--left-right', '--count', 'HEAD...@{u}'] + result = subprocess.run(cmd, capture_output=True, text=True) + if result.returncode == 0: + parts = result.stdout.strip().split() + ahead = int(parts[0]) if len(parts) > 0 else 0 + behind = int(parts[1]) if len(parts) > 1 else 0 + else: + ahead = behind = 0 + + commit_info = cls.get_commit_info(app_path) + + return { + 'is_git_repo': True, + 'remote_url': remote_url, + 'branch': commit_info.get('branch') if commit_info else None, + 'commit': commit_info, + 'changes': len(changes), + 'has_uncommitted': len(changes) > 0, + 'ahead': ahead, + 'behind': behind + } + + except Exception as e: + return {'error': str(e)} diff --git a/backend/app/services/log_service.py b/backend/app/services/log_service.py index 7202709a..3167572a 100644 --- a/backend/app/services/log_service.py +++ b/backend/app/services/log_service.py @@ -21,6 +21,29 @@ class LogService: 'auth': '/var/log/auth.log', } + # Allowed directories for log file access (path traversal protection) + ALLOWED_LOG_DIRECTORIES = [ + '/var/log', + '/home', + '/opt', + ] + + @classmethod + def is_path_allowed(cls, filepath: str) -> bool: + """Check if the filepath is within allowed directories.""" + try: + # Resolve the absolute path to prevent traversal attacks + real_path = os.path.realpath(filepath) + + # Check if the path starts with any allowed directory + for allowed_dir in cls.ALLOWED_LOG_DIRECTORIES: + if real_path.startswith(allowed_dir): + return True + + return False + except (ValueError, OSError): + return False + @classmethod def get_log_files(cls) -> List[Dict]: """Get list of available log files.""" @@ -47,6 +70,9 @@ class LogService: @classmethod def read_log(cls, filepath: str, lines: int = 100, from_end: bool = True) -> Dict: """Read lines from a log file.""" + if not cls.is_path_allowed(filepath): + return {'success': False, 'error': 'Access denied: path not in allowed directories'} + if not os.path.exists(filepath): return {'success': False, 'error': 'Log file not found'} @@ -85,6 +111,9 @@ class LogService: @classmethod def search_log(cls, filepath: str, pattern: str, lines: int = 100) -> Dict: """Search log file for pattern.""" + if not cls.is_path_allowed(filepath): + return {'success': False, 'error': 'Access denied: path not in allowed directories'} + if not os.path.exists(filepath): return {'success': False, 'error': 'Log file not found'} @@ -155,6 +184,9 @@ class LogService: @classmethod def clear_log(cls, filepath: str) -> Dict: """Clear/truncate a log file.""" + if not cls.is_path_allowed(filepath): + return {'success': False, 'error': 'Access denied: path not in allowed directories'} + if not os.path.exists(filepath): return {'success': False, 'error': 'Log file not found'} @@ -194,6 +226,10 @@ class LogService: @classmethod def tail_log(cls, filepath: str, callback, stop_event: threading.Event = None): """Stream log file in real-time (for WebSocket use).""" + if not cls.is_path_allowed(filepath): + callback({'error': 'Access denied: path not in allowed directories'}) + return + if not os.path.exists(filepath): callback({'error': 'Log file not found'}) return diff --git a/backend/app/services/monitoring_service.py b/backend/app/services/monitoring_service.py new file mode 100644 index 00000000..b08b9cbd --- /dev/null +++ b/backend/app/services/monitoring_service.py @@ -0,0 +1,386 @@ +import os +import json +import psutil +import smtplib +from email.mime.text import MIMEText +from email.mime.multipart import MIMEMultipart +from datetime import datetime, timedelta +from typing import Dict, List, Optional +from pathlib import Path +import threading +import time + + +class MonitoringService: + """Service for system monitoring and alerts.""" + + CONFIG_DIR = '/etc/serverkit' + ALERTS_CONFIG = os.path.join(CONFIG_DIR, 'alerts.json') + ALERTS_LOG = '/var/log/serverkit/alerts.log' + + # Default thresholds + DEFAULT_THRESHOLDS = { + 'cpu_percent': 80, + 'memory_percent': 85, + 'disk_percent': 90, + 'load_average': 5.0 + } + + # Alert cooldown (don't send same alert within this period) + ALERT_COOLDOWN = 300 # 5 minutes + + _last_alerts = {} + _monitoring_thread = None + _stop_monitoring = False + + @classmethod + def get_config(cls) -> Dict: + """Get monitoring configuration.""" + if os.path.exists(cls.ALERTS_CONFIG): + try: + with open(cls.ALERTS_CONFIG, 'r') as f: + return json.load(f) + except Exception: + pass + + return { + 'enabled': False, + 'thresholds': cls.DEFAULT_THRESHOLDS.copy(), + 'email': { + 'enabled': False, + 'smtp_host': '', + 'smtp_port': 587, + 'smtp_user': '', + 'smtp_password': '', + 'from_email': '', + 'to_emails': [] + }, + 'webhook': { + 'enabled': False, + 'url': '' + }, + 'check_interval': 60 # seconds + } + + @classmethod + def save_config(cls, config: Dict) -> Dict: + """Save monitoring configuration.""" + try: + os.makedirs(cls.CONFIG_DIR, exist_ok=True) + with open(cls.ALERTS_CONFIG, 'w') as f: + json.dump(config, f, indent=2) + return {'success': True, 'message': 'Configuration saved'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def get_thresholds(cls) -> Dict: + """Get current alert thresholds.""" + config = cls.get_config() + return config.get('thresholds', cls.DEFAULT_THRESHOLDS) + + @classmethod + def set_thresholds(cls, thresholds: Dict) -> Dict: + """Set alert thresholds.""" + config = cls.get_config() + config['thresholds'] = {**config.get('thresholds', {}), **thresholds} + return cls.save_config(config) + + @classmethod + def get_current_metrics(cls) -> Dict: + """Get current system metrics.""" + cpu_percent = psutil.cpu_percent(interval=1) + memory = psutil.virtual_memory() + disk = psutil.disk_usage('/') + + try: + load_avg = os.getloadavg() + except (OSError, AttributeError): + load_avg = (0, 0, 0) + + return { + 'timestamp': datetime.now().isoformat(), + 'cpu': { + 'percent': cpu_percent, + 'cores': psutil.cpu_count() + }, + 'memory': { + 'percent': memory.percent, + 'used': memory.used, + 'total': memory.total, + 'available': memory.available + }, + 'disk': { + 'percent': disk.percent, + 'used': disk.used, + 'total': disk.total, + 'free': disk.free + }, + 'load_average': { + '1min': load_avg[0], + '5min': load_avg[1], + '15min': load_avg[2] + } + } + + @classmethod + def check_thresholds(cls) -> List[Dict]: + """Check if any thresholds are exceeded.""" + metrics = cls.get_current_metrics() + thresholds = cls.get_thresholds() + alerts = [] + + # CPU check + if metrics['cpu']['percent'] > thresholds.get('cpu_percent', 80): + alerts.append({ + 'type': 'cpu', + 'severity': 'warning' if metrics['cpu']['percent'] < 95 else 'critical', + 'message': f"CPU usage at {metrics['cpu']['percent']}% (threshold: {thresholds['cpu_percent']}%)", + 'value': metrics['cpu']['percent'], + 'threshold': thresholds['cpu_percent'] + }) + + # Memory check + if metrics['memory']['percent'] > thresholds.get('memory_percent', 85): + alerts.append({ + 'type': 'memory', + 'severity': 'warning' if metrics['memory']['percent'] < 95 else 'critical', + 'message': f"Memory usage at {metrics['memory']['percent']}% (threshold: {thresholds['memory_percent']}%)", + 'value': metrics['memory']['percent'], + 'threshold': thresholds['memory_percent'] + }) + + # Disk check + if metrics['disk']['percent'] > thresholds.get('disk_percent', 90): + alerts.append({ + 'type': 'disk', + 'severity': 'warning' if metrics['disk']['percent'] < 95 else 'critical', + 'message': f"Disk usage at {metrics['disk']['percent']}% (threshold: {thresholds['disk_percent']}%)", + 'value': metrics['disk']['percent'], + 'threshold': thresholds['disk_percent'] + }) + + # Load average check + if metrics['load_average']['1min'] > thresholds.get('load_average', 5.0): + alerts.append({ + 'type': 'load', + 'severity': 'warning', + 'message': f"Load average at {metrics['load_average']['1min']:.2f} (threshold: {thresholds['load_average']})", + 'value': metrics['load_average']['1min'], + 'threshold': thresholds['load_average'] + }) + + return alerts + + @classmethod + def send_email_alert(cls, alerts: List[Dict]) -> Dict: + """Send email alert notification.""" + config = cls.get_config() + email_config = config.get('email', {}) + + if not email_config.get('enabled') or not email_config.get('to_emails'): + return {'success': False, 'error': 'Email alerts not configured'} + + try: + # Build email content + subject = f"[ServerKit Alert] {len(alerts)} alert(s) triggered" + + body = "The following alerts have been triggered:\n\n" + for alert in alerts: + body += f"• [{alert['severity'].upper()}] {alert['message']}\n" + body += f"\nTimestamp: {datetime.now().isoformat()}" + body += f"\nHostname: {os.uname().nodename if hasattr(os, 'uname') else 'unknown'}" + + # Create message + msg = MIMEMultipart() + msg['From'] = email_config['from_email'] + msg['To'] = ', '.join(email_config['to_emails']) + msg['Subject'] = subject + msg.attach(MIMEText(body, 'plain')) + + # Send email + with smtplib.SMTP(email_config['smtp_host'], email_config['smtp_port']) as server: + server.starttls() + if email_config.get('smtp_user') and email_config.get('smtp_password'): + server.login(email_config['smtp_user'], email_config['smtp_password']) + server.send_message(msg) + + return {'success': True, 'message': 'Email sent'} + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def send_webhook_alert(cls, alerts: List[Dict]) -> Dict: + """Send webhook alert notification.""" + import requests + + config = cls.get_config() + webhook_config = config.get('webhook', {}) + + if not webhook_config.get('enabled') or not webhook_config.get('url'): + return {'success': False, 'error': 'Webhook not configured'} + + try: + payload = { + 'source': 'serverkit', + 'timestamp': datetime.now().isoformat(), + 'alerts': alerts + } + + response = requests.post( + webhook_config['url'], + json=payload, + timeout=10 + ) + + if response.ok: + return {'success': True, 'message': 'Webhook sent'} + return {'success': False, 'error': f'Webhook returned {response.status_code}'} + + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def process_alerts(cls, alerts: List[Dict]) -> None: + """Process and send alerts (with cooldown).""" + if not alerts: + return + + config = cls.get_config() + now = datetime.now() + + # Filter alerts by cooldown + alerts_to_send = [] + for alert in alerts: + alert_key = f"{alert['type']}_{alert['severity']}" + last_sent = cls._last_alerts.get(alert_key) + + if not last_sent or (now - last_sent).total_seconds() > cls.ALERT_COOLDOWN: + alerts_to_send.append(alert) + cls._last_alerts[alert_key] = now + + if not alerts_to_send: + return + + # Log alerts + cls.log_alert(alerts_to_send) + + # Send notifications + if config.get('email', {}).get('enabled'): + cls.send_email_alert(alerts_to_send) + + if config.get('webhook', {}).get('enabled'): + cls.send_webhook_alert(alerts_to_send) + + @classmethod + def log_alert(cls, alerts: List[Dict]) -> None: + """Log alerts to file.""" + try: + log_dir = os.path.dirname(cls.ALERTS_LOG) + os.makedirs(log_dir, exist_ok=True) + + with open(cls.ALERTS_LOG, 'a') as f: + for alert in alerts: + entry = { + 'timestamp': datetime.now().isoformat(), + **alert + } + f.write(json.dumps(entry) + '\n') + except Exception: + pass + + @classmethod + def get_alert_history(cls, limit: int = 100) -> List[Dict]: + """Get recent alert history.""" + alerts = [] + + if not os.path.exists(cls.ALERTS_LOG): + return alerts + + try: + with open(cls.ALERTS_LOG, 'r') as f: + lines = f.readlines() + + for line in lines[-limit:]: + try: + alerts.append(json.loads(line.strip())) + except json.JSONDecodeError: + pass + + alerts.reverse() # Most recent first + + except Exception: + pass + + return alerts + + @classmethod + def clear_alert_history(cls) -> Dict: + """Clear alert history.""" + try: + if os.path.exists(cls.ALERTS_LOG): + os.remove(cls.ALERTS_LOG) + return {'success': True, 'message': 'Alert history cleared'} + except Exception as e: + return {'success': False, 'error': str(e)} + + @classmethod + def start_monitoring(cls) -> Dict: + """Start background monitoring.""" + if cls._monitoring_thread and cls._monitoring_thread.is_alive(): + return {'success': False, 'error': 'Monitoring already running'} + + config = cls.get_config() + config['enabled'] = True + cls.save_config(config) + + cls._stop_monitoring = False + cls._monitoring_thread = threading.Thread(target=cls._monitor_loop, daemon=True) + cls._monitoring_thread.start() + + return {'success': True, 'message': 'Monitoring started'} + + @classmethod + def stop_monitoring(cls) -> Dict: + """Stop background monitoring.""" + config = cls.get_config() + config['enabled'] = False + cls.save_config(config) + + cls._stop_monitoring = True + + return {'success': True, 'message': 'Monitoring stopped'} + + @classmethod + def _monitor_loop(cls) -> None: + """Background monitoring loop.""" + while not cls._stop_monitoring: + config = cls.get_config() + if not config.get('enabled'): + break + + try: + alerts = cls.check_thresholds() + cls.process_alerts(alerts) + except Exception: + pass + + time.sleep(config.get('check_interval', 60)) + + @classmethod + def get_status(cls) -> Dict: + """Get monitoring status.""" + config = cls.get_config() + metrics = cls.get_current_metrics() + alerts = cls.check_thresholds() + + return { + 'enabled': config.get('enabled', False), + 'thresholds': config.get('thresholds', cls.DEFAULT_THRESHOLDS), + 'check_interval': config.get('check_interval', 60), + 'email_enabled': config.get('email', {}).get('enabled', False), + 'webhook_enabled': config.get('webhook', {}).get('enabled', False), + 'current_metrics': metrics, + 'active_alerts': alerts + } diff --git a/backend/config.py b/backend/config.py index d06f3ec6..474ffe04 100644 --- a/backend/config.py +++ b/backend/config.py @@ -1,6 +1,16 @@ import os +import sys from datetime import timedelta +# Default insecure keys that must be changed in production +INSECURE_SECRET_KEYS = [ + 'dev-secret-key-change-in-production', + 'jwt-secret-key-change-in-production', + 'change-this-to-a-secure-random-string', + 'change-this-to-another-secure-random-string', +] + + class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production') @@ -24,6 +34,18 @@ class DevelopmentConfig(Config): class ProductionConfig(Config): DEBUG = False + def __init__(self): + # Validate that secret keys are not default values in production + if self.SECRET_KEY in INSECURE_SECRET_KEYS: + print("FATAL: SECRET_KEY is set to a default insecure value in production mode!", file=sys.stderr) + print("Generate a secure key with: python -c \"import secrets; print(secrets.token_hex(32))\"", file=sys.stderr) + sys.exit(1) + + if self.JWT_SECRET_KEY in INSECURE_SECRET_KEYS: + print("FATAL: JWT_SECRET_KEY is set to a default insecure value in production mode!", file=sys.stderr) + print("Generate a secure key with: python -c \"import secrets; print(secrets.token_hex(32))\"", file=sys.stderr) + sys.exit(1) + config = { 'development': DevelopmentConfig, diff --git a/backend/requirements.txt b/backend/requirements.txt index 9441be34..4c91700b 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -31,3 +31,6 @@ python-dotenv==1.0.0 # YAML parsing (for Docker Compose) PyYAML==6.0.1 + +# Rate limiting +Flask-Limiter==3.5.0 diff --git a/backend/run.py b/backend/run.py index 42bc84d5..df4e7246 100644 --- a/backend/run.py +++ b/backend/run.py @@ -1,4 +1,5 @@ import os +import sys from app import create_app, get_socketio app = create_app() @@ -6,7 +7,15 @@ socketio = get_socketio() if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) - debug = os.environ.get('FLASK_ENV', 'development') == 'development' + env = os.environ.get('FLASK_ENV', 'development') + debug = env == 'development' - # Use SocketIO to run the app (supports WebSocket) - socketio.run(app, host='0.0.0.0', port=port, debug=debug, allow_unsafe_werkzeug=True) + # Prevent running development server in production + if env == 'production': + print("ERROR: Do not run the development server in production!", file=sys.stderr) + print("Use a production WSGI server like gunicorn instead:", file=sys.stderr) + print(" gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 run:app", file=sys.stderr) + sys.exit(1) + + # Use SocketIO to run the app (supports WebSocket) - only in development + socketio.run(app, host='0.0.0.0', port=port, debug=debug) diff --git a/deploy/serverkit.service b/deploy/serverkit.service new file mode 100644 index 00000000..10956eb8 --- /dev/null +++ b/deploy/serverkit.service @@ -0,0 +1,23 @@ +[Unit] +Description=ServerKit Web Server Management Dashboard +Documentation=https://github.com/yourusername/serverkit +After=network.target docker.service +Requires=docker.service + +[Service] +Type=oneshot +RemainAfterExit=yes +WorkingDirectory=/opt/serverkit +ExecStart=/usr/bin/docker compose -f docker-compose.prod.yml up -d +ExecStop=/usr/bin/docker compose -f docker-compose.prod.yml down +ExecReload=/usr/bin/docker compose -f docker-compose.prod.yml restart +TimeoutStartSec=300 + +# Security hardening +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths=/opt/serverkit + +[Install] +WantedBy=multi-user.target diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml new file mode 100644 index 00000000..2c6b6fac --- /dev/null +++ b/docker-compose.prod.yml @@ -0,0 +1,74 @@ +# Docker Compose - Production Configuration +version: '3.8' + +services: + backend: + build: + context: ./backend + dockerfile: Dockerfile + container_name: serverkit-backend + environment: + - FLASK_ENV=production + - DATABASE_URL=${DATABASE_URL:-sqlite:///serverkit.db} + - SECRET_KEY=${SECRET_KEY} + - JWT_SECRET_KEY=${JWT_SECRET_KEY} + - CORS_ORIGINS=${CORS_ORIGINS:-https://yourdomain.com} + volumes: + - backend-data:/app/instance + - /var/log:/var/log:ro + - /home:/home:ro + - /opt:/opt:ro + networks: + - serverkit-network + restart: always + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + + frontend: + build: + context: ./frontend + dockerfile: Dockerfile + container_name: serverkit-frontend + depends_on: + - backend + networks: + - serverkit-network + restart: always + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + + nginx: + image: nginx:alpine + container_name: serverkit-nginx + depends_on: + - frontend + - backend + ports: + - "80:80" + - "443:443" + volumes: + - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro + - ./nginx/ssl:/etc/nginx/ssl:ro + - nginx-cache:/var/cache/nginx + networks: + - serverkit-network + restart: always + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" + +networks: + serverkit-network: + driver: bridge + +volumes: + backend-data: + nginx-cache: diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..a0080156 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,43 @@ +# Docker Compose - Development Configuration +version: '3.8' + +services: + backend: + build: + context: ./backend + dockerfile: Dockerfile + container_name: serverkit-backend + environment: + - FLASK_ENV=development + - DATABASE_URL=sqlite:///serverkit.db + - SECRET_KEY=${SECRET_KEY:-dev-secret-key-change-in-production} + - JWT_SECRET_KEY=${JWT_SECRET_KEY:-jwt-secret-key-change-in-production} + - CORS_ORIGINS=http://localhost:5173,http://localhost:3000 + volumes: + - ./backend:/app + - backend-data:/app/instance + ports: + - "5000:5000" + networks: + - serverkit-network + restart: unless-stopped + + frontend: + build: + context: ./frontend + dockerfile: Dockerfile + container_name: serverkit-frontend + depends_on: + - backend + ports: + - "80:80" + networks: + - serverkit-network + restart: unless-stopped + +networks: + serverkit-network: + driver: bridge + +volumes: + backend-data: diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 00000000..7197c308 --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,233 @@ +# ServerKit Deployment Guide + +This guide covers deploying ServerKit in production using Docker. + +## Prerequisites + +- Docker 20.10+ and Docker Compose 2.0+ +- A server with at least 1GB RAM +- A domain name (for SSL/HTTPS) +- SSL certificate (Let's Encrypt recommended) + +## Quick Start (Development) + +```bash +# Clone the repository +git clone https://github.com/yourusername/serverkit.git +cd serverkit + +# Start with Docker Compose +docker compose up -d + +# Access at http://localhost +``` + +## Production Deployment + +### 1. Generate Secure Keys + +```bash +# Generate SECRET_KEY +python -c "import secrets; print(secrets.token_hex(32))" + +# Generate JWT_SECRET_KEY +python -c "import secrets; print(secrets.token_hex(32))" +``` + +### 2. Create Environment File + +Create `.env` in the project root: + +```bash +# Required - generate unique keys! +SECRET_KEY=your-generated-secret-key +JWT_SECRET_KEY=your-generated-jwt-secret-key + +# Database (SQLite by default, or use PostgreSQL) +DATABASE_URL=sqlite:///serverkit.db +# DATABASE_URL=postgresql://user:pass@host:5432/serverkit + +# CORS origins (your domain) +CORS_ORIGINS=https://yourdomain.com +``` + +### 3. SSL Certificate Setup + +#### Using Let's Encrypt (Recommended) + +```bash +# Create directories +mkdir -p nginx/ssl + +# Install certbot and get certificate +sudo certbot certonly --standalone -d yourdomain.com + +# Copy certificates +sudo cp /etc/letsencrypt/live/yourdomain.com/fullchain.pem nginx/ssl/ +sudo cp /etc/letsencrypt/live/yourdomain.com/privkey.pem nginx/ssl/ +``` + +#### Using Self-Signed (Testing Only) + +```bash +mkdir -p nginx/ssl +openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout nginx/ssl/privkey.pem \ + -out nginx/ssl/fullchain.pem \ + -subj "/CN=localhost" +``` + +### 4. Deploy + +```bash +# Build and start production containers +docker compose -f docker-compose.prod.yml up -d --build + +# Check status +docker compose -f docker-compose.prod.yml ps + +# View logs +docker compose -f docker-compose.prod.yml logs -f +``` + +### 5. Initial Setup + +1. Navigate to `https://yourdomain.com` +2. Register the first admin user +3. Configure server monitoring settings + +## Systemd Service (Optional) + +Install as a system service for automatic startup: + +```bash +# Copy the service file +sudo cp deploy/serverkit.service /etc/systemd/system/ + +# Copy project to /opt +sudo mkdir -p /opt/serverkit +sudo cp -r . /opt/serverkit/ + +# Enable and start +sudo systemctl daemon-reload +sudo systemctl enable serverkit +sudo systemctl start serverkit + +# Check status +sudo systemctl status serverkit +``` + +## Maintenance + +### Updating + +```bash +cd /opt/serverkit +git pull +docker compose -f docker-compose.prod.yml up -d --build +``` + +### Backup Database + +```bash +# SQLite +docker compose -f docker-compose.prod.yml exec backend \ + cp /app/instance/serverkit.db /app/instance/serverkit.db.backup + +# Copy to host +docker cp serverkit-backend:/app/instance/serverkit.db.backup ./backup/ +``` + +### View Logs + +```bash +# All services +docker compose -f docker-compose.prod.yml logs -f + +# Specific service +docker compose -f docker-compose.prod.yml logs -f backend +docker compose -f docker-compose.prod.yml logs -f nginx +``` + +### Restart Services + +```bash +docker compose -f docker-compose.prod.yml restart +# or +sudo systemctl restart serverkit +``` + +## Security Checklist + +- [ ] Generated unique SECRET_KEY and JWT_SECRET_KEY +- [ ] SSL/TLS certificate configured +- [ ] Firewall configured (ports 80, 443 only) +- [ ] Regular backups configured +- [ ] Monitoring/alerting set up +- [ ] Rate limiting verified working +- [ ] Security headers present (check with browser dev tools) + +## Troubleshooting + +### Container won't start + +```bash +# Check logs +docker compose -f docker-compose.prod.yml logs backend + +# Check if port is in use +sudo lsof -i :5000 +sudo lsof -i :80 +``` + +### 502 Bad Gateway + +Usually means the backend isn't running: + +```bash +docker compose -f docker-compose.prod.yml ps +docker compose -f docker-compose.prod.yml restart backend +``` + +### WebSocket connection failed + +Ensure nginx is properly proxying WebSocket connections. Check the `/socket.io` location block in nginx.conf. + +### SSL Certificate Issues + +```bash +# Test certificate +openssl s_client -connect yourdomain.com:443 -servername yourdomain.com + +# Check certificate expiry +openssl x509 -in nginx/ssl/fullchain.pem -noout -dates +``` + +## Architecture + +``` + ┌─────────────┐ + │ Client │ + └──────┬──────┘ + │ + ┌──────▼──────┐ + │ Nginx │ + │ (SSL/TLS) │ + └──────┬──────┘ + │ + ┌───────────────┼───────────────┐ + │ │ │ + ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐ + │ Frontend │ │ Backend │ │ Socket.IO │ + │ (React) │ │ (Flask) │ │ (WebSocket) │ + └─────────────┘ └──────┬──────┘ └─────────────┘ + │ + ┌──────▼──────┐ + │ SQLite/ │ + │ PostgreSQL │ + └─────────────┘ +``` + +## Support + +For issues and questions, please open an issue on GitHub. diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 00000000..4884a47e --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,42 @@ +# Frontend Dockerfile for ServerKit +# Stage 1: Build +FROM node:20-alpine AS builder + +WORKDIR /app + +# Copy package files +COPY package*.json ./ + +# Install dependencies +RUN npm ci + +# Copy source code +COPY . . + +# Build the application +RUN npm run build + +# Stage 2: Production +FROM nginx:alpine + +# Copy custom nginx config +COPY nginx.conf /etc/nginx/conf.d/default.conf + +# Copy built assets from builder stage +COPY --from=builder /app/dist /usr/share/nginx/html + +# Create non-root user for nginx +RUN chown -R nginx:nginx /usr/share/nginx/html && \ + chown -R nginx:nginx /var/cache/nginx && \ + chown -R nginx:nginx /var/log/nginx && \ + chown -R nginx:nginx /etc/nginx/conf.d + +# Expose port +EXPOSE 80 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ + CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1 + +# Start nginx +CMD ["nginx", "-g", "daemon off;"] diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 00000000..664191a8 --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,62 @@ +server { + listen 80; + server_name localhost; + root /usr/share/nginx/html; + index index.html; + + # Gzip compression + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_proxied any; + gzip_types text/plain text/css text/xml text/javascript application/javascript application/json application/xml; + + # Security headers + add_header X-Frame-Options "DENY" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + + # SPA routing - serve index.html for all routes + location / { + try_files $uri $uri/ /index.html; + } + + # Proxy API requests to backend + location /api { + proxy_pass http://backend:5000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Timeout settings + proxy_connect_timeout 60s; + proxy_send_timeout 60s; + proxy_read_timeout 60s; + } + + # WebSocket support for socket.io + location /socket.io { + proxy_pass http://backend:5000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # WebSocket specific timeouts + proxy_connect_timeout 7d; + proxy_send_timeout 7d; + proxy_read_timeout 7d; + } + + # Cache static assets + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { + expires 1y; + add_header Cache-Control "public, immutable"; + } +} diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index c9f30fe9..5153433b 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,6 +1,8 @@ import React from 'react'; import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'; import { AuthProvider, useAuth } from './contexts/AuthContext'; +import { ToastProvider } from './contexts/ToastContext'; +import { ToastContainer } from './components/Toast'; import DashboardLayout from './layouts/DashboardLayout'; import Dashboard from './pages/Dashboard'; import Login from './pages/Login'; @@ -9,6 +11,11 @@ import Applications from './pages/Applications'; import ApplicationDetail from './pages/ApplicationDetail'; import Docker from './pages/Docker'; import Databases from './pages/Databases'; +import Domains from './pages/Domains'; +import Monitoring from './pages/Monitoring'; +import Backups from './pages/Backups'; +import Terminal from './pages/Terminal'; +import Settings from './pages/Settings'; function PrivateRoute({ children }) { const { isAuthenticated, loading } = useAuth(); @@ -51,12 +58,14 @@ function AppRoutes() { } /> } /> } /> - Domains & Sites} /> + } /> } /> SSL Certificates} /> } /> - Terminal / Logs} /> - Settings} /> + } /> + } /> + } /> + } /> ); @@ -66,7 +75,10 @@ function App() { return ( - + + + + ); diff --git a/frontend/src/components/ConfirmDialog.jsx b/frontend/src/components/ConfirmDialog.jsx new file mode 100644 index 00000000..1fcb123c --- /dev/null +++ b/frontend/src/components/ConfirmDialog.jsx @@ -0,0 +1,53 @@ +import React from 'react'; +import { AlertTriangle, Info, AlertCircle } from 'lucide-react'; + +const iconMap = { + danger: AlertTriangle, + warning: AlertCircle, + info: Info +}; + +export function ConfirmDialog({ + isOpen, + title, + message, + confirmText = 'Confirm', + cancelText = 'Cancel', + variant = 'danger', + onConfirm, + onCancel +}) { + if (!isOpen) return null; + + const Icon = iconMap[variant] || AlertTriangle; + + return ( +
+
e.stopPropagation()}> +
+
+ +
+

{title}

+

{message}

+
+
+ + +
+
+
+ ); +} + +export default ConfirmDialog; diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx index 2990f326..3b76a009 100644 --- a/frontend/src/components/Sidebar.jsx +++ b/frontend/src/components/Sidebar.jsx @@ -74,6 +74,24 @@ const Sidebar = () => { +
Operations
+ +
System